Annotation of gforth/doc/gforth.ds, revision 1.131
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.113 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 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.26 crook 334:
335: Locals
336:
337: * Gforth locals::
338: * ANS Forth locals::
339:
340: Gforth locals
341:
342: * Where are locals visible by name?::
343: * How long do locals live?::
1.78 anton 344: * Locals programming style::
345: * Locals implementation::
1.26 crook 346:
1.12 anton 347: Structures
348:
349: * Why explicit structure support?::
350: * Structure Usage::
351: * Structure Naming Convention::
352: * Structure Implementation::
353: * Structure Glossary::
354:
355: Object-oriented Forth
356:
1.48 anton 357: * Why object-oriented programming?::
358: * Object-Oriented Terminology::
359: * Objects::
360: * OOF::
361: * Mini-OOF::
1.23 crook 362: * Comparison with other object models::
1.12 anton 363:
1.24 anton 364: The @file{objects.fs} model
1.12 anton 365:
366: * Properties of the Objects model::
367: * Basic Objects Usage::
1.41 anton 368: * The Objects base class::
1.12 anton 369: * Creating objects::
370: * Object-Oriented Programming Style::
371: * Class Binding::
372: * Method conveniences::
373: * Classes and Scoping::
1.41 anton 374: * Dividing classes::
1.12 anton 375: * Object Interfaces::
376: * Objects Implementation::
377: * Objects Glossary::
378:
1.24 anton 379: The @file{oof.fs} model
1.12 anton 380:
1.67 anton 381: * Properties of the OOF model::
382: * Basic OOF Usage::
383: * The OOF base class::
384: * Class Declaration::
385: * Class Implementation::
1.12 anton 386:
1.24 anton 387: The @file{mini-oof.fs} model
1.23 crook 388:
1.48 anton 389: * Basic Mini-OOF Usage::
390: * Mini-OOF Example::
391: * Mini-OOF Implementation::
1.23 crook 392:
1.78 anton 393: Programming Tools
394:
395: * Examining::
396: * Forgetting words::
397: * Debugging:: Simple and quick.
398: * Assertions:: Making your programs self-checking.
399: * Singlestep Debugger:: Executing your program word by word.
400:
401: Assembler and Code Words
402:
403: * Code and ;code::
404: * Common Assembler:: Assembler Syntax
405: * Common Disassembler::
406: * 386 Assembler:: Deviations and special cases
407: * Alpha Assembler:: Deviations and special cases
408: * MIPS assembler:: Deviations and special cases
409: * Other assemblers:: How to write them
410:
1.12 anton 411: Tools
412:
413: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 414: * Stack depth changes:: Where does this stack item come from?
1.12 anton 415:
416: ANS conformance
417:
418: * The Core Words::
419: * The optional Block word set::
420: * The optional Double Number word set::
421: * The optional Exception word set::
422: * The optional Facility word set::
423: * The optional File-Access word set::
424: * The optional Floating-Point word set::
425: * The optional Locals word set::
426: * The optional Memory-Allocation word set::
427: * The optional Programming-Tools word set::
428: * The optional Search-Order word set::
429:
430: The Core Words
431:
432: * core-idef:: Implementation Defined Options
433: * core-ambcond:: Ambiguous Conditions
434: * core-other:: Other System Documentation
435:
436: The optional Block word set
437:
438: * block-idef:: Implementation Defined Options
439: * block-ambcond:: Ambiguous Conditions
440: * block-other:: Other System Documentation
441:
442: The optional Double Number word set
443:
444: * double-ambcond:: Ambiguous Conditions
445:
446: The optional Exception word set
447:
448: * exception-idef:: Implementation Defined Options
449:
450: The optional Facility word set
451:
452: * facility-idef:: Implementation Defined Options
453: * facility-ambcond:: Ambiguous Conditions
454:
455: The optional File-Access word set
456:
457: * file-idef:: Implementation Defined Options
458: * file-ambcond:: Ambiguous Conditions
459:
460: The optional Floating-Point word set
461:
462: * floating-idef:: Implementation Defined Options
463: * floating-ambcond:: Ambiguous Conditions
464:
465: The optional Locals word set
466:
467: * locals-idef:: Implementation Defined Options
468: * locals-ambcond:: Ambiguous Conditions
469:
470: The optional Memory-Allocation word set
471:
472: * memory-idef:: Implementation Defined Options
473:
474: The optional Programming-Tools word set
475:
476: * programming-idef:: Implementation Defined Options
477: * programming-ambcond:: Ambiguous Conditions
478:
479: The optional Search-Order word set
480:
481: * search-idef:: Implementation Defined Options
482: * search-ambcond:: Ambiguous Conditions
483:
1.109 anton 484: Emacs and Gforth
485:
486: * Installing gforth.el:: Making Emacs aware of Forth.
487: * Emacs Tags:: Viewing the source of a word in Emacs.
488: * Hilighting:: Making Forth code look prettier.
489: * Auto-Indentation:: Customizing auto-indentation.
490: * Blocks Files:: Reading and writing blocks files.
491:
1.12 anton 492: Image Files
493:
1.24 anton 494: * Image Licensing Issues:: Distribution terms for images.
495: * Image File Background:: Why have image files?
1.67 anton 496: * Non-Relocatable Image Files:: don't always work.
1.24 anton 497: * Data-Relocatable Image Files:: are better.
1.67 anton 498: * Fully Relocatable Image Files:: better yet.
1.24 anton 499: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 500: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 501: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 502:
503: Fully Relocatable Image Files
504:
1.27 crook 505: * gforthmi:: The normal way
1.12 anton 506: * cross.fs:: The hard way
507:
508: Engine
509:
510: * Portability::
511: * Threading::
512: * Primitives::
513: * Performance::
514:
515: Threading
516:
517: * Scheduling::
518: * Direct or Indirect Threaded?::
1.109 anton 519: * Dynamic Superinstructions::
1.12 anton 520: * DOES>::
521:
522: Primitives
523:
524: * Automatic Generation::
525: * TOS Optimization::
526: * Produced code::
1.13 pazsan 527:
528: Cross Compiler
529:
1.67 anton 530: * Using the Cross Compiler::
531: * How the Cross Compiler Works::
1.13 pazsan 532:
1.113 anton 533: Licenses
534:
535: * GNU Free Documentation License:: License for copying this manual.
536: * Copying:: GPL (for copying this software).
537:
1.24 anton 538: @end detailmenu
1.1 anton 539: @end menu
540:
1.113 anton 541: @c ----------------------------------------------------------
1.1 anton 542: @iftex
543: @unnumbered Preface
544: @cindex Preface
1.21 crook 545: This manual documents Gforth. Some introductory material is provided for
546: readers who are unfamiliar with Forth or who are migrating to Gforth
547: from other Forth compilers. However, this manual is primarily a
548: reference manual.
1.1 anton 549: @end iftex
550:
1.28 crook 551: @comment TODO much more blurb here.
1.26 crook 552:
553: @c ******************************************************************
1.113 anton 554: @node Goals, Gforth Environment, Top, Top
1.26 crook 555: @comment node-name, next, previous, up
556: @chapter Goals of Gforth
557: @cindex goals of the Gforth project
558: The goal of the Gforth Project is to develop a standard model for
559: ANS Forth. This can be split into several subgoals:
560:
561: @itemize @bullet
562: @item
563: Gforth should conform to the ANS Forth Standard.
564: @item
565: It should be a model, i.e. it should define all the
566: implementation-dependent things.
567: @item
568: It should become standard, i.e. widely accepted and used. This goal
569: is the most difficult one.
570: @end itemize
571:
572: To achieve these goals Gforth should be
573: @itemize @bullet
574: @item
575: Similar to previous models (fig-Forth, F83)
576: @item
577: Powerful. It should provide for all the things that are considered
578: necessary today and even some that are not yet considered necessary.
579: @item
580: Efficient. It should not get the reputation of being exceptionally
581: slow.
582: @item
583: Free.
584: @item
585: Available on many machines/easy to port.
586: @end itemize
587:
588: Have we achieved these goals? Gforth conforms to the ANS Forth
589: standard. It may be considered a model, but we have not yet documented
590: which parts of the model are stable and which parts we are likely to
591: change. It certainly has not yet become a de facto standard, but it
592: appears to be quite popular. It has some similarities to and some
593: differences from previous models. It has some powerful features, but not
594: yet everything that we envisioned. We certainly have achieved our
1.65 anton 595: execution speed goals (@pxref{Performance})@footnote{However, in 1998
596: the bar was raised when the major commercial Forth vendors switched to
597: native code compilers.}. It is free and available on many machines.
1.29 crook 598:
1.26 crook 599: @c ******************************************************************
1.48 anton 600: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 601: @chapter Gforth Environment
602: @cindex Gforth environment
1.21 crook 603:
1.45 crook 604: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 605: material in this chapter.
1.21 crook 606:
607: @menu
1.29 crook 608: * Invoking Gforth:: Getting in
609: * Leaving Gforth:: Getting out
610: * Command-line editing::
1.48 anton 611: * Environment variables:: that affect how Gforth starts up
1.29 crook 612: * Gforth Files:: What gets installed and where
1.112 anton 613: * Gforth in pipes::
1.48 anton 614: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 615: @end menu
616:
1.49 anton 617: For related information about the creation of images see @ref{Image Files}.
1.29 crook 618:
1.21 crook 619: @comment ----------------------------------------------
1.48 anton 620: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 621: @section Invoking Gforth
622: @cindex invoking Gforth
623: @cindex running Gforth
624: @cindex command-line options
625: @cindex options on the command line
626: @cindex flags on the command line
1.21 crook 627:
1.30 anton 628: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 629: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 630: will usually just say @code{gforth} -- this automatically loads the
631: default image file @file{gforth.fi}. In many other cases the default
632: Gforth image will be invoked like this:
1.21 crook 633: @example
1.30 anton 634: gforth [file | -e forth-code] ...
1.21 crook 635: @end example
1.29 crook 636: @noindent
637: This interprets the contents of the files and the Forth code in the order they
638: are given.
1.21 crook 639:
1.109 anton 640: In addition to the @command{gforth} engine, there is also an engine
641: called @command{gforth-fast}, which is faster, but gives less
642: informative error messages (@pxref{Error messages}) and may catch some
643: stack underflows later or not at all. You should use it for debugged,
644: performance-critical programs.
645:
646: Moreover, there is an engine called @command{gforth-itc}, which is
647: useful in some backwards-compatibility situations (@pxref{Direct or
648: Indirect Threaded?}).
1.30 anton 649:
1.29 crook 650: In general, the command line looks like this:
1.21 crook 651:
652: @example
1.30 anton 653: gforth[-fast] [engine options] [image options]
1.21 crook 654: @end example
655:
1.30 anton 656: The engine options must come before the rest of the command
1.29 crook 657: line. They are:
1.26 crook 658:
1.29 crook 659: @table @code
660: @cindex -i, command-line option
661: @cindex --image-file, command-line option
662: @item --image-file @i{file}
663: @itemx -i @i{file}
664: Loads the Forth image @i{file} instead of the default
665: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 666:
1.39 anton 667: @cindex --appl-image, command-line option
668: @item --appl-image @i{file}
669: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 670: to the image (instead of processing them as engine options). This is
671: useful for building executable application images on Unix, built with
1.39 anton 672: @code{gforthmi --application ...}.
673:
1.29 crook 674: @cindex --path, command-line option
675: @cindex -p, command-line option
676: @item --path @i{path}
677: @itemx -p @i{path}
678: Uses @i{path} for searching the image file and Forth source code files
679: instead of the default in the environment variable @code{GFORTHPATH} or
680: the path specified at installation time (e.g.,
681: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
682: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 683:
1.29 crook 684: @cindex --dictionary-size, command-line option
685: @cindex -m, command-line option
686: @cindex @i{size} parameters for command-line options
687: @cindex size of the dictionary and the stacks
688: @item --dictionary-size @i{size}
689: @itemx -m @i{size}
690: Allocate @i{size} space for the Forth dictionary space instead of
691: using the default specified in the image (typically 256K). The
692: @i{size} specification for this and subsequent options consists of
693: an integer and a unit (e.g.,
694: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
695: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
696: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
697: @code{e} is used.
1.21 crook 698:
1.29 crook 699: @cindex --data-stack-size, command-line option
700: @cindex -d, command-line option
701: @item --data-stack-size @i{size}
702: @itemx -d @i{size}
703: Allocate @i{size} space for the data stack instead of using the
704: default specified in the image (typically 16K).
1.21 crook 705:
1.29 crook 706: @cindex --return-stack-size, command-line option
707: @cindex -r, command-line option
708: @item --return-stack-size @i{size}
709: @itemx -r @i{size}
710: Allocate @i{size} space for the return stack instead of using the
711: default specified in the image (typically 15K).
1.21 crook 712:
1.29 crook 713: @cindex --fp-stack-size, command-line option
714: @cindex -f, command-line option
715: @item --fp-stack-size @i{size}
716: @itemx -f @i{size}
717: Allocate @i{size} space for the floating point stack instead of
718: using the default specified in the image (typically 15.5K). In this case
719: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 720:
1.48 anton 721: @cindex --locals-stack-size, command-line option
722: @cindex -l, command-line option
723: @item --locals-stack-size @i{size}
724: @itemx -l @i{size}
725: Allocate @i{size} space for the locals stack instead of using the
726: default specified in the image (typically 14.5K).
727:
728: @cindex -h, command-line option
729: @cindex --help, command-line option
730: @item --help
731: @itemx -h
732: Print a message about the command-line options
733:
734: @cindex -v, command-line option
735: @cindex --version, command-line option
736: @item --version
737: @itemx -v
738: Print version and exit
739:
740: @cindex --debug, command-line option
741: @item --debug
742: Print some information useful for debugging on startup.
743:
744: @cindex --offset-image, command-line option
745: @item --offset-image
746: Start the dictionary at a slightly different position than would be used
747: otherwise (useful for creating data-relocatable images,
748: @pxref{Data-Relocatable Image Files}).
749:
750: @cindex --no-offset-im, command-line option
751: @item --no-offset-im
752: Start the dictionary at the normal position.
753:
754: @cindex --clear-dictionary, command-line option
755: @item --clear-dictionary
756: Initialize all bytes in the dictionary to 0 before loading the image
757: (@pxref{Data-Relocatable Image Files}).
758:
759: @cindex --die-on-signal, command-line-option
760: @item --die-on-signal
761: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
762: or the segmentation violation SIGSEGV) by translating it into a Forth
763: @code{THROW}. With this option, Gforth exits if it receives such a
764: signal. This option is useful when the engine and/or the image might be
765: severely broken (such that it causes another signal before recovering
766: from the first); this option avoids endless loops in such cases.
1.109 anton 767:
1.119 anton 768: @cindex --no-dynamic, command-line option
769: @cindex --dynamic, command-line option
1.109 anton 770: @item --no-dynamic
771: @item --dynamic
772: Disable or enable dynamic superinstructions with replication
773: (@pxref{Dynamic Superinstructions}).
774:
1.119 anton 775: @cindex --no-super, command-line option
1.109 anton 776: @item --no-super
1.110 anton 777: Disable dynamic superinstructions, use just dynamic replication; this is
778: useful if you want to patch threaded code (@pxref{Dynamic
779: Superinstructions}).
1.119 anton 780:
781: @cindex --ss-number, command-line option
782: @item --ss-number=@var{N}
783: Use only the first @var{N} static superinstructions compiled into the
784: engine (default: use them all; note that only @code{gforth-fast} has
785: any). This option is useful for measuring the performance impact of
786: static superinstructions.
787:
788: @cindex --ss-min-..., command-line options
789: @item --ss-min-codesize
790: @item --ss-min-ls
791: @item --ss-min-lsu
792: @item --ss-min-nexts
793: Use specified metric for determining the cost of a primitive or static
794: superinstruction for static superinstruction selection. @code{Codesize}
795: is the native code size of the primive or static superinstruction,
796: @code{ls} is the number of loads and stores, @code{lsu} is the number of
797: loads, stores, and updates, and @code{nexts} is the number of dispatches
798: (not taking dynamic superinstructions into account), i.e. every
799: primitive or static superinstruction has cost 1. Default:
800: @code{codesize} if you use dynamic code generation, otherwise
801: @code{nexts}.
802:
803: @cindex --ss-greedy, command-line option
804: @item --ss-greedy
805: This option is useful for measuring the performance impact of static
806: superinstructions. By default, an optimal shortest-path algorithm is
807: used for selecting static superinstructions. With @option{--ss-greedy}
808: this algorithm is modified to assume that anything after the static
809: superinstruction currently under consideration is not combined into
810: static superinstructions. With @option{--ss-min-nexts} this produces
811: the same result as a greedy algorithm that always selects the longest
812: superinstruction available at the moment. E.g., if there are
813: superinstructions AB and BCD, then for the sequence A B C D the optimal
814: algorithm will select A BCD and the greedy algorithm will select AB C D.
815:
816: @cindex --print-metrics, command-line option
817: @item --print-metrics
818: Prints some metrics used during static superinstruction selection:
819: @code{code size} is the actual size of the dynamically generated code.
820: @code{Metric codesize} is the sum of the codesize metrics as seen by
821: static superinstruction selection; there is a difference from @code{code
822: size}, because not all primitives and static superinstructions are
823: compiled into dynamically generated code, and because of markers. The
824: other metrics correspond to the @option{ss-min-...} options. This
825: option is useful for evaluating the effects of the @option{--ss-...}
826: options.
1.109 anton 827:
1.48 anton 828: @end table
829:
830: @cindex loading files at startup
831: @cindex executing code on startup
832: @cindex batch processing with Gforth
833: As explained above, the image-specific command-line arguments for the
834: default image @file{gforth.fi} consist of a sequence of filenames and
835: @code{-e @var{forth-code}} options that are interpreted in the sequence
836: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 837: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
838: option takes only one argument; if you want to evaluate more Forth
839: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 840: after processing the command line (instead of entering interactive mode)
1.121 anton 841: append @code{-e bye} to the command line. You can also process the
842: command-line arguments with a Forth program (@pxref{OS command line
843: arguments}).
1.48 anton 844:
845: @cindex versions, invoking other versions of Gforth
846: If you have several versions of Gforth installed, @code{gforth} will
847: invoke the version that was installed last. @code{gforth-@i{version}}
848: invokes a specific version. If your environment contains the variable
849: @code{GFORTHPATH}, you may want to override it by using the
850: @code{--path} option.
851:
852: Not yet implemented:
853: On startup the system first executes the system initialization file
854: (unless the option @code{--no-init-file} is given; note that the system
855: resulting from using this option may not be ANS Forth conformant). Then
856: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 857: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 858: then in @file{~}, then in the normal path (see above).
859:
860:
861:
862: @comment ----------------------------------------------
863: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
864: @section Leaving Gforth
865: @cindex Gforth - leaving
866: @cindex leaving Gforth
867:
868: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
869: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
870: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 871: data are discarded. For ways of saving the state of the system before
872: leaving Gforth see @ref{Image Files}.
1.48 anton 873:
874: doc-bye
875:
876:
877: @comment ----------------------------------------------
1.65 anton 878: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 879: @section Command-line editing
880: @cindex command-line editing
881:
882: Gforth maintains a history file that records every line that you type to
883: the text interpreter. This file is preserved between sessions, and is
884: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
885: repeatedly you can recall successively older commands from this (or
886: previous) session(s). The full list of command-line editing facilities is:
887:
888: @itemize @bullet
889: @item
890: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
891: commands from the history buffer.
892: @item
893: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
894: from the history buffer.
895: @item
896: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
897: @item
898: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
899: @item
900: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
901: closing up the line.
902: @item
903: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
904: @item
905: @kbd{Ctrl-a} to move the cursor to the start of the line.
906: @item
907: @kbd{Ctrl-e} to move the cursor to the end of the line.
908: @item
909: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
910: line.
911: @item
912: @key{TAB} to step through all possible full-word completions of the word
913: currently being typed.
914: @item
1.65 anton 915: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
916: using @code{bye}).
917: @item
918: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
919: character under the cursor.
1.48 anton 920: @end itemize
921:
922: When editing, displayable characters are inserted to the left of the
923: cursor position; the line is always in ``insert'' (as opposed to
924: ``overstrike'') mode.
925:
926: @cindex history file
927: @cindex @file{.gforth-history}
928: On Unix systems, the history file is @file{~/.gforth-history} by
929: default@footnote{i.e. it is stored in the user's home directory.}. You
930: can find out the name and location of your history file using:
931:
932: @example
933: history-file type \ Unix-class systems
934:
935: history-file type \ Other systems
936: history-dir type
937: @end example
938:
939: If you enter long definitions by hand, you can use a text editor to
940: paste them out of the history file into a Forth source file for reuse at
941: a later time.
942:
943: Gforth never trims the size of the history file, so you should do this
944: periodically, if necessary.
945:
946: @comment this is all defined in history.fs
947: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
948: @comment chosen?
949:
950:
951: @comment ----------------------------------------------
1.65 anton 952: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 953: @section Environment variables
954: @cindex environment variables
955:
956: Gforth uses these environment variables:
957:
958: @itemize @bullet
959: @item
960: @cindex @code{GFORTHHIST} -- environment variable
961: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
962: open/create the history file, @file{.gforth-history}. Default:
963: @code{$HOME}.
964:
965: @item
966: @cindex @code{GFORTHPATH} -- environment variable
967: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
968: for Forth source-code files.
969:
970: @item
1.129 anton 971: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
972:
973: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
974: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 975: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 976: and the command are directly concatenated, so if a space between them is
977: necessary, append it to the prefix.
978:
979: @item
1.48 anton 980: @cindex @code{GFORTH} -- environment variable
1.49 anton 981: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 982:
983: @item
984: @cindex @code{GFORTHD} -- environment variable
1.62 crook 985: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 986:
987: @item
988: @cindex @code{TMP}, @code{TEMP} - environment variable
989: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
990: location for the history file.
991: @end itemize
992:
993: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
994: @comment mentioning these.
995:
996: All the Gforth environment variables default to sensible values if they
997: are not set.
998:
999:
1000: @comment ----------------------------------------------
1.112 anton 1001: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1002: @section Gforth files
1003: @cindex Gforth files
1004:
1005: When you install Gforth on a Unix system, it installs files in these
1006: locations by default:
1007:
1008: @itemize @bullet
1009: @item
1010: @file{/usr/local/bin/gforth}
1011: @item
1012: @file{/usr/local/bin/gforthmi}
1013: @item
1014: @file{/usr/local/man/man1/gforth.1} - man page.
1015: @item
1016: @file{/usr/local/info} - the Info version of this manual.
1017: @item
1018: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1019: @item
1020: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1021: @item
1022: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1023: @item
1024: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1025: @end itemize
1026:
1027: You can select different places for installation by using
1028: @code{configure} options (listed with @code{configure --help}).
1029:
1030: @comment ----------------------------------------------
1.112 anton 1031: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1032: @section Gforth in pipes
1033: @cindex pipes, Gforth as part of
1034:
1035: Gforth can be used in pipes created elsewhere (described here). It can
1036: also create pipes on its own (@pxref{Pipes}).
1037:
1038: @cindex input from pipes
1039: If you pipe into Gforth, your program should read with @code{read-file}
1040: or @code{read-line} from @code{stdin} (@pxref{General files}).
1041: @code{Key} does not recognize the end of input. Words like
1042: @code{accept} echo the input and are therefore usually not useful for
1043: reading from a pipe. You have to invoke the Forth program with an OS
1044: command-line option, as you have no chance to use the Forth command line
1045: (the text interpreter would try to interpret the pipe input).
1046:
1047: @cindex output in pipes
1048: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1049:
1050: @cindex silent exiting from Gforth
1051: When you write to a pipe that has been closed at the other end, Gforth
1052: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1053: into the exception @code{broken-pipe-error}. If your application does
1054: not catch that exception, the system catches it and exits, usually
1055: silently (unless you were working on the Forth command line; then it
1056: prints an error message and exits). This is usually the desired
1057: behaviour.
1058:
1059: If you do not like this behaviour, you have to catch the exception
1060: yourself, and react to it.
1061:
1062: Here's an example of an invocation of Gforth that is usable in a pipe:
1063:
1064: @example
1065: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1066: type repeat ; foo bye"
1067: @end example
1068:
1069: This example just copies the input verbatim to the output. A very
1070: simple pipe containing this example looks like this:
1071:
1072: @example
1073: cat startup.fs |
1074: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1075: type repeat ; foo bye"|
1076: head
1077: @end example
1078:
1079: @cindex stderr and pipes
1080: Pipes involving Gforth's @code{stderr} output do not work.
1081:
1082: @comment ----------------------------------------------
1083: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1084: @section Startup speed
1085: @cindex Startup speed
1086: @cindex speed, startup
1087:
1088: If Gforth is used for CGI scripts or in shell scripts, its startup
1089: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1090: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1091: system time.
1092:
1093: If startup speed is a problem, you may consider the following ways to
1094: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1095: (for example, by using Fast-CGI).
1.48 anton 1096:
1.112 anton 1097: An easy step that influences Gforth startup speed is the use of the
1098: @option{--no-dynamic} option; this decreases image loading speed, but
1099: increases compile-time and run-time.
1100:
1101: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1102: building it with @code{XLDFLAGS=-static}. This requires more memory for
1103: the code and will therefore slow down the first invocation, but
1104: subsequent invocations avoid the dynamic linking overhead. Another
1105: disadvantage is that Gforth won't profit from library upgrades. As a
1106: result, @code{gforth-static -e bye} takes about 17.1ms user and
1107: 8.2ms system time.
1108:
1109: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1110: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1111: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1112: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1113: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1114: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1115: address for the dictionary, for whatever reason; so you better provide a
1116: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1117: bye} takes about 15.3ms user and 7.5ms system time.
1118:
1119: The final step is to disable dictionary hashing in Gforth. Gforth
1120: builds the hash table on startup, which takes much of the startup
1121: overhead. You can do this by commenting out the @code{include hash.fs}
1122: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1123: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1124: The disadvantages are that functionality like @code{table} and
1125: @code{ekey} is missing and that text interpretation (e.g., compiling)
1126: now takes much longer. So, you should only use this method if there is
1127: no significant text interpretation to perform (the script should be
1.62 crook 1128: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1129: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1130:
1131: @c ******************************************************************
1132: @node Tutorial, Introduction, Gforth Environment, Top
1133: @chapter Forth Tutorial
1134: @cindex Tutorial
1135: @cindex Forth Tutorial
1136:
1.67 anton 1137: @c Topics from nac's Introduction that could be mentioned:
1138: @c press <ret> after each line
1139: @c Prompt
1140: @c numbers vs. words in dictionary on text interpretation
1141: @c what happens on redefinition
1142: @c parsing words (in particular, defining words)
1143:
1.83 anton 1144: The difference of this chapter from the Introduction
1145: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1146: be used while sitting in front of a computer, and covers much more
1147: material, but does not explain how the Forth system works.
1148:
1.62 crook 1149: This tutorial can be used with any ANS-compliant Forth; any
1150: Gforth-specific features are marked as such and you can skip them if you
1151: work with another Forth. This tutorial does not explain all features of
1152: Forth, just enough to get you started and give you some ideas about the
1153: facilities available in Forth. Read the rest of the manual and the
1154: standard when you are through this.
1.48 anton 1155:
1156: The intended way to use this tutorial is that you work through it while
1157: sitting in front of the console, take a look at the examples and predict
1158: what they will do, then try them out; if the outcome is not as expected,
1159: find out why (e.g., by trying out variations of the example), so you
1160: understand what's going on. There are also some assignments that you
1161: should solve.
1162:
1163: This tutorial assumes that you have programmed before and know what,
1164: e.g., a loop is.
1165:
1166: @c !! explain compat library
1167:
1168: @menu
1169: * Starting Gforth Tutorial::
1170: * Syntax Tutorial::
1171: * Crash Course Tutorial::
1172: * Stack Tutorial::
1173: * Arithmetics Tutorial::
1174: * Stack Manipulation Tutorial::
1175: * Using files for Forth code Tutorial::
1176: * Comments Tutorial::
1177: * Colon Definitions Tutorial::
1178: * Decompilation Tutorial::
1179: * Stack-Effect Comments Tutorial::
1180: * Types Tutorial::
1181: * Factoring Tutorial::
1182: * Designing the stack effect Tutorial::
1183: * Local Variables Tutorial::
1184: * Conditional execution Tutorial::
1185: * Flags and Comparisons Tutorial::
1186: * General Loops Tutorial::
1187: * Counted loops Tutorial::
1188: * Recursion Tutorial::
1189: * Leaving definitions or loops Tutorial::
1190: * Return Stack Tutorial::
1191: * Memory Tutorial::
1192: * Characters and Strings Tutorial::
1193: * Alignment Tutorial::
1.87 anton 1194: * Files Tutorial::
1.48 anton 1195: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1196: * Execution Tokens Tutorial::
1197: * Exceptions Tutorial::
1198: * Defining Words Tutorial::
1199: * Arrays and Records Tutorial::
1200: * POSTPONE Tutorial::
1201: * Literal Tutorial::
1202: * Advanced macros Tutorial::
1203: * Compilation Tokens Tutorial::
1204: * Wordlists and Search Order Tutorial::
1205: @end menu
1206:
1207: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1208: @section Starting Gforth
1.66 anton 1209: @cindex starting Gforth tutorial
1.48 anton 1210: You can start Gforth by typing its name:
1211:
1212: @example
1213: gforth
1214: @end example
1215:
1216: That puts you into interactive mode; you can leave Gforth by typing
1217: @code{bye}. While in Gforth, you can edit the command line and access
1218: the command line history with cursor keys, similar to bash.
1219:
1220:
1221: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1222: @section Syntax
1.66 anton 1223: @cindex syntax tutorial
1.48 anton 1224:
1225: A @dfn{word} is a sequence of arbitrary characters (expcept white
1226: space). Words are separated by white space. E.g., each of the
1227: following lines contains exactly one word:
1228:
1229: @example
1230: word
1231: !@@#$%^&*()
1232: 1234567890
1233: 5!a
1234: @end example
1235:
1236: A frequent beginner's error is to leave away necessary white space,
1237: resulting in an error like @samp{Undefined word}; so if you see such an
1238: error, check if you have put spaces wherever necessary.
1239:
1240: @example
1241: ." hello, world" \ correct
1242: ."hello, world" \ gives an "Undefined word" error
1243: @end example
1244:
1.65 anton 1245: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1246: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1247: your system is case-sensitive, you may have to type all the examples
1248: given here in upper case.
1249:
1250:
1251: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1252: @section Crash Course
1253:
1254: Type
1255:
1256: @example
1257: 0 0 !
1258: here execute
1259: ' catch >body 20 erase abort
1260: ' (quit) >body 20 erase
1261: @end example
1262:
1263: The last two examples are guaranteed to destroy parts of Gforth (and
1264: most other systems), so you better leave Gforth afterwards (if it has
1265: not finished by itself). On some systems you may have to kill gforth
1266: from outside (e.g., in Unix with @code{kill}).
1267:
1268: Now that you know how to produce crashes (and that there's not much to
1269: them), let's learn how to produce meaningful programs.
1270:
1271:
1272: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1273: @section Stack
1.66 anton 1274: @cindex stack tutorial
1.48 anton 1275:
1276: The most obvious feature of Forth is the stack. When you type in a
1277: number, it is pushed on the stack. You can display the content of the
1278: stack with @code{.s}.
1279:
1280: @example
1281: 1 2 .s
1282: 3 .s
1283: @end example
1284:
1285: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1286: appear in @code{.s} output as they appeared in the input.
1287:
1288: You can print the top of stack element with @code{.}.
1289:
1290: @example
1291: 1 2 3 . . .
1292: @end example
1293:
1294: In general, words consume their stack arguments (@code{.s} is an
1295: exception).
1296:
1297: @assignment
1298: What does the stack contain after @code{5 6 7 .}?
1299: @endassignment
1300:
1301:
1302: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1303: @section Arithmetics
1.66 anton 1304: @cindex arithmetics tutorial
1.48 anton 1305:
1306: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1307: operate on the top two stack items:
1308:
1309: @example
1.67 anton 1310: 2 2 .s
1311: + .s
1312: .
1.48 anton 1313: 2 1 - .
1314: 7 3 mod .
1315: @end example
1316:
1317: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1318: as in the corresponding infix expression (this is generally the case in
1319: Forth).
1320:
1321: Parentheses are superfluous (and not available), because the order of
1322: the words unambiguously determines the order of evaluation and the
1323: operands:
1324:
1325: @example
1326: 3 4 + 5 * .
1327: 3 4 5 * + .
1328: @end example
1329:
1330: @assignment
1331: What are the infix expressions corresponding to the Forth code above?
1332: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1333: known as Postfix or RPN (Reverse Polish Notation).}.
1334: @endassignment
1335:
1336: To change the sign, use @code{negate}:
1337:
1338: @example
1339: 2 negate .
1340: @end example
1341:
1342: @assignment
1343: Convert -(-3)*4-5 to Forth.
1344: @endassignment
1345:
1346: @code{/mod} performs both @code{/} and @code{mod}.
1347:
1348: @example
1349: 7 3 /mod . .
1350: @end example
1351:
1.66 anton 1352: Reference: @ref{Arithmetic}.
1353:
1354:
1.48 anton 1355: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1356: @section Stack Manipulation
1.66 anton 1357: @cindex stack manipulation tutorial
1.48 anton 1358:
1359: Stack manipulation words rearrange the data on the stack.
1360:
1361: @example
1362: 1 .s drop .s
1363: 1 .s dup .s drop drop .s
1364: 1 2 .s over .s drop drop drop
1365: 1 2 .s swap .s drop drop
1366: 1 2 3 .s rot .s drop drop drop
1367: @end example
1368:
1369: These are the most important stack manipulation words. There are also
1370: variants that manipulate twice as many stack items:
1371:
1372: @example
1373: 1 2 3 4 .s 2swap .s 2drop 2drop
1374: @end example
1375:
1376: Two more stack manipulation words are:
1377:
1378: @example
1379: 1 2 .s nip .s drop
1380: 1 2 .s tuck .s 2drop drop
1381: @end example
1382:
1383: @assignment
1384: Replace @code{nip} and @code{tuck} with combinations of other stack
1385: manipulation words.
1386:
1387: @example
1388: Given: How do you get:
1389: 1 2 3 3 2 1
1390: 1 2 3 1 2 3 2
1391: 1 2 3 1 2 3 3
1392: 1 2 3 1 3 3
1393: 1 2 3 2 1 3
1394: 1 2 3 4 4 3 2 1
1395: 1 2 3 1 2 3 1 2 3
1396: 1 2 3 4 1 2 3 4 1 2
1397: 1 2 3
1398: 1 2 3 1 2 3 4
1399: 1 2 3 1 3
1400: @end example
1401: @endassignment
1402:
1403: @example
1404: 5 dup * .
1405: @end example
1406:
1407: @assignment
1408: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1409: Write a piece of Forth code that expects two numbers on the stack
1410: (@var{a} and @var{b}, with @var{b} on top) and computes
1411: @code{(a-b)(a+1)}.
1412: @endassignment
1413:
1.66 anton 1414: Reference: @ref{Stack Manipulation}.
1415:
1416:
1.48 anton 1417: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1418: @section Using files for Forth code
1.66 anton 1419: @cindex loading Forth code, tutorial
1420: @cindex files containing Forth code, tutorial
1.48 anton 1421:
1422: While working at the Forth command line is convenient for one-line
1423: examples and short one-off code, you probably want to store your source
1424: code in files for convenient editing and persistence. You can use your
1425: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1426: Gforth}) to create @var{file.fs} and use
1.48 anton 1427:
1428: @example
1.102 anton 1429: s" @var{file.fs}" included
1.48 anton 1430: @end example
1431:
1432: to load it into your Forth system. The file name extension I use for
1433: Forth files is @samp{.fs}.
1434:
1435: You can easily start Gforth with some files loaded like this:
1436:
1437: @example
1.102 anton 1438: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1439: @end example
1440:
1441: If an error occurs during loading these files, Gforth terminates,
1442: whereas an error during @code{INCLUDED} within Gforth usually gives you
1443: a Gforth command line. Starting the Forth system every time gives you a
1444: clean start every time, without interference from the results of earlier
1445: tries.
1446:
1447: I often put all the tests in a file, then load the code and run the
1448: tests with
1449:
1450: @example
1.102 anton 1451: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1452: @end example
1453:
1454: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1455: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1456: restart this command without ado.
1457:
1458: The advantage of this approach is that the tests can be repeated easily
1459: every time the program ist changed, making it easy to catch bugs
1460: introduced by the change.
1461:
1.66 anton 1462: Reference: @ref{Forth source files}.
1463:
1.48 anton 1464:
1465: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1466: @section Comments
1.66 anton 1467: @cindex comments tutorial
1.48 anton 1468:
1469: @example
1470: \ That's a comment; it ends at the end of the line
1471: ( Another comment; it ends here: ) .s
1472: @end example
1473:
1474: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1475: separated with white space from the following text.
1476:
1477: @example
1478: \This gives an "Undefined word" error
1479: @end example
1480:
1481: The first @code{)} ends a comment started with @code{(}, so you cannot
1482: nest @code{(}-comments; and you cannot comment out text containing a
1483: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1484: avoid @code{)} in word names.}.
1485:
1486: I use @code{\}-comments for descriptive text and for commenting out code
1487: of one or more line; I use @code{(}-comments for describing the stack
1488: effect, the stack contents, or for commenting out sub-line pieces of
1489: code.
1490:
1491: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1492: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1493: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1494: with @kbd{M-q}.
1495:
1.66 anton 1496: Reference: @ref{Comments}.
1497:
1.48 anton 1498:
1499: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1500: @section Colon Definitions
1.66 anton 1501: @cindex colon definitions, tutorial
1502: @cindex definitions, tutorial
1503: @cindex procedures, tutorial
1504: @cindex functions, tutorial
1.48 anton 1505:
1506: are similar to procedures and functions in other programming languages.
1507:
1508: @example
1509: : squared ( n -- n^2 )
1510: dup * ;
1511: 5 squared .
1512: 7 squared .
1513: @end example
1514:
1515: @code{:} starts the colon definition; its name is @code{squared}. The
1516: following comment describes its stack effect. The words @code{dup *}
1517: are not executed, but compiled into the definition. @code{;} ends the
1518: colon definition.
1519:
1520: The newly-defined word can be used like any other word, including using
1521: it in other definitions:
1522:
1523: @example
1524: : cubed ( n -- n^3 )
1525: dup squared * ;
1526: -5 cubed .
1527: : fourth-power ( n -- n^4 )
1528: squared squared ;
1529: 3 fourth-power .
1530: @end example
1531:
1532: @assignment
1533: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1534: @code{/mod} in terms of other Forth words, and check if they work (hint:
1535: test your tests on the originals first). Don't let the
1536: @samp{redefined}-Messages spook you, they are just warnings.
1537: @endassignment
1538:
1.66 anton 1539: Reference: @ref{Colon Definitions}.
1540:
1.48 anton 1541:
1542: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1543: @section Decompilation
1.66 anton 1544: @cindex decompilation tutorial
1545: @cindex see tutorial
1.48 anton 1546:
1547: You can decompile colon definitions with @code{see}:
1548:
1549: @example
1550: see squared
1551: see cubed
1552: @end example
1553:
1554: In Gforth @code{see} shows you a reconstruction of the source code from
1555: the executable code. Informations that were present in the source, but
1556: not in the executable code, are lost (e.g., comments).
1557:
1.65 anton 1558: You can also decompile the predefined words:
1559:
1560: @example
1561: see .
1562: see +
1563: @end example
1564:
1565:
1.48 anton 1566: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1567: @section Stack-Effect Comments
1.66 anton 1568: @cindex stack-effect comments, tutorial
1569: @cindex --, tutorial
1.48 anton 1570: By convention the comment after the name of a definition describes the
1571: stack effect: The part in from of the @samp{--} describes the state of
1572: the stack before the execution of the definition, i.e., the parameters
1573: that are passed into the colon definition; the part behind the @samp{--}
1574: is the state of the stack after the execution of the definition, i.e.,
1575: the results of the definition. The stack comment only shows the top
1576: stack items that the definition accesses and/or changes.
1577:
1578: You should put a correct stack effect on every definition, even if it is
1579: just @code{( -- )}. You should also add some descriptive comment to
1580: more complicated words (I usually do this in the lines following
1581: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1582: you have to work through every definition before you can understand
1.48 anton 1583: any).
1584:
1585: @assignment
1586: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1587: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1588: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1589: are done, you can compare your stack effects to those in this manual
1.48 anton 1590: (@pxref{Word Index}).
1591: @endassignment
1592:
1593: Sometimes programmers put comments at various places in colon
1594: definitions that describe the contents of the stack at that place (stack
1595: comments); i.e., they are like the first part of a stack-effect
1596: comment. E.g.,
1597:
1598: @example
1599: : cubed ( n -- n^3 )
1600: dup squared ( n n^2 ) * ;
1601: @end example
1602:
1603: In this case the stack comment is pretty superfluous, because the word
1604: is simple enough. If you think it would be a good idea to add such a
1605: comment to increase readability, you should also consider factoring the
1606: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1607: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1608: however, if you decide not to refactor it, then having such a comment is
1609: better than not having it.
1610:
1611: The names of the stack items in stack-effect and stack comments in the
1612: standard, in this manual, and in many programs specify the type through
1613: a type prefix, similar to Fortran and Hungarian notation. The most
1614: frequent prefixes are:
1615:
1616: @table @code
1617: @item n
1618: signed integer
1619: @item u
1620: unsigned integer
1621: @item c
1622: character
1623: @item f
1624: Boolean flags, i.e. @code{false} or @code{true}.
1625: @item a-addr,a-
1626: Cell-aligned address
1627: @item c-addr,c-
1628: Char-aligned address (note that a Char may have two bytes in Windows NT)
1629: @item xt
1630: Execution token, same size as Cell
1631: @item w,x
1632: Cell, can contain an integer or an address. It usually takes 32, 64 or
1633: 16 bits (depending on your platform and Forth system). A cell is more
1634: commonly known as machine word, but the term @emph{word} already means
1635: something different in Forth.
1636: @item d
1637: signed double-cell integer
1638: @item ud
1639: unsigned double-cell integer
1640: @item r
1641: Float (on the FP stack)
1642: @end table
1643:
1644: You can find a more complete list in @ref{Notation}.
1645:
1646: @assignment
1647: Write stack-effect comments for all definitions you have written up to
1648: now.
1649: @endassignment
1650:
1651:
1652: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1653: @section Types
1.66 anton 1654: @cindex types tutorial
1.48 anton 1655:
1656: In Forth the names of the operations are not overloaded; so similar
1657: operations on different types need different names; e.g., @code{+} adds
1658: integers, and you have to use @code{f+} to add floating-point numbers.
1659: The following prefixes are often used for related operations on
1660: different types:
1661:
1662: @table @code
1663: @item (none)
1664: signed integer
1665: @item u
1666: unsigned integer
1667: @item c
1668: character
1669: @item d
1670: signed double-cell integer
1671: @item ud, du
1672: unsigned double-cell integer
1673: @item 2
1674: two cells (not-necessarily double-cell numbers)
1675: @item m, um
1676: mixed single-cell and double-cell operations
1677: @item f
1678: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1679: and @samp{r} represents FP numbers).
1.48 anton 1680: @end table
1681:
1682: If there are no differences between the signed and the unsigned variant
1683: (e.g., for @code{+}), there is only the prefix-less variant.
1684:
1685: Forth does not perform type checking, neither at compile time, nor at
1686: run time. If you use the wrong oeration, the data are interpreted
1687: incorrectly:
1688:
1689: @example
1690: -1 u.
1691: @end example
1692:
1693: If you have only experience with type-checked languages until now, and
1694: have heard how important type-checking is, don't panic! In my
1695: experience (and that of other Forthers), type errors in Forth code are
1696: usually easy to find (once you get used to it), the increased vigilance
1697: of the programmer tends to catch some harder errors in addition to most
1698: type errors, and you never have to work around the type system, so in
1699: most situations the lack of type-checking seems to be a win (projects to
1700: add type checking to Forth have not caught on).
1701:
1702:
1703: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1704: @section Factoring
1.66 anton 1705: @cindex factoring tutorial
1.48 anton 1706:
1707: If you try to write longer definitions, you will soon find it hard to
1708: keep track of the stack contents. Therefore, good Forth programmers
1709: tend to write only short definitions (e.g., three lines). The art of
1710: finding meaningful short definitions is known as factoring (as in
1711: factoring polynomials).
1712:
1713: Well-factored programs offer additional advantages: smaller, more
1714: general words, are easier to test and debug and can be reused more and
1715: better than larger, specialized words.
1716:
1717: So, if you run into difficulties with stack management, when writing
1718: code, try to define meaningful factors for the word, and define the word
1719: in terms of those. Even if a factor contains only two words, it is
1720: often helpful.
1721:
1.65 anton 1722: Good factoring is not easy, and it takes some practice to get the knack
1723: for it; but even experienced Forth programmers often don't find the
1724: right solution right away, but only when rewriting the program. So, if
1725: you don't come up with a good solution immediately, keep trying, don't
1726: despair.
1.48 anton 1727:
1728: @c example !!
1729:
1730:
1731: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1732: @section Designing the stack effect
1.66 anton 1733: @cindex Stack effect design, tutorial
1734: @cindex design of stack effects, tutorial
1.48 anton 1735:
1736: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1737: function; and since there is only one result, you don't have to deal with
1.48 anton 1738: the order of results, either.
1739:
1.117 anton 1740: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1741: parameter and result order of a definition is important and should be
1742: designed well. The general guideline is to design the stack effect such
1743: that the word is simple to use in most cases, even if that complicates
1744: the implementation of the word. Some concrete rules are:
1745:
1746: @itemize @bullet
1747:
1748: @item
1749: Words consume all of their parameters (e.g., @code{.}).
1750:
1751: @item
1752: If there is a convention on the order of parameters (e.g., from
1753: mathematics or another programming language), stick with it (e.g.,
1754: @code{-}).
1755:
1756: @item
1757: If one parameter usually requires only a short computation (e.g., it is
1758: a constant), pass it on the top of the stack. Conversely, parameters
1759: that usually require a long sequence of code to compute should be passed
1760: as the bottom (i.e., first) parameter. This makes the code easier to
1761: read, because reader does not need to keep track of the bottom item
1762: through a long sequence of code (or, alternatively, through stack
1.49 anton 1763: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1764: address on top of the stack because it is usually simpler to compute
1765: than the stored value (often the address is just a variable).
1766:
1767: @item
1768: Similarly, results that are usually consumed quickly should be returned
1769: on the top of stack, whereas a result that is often used in long
1770: computations should be passed as bottom result. E.g., the file words
1771: like @code{open-file} return the error code on the top of stack, because
1772: it is usually consumed quickly by @code{throw}; moreover, the error code
1773: has to be checked before doing anything with the other results.
1774:
1775: @end itemize
1776:
1777: These rules are just general guidelines, don't lose sight of the overall
1778: goal to make the words easy to use. E.g., if the convention rule
1779: conflicts with the computation-length rule, you might decide in favour
1780: of the convention if the word will be used rarely, and in favour of the
1781: computation-length rule if the word will be used frequently (because
1782: with frequent use the cost of breaking the computation-length rule would
1783: be quite high, and frequent use makes it easier to remember an
1784: unconventional order).
1785:
1786: @c example !! structure package
1787:
1.65 anton 1788:
1.48 anton 1789: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1790: @section Local Variables
1.66 anton 1791: @cindex local variables, tutorial
1.48 anton 1792:
1793: You can define local variables (@emph{locals}) in a colon definition:
1794:
1795: @example
1796: : swap @{ a b -- b a @}
1797: b a ;
1798: 1 2 swap .s 2drop
1799: @end example
1800:
1801: (If your Forth system does not support this syntax, include
1802: @file{compat/anslocals.fs} first).
1803:
1804: In this example @code{@{ a b -- b a @}} is the locals definition; it
1805: takes two cells from the stack, puts the top of stack in @code{b} and
1806: the next stack element in @code{a}. @code{--} starts a comment ending
1807: with @code{@}}. After the locals definition, using the name of the
1808: local will push its value on the stack. You can leave the comment
1809: part (@code{-- b a}) away:
1810:
1811: @example
1812: : swap ( x1 x2 -- x2 x1 )
1813: @{ a b @} b a ;
1814: @end example
1815:
1816: In Gforth you can have several locals definitions, anywhere in a colon
1817: definition; in contrast, in a standard program you can have only one
1818: locals definition per colon definition, and that locals definition must
1819: be outside any controll structure.
1820:
1821: With locals you can write slightly longer definitions without running
1822: into stack trouble. However, I recommend trying to write colon
1823: definitions without locals for exercise purposes to help you gain the
1824: essential factoring skills.
1825:
1826: @assignment
1827: Rewrite your definitions until now with locals
1828: @endassignment
1829:
1.66 anton 1830: Reference: @ref{Locals}.
1831:
1.48 anton 1832:
1833: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1834: @section Conditional execution
1.66 anton 1835: @cindex conditionals, tutorial
1836: @cindex if, tutorial
1.48 anton 1837:
1838: In Forth you can use control structures only inside colon definitions.
1839: An @code{if}-structure looks like this:
1840:
1841: @example
1842: : abs ( n1 -- +n2 )
1843: dup 0 < if
1844: negate
1845: endif ;
1846: 5 abs .
1847: -5 abs .
1848: @end example
1849:
1850: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1851: the following code is performed, otherwise execution continues after the
1.51 pazsan 1852: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1853: elements and prioduces a flag:
1854:
1855: @example
1856: 1 2 < .
1857: 2 1 < .
1858: 1 1 < .
1859: @end example
1860:
1861: Actually the standard name for @code{endif} is @code{then}. This
1862: tutorial presents the examples using @code{endif}, because this is often
1863: less confusing for people familiar with other programming languages
1864: where @code{then} has a different meaning. If your system does not have
1865: @code{endif}, define it with
1866:
1867: @example
1868: : endif postpone then ; immediate
1869: @end example
1870:
1871: You can optionally use an @code{else}-part:
1872:
1873: @example
1874: : min ( n1 n2 -- n )
1875: 2dup < if
1876: drop
1877: else
1878: nip
1879: endif ;
1880: 2 3 min .
1881: 3 2 min .
1882: @end example
1883:
1884: @assignment
1885: Write @code{min} without @code{else}-part (hint: what's the definition
1886: of @code{nip}?).
1887: @endassignment
1888:
1.66 anton 1889: Reference: @ref{Selection}.
1890:
1.48 anton 1891:
1892: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1893: @section Flags and Comparisons
1.66 anton 1894: @cindex flags tutorial
1895: @cindex comparison tutorial
1.48 anton 1896:
1897: In a false-flag all bits are clear (0 when interpreted as integer). In
1898: a canonical true-flag all bits are set (-1 as a twos-complement signed
1899: integer); in many contexts (e.g., @code{if}) any non-zero value is
1900: treated as true flag.
1901:
1902: @example
1903: false .
1904: true .
1905: true hex u. decimal
1906: @end example
1907:
1908: Comparison words produce canonical flags:
1909:
1910: @example
1911: 1 1 = .
1912: 1 0= .
1913: 0 1 < .
1914: 0 0 < .
1915: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1916: -1 1 < .
1917: @end example
1918:
1.66 anton 1919: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1920: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1921: these combinations are standard (for details see the standard,
1922: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1923:
1924: You can use @code{and or xor invert} can be used as operations on
1925: canonical flags. Actually they are bitwise operations:
1926:
1927: @example
1928: 1 2 and .
1929: 1 2 or .
1930: 1 3 xor .
1931: 1 invert .
1932: @end example
1933:
1934: You can convert a zero/non-zero flag into a canonical flag with
1935: @code{0<>} (and complement it on the way with @code{0=}).
1936:
1937: @example
1938: 1 0= .
1939: 1 0<> .
1940: @end example
1941:
1.65 anton 1942: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1943: operation of the Boolean operations to avoid @code{if}s:
1944:
1945: @example
1946: : foo ( n1 -- n2 )
1947: 0= if
1948: 14
1949: else
1950: 0
1951: endif ;
1952: 0 foo .
1953: 1 foo .
1954:
1955: : foo ( n1 -- n2 )
1956: 0= 14 and ;
1957: 0 foo .
1958: 1 foo .
1959: @end example
1960:
1961: @assignment
1962: Write @code{min} without @code{if}.
1963: @endassignment
1964:
1.66 anton 1965: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1966: @ref{Bitwise operations}.
1967:
1.48 anton 1968:
1969: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1970: @section General Loops
1.66 anton 1971: @cindex loops, indefinite, tutorial
1.48 anton 1972:
1973: The endless loop is the most simple one:
1974:
1975: @example
1976: : endless ( -- )
1977: 0 begin
1978: dup . 1+
1979: again ;
1980: endless
1981: @end example
1982:
1983: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
1984: does nothing at run-time, @code{again} jumps back to @code{begin}.
1985:
1986: A loop with one exit at any place looks like this:
1987:
1988: @example
1989: : log2 ( +n1 -- n2 )
1990: \ logarithmus dualis of n1>0, rounded down to the next integer
1991: assert( dup 0> )
1992: 2/ 0 begin
1993: over 0> while
1994: 1+ swap 2/ swap
1995: repeat
1996: nip ;
1997: 7 log2 .
1998: 8 log2 .
1999: @end example
2000:
2001: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2002: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2003: continues behind the @code{while}. @code{Repeat} jumps back to
2004: @code{begin}, just like @code{again}.
2005:
2006: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2007: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2008: one bit (arithmetic shift right):
2009:
2010: @example
2011: -5 2 / .
2012: -5 2/ .
2013: @end example
2014:
2015: @code{assert(} is no standard word, but you can get it on systems other
2016: then Gforth by including @file{compat/assert.fs}. You can see what it
2017: does by trying
2018:
2019: @example
2020: 0 log2 .
2021: @end example
2022:
2023: Here's a loop with an exit at the end:
2024:
2025: @example
2026: : log2 ( +n1 -- n2 )
2027: \ logarithmus dualis of n1>0, rounded down to the next integer
2028: assert( dup 0 > )
2029: -1 begin
2030: 1+ swap 2/ swap
2031: over 0 <=
2032: until
2033: nip ;
2034: @end example
2035:
2036: @code{Until} consumes a flag; if it is non-zero, execution continues at
2037: the @code{begin}, otherwise after the @code{until}.
2038:
2039: @assignment
2040: Write a definition for computing the greatest common divisor.
2041: @endassignment
2042:
1.66 anton 2043: Reference: @ref{Simple Loops}.
2044:
1.48 anton 2045:
2046: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2047: @section Counted loops
1.66 anton 2048: @cindex loops, counted, tutorial
1.48 anton 2049:
2050: @example
2051: : ^ ( n1 u -- n )
2052: \ n = the uth power of u1
2053: 1 swap 0 u+do
2054: over *
2055: loop
2056: nip ;
2057: 3 2 ^ .
2058: 4 3 ^ .
2059: @end example
2060:
2061: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2062: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2063: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2064: times (or not at all, if @code{u3-u4<0}).
2065:
2066: You can see the stack effect design rules at work in the stack effect of
2067: the loop start words: Since the start value of the loop is more
2068: frequently constant than the end value, the start value is passed on
2069: the top-of-stack.
2070:
2071: You can access the counter of a counted loop with @code{i}:
2072:
2073: @example
2074: : fac ( u -- u! )
2075: 1 swap 1+ 1 u+do
2076: i *
2077: loop ;
2078: 5 fac .
2079: 7 fac .
2080: @end example
2081:
2082: There is also @code{+do}, which expects signed numbers (important for
2083: deciding whether to enter the loop).
2084:
2085: @assignment
2086: Write a definition for computing the nth Fibonacci number.
2087: @endassignment
2088:
1.65 anton 2089: You can also use increments other than 1:
2090:
2091: @example
2092: : up2 ( n1 n2 -- )
2093: +do
2094: i .
2095: 2 +loop ;
2096: 10 0 up2
2097:
2098: : down2 ( n1 n2 -- )
2099: -do
2100: i .
2101: 2 -loop ;
2102: 0 10 down2
2103: @end example
1.48 anton 2104:
1.66 anton 2105: Reference: @ref{Counted Loops}.
2106:
1.48 anton 2107:
2108: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2109: @section Recursion
1.66 anton 2110: @cindex recursion tutorial
1.48 anton 2111:
2112: Usually the name of a definition is not visible in the definition; but
2113: earlier definitions are usually visible:
2114:
2115: @example
2116: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2117: : / ( n1 n2 -- n )
2118: dup 0= if
2119: -10 throw \ report division by zero
2120: endif
2121: / \ old version
2122: ;
2123: 1 0 /
2124: @end example
2125:
2126: For recursive definitions you can use @code{recursive} (non-standard) or
2127: @code{recurse}:
2128:
2129: @example
2130: : fac1 ( n -- n! ) recursive
2131: dup 0> if
2132: dup 1- fac1 *
2133: else
2134: drop 1
2135: endif ;
2136: 7 fac1 .
2137:
2138: : fac2 ( n -- n! )
2139: dup 0> if
2140: dup 1- recurse *
2141: else
2142: drop 1
2143: endif ;
2144: 8 fac2 .
2145: @end example
2146:
2147: @assignment
2148: Write a recursive definition for computing the nth Fibonacci number.
2149: @endassignment
2150:
1.66 anton 2151: Reference (including indirect recursion): @xref{Calls and returns}.
2152:
1.48 anton 2153:
2154: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2155: @section Leaving definitions or loops
1.66 anton 2156: @cindex leaving definitions, tutorial
2157: @cindex leaving loops, tutorial
1.48 anton 2158:
2159: @code{EXIT} exits the current definition right away. For every counted
2160: loop that is left in this way, an @code{UNLOOP} has to be performed
2161: before the @code{EXIT}:
2162:
2163: @c !! real examples
2164: @example
2165: : ...
2166: ... u+do
2167: ... if
2168: ... unloop exit
2169: endif
2170: ...
2171: loop
2172: ... ;
2173: @end example
2174:
2175: @code{LEAVE} leaves the innermost counted loop right away:
2176:
2177: @example
2178: : ...
2179: ... u+do
2180: ... if
2181: ... leave
2182: endif
2183: ...
2184: loop
2185: ... ;
2186: @end example
2187:
1.65 anton 2188: @c !! example
1.48 anton 2189:
1.66 anton 2190: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2191:
2192:
1.48 anton 2193: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2194: @section Return Stack
1.66 anton 2195: @cindex return stack tutorial
1.48 anton 2196:
2197: In addition to the data stack Forth also has a second stack, the return
2198: stack; most Forth systems store the return addresses of procedure calls
2199: there (thus its name). Programmers can also use this stack:
2200:
2201: @example
2202: : foo ( n1 n2 -- )
2203: .s
2204: >r .s
1.50 anton 2205: r@@ .
1.48 anton 2206: >r .s
1.50 anton 2207: r@@ .
1.48 anton 2208: r> .
1.50 anton 2209: r@@ .
1.48 anton 2210: r> . ;
2211: 1 2 foo
2212: @end example
2213:
2214: @code{>r} takes an element from the data stack and pushes it onto the
2215: return stack; conversely, @code{r>} moves an elementm from the return to
2216: the data stack; @code{r@@} pushes a copy of the top of the return stack
2217: on the return stack.
2218:
2219: Forth programmers usually use the return stack for storing data
2220: temporarily, if using the data stack alone would be too complex, and
2221: factoring and locals are not an option:
2222:
2223: @example
2224: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2225: rot >r rot r> ;
2226: @end example
2227:
2228: The return address of the definition and the loop control parameters of
2229: counted loops usually reside on the return stack, so you have to take
2230: all items, that you have pushed on the return stack in a colon
2231: definition or counted loop, from the return stack before the definition
2232: or loop ends. You cannot access items that you pushed on the return
2233: stack outside some definition or loop within the definition of loop.
2234:
2235: If you miscount the return stack items, this usually ends in a crash:
2236:
2237: @example
2238: : crash ( n -- )
2239: >r ;
2240: 5 crash
2241: @end example
2242:
2243: You cannot mix using locals and using the return stack (according to the
2244: standard; Gforth has no problem). However, they solve the same
2245: problems, so this shouldn't be an issue.
2246:
2247: @assignment
2248: Can you rewrite any of the definitions you wrote until now in a better
2249: way using the return stack?
2250: @endassignment
2251:
1.66 anton 2252: Reference: @ref{Return stack}.
2253:
1.48 anton 2254:
2255: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2256: @section Memory
1.66 anton 2257: @cindex memory access/allocation tutorial
1.48 anton 2258:
2259: You can create a global variable @code{v} with
2260:
2261: @example
2262: variable v ( -- addr )
2263: @end example
2264:
2265: @code{v} pushes the address of a cell in memory on the stack. This cell
2266: was reserved by @code{variable}. You can use @code{!} (store) to store
2267: values into this cell and @code{@@} (fetch) to load the value from the
2268: stack into memory:
2269:
2270: @example
2271: v .
2272: 5 v ! .s
1.50 anton 2273: v @@ .
1.48 anton 2274: @end example
2275:
1.65 anton 2276: You can see a raw dump of memory with @code{dump}:
2277:
2278: @example
2279: v 1 cells .s dump
2280: @end example
2281:
2282: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2283: generally, address units (aus)) that @code{n1 cells} occupy. You can
2284: also reserve more memory:
1.48 anton 2285:
2286: @example
2287: create v2 20 cells allot
1.65 anton 2288: v2 20 cells dump
1.48 anton 2289: @end example
2290:
1.65 anton 2291: creates a word @code{v2} and reserves 20 uninitialized cells; the
2292: address pushed by @code{v2} points to the start of these 20 cells. You
2293: can use address arithmetic to access these cells:
1.48 anton 2294:
2295: @example
2296: 3 v2 5 cells + !
1.65 anton 2297: v2 20 cells dump
1.48 anton 2298: @end example
2299:
2300: You can reserve and initialize memory with @code{,}:
2301:
2302: @example
2303: create v3
2304: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2305: v3 @@ .
2306: v3 cell+ @@ .
2307: v3 2 cells + @@ .
1.65 anton 2308: v3 5 cells dump
1.48 anton 2309: @end example
2310:
2311: @assignment
2312: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2313: @code{u} cells, with the first of these cells at @code{addr}, the next
2314: one at @code{addr cell+} etc.
2315: @endassignment
2316:
2317: You can also reserve memory without creating a new word:
2318:
2319: @example
1.60 anton 2320: here 10 cells allot .
2321: here .
1.48 anton 2322: @end example
2323:
2324: @code{Here} pushes the start address of the memory area. You should
2325: store it somewhere, or you will have a hard time finding the memory area
2326: again.
2327:
2328: @code{Allot} manages dictionary memory. The dictionary memory contains
2329: the system's data structures for words etc. on Gforth and most other
2330: Forth systems. It is managed like a stack: You can free the memory that
2331: you have just @code{allot}ed with
2332:
2333: @example
2334: -10 cells allot
1.60 anton 2335: here .
1.48 anton 2336: @end example
2337:
2338: Note that you cannot do this if you have created a new word in the
2339: meantime (because then your @code{allot}ed memory is no longer on the
2340: top of the dictionary ``stack'').
2341:
2342: Alternatively, you can use @code{allocate} and @code{free} which allow
2343: freeing memory in any order:
2344:
2345: @example
2346: 10 cells allocate throw .s
2347: 20 cells allocate throw .s
2348: swap
2349: free throw
2350: free throw
2351: @end example
2352:
2353: The @code{throw}s deal with errors (e.g., out of memory).
2354:
1.65 anton 2355: And there is also a
2356: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2357: garbage collector}, which eliminates the need to @code{free} memory
2358: explicitly.
1.48 anton 2359:
1.66 anton 2360: Reference: @ref{Memory}.
2361:
1.48 anton 2362:
2363: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2364: @section Characters and Strings
1.66 anton 2365: @cindex strings tutorial
2366: @cindex characters tutorial
1.48 anton 2367:
2368: On the stack characters take up a cell, like numbers. In memory they
2369: have their own size (one 8-bit byte on most systems), and therefore
2370: require their own words for memory access:
2371:
2372: @example
2373: create v4
2374: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2375: v4 4 chars + c@@ .
1.65 anton 2376: v4 5 chars dump
1.48 anton 2377: @end example
2378:
2379: The preferred representation of strings on the stack is @code{addr
2380: u-count}, where @code{addr} is the address of the first character and
2381: @code{u-count} is the number of characters in the string.
2382:
2383: @example
2384: v4 5 type
2385: @end example
2386:
2387: You get a string constant with
2388:
2389: @example
2390: s" hello, world" .s
2391: type
2392: @end example
2393:
2394: Make sure you have a space between @code{s"} and the string; @code{s"}
2395: is a normal Forth word and must be delimited with white space (try what
2396: happens when you remove the space).
2397:
2398: However, this interpretive use of @code{s"} is quite restricted: the
2399: string exists only until the next call of @code{s"} (some Forth systems
2400: keep more than one of these strings, but usually they still have a
1.62 crook 2401: limited lifetime).
1.48 anton 2402:
2403: @example
2404: s" hello," s" world" .s
2405: type
2406: type
2407: @end example
2408:
1.62 crook 2409: You can also use @code{s"} in a definition, and the resulting
2410: strings then live forever (well, for as long as the definition):
1.48 anton 2411:
2412: @example
2413: : foo s" hello," s" world" ;
2414: foo .s
2415: type
2416: type
2417: @end example
2418:
2419: @assignment
2420: @code{Emit ( c -- )} types @code{c} as character (not a number).
2421: Implement @code{type ( addr u -- )}.
2422: @endassignment
2423:
1.66 anton 2424: Reference: @ref{Memory Blocks}.
2425:
2426:
1.84 pazsan 2427: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2428: @section Alignment
1.66 anton 2429: @cindex alignment tutorial
2430: @cindex memory alignment tutorial
1.48 anton 2431:
2432: On many processors cells have to be aligned in memory, if you want to
2433: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2434: not require alignment, access to aligned cells is faster).
1.48 anton 2435:
2436: @code{Create} aligns @code{here} (i.e., the place where the next
2437: allocation will occur, and that the @code{create}d word points to).
2438: Likewise, the memory produced by @code{allocate} starts at an aligned
2439: address. Adding a number of @code{cells} to an aligned address produces
2440: another aligned address.
2441:
2442: However, address arithmetic involving @code{char+} and @code{chars} can
2443: create an address that is not cell-aligned. @code{Aligned ( addr --
2444: a-addr )} produces the next aligned address:
2445:
2446: @example
1.50 anton 2447: v3 char+ aligned .s @@ .
2448: v3 char+ .s @@ .
1.48 anton 2449: @end example
2450:
2451: Similarly, @code{align} advances @code{here} to the next aligned
2452: address:
2453:
2454: @example
2455: create v5 97 c,
2456: here .
2457: align here .
2458: 1000 ,
2459: @end example
2460:
2461: Note that you should use aligned addresses even if your processor does
2462: not require them, if you want your program to be portable.
2463:
1.66 anton 2464: Reference: @ref{Address arithmetic}.
2465:
1.48 anton 2466:
1.84 pazsan 2467: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2468: @section Files
2469: @cindex files tutorial
2470:
2471: This section gives a short introduction into how to use files inside
2472: Forth. It's broken up into five easy steps:
2473:
2474: @enumerate 1
2475: @item Opened an ASCII text file for input
2476: @item Opened a file for output
2477: @item Read input file until string matched (or some other condition matched)
2478: @item Wrote some lines from input ( modified or not) to output
2479: @item Closed the files.
2480: @end enumerate
2481:
2482: @subsection Open file for input
2483:
2484: @example
2485: s" foo.in" r/o open-file throw Value fd-in
2486: @end example
2487:
2488: @subsection Create file for output
2489:
2490: @example
2491: s" foo.out" w/o create-file throw Value fd-out
2492: @end example
2493:
2494: The available file modes are r/o for read-only access, r/w for
2495: read-write access, and w/o for write-only access. You could open both
2496: files with r/w, too, if you like. All file words return error codes; for
2497: most applications, it's best to pass there error codes with @code{throw}
2498: to the outer error handler.
2499:
2500: If you want words for opening and assigning, define them as follows:
2501:
2502: @example
2503: 0 Value fd-in
2504: 0 Value fd-out
2505: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2506: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2507: @end example
2508:
2509: Usage example:
2510:
2511: @example
2512: s" foo.in" open-input
2513: s" foo.out" open-output
2514: @end example
2515:
2516: @subsection Scan file for a particular line
2517:
2518: @example
2519: 256 Constant max-line
2520: Create line-buffer max-line 2 + allot
2521:
2522: : scan-file ( addr u -- )
2523: begin
2524: line-buffer max-line fd-in read-line throw
2525: while
2526: >r 2dup line-buffer r> compare 0=
2527: until
2528: else
2529: drop
2530: then
2531: 2drop ;
2532: @end example
2533:
2534: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2535: the buffer at addr, and returns the number of bytes read, a flag that is
2536: false when the end of file is reached, and an error code.
1.84 pazsan 2537:
2538: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2539: returns zero if both strings are equal. It returns a positive number if
2540: the first string is lexically greater, a negative if the second string
2541: is lexically greater.
2542:
2543: We haven't seen this loop here; it has two exits. Since the @code{while}
2544: exits with the number of bytes read on the stack, we have to clean up
2545: that separately; that's after the @code{else}.
2546:
2547: Usage example:
2548:
2549: @example
2550: s" The text I search is here" scan-file
2551: @end example
2552:
2553: @subsection Copy input to output
2554:
2555: @example
2556: : copy-file ( -- )
2557: begin
2558: line-buffer max-line fd-in read-line throw
2559: while
2560: line-buffer swap fd-out write-file throw
2561: repeat ;
2562: @end example
2563:
2564: @subsection Close files
2565:
2566: @example
2567: fd-in close-file throw
2568: fd-out close-file throw
2569: @end example
2570:
2571: Likewise, you can put that into definitions, too:
2572:
2573: @example
2574: : close-input ( -- ) fd-in close-file throw ;
2575: : close-output ( -- ) fd-out close-file throw ;
2576: @end example
2577:
2578: @assignment
2579: How could you modify @code{copy-file} so that it copies until a second line is
2580: matched? Can you write a program that extracts a section of a text file,
2581: given the line that starts and the line that terminates that section?
2582: @endassignment
2583:
2584: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2585: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2586: @cindex semantics tutorial
2587: @cindex interpretation semantics tutorial
2588: @cindex compilation semantics tutorial
2589: @cindex immediate, tutorial
1.48 anton 2590:
2591: When a word is compiled, it behaves differently from being interpreted.
2592: E.g., consider @code{+}:
2593:
2594: @example
2595: 1 2 + .
2596: : foo + ;
2597: @end example
2598:
2599: These two behaviours are known as compilation and interpretation
2600: semantics. For normal words (e.g., @code{+}), the compilation semantics
2601: is to append the interpretation semantics to the currently defined word
2602: (@code{foo} in the example above). I.e., when @code{foo} is executed
2603: later, the interpretation semantics of @code{+} (i.e., adding two
2604: numbers) will be performed.
2605:
2606: However, there are words with non-default compilation semantics, e.g.,
2607: the control-flow words like @code{if}. You can use @code{immediate} to
2608: change the compilation semantics of the last defined word to be equal to
2609: the interpretation semantics:
2610:
2611: @example
2612: : [FOO] ( -- )
2613: 5 . ; immediate
2614:
2615: [FOO]
2616: : bar ( -- )
2617: [FOO] ;
2618: bar
2619: see bar
2620: @end example
2621:
2622: Two conventions to mark words with non-default compilation semnatics are
2623: names with brackets (more frequently used) and to write them all in
2624: upper case (less frequently used).
2625:
2626: In Gforth (and many other systems) you can also remove the
2627: interpretation semantics with @code{compile-only} (the compilation
2628: semantics is derived from the original interpretation semantics):
2629:
2630: @example
2631: : flip ( -- )
2632: 6 . ; compile-only \ but not immediate
2633: flip
2634:
2635: : flop ( -- )
2636: flip ;
2637: flop
2638: @end example
2639:
2640: In this example the interpretation semantics of @code{flop} is equal to
2641: the original interpretation semantics of @code{flip}.
2642:
2643: The text interpreter has two states: in interpret state, it performs the
2644: interpretation semantics of words it encounters; in compile state, it
2645: performs the compilation semantics of these words.
2646:
2647: Among other things, @code{:} switches into compile state, and @code{;}
2648: switches back to interpret state. They contain the factors @code{]}
2649: (switch to compile state) and @code{[} (switch to interpret state), that
2650: do nothing but switch the state.
2651:
2652: @example
2653: : xxx ( -- )
2654: [ 5 . ]
2655: ;
2656:
2657: xxx
2658: see xxx
2659: @end example
2660:
2661: These brackets are also the source of the naming convention mentioned
2662: above.
2663:
1.66 anton 2664: Reference: @ref{Interpretation and Compilation Semantics}.
2665:
1.48 anton 2666:
2667: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2668: @section Execution Tokens
1.66 anton 2669: @cindex execution tokens tutorial
2670: @cindex XT tutorial
1.48 anton 2671:
2672: @code{' word} gives you the execution token (XT) of a word. The XT is a
2673: cell representing the interpretation semantics of a word. You can
2674: execute this semantics with @code{execute}:
2675:
2676: @example
2677: ' + .s
2678: 1 2 rot execute .
2679: @end example
2680:
2681: The XT is similar to a function pointer in C. However, parameter
2682: passing through the stack makes it a little more flexible:
2683:
2684: @example
2685: : map-array ( ... addr u xt -- ... )
1.50 anton 2686: \ executes xt ( ... x -- ... ) for every element of the array starting
2687: \ at addr and containing u elements
1.48 anton 2688: @{ xt @}
2689: cells over + swap ?do
1.50 anton 2690: i @@ xt execute
1.48 anton 2691: 1 cells +loop ;
2692:
2693: create a 3 , 4 , 2 , -1 , 4 ,
2694: a 5 ' . map-array .s
2695: 0 a 5 ' + map-array .
2696: s" max-n" environment? drop .s
2697: a 5 ' min map-array .
2698: @end example
2699:
2700: You can use map-array with the XTs of words that consume one element
2701: more than they produce. In theory you can also use it with other XTs,
2702: but the stack effect then depends on the size of the array, which is
2703: hard to understand.
2704:
1.51 pazsan 2705: Since XTs are cell-sized, you can store them in memory and manipulate
2706: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2707: word with @code{compile,}:
2708:
2709: @example
2710: : foo1 ( n1 n2 -- n )
2711: [ ' + compile, ] ;
2712: see foo
2713: @end example
2714:
2715: This is non-standard, because @code{compile,} has no compilation
2716: semantics in the standard, but it works in good Forth systems. For the
2717: broken ones, use
2718:
2719: @example
2720: : [compile,] compile, ; immediate
2721:
2722: : foo1 ( n1 n2 -- n )
2723: [ ' + ] [compile,] ;
2724: see foo
2725: @end example
2726:
2727: @code{'} is a word with default compilation semantics; it parses the
2728: next word when its interpretation semantics are executed, not during
2729: compilation:
2730:
2731: @example
2732: : foo ( -- xt )
2733: ' ;
2734: see foo
2735: : bar ( ... "word" -- ... )
2736: ' execute ;
2737: see bar
1.60 anton 2738: 1 2 bar + .
1.48 anton 2739: @end example
2740:
2741: You often want to parse a word during compilation and compile its XT so
2742: it will be pushed on the stack at run-time. @code{[']} does this:
2743:
2744: @example
2745: : xt-+ ( -- xt )
2746: ['] + ;
2747: see xt-+
2748: 1 2 xt-+ execute .
2749: @end example
2750:
2751: Many programmers tend to see @code{'} and the word it parses as one
2752: unit, and expect it to behave like @code{[']} when compiled, and are
2753: confused by the actual behaviour. If you are, just remember that the
2754: Forth system just takes @code{'} as one unit and has no idea that it is
2755: a parsing word (attempts to convenience programmers in this issue have
2756: usually resulted in even worse pitfalls, see
1.66 anton 2757: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2758: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2759:
2760: Note that the state of the interpreter does not come into play when
1.51 pazsan 2761: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2762: compile state, it still gives you the interpretation semantics. And
2763: whatever that state is, @code{execute} performs the semantics
1.66 anton 2764: represented by the XT (i.e., for XTs produced with @code{'} the
2765: interpretation semantics).
2766:
2767: Reference: @ref{Tokens for Words}.
1.48 anton 2768:
2769:
2770: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2771: @section Exceptions
1.66 anton 2772: @cindex exceptions tutorial
1.48 anton 2773:
2774: @code{throw ( n -- )} causes an exception unless n is zero.
2775:
2776: @example
2777: 100 throw .s
2778: 0 throw .s
2779: @end example
2780:
2781: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2782: it catches exceptions and pushes the number of the exception on the
2783: stack (or 0, if the xt executed without exception). If there was an
2784: exception, the stacks have the same depth as when entering @code{catch}:
2785:
2786: @example
2787: .s
2788: 3 0 ' / catch .s
2789: 3 2 ' / catch .s
2790: @end example
2791:
2792: @assignment
2793: Try the same with @code{execute} instead of @code{catch}.
2794: @endassignment
2795:
2796: @code{Throw} always jumps to the dynamically next enclosing
2797: @code{catch}, even if it has to leave several call levels to achieve
2798: this:
2799:
2800: @example
2801: : foo 100 throw ;
2802: : foo1 foo ." after foo" ;
1.51 pazsan 2803: : bar ['] foo1 catch ;
1.60 anton 2804: bar .
1.48 anton 2805: @end example
2806:
2807: It is often important to restore a value upon leaving a definition, even
2808: if the definition is left through an exception. You can ensure this
2809: like this:
2810:
2811: @example
2812: : ...
2813: save-x
1.51 pazsan 2814: ['] word-changing-x catch ( ... n )
1.48 anton 2815: restore-x
2816: ( ... n ) throw ;
2817: @end example
2818:
1.55 anton 2819: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2820: @code{try ... recover ... endtry}. If the code between @code{try} and
2821: @code{recover} has an exception, the stack depths are restored, the
2822: exception number is pushed on the stack, and the code between
2823: @code{recover} and @code{endtry} is performed. E.g., the definition for
2824: @code{catch} is
2825:
2826: @example
2827: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2828: try
2829: execute 0
2830: recover
2831: nip
2832: endtry ;
2833: @end example
2834:
2835: The equivalent to the restoration code above is
2836:
2837: @example
2838: : ...
2839: save-x
2840: try
1.92 anton 2841: word-changing-x 0
2842: recover endtry
1.48 anton 2843: restore-x
2844: throw ;
2845: @end example
2846:
1.92 anton 2847: This works if @code{word-changing-x} does not change the stack depth,
2848: otherwise you should add some code between @code{recover} and
2849: @code{endtry} to balance the stack.
1.48 anton 2850:
1.66 anton 2851: Reference: @ref{Exception Handling}.
2852:
1.48 anton 2853:
2854: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2855: @section Defining Words
1.66 anton 2856: @cindex defining words tutorial
2857: @cindex does> tutorial
2858: @cindex create...does> tutorial
2859:
2860: @c before semantics?
1.48 anton 2861:
2862: @code{:}, @code{create}, and @code{variable} are definition words: They
2863: define other words. @code{Constant} is another definition word:
2864:
2865: @example
2866: 5 constant foo
2867: foo .
2868: @end example
2869:
2870: You can also use the prefixes @code{2} (double-cell) and @code{f}
2871: (floating point) with @code{variable} and @code{constant}.
2872:
2873: You can also define your own defining words. E.g.:
2874:
2875: @example
2876: : variable ( "name" -- )
2877: create 0 , ;
2878: @end example
2879:
2880: You can also define defining words that create words that do something
2881: other than just producing their address:
2882:
2883: @example
2884: : constant ( n "name" -- )
2885: create ,
2886: does> ( -- n )
1.50 anton 2887: ( addr ) @@ ;
1.48 anton 2888:
2889: 5 constant foo
2890: foo .
2891: @end example
2892:
2893: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2894: @code{does>} replaces @code{;}, but it also does something else: It
2895: changes the last defined word such that it pushes the address of the
2896: body of the word and then performs the code after the @code{does>}
2897: whenever it is called.
2898:
2899: In the example above, @code{constant} uses @code{,} to store 5 into the
2900: body of @code{foo}. When @code{foo} executes, it pushes the address of
2901: the body onto the stack, then (in the code after the @code{does>})
2902: fetches the 5 from there.
2903:
2904: The stack comment near the @code{does>} reflects the stack effect of the
2905: defined word, not the stack effect of the code after the @code{does>}
2906: (the difference is that the code expects the address of the body that
2907: the stack comment does not show).
2908:
2909: You can use these definition words to do factoring in cases that involve
2910: (other) definition words. E.g., a field offset is always added to an
2911: address. Instead of defining
2912:
2913: @example
2914: 2 cells constant offset-field1
2915: @end example
2916:
2917: and using this like
2918:
2919: @example
2920: ( addr ) offset-field1 +
2921: @end example
2922:
2923: you can define a definition word
2924:
2925: @example
2926: : simple-field ( n "name" -- )
2927: create ,
2928: does> ( n1 -- n1+n )
1.50 anton 2929: ( addr ) @@ + ;
1.48 anton 2930: @end example
1.21 crook 2931:
1.48 anton 2932: Definition and use of field offsets now look like this:
1.21 crook 2933:
1.48 anton 2934: @example
2935: 2 cells simple-field field1
1.60 anton 2936: create mystruct 4 cells allot
2937: mystruct .s field1 .s drop
1.48 anton 2938: @end example
1.21 crook 2939:
1.48 anton 2940: If you want to do something with the word without performing the code
2941: after the @code{does>}, you can access the body of a @code{create}d word
2942: with @code{>body ( xt -- addr )}:
1.21 crook 2943:
1.48 anton 2944: @example
2945: : value ( n "name" -- )
2946: create ,
2947: does> ( -- n1 )
1.50 anton 2948: @@ ;
1.48 anton 2949: : to ( n "name" -- )
2950: ' >body ! ;
1.21 crook 2951:
1.48 anton 2952: 5 value foo
2953: foo .
2954: 7 to foo
2955: foo .
2956: @end example
1.21 crook 2957:
1.48 anton 2958: @assignment
2959: Define @code{defer ( "name" -- )}, which creates a word that stores an
2960: XT (at the start the XT of @code{abort}), and upon execution
2961: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2962: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2963: recursion is one application of @code{defer}.
2964: @endassignment
1.29 crook 2965:
1.66 anton 2966: Reference: @ref{User-defined Defining Words}.
2967:
2968:
1.48 anton 2969: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2970: @section Arrays and Records
1.66 anton 2971: @cindex arrays tutorial
2972: @cindex records tutorial
2973: @cindex structs tutorial
1.29 crook 2974:
1.48 anton 2975: Forth has no standard words for defining data structures such as arrays
2976: and records (structs in C terminology), but you can build them yourself
2977: based on address arithmetic. You can also define words for defining
2978: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2979:
1.48 anton 2980: One of the first projects a Forth newcomer sets out upon when learning
2981: about defining words is an array defining word (possibly for
2982: n-dimensional arrays). Go ahead and do it, I did it, too; you will
2983: learn something from it. However, don't be disappointed when you later
2984: learn that you have little use for these words (inappropriate use would
2985: be even worse). I have not yet found a set of useful array words yet;
2986: the needs are just too diverse, and named, global arrays (the result of
2987: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 2988: consider how to pass them as parameters). Another such project is a set
2989: of words to help dealing with strings.
1.29 crook 2990:
1.48 anton 2991: On the other hand, there is a useful set of record words, and it has
2992: been defined in @file{compat/struct.fs}; these words are predefined in
2993: Gforth. They are explained in depth elsewhere in this manual (see
2994: @pxref{Structures}). The @code{simple-field} example above is
2995: simplified variant of fields in this package.
1.21 crook 2996:
2997:
1.48 anton 2998: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
2999: @section @code{POSTPONE}
1.66 anton 3000: @cindex postpone tutorial
1.21 crook 3001:
1.48 anton 3002: You can compile the compilation semantics (instead of compiling the
3003: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3004:
1.48 anton 3005: @example
3006: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3007: POSTPONE + ; immediate
1.48 anton 3008: : foo ( n1 n2 -- n )
3009: MY-+ ;
3010: 1 2 foo .
3011: see foo
3012: @end example
1.21 crook 3013:
1.48 anton 3014: During the definition of @code{foo} the text interpreter performs the
3015: compilation semantics of @code{MY-+}, which performs the compilation
3016: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3017:
3018: This example also displays separate stack comments for the compilation
3019: semantics and for the stack effect of the compiled code. For words with
3020: default compilation semantics these stack effects are usually not
3021: displayed; the stack effect of the compilation semantics is always
3022: @code{( -- )} for these words, the stack effect for the compiled code is
3023: the stack effect of the interpretation semantics.
3024:
3025: Note that the state of the interpreter does not come into play when
3026: performing the compilation semantics in this way. You can also perform
3027: it interpretively, e.g.:
3028:
3029: @example
3030: : foo2 ( n1 n2 -- n )
3031: [ MY-+ ] ;
3032: 1 2 foo .
3033: see foo
3034: @end example
1.21 crook 3035:
1.48 anton 3036: However, there are some broken Forth systems where this does not always
1.62 crook 3037: work, and therefore this practice was been declared non-standard in
1.48 anton 3038: 1999.
3039: @c !! repair.fs
3040:
3041: Here is another example for using @code{POSTPONE}:
1.44 crook 3042:
1.48 anton 3043: @example
3044: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3045: POSTPONE negate POSTPONE + ; immediate compile-only
3046: : bar ( n1 n2 -- n )
3047: MY-- ;
3048: 2 1 bar .
3049: see bar
3050: @end example
1.21 crook 3051:
1.48 anton 3052: You can define @code{ENDIF} in this way:
1.21 crook 3053:
1.48 anton 3054: @example
3055: : ENDIF ( Compilation: orig -- )
3056: POSTPONE then ; immediate
3057: @end example
1.21 crook 3058:
1.48 anton 3059: @assignment
3060: Write @code{MY-2DUP} that has compilation semantics equivalent to
3061: @code{2dup}, but compiles @code{over over}.
3062: @endassignment
1.29 crook 3063:
1.66 anton 3064: @c !! @xref{Macros} for reference
3065:
3066:
1.48 anton 3067: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3068: @section @code{Literal}
1.66 anton 3069: @cindex literal tutorial
1.29 crook 3070:
1.48 anton 3071: You cannot @code{POSTPONE} numbers:
1.21 crook 3072:
1.48 anton 3073: @example
3074: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3075: @end example
3076:
1.48 anton 3077: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3078:
1.48 anton 3079: @example
3080: : [FOO] ( compilation: --; run-time: -- n )
3081: 500 POSTPONE literal ; immediate
1.29 crook 3082:
1.60 anton 3083: : flip [FOO] ;
1.48 anton 3084: flip .
3085: see flip
3086: @end example
1.29 crook 3087:
1.48 anton 3088: @code{LITERAL} consumes a number at compile-time (when it's compilation
3089: semantics are executed) and pushes it at run-time (when the code it
3090: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3091: number computed at compile time into the current word:
1.29 crook 3092:
1.48 anton 3093: @example
3094: : bar ( -- n )
3095: [ 2 2 + ] literal ;
3096: see bar
3097: @end example
1.29 crook 3098:
1.48 anton 3099: @assignment
3100: Write @code{]L} which allows writing the example above as @code{: bar (
3101: -- n ) [ 2 2 + ]L ;}
3102: @endassignment
3103:
1.66 anton 3104: @c !! @xref{Macros} for reference
3105:
1.48 anton 3106:
3107: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3108: @section Advanced macros
1.66 anton 3109: @cindex macros, advanced tutorial
3110: @cindex run-time code generation, tutorial
1.48 anton 3111:
1.66 anton 3112: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3113: Execution Tokens}. It frequently performs @code{execute}, a relatively
3114: expensive operation in some Forth implementations. You can use
1.48 anton 3115: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3116: and produce a word that contains the word to be performed directly:
3117:
3118: @c use ]] ... [[
3119: @example
3120: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3121: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3122: \ array beginning at addr and containing u elements
3123: @{ xt @}
3124: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3125: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3126: 1 cells POSTPONE literal POSTPONE +loop ;
3127:
3128: : sum-array ( addr u -- n )
3129: 0 rot rot [ ' + compile-map-array ] ;
3130: see sum-array
3131: a 5 sum-array .
3132: @end example
3133:
3134: You can use the full power of Forth for generating the code; here's an
3135: example where the code is generated in a loop:
3136:
3137: @example
3138: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3139: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3140: POSTPONE tuck POSTPONE @@
1.48 anton 3141: POSTPONE literal POSTPONE * POSTPONE +
3142: POSTPONE swap POSTPONE cell+ ;
3143:
3144: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3145: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3146: 0 postpone literal postpone swap
3147: [ ' compile-vmul-step compile-map-array ]
3148: postpone drop ;
3149: see compile-vmul
3150:
3151: : a-vmul ( addr -- n )
1.51 pazsan 3152: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3153: [ a 5 compile-vmul ] ;
3154: see a-vmul
3155: a a-vmul .
3156: @end example
3157:
3158: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3159: also use @code{map-array} instead (try it now!).
1.48 anton 3160:
3161: You can use this technique for efficient multiplication of large
3162: matrices. In matrix multiplication, you multiply every line of one
3163: matrix with every column of the other matrix. You can generate the code
3164: for one line once, and use it for every column. The only downside of
3165: this technique is that it is cumbersome to recover the memory consumed
3166: by the generated code when you are done (and in more complicated cases
3167: it is not possible portably).
3168:
1.66 anton 3169: @c !! @xref{Macros} for reference
3170:
3171:
1.48 anton 3172: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3173: @section Compilation Tokens
1.66 anton 3174: @cindex compilation tokens, tutorial
3175: @cindex CT, tutorial
1.48 anton 3176:
3177: This section is Gforth-specific. You can skip it.
3178:
3179: @code{' word compile,} compiles the interpretation semantics. For words
3180: with default compilation semantics this is the same as performing the
3181: compilation semantics. To represent the compilation semantics of other
3182: words (e.g., words like @code{if} that have no interpretation
3183: semantics), Gforth has the concept of a compilation token (CT,
3184: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3185: You can perform the compilation semantics represented by a CT with
3186: @code{execute}:
1.29 crook 3187:
1.48 anton 3188: @example
3189: : foo2 ( n1 n2 -- n )
3190: [ comp' + execute ] ;
3191: see foo
3192: @end example
1.29 crook 3193:
1.48 anton 3194: You can compile the compilation semantics represented by a CT with
3195: @code{postpone,}:
1.30 anton 3196:
1.48 anton 3197: @example
3198: : foo3 ( -- )
3199: [ comp' + postpone, ] ;
3200: see foo3
3201: @end example
1.30 anton 3202:
1.51 pazsan 3203: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3204: @code{comp'} is particularly useful for words that have no
3205: interpretation semantics:
1.29 crook 3206:
1.30 anton 3207: @example
1.48 anton 3208: ' if
1.60 anton 3209: comp' if .s 2drop
1.30 anton 3210: @end example
3211:
1.66 anton 3212: Reference: @ref{Tokens for Words}.
3213:
1.29 crook 3214:
1.48 anton 3215: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3216: @section Wordlists and Search Order
1.66 anton 3217: @cindex wordlists tutorial
3218: @cindex search order, tutorial
1.48 anton 3219:
3220: The dictionary is not just a memory area that allows you to allocate
3221: memory with @code{allot}, it also contains the Forth words, arranged in
3222: several wordlists. When searching for a word in a wordlist,
3223: conceptually you start searching at the youngest and proceed towards
3224: older words (in reality most systems nowadays use hash-tables); i.e., if
3225: you define a word with the same name as an older word, the new word
3226: shadows the older word.
3227:
3228: Which wordlists are searched in which order is determined by the search
3229: order. You can display the search order with @code{order}. It displays
3230: first the search order, starting with the wordlist searched first, then
3231: it displays the wordlist that will contain newly defined words.
1.21 crook 3232:
1.48 anton 3233: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3234:
1.48 anton 3235: @example
3236: wordlist constant mywords
3237: @end example
1.21 crook 3238:
1.48 anton 3239: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3240: defined words (the @emph{current} wordlist):
1.21 crook 3241:
1.48 anton 3242: @example
3243: mywords set-current
3244: order
3245: @end example
1.26 crook 3246:
1.48 anton 3247: Gforth does not display a name for the wordlist in @code{mywords}
3248: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3249:
1.48 anton 3250: You can get the current wordlist with @code{get-current ( -- wid)}. If
3251: you want to put something into a specific wordlist without overall
3252: effect on the current wordlist, this typically looks like this:
1.21 crook 3253:
1.48 anton 3254: @example
3255: get-current mywords set-current ( wid )
3256: create someword
3257: ( wid ) set-current
3258: @end example
1.21 crook 3259:
1.48 anton 3260: You can write the search order with @code{set-order ( wid1 .. widn n --
3261: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3262: searched wordlist is topmost.
1.21 crook 3263:
1.48 anton 3264: @example
3265: get-order mywords swap 1+ set-order
3266: order
3267: @end example
1.21 crook 3268:
1.48 anton 3269: Yes, the order of wordlists in the output of @code{order} is reversed
3270: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3271:
1.48 anton 3272: @assignment
3273: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3274: wordlist to the search order. Define @code{previous ( -- )}, which
3275: removes the first searched wordlist from the search order. Experiment
3276: with boundary conditions (you will see some crashes or situations that
3277: are hard or impossible to leave).
3278: @endassignment
1.21 crook 3279:
1.48 anton 3280: The search order is a powerful foundation for providing features similar
3281: to Modula-2 modules and C++ namespaces. However, trying to modularize
3282: programs in this way has disadvantages for debugging and reuse/factoring
3283: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3284: though). These disadvantages are not so clear in other
1.82 anton 3285: languages/programming environments, because these languages are not so
1.48 anton 3286: strong in debugging and reuse.
1.21 crook 3287:
1.66 anton 3288: @c !! example
3289:
3290: Reference: @ref{Word Lists}.
1.21 crook 3291:
1.29 crook 3292: @c ******************************************************************
1.48 anton 3293: @node Introduction, Words, Tutorial, Top
1.29 crook 3294: @comment node-name, next, previous, up
3295: @chapter An Introduction to ANS Forth
3296: @cindex Forth - an introduction
1.21 crook 3297:
1.83 anton 3298: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3299: that it is slower-paced in its examples, but uses them to dive deep into
3300: explaining Forth internals (not covered by the Tutorial). Apart from
3301: that, this chapter covers far less material. It is suitable for reading
3302: without using a computer.
3303:
1.29 crook 3304: The primary purpose of this manual is to document Gforth. However, since
3305: Forth is not a widely-known language and there is a lack of up-to-date
3306: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3307: material. For other sources of Forth-related
3308: information, see @ref{Forth-related information}.
1.21 crook 3309:
1.29 crook 3310: The examples in this section should work on any ANS Forth; the
3311: output shown was produced using Gforth. Each example attempts to
3312: reproduce the exact output that Gforth produces. If you try out the
3313: examples (and you should), what you should type is shown @kbd{like this}
3314: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3315: that, where the example shows @key{RET} it means that you should
1.29 crook 3316: press the ``carriage return'' key. Unfortunately, some output formats for
3317: this manual cannot show the difference between @kbd{this} and
3318: @code{this} which will make trying out the examples harder (but not
3319: impossible).
1.21 crook 3320:
1.29 crook 3321: Forth is an unusual language. It provides an interactive development
3322: environment which includes both an interpreter and compiler. Forth
3323: programming style encourages you to break a problem down into many
3324: @cindex factoring
3325: small fragments (@dfn{factoring}), and then to develop and test each
3326: fragment interactively. Forth advocates assert that breaking the
3327: edit-compile-test cycle used by conventional programming languages can
3328: lead to great productivity improvements.
1.21 crook 3329:
1.29 crook 3330: @menu
1.67 anton 3331: * Introducing the Text Interpreter::
3332: * Stacks and Postfix notation::
3333: * Your first definition::
3334: * How does that work?::
3335: * Forth is written in Forth::
3336: * Review - elements of a Forth system::
3337: * Where to go next::
3338: * Exercises::
1.29 crook 3339: @end menu
1.21 crook 3340:
1.29 crook 3341: @comment ----------------------------------------------
3342: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3343: @section Introducing the Text Interpreter
3344: @cindex text interpreter
3345: @cindex outer interpreter
1.21 crook 3346:
1.30 anton 3347: @c IMO this is too detailed and the pace is too slow for
3348: @c an introduction. If you know German, take a look at
3349: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3350: @c to see how I do it - anton
3351:
1.44 crook 3352: @c nac-> Where I have accepted your comments 100% and modified the text
3353: @c accordingly, I have deleted your comments. Elsewhere I have added a
3354: @c response like this to attempt to rationalise what I have done. Of
3355: @c course, this is a very clumsy mechanism for something that would be
3356: @c done far more efficiently over a beer. Please delete any dialogue
3357: @c you consider closed.
3358:
1.29 crook 3359: When you invoke the Forth image, you will see a startup banner printed
3360: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3361: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3362: its command line interpreter, which is called the @dfn{Text Interpreter}
3363: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3364: about the text interpreter as you read through this chapter, for more
3365: detail @pxref{The Text Interpreter}).
1.21 crook 3366:
1.29 crook 3367: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3368: input. Type a number and press the @key{RET} key:
1.21 crook 3369:
1.26 crook 3370: @example
1.30 anton 3371: @kbd{45@key{RET}} ok
1.26 crook 3372: @end example
1.21 crook 3373:
1.29 crook 3374: Rather than give you a prompt to invite you to input something, the text
3375: interpreter prints a status message @i{after} it has processed a line
3376: of input. The status message in this case (``@code{ ok}'' followed by
3377: carriage-return) indicates that the text interpreter was able to process
3378: all of your input successfully. Now type something illegal:
3379:
3380: @example
1.30 anton 3381: @kbd{qwer341@key{RET}}
1.29 crook 3382: :1: Undefined word
3383: qwer341
3384: ^^^^^^^
3385: $400D2BA8 Bounce
3386: $400DBDA8 no.extensions
3387: @end example
1.23 crook 3388:
1.29 crook 3389: The exact text, other than the ``Undefined word'' may differ slightly on
3390: your system, but the effect is the same; when the text interpreter
3391: detects an error, it discards any remaining text on a line, resets
1.49 anton 3392: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3393: messages}.
1.23 crook 3394:
1.29 crook 3395: The text interpreter waits for you to press carriage-return, and then
3396: processes your input line. Starting at the beginning of the line, it
3397: breaks the line into groups of characters separated by spaces. For each
3398: group of characters in turn, it makes two attempts to do something:
1.23 crook 3399:
1.29 crook 3400: @itemize @bullet
3401: @item
1.44 crook 3402: @cindex name dictionary
1.29 crook 3403: It tries to treat it as a command. It does this by searching a @dfn{name
3404: dictionary}. If the group of characters matches an entry in the name
3405: dictionary, the name dictionary provides the text interpreter with
3406: information that allows the text interpreter perform some actions. In
3407: Forth jargon, we say that the group
3408: @cindex word
3409: @cindex definition
3410: @cindex execution token
3411: @cindex xt
3412: of characters names a @dfn{word}, that the dictionary search returns an
3413: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3414: word, and that the text interpreter executes the xt. Often, the terms
3415: @dfn{word} and @dfn{definition} are used interchangeably.
3416: @item
3417: If the text interpreter fails to find a match in the name dictionary, it
3418: tries to treat the group of characters as a number in the current number
3419: base (when you start up Forth, the current number base is base 10). If
3420: the group of characters legitimately represents a number, the text
3421: interpreter pushes the number onto a stack (we'll learn more about that
3422: in the next section).
3423: @end itemize
1.23 crook 3424:
1.29 crook 3425: If the text interpreter is unable to do either of these things with any
3426: group of characters, it discards the group of characters and the rest of
3427: the line, then prints an error message. If the text interpreter reaches
3428: the end of the line without error, it prints the status message ``@code{ ok}''
3429: followed by carriage-return.
1.21 crook 3430:
1.29 crook 3431: This is the simplest command we can give to the text interpreter:
1.23 crook 3432:
3433: @example
1.30 anton 3434: @key{RET} ok
1.23 crook 3435: @end example
1.21 crook 3436:
1.29 crook 3437: The text interpreter did everything we asked it to do (nothing) without
3438: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3439: command:
1.21 crook 3440:
1.23 crook 3441: @example
1.30 anton 3442: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3443: :1: Undefined word
3444: 12 dup fred dup
3445: ^^^^
3446: $400D2BA8 Bounce
3447: $400DBDA8 no.extensions
1.23 crook 3448: @end example
1.21 crook 3449:
1.29 crook 3450: When you press the carriage-return key, the text interpreter starts to
3451: work its way along the line:
1.21 crook 3452:
1.29 crook 3453: @itemize @bullet
3454: @item
3455: When it gets to the space after the @code{2}, it takes the group of
3456: characters @code{12} and looks them up in the name
3457: dictionary@footnote{We can't tell if it found them or not, but assume
3458: for now that it did not}. There is no match for this group of characters
3459: in the name dictionary, so it tries to treat them as a number. It is
3460: able to do this successfully, so it puts the number, 12, ``on the stack''
3461: (whatever that means).
3462: @item
3463: The text interpreter resumes scanning the line and gets the next group
3464: of characters, @code{dup}. It looks it up in the name dictionary and
3465: (you'll have to take my word for this) finds it, and executes the word
3466: @code{dup} (whatever that means).
3467: @item
3468: Once again, the text interpreter resumes scanning the line and gets the
3469: group of characters @code{fred}. It looks them up in the name
3470: dictionary, but can't find them. It tries to treat them as a number, but
3471: they don't represent any legal number.
3472: @end itemize
1.21 crook 3473:
1.29 crook 3474: At this point, the text interpreter gives up and prints an error
3475: message. The error message shows exactly how far the text interpreter
3476: got in processing the line. In particular, it shows that the text
3477: interpreter made no attempt to do anything with the final character
3478: group, @code{dup}, even though we have good reason to believe that the
3479: text interpreter would have no problem looking that word up and
3480: executing it a second time.
1.21 crook 3481:
3482:
1.29 crook 3483: @comment ----------------------------------------------
3484: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3485: @section Stacks, postfix notation and parameter passing
3486: @cindex text interpreter
3487: @cindex outer interpreter
1.21 crook 3488:
1.29 crook 3489: In procedural programming languages (like C and Pascal), the
3490: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3491: functions or procedures are called with @dfn{explicit parameters}. For
3492: example, in C we might write:
1.21 crook 3493:
1.23 crook 3494: @example
1.29 crook 3495: total = total + new_volume(length,height,depth);
1.23 crook 3496: @end example
1.21 crook 3497:
1.23 crook 3498: @noindent
1.29 crook 3499: where new_volume is a function-call to another piece of code, and total,
3500: length, height and depth are all variables. length, height and depth are
3501: parameters to the function-call.
1.21 crook 3502:
1.29 crook 3503: In Forth, the equivalent of the function or procedure is the
3504: @dfn{definition} and parameters are implicitly passed between
3505: definitions using a shared stack that is visible to the
3506: programmer. Although Forth does support variables, the existence of the
3507: stack means that they are used far less often than in most other
3508: programming languages. When the text interpreter encounters a number, it
3509: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3510: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3511: used for any operation is implied unambiguously by the operation being
3512: performed. The stack used for all integer operations is called the @dfn{data
3513: stack} and, since this is the stack used most commonly, references to
3514: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3515:
1.29 crook 3516: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3517:
1.23 crook 3518: @example
1.30 anton 3519: @kbd{1 2 3@key{RET}} ok
1.23 crook 3520: @end example
1.21 crook 3521:
1.29 crook 3522: Then this instructs the text interpreter to placed three numbers on the
3523: (data) stack. An analogy for the behaviour of the stack is to take a
3524: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3525: the table. The 3 was the last card onto the pile (``last-in'') and if
3526: you take a card off the pile then, unless you're prepared to fiddle a
3527: bit, the card that you take off will be the 3 (``first-out''). The
3528: number that will be first-out of the stack is called the @dfn{top of
3529: stack}, which
3530: @cindex TOS definition
3531: is often abbreviated to @dfn{TOS}.
1.21 crook 3532:
1.29 crook 3533: To understand how parameters are passed in Forth, consider the
3534: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3535: be surprised to learn that this definition performs addition. More
3536: precisely, it adds two number together and produces a result. Where does
3537: it get the two numbers from? It takes the top two numbers off the
3538: stack. Where does it place the result? On the stack. You can act-out the
3539: behaviour of @code{+} with your playing cards like this:
1.21 crook 3540:
3541: @itemize @bullet
3542: @item
1.29 crook 3543: Pick up two cards from the stack on the table
1.21 crook 3544: @item
1.29 crook 3545: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3546: numbers''
1.21 crook 3547: @item
1.29 crook 3548: Decide that the answer is 5
1.21 crook 3549: @item
1.29 crook 3550: Shuffle the two cards back into the pack and find a 5
1.21 crook 3551: @item
1.29 crook 3552: Put a 5 on the remaining ace that's on the table.
1.21 crook 3553: @end itemize
3554:
1.29 crook 3555: If you don't have a pack of cards handy but you do have Forth running,
3556: you can use the definition @code{.s} to show the current state of the stack,
3557: without affecting the stack. Type:
1.21 crook 3558:
3559: @example
1.124 anton 3560: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3561: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3562: @end example
3563:
1.124 anton 3564: The text interpreter looks up the word @code{clearstacks} and executes
3565: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3566: left on it by earlier examples. The text interpreter pushes each of the
3567: three numbers in turn onto the stack. Finally, the text interpreter
3568: looks up the word @code{.s} and executes it. The effect of executing
3569: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3570: followed by a list of all the items on the stack; the item on the far
3571: right-hand side is the TOS.
1.21 crook 3572:
1.29 crook 3573: You can now type:
1.21 crook 3574:
1.29 crook 3575: @example
1.30 anton 3576: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3577: @end example
1.21 crook 3578:
1.29 crook 3579: @noindent
3580: which is correct; there are now 2 items on the stack and the result of
3581: the addition is 5.
1.23 crook 3582:
1.29 crook 3583: If you're playing with cards, try doing a second addition: pick up the
3584: two cards, work out that their sum is 6, shuffle them into the pack,
3585: look for a 6 and place that on the table. You now have just one item on
3586: the stack. What happens if you try to do a third addition? Pick up the
3587: first card, pick up the second card -- ah! There is no second card. This
3588: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3589: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3590: Underflow or an Invalid Memory Address error).
1.23 crook 3591:
1.29 crook 3592: The opposite situation to a stack underflow is a @dfn{stack overflow},
3593: which simply accepts that there is a finite amount of storage space
3594: reserved for the stack. To stretch the playing card analogy, if you had
3595: enough packs of cards and you piled the cards up on the table, you would
3596: eventually be unable to add another card; you'd hit the ceiling. Gforth
3597: allows you to set the maximum size of the stacks. In general, the only
3598: time that you will get a stack overflow is because a definition has a
3599: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3600:
1.29 crook 3601: There's one final use for the playing card analogy. If you model your
3602: stack using a pack of playing cards, the maximum number of items on
3603: your stack will be 52 (I assume you didn't use the Joker). The maximum
3604: @i{value} of any item on the stack is 13 (the King). In fact, the only
3605: possible numbers are positive integer numbers 1 through 13; you can't
3606: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3607: think about some of the cards, you can accommodate different
3608: numbers. For example, you could think of the Jack as representing 0,
3609: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3610: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3611: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3612:
1.29 crook 3613: In that analogy, the limit was the amount of information that a single
3614: stack entry could hold, and Forth has a similar limit. In Forth, the
3615: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3616: implementation dependent and affects the maximum value that a stack
3617: entry can hold. A Standard Forth provides a cell size of at least
3618: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3619:
1.29 crook 3620: Forth does not do any type checking for you, so you are free to
3621: manipulate and combine stack items in any way you wish. A convenient way
3622: of treating stack items is as 2's complement signed integers, and that
3623: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3624:
1.29 crook 3625: @example
1.30 anton 3626: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3627: @end example
1.21 crook 3628:
1.29 crook 3629: If you use numbers and definitions like @code{+} in order to turn Forth
3630: into a great big pocket calculator, you will realise that it's rather
3631: different from a normal calculator. Rather than typing 2 + 3 = you had
3632: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3633: result). The terminology used to describe this difference is to say that
3634: your calculator uses @dfn{Infix Notation} (parameters and operators are
3635: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3636: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3637:
1.29 crook 3638: Whilst postfix notation might look confusing to begin with, it has
3639: several important advantages:
1.21 crook 3640:
1.23 crook 3641: @itemize @bullet
3642: @item
1.29 crook 3643: it is unambiguous
1.23 crook 3644: @item
1.29 crook 3645: it is more concise
1.23 crook 3646: @item
1.29 crook 3647: it fits naturally with a stack-based system
1.23 crook 3648: @end itemize
1.21 crook 3649:
1.29 crook 3650: To examine these claims in more detail, consider these sums:
1.21 crook 3651:
1.29 crook 3652: @example
3653: 6 + 5 * 4 =
3654: 4 * 5 + 6 =
3655: @end example
1.21 crook 3656:
1.29 crook 3657: If you're just learning maths or your maths is very rusty, you will
3658: probably come up with the answer 44 for the first and 26 for the
3659: second. If you are a bit of a whizz at maths you will remember the
3660: @i{convention} that multiplication takes precendence over addition, and
3661: you'd come up with the answer 26 both times. To explain the answer 26
3662: to someone who got the answer 44, you'd probably rewrite the first sum
3663: like this:
1.21 crook 3664:
1.29 crook 3665: @example
3666: 6 + (5 * 4) =
3667: @end example
1.21 crook 3668:
1.29 crook 3669: If what you really wanted was to perform the addition before the
3670: multiplication, you would have to use parentheses to force it.
1.21 crook 3671:
1.29 crook 3672: If you did the first two sums on a pocket calculator you would probably
3673: get the right answers, unless you were very cautious and entered them using
3674: these keystroke sequences:
1.21 crook 3675:
1.29 crook 3676: 6 + 5 = * 4 =
3677: 4 * 5 = + 6 =
1.21 crook 3678:
1.29 crook 3679: Postfix notation is unambiguous because the order that the operators
3680: are applied is always explicit; that also means that parentheses are
3681: never required. The operators are @i{active} (the act of quoting the
3682: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3683:
1.29 crook 3684: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3685: equivalent ways:
1.26 crook 3686:
3687: @example
1.29 crook 3688: 6 5 4 * + or:
3689: 5 4 * 6 +
1.26 crook 3690: @end example
1.23 crook 3691:
1.29 crook 3692: An important thing that you should notice about this notation is that
3693: the @i{order} of the numbers does not change; if you want to subtract
3694: 2 from 10 you type @code{10 2 -}.
1.1 anton 3695:
1.29 crook 3696: The reason that Forth uses postfix notation is very simple to explain: it
3697: makes the implementation extremely simple, and it follows naturally from
3698: using the stack as a mechanism for passing parameters. Another way of
3699: thinking about this is to realise that all Forth definitions are
3700: @i{active}; they execute as they are encountered by the text
3701: interpreter. The result of this is that the syntax of Forth is trivially
3702: simple.
1.1 anton 3703:
3704:
3705:
1.29 crook 3706: @comment ----------------------------------------------
3707: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3708: @section Your first Forth definition
3709: @cindex first definition
1.1 anton 3710:
1.29 crook 3711: Until now, the examples we've seen have been trivial; we've just been
3712: using Forth as a bigger-than-pocket calculator. Also, each calculation
3713: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3714: again@footnote{That's not quite true. If you press the up-arrow key on
3715: your keyboard you should be able to scroll back to any earlier command,
3716: edit it and re-enter it.} In this section we'll see how to add new
3717: words to Forth's vocabulary.
1.1 anton 3718:
1.29 crook 3719: The easiest way to create a new word is to use a @dfn{colon
3720: definition}. We'll define a few and try them out before worrying too
3721: much about how they work. Try typing in these examples; be careful to
3722: copy the spaces accurately:
1.1 anton 3723:
1.29 crook 3724: @example
3725: : add-two 2 + . ;
3726: : greet ." Hello and welcome" ;
3727: : demo 5 add-two ;
3728: @end example
1.1 anton 3729:
1.29 crook 3730: @noindent
3731: Now try them out:
1.1 anton 3732:
1.29 crook 3733: @example
1.30 anton 3734: @kbd{greet@key{RET}} Hello and welcome ok
3735: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3736: @kbd{4 add-two@key{RET}} 6 ok
3737: @kbd{demo@key{RET}} 7 ok
3738: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3739: @end example
1.1 anton 3740:
1.29 crook 3741: The first new thing that we've introduced here is the pair of words
3742: @code{:} and @code{;}. These are used to start and terminate a new
3743: definition, respectively. The first word after the @code{:} is the name
3744: for the new definition.
1.1 anton 3745:
1.29 crook 3746: As you can see from the examples, a definition is built up of words that
3747: have already been defined; Forth makes no distinction between
3748: definitions that existed when you started the system up, and those that
3749: you define yourself.
1.1 anton 3750:
1.29 crook 3751: The examples also introduce the words @code{.} (dot), @code{."}
3752: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3753: the stack and displays it. It's like @code{.s} except that it only
3754: displays the top item of the stack and it is destructive; after it has
3755: executed, the number is no longer on the stack. There is always one
3756: space printed after the number, and no spaces before it. Dot-quote
3757: defines a string (a sequence of characters) that will be printed when
3758: the word is executed. The string can contain any printable characters
3759: except @code{"}. A @code{"} has a special function; it is not a Forth
3760: word but it acts as a delimiter (the way that delimiters work is
3761: described in the next section). Finally, @code{dup} duplicates the value
3762: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3763:
1.29 crook 3764: We already know that the text interpreter searches through the
3765: dictionary to locate names. If you've followed the examples earlier, you
3766: will already have a definition called @code{add-two}. Lets try modifying
3767: it by typing in a new definition:
1.1 anton 3768:
1.29 crook 3769: @example
1.30 anton 3770: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3771: @end example
1.5 anton 3772:
1.29 crook 3773: Forth recognised that we were defining a word that already exists, and
3774: printed a message to warn us of that fact. Let's try out the new
3775: definition:
1.5 anton 3776:
1.29 crook 3777: @example
1.30 anton 3778: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3779: @end example
1.1 anton 3780:
1.29 crook 3781: @noindent
3782: All that we've actually done here, though, is to create a new
3783: definition, with a particular name. The fact that there was already a
3784: definition with the same name did not make any difference to the way
3785: that the new definition was created (except that Forth printed a warning
3786: message). The old definition of add-two still exists (try @code{demo}
3787: again to see that this is true). Any new definition will use the new
3788: definition of @code{add-two}, but old definitions continue to use the
3789: version that already existed at the time that they were @code{compiled}.
1.1 anton 3790:
1.29 crook 3791: Before you go on to the next section, try defining and redefining some
3792: words of your own.
1.1 anton 3793:
1.29 crook 3794: @comment ----------------------------------------------
3795: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3796: @section How does that work?
3797: @cindex parsing words
1.1 anton 3798:
1.30 anton 3799: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3800:
3801: @c Is it a good idea to talk about the interpretation semantics of a
3802: @c number? We don't have an xt to go along with it. - anton
3803:
3804: @c Now that I have eliminated execution semantics, I wonder if it would not
3805: @c be better to keep them (or add run-time semantics), to make it easier to
3806: @c explain what compilation semantics usually does. - anton
3807:
1.44 crook 3808: @c nac-> I removed the term ``default compilation sematics'' from the
3809: @c introductory chapter. Removing ``execution semantics'' was making
3810: @c everything simpler to explain, then I think the use of this term made
3811: @c everything more complex again. I replaced it with ``default
3812: @c semantics'' (which is used elsewhere in the manual) by which I mean
3813: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3814: @c flag set''.
3815:
3816: @c anton: I have eliminated default semantics (except in one place where it
3817: @c means "default interpretation and compilation semantics"), because it
3818: @c makes no sense in the presence of combined words. I reverted to
3819: @c "execution semantics" where necessary.
3820:
3821: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3822: @c section (and, unusually for me, I think I even made it shorter!). See
3823: @c what you think -- I know I have not addressed your primary concern
3824: @c that it is too heavy-going for an introduction. From what I understood
3825: @c of your course notes it looks as though they might be a good framework.
3826: @c Things that I've tried to capture here are some things that came as a
3827: @c great revelation here when I first understood them. Also, I like the
3828: @c fact that a very simple code example shows up almost all of the issues
3829: @c that you need to understand to see how Forth works. That's unique and
3830: @c worthwhile to emphasise.
3831:
1.83 anton 3832: @c anton: I think it's a good idea to present the details, especially those
3833: @c that you found to be a revelation, and probably the tutorial tries to be
3834: @c too superficial and does not get some of the things across that make
3835: @c Forth special. I do believe that most of the time these things should
3836: @c be discussed at the end of a section or in separate sections instead of
3837: @c in the middle of a section (e.g., the stuff you added in "User-defined
3838: @c defining words" leads in a completely different direction from the rest
3839: @c of the section).
3840:
1.29 crook 3841: Now we're going to take another look at the definition of @code{add-two}
3842: from the previous section. From our knowledge of the way that the text
3843: interpreter works, we would have expected this result when we tried to
3844: define @code{add-two}:
1.21 crook 3845:
1.29 crook 3846: @example
1.44 crook 3847: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3848: ^^^^^^^
3849: Error: Undefined word
3850: @end example
1.28 crook 3851:
1.29 crook 3852: The reason that this didn't happen is bound up in the way that @code{:}
3853: works. The word @code{:} does two special things. The first special
3854: thing that it does prevents the text interpreter from ever seeing the
3855: characters @code{add-two}. The text interpreter uses a variable called
3856: @cindex modifying >IN
1.44 crook 3857: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3858: input line. When it encounters the word @code{:} it behaves in exactly
3859: the same way as it does for any other word; it looks it up in the name
3860: dictionary, finds its xt and executes it. When @code{:} executes, it
3861: looks at the input buffer, finds the word @code{add-two} and advances the
3862: value of @code{>IN} to point past it. It then does some other stuff
3863: associated with creating the new definition (including creating an entry
3864: for @code{add-two} in the name dictionary). When the execution of @code{:}
3865: completes, control returns to the text interpreter, which is oblivious
3866: to the fact that it has been tricked into ignoring part of the input
3867: line.
1.21 crook 3868:
1.29 crook 3869: @cindex parsing words
3870: Words like @code{:} -- words that advance the value of @code{>IN} and so
3871: prevent the text interpreter from acting on the whole of the input line
3872: -- are called @dfn{parsing words}.
1.21 crook 3873:
1.29 crook 3874: @cindex @code{state} - effect on the text interpreter
3875: @cindex text interpreter - effect of state
3876: The second special thing that @code{:} does is change the value of a
3877: variable called @code{state}, which affects the way that the text
3878: interpreter behaves. When Gforth starts up, @code{state} has the value
3879: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3880: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3881: the text interpreter is said to be @dfn{compiling}.
3882:
3883: In this example, the text interpreter is compiling when it processes the
3884: string ``@code{2 + . ;}''. It still breaks the string down into
3885: character sequences in the same way. However, instead of pushing the
3886: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3887: into the definition of @code{add-two} that will make the number @code{2} get
3888: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3889: the behaviours of @code{+} and @code{.} are also compiled into the
3890: definition.
3891:
3892: One category of words don't get compiled. These so-called @dfn{immediate
3893: words} get executed (performed @i{now}) regardless of whether the text
3894: interpreter is interpreting or compiling. The word @code{;} is an
3895: immediate word. Rather than being compiled into the definition, it
3896: executes. Its effect is to terminate the current definition, which
3897: includes changing the value of @code{state} back to 0.
3898:
3899: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3900: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3901: definition.
1.28 crook 3902:
1.30 anton 3903: In Forth, every word or number can be described in terms of two
1.29 crook 3904: properties:
1.28 crook 3905:
3906: @itemize @bullet
3907: @item
1.29 crook 3908: @cindex interpretation semantics
1.44 crook 3909: Its @dfn{interpretation semantics} describe how it will behave when the
3910: text interpreter encounters it in @dfn{interpret} state. The
3911: interpretation semantics of a word are represented by an @dfn{execution
3912: token}.
1.28 crook 3913: @item
1.29 crook 3914: @cindex compilation semantics
1.44 crook 3915: Its @dfn{compilation semantics} describe how it will behave when the
3916: text interpreter encounters it in @dfn{compile} state. The compilation
3917: semantics of a word are represented in an implementation-dependent way;
3918: Gforth uses a @dfn{compilation token}.
1.29 crook 3919: @end itemize
3920:
3921: @noindent
3922: Numbers are always treated in a fixed way:
3923:
3924: @itemize @bullet
1.28 crook 3925: @item
1.44 crook 3926: When the number is @dfn{interpreted}, its behaviour is to push the
3927: number onto the stack.
1.28 crook 3928: @item
1.30 anton 3929: When the number is @dfn{compiled}, a piece of code is appended to the
3930: current definition that pushes the number when it runs. (In other words,
3931: the compilation semantics of a number are to postpone its interpretation
3932: semantics until the run-time of the definition that it is being compiled
3933: into.)
1.29 crook 3934: @end itemize
3935:
1.44 crook 3936: Words don't behave in such a regular way, but most have @i{default
3937: semantics} which means that they behave like this:
1.29 crook 3938:
3939: @itemize @bullet
1.28 crook 3940: @item
1.30 anton 3941: The @dfn{interpretation semantics} of the word are to do something useful.
3942: @item
1.29 crook 3943: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3944: @dfn{interpretation semantics} to the current definition (so that its
3945: run-time behaviour is to do something useful).
1.28 crook 3946: @end itemize
3947:
1.30 anton 3948: @cindex immediate words
1.44 crook 3949: The actual behaviour of any particular word can be controlled by using
3950: the words @code{immediate} and @code{compile-only} when the word is
3951: defined. These words set flags in the name dictionary entry of the most
3952: recently defined word, and these flags are retrieved by the text
3953: interpreter when it finds the word in the name dictionary.
3954:
3955: A word that is marked as @dfn{immediate} has compilation semantics that
3956: are identical to its interpretation semantics. In other words, it
3957: behaves like this:
1.29 crook 3958:
3959: @itemize @bullet
3960: @item
1.30 anton 3961: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3962: @item
1.30 anton 3963: The @dfn{compilation semantics} of the word are to do something useful
3964: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3965: @end itemize
1.28 crook 3966:
1.44 crook 3967: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3968: performing the interpretation semantics of the word directly; an attempt
3969: to do so will generate an error. It is never necessary to use
3970: @code{compile-only} (and it is not even part of ANS Forth, though it is
3971: provided by many implementations) but it is good etiquette to apply it
3972: to a word that will not behave correctly (and might have unexpected
3973: side-effects) in interpret state. For example, it is only legal to use
3974: the conditional word @code{IF} within a definition. If you forget this
3975: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3976: @code{compile-only} allows the text interpreter to generate a helpful
3977: error message rather than subjecting you to the consequences of your
3978: folly.
3979:
1.29 crook 3980: This example shows the difference between an immediate and a
3981: non-immediate word:
1.28 crook 3982:
1.29 crook 3983: @example
3984: : show-state state @@ . ;
3985: : show-state-now show-state ; immediate
3986: : word1 show-state ;
3987: : word2 show-state-now ;
1.28 crook 3988: @end example
1.23 crook 3989:
1.29 crook 3990: The word @code{immediate} after the definition of @code{show-state-now}
3991: makes that word an immediate word. These definitions introduce a new
3992: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
3993: variable, and leaves it on the stack. Therefore, the behaviour of
3994: @code{show-state} is to print a number that represents the current value
3995: of @code{state}.
1.28 crook 3996:
1.29 crook 3997: When you execute @code{word1}, it prints the number 0, indicating that
3998: the system is interpreting. When the text interpreter compiled the
3999: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4000: compilation semantics are to append its interpretation semantics to the
1.29 crook 4001: current definition. When you execute @code{word1}, it performs the
1.30 anton 4002: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4003: (and therefore @code{show-state}) are executed, the system is
4004: interpreting.
1.28 crook 4005:
1.30 anton 4006: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4007: you should have seen the number -1 printed, followed by ``@code{
4008: ok}''. When the text interpreter compiled the definition of
4009: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4010: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4011: semantics. It is executed straight away (even before the text
4012: interpreter has moved on to process another group of characters; the
4013: @code{;} in this example). The effect of executing it are to display the
4014: value of @code{state} @i{at the time that the definition of}
4015: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4016: system is compiling at this time. If you execute @code{word2} it does
4017: nothing at all.
1.28 crook 4018:
1.29 crook 4019: @cindex @code{."}, how it works
4020: Before leaving the subject of immediate words, consider the behaviour of
4021: @code{."} in the definition of @code{greet}, in the previous
4022: section. This word is both a parsing word and an immediate word. Notice
4023: that there is a space between @code{."} and the start of the text
4024: @code{Hello and welcome}, but that there is no space between the last
4025: letter of @code{welcome} and the @code{"} character. The reason for this
4026: is that @code{."} is a Forth word; it must have a space after it so that
4027: the text interpreter can identify it. The @code{"} is not a Forth word;
4028: it is a @dfn{delimiter}. The examples earlier show that, when the string
4029: is displayed, there is neither a space before the @code{H} nor after the
4030: @code{e}. Since @code{."} is an immediate word, it executes at the time
4031: that @code{greet} is defined. When it executes, its behaviour is to
4032: search forward in the input line looking for the delimiter. When it
4033: finds the delimiter, it updates @code{>IN} to point past the
4034: delimiter. It also compiles some magic code into the definition of
4035: @code{greet}; the xt of a run-time routine that prints a text string. It
4036: compiles the string @code{Hello and welcome} into memory so that it is
4037: available to be printed later. When the text interpreter gains control,
4038: the next word it finds in the input stream is @code{;} and so it
4039: terminates the definition of @code{greet}.
1.28 crook 4040:
4041:
4042: @comment ----------------------------------------------
1.29 crook 4043: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4044: @section Forth is written in Forth
4045: @cindex structure of Forth programs
4046:
4047: When you start up a Forth compiler, a large number of definitions
4048: already exist. In Forth, you develop a new application using bottom-up
4049: programming techniques to create new definitions that are defined in
4050: terms of existing definitions. As you create each definition you can
4051: test and debug it interactively.
4052:
4053: If you have tried out the examples in this section, you will probably
4054: have typed them in by hand; when you leave Gforth, your definitions will
4055: be lost. You can avoid this by using a text editor to enter Forth source
4056: code into a file, and then loading code from the file using
1.49 anton 4057: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4058: processed by the text interpreter, just as though you had typed it in by
4059: hand@footnote{Actually, there are some subtle differences -- see
4060: @ref{The Text Interpreter}.}.
4061:
4062: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4063: files for program entry (@pxref{Blocks}).
1.28 crook 4064:
1.29 crook 4065: In common with many, if not most, Forth compilers, most of Gforth is
4066: actually written in Forth. All of the @file{.fs} files in the
4067: installation directory@footnote{For example,
1.30 anton 4068: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4069: study to see examples of Forth programming.
1.28 crook 4070:
1.29 crook 4071: Gforth maintains a history file that records every line that you type to
4072: the text interpreter. This file is preserved between sessions, and is
4073: used to provide a command-line recall facility. If you enter long
4074: definitions by hand, you can use a text editor to paste them out of the
4075: history file into a Forth source file for reuse at a later time
1.49 anton 4076: (for more information @pxref{Command-line editing}).
1.28 crook 4077:
4078:
4079: @comment ----------------------------------------------
1.29 crook 4080: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4081: @section Review - elements of a Forth system
4082: @cindex elements of a Forth system
1.28 crook 4083:
1.29 crook 4084: To summarise this chapter:
1.28 crook 4085:
4086: @itemize @bullet
4087: @item
1.29 crook 4088: Forth programs use @dfn{factoring} to break a problem down into small
4089: fragments called @dfn{words} or @dfn{definitions}.
4090: @item
4091: Forth program development is an interactive process.
4092: @item
4093: The main command loop that accepts input, and controls both
4094: interpretation and compilation, is called the @dfn{text interpreter}
4095: (also known as the @dfn{outer interpreter}).
4096: @item
4097: Forth has a very simple syntax, consisting of words and numbers
4098: separated by spaces or carriage-return characters. Any additional syntax
4099: is imposed by @dfn{parsing words}.
4100: @item
4101: Forth uses a stack to pass parameters between words. As a result, it
4102: uses postfix notation.
4103: @item
4104: To use a word that has previously been defined, the text interpreter
4105: searches for the word in the @dfn{name dictionary}.
4106: @item
1.30 anton 4107: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4108: @item
1.29 crook 4109: The text interpreter uses the value of @code{state} to select between
4110: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4111: semantics} of a word that it encounters.
1.28 crook 4112: @item
1.30 anton 4113: The relationship between the @dfn{interpretation semantics} and
4114: @dfn{compilation semantics} for a word
1.29 crook 4115: depend upon the way in which the word was defined (for example, whether
4116: it is an @dfn{immediate} word).
1.28 crook 4117: @item
1.29 crook 4118: Forth definitions can be implemented in Forth (called @dfn{high-level
4119: definitions}) or in some other way (usually a lower-level language and
4120: as a result often called @dfn{low-level definitions}, @dfn{code
4121: definitions} or @dfn{primitives}).
1.28 crook 4122: @item
1.29 crook 4123: Many Forth systems are implemented mainly in Forth.
1.28 crook 4124: @end itemize
4125:
4126:
1.29 crook 4127: @comment ----------------------------------------------
1.48 anton 4128: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4129: @section Where To Go Next
4130: @cindex where to go next
1.28 crook 4131:
1.29 crook 4132: Amazing as it may seem, if you have read (and understood) this far, you
4133: know almost all the fundamentals about the inner workings of a Forth
4134: system. You certainly know enough to be able to read and understand the
4135: rest of this manual and the ANS Forth document, to learn more about the
4136: facilities that Forth in general and Gforth in particular provide. Even
4137: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4138: However, that's not a good idea just yet... better to try writing some
1.29 crook 4139: programs in Gforth.
1.28 crook 4140:
1.29 crook 4141: Forth has such a rich vocabulary that it can be hard to know where to
4142: start in learning it. This section suggests a few sets of words that are
4143: enough to write small but useful programs. Use the word index in this
4144: document to learn more about each word, then try it out and try to write
4145: small definitions using it. Start by experimenting with these words:
1.28 crook 4146:
4147: @itemize @bullet
4148: @item
1.29 crook 4149: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4150: @item
4151: Comparison: @code{MIN MAX =}
4152: @item
4153: Logic: @code{AND OR XOR NOT}
4154: @item
4155: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4156: @item
1.29 crook 4157: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4158: @item
1.29 crook 4159: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4160: @item
1.29 crook 4161: Defining words: @code{: ; CREATE}
1.28 crook 4162: @item
1.29 crook 4163: Memory allocation words: @code{ALLOT ,}
1.28 crook 4164: @item
1.29 crook 4165: Tools: @code{SEE WORDS .S MARKER}
4166: @end itemize
4167:
4168: When you have mastered those, go on to:
4169:
4170: @itemize @bullet
1.28 crook 4171: @item
1.29 crook 4172: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4173: @item
1.29 crook 4174: Memory access: @code{@@ !}
1.28 crook 4175: @end itemize
1.23 crook 4176:
1.29 crook 4177: When you have mastered these, there's nothing for it but to read through
4178: the whole of this manual and find out what you've missed.
4179:
4180: @comment ----------------------------------------------
1.48 anton 4181: @node Exercises, , Where to go next, Introduction
1.29 crook 4182: @section Exercises
4183: @cindex exercises
4184:
4185: TODO: provide a set of programming excercises linked into the stuff done
4186: already and into other sections of the manual. Provide solutions to all
4187: the exercises in a .fs file in the distribution.
4188:
4189: @c Get some inspiration from Starting Forth and Kelly&Spies.
4190:
4191: @c excercises:
4192: @c 1. take inches and convert to feet and inches.
4193: @c 2. take temperature and convert from fahrenheight to celcius;
4194: @c may need to care about symmetric vs floored??
4195: @c 3. take input line and do character substitution
4196: @c to encipher or decipher
4197: @c 4. as above but work on a file for in and out
4198: @c 5. take input line and convert to pig-latin
4199: @c
4200: @c thing of sets of things to exercise then come up with
4201: @c problems that need those things.
4202:
4203:
1.26 crook 4204: @c ******************************************************************
1.29 crook 4205: @node Words, Error messages, Introduction, Top
1.1 anton 4206: @chapter Forth Words
1.26 crook 4207: @cindex words
1.1 anton 4208:
4209: @menu
4210: * Notation::
1.65 anton 4211: * Case insensitivity::
4212: * Comments::
4213: * Boolean Flags::
1.1 anton 4214: * Arithmetic::
4215: * Stack Manipulation::
1.5 anton 4216: * Memory::
1.1 anton 4217: * Control Structures::
4218: * Defining Words::
1.65 anton 4219: * Interpretation and Compilation Semantics::
1.47 crook 4220: * Tokens for Words::
1.81 anton 4221: * Compiling words::
1.65 anton 4222: * The Text Interpreter::
1.111 anton 4223: * The Input Stream::
1.65 anton 4224: * Word Lists::
4225: * Environmental Queries::
1.12 anton 4226: * Files::
4227: * Blocks::
4228: * Other I/O::
1.121 anton 4229: * OS command line arguments::
1.78 anton 4230: * Locals::
4231: * Structures::
4232: * Object-oriented Forth::
1.12 anton 4233: * Programming Tools::
4234: * Assembler and Code Words::
4235: * Threading Words::
1.65 anton 4236: * Passing Commands to the OS::
4237: * Keeping track of Time::
4238: * Miscellaneous Words::
1.1 anton 4239: @end menu
4240:
1.65 anton 4241: @node Notation, Case insensitivity, Words, Words
1.1 anton 4242: @section Notation
4243: @cindex notation of glossary entries
4244: @cindex format of glossary entries
4245: @cindex glossary notation format
4246: @cindex word glossary entry format
4247:
4248: The Forth words are described in this section in the glossary notation
1.67 anton 4249: that has become a de-facto standard for Forth texts:
1.1 anton 4250:
4251: @format
1.29 crook 4252: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4253: @end format
1.29 crook 4254: @i{Description}
1.1 anton 4255:
4256: @table @var
4257: @item word
1.28 crook 4258: The name of the word.
1.1 anton 4259:
4260: @item Stack effect
4261: @cindex stack effect
1.29 crook 4262: The stack effect is written in the notation @code{@i{before} --
4263: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4264: stack entries before and after the execution of the word. The rest of
4265: the stack is not touched by the word. The top of stack is rightmost,
4266: i.e., a stack sequence is written as it is typed in. Note that Gforth
4267: uses a separate floating point stack, but a unified stack
1.29 crook 4268: notation. Also, return stack effects are not shown in @i{stack
4269: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4270: the type and/or the function of the item. See below for a discussion of
4271: the types.
4272:
4273: All words have two stack effects: A compile-time stack effect and a
4274: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4275: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4276: this standard behaviour, or the word does other unusual things at
4277: compile time, both stack effects are shown; otherwise only the run-time
4278: stack effect is shown.
4279:
4280: @cindex pronounciation of words
4281: @item pronunciation
4282: How the word is pronounced.
4283:
4284: @cindex wordset
1.67 anton 4285: @cindex environment wordset
1.1 anton 4286: @item wordset
1.21 crook 4287: The ANS Forth standard is divided into several word sets. A standard
4288: system need not support all of them. Therefore, in theory, the fewer
4289: word sets your program uses the more portable it will be. However, we
4290: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4291: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4292: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4293: describes words that will work in future releases of Gforth;
4294: @code{gforth-internal} words are more volatile. Environmental query
4295: strings are also displayed like words; you can recognize them by the
1.21 crook 4296: @code{environment} in the word set field.
1.1 anton 4297:
4298: @item Description
4299: A description of the behaviour of the word.
4300: @end table
4301:
4302: @cindex types of stack items
4303: @cindex stack item types
4304: The type of a stack item is specified by the character(s) the name
4305: starts with:
4306:
4307: @table @code
4308: @item f
4309: @cindex @code{f}, stack item type
4310: Boolean flags, i.e. @code{false} or @code{true}.
4311: @item c
4312: @cindex @code{c}, stack item type
4313: Char
4314: @item w
4315: @cindex @code{w}, stack item type
4316: Cell, can contain an integer or an address
4317: @item n
4318: @cindex @code{n}, stack item type
4319: signed integer
4320: @item u
4321: @cindex @code{u}, stack item type
4322: unsigned integer
4323: @item d
4324: @cindex @code{d}, stack item type
4325: double sized signed integer
4326: @item ud
4327: @cindex @code{ud}, stack item type
4328: double sized unsigned integer
4329: @item r
4330: @cindex @code{r}, stack item type
4331: Float (on the FP stack)
1.21 crook 4332: @item a-
1.1 anton 4333: @cindex @code{a_}, stack item type
4334: Cell-aligned address
1.21 crook 4335: @item c-
1.1 anton 4336: @cindex @code{c_}, stack item type
4337: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4338: @item f-
1.1 anton 4339: @cindex @code{f_}, stack item type
4340: Float-aligned address
1.21 crook 4341: @item df-
1.1 anton 4342: @cindex @code{df_}, stack item type
4343: Address aligned for IEEE double precision float
1.21 crook 4344: @item sf-
1.1 anton 4345: @cindex @code{sf_}, stack item type
4346: Address aligned for IEEE single precision float
4347: @item xt
4348: @cindex @code{xt}, stack item type
4349: Execution token, same size as Cell
4350: @item wid
4351: @cindex @code{wid}, stack item type
1.21 crook 4352: Word list ID, same size as Cell
1.68 anton 4353: @item ior, wior
4354: @cindex ior type description
4355: @cindex wior type description
4356: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4357: @item f83name
4358: @cindex @code{f83name}, stack item type
4359: Pointer to a name structure
4360: @item "
4361: @cindex @code{"}, stack item type
1.12 anton 4362: string in the input stream (not on the stack). The terminating character
4363: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4364: quotes.
4365: @end table
4366:
1.65 anton 4367: @comment ----------------------------------------------
4368: @node Case insensitivity, Comments, Notation, Words
4369: @section Case insensitivity
4370: @cindex case sensitivity
4371: @cindex upper and lower case
4372:
4373: Gforth is case-insensitive; you can enter definitions and invoke
4374: Standard words using upper, lower or mixed case (however,
4375: @pxref{core-idef, Implementation-defined options, Implementation-defined
4376: options}).
4377:
4378: ANS Forth only @i{requires} implementations to recognise Standard words
4379: when they are typed entirely in upper case. Therefore, a Standard
4380: program must use upper case for all Standard words. You can use whatever
4381: case you like for words that you define, but in a Standard program you
4382: have to use the words in the same case that you defined them.
4383:
4384: Gforth supports case sensitivity through @code{table}s (case-sensitive
4385: wordlists, @pxref{Word Lists}).
4386:
4387: Two people have asked how to convert Gforth to be case-sensitive; while
4388: we think this is a bad idea, you can change all wordlists into tables
4389: like this:
4390:
4391: @example
4392: ' table-find forth-wordlist wordlist-map @ !
4393: @end example
4394:
4395: Note that you now have to type the predefined words in the same case
4396: that we defined them, which are varying. You may want to convert them
4397: to your favourite case before doing this operation (I won't explain how,
4398: because if you are even contemplating doing this, you'd better have
4399: enough knowledge of Forth systems to know this already).
4400:
4401: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4402: @section Comments
1.26 crook 4403: @cindex comments
1.21 crook 4404:
1.29 crook 4405: Forth supports two styles of comment; the traditional @i{in-line} comment,
4406: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4407:
1.44 crook 4408:
1.23 crook 4409: doc-(
1.21 crook 4410: doc-\
1.23 crook 4411: doc-\G
1.21 crook 4412:
1.44 crook 4413:
1.21 crook 4414: @node Boolean Flags, Arithmetic, Comments, Words
4415: @section Boolean Flags
1.26 crook 4416: @cindex Boolean flags
1.21 crook 4417:
4418: A Boolean flag is cell-sized. A cell with all bits clear represents the
4419: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4420: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4421: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4422: @c on and off to Memory?
4423: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4424:
1.21 crook 4425: doc-true
4426: doc-false
1.29 crook 4427: doc-on
4428: doc-off
1.21 crook 4429:
1.44 crook 4430:
1.21 crook 4431: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4432: @section Arithmetic
4433: @cindex arithmetic words
4434:
4435: @cindex division with potentially negative operands
4436: Forth arithmetic is not checked, i.e., you will not hear about integer
4437: overflow on addition or multiplication, you may hear about division by
4438: zero if you are lucky. The operator is written after the operands, but
4439: the operands are still in the original order. I.e., the infix @code{2-1}
4440: corresponds to @code{2 1 -}. Forth offers a variety of division
4441: operators. If you perform division with potentially negative operands,
4442: you do not want to use @code{/} or @code{/mod} with its undefined
4443: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4444: former, @pxref{Mixed precision}).
1.26 crook 4445: @comment TODO discuss the different division forms and the std approach
1.1 anton 4446:
4447: @menu
4448: * Single precision::
1.67 anton 4449: * Double precision:: Double-cell integer arithmetic
1.1 anton 4450: * Bitwise operations::
1.67 anton 4451: * Numeric comparison::
1.29 crook 4452: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4453: * Floating Point::
4454: @end menu
4455:
1.67 anton 4456: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4457: @subsection Single precision
4458: @cindex single precision arithmetic words
4459:
1.67 anton 4460: @c !! cell undefined
4461:
4462: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4463: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4464: treat them. For the rules used by the text interpreter for recognising
4465: single-precision integers see @ref{Number Conversion}.
1.21 crook 4466:
1.67 anton 4467: These words are all defined for signed operands, but some of them also
4468: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4469: @code{*}.
1.44 crook 4470:
1.1 anton 4471: doc-+
1.21 crook 4472: doc-1+
1.128 anton 4473: doc-under+
1.1 anton 4474: doc--
1.21 crook 4475: doc-1-
1.1 anton 4476: doc-*
4477: doc-/
4478: doc-mod
4479: doc-/mod
4480: doc-negate
4481: doc-abs
4482: doc-min
4483: doc-max
1.27 crook 4484: doc-floored
1.1 anton 4485:
1.44 crook 4486:
1.67 anton 4487: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4488: @subsection Double precision
4489: @cindex double precision arithmetic words
4490:
1.49 anton 4491: For the rules used by the text interpreter for
4492: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4493:
4494: A double precision number is represented by a cell pair, with the most
1.67 anton 4495: significant cell at the TOS. It is trivial to convert an unsigned single
4496: to a double: simply push a @code{0} onto the TOS. Since numbers are
4497: represented by Gforth using 2's complement arithmetic, converting a
4498: signed single to a (signed) double requires sign-extension across the
4499: most significant cell. This can be achieved using @code{s>d}. The moral
4500: of the story is that you cannot convert a number without knowing whether
4501: it represents an unsigned or a signed number.
1.21 crook 4502:
1.67 anton 4503: These words are all defined for signed operands, but some of them also
4504: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4505:
1.21 crook 4506: doc-s>d
1.67 anton 4507: doc-d>s
1.21 crook 4508: doc-d+
4509: doc-d-
4510: doc-dnegate
4511: doc-dabs
4512: doc-dmin
4513: doc-dmax
4514:
1.44 crook 4515:
1.67 anton 4516: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4517: @subsection Bitwise operations
4518: @cindex bitwise operation words
4519:
4520:
4521: doc-and
4522: doc-or
4523: doc-xor
4524: doc-invert
4525: doc-lshift
4526: doc-rshift
4527: doc-2*
4528: doc-d2*
4529: doc-2/
4530: doc-d2/
4531:
4532:
4533: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4534: @subsection Numeric comparison
4535: @cindex numeric comparison words
4536:
1.67 anton 4537: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4538: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4539:
1.28 crook 4540: doc-<
4541: doc-<=
4542: doc-<>
4543: doc-=
4544: doc->
4545: doc->=
4546:
1.21 crook 4547: doc-0<
1.23 crook 4548: doc-0<=
1.21 crook 4549: doc-0<>
4550: doc-0=
1.23 crook 4551: doc-0>
4552: doc-0>=
1.28 crook 4553:
4554: doc-u<
4555: doc-u<=
1.44 crook 4556: @c u<> and u= exist but are the same as <> and =
1.31 anton 4557: @c doc-u<>
4558: @c doc-u=
1.28 crook 4559: doc-u>
4560: doc-u>=
4561:
4562: doc-within
4563:
4564: doc-d<
4565: doc-d<=
4566: doc-d<>
4567: doc-d=
4568: doc-d>
4569: doc-d>=
1.23 crook 4570:
1.21 crook 4571: doc-d0<
1.23 crook 4572: doc-d0<=
4573: doc-d0<>
1.21 crook 4574: doc-d0=
1.23 crook 4575: doc-d0>
4576: doc-d0>=
4577:
1.21 crook 4578: doc-du<
1.28 crook 4579: doc-du<=
1.44 crook 4580: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4581: @c doc-du<>
4582: @c doc-du=
1.28 crook 4583: doc-du>
4584: doc-du>=
1.1 anton 4585:
1.44 crook 4586:
1.21 crook 4587: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4588: @subsection Mixed precision
4589: @cindex mixed precision arithmetic words
4590:
1.44 crook 4591:
1.1 anton 4592: doc-m+
4593: doc-*/
4594: doc-*/mod
4595: doc-m*
4596: doc-um*
4597: doc-m*/
4598: doc-um/mod
4599: doc-fm/mod
4600: doc-sm/rem
4601:
1.44 crook 4602:
1.21 crook 4603: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4604: @subsection Floating Point
4605: @cindex floating point arithmetic words
4606:
1.49 anton 4607: For the rules used by the text interpreter for
4608: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4609:
1.67 anton 4610: Gforth has a separate floating point stack, but the documentation uses
4611: the unified notation.@footnote{It's easy to generate the separate
4612: notation from that by just separating the floating-point numbers out:
4613: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4614: r3 )}.}
1.1 anton 4615:
4616: @cindex floating-point arithmetic, pitfalls
4617: Floating point numbers have a number of unpleasant surprises for the
4618: unwary (e.g., floating point addition is not associative) and even a few
4619: for the wary. You should not use them unless you know what you are doing
4620: or you don't care that the results you get are totally bogus. If you
4621: want to learn about the problems of floating point numbers (and how to
1.66 anton 4622: avoid them), you might start with @cite{David Goldberg,
4623: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4624: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4625: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4626:
1.44 crook 4627:
1.21 crook 4628: doc-d>f
4629: doc-f>d
1.1 anton 4630: doc-f+
4631: doc-f-
4632: doc-f*
4633: doc-f/
4634: doc-fnegate
4635: doc-fabs
4636: doc-fmax
4637: doc-fmin
4638: doc-floor
4639: doc-fround
4640: doc-f**
4641: doc-fsqrt
4642: doc-fexp
4643: doc-fexpm1
4644: doc-fln
4645: doc-flnp1
4646: doc-flog
4647: doc-falog
1.32 anton 4648: doc-f2*
4649: doc-f2/
4650: doc-1/f
4651: doc-precision
4652: doc-set-precision
4653:
4654: @cindex angles in trigonometric operations
4655: @cindex trigonometric operations
4656: Angles in floating point operations are given in radians (a full circle
4657: has 2 pi radians).
4658:
1.1 anton 4659: doc-fsin
4660: doc-fcos
4661: doc-fsincos
4662: doc-ftan
4663: doc-fasin
4664: doc-facos
4665: doc-fatan
4666: doc-fatan2
4667: doc-fsinh
4668: doc-fcosh
4669: doc-ftanh
4670: doc-fasinh
4671: doc-facosh
4672: doc-fatanh
1.21 crook 4673: doc-pi
1.28 crook 4674:
1.32 anton 4675: @cindex equality of floats
4676: @cindex floating-point comparisons
1.31 anton 4677: One particular problem with floating-point arithmetic is that comparison
4678: for equality often fails when you would expect it to succeed. For this
4679: reason approximate equality is often preferred (but you still have to
1.67 anton 4680: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4681: differently from what you might expect. The comparison words are:
1.31 anton 4682:
4683: doc-f~rel
4684: doc-f~abs
1.68 anton 4685: doc-f~
1.31 anton 4686: doc-f=
4687: doc-f<>
4688:
4689: doc-f<
4690: doc-f<=
4691: doc-f>
4692: doc-f>=
4693:
1.21 crook 4694: doc-f0<
1.28 crook 4695: doc-f0<=
4696: doc-f0<>
1.21 crook 4697: doc-f0=
1.28 crook 4698: doc-f0>
4699: doc-f0>=
4700:
1.1 anton 4701:
4702: @node Stack Manipulation, Memory, Arithmetic, Words
4703: @section Stack Manipulation
4704: @cindex stack manipulation words
4705:
4706: @cindex floating-point stack in the standard
1.21 crook 4707: Gforth maintains a number of separate stacks:
4708:
1.29 crook 4709: @cindex data stack
4710: @cindex parameter stack
1.21 crook 4711: @itemize @bullet
4712: @item
1.29 crook 4713: A data stack (also known as the @dfn{parameter stack}) -- for
4714: characters, cells, addresses, and double cells.
1.21 crook 4715:
1.29 crook 4716: @cindex floating-point stack
1.21 crook 4717: @item
1.44 crook 4718: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4719:
1.29 crook 4720: @cindex return stack
1.21 crook 4721: @item
1.44 crook 4722: A return stack -- for holding the return addresses of colon
1.32 anton 4723: definitions and other (non-FP) data.
1.21 crook 4724:
1.29 crook 4725: @cindex locals stack
1.21 crook 4726: @item
1.44 crook 4727: A locals stack -- for holding local variables.
1.21 crook 4728: @end itemize
4729:
1.1 anton 4730: @menu
4731: * Data stack::
4732: * Floating point stack::
4733: * Return stack::
4734: * Locals stack::
4735: * Stack pointer manipulation::
4736: @end menu
4737:
4738: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4739: @subsection Data stack
4740: @cindex data stack manipulation words
4741: @cindex stack manipulations words, data stack
4742:
1.44 crook 4743:
1.1 anton 4744: doc-drop
4745: doc-nip
4746: doc-dup
4747: doc-over
4748: doc-tuck
4749: doc-swap
1.21 crook 4750: doc-pick
1.1 anton 4751: doc-rot
4752: doc--rot
4753: doc-?dup
4754: doc-roll
4755: doc-2drop
4756: doc-2nip
4757: doc-2dup
4758: doc-2over
4759: doc-2tuck
4760: doc-2swap
4761: doc-2rot
4762:
1.44 crook 4763:
1.1 anton 4764: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4765: @subsection Floating point stack
4766: @cindex floating-point stack manipulation words
4767: @cindex stack manipulation words, floating-point stack
4768:
1.32 anton 4769: Whilst every sane Forth has a separate floating-point stack, it is not
4770: strictly required; an ANS Forth system could theoretically keep
4771: floating-point numbers on the data stack. As an additional difficulty,
4772: you don't know how many cells a floating-point number takes. It is
4773: reportedly possible to write words in a way that they work also for a
4774: unified stack model, but we do not recommend trying it. Instead, just
4775: say that your program has an environmental dependency on a separate
4776: floating-point stack.
4777:
4778: doc-floating-stack
4779:
1.1 anton 4780: doc-fdrop
4781: doc-fnip
4782: doc-fdup
4783: doc-fover
4784: doc-ftuck
4785: doc-fswap
1.21 crook 4786: doc-fpick
1.1 anton 4787: doc-frot
4788:
1.44 crook 4789:
1.1 anton 4790: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4791: @subsection Return stack
4792: @cindex return stack manipulation words
4793: @cindex stack manipulation words, return stack
4794:
1.32 anton 4795: @cindex return stack and locals
4796: @cindex locals and return stack
4797: A Forth system is allowed to keep local variables on the
4798: return stack. This is reasonable, as local variables usually eliminate
4799: the need to use the return stack explicitly. So, if you want to produce
4800: a standard compliant program and you are using local variables in a
4801: word, forget about return stack manipulations in that word (refer to the
4802: standard document for the exact rules).
4803:
1.1 anton 4804: doc->r
4805: doc-r>
4806: doc-r@
4807: doc-rdrop
4808: doc-2>r
4809: doc-2r>
4810: doc-2r@
4811: doc-2rdrop
4812:
1.44 crook 4813:
1.1 anton 4814: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4815: @subsection Locals stack
4816:
1.78 anton 4817: Gforth uses an extra locals stack. It is described, along with the
4818: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4819:
1.1 anton 4820: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4821: @subsection Stack pointer manipulation
4822: @cindex stack pointer manipulation words
4823:
1.44 crook 4824: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4825: doc-sp0
1.1 anton 4826: doc-sp@
4827: doc-sp!
1.21 crook 4828: doc-fp0
1.1 anton 4829: doc-fp@
4830: doc-fp!
1.21 crook 4831: doc-rp0
1.1 anton 4832: doc-rp@
4833: doc-rp!
1.21 crook 4834: doc-lp0
1.1 anton 4835: doc-lp@
4836: doc-lp!
4837:
1.44 crook 4838:
1.1 anton 4839: @node Memory, Control Structures, Stack Manipulation, Words
4840: @section Memory
1.26 crook 4841: @cindex memory words
1.1 anton 4842:
1.32 anton 4843: @menu
4844: * Memory model::
4845: * Dictionary allocation::
4846: * Heap Allocation::
4847: * Memory Access::
4848: * Address arithmetic::
4849: * Memory Blocks::
4850: @end menu
4851:
1.67 anton 4852: In addition to the standard Forth memory allocation words, there is also
4853: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4854: garbage collector}.
4855:
1.32 anton 4856: @node Memory model, Dictionary allocation, Memory, Memory
4857: @subsection ANS Forth and Gforth memory models
4858:
4859: @c The ANS Forth description is a mess (e.g., is the heap part of
4860: @c the dictionary?), so let's not stick to closely with it.
4861:
1.67 anton 4862: ANS Forth considers a Forth system as consisting of several address
4863: spaces, of which only @dfn{data space} is managed and accessible with
4864: the memory words. Memory not necessarily in data space includes the
4865: stacks, the code (called code space) and the headers (called name
4866: space). In Gforth everything is in data space, but the code for the
4867: primitives is usually read-only.
1.32 anton 4868:
4869: Data space is divided into a number of areas: The (data space portion of
4870: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4871: refer to the search data structure embodied in word lists and headers,
4872: because it is used for looking up names, just as you would in a
4873: conventional dictionary.}, the heap, and a number of system-allocated
4874: buffers.
4875:
1.68 anton 4876: @cindex address arithmetic restrictions, ANS vs. Gforth
4877: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4878: In ANS Forth data space is also divided into contiguous regions. You
4879: can only use address arithmetic within a contiguous region, not between
4880: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4881: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4882: allocation}).
4883:
4884: Gforth provides one big address space, and address arithmetic can be
4885: performed between any addresses. However, in the dictionary headers or
4886: code are interleaved with data, so almost the only contiguous data space
4887: regions there are those described by ANS Forth as contiguous; but you
4888: can be sure that the dictionary is allocated towards increasing
4889: addresses even between contiguous regions. The memory order of
4890: allocations in the heap is platform-dependent (and possibly different
4891: from one run to the next).
4892:
1.27 crook 4893:
1.32 anton 4894: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4895: @subsection Dictionary allocation
1.27 crook 4896: @cindex reserving data space
4897: @cindex data space - reserving some
4898:
1.32 anton 4899: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4900: you want to deallocate X, you also deallocate everything
4901: allocated after X.
4902:
1.68 anton 4903: @cindex contiguous regions in dictionary allocation
1.32 anton 4904: The allocations using the words below are contiguous and grow the region
4905: towards increasing addresses. Other words that allocate dictionary
4906: memory of any kind (i.e., defining words including @code{:noname}) end
4907: the contiguous region and start a new one.
4908:
4909: In ANS Forth only @code{create}d words are guaranteed to produce an
4910: address that is the start of the following contiguous region. In
4911: particular, the cell allocated by @code{variable} is not guaranteed to
4912: be contiguous with following @code{allot}ed memory.
4913:
4914: You can deallocate memory by using @code{allot} with a negative argument
4915: (with some restrictions, see @code{allot}). For larger deallocations use
4916: @code{marker}.
1.27 crook 4917:
1.29 crook 4918:
1.27 crook 4919: doc-here
4920: doc-unused
4921: doc-allot
4922: doc-c,
1.29 crook 4923: doc-f,
1.27 crook 4924: doc-,
4925: doc-2,
4926:
1.32 anton 4927: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4928: course you should allocate memory in an aligned way, too. I.e., before
4929: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4930: The words below align @code{here} if it is not already. Basically it is
4931: only already aligned for a type, if the last allocation was a multiple
4932: of the size of this type and if @code{here} was aligned for this type
4933: before.
4934:
4935: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4936: ANS Forth (@code{maxalign}ed in Gforth).
4937:
4938: doc-align
4939: doc-falign
4940: doc-sfalign
4941: doc-dfalign
4942: doc-maxalign
4943: doc-cfalign
4944:
4945:
4946: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4947: @subsection Heap allocation
4948: @cindex heap allocation
4949: @cindex dynamic allocation of memory
4950: @cindex memory-allocation word set
4951:
1.68 anton 4952: @cindex contiguous regions and heap allocation
1.32 anton 4953: Heap allocation supports deallocation of allocated memory in any
4954: order. Dictionary allocation is not affected by it (i.e., it does not
4955: end a contiguous region). In Gforth, these words are implemented using
4956: the standard C library calls malloc(), free() and resize().
4957:
1.68 anton 4958: The memory region produced by one invocation of @code{allocate} or
4959: @code{resize} is internally contiguous. There is no contiguity between
4960: such a region and any other region (including others allocated from the
4961: heap).
4962:
1.32 anton 4963: doc-allocate
4964: doc-free
4965: doc-resize
4966:
1.27 crook 4967:
1.32 anton 4968: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4969: @subsection Memory Access
4970: @cindex memory access words
4971:
4972: doc-@
4973: doc-!
4974: doc-+!
4975: doc-c@
4976: doc-c!
4977: doc-2@
4978: doc-2!
4979: doc-f@
4980: doc-f!
4981: doc-sf@
4982: doc-sf!
4983: doc-df@
4984: doc-df!
4985:
1.68 anton 4986:
1.32 anton 4987: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4988: @subsection Address arithmetic
1.1 anton 4989: @cindex address arithmetic words
4990:
1.67 anton 4991: Address arithmetic is the foundation on which you can build data
4992: structures like arrays, records (@pxref{Structures}) and objects
4993: (@pxref{Object-oriented Forth}).
1.32 anton 4994:
1.68 anton 4995: @cindex address unit
4996: @cindex au (address unit)
1.1 anton 4997: ANS Forth does not specify the sizes of the data types. Instead, it
4998: offers a number of words for computing sizes and doing address
1.29 crook 4999: arithmetic. Address arithmetic is performed in terms of address units
5000: (aus); on most systems the address unit is one byte. Note that a
5001: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5002: platforms where it is a noop, it compiles to nothing).
1.1 anton 5003:
1.67 anton 5004: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5005: you have the address of a cell, perform @code{1 cells +}, and you will
5006: have the address of the next cell.
5007:
1.68 anton 5008: @cindex contiguous regions and address arithmetic
1.67 anton 5009: In ANS Forth you can perform address arithmetic only within a contiguous
5010: region, i.e., if you have an address into one region, you can only add
5011: and subtract such that the result is still within the region; you can
5012: only subtract or compare addresses from within the same contiguous
5013: region. Reasons: several contiguous regions can be arranged in memory
5014: in any way; on segmented systems addresses may have unusual
5015: representations, such that address arithmetic only works within a
5016: region. Gforth provides a few more guarantees (linear address space,
5017: dictionary grows upwards), but in general I have found it easy to stay
5018: within contiguous regions (exception: computing and comparing to the
5019: address just beyond the end of an array).
5020:
1.1 anton 5021: @cindex alignment of addresses for types
5022: ANS Forth also defines words for aligning addresses for specific
5023: types. Many computers require that accesses to specific data types
5024: must only occur at specific addresses; e.g., that cells may only be
5025: accessed at addresses divisible by 4. Even if a machine allows unaligned
5026: accesses, it can usually perform aligned accesses faster.
5027:
5028: For the performance-conscious: alignment operations are usually only
5029: necessary during the definition of a data structure, not during the
5030: (more frequent) accesses to it.
5031:
5032: ANS Forth defines no words for character-aligning addresses. This is not
5033: an oversight, but reflects the fact that addresses that are not
5034: char-aligned have no use in the standard and therefore will not be
5035: created.
5036:
5037: @cindex @code{CREATE} and alignment
1.29 crook 5038: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5039: are cell-aligned; in addition, Gforth guarantees that these addresses
5040: are aligned for all purposes.
5041:
1.26 crook 5042: Note that the ANS Forth word @code{char} has nothing to do with address
5043: arithmetic.
1.1 anton 5044:
1.44 crook 5045:
1.1 anton 5046: doc-chars
5047: doc-char+
5048: doc-cells
5049: doc-cell+
5050: doc-cell
5051: doc-aligned
5052: doc-floats
5053: doc-float+
5054: doc-float
5055: doc-faligned
5056: doc-sfloats
5057: doc-sfloat+
5058: doc-sfaligned
5059: doc-dfloats
5060: doc-dfloat+
5061: doc-dfaligned
5062: doc-maxaligned
5063: doc-cfaligned
5064: doc-address-unit-bits
5065:
1.44 crook 5066:
1.32 anton 5067: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5068: @subsection Memory Blocks
5069: @cindex memory block words
1.27 crook 5070: @cindex character strings - moving and copying
5071:
1.49 anton 5072: Memory blocks often represent character strings; For ways of storing
5073: character strings in memory see @ref{String Formats}. For other
5074: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5075:
1.67 anton 5076: A few of these words work on address unit blocks. In that case, you
5077: usually have to insert @code{CHARS} before the word when working on
5078: character strings. Most words work on character blocks, and expect a
5079: char-aligned address.
5080:
5081: When copying characters between overlapping memory regions, use
5082: @code{chars move} or choose carefully between @code{cmove} and
5083: @code{cmove>}.
1.44 crook 5084:
1.1 anton 5085: doc-move
5086: doc-erase
5087: doc-cmove
5088: doc-cmove>
5089: doc-fill
5090: doc-blank
1.21 crook 5091: doc-compare
1.111 anton 5092: doc-str=
5093: doc-str<
5094: doc-string-prefix?
1.21 crook 5095: doc-search
1.27 crook 5096: doc--trailing
5097: doc-/string
1.82 anton 5098: doc-bounds
1.44 crook 5099:
1.111 anton 5100:
1.27 crook 5101: @comment TODO examples
5102:
1.1 anton 5103:
1.26 crook 5104: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5105: @section Control Structures
5106: @cindex control structures
5107:
1.33 anton 5108: Control structures in Forth cannot be used interpretively, only in a
5109: colon definition@footnote{To be precise, they have no interpretation
5110: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5111: not like this limitation, but have not seen a satisfying way around it
5112: yet, although many schemes have been proposed.
1.1 anton 5113:
5114: @menu
1.33 anton 5115: * Selection:: IF ... ELSE ... ENDIF
5116: * Simple Loops:: BEGIN ...
1.29 crook 5117: * Counted Loops:: DO
1.67 anton 5118: * Arbitrary control structures::
5119: * Calls and returns::
1.1 anton 5120: * Exception Handling::
5121: @end menu
5122:
5123: @node Selection, Simple Loops, Control Structures, Control Structures
5124: @subsection Selection
5125: @cindex selection control structures
5126: @cindex control structures for selection
5127:
5128: @cindex @code{IF} control structure
5129: @example
1.29 crook 5130: @i{flag}
1.1 anton 5131: IF
1.29 crook 5132: @i{code}
1.1 anton 5133: ENDIF
5134: @end example
1.21 crook 5135: @noindent
1.33 anton 5136:
1.44 crook 5137: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5138: with any bit set represents truth) @i{code} is executed.
1.33 anton 5139:
1.1 anton 5140: @example
1.29 crook 5141: @i{flag}
1.1 anton 5142: IF
1.29 crook 5143: @i{code1}
1.1 anton 5144: ELSE
1.29 crook 5145: @i{code2}
1.1 anton 5146: ENDIF
5147: @end example
5148:
1.44 crook 5149: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5150: executed.
1.33 anton 5151:
1.1 anton 5152: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5153: standard, and @code{ENDIF} is not, although it is quite popular. We
5154: recommend using @code{ENDIF}, because it is less confusing for people
5155: who also know other languages (and is not prone to reinforcing negative
5156: prejudices against Forth in these people). Adding @code{ENDIF} to a
5157: system that only supplies @code{THEN} is simple:
5158: @example
1.82 anton 5159: : ENDIF POSTPONE then ; immediate
1.1 anton 5160: @end example
5161:
5162: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5163: (adv.)} has the following meanings:
5164: @quotation
5165: ... 2b: following next after in order ... 3d: as a necessary consequence
5166: (if you were there, then you saw them).
5167: @end quotation
5168: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5169: and many other programming languages has the meaning 3d.]
5170:
1.21 crook 5171: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5172: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5173: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5174: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5175: @file{compat/control.fs}.
5176:
5177: @cindex @code{CASE} control structure
5178: @example
1.29 crook 5179: @i{n}
1.1 anton 5180: CASE
1.29 crook 5181: @i{n1} OF @i{code1} ENDOF
5182: @i{n2} OF @i{code2} ENDOF
1.1 anton 5183: @dots{}
1.68 anton 5184: ( n ) @i{default-code} ( n )
1.131 ! anton 5185: ENDCASE ( )
1.1 anton 5186: @end example
5187:
1.131 ! anton 5188: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
! 5189: no @i{ni} matches, the optional @i{default-code} is executed. The
! 5190: optional default case can be added by simply writing the code after
! 5191: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
! 5192: but must not consume it. The value @i{n} is consumed by this
! 5193: construction (either by a OF that matches, or by the ENDCASE, if no OF
! 5194: matches).
1.1 anton 5195:
1.69 anton 5196: @progstyle
1.131 ! anton 5197: To keep the code understandable, you should ensure that you change the
! 5198: stack in the same way (wrt. number and types of stack items consumed
! 5199: and pushed) on all paths through a selection construct.
1.69 anton 5200:
1.1 anton 5201: @node Simple Loops, Counted Loops, Selection, Control Structures
5202: @subsection Simple Loops
5203: @cindex simple loops
5204: @cindex loops without count
5205:
5206: @cindex @code{WHILE} loop
5207: @example
5208: BEGIN
1.29 crook 5209: @i{code1}
5210: @i{flag}
1.1 anton 5211: WHILE
1.29 crook 5212: @i{code2}
1.1 anton 5213: REPEAT
5214: @end example
5215:
1.29 crook 5216: @i{code1} is executed and @i{flag} is computed. If it is true,
5217: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5218: false, execution continues after the @code{REPEAT}.
5219:
5220: @cindex @code{UNTIL} loop
5221: @example
5222: BEGIN
1.29 crook 5223: @i{code}
5224: @i{flag}
1.1 anton 5225: UNTIL
5226: @end example
5227:
1.29 crook 5228: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5229:
1.69 anton 5230: @progstyle
5231: To keep the code understandable, a complete iteration of the loop should
5232: not change the number and types of the items on the stacks.
5233:
1.1 anton 5234: @cindex endless loop
5235: @cindex loops, endless
5236: @example
5237: BEGIN
1.29 crook 5238: @i{code}
1.1 anton 5239: AGAIN
5240: @end example
5241:
5242: This is an endless loop.
5243:
5244: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5245: @subsection Counted Loops
5246: @cindex counted loops
5247: @cindex loops, counted
5248: @cindex @code{DO} loops
5249:
5250: The basic counted loop is:
5251: @example
1.29 crook 5252: @i{limit} @i{start}
1.1 anton 5253: ?DO
1.29 crook 5254: @i{body}
1.1 anton 5255: LOOP
5256: @end example
5257:
1.29 crook 5258: This performs one iteration for every integer, starting from @i{start}
5259: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5260: accessed with @code{i}. For example, the loop:
1.1 anton 5261: @example
5262: 10 0 ?DO
5263: i .
5264: LOOP
5265: @end example
1.21 crook 5266: @noindent
5267: prints @code{0 1 2 3 4 5 6 7 8 9}
5268:
1.1 anton 5269: The index of the innermost loop can be accessed with @code{i}, the index
5270: of the next loop with @code{j}, and the index of the third loop with
5271: @code{k}.
5272:
1.44 crook 5273:
1.1 anton 5274: doc-i
5275: doc-j
5276: doc-k
5277:
1.44 crook 5278:
1.1 anton 5279: The loop control data are kept on the return stack, so there are some
1.21 crook 5280: restrictions on mixing return stack accesses and counted loop words. In
5281: particuler, if you put values on the return stack outside the loop, you
5282: cannot read them inside the loop@footnote{well, not in a way that is
5283: portable.}. If you put values on the return stack within a loop, you
5284: have to remove them before the end of the loop and before accessing the
5285: index of the loop.
1.1 anton 5286:
5287: There are several variations on the counted loop:
5288:
1.21 crook 5289: @itemize @bullet
5290: @item
5291: @code{LEAVE} leaves the innermost counted loop immediately; execution
5292: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5293:
5294: @example
5295: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5296: @end example
5297: prints @code{0 1 2 3}
5298:
1.1 anton 5299:
1.21 crook 5300: @item
5301: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5302: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5303: return stack so @code{EXIT} can get to its return address. For example:
5304:
5305: @example
5306: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5307: @end example
5308: prints @code{0 1 2 3}
5309:
5310:
5311: @item
1.29 crook 5312: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5313: (and @code{LOOP} iterates until they become equal by wrap-around
5314: arithmetic). This behaviour is usually not what you want. Therefore,
5315: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5316: @code{?DO}), which do not enter the loop if @i{start} is greater than
5317: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5318: unsigned loop parameters.
5319:
1.21 crook 5320: @item
5321: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5322: the loop, independent of the loop parameters. Do not use @code{DO}, even
5323: if you know that the loop is entered in any case. Such knowledge tends
5324: to become invalid during maintenance of a program, and then the
5325: @code{DO} will make trouble.
5326:
5327: @item
1.29 crook 5328: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5329: index by @i{n} instead of by 1. The loop is terminated when the border
5330: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5331:
1.21 crook 5332: @example
5333: 4 0 +DO i . 2 +LOOP
5334: @end example
5335: @noindent
5336: prints @code{0 2}
5337:
5338: @example
5339: 4 1 +DO i . 2 +LOOP
5340: @end example
5341: @noindent
5342: prints @code{1 3}
1.1 anton 5343:
1.68 anton 5344: @item
1.1 anton 5345: @cindex negative increment for counted loops
5346: @cindex counted loops with negative increment
1.29 crook 5347: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5348:
1.21 crook 5349: @example
5350: -1 0 ?DO i . -1 +LOOP
5351: @end example
5352: @noindent
5353: prints @code{0 -1}
1.1 anton 5354:
1.21 crook 5355: @example
5356: 0 0 ?DO i . -1 +LOOP
5357: @end example
5358: prints nothing.
1.1 anton 5359:
1.29 crook 5360: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5361: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5362: index by @i{u} each iteration. The loop is terminated when the border
5363: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5364: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5365:
1.21 crook 5366: @example
5367: -2 0 -DO i . 1 -LOOP
5368: @end example
5369: @noindent
5370: prints @code{0 -1}
1.1 anton 5371:
1.21 crook 5372: @example
5373: -1 0 -DO i . 1 -LOOP
5374: @end example
5375: @noindent
5376: prints @code{0}
5377:
5378: @example
5379: 0 0 -DO i . 1 -LOOP
5380: @end example
5381: @noindent
5382: prints nothing.
1.1 anton 5383:
1.21 crook 5384: @end itemize
1.1 anton 5385:
5386: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5387: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5388: for these words that uses only standard words is provided in
5389: @file{compat/loops.fs}.
1.1 anton 5390:
5391:
5392: @cindex @code{FOR} loops
1.26 crook 5393: Another counted loop is:
1.1 anton 5394: @example
1.29 crook 5395: @i{n}
1.1 anton 5396: FOR
1.29 crook 5397: @i{body}
1.1 anton 5398: NEXT
5399: @end example
5400: This is the preferred loop of native code compiler writers who are too
1.26 crook 5401: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5402: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5403: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5404: Forth systems may behave differently, even if they support @code{FOR}
5405: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5406:
5407: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5408: @subsection Arbitrary control structures
5409: @cindex control structures, user-defined
5410:
5411: @cindex control-flow stack
5412: ANS Forth permits and supports using control structures in a non-nested
5413: way. Information about incomplete control structures is stored on the
5414: control-flow stack. This stack may be implemented on the Forth data
5415: stack, and this is what we have done in Gforth.
5416:
5417: @cindex @code{orig}, control-flow stack item
5418: @cindex @code{dest}, control-flow stack item
5419: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5420: entry represents a backward branch target. A few words are the basis for
5421: building any control structure possible (except control structures that
5422: need storage, like calls, coroutines, and backtracking).
5423:
1.44 crook 5424:
1.1 anton 5425: doc-if
5426: doc-ahead
5427: doc-then
5428: doc-begin
5429: doc-until
5430: doc-again
5431: doc-cs-pick
5432: doc-cs-roll
5433:
1.44 crook 5434:
1.21 crook 5435: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5436: manipulate the control-flow stack in a portable way. Without them, you
5437: would need to know how many stack items are occupied by a control-flow
5438: entry (many systems use one cell. In Gforth they currently take three,
5439: but this may change in the future).
5440:
1.1 anton 5441: Some standard control structure words are built from these words:
5442:
1.44 crook 5443:
1.1 anton 5444: doc-else
5445: doc-while
5446: doc-repeat
5447:
1.44 crook 5448:
5449: @noindent
1.1 anton 5450: Gforth adds some more control-structure words:
5451:
1.44 crook 5452:
1.1 anton 5453: doc-endif
5454: doc-?dup-if
5455: doc-?dup-0=-if
5456:
1.44 crook 5457:
5458: @noindent
1.1 anton 5459: Counted loop words constitute a separate group of words:
5460:
1.44 crook 5461:
1.1 anton 5462: doc-?do
5463: doc-+do
5464: doc-u+do
5465: doc--do
5466: doc-u-do
5467: doc-do
5468: doc-for
5469: doc-loop
5470: doc-+loop
5471: doc--loop
5472: doc-next
5473: doc-leave
5474: doc-?leave
5475: doc-unloop
5476: doc-done
5477:
1.44 crook 5478:
1.21 crook 5479: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5480: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5481: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5482: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5483: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5484: resolved (by using one of the loop-ending words or @code{DONE}).
5485:
1.44 crook 5486: @noindent
1.26 crook 5487: Another group of control structure words are:
1.1 anton 5488:
1.44 crook 5489:
1.1 anton 5490: doc-case
5491: doc-endcase
5492: doc-of
5493: doc-endof
5494:
1.44 crook 5495:
1.21 crook 5496: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5497: @code{CS-ROLL}.
1.1 anton 5498:
5499: @subsubsection Programming Style
1.47 crook 5500: @cindex control structures programming style
5501: @cindex programming style, arbitrary control structures
1.1 anton 5502:
5503: In order to ensure readability we recommend that you do not create
5504: arbitrary control structures directly, but define new control structure
5505: words for the control structure you want and use these words in your
1.26 crook 5506: program. For example, instead of writing:
1.1 anton 5507:
5508: @example
1.26 crook 5509: BEGIN
1.1 anton 5510: ...
1.26 crook 5511: IF [ 1 CS-ROLL ]
1.1 anton 5512: ...
1.26 crook 5513: AGAIN THEN
1.1 anton 5514: @end example
5515:
1.21 crook 5516: @noindent
1.1 anton 5517: we recommend defining control structure words, e.g.,
5518:
5519: @example
1.26 crook 5520: : WHILE ( DEST -- ORIG DEST )
5521: POSTPONE IF
5522: 1 CS-ROLL ; immediate
5523:
5524: : REPEAT ( orig dest -- )
5525: POSTPONE AGAIN
5526: POSTPONE THEN ; immediate
1.1 anton 5527: @end example
5528:
1.21 crook 5529: @noindent
1.1 anton 5530: and then using these to create the control structure:
5531:
5532: @example
1.26 crook 5533: BEGIN
1.1 anton 5534: ...
1.26 crook 5535: WHILE
1.1 anton 5536: ...
1.26 crook 5537: REPEAT
1.1 anton 5538: @end example
5539:
5540: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5541: @code{WHILE} are predefined, so in this example it would not be
5542: necessary to define them.
5543:
5544: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5545: @subsection Calls and returns
5546: @cindex calling a definition
5547: @cindex returning from a definition
5548:
1.3 anton 5549: @cindex recursive definitions
5550: A definition can be called simply be writing the name of the definition
1.26 crook 5551: to be called. Normally a definition is invisible during its own
1.3 anton 5552: definition. If you want to write a directly recursive definition, you
1.26 crook 5553: can use @code{recursive} to make the current definition visible, or
5554: @code{recurse} to call the current definition directly.
1.3 anton 5555:
1.44 crook 5556:
1.3 anton 5557: doc-recursive
5558: doc-recurse
5559:
1.44 crook 5560:
1.21 crook 5561: @comment TODO add example of the two recursion methods
1.12 anton 5562: @quotation
5563: @progstyle
5564: I prefer using @code{recursive} to @code{recurse}, because calling the
5565: definition by name is more descriptive (if the name is well-chosen) than
5566: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5567: implementation, it is much better to read (and think) ``now sort the
5568: partitions'' than to read ``now do a recursive call''.
5569: @end quotation
1.3 anton 5570:
1.29 crook 5571: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5572:
5573: @example
1.28 crook 5574: Defer foo
1.3 anton 5575:
5576: : bar ( ... -- ... )
5577: ... foo ... ;
5578:
5579: :noname ( ... -- ... )
5580: ... bar ... ;
5581: IS foo
5582: @end example
5583:
1.44 crook 5584: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5585:
1.26 crook 5586: The current definition returns control to the calling definition when
1.33 anton 5587: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5588:
5589: doc-exit
5590: doc-;s
5591:
1.44 crook 5592:
1.1 anton 5593: @node Exception Handling, , Calls and returns, Control Structures
5594: @subsection Exception Handling
1.26 crook 5595: @cindex exceptions
1.1 anton 5596:
1.68 anton 5597: @c quit is a very bad idea for error handling,
5598: @c because it does not translate into a THROW
5599: @c it also does not belong into this chapter
5600:
5601: If a word detects an error condition that it cannot handle, it can
5602: @code{throw} an exception. In the simplest case, this will terminate
5603: your program, and report an appropriate error.
1.21 crook 5604:
1.68 anton 5605: doc-throw
1.1 anton 5606:
1.69 anton 5607: @code{Throw} consumes a cell-sized error number on the stack. There are
5608: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5609: Gforth (and most other systems) you can use the iors produced by various
5610: words as error numbers (e.g., a typical use of @code{allocate} is
5611: @code{allocate throw}). Gforth also provides the word @code{exception}
5612: to define your own error numbers (with decent error reporting); an ANS
5613: Forth version of this word (but without the error messages) is available
5614: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5615: numbers (anything outside the range -4095..0), but won't get nice error
5616: messages, only numbers. For example, try:
5617:
5618: @example
1.69 anton 5619: -10 throw \ ANS defined
5620: -267 throw \ system defined
5621: s" my error" exception throw \ user defined
5622: 7 throw \ arbitrary number
1.68 anton 5623: @end example
5624:
5625: doc---exception-exception
1.1 anton 5626:
1.69 anton 5627: A common idiom to @code{THROW} a specific error if a flag is true is
5628: this:
5629:
5630: @example
5631: @code{( flag ) 0<> @i{errno} and throw}
5632: @end example
5633:
5634: Your program can provide exception handlers to catch exceptions. An
5635: exception handler can be used to correct the problem, or to clean up
5636: some data structures and just throw the exception to the next exception
5637: handler. Note that @code{throw} jumps to the dynamically innermost
5638: exception handler. The system's exception handler is outermost, and just
5639: prints an error and restarts command-line interpretation (or, in batch
5640: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5641:
1.68 anton 5642: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5643:
1.68 anton 5644: doc-catch
5645:
5646: The most common use of exception handlers is to clean up the state when
5647: an error happens. E.g.,
1.1 anton 5648:
1.26 crook 5649: @example
1.68 anton 5650: base @ >r hex \ actually the hex should be inside foo, or we h
5651: ['] foo catch ( nerror|0 )
5652: r> base !
1.69 anton 5653: ( nerror|0 ) throw \ pass it on
1.26 crook 5654: @end example
1.1 anton 5655:
1.69 anton 5656: A use of @code{catch} for handling the error @code{myerror} might look
5657: like this:
1.44 crook 5658:
1.68 anton 5659: @example
1.69 anton 5660: ['] foo catch
5661: CASE
5662: myerror OF ... ( do something about it ) ENDOF
5663: dup throw \ default: pass other errors on, do nothing on non-errors
5664: ENDCASE
1.68 anton 5665: @end example
1.44 crook 5666:
1.68 anton 5667: Having to wrap the code into a separate word is often cumbersome,
5668: therefore Gforth provides an alternative syntax:
1.1 anton 5669:
5670: @example
1.69 anton 5671: TRY
1.68 anton 5672: @i{code1}
1.69 anton 5673: RECOVER \ optional
1.68 anton 5674: @i{code2} \ optional
1.69 anton 5675: ENDTRY
1.1 anton 5676: @end example
5677:
1.68 anton 5678: This performs @i{Code1}. If @i{code1} completes normally, execution
5679: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5680: reset to the state during @code{try}, the throw value is pushed on the
5681: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5682: through the @code{endtry} into the following code.
1.26 crook 5683:
1.68 anton 5684: doc-try
5685: doc-recover
5686: doc-endtry
1.26 crook 5687:
1.69 anton 5688: The cleanup example from above in this syntax:
1.26 crook 5689:
1.68 anton 5690: @example
1.69 anton 5691: base @ >r TRY
1.68 anton 5692: hex foo \ now the hex is placed correctly
1.69 anton 5693: 0 \ value for throw
1.92 anton 5694: RECOVER ENDTRY
1.68 anton 5695: r> base ! throw
1.1 anton 5696: @end example
5697:
1.69 anton 5698: And here's the error handling example:
1.1 anton 5699:
1.68 anton 5700: @example
1.69 anton 5701: TRY
1.68 anton 5702: foo
1.69 anton 5703: RECOVER
5704: CASE
5705: myerror OF ... ( do something about it ) ENDOF
5706: throw \ pass other errors on
5707: ENDCASE
5708: ENDTRY
1.68 anton 5709: @end example
1.1 anton 5710:
1.69 anton 5711: @progstyle
5712: As usual, you should ensure that the stack depth is statically known at
5713: the end: either after the @code{throw} for passing on errors, or after
5714: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5715: selection construct for handling the error).
5716:
1.68 anton 5717: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5718: and you can provide an error message. @code{Abort} just produces an
5719: ``Aborted'' error.
1.1 anton 5720:
1.68 anton 5721: The problem with these words is that exception handlers cannot
5722: differentiate between different @code{abort"}s; they just look like
5723: @code{-2 throw} to them (the error message cannot be accessed by
5724: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5725: exception handlers.
1.44 crook 5726:
1.68 anton 5727: doc-abort"
1.26 crook 5728: doc-abort
1.29 crook 5729:
5730:
1.44 crook 5731:
1.29 crook 5732: @c -------------------------------------------------------------
1.47 crook 5733: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5734: @section Defining Words
5735: @cindex defining words
5736:
1.47 crook 5737: Defining words are used to extend Forth by creating new entries in the dictionary.
5738:
1.29 crook 5739: @menu
1.67 anton 5740: * CREATE::
1.44 crook 5741: * Variables:: Variables and user variables
1.67 anton 5742: * Constants::
1.44 crook 5743: * Values:: Initialised variables
1.67 anton 5744: * Colon Definitions::
1.44 crook 5745: * Anonymous Definitions:: Definitions without names
1.69 anton 5746: * Supplying names:: Passing definition names as strings
1.67 anton 5747: * User-defined Defining Words::
1.44 crook 5748: * Deferred words:: Allow forward references
1.67 anton 5749: * Aliases::
1.29 crook 5750: @end menu
5751:
1.44 crook 5752: @node CREATE, Variables, Defining Words, Defining Words
5753: @subsection @code{CREATE}
1.29 crook 5754: @cindex simple defining words
5755: @cindex defining words, simple
5756:
5757: Defining words are used to create new entries in the dictionary. The
5758: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5759: this:
5760:
5761: @example
5762: CREATE new-word1
5763: @end example
5764:
1.69 anton 5765: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5766: input stream (@code{new-word1} in our example). It generates a
5767: dictionary entry for @code{new-word1}. When @code{new-word1} is
5768: executed, all that it does is leave an address on the stack. The address
5769: represents the value of the data space pointer (@code{HERE}) at the time
5770: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5771: associating a name with the address of a region of memory.
1.29 crook 5772:
1.34 anton 5773: doc-create
5774:
1.69 anton 5775: Note that in ANS Forth guarantees only for @code{create} that its body
5776: is in dictionary data space (i.e., where @code{here}, @code{allot}
5777: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5778: @code{create}d words can be modified with @code{does>}
5779: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5780: can only be applied to @code{create}d words.
5781:
1.29 crook 5782: By extending this example to reserve some memory in data space, we end
1.69 anton 5783: up with something like a @i{variable}. Here are two different ways to do
5784: it:
1.29 crook 5785:
5786: @example
5787: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5788: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5789: @end example
5790:
5791: The variable can be examined and modified using @code{@@} (``fetch'') and
5792: @code{!} (``store'') like this:
5793:
5794: @example
5795: new-word2 @@ . \ get address, fetch from it and display
5796: 1234 new-word2 ! \ new value, get address, store to it
5797: @end example
5798:
1.44 crook 5799: @cindex arrays
5800: A similar mechanism can be used to create arrays. For example, an
5801: 80-character text input buffer:
1.29 crook 5802:
5803: @example
1.44 crook 5804: CREATE text-buf 80 chars allot
5805:
5806: text-buf 0 chars c@@ \ the 1st character (offset 0)
5807: text-buf 3 chars c@@ \ the 4th character (offset 3)
5808: @end example
1.29 crook 5809:
1.44 crook 5810: You can build arbitrarily complex data structures by allocating
1.49 anton 5811: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5812: learn about some Gforth tools that make it easier,
1.49 anton 5813: @xref{Structures}.
1.44 crook 5814:
5815:
5816: @node Variables, Constants, CREATE, Defining Words
5817: @subsection Variables
5818: @cindex variables
5819:
5820: The previous section showed how a sequence of commands could be used to
5821: generate a variable. As a final refinement, the whole code sequence can
5822: be wrapped up in a defining word (pre-empting the subject of the next
5823: section), making it easier to create new variables:
5824:
5825: @example
5826: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5827: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5828:
5829: myvariableX foo \ variable foo starts off with an unknown value
5830: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5831:
5832: 45 3 * foo ! \ set foo to 135
5833: 1234 joe ! \ set joe to 1234
5834: 3 joe +! \ increment joe by 3.. to 1237
5835: @end example
5836:
5837: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5838: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5839: guarantee that a @code{Variable} is initialised when it is created
5840: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5841: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5842: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5843: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5844: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5845: store a boolean, you can use @code{on} and @code{off} to toggle its
5846: state.
1.29 crook 5847:
1.34 anton 5848: doc-variable
5849: doc-2variable
5850: doc-fvariable
5851:
1.29 crook 5852: @cindex user variables
5853: @cindex user space
5854: The defining word @code{User} behaves in the same way as @code{Variable}.
5855: The difference is that it reserves space in @i{user (data) space} rather
5856: than normal data space. In a Forth system that has a multi-tasker, each
5857: task has its own set of user variables.
5858:
1.34 anton 5859: doc-user
1.67 anton 5860: @c doc-udp
5861: @c doc-uallot
1.34 anton 5862:
1.29 crook 5863: @comment TODO is that stuff about user variables strictly correct? Is it
5864: @comment just terminal tasks that have user variables?
5865: @comment should document tasker.fs (with some examples) elsewhere
5866: @comment in this manual, then expand on user space and user variables.
5867:
1.44 crook 5868: @node Constants, Values, Variables, Defining Words
5869: @subsection Constants
5870: @cindex constants
5871:
5872: @code{Constant} allows you to declare a fixed value and refer to it by
5873: name. For example:
1.29 crook 5874:
5875: @example
5876: 12 Constant INCHES-PER-FOOT
5877: 3E+08 fconstant SPEED-O-LIGHT
5878: @end example
5879:
5880: A @code{Variable} can be both read and written, so its run-time
5881: behaviour is to supply an address through which its current value can be
5882: manipulated. In contrast, the value of a @code{Constant} cannot be
5883: changed once it has been declared@footnote{Well, often it can be -- but
5884: not in a Standard, portable way. It's safer to use a @code{Value} (read
5885: on).} so it's not necessary to supply the address -- it is more
5886: efficient to return the value of the constant directly. That's exactly
5887: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5888: the top of the stack (You can find one
5889: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5890:
1.69 anton 5891: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5892: double and floating-point constants, respectively.
5893:
1.34 anton 5894: doc-constant
5895: doc-2constant
5896: doc-fconstant
5897:
5898: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5899: @c nac-> How could that not be true in an ANS Forth? You can't define a
5900: @c constant, use it and then delete the definition of the constant..
1.69 anton 5901:
5902: @c anton->An ANS Forth system can compile a constant to a literal; On
5903: @c decompilation you would see only the number, just as if it had been used
5904: @c in the first place. The word will stay, of course, but it will only be
5905: @c used by the text interpreter (no run-time duties, except when it is
5906: @c POSTPONEd or somesuch).
5907:
5908: @c nac:
1.44 crook 5909: @c I agree that it's rather deep, but IMO it is an important difference
5910: @c relative to other programming languages.. often it's annoying: it
5911: @c certainly changes my programming style relative to C.
5912:
1.69 anton 5913: @c anton: In what way?
5914:
1.29 crook 5915: Constants in Forth behave differently from their equivalents in other
5916: programming languages. In other languages, a constant (such as an EQU in
5917: assembler or a #define in C) only exists at compile-time; in the
5918: executable program the constant has been translated into an absolute
5919: number and, unless you are using a symbolic debugger, it's impossible to
5920: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5921: an entry in the header space and remains there after the code that uses
5922: it has been defined. In fact, it must remain in the dictionary since it
5923: has run-time duties to perform. For example:
1.29 crook 5924:
5925: @example
5926: 12 Constant INCHES-PER-FOOT
5927: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5928: @end example
5929:
5930: @cindex in-lining of constants
5931: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5932: associated with the constant @code{INCHES-PER-FOOT}. If you use
5933: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5934: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5935: attempt to optimise constants by in-lining them where they are used. You
5936: can force Gforth to in-line a constant like this:
5937:
5938: @example
5939: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5940: @end example
5941:
5942: If you use @code{see} to decompile @i{this} version of
5943: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5944: longer present. To understand how this works, read
5945: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5946:
5947: In-lining constants in this way might improve execution time
5948: fractionally, and can ensure that a constant is now only referenced at
5949: compile-time. However, the definition of the constant still remains in
5950: the dictionary. Some Forth compilers provide a mechanism for controlling
5951: a second dictionary for holding transient words such that this second
5952: dictionary can be deleted later in order to recover memory
5953: space. However, there is no standard way of doing this.
5954:
5955:
1.44 crook 5956: @node Values, Colon Definitions, Constants, Defining Words
5957: @subsection Values
5958: @cindex values
1.34 anton 5959:
1.69 anton 5960: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5961: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5962: (not in ANS Forth) you can access (and change) a @code{value} also with
5963: @code{>body}.
5964:
5965: Here are some
5966: examples:
1.29 crook 5967:
5968: @example
1.69 anton 5969: 12 Value APPLES \ Define APPLES with an initial value of 12
5970: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5971: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5972: APPLES \ puts 35 on the top of the stack.
1.29 crook 5973: @end example
5974:
1.44 crook 5975: doc-value
5976: doc-to
1.29 crook 5977:
1.35 anton 5978:
1.69 anton 5979:
1.44 crook 5980: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5981: @subsection Colon Definitions
5982: @cindex colon definitions
1.35 anton 5983:
5984: @example
1.44 crook 5985: : name ( ... -- ... )
5986: word1 word2 word3 ;
1.29 crook 5987: @end example
5988:
1.44 crook 5989: @noindent
5990: Creates a word called @code{name} that, upon execution, executes
5991: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 5992:
1.49 anton 5993: The explanation above is somewhat superficial. For simple examples of
5994: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 5995: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 5996: Compilation Semantics}.
1.29 crook 5997:
1.44 crook 5998: doc-:
5999: doc-;
1.1 anton 6000:
1.34 anton 6001:
1.69 anton 6002: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6003: @subsection Anonymous Definitions
6004: @cindex colon definitions
6005: @cindex defining words without name
1.34 anton 6006:
1.44 crook 6007: Sometimes you want to define an @dfn{anonymous word}; a word without a
6008: name. You can do this with:
1.1 anton 6009:
1.44 crook 6010: doc-:noname
1.1 anton 6011:
1.44 crook 6012: This leaves the execution token for the word on the stack after the
6013: closing @code{;}. Here's an example in which a deferred word is
6014: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6015:
1.29 crook 6016: @example
1.44 crook 6017: Defer deferred
6018: :noname ( ... -- ... )
6019: ... ;
6020: IS deferred
1.29 crook 6021: @end example
1.26 crook 6022:
1.44 crook 6023: @noindent
6024: Gforth provides an alternative way of doing this, using two separate
6025: words:
1.27 crook 6026:
1.44 crook 6027: doc-noname
6028: @cindex execution token of last defined word
1.116 anton 6029: doc-latestxt
1.1 anton 6030:
1.44 crook 6031: @noindent
6032: The previous example can be rewritten using @code{noname} and
1.116 anton 6033: @code{latestxt}:
1.1 anton 6034:
1.26 crook 6035: @example
1.44 crook 6036: Defer deferred
6037: noname : ( ... -- ... )
6038: ... ;
1.116 anton 6039: latestxt IS deferred
1.26 crook 6040: @end example
1.1 anton 6041:
1.29 crook 6042: @noindent
1.44 crook 6043: @code{noname} works with any defining word, not just @code{:}.
6044:
1.116 anton 6045: @code{latestxt} also works when the last word was not defined as
1.71 anton 6046: @code{noname}. It does not work for combined words, though. It also has
6047: the useful property that is is valid as soon as the header for a
6048: definition has been built. Thus:
1.44 crook 6049:
6050: @example
1.116 anton 6051: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6052: @end example
1.1 anton 6053:
1.44 crook 6054: @noindent
6055: prints 3 numbers; the last two are the same.
1.26 crook 6056:
1.69 anton 6057: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6058: @subsection Supplying the name of a defined word
6059: @cindex names for defined words
6060: @cindex defining words, name given in a string
6061:
6062: By default, a defining word takes the name for the defined word from the
6063: input stream. Sometimes you want to supply the name from a string. You
6064: can do this with:
6065:
6066: doc-nextname
6067:
6068: For example:
6069:
6070: @example
6071: s" foo" nextname create
6072: @end example
6073:
6074: @noindent
6075: is equivalent to:
6076:
6077: @example
6078: create foo
6079: @end example
6080:
6081: @noindent
6082: @code{nextname} works with any defining word.
6083:
1.1 anton 6084:
1.69 anton 6085: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6086: @subsection User-defined Defining Words
6087: @cindex user-defined defining words
6088: @cindex defining words, user-defined
1.1 anton 6089:
1.29 crook 6090: You can create a new defining word by wrapping defining-time code around
6091: an existing defining word and putting the sequence in a colon
1.69 anton 6092: definition.
6093:
6094: @c anton: This example is very complex and leads in a quite different
6095: @c direction from the CREATE-DOES> stuff that follows. It should probably
6096: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6097: @c subsection of Defining Words)
6098:
6099: For example, suppose that you have a word @code{stats} that
1.29 crook 6100: gathers statistics about colon definitions given the @i{xt} of the
6101: definition, and you want every colon definition in your application to
6102: make a call to @code{stats}. You can define and use a new version of
6103: @code{:} like this:
6104:
6105: @example
6106: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6107: ... ; \ other code
6108:
1.116 anton 6109: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6110:
6111: my: foo + - ;
6112: @end example
6113:
6114: When @code{foo} is defined using @code{my:} these steps occur:
6115:
6116: @itemize @bullet
6117: @item
6118: @code{my:} is executed.
6119: @item
6120: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6121: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6122: the input stream for a name, builds a dictionary header for the name
6123: @code{foo} and switches @code{state} from interpret to compile.
6124: @item
1.116 anton 6125: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6126: being defined -- @code{foo} -- onto the stack.
6127: @item
6128: The code that was produced by @code{postpone literal} is executed; this
6129: causes the value on the stack to be compiled as a literal in the code
6130: area of @code{foo}.
6131: @item
6132: The code @code{['] stats} compiles a literal into the definition of
6133: @code{my:}. When @code{compile,} is executed, that literal -- the
6134: execution token for @code{stats} -- is layed down in the code area of
6135: @code{foo} , following the literal@footnote{Strictly speaking, the
6136: mechanism that @code{compile,} uses to convert an @i{xt} into something
6137: in the code area is implementation-dependent. A threaded implementation
6138: might spit out the execution token directly whilst another
6139: implementation might spit out a native code sequence.}.
6140: @item
6141: At this point, the execution of @code{my:} is complete, and control
6142: returns to the text interpreter. The text interpreter is in compile
6143: state, so subsequent text @code{+ -} is compiled into the definition of
6144: @code{foo} and the @code{;} terminates the definition as always.
6145: @end itemize
6146:
6147: You can use @code{see} to decompile a word that was defined using
6148: @code{my:} and see how it is different from a normal @code{:}
6149: definition. For example:
6150:
6151: @example
6152: : bar + - ; \ like foo but using : rather than my:
6153: see bar
6154: : bar
6155: + - ;
6156: see foo
6157: : foo
6158: 107645672 stats + - ;
6159:
6160: \ use ' stats . to show that 107645672 is the xt for stats
6161: @end example
6162:
6163: You can use techniques like this to make new defining words in terms of
6164: @i{any} existing defining word.
1.1 anton 6165:
6166:
1.29 crook 6167: @cindex defining defining words
1.26 crook 6168: @cindex @code{CREATE} ... @code{DOES>}
6169: If you want the words defined with your defining words to behave
6170: differently from words defined with standard defining words, you can
6171: write your defining word like this:
1.1 anton 6172:
6173: @example
1.26 crook 6174: : def-word ( "name" -- )
1.29 crook 6175: CREATE @i{code1}
1.26 crook 6176: DOES> ( ... -- ... )
1.29 crook 6177: @i{code2} ;
1.26 crook 6178:
6179: def-word name
1.1 anton 6180: @end example
6181:
1.29 crook 6182: @cindex child words
6183: This fragment defines a @dfn{defining word} @code{def-word} and then
6184: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6185: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6186: is not executed at this time. The word @code{name} is sometimes called a
6187: @dfn{child} of @code{def-word}.
6188:
6189: When you execute @code{name}, the address of the body of @code{name} is
6190: put on the data stack and @i{code2} is executed (the address of the body
6191: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6192: @code{CREATE}, i.e., the address a @code{create}d word returns by
6193: default).
6194:
6195: @c anton:
6196: @c www.dictionary.com says:
6197: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6198: @c several generations of absence, usually caused by the chance
6199: @c recombination of genes. 2.An individual or a part that exhibits
6200: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6201: @c of previous behavior after a period of absence.
6202: @c
6203: @c Doesn't seem to fit.
1.29 crook 6204:
1.69 anton 6205: @c @cindex atavism in child words
1.33 anton 6206: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6207: similarly; they all have a common run-time behaviour determined by
6208: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6209: body of the child word. The structure of the data is common to all
6210: children of @code{def-word}, but the data values are specific -- and
6211: private -- to each child word. When a child word is executed, the
6212: address of its private data area is passed as a parameter on TOS to be
6213: used and manipulated@footnote{It is legitimate both to read and write to
6214: this data area.} by @i{code2}.
1.29 crook 6215:
6216: The two fragments of code that make up the defining words act (are
6217: executed) at two completely separate times:
1.1 anton 6218:
1.29 crook 6219: @itemize @bullet
6220: @item
6221: At @i{define time}, the defining word executes @i{code1} to generate a
6222: child word
6223: @item
6224: At @i{child execution time}, when a child word is invoked, @i{code2}
6225: is executed, using parameters (data) that are private and specific to
6226: the child word.
6227: @end itemize
6228:
1.44 crook 6229: Another way of understanding the behaviour of @code{def-word} and
6230: @code{name} is to say that, if you make the following definitions:
1.33 anton 6231: @example
6232: : def-word1 ( "name" -- )
6233: CREATE @i{code1} ;
6234:
6235: : action1 ( ... -- ... )
6236: @i{code2} ;
6237:
6238: def-word1 name1
6239: @end example
6240:
1.44 crook 6241: @noindent
6242: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6243:
1.29 crook 6244: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6245:
1.1 anton 6246: @example
1.29 crook 6247: : CONSTANT ( w "name" -- )
6248: CREATE ,
1.26 crook 6249: DOES> ( -- w )
6250: @@ ;
1.1 anton 6251: @end example
6252:
1.29 crook 6253: @comment There is a beautiful description of how this works and what
6254: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6255: @comment commentary on the Counting Fruits problem.
6256:
6257: When you create a constant with @code{5 CONSTANT five}, a set of
6258: define-time actions take place; first a new word @code{five} is created,
6259: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6260: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6261: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6262: no code of its own; it simply contains a data field and a pointer to the
6263: code that follows @code{DOES>} in its defining word. That makes words
6264: created in this way very compact.
6265:
6266: The final example in this section is intended to remind you that space
6267: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6268: both read and written by a Standard program@footnote{Exercise: use this
6269: example as a starting point for your own implementation of @code{Value}
6270: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6271: @code{[']}.}:
6272:
6273: @example
6274: : foo ( "name" -- )
6275: CREATE -1 ,
6276: DOES> ( -- )
1.33 anton 6277: @@ . ;
1.29 crook 6278:
6279: foo first-word
6280: foo second-word
6281:
6282: 123 ' first-word >BODY !
6283: @end example
6284:
6285: If @code{first-word} had been a @code{CREATE}d word, we could simply
6286: have executed it to get the address of its data field. However, since it
6287: was defined to have @code{DOES>} actions, its execution semantics are to
6288: perform those @code{DOES>} actions. To get the address of its data field
6289: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6290: translate the xt into the address of the data field. When you execute
6291: @code{first-word}, it will display @code{123}. When you execute
6292: @code{second-word} it will display @code{-1}.
1.26 crook 6293:
6294: @cindex stack effect of @code{DOES>}-parts
6295: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6296: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6297: the stack effect of the defined words, not the stack effect of the
6298: following code (the following code expects the address of the body on
6299: the top of stack, which is not reflected in the stack comment). This is
6300: the convention that I use and recommend (it clashes a bit with using
6301: locals declarations for stack effect specification, though).
1.1 anton 6302:
1.53 anton 6303: @menu
6304: * CREATE..DOES> applications::
6305: * CREATE..DOES> details::
1.63 anton 6306: * Advanced does> usage example::
1.91 anton 6307: * @code{Const-does>}::
1.53 anton 6308: @end menu
6309:
6310: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6311: @subsubsection Applications of @code{CREATE..DOES>}
6312: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6313:
1.26 crook 6314: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6315:
1.26 crook 6316: @cindex factoring similar colon definitions
6317: When you see a sequence of code occurring several times, and you can
6318: identify a meaning, you will factor it out as a colon definition. When
6319: you see similar colon definitions, you can factor them using
6320: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6321: that look very similar:
1.1 anton 6322: @example
1.26 crook 6323: : ori, ( reg-target reg-source n -- )
6324: 0 asm-reg-reg-imm ;
6325: : andi, ( reg-target reg-source n -- )
6326: 1 asm-reg-reg-imm ;
1.1 anton 6327: @end example
6328:
1.26 crook 6329: @noindent
6330: This could be factored with:
6331: @example
6332: : reg-reg-imm ( op-code -- )
6333: CREATE ,
6334: DOES> ( reg-target reg-source n -- )
6335: @@ asm-reg-reg-imm ;
6336:
6337: 0 reg-reg-imm ori,
6338: 1 reg-reg-imm andi,
6339: @end example
1.1 anton 6340:
1.26 crook 6341: @cindex currying
6342: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6343: supply a part of the parameters for a word (known as @dfn{currying} in
6344: the functional language community). E.g., @code{+} needs two
6345: parameters. Creating versions of @code{+} with one parameter fixed can
6346: be done like this:
1.82 anton 6347:
1.1 anton 6348: @example
1.82 anton 6349: : curry+ ( n1 "name" -- )
1.26 crook 6350: CREATE ,
6351: DOES> ( n2 -- n1+n2 )
6352: @@ + ;
6353:
6354: 3 curry+ 3+
6355: -2 curry+ 2-
1.1 anton 6356: @end example
6357:
1.91 anton 6358:
1.63 anton 6359: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6360: @subsubsection The gory details of @code{CREATE..DOES>}
6361: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6362:
1.26 crook 6363: doc-does>
1.1 anton 6364:
1.26 crook 6365: @cindex @code{DOES>} in a separate definition
6366: This means that you need not use @code{CREATE} and @code{DOES>} in the
6367: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6368: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6369: @example
6370: : does1
6371: DOES> ( ... -- ... )
1.44 crook 6372: ... ;
6373:
6374: : does2
6375: DOES> ( ... -- ... )
6376: ... ;
6377:
6378: : def-word ( ... -- ... )
6379: create ...
6380: IF
6381: does1
6382: ELSE
6383: does2
6384: ENDIF ;
6385: @end example
6386:
6387: In this example, the selection of whether to use @code{does1} or
1.69 anton 6388: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6389: @code{CREATE}d.
6390:
6391: @cindex @code{DOES>} in interpretation state
6392: In a standard program you can apply a @code{DOES>}-part only if the last
6393: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6394: will override the behaviour of the last word defined in any case. In a
6395: standard program, you can use @code{DOES>} only in a colon
6396: definition. In Gforth, you can also use it in interpretation state, in a
6397: kind of one-shot mode; for example:
6398: @example
6399: CREATE name ( ... -- ... )
6400: @i{initialization}
6401: DOES>
6402: @i{code} ;
6403: @end example
6404:
6405: @noindent
6406: is equivalent to the standard:
6407: @example
6408: :noname
6409: DOES>
6410: @i{code} ;
6411: CREATE name EXECUTE ( ... -- ... )
6412: @i{initialization}
6413: @end example
6414:
1.53 anton 6415: doc->body
6416:
1.91 anton 6417: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6418: @subsubsection Advanced does> usage example
6419:
6420: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6421: for disassembling instructions, that follow a very repetetive scheme:
6422:
6423: @example
6424: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6425: @var{entry-num} cells @var{table} + !
6426: @end example
6427:
6428: Of course, this inspires the idea to factor out the commonalities to
6429: allow a definition like
6430:
6431: @example
6432: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6433: @end example
6434:
6435: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6436: correlated. Moreover, before I wrote the disassembler, there already
6437: existed code that defines instructions like this:
1.63 anton 6438:
6439: @example
6440: @var{entry-num} @var{inst-format} @var{inst-name}
6441: @end example
6442:
6443: This code comes from the assembler and resides in
6444: @file{arch/mips/insts.fs}.
6445:
6446: So I had to define the @var{inst-format} words that performed the scheme
6447: above when executed. At first I chose to use run-time code-generation:
6448:
6449: @example
6450: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6451: :noname Postpone @var{disasm-operands}
6452: name Postpone sliteral Postpone type Postpone ;
6453: swap cells @var{table} + ! ;
6454: @end example
6455:
6456: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6457:
1.63 anton 6458: An alternative would have been to write this using
6459: @code{create}/@code{does>}:
6460:
6461: @example
6462: : @var{inst-format} ( entry-num "name" -- )
6463: here name string, ( entry-num c-addr ) \ parse and save "name"
6464: noname create , ( entry-num )
1.116 anton 6465: latestxt swap cells @var{table} + !
1.63 anton 6466: does> ( addr w -- )
6467: \ disassemble instruction w at addr
6468: @@ >r
6469: @var{disasm-operands}
6470: r> count type ;
6471: @end example
6472:
6473: Somehow the first solution is simpler, mainly because it's simpler to
6474: shift a string from definition-time to use-time with @code{sliteral}
6475: than with @code{string,} and friends.
6476:
6477: I wrote a lot of words following this scheme and soon thought about
6478: factoring out the commonalities among them. Note that this uses a
6479: two-level defining word, i.e., a word that defines ordinary defining
6480: words.
6481:
6482: This time a solution involving @code{postpone} and friends seemed more
6483: difficult (try it as an exercise), so I decided to use a
6484: @code{create}/@code{does>} word; since I was already at it, I also used
6485: @code{create}/@code{does>} for the lower level (try using
6486: @code{postpone} etc. as an exercise), resulting in the following
6487: definition:
6488:
6489: @example
6490: : define-format ( disasm-xt table-xt -- )
6491: \ define an instruction format that uses disasm-xt for
6492: \ disassembling and enters the defined instructions into table
6493: \ table-xt
6494: create 2,
6495: does> ( u "inst" -- )
6496: \ defines an anonymous word for disassembling instruction inst,
6497: \ and enters it as u-th entry into table-xt
6498: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6499: noname create 2, \ define anonymous word
1.116 anton 6500: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6501: does> ( addr w -- )
6502: \ disassemble instruction w at addr
6503: 2@@ >r ( addr w disasm-xt R: c-addr )
6504: execute ( R: c-addr ) \ disassemble operands
6505: r> count type ; \ print name
6506: @end example
6507:
6508: Note that the tables here (in contrast to above) do the @code{cells +}
6509: by themselves (that's why you have to pass an xt). This word is used in
6510: the following way:
6511:
6512: @example
6513: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6514: @end example
6515:
1.71 anton 6516: As shown above, the defined instruction format is then used like this:
6517:
6518: @example
6519: @var{entry-num} @var{inst-format} @var{inst-name}
6520: @end example
6521:
1.63 anton 6522: In terms of currying, this kind of two-level defining word provides the
6523: parameters in three stages: first @var{disasm-operands} and @var{table},
6524: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6525: the instruction to be disassembled.
6526:
6527: Of course this did not quite fit all the instruction format names used
6528: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6529: the parameters into the right form.
6530:
6531: If you have trouble following this section, don't worry. First, this is
6532: involved and takes time (and probably some playing around) to
6533: understand; second, this is the first two-level
6534: @code{create}/@code{does>} word I have written in seventeen years of
6535: Forth; and if I did not have @file{insts.fs} to start with, I may well
6536: have elected to use just a one-level defining word (with some repeating
6537: of parameters when using the defining word). So it is not necessary to
6538: understand this, but it may improve your understanding of Forth.
1.44 crook 6539:
6540:
1.91 anton 6541: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6542: @subsubsection @code{Const-does>}
6543:
6544: A frequent use of @code{create}...@code{does>} is for transferring some
6545: values from definition-time to run-time. Gforth supports this use with
6546:
6547: doc-const-does>
6548:
6549: A typical use of this word is:
6550:
6551: @example
6552: : curry+ ( n1 "name" -- )
6553: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6554: + ;
6555:
6556: 3 curry+ 3+
6557: @end example
6558:
6559: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6560: definition to run-time.
6561:
6562: The advantages of using @code{const-does>} are:
6563:
6564: @itemize
6565:
6566: @item
6567: You don't have to deal with storing and retrieving the values, i.e.,
6568: your program becomes more writable and readable.
6569:
6570: @item
6571: When using @code{does>}, you have to introduce a @code{@@} that cannot
6572: be optimized away (because you could change the data using
6573: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6574:
6575: @end itemize
6576:
6577: An ANS Forth implementation of @code{const-does>} is available in
6578: @file{compat/const-does.fs}.
6579:
6580:
1.44 crook 6581: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6582: @subsection Deferred words
6583: @cindex deferred words
6584:
6585: The defining word @code{Defer} allows you to define a word by name
6586: without defining its behaviour; the definition of its behaviour is
6587: deferred. Here are two situation where this can be useful:
6588:
6589: @itemize @bullet
6590: @item
6591: Where you want to allow the behaviour of a word to be altered later, and
6592: for all precompiled references to the word to change when its behaviour
6593: is changed.
6594: @item
6595: For mutual recursion; @xref{Calls and returns}.
6596: @end itemize
6597:
6598: In the following example, @code{foo} always invokes the version of
6599: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6600: always invokes the version that prints ``@code{Hello}''. There is no way
6601: of getting @code{foo} to use the later version without re-ordering the
6602: source code and recompiling it.
6603:
6604: @example
6605: : greet ." Good morning" ;
6606: : foo ... greet ... ;
6607: : greet ." Hello" ;
6608: : bar ... greet ... ;
6609: @end example
6610:
6611: This problem can be solved by defining @code{greet} as a @code{Defer}red
6612: word. The behaviour of a @code{Defer}red word can be defined and
6613: redefined at any time by using @code{IS} to associate the xt of a
6614: previously-defined word with it. The previous example becomes:
6615:
6616: @example
1.69 anton 6617: Defer greet ( -- )
1.44 crook 6618: : foo ... greet ... ;
6619: : bar ... greet ... ;
1.69 anton 6620: : greet1 ( -- ) ." Good morning" ;
6621: : greet2 ( -- ) ." Hello" ;
1.44 crook 6622: ' greet2 <IS> greet \ make greet behave like greet2
6623: @end example
6624:
1.69 anton 6625: @progstyle
6626: You should write a stack comment for every deferred word, and put only
6627: XTs into deferred words that conform to this stack effect. Otherwise
6628: it's too difficult to use the deferred word.
6629:
1.44 crook 6630: A deferred word can be used to improve the statistics-gathering example
6631: from @ref{User-defined Defining Words}; rather than edit the
6632: application's source code to change every @code{:} to a @code{my:}, do
6633: this:
6634:
6635: @example
6636: : real: : ; \ retain access to the original
6637: defer : \ redefine as a deferred word
1.69 anton 6638: ' my: <IS> : \ use special version of :
1.44 crook 6639: \
6640: \ load application here
6641: \
1.69 anton 6642: ' real: <IS> : \ go back to the original
1.44 crook 6643: @end example
6644:
6645:
6646: One thing to note is that @code{<IS>} consumes its name when it is
6647: executed. If you want to specify the name at compile time, use
6648: @code{[IS]}:
6649:
6650: @example
6651: : set-greet ( xt -- )
6652: [IS] greet ;
6653:
6654: ' greet1 set-greet
6655: @end example
6656:
1.69 anton 6657: A deferred word can only inherit execution semantics from the xt
6658: (because that is all that an xt can represent -- for more discussion of
6659: this @pxref{Tokens for Words}); by default it will have default
6660: interpretation and compilation semantics deriving from this execution
6661: semantics. However, you can change the interpretation and compilation
6662: semantics of the deferred word in the usual ways:
1.44 crook 6663:
6664: @example
6665: : bar .... ; compile-only
6666: Defer fred immediate
6667: Defer jim
6668:
6669: ' bar <IS> jim \ jim has default semantics
6670: ' bar <IS> fred \ fred is immediate
6671: @end example
6672:
6673: doc-defer
6674: doc-<is>
6675: doc-[is]
6676: doc-is
6677: @comment TODO document these: what's defers [is]
6678: doc-what's
6679: doc-defers
6680:
6681: @c Use @code{words-deferred} to see a list of deferred words.
6682:
6683: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6684: are provided in @file{compat/defer.fs}.
6685:
6686:
1.69 anton 6687: @node Aliases, , Deferred words, Defining Words
1.44 crook 6688: @subsection Aliases
6689: @cindex aliases
1.1 anton 6690:
1.44 crook 6691: The defining word @code{Alias} allows you to define a word by name that
6692: has the same behaviour as some other word. Here are two situation where
6693: this can be useful:
1.1 anton 6694:
1.44 crook 6695: @itemize @bullet
6696: @item
6697: When you want access to a word's definition from a different word list
6698: (for an example of this, see the definition of the @code{Root} word list
6699: in the Gforth source).
6700: @item
6701: When you want to create a synonym; a definition that can be known by
6702: either of two names (for example, @code{THEN} and @code{ENDIF} are
6703: aliases).
6704: @end itemize
1.1 anton 6705:
1.69 anton 6706: Like deferred words, an alias has default compilation and interpretation
6707: semantics at the beginning (not the modifications of the other word),
6708: but you can change them in the usual ways (@code{immediate},
6709: @code{compile-only}). For example:
1.1 anton 6710:
6711: @example
1.44 crook 6712: : foo ... ; immediate
6713:
6714: ' foo Alias bar \ bar is not an immediate word
6715: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6716: @end example
6717:
1.44 crook 6718: Words that are aliases have the same xt, different headers in the
6719: dictionary, and consequently different name tokens (@pxref{Tokens for
6720: Words}) and possibly different immediate flags. An alias can only have
6721: default or immediate compilation semantics; you can define aliases for
6722: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6723:
1.44 crook 6724: doc-alias
1.1 anton 6725:
6726:
1.47 crook 6727: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6728: @section Interpretation and Compilation Semantics
1.26 crook 6729: @cindex semantics, interpretation and compilation
1.1 anton 6730:
1.71 anton 6731: @c !! state and ' are used without explanation
6732: @c example for immediate/compile-only? or is the tutorial enough
6733:
1.26 crook 6734: @cindex interpretation semantics
1.71 anton 6735: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6736: interpreter does when it encounters the word in interpret state. It also
6737: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6738: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6739: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6740: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6741:
1.26 crook 6742: @cindex compilation semantics
1.71 anton 6743: The @dfn{compilation semantics} of a (named) word are what the text
6744: interpreter does when it encounters the word in compile state. It also
6745: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6746: compiles@footnote{In standard terminology, ``appends to the current
6747: definition''.} the compilation semantics of @i{word}.
1.1 anton 6748:
1.26 crook 6749: @cindex execution semantics
6750: The standard also talks about @dfn{execution semantics}. They are used
6751: only for defining the interpretation and compilation semantics of many
6752: words. By default, the interpretation semantics of a word are to
6753: @code{execute} its execution semantics, and the compilation semantics of
6754: a word are to @code{compile,} its execution semantics.@footnote{In
6755: standard terminology: The default interpretation semantics are its
6756: execution semantics; the default compilation semantics are to append its
6757: execution semantics to the execution semantics of the current
6758: definition.}
6759:
1.71 anton 6760: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6761: the text interpreter, ticked, or @code{postpone}d, so they have no
6762: interpretation or compilation semantics. Their behaviour is represented
6763: by their XT (@pxref{Tokens for Words}), and we call it execution
6764: semantics, too.
6765:
1.26 crook 6766: @comment TODO expand, make it co-operate with new sections on text interpreter.
6767:
6768: @cindex immediate words
6769: @cindex compile-only words
6770: You can change the semantics of the most-recently defined word:
6771:
1.44 crook 6772:
1.26 crook 6773: doc-immediate
6774: doc-compile-only
6775: doc-restrict
6776:
1.82 anton 6777: By convention, words with non-default compilation semantics (e.g.,
6778: immediate words) often have names surrounded with brackets (e.g.,
6779: @code{[']}, @pxref{Execution token}).
1.44 crook 6780:
1.26 crook 6781: Note that ticking (@code{'}) a compile-only word gives an error
6782: (``Interpreting a compile-only word'').
1.1 anton 6783:
1.47 crook 6784: @menu
1.67 anton 6785: * Combined words::
1.47 crook 6786: @end menu
1.44 crook 6787:
1.71 anton 6788:
1.48 anton 6789: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6790: @subsection Combined Words
6791: @cindex combined words
6792:
6793: Gforth allows you to define @dfn{combined words} -- words that have an
6794: arbitrary combination of interpretation and compilation semantics.
6795:
1.26 crook 6796: doc-interpret/compile:
1.1 anton 6797:
1.26 crook 6798: This feature was introduced for implementing @code{TO} and @code{S"}. I
6799: recommend that you do not define such words, as cute as they may be:
6800: they make it hard to get at both parts of the word in some contexts.
6801: E.g., assume you want to get an execution token for the compilation
6802: part. Instead, define two words, one that embodies the interpretation
6803: part, and one that embodies the compilation part. Once you have done
6804: that, you can define a combined word with @code{interpret/compile:} for
6805: the convenience of your users.
1.1 anton 6806:
1.26 crook 6807: You might try to use this feature to provide an optimizing
6808: implementation of the default compilation semantics of a word. For
6809: example, by defining:
1.1 anton 6810: @example
1.26 crook 6811: :noname
6812: foo bar ;
6813: :noname
6814: POSTPONE foo POSTPONE bar ;
1.29 crook 6815: interpret/compile: opti-foobar
1.1 anton 6816: @end example
1.26 crook 6817:
1.23 crook 6818: @noindent
1.26 crook 6819: as an optimizing version of:
6820:
1.1 anton 6821: @example
1.26 crook 6822: : foobar
6823: foo bar ;
1.1 anton 6824: @end example
6825:
1.26 crook 6826: Unfortunately, this does not work correctly with @code{[compile]},
6827: because @code{[compile]} assumes that the compilation semantics of all
6828: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6829: opti-foobar} would compile compilation semantics, whereas
6830: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6831:
1.26 crook 6832: @cindex state-smart words (are a bad idea)
1.82 anton 6833: @anchor{state-smartness}
1.29 crook 6834: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6835: by @code{interpret/compile:} (words are state-smart if they check
6836: @code{STATE} during execution). E.g., they would try to code
6837: @code{foobar} like this:
1.1 anton 6838:
1.26 crook 6839: @example
6840: : foobar
6841: STATE @@
6842: IF ( compilation state )
6843: POSTPONE foo POSTPONE bar
6844: ELSE
6845: foo bar
6846: ENDIF ; immediate
6847: @end example
1.1 anton 6848:
1.26 crook 6849: Although this works if @code{foobar} is only processed by the text
6850: interpreter, it does not work in other contexts (like @code{'} or
6851: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6852: for a state-smart word, not for the interpretation semantics of the
6853: original @code{foobar}; when you execute this execution token (directly
6854: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6855: state, the result will not be what you expected (i.e., it will not
6856: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6857: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6858: M. Anton Ertl,
6859: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6860: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6861:
1.26 crook 6862: @cindex defining words with arbitrary semantics combinations
6863: It is also possible to write defining words that define words with
6864: arbitrary combinations of interpretation and compilation semantics. In
6865: general, they look like this:
1.1 anton 6866:
1.26 crook 6867: @example
6868: : def-word
6869: create-interpret/compile
1.29 crook 6870: @i{code1}
1.26 crook 6871: interpretation>
1.29 crook 6872: @i{code2}
1.26 crook 6873: <interpretation
6874: compilation>
1.29 crook 6875: @i{code3}
1.26 crook 6876: <compilation ;
6877: @end example
1.1 anton 6878:
1.29 crook 6879: For a @i{word} defined with @code{def-word}, the interpretation
6880: semantics are to push the address of the body of @i{word} and perform
6881: @i{code2}, and the compilation semantics are to push the address of
6882: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6883: can also be defined like this (except that the defined constants don't
6884: behave correctly when @code{[compile]}d):
1.1 anton 6885:
1.26 crook 6886: @example
6887: : constant ( n "name" -- )
6888: create-interpret/compile
6889: ,
6890: interpretation> ( -- n )
6891: @@
6892: <interpretation
6893: compilation> ( compilation. -- ; run-time. -- n )
6894: @@ postpone literal
6895: <compilation ;
6896: @end example
1.1 anton 6897:
1.44 crook 6898:
1.26 crook 6899: doc-create-interpret/compile
6900: doc-interpretation>
6901: doc-<interpretation
6902: doc-compilation>
6903: doc-<compilation
1.1 anton 6904:
1.44 crook 6905:
1.29 crook 6906: Words defined with @code{interpret/compile:} and
1.26 crook 6907: @code{create-interpret/compile} have an extended header structure that
6908: differs from other words; however, unless you try to access them with
6909: plain address arithmetic, you should not notice this. Words for
6910: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6911: @code{'} @i{word} @code{>body} also gives you the body of a word created
6912: with @code{create-interpret/compile}.
1.1 anton 6913:
1.44 crook 6914:
1.47 crook 6915: @c -------------------------------------------------------------
1.81 anton 6916: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6917: @section Tokens for Words
6918: @cindex tokens for words
6919:
6920: This section describes the creation and use of tokens that represent
6921: words.
6922:
1.71 anton 6923: @menu
6924: * Execution token:: represents execution/interpretation semantics
6925: * Compilation token:: represents compilation semantics
6926: * Name token:: represents named words
6927: @end menu
1.47 crook 6928:
1.71 anton 6929: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6930: @subsection Execution token
1.47 crook 6931:
6932: @cindex xt
6933: @cindex execution token
1.71 anton 6934: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6935: You can use @code{execute} to invoke this behaviour.
1.47 crook 6936:
1.71 anton 6937: @cindex tick (')
6938: You can use @code{'} to get an execution token that represents the
6939: interpretation semantics of a named word:
1.47 crook 6940:
6941: @example
1.97 anton 6942: 5 ' . ( n xt )
6943: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6944: @end example
1.47 crook 6945:
1.71 anton 6946: doc-'
6947:
6948: @code{'} parses at run-time; there is also a word @code{[']} that parses
6949: when it is compiled, and compiles the resulting XT:
6950:
6951: @example
6952: : foo ['] . execute ;
6953: 5 foo
6954: : bar ' execute ; \ by contrast,
6955: 5 bar . \ ' parses "." when bar executes
6956: @end example
6957:
6958: doc-[']
6959:
6960: If you want the execution token of @i{word}, write @code{['] @i{word}}
6961: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6962: @code{'} and @code{[']} behave somewhat unusually by complaining about
6963: compile-only words (because these words have no interpretation
6964: semantics). You might get what you want by using @code{COMP' @i{word}
6965: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6966: token}).
6967:
1.116 anton 6968: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6969: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6970: for the only behaviour the word has (the execution semantics). For
1.116 anton 6971: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6972: would produce if the word was defined anonymously.
6973:
6974: @example
6975: :noname ." hello" ;
6976: execute
1.47 crook 6977: @end example
6978:
1.71 anton 6979: An XT occupies one cell and can be manipulated like any other cell.
6980:
1.47 crook 6981: @cindex code field address
6982: @cindex CFA
1.71 anton 6983: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6984: operations that produce or consume it). For old hands: In Gforth, the
6985: XT is implemented as a code field address (CFA).
6986:
6987: doc-execute
6988: doc-perform
6989:
6990: @node Compilation token, Name token, Execution token, Tokens for Words
6991: @subsection Compilation token
1.47 crook 6992:
6993: @cindex compilation token
1.71 anton 6994: @cindex CT (compilation token)
6995: Gforth represents the compilation semantics of a named word by a
1.47 crook 6996: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6997: @i{xt} is an execution token. The compilation semantics represented by
6998: the compilation token can be performed with @code{execute}, which
6999: consumes the whole compilation token, with an additional stack effect
7000: determined by the represented compilation semantics.
7001:
7002: At present, the @i{w} part of a compilation token is an execution token,
7003: and the @i{xt} part represents either @code{execute} or
7004: @code{compile,}@footnote{Depending upon the compilation semantics of the
7005: word. If the word has default compilation semantics, the @i{xt} will
7006: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7007: @i{xt} will represent @code{execute}.}. However, don't rely on that
7008: knowledge, unless necessary; future versions of Gforth may introduce
7009: unusual compilation tokens (e.g., a compilation token that represents
7010: the compilation semantics of a literal).
7011:
1.71 anton 7012: You can perform the compilation semantics represented by the compilation
7013: token with @code{execute}. You can compile the compilation semantics
7014: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7015: equivalent to @code{postpone @i{word}}.
7016:
7017: doc-[comp']
7018: doc-comp'
7019: doc-postpone,
7020:
7021: @node Name token, , Compilation token, Tokens for Words
7022: @subsection Name token
1.47 crook 7023:
7024: @cindex name token
1.116 anton 7025: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7026: token is an abstract data type that occurs as argument or result of the
7027: words below.
7028:
7029: @c !! put this elswhere?
1.47 crook 7030: @cindex name field address
7031: @cindex NFA
1.116 anton 7032: The closest thing to the nt in older Forth systems is the name field
7033: address (NFA), but there are significant differences: in older Forth
7034: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7035: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7036: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7037: is a link field in the structure identified by the name token, but
7038: searching usually uses a hash table external to these structures; the
7039: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7040: implemented as the address of that count field.
1.47 crook 7041:
7042: doc-find-name
1.116 anton 7043: doc-latest
7044: doc->name
1.47 crook 7045: doc-name>int
7046: doc-name?int
7047: doc-name>comp
7048: doc-name>string
1.109 anton 7049: doc-id.
7050: doc-.name
7051: doc-.id
1.47 crook 7052:
1.81 anton 7053: @c ----------------------------------------------------------
7054: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7055: @section Compiling words
7056: @cindex compiling words
7057: @cindex macros
7058:
7059: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7060: between compilation and run-time. E.g., you can run arbitrary code
7061: between defining words (or for computing data used by defining words
7062: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7063: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7064: running arbitrary code while compiling a colon definition (exception:
7065: you must not allot dictionary space).
7066:
7067: @menu
7068: * Literals:: Compiling data values
7069: * Macros:: Compiling words
7070: @end menu
7071:
7072: @node Literals, Macros, Compiling words, Compiling words
7073: @subsection Literals
7074: @cindex Literals
7075:
7076: The simplest and most frequent example is to compute a literal during
7077: compilation. E.g., the following definition prints an array of strings,
7078: one string per line:
7079:
7080: @example
7081: : .strings ( addr u -- ) \ gforth
7082: 2* cells bounds U+DO
7083: cr i 2@@ type
7084: 2 cells +LOOP ;
7085: @end example
1.81 anton 7086:
1.82 anton 7087: With a simple-minded compiler like Gforth's, this computes @code{2
7088: cells} on every loop iteration. You can compute this value once and for
7089: all at compile time and compile it into the definition like this:
7090:
7091: @example
7092: : .strings ( addr u -- ) \ gforth
7093: 2* cells bounds U+DO
7094: cr i 2@@ type
7095: [ 2 cells ] literal +LOOP ;
7096: @end example
7097:
7098: @code{[} switches the text interpreter to interpret state (you will get
7099: an @code{ok} prompt if you type this example interactively and insert a
7100: newline between @code{[} and @code{]}), so it performs the
7101: interpretation semantics of @code{2 cells}; this computes a number.
7102: @code{]} switches the text interpreter back into compile state. It then
7103: performs @code{Literal}'s compilation semantics, which are to compile
7104: this number into the current word. You can decompile the word with
7105: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7106:
1.82 anton 7107: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7108: *} in this way.
1.81 anton 7109:
1.82 anton 7110: doc-[
7111: doc-]
1.81 anton 7112: doc-literal
7113: doc-]L
1.82 anton 7114:
7115: There are also words for compiling other data types than single cells as
7116: literals:
7117:
1.81 anton 7118: doc-2literal
7119: doc-fliteral
1.82 anton 7120: doc-sliteral
7121:
7122: @cindex colon-sys, passing data across @code{:}
7123: @cindex @code{:}, passing data across
7124: You might be tempted to pass data from outside a colon definition to the
7125: inside on the data stack. This does not work, because @code{:} puhes a
7126: colon-sys, making stuff below unaccessible. E.g., this does not work:
7127:
7128: @example
7129: 5 : foo literal ; \ error: "unstructured"
7130: @end example
7131:
7132: Instead, you have to pass the value in some other way, e.g., through a
7133: variable:
7134:
7135: @example
7136: variable temp
7137: 5 temp !
7138: : foo [ temp @@ ] literal ;
7139: @end example
7140:
7141:
7142: @node Macros, , Literals, Compiling words
7143: @subsection Macros
7144: @cindex Macros
7145: @cindex compiling compilation semantics
7146:
7147: @code{Literal} and friends compile data values into the current
7148: definition. You can also write words that compile other words into the
7149: current definition. E.g.,
7150:
7151: @example
7152: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7153: POSTPONE + ;
7154:
7155: : foo ( n1 n2 -- n )
7156: [ compile-+ ] ;
7157: 1 2 foo .
7158: @end example
7159:
7160: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7161: What happens in this example? @code{Postpone} compiles the compilation
7162: semantics of @code{+} into @code{compile-+}; later the text interpreter
7163: executes @code{compile-+} and thus the compilation semantics of +, which
7164: compile (the execution semantics of) @code{+} into
7165: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7166: should only be executed in compile state, so this example is not
7167: guaranteed to work on all standard systems, but on any decent system it
7168: will work.}
7169:
7170: doc-postpone
7171: doc-[compile]
7172:
7173: Compiling words like @code{compile-+} are usually immediate (or similar)
7174: so you do not have to switch to interpret state to execute them;
7175: mopifying the last example accordingly produces:
7176:
7177: @example
7178: : [compile-+] ( compilation: --; interpretation: -- )
7179: \ compiled code: ( n1 n2 -- n )
7180: POSTPONE + ; immediate
7181:
7182: : foo ( n1 n2 -- n )
7183: [compile-+] ;
7184: 1 2 foo .
7185: @end example
7186:
7187: Immediate compiling words are similar to macros in other languages (in
7188: particular, Lisp). The important differences to macros in, e.g., C are:
7189:
7190: @itemize @bullet
7191:
7192: @item
7193: You use the same language for defining and processing macros, not a
7194: separate preprocessing language and processor.
7195:
7196: @item
7197: Consequently, the full power of Forth is available in macro definitions.
7198: E.g., you can perform arbitrarily complex computations, or generate
7199: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7200: Tutorial}). This power is very useful when writing a parser generators
7201: or other code-generating software.
7202:
7203: @item
7204: Macros defined using @code{postpone} etc. deal with the language at a
7205: higher level than strings; name binding happens at macro definition
7206: time, so you can avoid the pitfalls of name collisions that can happen
7207: in C macros. Of course, Forth is a liberal language and also allows to
7208: shoot yourself in the foot with text-interpreted macros like
7209:
7210: @example
7211: : [compile-+] s" +" evaluate ; immediate
7212: @end example
7213:
7214: Apart from binding the name at macro use time, using @code{evaluate}
7215: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7216: @end itemize
7217:
7218: You may want the macro to compile a number into a word. The word to do
7219: it is @code{literal}, but you have to @code{postpone} it, so its
7220: compilation semantics take effect when the macro is executed, not when
7221: it is compiled:
7222:
7223: @example
7224: : [compile-5] ( -- ) \ compiled code: ( -- n )
7225: 5 POSTPONE literal ; immediate
7226:
7227: : foo [compile-5] ;
7228: foo .
7229: @end example
7230:
7231: You may want to pass parameters to a macro, that the macro should
7232: compile into the current definition. If the parameter is a number, then
7233: you can use @code{postpone literal} (similar for other values).
7234:
7235: If you want to pass a word that is to be compiled, the usual way is to
7236: pass an execution token and @code{compile,} it:
7237:
7238: @example
7239: : twice1 ( xt -- ) \ compiled code: ... -- ...
7240: dup compile, compile, ;
7241:
7242: : 2+ ( n1 -- n2 )
7243: [ ' 1+ twice1 ] ;
7244: @end example
7245:
7246: doc-compile,
7247:
7248: An alternative available in Gforth, that allows you to pass compile-only
7249: words as parameters is to use the compilation token (@pxref{Compilation
7250: token}). The same example in this technique:
7251:
7252: @example
7253: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7254: 2dup 2>r execute 2r> execute ;
7255:
7256: : 2+ ( n1 -- n2 )
7257: [ comp' 1+ twice ] ;
7258: @end example
7259:
7260: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7261: works even if the executed compilation semantics has an effect on the
7262: data stack.
7263:
7264: You can also define complete definitions with these words; this provides
7265: an alternative to using @code{does>} (@pxref{User-defined Defining
7266: Words}). E.g., instead of
7267:
7268: @example
7269: : curry+ ( n1 "name" -- )
7270: CREATE ,
7271: DOES> ( n2 -- n1+n2 )
7272: @@ + ;
7273: @end example
7274:
7275: you could define
7276:
7277: @example
7278: : curry+ ( n1 "name" -- )
7279: \ name execution: ( n2 -- n1+n2 )
7280: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7281:
1.82 anton 7282: -3 curry+ 3-
7283: see 3-
7284: @end example
1.81 anton 7285:
1.82 anton 7286: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7287: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7288:
1.82 anton 7289: This way of writing defining words is sometimes more, sometimes less
7290: convenient than using @code{does>} (@pxref{Advanced does> usage
7291: example}). One advantage of this method is that it can be optimized
7292: better, because the compiler knows that the value compiled with
7293: @code{literal} is fixed, whereas the data associated with a
7294: @code{create}d word can be changed.
1.47 crook 7295:
1.26 crook 7296: @c ----------------------------------------------------------
1.111 anton 7297: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7298: @section The Text Interpreter
7299: @cindex interpreter - outer
7300: @cindex text interpreter
7301: @cindex outer interpreter
1.1 anton 7302:
1.34 anton 7303: @c Should we really describe all these ugly details? IMO the text
7304: @c interpreter should be much cleaner, but that may not be possible within
7305: @c ANS Forth. - anton
1.44 crook 7306: @c nac-> I wanted to explain how it works to show how you can exploit
7307: @c it in your own programs. When I was writing a cross-compiler, figuring out
7308: @c some of these gory details was very helpful to me. None of the textbooks
7309: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7310: @c seems to positively avoid going into too much detail for some of
7311: @c the internals.
1.34 anton 7312:
1.71 anton 7313: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7314: @c it is; for the ugly details, I would prefer another place. I wonder
7315: @c whether we should have a chapter before "Words" that describes some
7316: @c basic concepts referred to in words, and a chapter after "Words" that
7317: @c describes implementation details.
7318:
1.29 crook 7319: The text interpreter@footnote{This is an expanded version of the
7320: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7321: that processes input from the current input device. It is also called
7322: the outer interpreter, in contrast to the inner interpreter
7323: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7324: implementations.
1.27 crook 7325:
1.29 crook 7326: @cindex interpret state
7327: @cindex compile state
7328: The text interpreter operates in one of two states: @dfn{interpret
7329: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7330: aptly-named variable @code{state}.
1.29 crook 7331:
7332: This section starts by describing how the text interpreter behaves when
7333: it is in interpret state, processing input from the user input device --
7334: the keyboard. This is the mode that a Forth system is in after it starts
7335: up.
7336:
7337: @cindex input buffer
7338: @cindex terminal input buffer
7339: The text interpreter works from an area of memory called the @dfn{input
7340: buffer}@footnote{When the text interpreter is processing input from the
7341: keyboard, this area of memory is called the @dfn{terminal input buffer}
7342: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7343: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7344: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7345: leading spaces (called @dfn{delimiters}) then parses a string (a
7346: sequence of non-space characters) until it reaches either a space
7347: character or the end of the buffer. Having parsed a string, it makes two
7348: attempts to process it:
1.27 crook 7349:
1.29 crook 7350: @cindex dictionary
1.27 crook 7351: @itemize @bullet
7352: @item
1.29 crook 7353: It looks for the string in a @dfn{dictionary} of definitions. If the
7354: string is found, the string names a @dfn{definition} (also known as a
7355: @dfn{word}) and the dictionary search returns information that allows
7356: the text interpreter to perform the word's @dfn{interpretation
7357: semantics}. In most cases, this simply means that the word will be
7358: executed.
1.27 crook 7359: @item
7360: If the string is not found in the dictionary, the text interpreter
1.29 crook 7361: attempts to treat it as a number, using the rules described in
7362: @ref{Number Conversion}. If the string represents a legal number in the
7363: current radix, the number is pushed onto a parameter stack (the data
7364: stack for integers, the floating-point stack for floating-point
7365: numbers).
7366: @end itemize
7367:
7368: If both attempts fail, or if the word is found in the dictionary but has
7369: no interpretation semantics@footnote{This happens if the word was
7370: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7371: remainder of the input buffer, issues an error message and waits for
7372: more input. If one of the attempts succeeds, the text interpreter
7373: repeats the parsing process until the whole of the input buffer has been
7374: processed, at which point it prints the status message ``@code{ ok}''
7375: and waits for more input.
7376:
1.71 anton 7377: @c anton: this should be in the input stream subsection (or below it)
7378:
1.29 crook 7379: @cindex parse area
7380: The text interpreter keeps track of its position in the input buffer by
7381: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7382: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7383: of the input buffer. The region from offset @code{>IN @@} to the end of
7384: the input buffer is called the @dfn{parse area}@footnote{In other words,
7385: the text interpreter processes the contents of the input buffer by
7386: parsing strings from the parse area until the parse area is empty.}.
7387: This example shows how @code{>IN} changes as the text interpreter parses
7388: the input buffer:
7389:
7390: @example
7391: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7392: CR ." ->" TYPE ." <-" ; IMMEDIATE
7393:
7394: 1 2 3 remaining + remaining .
7395:
7396: : foo 1 2 3 remaining SWAP remaining ;
7397: @end example
7398:
7399: @noindent
7400: The result is:
7401:
7402: @example
7403: ->+ remaining .<-
7404: ->.<-5 ok
7405:
7406: ->SWAP remaining ;-<
7407: ->;<- ok
7408: @end example
7409:
7410: @cindex parsing words
7411: The value of @code{>IN} can also be modified by a word in the input
7412: buffer that is executed by the text interpreter. This means that a word
7413: can ``trick'' the text interpreter into either skipping a section of the
7414: input buffer@footnote{This is how parsing words work.} or into parsing a
7415: section twice. For example:
1.27 crook 7416:
1.29 crook 7417: @example
1.71 anton 7418: : lat ." <<foo>>" ;
7419: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7420: @end example
7421:
7422: @noindent
7423: When @code{flat} is executed, this output is produced@footnote{Exercise
7424: for the reader: what would happen if the @code{3} were replaced with
7425: @code{4}?}:
7426:
7427: @example
1.71 anton 7428: <<bar>><<foo>>
1.29 crook 7429: @end example
7430:
1.71 anton 7431: This technique can be used to work around some of the interoperability
7432: problems of parsing words. Of course, it's better to avoid parsing
7433: words where possible.
7434:
1.29 crook 7435: @noindent
7436: Two important notes about the behaviour of the text interpreter:
1.27 crook 7437:
7438: @itemize @bullet
7439: @item
7440: It processes each input string to completion before parsing additional
1.29 crook 7441: characters from the input buffer.
7442: @item
7443: It treats the input buffer as a read-only region (and so must your code).
7444: @end itemize
7445:
7446: @noindent
7447: When the text interpreter is in compile state, its behaviour changes in
7448: these ways:
7449:
7450: @itemize @bullet
7451: @item
7452: If a parsed string is found in the dictionary, the text interpreter will
7453: perform the word's @dfn{compilation semantics}. In most cases, this
7454: simply means that the execution semantics of the word will be appended
7455: to the current definition.
1.27 crook 7456: @item
1.29 crook 7457: When a number is encountered, it is compiled into the current definition
7458: (as a literal) rather than being pushed onto a parameter stack.
7459: @item
7460: If an error occurs, @code{state} is modified to put the text interpreter
7461: back into interpret state.
7462: @item
7463: Each time a line is entered from the keyboard, Gforth prints
7464: ``@code{ compiled}'' rather than `` @code{ok}''.
7465: @end itemize
7466:
7467: @cindex text interpreter - input sources
7468: When the text interpreter is using an input device other than the
7469: keyboard, its behaviour changes in these ways:
7470:
7471: @itemize @bullet
7472: @item
7473: When the parse area is empty, the text interpreter attempts to refill
7474: the input buffer from the input source. When the input source is
1.71 anton 7475: exhausted, the input source is set back to the previous input source.
1.29 crook 7476: @item
7477: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7478: time the parse area is emptied.
7479: @item
7480: If an error occurs, the input source is set back to the user input
7481: device.
1.27 crook 7482: @end itemize
1.21 crook 7483:
1.49 anton 7484: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7485:
1.26 crook 7486: doc->in
1.27 crook 7487: doc-source
7488:
1.26 crook 7489: doc-tib
7490: doc-#tib
1.1 anton 7491:
1.44 crook 7492:
1.26 crook 7493: @menu
1.67 anton 7494: * Input Sources::
7495: * Number Conversion::
7496: * Interpret/Compile states::
7497: * Interpreter Directives::
1.26 crook 7498: @end menu
1.1 anton 7499:
1.29 crook 7500: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7501: @subsection Input Sources
7502: @cindex input sources
7503: @cindex text interpreter - input sources
7504:
1.44 crook 7505: By default, the text interpreter processes input from the user input
1.29 crook 7506: device (the keyboard) when Forth starts up. The text interpreter can
7507: process input from any of these sources:
7508:
7509: @itemize @bullet
7510: @item
7511: The user input device -- the keyboard.
7512: @item
7513: A file, using the words described in @ref{Forth source files}.
7514: @item
7515: A block, using the words described in @ref{Blocks}.
7516: @item
7517: A text string, using @code{evaluate}.
7518: @end itemize
7519:
7520: A program can identify the current input device from the values of
7521: @code{source-id} and @code{blk}.
7522:
1.44 crook 7523:
1.29 crook 7524: doc-source-id
7525: doc-blk
7526:
7527: doc-save-input
7528: doc-restore-input
7529:
7530: doc-evaluate
1.111 anton 7531: doc-query
1.1 anton 7532:
1.29 crook 7533:
1.44 crook 7534:
1.29 crook 7535: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7536: @subsection Number Conversion
7537: @cindex number conversion
7538: @cindex double-cell numbers, input format
7539: @cindex input format for double-cell numbers
7540: @cindex single-cell numbers, input format
7541: @cindex input format for single-cell numbers
7542: @cindex floating-point numbers, input format
7543: @cindex input format for floating-point numbers
1.1 anton 7544:
1.29 crook 7545: This section describes the rules that the text interpreter uses when it
7546: tries to convert a string into a number.
1.1 anton 7547:
1.26 crook 7548: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7549: number base@footnote{For example, 0-9 when the number base is decimal or
7550: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7551:
1.26 crook 7552: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7553:
1.29 crook 7554: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7555: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7556:
1.26 crook 7557: Let * represent any number of instances of the previous character
7558: (including none).
1.1 anton 7559:
1.26 crook 7560: Let any other character represent itself.
1.1 anton 7561:
1.29 crook 7562: @noindent
1.26 crook 7563: Now, the conversion rules are:
1.21 crook 7564:
1.26 crook 7565: @itemize @bullet
7566: @item
7567: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7568: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7569: @item
7570: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7571: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7572: arithmetic. Examples are -45 -5681 -0
7573: @item
7574: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7575: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7576: (all three of these represent the same number).
1.26 crook 7577: @item
7578: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7579: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7580: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7581: -34.65 (all three of these represent the same number).
1.26 crook 7582: @item
1.29 crook 7583: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7584: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7585: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7586: number) +12.E-4
1.26 crook 7587: @end itemize
1.1 anton 7588:
1.26 crook 7589: By default, the number base used for integer number conversion is given
1.35 anton 7590: by the contents of the variable @code{base}. Note that a lot of
7591: confusion can result from unexpected values of @code{base}. If you
7592: change @code{base} anywhere, make sure to save the old value and restore
7593: it afterwards. In general I recommend keeping @code{base} decimal, and
7594: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7595:
1.29 crook 7596: doc-dpl
1.26 crook 7597: doc-base
7598: doc-hex
7599: doc-decimal
1.1 anton 7600:
1.44 crook 7601:
1.26 crook 7602: @cindex '-prefix for character strings
7603: @cindex &-prefix for decimal numbers
7604: @cindex %-prefix for binary numbers
7605: @cindex $-prefix for hexadecimal numbers
1.35 anton 7606: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7607: prefix@footnote{Some Forth implementations provide a similar scheme by
7608: implementing @code{$} etc. as parsing words that process the subsequent
7609: number in the input stream and push it onto the stack. For example, see
7610: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7611: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7612: is required between the prefix and the number.} before the first digit
7613: of an (integer) number. Four prefixes are supported:
1.1 anton 7614:
1.26 crook 7615: @itemize @bullet
7616: @item
1.35 anton 7617: @code{&} -- decimal
1.26 crook 7618: @item
1.35 anton 7619: @code{%} -- binary
1.26 crook 7620: @item
1.35 anton 7621: @code{$} -- hexadecimal
1.26 crook 7622: @item
1.35 anton 7623: @code{'} -- base @code{max-char+1}
1.26 crook 7624: @end itemize
1.1 anton 7625:
1.26 crook 7626: Here are some examples, with the equivalent decimal number shown after
7627: in braces:
1.1 anton 7628:
1.26 crook 7629: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7630: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7631: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7632: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7633:
1.26 crook 7634: @cindex number conversion - traps for the unwary
1.29 crook 7635: @noindent
1.26 crook 7636: Number conversion has a number of traps for the unwary:
1.1 anton 7637:
1.26 crook 7638: @itemize @bullet
7639: @item
7640: You cannot determine the current number base using the code sequence
1.35 anton 7641: @code{base @@ .} -- the number base is always 10 in the current number
7642: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7643: @item
7644: If the number base is set to a value greater than 14 (for example,
7645: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7646: it to be intepreted as either a single-precision integer or a
7647: floating-point number (Gforth treats it as an integer). The ambiguity
7648: can be resolved by explicitly stating the sign of the mantissa and/or
7649: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7650: ambiguity arises; either representation will be treated as a
7651: floating-point number.
7652: @item
1.29 crook 7653: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7654: It is used to specify file types.
7655: @item
1.72 anton 7656: ANS Forth requires the @code{.} of a double-precision number to be the
7657: final character in the string. Gforth allows the @code{.} to be
7658: anywhere after the first digit.
1.26 crook 7659: @item
7660: The number conversion process does not check for overflow.
7661: @item
1.72 anton 7662: In an ANS Forth program @code{base} is required to be decimal when
7663: converting floating-point numbers. In Gforth, number conversion to
7664: floating-point numbers always uses base &10, irrespective of the value
7665: of @code{base}.
1.26 crook 7666: @end itemize
1.1 anton 7667:
1.49 anton 7668: You can read numbers into your programs with the words described in
7669: @ref{Input}.
1.1 anton 7670:
1.82 anton 7671: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7672: @subsection Interpret/Compile states
7673: @cindex Interpret/Compile states
1.1 anton 7674:
1.29 crook 7675: A standard program is not permitted to change @code{state}
7676: explicitly. However, it can change @code{state} implicitly, using the
7677: words @code{[} and @code{]}. When @code{[} is executed it switches
7678: @code{state} to interpret state, and therefore the text interpreter
7679: starts interpreting. When @code{]} is executed it switches @code{state}
7680: to compile state and therefore the text interpreter starts
1.44 crook 7681: compiling. The most common usage for these words is for switching into
7682: interpret state and back from within a colon definition; this technique
1.49 anton 7683: can be used to compile a literal (for an example, @pxref{Literals}) or
7684: for conditional compilation (for an example, @pxref{Interpreter
7685: Directives}).
1.44 crook 7686:
1.35 anton 7687:
7688: @c This is a bad example: It's non-standard, and it's not necessary.
7689: @c However, I can't think of a good example for switching into compile
7690: @c state when there is no current word (@code{state}-smart words are not a
7691: @c good reason). So maybe we should use an example for switching into
7692: @c interpret @code{state} in a colon def. - anton
1.44 crook 7693: @c nac-> I agree. I started out by putting in the example, then realised
7694: @c that it was non-ANS, so wrote more words around it. I hope this
7695: @c re-written version is acceptable to you. I do want to keep the example
7696: @c as it is helpful for showing what is and what is not portable, particularly
7697: @c where it outlaws a style in common use.
7698:
1.72 anton 7699: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7700: @c that, we can also show what's not. In any case, I have written a
7701: @c section Compiling Words which also deals with [ ].
1.35 anton 7702:
1.95 anton 7703: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7704:
1.95 anton 7705: @c @code{[} and @code{]} also give you the ability to switch into compile
7706: @c state and back, but we cannot think of any useful Standard application
7707: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7708:
7709: @c @example
7710: @c : AA ." this is A" ;
7711: @c : BB ." this is B" ;
7712: @c : CC ." this is C" ;
7713:
7714: @c create table ] aa bb cc [
7715:
7716: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7717: @c cells table + @@ execute ;
7718: @c @end example
7719:
7720: @c This example builds a jump table; @code{0 go} will display ``@code{this
7721: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7722: @c defining @code{table} like this:
7723:
7724: @c @example
7725: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7726: @c @end example
7727:
7728: @c The problem with this code is that the definition of @code{table} is not
7729: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7730: @c @i{may} work on systems where code space and data space co-incide, the
7731: @c Standard only allows data space to be assigned for a @code{CREATE}d
7732: @c word. In addition, the Standard only allows @code{@@} to access data
7733: @c space, whilst this example is using it to access code space. The only
7734: @c portable, Standard way to build this table is to build it in data space,
7735: @c like this:
7736:
7737: @c @example
7738: @c create table ' aa , ' bb , ' cc ,
7739: @c @end example
1.29 crook 7740:
1.95 anton 7741: @c doc-state
1.44 crook 7742:
1.29 crook 7743:
1.82 anton 7744: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7745: @subsection Interpreter Directives
7746: @cindex interpreter directives
1.72 anton 7747: @cindex conditional compilation
1.1 anton 7748:
1.29 crook 7749: These words are usually used in interpret state; typically to control
7750: which parts of a source file are processed by the text
1.26 crook 7751: interpreter. There are only a few ANS Forth Standard words, but Gforth
7752: supplements these with a rich set of immediate control structure words
7753: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7754: used in compile state (@pxref{Control Structures}). Typical usages:
7755:
7756: @example
1.72 anton 7757: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7758: .
7759: .
1.72 anton 7760: HAVE-ASSEMBLER [IF]
1.29 crook 7761: : ASSEMBLER-FEATURE
7762: ...
7763: ;
7764: [ENDIF]
7765: .
7766: .
7767: : SEE
7768: ... \ general-purpose SEE code
1.72 anton 7769: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7770: ... \ assembler-specific SEE code
7771: [ [ENDIF] ]
7772: ;
7773: @end example
1.1 anton 7774:
1.44 crook 7775:
1.26 crook 7776: doc-[IF]
7777: doc-[ELSE]
7778: doc-[THEN]
7779: doc-[ENDIF]
1.1 anton 7780:
1.26 crook 7781: doc-[IFDEF]
7782: doc-[IFUNDEF]
1.1 anton 7783:
1.26 crook 7784: doc-[?DO]
7785: doc-[DO]
7786: doc-[FOR]
7787: doc-[LOOP]
7788: doc-[+LOOP]
7789: doc-[NEXT]
1.1 anton 7790:
1.26 crook 7791: doc-[BEGIN]
7792: doc-[UNTIL]
7793: doc-[AGAIN]
7794: doc-[WHILE]
7795: doc-[REPEAT]
1.1 anton 7796:
1.27 crook 7797:
1.26 crook 7798: @c -------------------------------------------------------------
1.111 anton 7799: @node The Input Stream, Word Lists, The Text Interpreter, Words
7800: @section The Input Stream
7801: @cindex input stream
7802:
7803: @c !! integrate this better with the "Text Interpreter" section
7804: The text interpreter reads from the input stream, which can come from
7805: several sources (@pxref{Input Sources}). Some words, in particular
7806: defining words, but also words like @code{'}, read parameters from the
7807: input stream instead of from the stack.
7808:
7809: Such words are called parsing words, because they parse the input
7810: stream. Parsing words are hard to use in other words, because it is
7811: hard to pass program-generated parameters through the input stream.
7812: They also usually have an unintuitive combination of interpretation and
7813: compilation semantics when implemented naively, leading to various
7814: approaches that try to produce a more intuitive behaviour
7815: (@pxref{Combined words}).
7816:
7817: It should be obvious by now that parsing words are a bad idea. If you
7818: want to implement a parsing word for convenience, also provide a factor
7819: of the word that does not parse, but takes the parameters on the stack.
7820: To implement the parsing word on top if it, you can use the following
7821: words:
7822:
7823: @c anton: these belong in the input stream section
7824: doc-parse
7825: doc-parse-word
7826: doc-name
7827: doc-word
7828: doc-\"-parse
7829: doc-refill
7830:
7831: Conversely, if you have the bad luck (or lack of foresight) to have to
7832: deal with parsing words without having such factors, how do you pass a
7833: string that is not in the input stream to it?
7834:
7835: doc-execute-parsing
7836:
7837: If you want to run a parsing word on a file, the following word should
7838: help:
7839:
7840: doc-execute-parsing-file
7841:
7842: @c -------------------------------------------------------------
7843: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7844: @section Word Lists
7845: @cindex word lists
1.32 anton 7846: @cindex header space
1.1 anton 7847:
1.36 anton 7848: A wordlist is a list of named words; you can add new words and look up
7849: words by name (and you can remove words in a restricted way with
7850: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7851:
7852: @cindex search order stack
7853: The text interpreter searches the wordlists present in the search order
7854: (a stack of wordlists), from the top to the bottom. Within each
7855: wordlist, the search starts conceptually at the newest word; i.e., if
7856: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7857:
1.26 crook 7858: @cindex compilation word list
1.36 anton 7859: New words are added to the @dfn{compilation wordlist} (aka current
7860: wordlist).
1.1 anton 7861:
1.36 anton 7862: @cindex wid
7863: A word list is identified by a cell-sized word list identifier (@i{wid})
7864: in much the same way as a file is identified by a file handle. The
7865: numerical value of the wid has no (portable) meaning, and might change
7866: from session to session.
1.1 anton 7867:
1.29 crook 7868: The ANS Forth ``Search order'' word set is intended to provide a set of
7869: low-level tools that allow various different schemes to be
1.74 anton 7870: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7871: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7872: Forth.
1.1 anton 7873:
1.27 crook 7874: @comment TODO: locals section refers to here, saying that every word list (aka
7875: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7876: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7877:
1.45 crook 7878: @comment TODO: document markers, reveal, tables, mappedwordlist
7879:
7880: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7881: @comment word from the source files, rather than some alias.
1.44 crook 7882:
1.26 crook 7883: doc-forth-wordlist
7884: doc-definitions
7885: doc-get-current
7886: doc-set-current
7887: doc-get-order
1.45 crook 7888: doc---gforthman-set-order
1.26 crook 7889: doc-wordlist
1.30 anton 7890: doc-table
1.79 anton 7891: doc->order
1.36 anton 7892: doc-previous
1.26 crook 7893: doc-also
1.45 crook 7894: doc---gforthman-forth
1.26 crook 7895: doc-only
1.45 crook 7896: doc---gforthman-order
1.15 anton 7897:
1.26 crook 7898: doc-find
7899: doc-search-wordlist
1.15 anton 7900:
1.26 crook 7901: doc-words
7902: doc-vlist
1.44 crook 7903: @c doc-words-deferred
1.1 anton 7904:
1.74 anton 7905: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7906: doc-root
7907: doc-vocabulary
7908: doc-seal
7909: doc-vocs
7910: doc-current
7911: doc-context
1.1 anton 7912:
1.44 crook 7913:
1.26 crook 7914: @menu
1.75 anton 7915: * Vocabularies::
1.67 anton 7916: * Why use word lists?::
1.75 anton 7917: * Word list example::
1.26 crook 7918: @end menu
7919:
1.75 anton 7920: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7921: @subsection Vocabularies
7922: @cindex Vocabularies, detailed explanation
7923:
7924: Here is an example of creating and using a new wordlist using ANS
7925: Forth words:
7926:
7927: @example
7928: wordlist constant my-new-words-wordlist
7929: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7930:
7931: \ add it to the search order
7932: also my-new-words
7933:
7934: \ alternatively, add it to the search order and make it
7935: \ the compilation word list
7936: also my-new-words definitions
7937: \ type "order" to see the problem
7938: @end example
7939:
7940: The problem with this example is that @code{order} has no way to
7941: associate the name @code{my-new-words} with the wid of the word list (in
7942: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7943: that has no associated name). There is no Standard way of associating a
7944: name with a wid.
7945:
7946: In Gforth, this example can be re-coded using @code{vocabulary}, which
7947: associates a name with a wid:
7948:
7949: @example
7950: vocabulary my-new-words
7951:
7952: \ add it to the search order
7953: also my-new-words
7954:
7955: \ alternatively, add it to the search order and make it
7956: \ the compilation word list
7957: my-new-words definitions
7958: \ type "order" to see that the problem is solved
7959: @end example
7960:
7961:
7962: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7963: @subsection Why use word lists?
7964: @cindex word lists - why use them?
7965:
1.74 anton 7966: Here are some reasons why people use wordlists:
1.26 crook 7967:
7968: @itemize @bullet
1.74 anton 7969:
7970: @c anton: Gforth's hashing implementation makes the search speed
7971: @c independent from the number of words. But it is linear with the number
7972: @c of wordlists that have to be searched, so in effect using more wordlists
7973: @c actually slows down compilation.
7974:
7975: @c @item
7976: @c To improve compilation speed by reducing the number of header space
7977: @c entries that must be searched. This is achieved by creating a new
7978: @c word list that contains all of the definitions that are used in the
7979: @c definition of a Forth system but which would not usually be used by
7980: @c programs running on that system. That word list would be on the search
7981: @c list when the Forth system was compiled but would be removed from the
7982: @c search list for normal operation. This can be a useful technique for
7983: @c low-performance systems (for example, 8-bit processors in embedded
7984: @c systems) but is unlikely to be necessary in high-performance desktop
7985: @c systems.
7986:
1.26 crook 7987: @item
7988: To prevent a set of words from being used outside the context in which
7989: they are valid. Two classic examples of this are an integrated editor
7990: (all of the edit commands are defined in a separate word list; the
7991: search order is set to the editor word list when the editor is invoked;
7992: the old search order is restored when the editor is terminated) and an
7993: integrated assembler (the op-codes for the machine are defined in a
7994: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 7995:
7996: @item
7997: To organize the words of an application or library into a user-visible
7998: set (in @code{forth-wordlist} or some other common wordlist) and a set
7999: of helper words used just for the implementation (hidden in a separate
1.75 anton 8000: wordlist). This keeps @code{words}' output smaller, separates
8001: implementation and interface, and reduces the chance of name conflicts
8002: within the common wordlist.
1.74 anton 8003:
1.26 crook 8004: @item
8005: To prevent a name-space clash between multiple definitions with the same
8006: name. For example, when building a cross-compiler you might have a word
8007: @code{IF} that generates conditional code for your target system. By
8008: placing this definition in a different word list you can control whether
8009: the host system's @code{IF} or the target system's @code{IF} get used in
8010: any particular context by controlling the order of the word lists on the
8011: search order stack.
1.74 anton 8012:
1.26 crook 8013: @end itemize
1.1 anton 8014:
1.74 anton 8015: The downsides of using wordlists are:
8016:
8017: @itemize
8018:
8019: @item
8020: Debugging becomes more cumbersome.
8021:
8022: @item
8023: Name conflicts worked around with wordlists are still there, and you
8024: have to arrange the search order carefully to get the desired results;
8025: if you forget to do that, you get hard-to-find errors (as in any case
8026: where you read the code differently from the compiler; @code{see} can
1.75 anton 8027: help seeing which of several possible words the name resolves to in such
8028: cases). @code{See} displays just the name of the words, not what
8029: wordlist they belong to, so it might be misleading. Using unique names
8030: is a better approach to avoid name conflicts.
1.74 anton 8031:
8032: @item
8033: You have to explicitly undo any changes to the search order. In many
8034: cases it would be more convenient if this happened implicitly. Gforth
8035: currently does not provide such a feature, but it may do so in the
8036: future.
8037: @end itemize
8038:
8039:
1.75 anton 8040: @node Word list example, , Why use word lists?, Word Lists
8041: @subsection Word list example
8042: @cindex word lists - example
1.1 anton 8043:
1.74 anton 8044: The following example is from the
8045: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8046: garbage collector} and uses wordlists to separate public words from
8047: helper words:
8048:
8049: @example
8050: get-current ( wid )
8051: vocabulary garbage-collector also garbage-collector definitions
8052: ... \ define helper words
8053: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8054: ... \ define the public (i.e., API) words
8055: \ they can refer to the helper words
8056: previous \ restore original search order (helper words become invisible)
8057: @end example
8058:
1.26 crook 8059: @c -------------------------------------------------------------
8060: @node Environmental Queries, Files, Word Lists, Words
8061: @section Environmental Queries
8062: @cindex environmental queries
1.21 crook 8063:
1.26 crook 8064: ANS Forth introduced the idea of ``environmental queries'' as a way
8065: for a program running on a system to determine certain characteristics of the system.
8066: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8067:
1.32 anton 8068: The Standard requires that the header space used for environmental queries
8069: be distinct from the header space used for definitions.
1.21 crook 8070:
1.26 crook 8071: Typically, environmental queries are supported by creating a set of
1.29 crook 8072: definitions in a word list that is @i{only} used during environmental
1.26 crook 8073: queries; that is what Gforth does. There is no Standard way of adding
8074: definitions to the set of recognised environmental queries, but any
8075: implementation that supports the loading of optional word sets must have
8076: some mechanism for doing this (after loading the word set, the
8077: associated environmental query string must return @code{true}). In
8078: Gforth, the word list used to honour environmental queries can be
8079: manipulated just like any other word list.
1.21 crook 8080:
1.44 crook 8081:
1.26 crook 8082: doc-environment?
8083: doc-environment-wordlist
1.21 crook 8084:
1.26 crook 8085: doc-gforth
8086: doc-os-class
1.21 crook 8087:
1.44 crook 8088:
1.26 crook 8089: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8090: returning two items on the stack, querying it using @code{environment?}
8091: will return an additional item; the @code{true} flag that shows that the
8092: string was recognised.
1.21 crook 8093:
1.26 crook 8094: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8095:
1.26 crook 8096: Here are some examples of using environmental queries:
1.21 crook 8097:
1.26 crook 8098: @example
8099: s" address-unit-bits" environment? 0=
8100: [IF]
8101: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8102: [ELSE]
8103: drop \ ensure balanced stack effect
1.26 crook 8104: [THEN]
1.21 crook 8105:
1.75 anton 8106: \ this might occur in the prelude of a standard program that uses THROW
8107: s" exception" environment? [IF]
8108: 0= [IF]
8109: : throw abort" exception thrown" ;
8110: [THEN]
8111: [ELSE] \ we don't know, so make sure
8112: : throw abort" exception thrown" ;
8113: [THEN]
1.21 crook 8114:
1.26 crook 8115: s" gforth" environment? [IF] .( Gforth version ) TYPE
8116: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8117:
8118: \ a program using v*
8119: s" gforth" environment? [IF]
8120: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8121: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8122: >r swap 2swap swap 0e r> 0 ?DO
8123: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8124: LOOP
8125: 2drop 2drop ;
8126: [THEN]
8127: [ELSE] \
8128: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8129: ...
8130: [THEN]
1.26 crook 8131: @end example
1.21 crook 8132:
1.26 crook 8133: Here is an example of adding a definition to the environment word list:
1.21 crook 8134:
1.26 crook 8135: @example
8136: get-current environment-wordlist set-current
8137: true constant block
8138: true constant block-ext
8139: set-current
8140: @end example
1.21 crook 8141:
1.26 crook 8142: You can see what definitions are in the environment word list like this:
1.21 crook 8143:
1.26 crook 8144: @example
1.79 anton 8145: environment-wordlist >order words previous
1.26 crook 8146: @end example
1.21 crook 8147:
8148:
1.26 crook 8149: @c -------------------------------------------------------------
8150: @node Files, Blocks, Environmental Queries, Words
8151: @section Files
1.28 crook 8152: @cindex files
8153: @cindex I/O - file-handling
1.21 crook 8154:
1.26 crook 8155: Gforth provides facilities for accessing files that are stored in the
8156: host operating system's file-system. Files that are processed by Gforth
8157: can be divided into two categories:
1.21 crook 8158:
1.23 crook 8159: @itemize @bullet
8160: @item
1.29 crook 8161: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8162: @item
1.29 crook 8163: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8164: @end itemize
8165:
8166: @menu
1.48 anton 8167: * Forth source files::
8168: * General files::
8169: * Search Paths::
1.26 crook 8170: @end menu
8171:
8172: @c -------------------------------------------------------------
8173: @node Forth source files, General files, Files, Files
8174: @subsection Forth source files
8175: @cindex including files
8176: @cindex Forth source files
1.21 crook 8177:
1.26 crook 8178: The simplest way to interpret the contents of a file is to use one of
8179: these two formats:
1.21 crook 8180:
1.26 crook 8181: @example
8182: include mysource.fs
8183: s" mysource.fs" included
8184: @end example
1.21 crook 8185:
1.75 anton 8186: You usually want to include a file only if it is not included already
1.26 crook 8187: (by, say, another source file). In that case, you can use one of these
1.45 crook 8188: three formats:
1.21 crook 8189:
1.26 crook 8190: @example
8191: require mysource.fs
8192: needs mysource.fs
8193: s" mysource.fs" required
8194: @end example
1.21 crook 8195:
1.26 crook 8196: @cindex stack effect of included files
8197: @cindex including files, stack effect
1.45 crook 8198: It is good practice to write your source files such that interpreting them
8199: does not change the stack. Source files designed in this way can be used with
1.26 crook 8200: @code{required} and friends without complications. For example:
1.21 crook 8201:
1.26 crook 8202: @example
1.75 anton 8203: 1024 require foo.fs drop
1.26 crook 8204: @end example
1.21 crook 8205:
1.75 anton 8206: Here you want to pass the argument 1024 (e.g., a buffer size) to
8207: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8208: ), which allows its use with @code{require}. Of course with such
8209: parameters to required files, you have to ensure that the first
8210: @code{require} fits for all uses (i.e., @code{require} it early in the
8211: master load file).
1.44 crook 8212:
1.26 crook 8213: doc-include-file
8214: doc-included
1.28 crook 8215: doc-included?
1.26 crook 8216: doc-include
8217: doc-required
8218: doc-require
8219: doc-needs
1.75 anton 8220: @c doc-init-included-files @c internal
8221: doc-sourcefilename
8222: doc-sourceline#
1.44 crook 8223:
1.26 crook 8224: A definition in ANS Forth for @code{required} is provided in
8225: @file{compat/required.fs}.
1.21 crook 8226:
1.26 crook 8227: @c -------------------------------------------------------------
8228: @node General files, Search Paths, Forth source files, Files
8229: @subsection General files
8230: @cindex general files
8231: @cindex file-handling
1.21 crook 8232:
1.75 anton 8233: Files are opened/created by name and type. The following file access
8234: methods (FAMs) are recognised:
1.44 crook 8235:
1.75 anton 8236: @cindex fam (file access method)
1.26 crook 8237: doc-r/o
8238: doc-r/w
8239: doc-w/o
8240: doc-bin
1.1 anton 8241:
1.44 crook 8242:
1.26 crook 8243: When a file is opened/created, it returns a file identifier,
1.29 crook 8244: @i{wfileid} that is used for all other file commands. All file
8245: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8246: successful operation and an implementation-defined non-zero value in the
8247: case of an error.
1.21 crook 8248:
1.44 crook 8249:
1.26 crook 8250: doc-open-file
8251: doc-create-file
1.21 crook 8252:
1.26 crook 8253: doc-close-file
8254: doc-delete-file
8255: doc-rename-file
8256: doc-read-file
8257: doc-read-line
8258: doc-write-file
8259: doc-write-line
8260: doc-emit-file
8261: doc-flush-file
1.21 crook 8262:
1.26 crook 8263: doc-file-status
8264: doc-file-position
8265: doc-reposition-file
8266: doc-file-size
8267: doc-resize-file
1.21 crook 8268:
1.93 anton 8269: doc-slurp-file
8270: doc-slurp-fid
1.112 anton 8271: doc-stdin
8272: doc-stdout
8273: doc-stderr
1.44 crook 8274:
1.26 crook 8275: @c ---------------------------------------------------------
1.48 anton 8276: @node Search Paths, , General files, Files
1.26 crook 8277: @subsection Search Paths
8278: @cindex path for @code{included}
8279: @cindex file search path
8280: @cindex @code{include} search path
8281: @cindex search path for files
1.21 crook 8282:
1.26 crook 8283: If you specify an absolute filename (i.e., a filename starting with
8284: @file{/} or @file{~}, or with @file{:} in the second position (as in
8285: @samp{C:...})) for @code{included} and friends, that file is included
8286: just as you would expect.
1.21 crook 8287:
1.75 anton 8288: If the filename starts with @file{./}, this refers to the directory that
8289: the present file was @code{included} from. This allows files to include
8290: other files relative to their own position (irrespective of the current
8291: working directory or the absolute position). This feature is essential
8292: for libraries consisting of several files, where a file may include
8293: other files from the library. It corresponds to @code{#include "..."}
8294: in C. If the current input source is not a file, @file{.} refers to the
8295: directory of the innermost file being included, or, if there is no file
8296: being included, to the current working directory.
8297:
8298: For relative filenames (not starting with @file{./}), Gforth uses a
8299: search path similar to Forth's search order (@pxref{Word Lists}). It
8300: tries to find the given filename in the directories present in the path,
8301: and includes the first one it finds. There are separate search paths for
8302: Forth source files and general files. If the search path contains the
8303: directory @file{.}, this refers to the directory of the current file, or
8304: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8305:
1.26 crook 8306: Use @file{~+} to refer to the current working directory (as in the
8307: @code{bash}).
1.1 anton 8308:
1.75 anton 8309: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8310:
1.48 anton 8311: @menu
1.75 anton 8312: * Source Search Paths::
1.48 anton 8313: * General Search Paths::
8314: @end menu
8315:
1.26 crook 8316: @c ---------------------------------------------------------
1.75 anton 8317: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8318: @subsubsection Source Search Paths
8319: @cindex search path control, source files
1.5 anton 8320:
1.26 crook 8321: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8322: Gforth}). You can display it and change it using @code{fpath} in
8323: combination with the general path handling words.
1.5 anton 8324:
1.75 anton 8325: doc-fpath
8326: @c the functionality of the following words is easily available through
8327: @c fpath and the general path words. The may go away.
8328: @c doc-.fpath
8329: @c doc-fpath+
8330: @c doc-fpath=
8331: @c doc-open-fpath-file
1.44 crook 8332:
8333: @noindent
1.26 crook 8334: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8335:
1.26 crook 8336: @example
1.75 anton 8337: fpath path= /usr/lib/forth/|./
1.26 crook 8338: require timer.fs
8339: @end example
1.5 anton 8340:
1.75 anton 8341:
1.26 crook 8342: @c ---------------------------------------------------------
1.75 anton 8343: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8344: @subsubsection General Search Paths
1.75 anton 8345: @cindex search path control, source files
1.5 anton 8346:
1.26 crook 8347: Your application may need to search files in several directories, like
8348: @code{included} does. To facilitate this, Gforth allows you to define
8349: and use your own search paths, by providing generic equivalents of the
8350: Forth search path words:
1.5 anton 8351:
1.75 anton 8352: doc-open-path-file
8353: doc-path-allot
8354: doc-clear-path
8355: doc-also-path
1.26 crook 8356: doc-.path
8357: doc-path+
8358: doc-path=
1.5 anton 8359:
1.75 anton 8360: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8361:
1.75 anton 8362: Here's an example of creating an empty search path:
8363: @c
1.26 crook 8364: @example
1.75 anton 8365: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8366: @end example
1.5 anton 8367:
1.26 crook 8368: @c -------------------------------------------------------------
8369: @node Blocks, Other I/O, Files, Words
8370: @section Blocks
1.28 crook 8371: @cindex I/O - blocks
8372: @cindex blocks
8373:
8374: When you run Gforth on a modern desk-top computer, it runs under the
8375: control of an operating system which provides certain services. One of
8376: these services is @var{file services}, which allows Forth source code
8377: and data to be stored in files and read into Gforth (@pxref{Files}).
8378:
8379: Traditionally, Forth has been an important programming language on
8380: systems where it has interfaced directly to the underlying hardware with
8381: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8382: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8383:
8384: A block is a 1024-byte data area, which can be used to hold data or
8385: Forth source code. No structure is imposed on the contents of the
8386: block. A block is identified by its number; blocks are numbered
8387: contiguously from 1 to an implementation-defined maximum.
8388:
8389: A typical system that used blocks but no operating system might use a
8390: single floppy-disk drive for mass storage, with the disks formatted to
8391: provide 256-byte sectors. Blocks would be implemented by assigning the
8392: first four sectors of the disk to block 1, the second four sectors to
8393: block 2 and so on, up to the limit of the capacity of the disk. The disk
8394: would not contain any file system information, just the set of blocks.
8395:
1.29 crook 8396: @cindex blocks file
1.28 crook 8397: On systems that do provide file services, blocks are typically
1.29 crook 8398: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8399: file}. The size of the blocks file will be an exact multiple of 1024
8400: bytes, corresponding to the number of blocks it contains. This is the
8401: mechanism that Gforth uses.
8402:
1.29 crook 8403: @cindex @file{blocks.fb}
1.75 anton 8404: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8405: having specified a blocks file, Gforth defaults to the blocks file
8406: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8407: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8408:
1.29 crook 8409: @cindex block buffers
1.28 crook 8410: When you read and write blocks under program control, Gforth uses a
1.29 crook 8411: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8412: not used when you use @code{load} to interpret the contents of a block.
8413:
1.75 anton 8414: The behaviour of the block buffers is analagous to that of a cache.
8415: Each block buffer has three states:
1.28 crook 8416:
8417: @itemize @bullet
8418: @item
8419: Unassigned
8420: @item
8421: Assigned-clean
8422: @item
8423: Assigned-dirty
8424: @end itemize
8425:
1.29 crook 8426: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8427: block, the block (specified by its block number) must be assigned to a
8428: block buffer.
8429:
8430: The assignment of a block to a block buffer is performed by @code{block}
8431: or @code{buffer}. Use @code{block} when you wish to modify the existing
8432: contents of a block. Use @code{buffer} when you don't care about the
8433: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8434: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8435: with the particular block is already stored in a block buffer due to an
8436: earlier @code{block} command, @code{buffer} will return that block
8437: buffer and the existing contents of the block will be
8438: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8439: block buffer for the block.}.
1.28 crook 8440:
1.47 crook 8441: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8442: @code{buffer}, that block buffer becomes the @i{current block
8443: buffer}. Data may only be manipulated (read or written) within the
8444: current block buffer.
1.47 crook 8445:
8446: When the contents of the current block buffer has been modified it is
1.48 anton 8447: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8448: either abandon the changes (by doing nothing) or mark the block as
8449: changed (assigned-dirty), using @code{update}. Using @code{update} does
8450: not change the blocks file; it simply changes a block buffer's state to
8451: @i{assigned-dirty}. The block will be written implicitly when it's
8452: buffer is needed for another block, or explicitly by @code{flush} or
8453: @code{save-buffers}.
8454:
8455: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8456: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8457: @code{flush}.
1.28 crook 8458:
1.29 crook 8459: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8460: algorithm to assign a block buffer to a block. That means that any
8461: particular block can only be assigned to one specific block buffer,
1.29 crook 8462: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8463: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8464: the new block immediately. If it is @i{assigned-dirty} its current
8465: contents are written back to the blocks file on disk before it is
1.28 crook 8466: allocated to the new block.
8467:
8468: Although no structure is imposed on the contents of a block, it is
8469: traditional to display the contents as 16 lines each of 64 characters. A
8470: block provides a single, continuous stream of input (for example, it
8471: acts as a single parse area) -- there are no end-of-line characters
8472: within a block, and no end-of-file character at the end of a
8473: block. There are two consequences of this:
1.26 crook 8474:
1.28 crook 8475: @itemize @bullet
8476: @item
8477: The last character of one line wraps straight into the first character
8478: of the following line
8479: @item
8480: The word @code{\} -- comment to end of line -- requires special
8481: treatment; in the context of a block it causes all characters until the
8482: end of the current 64-character ``line'' to be ignored.
8483: @end itemize
8484:
8485: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8486: the current blocks file will be extended to the appropriate size and the
1.28 crook 8487: block buffer will be initialised with spaces.
8488:
1.47 crook 8489: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8490: for details) but doesn't encourage the use of blocks; the mechanism is
8491: only provided for backward compatibility -- ANS Forth requires blocks to
8492: be available when files are.
1.28 crook 8493:
8494: Common techniques that are used when working with blocks include:
8495:
8496: @itemize @bullet
8497: @item
8498: A screen editor that allows you to edit blocks without leaving the Forth
8499: environment.
8500: @item
8501: Shadow screens; where every code block has an associated block
8502: containing comments (for example: code in odd block numbers, comments in
8503: even block numbers). Typically, the block editor provides a convenient
8504: mechanism to toggle between code and comments.
8505: @item
8506: Load blocks; a single block (typically block 1) contains a number of
8507: @code{thru} commands which @code{load} the whole of the application.
8508: @end itemize
1.26 crook 8509:
1.29 crook 8510: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8511: integrated into a Forth programming environment.
1.26 crook 8512:
8513: @comment TODO what about errors on open-blocks?
1.44 crook 8514:
1.26 crook 8515: doc-open-blocks
8516: doc-use
1.75 anton 8517: doc-block-offset
1.26 crook 8518: doc-get-block-fid
8519: doc-block-position
1.28 crook 8520:
1.75 anton 8521: doc-list
1.28 crook 8522: doc-scr
8523:
1.45 crook 8524: doc---gforthman-block
1.28 crook 8525: doc-buffer
8526:
1.75 anton 8527: doc-empty-buffers
8528: doc-empty-buffer
1.26 crook 8529: doc-update
1.28 crook 8530: doc-updated?
1.26 crook 8531: doc-save-buffers
1.75 anton 8532: doc-save-buffer
1.26 crook 8533: doc-flush
1.28 crook 8534:
1.26 crook 8535: doc-load
8536: doc-thru
8537: doc-+load
8538: doc-+thru
1.45 crook 8539: doc---gforthman--->
1.26 crook 8540: doc-block-included
8541:
1.44 crook 8542:
1.26 crook 8543: @c -------------------------------------------------------------
1.126 pazsan 8544: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8545: @section Other I/O
1.28 crook 8546: @cindex I/O - keyboard and display
1.26 crook 8547:
8548: @menu
8549: * Simple numeric output:: Predefined formats
8550: * Formatted numeric output:: Formatted (pictured) output
8551: * String Formats:: How Forth stores strings in memory
1.67 anton 8552: * Displaying characters and strings:: Other stuff
1.26 crook 8553: * Input:: Input
1.112 anton 8554: * Pipes:: How to create your own pipes
1.26 crook 8555: @end menu
8556:
8557: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8558: @subsection Simple numeric output
1.28 crook 8559: @cindex numeric output - simple/free-format
1.5 anton 8560:
1.26 crook 8561: The simplest output functions are those that display numbers from the
8562: data or floating-point stacks. Floating-point output is always displayed
8563: using base 10. Numbers displayed from the data stack use the value stored
8564: in @code{base}.
1.5 anton 8565:
1.44 crook 8566:
1.26 crook 8567: doc-.
8568: doc-dec.
8569: doc-hex.
8570: doc-u.
8571: doc-.r
8572: doc-u.r
8573: doc-d.
8574: doc-ud.
8575: doc-d.r
8576: doc-ud.r
8577: doc-f.
8578: doc-fe.
8579: doc-fs.
1.111 anton 8580: doc-f.rdp
1.44 crook 8581:
1.26 crook 8582: Examples of printing the number 1234.5678E23 in the different floating-point output
8583: formats are shown below:
1.5 anton 8584:
8585: @example
1.26 crook 8586: f. 123456779999999000000000000.
8587: fe. 123.456779999999E24
8588: fs. 1.23456779999999E26
1.5 anton 8589: @end example
8590:
8591:
1.26 crook 8592: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8593: @subsection Formatted numeric output
1.28 crook 8594: @cindex formatted numeric output
1.26 crook 8595: @cindex pictured numeric output
1.28 crook 8596: @cindex numeric output - formatted
1.26 crook 8597:
1.29 crook 8598: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8599: output} for formatted printing of integers. In this technique, digits
8600: are extracted from the number (using the current output radix defined by
8601: @code{base}), converted to ASCII codes and appended to a string that is
8602: built in a scratch-pad area of memory (@pxref{core-idef,
8603: Implementation-defined options, Implementation-defined
8604: options}). Arbitrary characters can be appended to the string during the
8605: extraction process. The completed string is specified by an address
8606: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8607: under program control.
1.5 anton 8608:
1.75 anton 8609: All of the integer output words described in the previous section
8610: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8611: numeric output.
1.5 anton 8612:
1.47 crook 8613: Three important things to remember about pictured numeric output:
1.5 anton 8614:
1.26 crook 8615: @itemize @bullet
8616: @item
1.28 crook 8617: It always operates on double-precision numbers; to display a
1.49 anton 8618: single-precision number, convert it first (for ways of doing this
8619: @pxref{Double precision}).
1.26 crook 8620: @item
1.28 crook 8621: It always treats the double-precision number as though it were
8622: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8623: @item
8624: The string is built up from right to left; least significant digit first.
8625: @end itemize
1.5 anton 8626:
1.44 crook 8627:
1.26 crook 8628: doc-<#
1.47 crook 8629: doc-<<#
1.26 crook 8630: doc-#
8631: doc-#s
8632: doc-hold
8633: doc-sign
8634: doc-#>
1.47 crook 8635: doc-#>>
1.5 anton 8636:
1.26 crook 8637: doc-represent
1.111 anton 8638: doc-f>str-rdp
8639: doc-f>buf-rdp
1.5 anton 8640:
1.44 crook 8641:
8642: @noindent
1.26 crook 8643: Here are some examples of using pictured numeric output:
1.5 anton 8644:
8645: @example
1.26 crook 8646: : my-u. ( u -- )
8647: \ Simplest use of pns.. behaves like Standard u.
8648: 0 \ convert to unsigned double
1.75 anton 8649: <<# \ start conversion
1.26 crook 8650: #s \ convert all digits
8651: #> \ complete conversion
1.75 anton 8652: TYPE SPACE \ display, with trailing space
8653: #>> ; \ release hold area
1.5 anton 8654:
1.26 crook 8655: : cents-only ( u -- )
8656: 0 \ convert to unsigned double
1.75 anton 8657: <<# \ start conversion
1.26 crook 8658: # # \ convert two least-significant digits
8659: #> \ complete conversion, discard other digits
1.75 anton 8660: TYPE SPACE \ display, with trailing space
8661: #>> ; \ release hold area
1.5 anton 8662:
1.26 crook 8663: : dollars-and-cents ( u -- )
8664: 0 \ convert to unsigned double
1.75 anton 8665: <<# \ start conversion
1.26 crook 8666: # # \ convert two least-significant digits
8667: [char] . hold \ insert decimal point
8668: #s \ convert remaining digits
8669: [char] $ hold \ append currency symbol
8670: #> \ complete conversion
1.75 anton 8671: TYPE SPACE \ display, with trailing space
8672: #>> ; \ release hold area
1.5 anton 8673:
1.26 crook 8674: : my-. ( n -- )
8675: \ handling negatives.. behaves like Standard .
8676: s>d \ convert to signed double
8677: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8678: <<# \ start conversion
1.26 crook 8679: #s \ convert all digits
8680: rot sign \ get at sign byte, append "-" if needed
8681: #> \ complete conversion
1.75 anton 8682: TYPE SPACE \ display, with trailing space
8683: #>> ; \ release hold area
1.5 anton 8684:
1.26 crook 8685: : account. ( n -- )
1.75 anton 8686: \ accountants don't like minus signs, they use parentheses
1.26 crook 8687: \ for negative numbers
8688: s>d \ convert to signed double
8689: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8690: <<# \ start conversion
1.26 crook 8691: 2 pick \ get copy of sign byte
8692: 0< IF [char] ) hold THEN \ right-most character of output
8693: #s \ convert all digits
8694: rot \ get at sign byte
8695: 0< IF [char] ( hold THEN
8696: #> \ complete conversion
1.75 anton 8697: TYPE SPACE \ display, with trailing space
8698: #>> ; \ release hold area
8699:
1.5 anton 8700: @end example
8701:
1.26 crook 8702: Here are some examples of using these words:
1.5 anton 8703:
8704: @example
1.26 crook 8705: 1 my-u. 1
8706: hex -1 my-u. decimal FFFFFFFF
8707: 1 cents-only 01
8708: 1234 cents-only 34
8709: 2 dollars-and-cents $0.02
8710: 1234 dollars-and-cents $12.34
8711: 123 my-. 123
8712: -123 my. -123
8713: 123 account. 123
8714: -456 account. (456)
1.5 anton 8715: @end example
8716:
8717:
1.26 crook 8718: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8719: @subsection String Formats
1.27 crook 8720: @cindex strings - see character strings
8721: @cindex character strings - formats
1.28 crook 8722: @cindex I/O - see character strings
1.75 anton 8723: @cindex counted strings
8724:
8725: @c anton: this does not really belong here; maybe the memory section,
8726: @c or the principles chapter
1.26 crook 8727:
1.27 crook 8728: Forth commonly uses two different methods for representing character
8729: strings:
1.26 crook 8730:
8731: @itemize @bullet
8732: @item
8733: @cindex address of counted string
1.45 crook 8734: @cindex counted string
1.29 crook 8735: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8736: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8737: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8738: memory.
8739: @item
1.29 crook 8740: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8741: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8742: first byte of the string.
8743: @end itemize
8744:
8745: ANS Forth encourages the use of the second format when representing
1.75 anton 8746: strings.
1.26 crook 8747:
1.44 crook 8748:
1.26 crook 8749: doc-count
8750:
1.44 crook 8751:
1.49 anton 8752: For words that move, copy and search for strings see @ref{Memory
8753: Blocks}. For words that display characters and strings see
8754: @ref{Displaying characters and strings}.
1.26 crook 8755:
8756: @node Displaying characters and strings, Input, String Formats, Other I/O
8757: @subsection Displaying characters and strings
1.27 crook 8758: @cindex characters - compiling and displaying
8759: @cindex character strings - compiling and displaying
1.26 crook 8760:
8761: This section starts with a glossary of Forth words and ends with a set
8762: of examples.
8763:
1.44 crook 8764:
1.26 crook 8765: doc-bl
8766: doc-space
8767: doc-spaces
8768: doc-emit
8769: doc-toupper
8770: doc-."
8771: doc-.(
1.98 anton 8772: doc-.\"
1.26 crook 8773: doc-type
1.44 crook 8774: doc-typewhite
1.26 crook 8775: doc-cr
1.27 crook 8776: @cindex cursor control
1.26 crook 8777: doc-at-xy
8778: doc-page
8779: doc-s"
1.98 anton 8780: doc-s\"
1.26 crook 8781: doc-c"
8782: doc-char
8783: doc-[char]
8784:
1.44 crook 8785:
8786: @noindent
1.26 crook 8787: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8788:
8789: @example
1.26 crook 8790: .( text-1)
8791: : my-word
8792: ." text-2" cr
8793: .( text-3)
8794: ;
8795:
8796: ." text-4"
8797:
8798: : my-char
8799: [char] ALPHABET emit
8800: char emit
8801: ;
1.5 anton 8802: @end example
8803:
1.26 crook 8804: When you load this code into Gforth, the following output is generated:
1.5 anton 8805:
1.26 crook 8806: @example
1.30 anton 8807: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8808: @end example
1.5 anton 8809:
1.26 crook 8810: @itemize @bullet
8811: @item
8812: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8813: is an immediate word; it behaves in the same way whether it is used inside
8814: or outside a colon definition.
8815: @item
8816: Message @code{text-4} is displayed because of Gforth's added interpretation
8817: semantics for @code{."}.
8818: @item
1.29 crook 8819: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8820: performs the compilation semantics for @code{."} within the definition of
8821: @code{my-word}.
8822: @end itemize
1.5 anton 8823:
1.26 crook 8824: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8825:
1.26 crook 8826: @example
1.30 anton 8827: @kbd{my-word @key{RET}} text-2
1.26 crook 8828: ok
1.30 anton 8829: @kbd{my-char fred @key{RET}} Af ok
8830: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8831: @end example
1.5 anton 8832:
8833: @itemize @bullet
8834: @item
1.26 crook 8835: Message @code{text-2} is displayed because of the run-time behaviour of
8836: @code{."}.
8837: @item
8838: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8839: on the stack at run-time. @code{emit} always displays the character
8840: when @code{my-char} is executed.
8841: @item
8842: @code{char} parses a string at run-time and the second @code{emit} displays
8843: the first character of the string.
1.5 anton 8844: @item
1.26 crook 8845: If you type @code{see my-char} you can see that @code{[char]} discarded
8846: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8847: definition of @code{my-char}.
1.5 anton 8848: @end itemize
8849:
8850:
8851:
1.112 anton 8852: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8853: @subsection Input
8854: @cindex input
1.28 crook 8855: @cindex I/O - see input
8856: @cindex parsing a string
1.5 anton 8857:
1.49 anton 8858: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8859:
1.27 crook 8860: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8861: @comment then index them
1.27 crook 8862:
1.44 crook 8863:
1.27 crook 8864: doc-key
8865: doc-key?
1.45 crook 8866: doc-ekey
8867: doc-ekey?
8868: doc-ekey>char
1.26 crook 8869: doc->number
8870: doc->float
8871: doc-accept
1.109 anton 8872: doc-edit-line
1.27 crook 8873: doc-pad
8874: @comment obsolescent words..
8875: doc-convert
1.26 crook 8876: doc-expect
1.27 crook 8877: doc-span
1.5 anton 8878:
8879:
1.112 anton 8880: @node Pipes, , Input, Other I/O
8881: @subsection Pipes
8882: @cindex pipes, creating your own
8883:
8884: In addition to using Gforth in pipes created by other processes
8885: (@pxref{Gforth in pipes}), you can create your own pipe with
8886: @code{open-pipe}, and read from or write to it.
8887:
8888: doc-open-pipe
8889: doc-close-pipe
8890:
8891: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8892: you don't catch this exception, Gforth will catch it and exit, usually
8893: silently (@pxref{Gforth in pipes}). Since you probably do not want
8894: this, you should wrap a @code{catch} or @code{try} block around the code
8895: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8896: problem yourself, and then return to regular processing.
8897:
8898: doc-broken-pipe-error
8899:
8900:
1.121 anton 8901: @node OS command line arguments, Locals, Other I/O, Words
8902: @section OS command line arguments
8903: @cindex OS command line arguments
8904: @cindex command line arguments, OS
8905: @cindex arguments, OS command line
8906:
8907: The usual way to pass arguments to Gforth programs on the command line
8908: is via the @option{-e} option, e.g.
8909:
8910: @example
8911: gforth -e "123 456" foo.fs -e bye
8912: @end example
8913:
8914: However, you may want to interpret the command-line arguments directly.
8915: In that case, you can access the (image-specific) command-line arguments
1.123 anton 8916: through @code{next-arg}:
1.121 anton 8917:
1.123 anton 8918: doc-next-arg
1.121 anton 8919:
1.123 anton 8920: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 8921:
8922: @example
8923: : echo ( -- )
1.122 anton 8924: begin
1.123 anton 8925: next-arg 2dup 0 0 d<> while
8926: type space
8927: repeat
8928: 2drop ;
1.121 anton 8929:
8930: echo cr bye
8931: @end example
8932:
8933: This can be invoked with
8934:
8935: @example
8936: gforth echo.fs hello world
8937: @end example
1.123 anton 8938:
8939: and it will print
8940:
8941: @example
8942: hello world
8943: @end example
8944:
8945: The next lower level of dealing with the OS command line are the
8946: following words:
8947:
8948: doc-arg
8949: doc-shift-args
8950:
8951: Finally, at the lowest level Gforth provides the following words:
8952:
8953: doc-argc
8954: doc-argv
1.121 anton 8955:
1.78 anton 8956: @c -------------------------------------------------------------
1.126 pazsan 8957: @node Locals, Structures, OS command line arguments, Words
1.78 anton 8958: @section Locals
8959: @cindex locals
8960:
8961: Local variables can make Forth programming more enjoyable and Forth
8962: programs easier to read. Unfortunately, the locals of ANS Forth are
8963: laden with restrictions. Therefore, we provide not only the ANS Forth
8964: locals wordset, but also our own, more powerful locals wordset (we
8965: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 8966:
1.78 anton 8967: The ideas in this section have also been published in M. Anton Ertl,
8968: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8969: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 8970:
8971: @menu
1.78 anton 8972: * Gforth locals::
8973: * ANS Forth locals::
1.5 anton 8974: @end menu
8975:
1.78 anton 8976: @node Gforth locals, ANS Forth locals, Locals, Locals
8977: @subsection Gforth locals
8978: @cindex Gforth locals
8979: @cindex locals, Gforth style
1.5 anton 8980:
1.78 anton 8981: Locals can be defined with
1.44 crook 8982:
1.78 anton 8983: @example
8984: @{ local1 local2 ... -- comment @}
8985: @end example
8986: or
8987: @example
8988: @{ local1 local2 ... @}
8989: @end example
1.5 anton 8990:
1.78 anton 8991: E.g.,
8992: @example
8993: : max @{ n1 n2 -- n3 @}
8994: n1 n2 > if
8995: n1
8996: else
8997: n2
8998: endif ;
8999: @end example
1.44 crook 9000:
1.78 anton 9001: The similarity of locals definitions with stack comments is intended. A
9002: locals definition often replaces the stack comment of a word. The order
9003: of the locals corresponds to the order in a stack comment and everything
9004: after the @code{--} is really a comment.
1.77 anton 9005:
1.78 anton 9006: This similarity has one disadvantage: It is too easy to confuse locals
9007: declarations with stack comments, causing bugs and making them hard to
9008: find. However, this problem can be avoided by appropriate coding
9009: conventions: Do not use both notations in the same program. If you do,
9010: they should be distinguished using additional means, e.g. by position.
1.77 anton 9011:
1.78 anton 9012: @cindex types of locals
9013: @cindex locals types
9014: The name of the local may be preceded by a type specifier, e.g.,
9015: @code{F:} for a floating point value:
1.5 anton 9016:
1.78 anton 9017: @example
9018: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9019: \ complex multiplication
9020: Ar Br f* Ai Bi f* f-
9021: Ar Bi f* Ai Br f* f+ ;
9022: @end example
1.44 crook 9023:
1.78 anton 9024: @cindex flavours of locals
9025: @cindex locals flavours
9026: @cindex value-flavoured locals
9027: @cindex variable-flavoured locals
9028: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9029: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9030: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9031: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9032: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9033: produces its address (which becomes invalid when the variable's scope is
9034: left). E.g., the standard word @code{emit} can be defined in terms of
9035: @code{type} like this:
1.5 anton 9036:
1.78 anton 9037: @example
9038: : emit @{ C^ char* -- @}
9039: char* 1 type ;
9040: @end example
1.5 anton 9041:
1.78 anton 9042: @cindex default type of locals
9043: @cindex locals, default type
9044: A local without type specifier is a @code{W:} local. Both flavours of
9045: locals are initialized with values from the data or FP stack.
1.44 crook 9046:
1.78 anton 9047: Currently there is no way to define locals with user-defined data
9048: structures, but we are working on it.
1.5 anton 9049:
1.78 anton 9050: Gforth allows defining locals everywhere in a colon definition. This
9051: poses the following questions:
1.5 anton 9052:
1.78 anton 9053: @menu
9054: * Where are locals visible by name?::
9055: * How long do locals live?::
9056: * Locals programming style::
9057: * Locals implementation::
9058: @end menu
1.44 crook 9059:
1.78 anton 9060: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9061: @subsubsection Where are locals visible by name?
9062: @cindex locals visibility
9063: @cindex visibility of locals
9064: @cindex scope of locals
1.5 anton 9065:
1.78 anton 9066: Basically, the answer is that locals are visible where you would expect
9067: it in block-structured languages, and sometimes a little longer. If you
9068: want to restrict the scope of a local, enclose its definition in
9069: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9070:
9071:
1.78 anton 9072: doc-scope
9073: doc-endscope
1.5 anton 9074:
9075:
1.78 anton 9076: These words behave like control structure words, so you can use them
9077: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9078: arbitrary ways.
1.77 anton 9079:
1.78 anton 9080: If you want a more exact answer to the visibility question, here's the
9081: basic principle: A local is visible in all places that can only be
9082: reached through the definition of the local@footnote{In compiler
9083: construction terminology, all places dominated by the definition of the
9084: local.}. In other words, it is not visible in places that can be reached
9085: without going through the definition of the local. E.g., locals defined
9086: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9087: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9088: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9089:
1.78 anton 9090: The reasoning behind this solution is: We want to have the locals
9091: visible as long as it is meaningful. The user can always make the
9092: visibility shorter by using explicit scoping. In a place that can
9093: only be reached through the definition of a local, the meaning of a
9094: local name is clear. In other places it is not: How is the local
9095: initialized at the control flow path that does not contain the
9096: definition? Which local is meant, if the same name is defined twice in
9097: two independent control flow paths?
1.77 anton 9098:
1.78 anton 9099: This should be enough detail for nearly all users, so you can skip the
9100: rest of this section. If you really must know all the gory details and
9101: options, read on.
1.77 anton 9102:
1.78 anton 9103: In order to implement this rule, the compiler has to know which places
9104: are unreachable. It knows this automatically after @code{AHEAD},
9105: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9106: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9107: compiler that the control flow never reaches that place. If
9108: @code{UNREACHABLE} is not used where it could, the only consequence is
9109: that the visibility of some locals is more limited than the rule above
9110: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9111: lie to the compiler), buggy code will be produced.
1.77 anton 9112:
1.5 anton 9113:
1.78 anton 9114: doc-unreachable
1.5 anton 9115:
1.23 crook 9116:
1.78 anton 9117: Another problem with this rule is that at @code{BEGIN}, the compiler
9118: does not know which locals will be visible on the incoming
9119: back-edge. All problems discussed in the following are due to this
9120: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9121: loops as examples; the discussion also applies to @code{?DO} and other
9122: loops). Perhaps the most insidious example is:
1.26 crook 9123: @example
1.78 anton 9124: AHEAD
9125: BEGIN
9126: x
9127: [ 1 CS-ROLL ] THEN
9128: @{ x @}
9129: ...
9130: UNTIL
1.26 crook 9131: @end example
1.23 crook 9132:
1.78 anton 9133: This should be legal according to the visibility rule. The use of
9134: @code{x} can only be reached through the definition; but that appears
9135: textually below the use.
9136:
9137: From this example it is clear that the visibility rules cannot be fully
9138: implemented without major headaches. Our implementation treats common
9139: cases as advertised and the exceptions are treated in a safe way: The
9140: compiler makes a reasonable guess about the locals visible after a
9141: @code{BEGIN}; if it is too pessimistic, the
9142: user will get a spurious error about the local not being defined; if the
9143: compiler is too optimistic, it will notice this later and issue a
9144: warning. In the case above the compiler would complain about @code{x}
9145: being undefined at its use. You can see from the obscure examples in
9146: this section that it takes quite unusual control structures to get the
9147: compiler into trouble, and even then it will often do fine.
1.23 crook 9148:
1.78 anton 9149: If the @code{BEGIN} is reachable from above, the most optimistic guess
9150: is that all locals visible before the @code{BEGIN} will also be
9151: visible after the @code{BEGIN}. This guess is valid for all loops that
9152: are entered only through the @code{BEGIN}, in particular, for normal
9153: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9154: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9155: compiler. When the branch to the @code{BEGIN} is finally generated by
9156: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9157: warns the user if it was too optimistic:
1.26 crook 9158: @example
1.78 anton 9159: IF
9160: @{ x @}
9161: BEGIN
9162: \ x ?
9163: [ 1 cs-roll ] THEN
9164: ...
9165: UNTIL
1.26 crook 9166: @end example
1.23 crook 9167:
1.78 anton 9168: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9169: optimistically assumes that it lives until the @code{THEN}. It notices
9170: this difference when it compiles the @code{UNTIL} and issues a
9171: warning. The user can avoid the warning, and make sure that @code{x}
9172: is not used in the wrong area by using explicit scoping:
9173: @example
9174: IF
9175: SCOPE
9176: @{ x @}
9177: ENDSCOPE
9178: BEGIN
9179: [ 1 cs-roll ] THEN
9180: ...
9181: UNTIL
9182: @end example
1.23 crook 9183:
1.78 anton 9184: Since the guess is optimistic, there will be no spurious error messages
9185: about undefined locals.
1.44 crook 9186:
1.78 anton 9187: If the @code{BEGIN} is not reachable from above (e.g., after
9188: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9189: optimistic guess, as the locals visible after the @code{BEGIN} may be
9190: defined later. Therefore, the compiler assumes that no locals are
9191: visible after the @code{BEGIN}. However, the user can use
9192: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9193: visible at the BEGIN as at the point where the top control-flow stack
9194: item was created.
1.23 crook 9195:
1.44 crook 9196:
1.78 anton 9197: doc-assume-live
1.26 crook 9198:
1.23 crook 9199:
1.78 anton 9200: @noindent
9201: E.g.,
9202: @example
9203: @{ x @}
9204: AHEAD
9205: ASSUME-LIVE
9206: BEGIN
9207: x
9208: [ 1 CS-ROLL ] THEN
9209: ...
9210: UNTIL
9211: @end example
1.44 crook 9212:
1.78 anton 9213: Other cases where the locals are defined before the @code{BEGIN} can be
9214: handled by inserting an appropriate @code{CS-ROLL} before the
9215: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9216: behind the @code{ASSUME-LIVE}).
1.23 crook 9217:
1.78 anton 9218: Cases where locals are defined after the @code{BEGIN} (but should be
9219: visible immediately after the @code{BEGIN}) can only be handled by
9220: rearranging the loop. E.g., the ``most insidious'' example above can be
9221: arranged into:
9222: @example
9223: BEGIN
9224: @{ x @}
9225: ... 0=
9226: WHILE
9227: x
9228: REPEAT
9229: @end example
1.44 crook 9230:
1.78 anton 9231: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9232: @subsubsection How long do locals live?
9233: @cindex locals lifetime
9234: @cindex lifetime of locals
1.23 crook 9235:
1.78 anton 9236: The right answer for the lifetime question would be: A local lives at
9237: least as long as it can be accessed. For a value-flavoured local this
9238: means: until the end of its visibility. However, a variable-flavoured
9239: local could be accessed through its address far beyond its visibility
9240: scope. Ultimately, this would mean that such locals would have to be
9241: garbage collected. Since this entails un-Forth-like implementation
9242: complexities, I adopted the same cowardly solution as some other
9243: languages (e.g., C): The local lives only as long as it is visible;
9244: afterwards its address is invalid (and programs that access it
9245: afterwards are erroneous).
1.23 crook 9246:
1.78 anton 9247: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9248: @subsubsection Locals programming style
9249: @cindex locals programming style
9250: @cindex programming style, locals
1.23 crook 9251:
1.78 anton 9252: The freedom to define locals anywhere has the potential to change
9253: programming styles dramatically. In particular, the need to use the
9254: return stack for intermediate storage vanishes. Moreover, all stack
9255: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9256: determined arguments) can be eliminated: If the stack items are in the
9257: wrong order, just write a locals definition for all of them; then
9258: write the items in the order you want.
1.23 crook 9259:
1.78 anton 9260: This seems a little far-fetched and eliminating stack manipulations is
9261: unlikely to become a conscious programming objective. Still, the number
9262: of stack manipulations will be reduced dramatically if local variables
9263: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9264: a traditional implementation of @code{max}).
1.23 crook 9265:
1.78 anton 9266: This shows one potential benefit of locals: making Forth programs more
9267: readable. Of course, this benefit will only be realized if the
9268: programmers continue to honour the principle of factoring instead of
9269: using the added latitude to make the words longer.
1.23 crook 9270:
1.78 anton 9271: @cindex single-assignment style for locals
9272: Using @code{TO} can and should be avoided. Without @code{TO},
9273: every value-flavoured local has only a single assignment and many
9274: advantages of functional languages apply to Forth. I.e., programs are
9275: easier to analyse, to optimize and to read: It is clear from the
9276: definition what the local stands for, it does not turn into something
9277: different later.
1.23 crook 9278:
1.78 anton 9279: E.g., a definition using @code{TO} might look like this:
9280: @example
9281: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9282: u1 u2 min 0
9283: ?do
9284: addr1 c@@ addr2 c@@ -
9285: ?dup-if
9286: unloop exit
9287: then
9288: addr1 char+ TO addr1
9289: addr2 char+ TO addr2
9290: loop
9291: u1 u2 - ;
1.26 crook 9292: @end example
1.78 anton 9293: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9294: every loop iteration. @code{strcmp} is a typical example of the
9295: readability problems of using @code{TO}. When you start reading
9296: @code{strcmp}, you think that @code{addr1} refers to the start of the
9297: string. Only near the end of the loop you realize that it is something
9298: else.
1.23 crook 9299:
1.78 anton 9300: This can be avoided by defining two locals at the start of the loop that
9301: are initialized with the right value for the current iteration.
9302: @example
9303: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9304: addr1 addr2
9305: u1 u2 min 0
9306: ?do @{ s1 s2 @}
9307: s1 c@@ s2 c@@ -
9308: ?dup-if
9309: unloop exit
9310: then
9311: s1 char+ s2 char+
9312: loop
9313: 2drop
9314: u1 u2 - ;
9315: @end example
9316: Here it is clear from the start that @code{s1} has a different value
9317: in every loop iteration.
1.23 crook 9318:
1.78 anton 9319: @node Locals implementation, , Locals programming style, Gforth locals
9320: @subsubsection Locals implementation
9321: @cindex locals implementation
9322: @cindex implementation of locals
1.23 crook 9323:
1.78 anton 9324: @cindex locals stack
9325: Gforth uses an extra locals stack. The most compelling reason for
9326: this is that the return stack is not float-aligned; using an extra stack
9327: also eliminates the problems and restrictions of using the return stack
9328: as locals stack. Like the other stacks, the locals stack grows toward
9329: lower addresses. A few primitives allow an efficient implementation:
9330:
9331:
9332: doc-@local#
9333: doc-f@local#
9334: doc-laddr#
9335: doc-lp+!#
9336: doc-lp!
9337: doc->l
9338: doc-f>l
9339:
9340:
9341: In addition to these primitives, some specializations of these
9342: primitives for commonly occurring inline arguments are provided for
9343: efficiency reasons, e.g., @code{@@local0} as specialization of
9344: @code{@@local#} for the inline argument 0. The following compiling words
9345: compile the right specialized version, or the general version, as
9346: appropriate:
1.23 crook 9347:
1.5 anton 9348:
1.107 dvdkhlng 9349: @c doc-compile-@local
9350: @c doc-compile-f@local
1.78 anton 9351: doc-compile-lp+!
1.5 anton 9352:
9353:
1.78 anton 9354: Combinations of conditional branches and @code{lp+!#} like
9355: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9356: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9357:
1.78 anton 9358: A special area in the dictionary space is reserved for keeping the
9359: local variable names. @code{@{} switches the dictionary pointer to this
9360: area and @code{@}} switches it back and generates the locals
9361: initializing code. @code{W:} etc.@ are normal defining words. This
9362: special area is cleared at the start of every colon definition.
1.5 anton 9363:
1.78 anton 9364: @cindex word list for defining locals
9365: A special feature of Gforth's dictionary is used to implement the
9366: definition of locals without type specifiers: every word list (aka
9367: vocabulary) has its own methods for searching
9368: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9369: with a special search method: When it is searched for a word, it
9370: actually creates that word using @code{W:}. @code{@{} changes the search
9371: order to first search the word list containing @code{@}}, @code{W:} etc.,
9372: and then the word list for defining locals without type specifiers.
1.5 anton 9373:
1.78 anton 9374: The lifetime rules support a stack discipline within a colon
9375: definition: The lifetime of a local is either nested with other locals
9376: lifetimes or it does not overlap them.
1.23 crook 9377:
1.78 anton 9378: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9379: pointer manipulation is generated. Between control structure words
9380: locals definitions can push locals onto the locals stack. @code{AGAIN}
9381: is the simplest of the other three control flow words. It has to
9382: restore the locals stack depth of the corresponding @code{BEGIN}
9383: before branching. The code looks like this:
9384: @format
9385: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9386: @code{branch} <begin>
9387: @end format
1.26 crook 9388:
1.78 anton 9389: @code{UNTIL} is a little more complicated: If it branches back, it
9390: must adjust the stack just like @code{AGAIN}. But if it falls through,
9391: the locals stack must not be changed. The compiler generates the
9392: following code:
9393: @format
9394: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9395: @end format
9396: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9397:
1.78 anton 9398: @code{THEN} can produce somewhat inefficient code:
9399: @format
9400: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9401: <orig target>:
9402: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9403: @end format
9404: The second @code{lp+!#} adjusts the locals stack pointer from the
9405: level at the @i{orig} point to the level after the @code{THEN}. The
9406: first @code{lp+!#} adjusts the locals stack pointer from the current
9407: level to the level at the orig point, so the complete effect is an
9408: adjustment from the current level to the right level after the
9409: @code{THEN}.
1.26 crook 9410:
1.78 anton 9411: @cindex locals information on the control-flow stack
9412: @cindex control-flow stack items, locals information
9413: In a conventional Forth implementation a dest control-flow stack entry
9414: is just the target address and an orig entry is just the address to be
9415: patched. Our locals implementation adds a word list to every orig or dest
9416: item. It is the list of locals visible (or assumed visible) at the point
9417: described by the entry. Our implementation also adds a tag to identify
9418: the kind of entry, in particular to differentiate between live and dead
9419: (reachable and unreachable) orig entries.
1.26 crook 9420:
1.78 anton 9421: A few unusual operations have to be performed on locals word lists:
1.44 crook 9422:
1.5 anton 9423:
1.78 anton 9424: doc-common-list
9425: doc-sub-list?
9426: doc-list-size
1.52 anton 9427:
9428:
1.78 anton 9429: Several features of our locals word list implementation make these
9430: operations easy to implement: The locals word lists are organised as
9431: linked lists; the tails of these lists are shared, if the lists
9432: contain some of the same locals; and the address of a name is greater
9433: than the address of the names behind it in the list.
1.5 anton 9434:
1.78 anton 9435: Another important implementation detail is the variable
9436: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9437: determine if they can be reached directly or only through the branch
9438: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9439: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9440: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9441:
1.78 anton 9442: Counted loops are similar to other loops in most respects, but
9443: @code{LEAVE} requires special attention: It performs basically the same
9444: service as @code{AHEAD}, but it does not create a control-flow stack
9445: entry. Therefore the information has to be stored elsewhere;
9446: traditionally, the information was stored in the target fields of the
9447: branches created by the @code{LEAVE}s, by organizing these fields into a
9448: linked list. Unfortunately, this clever trick does not provide enough
9449: space for storing our extended control flow information. Therefore, we
9450: introduce another stack, the leave stack. It contains the control-flow
9451: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9452:
1.78 anton 9453: Local names are kept until the end of the colon definition, even if
9454: they are no longer visible in any control-flow path. In a few cases
9455: this may lead to increased space needs for the locals name area, but
9456: usually less than reclaiming this space would cost in code size.
1.5 anton 9457:
1.44 crook 9458:
1.78 anton 9459: @node ANS Forth locals, , Gforth locals, Locals
9460: @subsection ANS Forth locals
9461: @cindex locals, ANS Forth style
1.5 anton 9462:
1.78 anton 9463: The ANS Forth locals wordset does not define a syntax for locals, but
9464: words that make it possible to define various syntaxes. One of the
9465: possible syntaxes is a subset of the syntax we used in the Gforth locals
9466: wordset, i.e.:
1.29 crook 9467:
9468: @example
1.78 anton 9469: @{ local1 local2 ... -- comment @}
9470: @end example
9471: @noindent
9472: or
9473: @example
9474: @{ local1 local2 ... @}
1.29 crook 9475: @end example
9476:
1.78 anton 9477: The order of the locals corresponds to the order in a stack comment. The
9478: restrictions are:
1.5 anton 9479:
1.78 anton 9480: @itemize @bullet
9481: @item
9482: Locals can only be cell-sized values (no type specifiers are allowed).
9483: @item
9484: Locals can be defined only outside control structures.
9485: @item
9486: Locals can interfere with explicit usage of the return stack. For the
9487: exact (and long) rules, see the standard. If you don't use return stack
9488: accessing words in a definition using locals, you will be all right. The
9489: purpose of this rule is to make locals implementation on the return
9490: stack easier.
9491: @item
9492: The whole definition must be in one line.
9493: @end itemize
1.5 anton 9494:
1.78 anton 9495: Locals defined in ANS Forth behave like @code{VALUE}s
9496: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9497: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9498:
1.78 anton 9499: Since the syntax above is supported by Gforth directly, you need not do
9500: anything to use it. If you want to port a program using this syntax to
9501: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9502: syntax on the other system.
1.5 anton 9503:
1.78 anton 9504: Note that a syntax shown in the standard, section A.13 looks
9505: similar, but is quite different in having the order of locals
9506: reversed. Beware!
1.5 anton 9507:
1.78 anton 9508: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9509:
1.78 anton 9510: doc-(local)
1.5 anton 9511:
1.78 anton 9512: The ANS Forth locals extension wordset defines a syntax using
9513: @code{locals|}, but it is so awful that we strongly recommend not to use
9514: it. We have implemented this syntax to make porting to Gforth easy, but
9515: do not document it here. The problem with this syntax is that the locals
9516: are defined in an order reversed with respect to the standard stack
9517: comment notation, making programs harder to read, and easier to misread
9518: and miswrite. The only merit of this syntax is that it is easy to
9519: implement using the ANS Forth locals wordset.
1.53 anton 9520:
9521:
1.78 anton 9522: @c ----------------------------------------------------------
9523: @node Structures, Object-oriented Forth, Locals, Words
9524: @section Structures
9525: @cindex structures
9526: @cindex records
1.53 anton 9527:
1.78 anton 9528: This section presents the structure package that comes with Gforth. A
9529: version of the package implemented in ANS Forth is available in
9530: @file{compat/struct.fs}. This package was inspired by a posting on
9531: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9532: possibly John Hayes). A version of this section has been published in
9533: M. Anton Ertl,
9534: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9535: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9536: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9537:
1.78 anton 9538: @menu
9539: * Why explicit structure support?::
9540: * Structure Usage::
9541: * Structure Naming Convention::
9542: * Structure Implementation::
9543: * Structure Glossary::
9544: @end menu
1.55 anton 9545:
1.78 anton 9546: @node Why explicit structure support?, Structure Usage, Structures, Structures
9547: @subsection Why explicit structure support?
1.53 anton 9548:
1.78 anton 9549: @cindex address arithmetic for structures
9550: @cindex structures using address arithmetic
9551: If we want to use a structure containing several fields, we could simply
9552: reserve memory for it, and access the fields using address arithmetic
9553: (@pxref{Address arithmetic}). As an example, consider a structure with
9554: the following fields
1.57 anton 9555:
1.78 anton 9556: @table @code
9557: @item a
9558: is a float
9559: @item b
9560: is a cell
9561: @item c
9562: is a float
9563: @end table
1.57 anton 9564:
1.78 anton 9565: Given the (float-aligned) base address of the structure we get the
9566: address of the field
1.52 anton 9567:
1.78 anton 9568: @table @code
9569: @item a
9570: without doing anything further.
9571: @item b
9572: with @code{float+}
9573: @item c
9574: with @code{float+ cell+ faligned}
9575: @end table
1.52 anton 9576:
1.78 anton 9577: It is easy to see that this can become quite tiring.
1.52 anton 9578:
1.78 anton 9579: Moreover, it is not very readable, because seeing a
9580: @code{cell+} tells us neither which kind of structure is
9581: accessed nor what field is accessed; we have to somehow infer the kind
9582: of structure, and then look up in the documentation, which field of
9583: that structure corresponds to that offset.
1.53 anton 9584:
1.78 anton 9585: Finally, this kind of address arithmetic also causes maintenance
9586: troubles: If you add or delete a field somewhere in the middle of the
9587: structure, you have to find and change all computations for the fields
9588: afterwards.
1.52 anton 9589:
1.78 anton 9590: So, instead of using @code{cell+} and friends directly, how
9591: about storing the offsets in constants:
1.52 anton 9592:
1.78 anton 9593: @example
9594: 0 constant a-offset
9595: 0 float+ constant b-offset
9596: 0 float+ cell+ faligned c-offset
9597: @end example
1.64 pazsan 9598:
1.78 anton 9599: Now we can get the address of field @code{x} with @code{x-offset
9600: +}. This is much better in all respects. Of course, you still
9601: have to change all later offset definitions if you add a field. You can
9602: fix this by declaring the offsets in the following way:
1.57 anton 9603:
1.78 anton 9604: @example
9605: 0 constant a-offset
9606: a-offset float+ constant b-offset
9607: b-offset cell+ faligned constant c-offset
9608: @end example
1.57 anton 9609:
1.78 anton 9610: Since we always use the offsets with @code{+}, we could use a defining
9611: word @code{cfield} that includes the @code{+} in the action of the
9612: defined word:
1.64 pazsan 9613:
1.78 anton 9614: @example
9615: : cfield ( n "name" -- )
9616: create ,
9617: does> ( name execution: addr1 -- addr2 )
9618: @@ + ;
1.64 pazsan 9619:
1.78 anton 9620: 0 cfield a
9621: 0 a float+ cfield b
9622: 0 b cell+ faligned cfield c
9623: @end example
1.64 pazsan 9624:
1.78 anton 9625: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9626:
1.78 anton 9627: The structure field words now can be used quite nicely. However,
9628: their definition is still a bit cumbersome: We have to repeat the
9629: name, the information about size and alignment is distributed before
9630: and after the field definitions etc. The structure package presented
9631: here addresses these problems.
1.64 pazsan 9632:
1.78 anton 9633: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9634: @subsection Structure Usage
9635: @cindex structure usage
1.57 anton 9636:
1.78 anton 9637: @cindex @code{field} usage
9638: @cindex @code{struct} usage
9639: @cindex @code{end-struct} usage
9640: You can define a structure for a (data-less) linked list with:
1.57 anton 9641: @example
1.78 anton 9642: struct
9643: cell% field list-next
9644: end-struct list%
1.57 anton 9645: @end example
9646:
1.78 anton 9647: With the address of the list node on the stack, you can compute the
9648: address of the field that contains the address of the next node with
9649: @code{list-next}. E.g., you can determine the length of a list
9650: with:
1.57 anton 9651:
9652: @example
1.78 anton 9653: : list-length ( list -- n )
9654: \ "list" is a pointer to the first element of a linked list
9655: \ "n" is the length of the list
9656: 0 BEGIN ( list1 n1 )
9657: over
9658: WHILE ( list1 n1 )
9659: 1+ swap list-next @@ swap
9660: REPEAT
9661: nip ;
1.57 anton 9662: @end example
9663:
1.78 anton 9664: You can reserve memory for a list node in the dictionary with
9665: @code{list% %allot}, which leaves the address of the list node on the
9666: stack. For the equivalent allocation on the heap you can use @code{list%
9667: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9668: use @code{list% %allocate}). You can get the the size of a list
9669: node with @code{list% %size} and its alignment with @code{list%
9670: %alignment}.
9671:
9672: Note that in ANS Forth the body of a @code{create}d word is
9673: @code{aligned} but not necessarily @code{faligned};
9674: therefore, if you do a:
1.57 anton 9675:
9676: @example
1.78 anton 9677: create @emph{name} foo% %allot drop
1.57 anton 9678: @end example
9679:
1.78 anton 9680: @noindent
9681: then the memory alloted for @code{foo%} is guaranteed to start at the
9682: body of @code{@emph{name}} only if @code{foo%} contains only character,
9683: cell and double fields. Therefore, if your structure contains floats,
9684: better use
1.57 anton 9685:
9686: @example
1.78 anton 9687: foo% %allot constant @emph{name}
1.57 anton 9688: @end example
9689:
1.78 anton 9690: @cindex structures containing structures
9691: You can include a structure @code{foo%} as a field of
9692: another structure, like this:
1.65 anton 9693: @example
1.78 anton 9694: struct
9695: ...
9696: foo% field ...
9697: ...
9698: end-struct ...
1.65 anton 9699: @end example
1.52 anton 9700:
1.78 anton 9701: @cindex structure extension
9702: @cindex extended records
9703: Instead of starting with an empty structure, you can extend an
9704: existing structure. E.g., a plain linked list without data, as defined
9705: above, is hardly useful; You can extend it to a linked list of integers,
9706: like this:@footnote{This feature is also known as @emph{extended
9707: records}. It is the main innovation in the Oberon language; in other
9708: words, adding this feature to Modula-2 led Wirth to create a new
9709: language, write a new compiler etc. Adding this feature to Forth just
9710: required a few lines of code.}
1.52 anton 9711:
1.78 anton 9712: @example
9713: list%
9714: cell% field intlist-int
9715: end-struct intlist%
9716: @end example
1.55 anton 9717:
1.78 anton 9718: @code{intlist%} is a structure with two fields:
9719: @code{list-next} and @code{intlist-int}.
1.55 anton 9720:
1.78 anton 9721: @cindex structures containing arrays
9722: You can specify an array type containing @emph{n} elements of
9723: type @code{foo%} like this:
1.55 anton 9724:
9725: @example
1.78 anton 9726: foo% @emph{n} *
1.56 anton 9727: @end example
1.55 anton 9728:
1.78 anton 9729: You can use this array type in any place where you can use a normal
9730: type, e.g., when defining a @code{field}, or with
9731: @code{%allot}.
9732:
9733: @cindex first field optimization
9734: The first field is at the base address of a structure and the word for
9735: this field (e.g., @code{list-next}) actually does not change the address
9736: on the stack. You may be tempted to leave it away in the interest of
9737: run-time and space efficiency. This is not necessary, because the
9738: structure package optimizes this case: If you compile a first-field
9739: words, no code is generated. So, in the interest of readability and
9740: maintainability you should include the word for the field when accessing
9741: the field.
1.52 anton 9742:
9743:
1.78 anton 9744: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9745: @subsection Structure Naming Convention
9746: @cindex structure naming convention
1.52 anton 9747:
1.78 anton 9748: The field names that come to (my) mind are often quite generic, and,
9749: if used, would cause frequent name clashes. E.g., many structures
9750: probably contain a @code{counter} field. The structure names
9751: that come to (my) mind are often also the logical choice for the names
9752: of words that create such a structure.
1.52 anton 9753:
1.78 anton 9754: Therefore, I have adopted the following naming conventions:
1.52 anton 9755:
1.78 anton 9756: @itemize @bullet
9757: @cindex field naming convention
9758: @item
9759: The names of fields are of the form
9760: @code{@emph{struct}-@emph{field}}, where
9761: @code{@emph{struct}} is the basic name of the structure, and
9762: @code{@emph{field}} is the basic name of the field. You can
9763: think of field words as converting the (address of the)
9764: structure into the (address of the) field.
1.52 anton 9765:
1.78 anton 9766: @cindex structure naming convention
9767: @item
9768: The names of structures are of the form
9769: @code{@emph{struct}%}, where
9770: @code{@emph{struct}} is the basic name of the structure.
9771: @end itemize
1.52 anton 9772:
1.78 anton 9773: This naming convention does not work that well for fields of extended
9774: structures; e.g., the integer list structure has a field
9775: @code{intlist-int}, but has @code{list-next}, not
9776: @code{intlist-next}.
1.53 anton 9777:
1.78 anton 9778: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9779: @subsection Structure Implementation
9780: @cindex structure implementation
9781: @cindex implementation of structures
1.52 anton 9782:
1.78 anton 9783: The central idea in the implementation is to pass the data about the
9784: structure being built on the stack, not in some global
9785: variable. Everything else falls into place naturally once this design
9786: decision is made.
1.53 anton 9787:
1.78 anton 9788: The type description on the stack is of the form @emph{align
9789: size}. Keeping the size on the top-of-stack makes dealing with arrays
9790: very simple.
1.53 anton 9791:
1.78 anton 9792: @code{field} is a defining word that uses @code{Create}
9793: and @code{DOES>}. The body of the field contains the offset
9794: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9795:
9796: @example
1.78 anton 9797: @@ +
1.53 anton 9798: @end example
9799:
1.78 anton 9800: @noindent
9801: i.e., add the offset to the address, giving the stack effect
9802: @i{addr1 -- addr2} for a field.
9803:
9804: @cindex first field optimization, implementation
9805: This simple structure is slightly complicated by the optimization
9806: for fields with offset 0, which requires a different
9807: @code{DOES>}-part (because we cannot rely on there being
9808: something on the stack if such a field is invoked during
9809: compilation). Therefore, we put the different @code{DOES>}-parts
9810: in separate words, and decide which one to invoke based on the
9811: offset. For a zero offset, the field is basically a noop; it is
9812: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9813:
1.78 anton 9814: @node Structure Glossary, , Structure Implementation, Structures
9815: @subsection Structure Glossary
9816: @cindex structure glossary
1.53 anton 9817:
1.5 anton 9818:
1.78 anton 9819: doc-%align
9820: doc-%alignment
9821: doc-%alloc
9822: doc-%allocate
9823: doc-%allot
9824: doc-cell%
9825: doc-char%
9826: doc-dfloat%
9827: doc-double%
9828: doc-end-struct
9829: doc-field
9830: doc-float%
9831: doc-naligned
9832: doc-sfloat%
9833: doc-%size
9834: doc-struct
1.54 anton 9835:
9836:
1.26 crook 9837: @c -------------------------------------------------------------
1.78 anton 9838: @node Object-oriented Forth, Programming Tools, Structures, Words
9839: @section Object-oriented Forth
9840:
9841: Gforth comes with three packages for object-oriented programming:
9842: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9843: is preloaded, so you have to @code{include} them before use. The most
9844: important differences between these packages (and others) are discussed
9845: in @ref{Comparison with other object models}. All packages are written
9846: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9847:
1.78 anton 9848: @menu
9849: * Why object-oriented programming?::
9850: * Object-Oriented Terminology::
9851: * Objects::
9852: * OOF::
9853: * Mini-OOF::
9854: * Comparison with other object models::
9855: @end menu
1.5 anton 9856:
1.78 anton 9857: @c ----------------------------------------------------------------
9858: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9859: @subsection Why object-oriented programming?
9860: @cindex object-oriented programming motivation
9861: @cindex motivation for object-oriented programming
1.44 crook 9862:
1.78 anton 9863: Often we have to deal with several data structures (@emph{objects}),
9864: that have to be treated similarly in some respects, but differently in
9865: others. Graphical objects are the textbook example: circles, triangles,
9866: dinosaurs, icons, and others, and we may want to add more during program
9867: development. We want to apply some operations to any graphical object,
9868: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9869: has to do something different for every kind of object.
9870: @comment TODO add some other operations eg perimeter, area
9871: @comment and tie in to concrete examples later..
1.5 anton 9872:
1.78 anton 9873: We could implement @code{draw} as a big @code{CASE}
9874: control structure that executes the appropriate code depending on the
9875: kind of object to be drawn. This would be not be very elegant, and,
9876: moreover, we would have to change @code{draw} every time we add
9877: a new kind of graphical object (say, a spaceship).
1.44 crook 9878:
1.78 anton 9879: What we would rather do is: When defining spaceships, we would tell
9880: the system: ``Here's how you @code{draw} a spaceship; you figure
9881: out the rest''.
1.5 anton 9882:
1.78 anton 9883: This is the problem that all systems solve that (rightfully) call
9884: themselves object-oriented; the object-oriented packages presented here
9885: solve this problem (and not much else).
9886: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9887:
1.78 anton 9888: @c ------------------------------------------------------------------------
9889: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9890: @subsection Object-Oriented Terminology
9891: @cindex object-oriented terminology
9892: @cindex terminology for object-oriented programming
1.5 anton 9893:
1.78 anton 9894: This section is mainly for reference, so you don't have to understand
9895: all of it right away. The terminology is mainly Smalltalk-inspired. In
9896: short:
1.44 crook 9897:
1.78 anton 9898: @table @emph
9899: @cindex class
9900: @item class
9901: a data structure definition with some extras.
1.5 anton 9902:
1.78 anton 9903: @cindex object
9904: @item object
9905: an instance of the data structure described by the class definition.
1.5 anton 9906:
1.78 anton 9907: @cindex instance variables
9908: @item instance variables
9909: fields of the data structure.
1.5 anton 9910:
1.78 anton 9911: @cindex selector
9912: @cindex method selector
9913: @cindex virtual function
9914: @item selector
9915: (or @emph{method selector}) a word (e.g.,
9916: @code{draw}) that performs an operation on a variety of data
9917: structures (classes). A selector describes @emph{what} operation to
9918: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9919:
1.78 anton 9920: @cindex method
9921: @item method
9922: the concrete definition that performs the operation
9923: described by the selector for a specific class. A method specifies
9924: @emph{how} the operation is performed for a specific class.
1.5 anton 9925:
1.78 anton 9926: @cindex selector invocation
9927: @cindex message send
9928: @cindex invoking a selector
9929: @item selector invocation
9930: a call of a selector. One argument of the call (the TOS (top-of-stack))
9931: is used for determining which method is used. In Smalltalk terminology:
9932: a message (consisting of the selector and the other arguments) is sent
9933: to the object.
1.5 anton 9934:
1.78 anton 9935: @cindex receiving object
9936: @item receiving object
9937: the object used for determining the method executed by a selector
9938: invocation. In the @file{objects.fs} model, it is the object that is on
9939: the TOS when the selector is invoked. (@emph{Receiving} comes from
9940: the Smalltalk @emph{message} terminology.)
1.5 anton 9941:
1.78 anton 9942: @cindex child class
9943: @cindex parent class
9944: @cindex inheritance
9945: @item child class
9946: a class that has (@emph{inherits}) all properties (instance variables,
9947: selectors, methods) from a @emph{parent class}. In Smalltalk
9948: terminology: The subclass inherits from the superclass. In C++
9949: terminology: The derived class inherits from the base class.
1.5 anton 9950:
1.78 anton 9951: @end table
1.5 anton 9952:
1.78 anton 9953: @c If you wonder about the message sending terminology, it comes from
9954: @c a time when each object had it's own task and objects communicated via
9955: @c message passing; eventually the Smalltalk developers realized that
9956: @c they can do most things through simple (indirect) calls. They kept the
9957: @c terminology.
1.5 anton 9958:
1.78 anton 9959: @c --------------------------------------------------------------
9960: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9961: @subsection The @file{objects.fs} model
9962: @cindex objects
9963: @cindex object-oriented programming
1.26 crook 9964:
1.78 anton 9965: @cindex @file{objects.fs}
9966: @cindex @file{oof.fs}
1.26 crook 9967:
1.78 anton 9968: This section describes the @file{objects.fs} package. This material also
9969: has been published in M. Anton Ertl,
9970: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9971: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9972: 37--43.
9973: @c McKewan's and Zsoter's packages
1.26 crook 9974:
1.78 anton 9975: This section assumes that you have read @ref{Structures}.
1.5 anton 9976:
1.78 anton 9977: The techniques on which this model is based have been used to implement
9978: the parser generator, Gray, and have also been used in Gforth for
9979: implementing the various flavours of word lists (hashed or not,
9980: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 9981:
9982:
1.26 crook 9983: @menu
1.78 anton 9984: * Properties of the Objects model::
9985: * Basic Objects Usage::
9986: * The Objects base class::
9987: * Creating objects::
9988: * Object-Oriented Programming Style::
9989: * Class Binding::
9990: * Method conveniences::
9991: * Classes and Scoping::
9992: * Dividing classes::
9993: * Object Interfaces::
9994: * Objects Implementation::
9995: * Objects Glossary::
1.26 crook 9996: @end menu
1.5 anton 9997:
1.78 anton 9998: Marcel Hendrix provided helpful comments on this section.
1.5 anton 9999:
1.78 anton 10000: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10001: @subsubsection Properties of the @file{objects.fs} model
10002: @cindex @file{objects.fs} properties
1.5 anton 10003:
1.78 anton 10004: @itemize @bullet
10005: @item
10006: It is straightforward to pass objects on the stack. Passing
10007: selectors on the stack is a little less convenient, but possible.
1.44 crook 10008:
1.78 anton 10009: @item
10010: Objects are just data structures in memory, and are referenced by their
10011: address. You can create words for objects with normal defining words
10012: like @code{constant}. Likewise, there is no difference between instance
10013: variables that contain objects and those that contain other data.
1.5 anton 10014:
1.78 anton 10015: @item
10016: Late binding is efficient and easy to use.
1.44 crook 10017:
1.78 anton 10018: @item
10019: It avoids parsing, and thus avoids problems with state-smartness
10020: and reduced extensibility; for convenience there are a few parsing
10021: words, but they have non-parsing counterparts. There are also a few
10022: defining words that parse. This is hard to avoid, because all standard
10023: defining words parse (except @code{:noname}); however, such
10024: words are not as bad as many other parsing words, because they are not
10025: state-smart.
1.5 anton 10026:
1.78 anton 10027: @item
10028: It does not try to incorporate everything. It does a few things and does
10029: them well (IMO). In particular, this model was not designed to support
10030: information hiding (although it has features that may help); you can use
10031: a separate package for achieving this.
1.5 anton 10032:
1.78 anton 10033: @item
10034: It is layered; you don't have to learn and use all features to use this
10035: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10036: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10037: are optional and independent of each other.
1.5 anton 10038:
1.78 anton 10039: @item
10040: An implementation in ANS Forth is available.
1.5 anton 10041:
1.78 anton 10042: @end itemize
1.5 anton 10043:
1.44 crook 10044:
1.78 anton 10045: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10046: @subsubsection Basic @file{objects.fs} Usage
10047: @cindex basic objects usage
10048: @cindex objects, basic usage
1.5 anton 10049:
1.78 anton 10050: You can define a class for graphical objects like this:
1.44 crook 10051:
1.78 anton 10052: @cindex @code{class} usage
10053: @cindex @code{end-class} usage
10054: @cindex @code{selector} usage
1.5 anton 10055: @example
1.78 anton 10056: object class \ "object" is the parent class
10057: selector draw ( x y graphical -- )
10058: end-class graphical
10059: @end example
10060:
10061: This code defines a class @code{graphical} with an
10062: operation @code{draw}. We can perform the operation
10063: @code{draw} on any @code{graphical} object, e.g.:
10064:
10065: @example
10066: 100 100 t-rex draw
1.26 crook 10067: @end example
1.5 anton 10068:
1.78 anton 10069: @noindent
10070: where @code{t-rex} is a word (say, a constant) that produces a
10071: graphical object.
10072:
10073: @comment TODO add a 2nd operation eg perimeter.. and use for
10074: @comment a concrete example
1.5 anton 10075:
1.78 anton 10076: @cindex abstract class
10077: How do we create a graphical object? With the present definitions,
10078: we cannot create a useful graphical object. The class
10079: @code{graphical} describes graphical objects in general, but not
10080: any concrete graphical object type (C++ users would call it an
10081: @emph{abstract class}); e.g., there is no method for the selector
10082: @code{draw} in the class @code{graphical}.
1.5 anton 10083:
1.78 anton 10084: For concrete graphical objects, we define child classes of the
10085: class @code{graphical}, e.g.:
1.5 anton 10086:
1.78 anton 10087: @cindex @code{overrides} usage
10088: @cindex @code{field} usage in class definition
1.26 crook 10089: @example
1.78 anton 10090: graphical class \ "graphical" is the parent class
10091: cell% field circle-radius
1.5 anton 10092:
1.78 anton 10093: :noname ( x y circle -- )
10094: circle-radius @@ draw-circle ;
10095: overrides draw
1.5 anton 10096:
1.78 anton 10097: :noname ( n-radius circle -- )
10098: circle-radius ! ;
10099: overrides construct
1.5 anton 10100:
1.78 anton 10101: end-class circle
10102: @end example
1.44 crook 10103:
1.78 anton 10104: Here we define a class @code{circle} as a child of @code{graphical},
10105: with field @code{circle-radius} (which behaves just like a field
10106: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10107: for the selectors @code{draw} and @code{construct} (@code{construct} is
10108: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10109:
1.78 anton 10110: Now we can create a circle on the heap (i.e.,
10111: @code{allocate}d memory) with:
1.44 crook 10112:
1.78 anton 10113: @cindex @code{heap-new} usage
1.5 anton 10114: @example
1.78 anton 10115: 50 circle heap-new constant my-circle
1.5 anton 10116: @end example
10117:
1.78 anton 10118: @noindent
10119: @code{heap-new} invokes @code{construct}, thus
10120: initializing the field @code{circle-radius} with 50. We can draw
10121: this new circle at (100,100) with:
1.5 anton 10122:
10123: @example
1.78 anton 10124: 100 100 my-circle draw
1.5 anton 10125: @end example
10126:
1.78 anton 10127: @cindex selector invocation, restrictions
10128: @cindex class definition, restrictions
10129: Note: You can only invoke a selector if the object on the TOS
10130: (the receiving object) belongs to the class where the selector was
10131: defined or one of its descendents; e.g., you can invoke
10132: @code{draw} only for objects belonging to @code{graphical}
10133: or its descendents (e.g., @code{circle}). Immediately before
10134: @code{end-class}, the search order has to be the same as
10135: immediately after @code{class}.
10136:
10137: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10138: @subsubsection The @file{object.fs} base class
10139: @cindex @code{object} class
10140:
10141: When you define a class, you have to specify a parent class. So how do
10142: you start defining classes? There is one class available from the start:
10143: @code{object}. It is ancestor for all classes and so is the
10144: only class that has no parent. It has two selectors: @code{construct}
10145: and @code{print}.
10146:
10147: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10148: @subsubsection Creating objects
10149: @cindex creating objects
10150: @cindex object creation
10151: @cindex object allocation options
10152:
10153: @cindex @code{heap-new} discussion
10154: @cindex @code{dict-new} discussion
10155: @cindex @code{construct} discussion
10156: You can create and initialize an object of a class on the heap with
10157: @code{heap-new} ( ... class -- object ) and in the dictionary
10158: (allocation with @code{allot}) with @code{dict-new} (
10159: ... class -- object ). Both words invoke @code{construct}, which
10160: consumes the stack items indicated by "..." above.
10161:
10162: @cindex @code{init-object} discussion
10163: @cindex @code{class-inst-size} discussion
10164: If you want to allocate memory for an object yourself, you can get its
10165: alignment and size with @code{class-inst-size 2@@} ( class --
10166: align size ). Once you have memory for an object, you can initialize
10167: it with @code{init-object} ( ... class object -- );
10168: @code{construct} does only a part of the necessary work.
10169:
10170: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10171: @subsubsection Object-Oriented Programming Style
10172: @cindex object-oriented programming style
10173: @cindex programming style, object-oriented
1.5 anton 10174:
1.78 anton 10175: This section is not exhaustive.
1.5 anton 10176:
1.78 anton 10177: @cindex stack effects of selectors
10178: @cindex selectors and stack effects
10179: In general, it is a good idea to ensure that all methods for the
10180: same selector have the same stack effect: when you invoke a selector,
10181: you often have no idea which method will be invoked, so, unless all
10182: methods have the same stack effect, you will not know the stack effect
10183: of the selector invocation.
1.5 anton 10184:
1.78 anton 10185: One exception to this rule is methods for the selector
10186: @code{construct}. We know which method is invoked, because we
10187: specify the class to be constructed at the same place. Actually, I
10188: defined @code{construct} as a selector only to give the users a
10189: convenient way to specify initialization. The way it is used, a
10190: mechanism different from selector invocation would be more natural
10191: (but probably would take more code and more space to explain).
1.5 anton 10192:
1.78 anton 10193: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10194: @subsubsection Class Binding
10195: @cindex class binding
10196: @cindex early binding
1.5 anton 10197:
1.78 anton 10198: @cindex late binding
10199: Normal selector invocations determine the method at run-time depending
10200: on the class of the receiving object. This run-time selection is called
10201: @i{late binding}.
1.5 anton 10202:
1.78 anton 10203: Sometimes it's preferable to invoke a different method. For example,
10204: you might want to use the simple method for @code{print}ing
10205: @code{object}s instead of the possibly long-winded @code{print} method
10206: of the receiver class. You can achieve this by replacing the invocation
10207: of @code{print} with:
1.5 anton 10208:
1.78 anton 10209: @cindex @code{[bind]} usage
1.5 anton 10210: @example
1.78 anton 10211: [bind] object print
1.5 anton 10212: @end example
10213:
1.78 anton 10214: @noindent
10215: in compiled code or:
10216:
10217: @cindex @code{bind} usage
1.5 anton 10218: @example
1.78 anton 10219: bind object print
1.5 anton 10220: @end example
10221:
1.78 anton 10222: @cindex class binding, alternative to
10223: @noindent
10224: in interpreted code. Alternatively, you can define the method with a
10225: name (e.g., @code{print-object}), and then invoke it through the
10226: name. Class binding is just a (often more convenient) way to achieve
10227: the same effect; it avoids name clutter and allows you to invoke
10228: methods directly without naming them first.
1.5 anton 10229:
1.78 anton 10230: @cindex superclass binding
10231: @cindex parent class binding
10232: A frequent use of class binding is this: When we define a method
10233: for a selector, we often want the method to do what the selector does
10234: in the parent class, and a little more. There is a special word for
10235: this purpose: @code{[parent]}; @code{[parent]
10236: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10237: selector}}, where @code{@emph{parent}} is the parent
10238: class of the current class. E.g., a method definition might look like:
1.44 crook 10239:
1.78 anton 10240: @cindex @code{[parent]} usage
10241: @example
10242: :noname
10243: dup [parent] foo \ do parent's foo on the receiving object
10244: ... \ do some more
10245: ; overrides foo
10246: @end example
1.6 pazsan 10247:
1.78 anton 10248: @cindex class binding as optimization
10249: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10250: March 1997), Andrew McKewan presents class binding as an optimization
10251: technique. I recommend not using it for this purpose unless you are in
10252: an emergency. Late binding is pretty fast with this model anyway, so the
10253: benefit of using class binding is small; the cost of using class binding
10254: where it is not appropriate is reduced maintainability.
1.44 crook 10255:
1.78 anton 10256: While we are at programming style questions: You should bind
10257: selectors only to ancestor classes of the receiving object. E.g., say,
10258: you know that the receiving object is of class @code{foo} or its
10259: descendents; then you should bind only to @code{foo} and its
10260: ancestors.
1.12 anton 10261:
1.78 anton 10262: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10263: @subsubsection Method conveniences
10264: @cindex method conveniences
1.44 crook 10265:
1.78 anton 10266: In a method you usually access the receiving object pretty often. If
10267: you define the method as a plain colon definition (e.g., with
10268: @code{:noname}), you may have to do a lot of stack
10269: gymnastics. To avoid this, you can define the method with @code{m:
10270: ... ;m}. E.g., you could define the method for
10271: @code{draw}ing a @code{circle} with
1.6 pazsan 10272:
1.78 anton 10273: @cindex @code{this} usage
10274: @cindex @code{m:} usage
10275: @cindex @code{;m} usage
10276: @example
10277: m: ( x y circle -- )
10278: ( x y ) this circle-radius @@ draw-circle ;m
10279: @end example
1.6 pazsan 10280:
1.78 anton 10281: @cindex @code{exit} in @code{m: ... ;m}
10282: @cindex @code{exitm} discussion
10283: @cindex @code{catch} in @code{m: ... ;m}
10284: When this method is executed, the receiver object is removed from the
10285: stack; you can access it with @code{this} (admittedly, in this
10286: example the use of @code{m: ... ;m} offers no advantage). Note
10287: that I specify the stack effect for the whole method (i.e. including
10288: the receiver object), not just for the code between @code{m:}
10289: and @code{;m}. You cannot use @code{exit} in
10290: @code{m:...;m}; instead, use
10291: @code{exitm}.@footnote{Moreover, for any word that calls
10292: @code{catch} and was defined before loading
10293: @code{objects.fs}, you have to redefine it like I redefined
10294: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10295:
1.78 anton 10296: @cindex @code{inst-var} usage
10297: You will frequently use sequences of the form @code{this
10298: @emph{field}} (in the example above: @code{this
10299: circle-radius}). If you use the field only in this way, you can
10300: define it with @code{inst-var} and eliminate the
10301: @code{this} before the field name. E.g., the @code{circle}
10302: class above could also be defined with:
1.6 pazsan 10303:
1.78 anton 10304: @example
10305: graphical class
10306: cell% inst-var radius
1.6 pazsan 10307:
1.78 anton 10308: m: ( x y circle -- )
10309: radius @@ draw-circle ;m
10310: overrides draw
1.6 pazsan 10311:
1.78 anton 10312: m: ( n-radius circle -- )
10313: radius ! ;m
10314: overrides construct
1.6 pazsan 10315:
1.78 anton 10316: end-class circle
10317: @end example
1.6 pazsan 10318:
1.78 anton 10319: @code{radius} can only be used in @code{circle} and its
10320: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10321:
1.78 anton 10322: @cindex @code{inst-value} usage
10323: You can also define fields with @code{inst-value}, which is
10324: to @code{inst-var} what @code{value} is to
10325: @code{variable}. You can change the value of such a field with
10326: @code{[to-inst]}. E.g., we could also define the class
10327: @code{circle} like this:
1.44 crook 10328:
1.78 anton 10329: @example
10330: graphical class
10331: inst-value radius
1.6 pazsan 10332:
1.78 anton 10333: m: ( x y circle -- )
10334: radius draw-circle ;m
10335: overrides draw
1.44 crook 10336:
1.78 anton 10337: m: ( n-radius circle -- )
10338: [to-inst] radius ;m
10339: overrides construct
1.6 pazsan 10340:
1.78 anton 10341: end-class circle
10342: @end example
1.6 pazsan 10343:
1.78 anton 10344: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10345:
1.78 anton 10346: @c Finally, you can define named methods with @code{:m}. One use of this
10347: @c feature is the definition of words that occur only in one class and are
10348: @c not intended to be overridden, but which still need method context
10349: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10350: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10351:
10352:
1.78 anton 10353: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10354: @subsubsection Classes and Scoping
10355: @cindex classes and scoping
10356: @cindex scoping and classes
1.6 pazsan 10357:
1.78 anton 10358: Inheritance is frequent, unlike structure extension. This exacerbates
10359: the problem with the field name convention (@pxref{Structure Naming
10360: Convention}): One always has to remember in which class the field was
10361: originally defined; changing a part of the class structure would require
10362: changes for renaming in otherwise unaffected code.
1.6 pazsan 10363:
1.78 anton 10364: @cindex @code{inst-var} visibility
10365: @cindex @code{inst-value} visibility
10366: To solve this problem, I added a scoping mechanism (which was not in my
10367: original charter): A field defined with @code{inst-var} (or
10368: @code{inst-value}) is visible only in the class where it is defined and in
10369: the descendent classes of this class. Using such fields only makes
10370: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10371:
1.78 anton 10372: This scoping mechanism allows us to use the unadorned field name,
10373: because name clashes with unrelated words become much less likely.
1.6 pazsan 10374:
1.78 anton 10375: @cindex @code{protected} discussion
10376: @cindex @code{private} discussion
10377: Once we have this mechanism, we can also use it for controlling the
10378: visibility of other words: All words defined after
10379: @code{protected} are visible only in the current class and its
10380: descendents. @code{public} restores the compilation
10381: (i.e. @code{current}) word list that was in effect before. If you
10382: have several @code{protected}s without an intervening
10383: @code{public} or @code{set-current}, @code{public}
10384: will restore the compilation word list in effect before the first of
10385: these @code{protected}s.
1.6 pazsan 10386:
1.78 anton 10387: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10388: @subsubsection Dividing classes
10389: @cindex Dividing classes
10390: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10391:
1.78 anton 10392: You may want to do the definition of methods separate from the
10393: definition of the class, its selectors, fields, and instance variables,
10394: i.e., separate the implementation from the definition. You can do this
10395: in the following way:
1.6 pazsan 10396:
1.78 anton 10397: @example
10398: graphical class
10399: inst-value radius
10400: end-class circle
1.6 pazsan 10401:
1.78 anton 10402: ... \ do some other stuff
1.6 pazsan 10403:
1.78 anton 10404: circle methods \ now we are ready
1.44 crook 10405:
1.78 anton 10406: m: ( x y circle -- )
10407: radius draw-circle ;m
10408: overrides draw
1.6 pazsan 10409:
1.78 anton 10410: m: ( n-radius circle -- )
10411: [to-inst] radius ;m
10412: overrides construct
1.44 crook 10413:
1.78 anton 10414: end-methods
10415: @end example
1.7 pazsan 10416:
1.78 anton 10417: You can use several @code{methods}...@code{end-methods} sections. The
10418: only things you can do to the class in these sections are: defining
10419: methods, and overriding the class's selectors. You must not define new
10420: selectors or fields.
1.7 pazsan 10421:
1.78 anton 10422: Note that you often have to override a selector before using it. In
10423: particular, you usually have to override @code{construct} with a new
10424: method before you can invoke @code{heap-new} and friends. E.g., you
10425: must not create a circle before the @code{overrides construct} sequence
10426: in the example above.
1.7 pazsan 10427:
1.78 anton 10428: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10429: @subsubsection Object Interfaces
10430: @cindex object interfaces
10431: @cindex interfaces for objects
1.7 pazsan 10432:
1.78 anton 10433: In this model you can only call selectors defined in the class of the
10434: receiving objects or in one of its ancestors. If you call a selector
10435: with a receiving object that is not in one of these classes, the
10436: result is undefined; if you are lucky, the program crashes
10437: immediately.
1.7 pazsan 10438:
1.78 anton 10439: @cindex selectors common to hardly-related classes
10440: Now consider the case when you want to have a selector (or several)
10441: available in two classes: You would have to add the selector to a
10442: common ancestor class, in the worst case to @code{object}. You
10443: may not want to do this, e.g., because someone else is responsible for
10444: this ancestor class.
1.7 pazsan 10445:
1.78 anton 10446: The solution for this problem is interfaces. An interface is a
10447: collection of selectors. If a class implements an interface, the
10448: selectors become available to the class and its descendents. A class
10449: can implement an unlimited number of interfaces. For the problem
10450: discussed above, we would define an interface for the selector(s), and
10451: both classes would implement the interface.
1.7 pazsan 10452:
1.78 anton 10453: As an example, consider an interface @code{storage} for
10454: writing objects to disk and getting them back, and a class
10455: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10456:
1.78 anton 10457: @cindex @code{interface} usage
10458: @cindex @code{end-interface} usage
10459: @cindex @code{implementation} usage
10460: @example
10461: interface
10462: selector write ( file object -- )
10463: selector read1 ( file object -- )
10464: end-interface storage
1.13 pazsan 10465:
1.78 anton 10466: bar class
10467: storage implementation
1.13 pazsan 10468:
1.78 anton 10469: ... overrides write
10470: ... overrides read1
10471: ...
10472: end-class foo
10473: @end example
1.13 pazsan 10474:
1.78 anton 10475: @noindent
10476: (I would add a word @code{read} @i{( file -- object )} that uses
10477: @code{read1} internally, but that's beyond the point illustrated
10478: here.)
1.13 pazsan 10479:
1.78 anton 10480: Note that you cannot use @code{protected} in an interface; and
10481: of course you cannot define fields.
1.13 pazsan 10482:
1.78 anton 10483: In the Neon model, all selectors are available for all classes;
10484: therefore it does not need interfaces. The price you pay in this model
10485: is slower late binding, and therefore, added complexity to avoid late
10486: binding.
1.13 pazsan 10487:
1.78 anton 10488: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10489: @subsubsection @file{objects.fs} Implementation
10490: @cindex @file{objects.fs} implementation
1.13 pazsan 10491:
1.78 anton 10492: @cindex @code{object-map} discussion
10493: An object is a piece of memory, like one of the data structures
10494: described with @code{struct...end-struct}. It has a field
10495: @code{object-map} that points to the method map for the object's
10496: class.
1.13 pazsan 10497:
1.78 anton 10498: @cindex method map
10499: @cindex virtual function table
10500: The @emph{method map}@footnote{This is Self terminology; in C++
10501: terminology: virtual function table.} is an array that contains the
10502: execution tokens (@i{xt}s) of the methods for the object's class. Each
10503: selector contains an offset into a method map.
1.13 pazsan 10504:
1.78 anton 10505: @cindex @code{selector} implementation, class
10506: @code{selector} is a defining word that uses
10507: @code{CREATE} and @code{DOES>}. The body of the
10508: selector contains the offset; the @code{DOES>} action for a
10509: class selector is, basically:
1.8 pazsan 10510:
10511: @example
1.78 anton 10512: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10513: @end example
10514:
1.78 anton 10515: Since @code{object-map} is the first field of the object, it
10516: does not generate any code. As you can see, calling a selector has a
10517: small, constant cost.
1.26 crook 10518:
1.78 anton 10519: @cindex @code{current-interface} discussion
10520: @cindex class implementation and representation
10521: A class is basically a @code{struct} combined with a method
10522: map. During the class definition the alignment and size of the class
10523: are passed on the stack, just as with @code{struct}s, so
10524: @code{field} can also be used for defining class
10525: fields. However, passing more items on the stack would be
10526: inconvenient, so @code{class} builds a data structure in memory,
10527: which is accessed through the variable
10528: @code{current-interface}. After its definition is complete, the
10529: class is represented on the stack by a pointer (e.g., as parameter for
10530: a child class definition).
1.26 crook 10531:
1.78 anton 10532: A new class starts off with the alignment and size of its parent,
10533: and a copy of the parent's method map. Defining new fields extends the
10534: size and alignment; likewise, defining new selectors extends the
10535: method map. @code{overrides} just stores a new @i{xt} in the method
10536: map at the offset given by the selector.
1.13 pazsan 10537:
1.78 anton 10538: @cindex class binding, implementation
10539: Class binding just gets the @i{xt} at the offset given by the selector
10540: from the class's method map and @code{compile,}s (in the case of
10541: @code{[bind]}) it.
1.13 pazsan 10542:
1.78 anton 10543: @cindex @code{this} implementation
10544: @cindex @code{catch} and @code{this}
10545: @cindex @code{this} and @code{catch}
10546: I implemented @code{this} as a @code{value}. At the
10547: start of an @code{m:...;m} method the old @code{this} is
10548: stored to the return stack and restored at the end; and the object on
10549: the TOS is stored @code{TO this}. This technique has one
10550: disadvantage: If the user does not leave the method via
10551: @code{;m}, but via @code{throw} or @code{exit},
10552: @code{this} is not restored (and @code{exit} may
10553: crash). To deal with the @code{throw} problem, I have redefined
10554: @code{catch} to save and restore @code{this}; the same
10555: should be done with any word that can catch an exception. As for
10556: @code{exit}, I simply forbid it (as a replacement, there is
10557: @code{exitm}).
1.13 pazsan 10558:
1.78 anton 10559: @cindex @code{inst-var} implementation
10560: @code{inst-var} is just the same as @code{field}, with
10561: a different @code{DOES>} action:
1.13 pazsan 10562: @example
1.78 anton 10563: @@ this +
1.8 pazsan 10564: @end example
1.78 anton 10565: Similar for @code{inst-value}.
1.8 pazsan 10566:
1.78 anton 10567: @cindex class scoping implementation
10568: Each class also has a word list that contains the words defined with
10569: @code{inst-var} and @code{inst-value}, and its protected
10570: words. It also has a pointer to its parent. @code{class} pushes
10571: the word lists of the class and all its ancestors onto the search order stack,
10572: and @code{end-class} drops them.
1.20 pazsan 10573:
1.78 anton 10574: @cindex interface implementation
10575: An interface is like a class without fields, parent and protected
10576: words; i.e., it just has a method map. If a class implements an
10577: interface, its method map contains a pointer to the method map of the
10578: interface. The positive offsets in the map are reserved for class
10579: methods, therefore interface map pointers have negative
10580: offsets. Interfaces have offsets that are unique throughout the
10581: system, unlike class selectors, whose offsets are only unique for the
10582: classes where the selector is available (invokable).
1.20 pazsan 10583:
1.78 anton 10584: This structure means that interface selectors have to perform one
10585: indirection more than class selectors to find their method. Their body
10586: contains the interface map pointer offset in the class method map, and
10587: the method offset in the interface method map. The
10588: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10589:
10590: @example
1.78 anton 10591: ( object selector-body )
10592: 2dup selector-interface @@ ( object selector-body object interface-offset )
10593: swap object-map @@ + @@ ( object selector-body map )
10594: swap selector-offset @@ + @@ execute
1.20 pazsan 10595: @end example
10596:
1.78 anton 10597: where @code{object-map} and @code{selector-offset} are
10598: first fields and generate no code.
1.20 pazsan 10599:
1.78 anton 10600: As a concrete example, consider the following code:
1.20 pazsan 10601:
10602: @example
1.78 anton 10603: interface
10604: selector if1sel1
10605: selector if1sel2
10606: end-interface if1
1.20 pazsan 10607:
1.78 anton 10608: object class
10609: if1 implementation
10610: selector cl1sel1
10611: cell% inst-var cl1iv1
1.20 pazsan 10612:
1.78 anton 10613: ' m1 overrides construct
10614: ' m2 overrides if1sel1
10615: ' m3 overrides if1sel2
10616: ' m4 overrides cl1sel2
10617: end-class cl1
1.20 pazsan 10618:
1.78 anton 10619: create obj1 object dict-new drop
10620: create obj2 cl1 dict-new drop
10621: @end example
1.20 pazsan 10622:
1.78 anton 10623: The data structure created by this code (including the data structure
10624: for @code{object}) is shown in the
10625: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10626: @comment TODO add this diagram..
1.20 pazsan 10627:
1.78 anton 10628: @node Objects Glossary, , Objects Implementation, Objects
10629: @subsubsection @file{objects.fs} Glossary
10630: @cindex @file{objects.fs} Glossary
1.20 pazsan 10631:
10632:
1.78 anton 10633: doc---objects-bind
10634: doc---objects-<bind>
10635: doc---objects-bind'
10636: doc---objects-[bind]
10637: doc---objects-class
10638: doc---objects-class->map
10639: doc---objects-class-inst-size
10640: doc---objects-class-override!
1.79 anton 10641: doc---objects-class-previous
10642: doc---objects-class>order
1.78 anton 10643: doc---objects-construct
10644: doc---objects-current'
10645: doc---objects-[current]
10646: doc---objects-current-interface
10647: doc---objects-dict-new
10648: doc---objects-end-class
10649: doc---objects-end-class-noname
10650: doc---objects-end-interface
10651: doc---objects-end-interface-noname
10652: doc---objects-end-methods
10653: doc---objects-exitm
10654: doc---objects-heap-new
10655: doc---objects-implementation
10656: doc---objects-init-object
10657: doc---objects-inst-value
10658: doc---objects-inst-var
10659: doc---objects-interface
10660: doc---objects-m:
10661: doc---objects-:m
10662: doc---objects-;m
10663: doc---objects-method
10664: doc---objects-methods
10665: doc---objects-object
10666: doc---objects-overrides
10667: doc---objects-[parent]
10668: doc---objects-print
10669: doc---objects-protected
10670: doc---objects-public
10671: doc---objects-selector
10672: doc---objects-this
10673: doc---objects-<to-inst>
10674: doc---objects-[to-inst]
10675: doc---objects-to-this
10676: doc---objects-xt-new
1.20 pazsan 10677:
10678:
1.78 anton 10679: @c -------------------------------------------------------------
10680: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10681: @subsection The @file{oof.fs} model
10682: @cindex oof
10683: @cindex object-oriented programming
1.20 pazsan 10684:
1.78 anton 10685: @cindex @file{objects.fs}
10686: @cindex @file{oof.fs}
1.20 pazsan 10687:
1.78 anton 10688: This section describes the @file{oof.fs} package.
1.20 pazsan 10689:
1.78 anton 10690: The package described in this section has been used in bigFORTH since 1991, and
10691: used for two large applications: a chromatographic system used to
10692: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10693:
1.78 anton 10694: You can find a description (in German) of @file{oof.fs} in @cite{Object
10695: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10696: 10(2), 1994.
1.20 pazsan 10697:
1.78 anton 10698: @menu
10699: * Properties of the OOF model::
10700: * Basic OOF Usage::
10701: * The OOF base class::
10702: * Class Declaration::
10703: * Class Implementation::
10704: @end menu
1.20 pazsan 10705:
1.78 anton 10706: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10707: @subsubsection Properties of the @file{oof.fs} model
10708: @cindex @file{oof.fs} properties
1.20 pazsan 10709:
1.78 anton 10710: @itemize @bullet
10711: @item
10712: This model combines object oriented programming with information
10713: hiding. It helps you writing large application, where scoping is
10714: necessary, because it provides class-oriented scoping.
1.20 pazsan 10715:
1.78 anton 10716: @item
10717: Named objects, object pointers, and object arrays can be created,
10718: selector invocation uses the ``object selector'' syntax. Selector invocation
10719: to objects and/or selectors on the stack is a bit less convenient, but
10720: possible.
1.44 crook 10721:
1.78 anton 10722: @item
10723: Selector invocation and instance variable usage of the active object is
10724: straightforward, since both make use of the active object.
1.44 crook 10725:
1.78 anton 10726: @item
10727: Late binding is efficient and easy to use.
1.20 pazsan 10728:
1.78 anton 10729: @item
10730: State-smart objects parse selectors. However, extensibility is provided
10731: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10732:
1.78 anton 10733: @item
10734: An implementation in ANS Forth is available.
1.20 pazsan 10735:
1.78 anton 10736: @end itemize
1.23 crook 10737:
10738:
1.78 anton 10739: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10740: @subsubsection Basic @file{oof.fs} Usage
10741: @cindex @file{oof.fs} usage
1.23 crook 10742:
1.78 anton 10743: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10744:
1.78 anton 10745: You can define a class for graphical objects like this:
1.23 crook 10746:
1.78 anton 10747: @cindex @code{class} usage
10748: @cindex @code{class;} usage
10749: @cindex @code{method} usage
10750: @example
10751: object class graphical \ "object" is the parent class
10752: method draw ( x y graphical -- )
10753: class;
10754: @end example
1.23 crook 10755:
1.78 anton 10756: This code defines a class @code{graphical} with an
10757: operation @code{draw}. We can perform the operation
10758: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10759:
1.78 anton 10760: @example
10761: 100 100 t-rex draw
10762: @end example
1.23 crook 10763:
1.78 anton 10764: @noindent
10765: where @code{t-rex} is an object or object pointer, created with e.g.
10766: @code{graphical : t-rex}.
1.23 crook 10767:
1.78 anton 10768: @cindex abstract class
10769: How do we create a graphical object? With the present definitions,
10770: we cannot create a useful graphical object. The class
10771: @code{graphical} describes graphical objects in general, but not
10772: any concrete graphical object type (C++ users would call it an
10773: @emph{abstract class}); e.g., there is no method for the selector
10774: @code{draw} in the class @code{graphical}.
1.23 crook 10775:
1.78 anton 10776: For concrete graphical objects, we define child classes of the
10777: class @code{graphical}, e.g.:
1.23 crook 10778:
1.78 anton 10779: @example
10780: graphical class circle \ "graphical" is the parent class
10781: cell var circle-radius
10782: how:
10783: : draw ( x y -- )
10784: circle-radius @@ draw-circle ;
1.23 crook 10785:
1.78 anton 10786: : init ( n-radius -- (
10787: circle-radius ! ;
10788: class;
10789: @end example
1.1 anton 10790:
1.78 anton 10791: Here we define a class @code{circle} as a child of @code{graphical},
10792: with a field @code{circle-radius}; it defines new methods for the
10793: selectors @code{draw} and @code{init} (@code{init} is defined in
10794: @code{object}, the parent class of @code{graphical}).
1.1 anton 10795:
1.78 anton 10796: Now we can create a circle in the dictionary with:
1.1 anton 10797:
1.78 anton 10798: @example
10799: 50 circle : my-circle
10800: @end example
1.21 crook 10801:
1.78 anton 10802: @noindent
10803: @code{:} invokes @code{init}, thus initializing the field
10804: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10805: with:
1.1 anton 10806:
1.78 anton 10807: @example
10808: 100 100 my-circle draw
10809: @end example
1.1 anton 10810:
1.78 anton 10811: @cindex selector invocation, restrictions
10812: @cindex class definition, restrictions
10813: Note: You can only invoke a selector if the receiving object belongs to
10814: the class where the selector was defined or one of its descendents;
10815: e.g., you can invoke @code{draw} only for objects belonging to
10816: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10817: mechanism will check if you try to invoke a selector that is not
10818: defined in this class hierarchy, so you'll get an error at compilation
10819: time.
1.1 anton 10820:
10821:
1.78 anton 10822: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10823: @subsubsection The @file{oof.fs} base class
10824: @cindex @file{oof.fs} base class
1.1 anton 10825:
1.78 anton 10826: When you define a class, you have to specify a parent class. So how do
10827: you start defining classes? There is one class available from the start:
10828: @code{object}. You have to use it as ancestor for all classes. It is the
10829: only class that has no parent. Classes are also objects, except that
10830: they don't have instance variables; class manipulation such as
10831: inheritance or changing definitions of a class is handled through
10832: selectors of the class @code{object}.
1.1 anton 10833:
1.78 anton 10834: @code{object} provides a number of selectors:
1.1 anton 10835:
1.78 anton 10836: @itemize @bullet
10837: @item
10838: @code{class} for subclassing, @code{definitions} to add definitions
10839: later on, and @code{class?} to get type informations (is the class a
10840: subclass of the class passed on the stack?).
1.1 anton 10841:
1.78 anton 10842: doc---object-class
10843: doc---object-definitions
10844: doc---object-class?
1.1 anton 10845:
10846:
1.26 crook 10847: @item
1.78 anton 10848: @code{init} and @code{dispose} as constructor and destructor of the
10849: object. @code{init} is invocated after the object's memory is allocated,
10850: while @code{dispose} also handles deallocation. Thus if you redefine
10851: @code{dispose}, you have to call the parent's dispose with @code{super
10852: dispose}, too.
10853:
10854: doc---object-init
10855: doc---object-dispose
10856:
1.1 anton 10857:
1.26 crook 10858: @item
1.78 anton 10859: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10860: @code{[]} to create named and unnamed objects and object arrays or
10861: object pointers.
10862:
10863: doc---object-new
10864: doc---object-new[]
10865: doc---object-:
10866: doc---object-ptr
10867: doc---object-asptr
10868: doc---object-[]
10869:
1.1 anton 10870:
1.26 crook 10871: @item
1.78 anton 10872: @code{::} and @code{super} for explicit scoping. You should use explicit
10873: scoping only for super classes or classes with the same set of instance
10874: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10875:
1.78 anton 10876: doc---object-::
10877: doc---object-super
1.21 crook 10878:
10879:
1.26 crook 10880: @item
1.78 anton 10881: @code{self} to get the address of the object
1.21 crook 10882:
1.78 anton 10883: doc---object-self
1.21 crook 10884:
10885:
1.78 anton 10886: @item
10887: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10888: pointers and instance defers.
1.21 crook 10889:
1.78 anton 10890: doc---object-bind
10891: doc---object-bound
10892: doc---object-link
10893: doc---object-is
1.21 crook 10894:
10895:
1.78 anton 10896: @item
10897: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10898: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10899:
1.78 anton 10900: doc---object-'
10901: doc---object-postpone
1.21 crook 10902:
10903:
1.78 anton 10904: @item
10905: @code{with} and @code{endwith} to select the active object from the
10906: stack, and enable its scope. Using @code{with} and @code{endwith}
10907: also allows you to create code using selector @code{postpone} without being
10908: trapped by the state-smart objects.
1.21 crook 10909:
1.78 anton 10910: doc---object-with
10911: doc---object-endwith
1.21 crook 10912:
10913:
1.78 anton 10914: @end itemize
1.21 crook 10915:
1.78 anton 10916: @node Class Declaration, Class Implementation, The OOF base class, OOF
10917: @subsubsection Class Declaration
10918: @cindex class declaration
1.21 crook 10919:
1.78 anton 10920: @itemize @bullet
10921: @item
10922: Instance variables
1.21 crook 10923:
1.78 anton 10924: doc---oof-var
1.21 crook 10925:
10926:
1.78 anton 10927: @item
10928: Object pointers
1.21 crook 10929:
1.78 anton 10930: doc---oof-ptr
10931: doc---oof-asptr
1.21 crook 10932:
10933:
1.78 anton 10934: @item
10935: Instance defers
1.21 crook 10936:
1.78 anton 10937: doc---oof-defer
1.21 crook 10938:
10939:
1.78 anton 10940: @item
10941: Method selectors
1.21 crook 10942:
1.78 anton 10943: doc---oof-early
10944: doc---oof-method
1.21 crook 10945:
10946:
1.78 anton 10947: @item
10948: Class-wide variables
1.21 crook 10949:
1.78 anton 10950: doc---oof-static
1.21 crook 10951:
10952:
1.78 anton 10953: @item
10954: End declaration
1.1 anton 10955:
1.78 anton 10956: doc---oof-how:
10957: doc---oof-class;
1.21 crook 10958:
10959:
1.78 anton 10960: @end itemize
1.21 crook 10961:
1.78 anton 10962: @c -------------------------------------------------------------
10963: @node Class Implementation, , Class Declaration, OOF
10964: @subsubsection Class Implementation
10965: @cindex class implementation
1.21 crook 10966:
1.78 anton 10967: @c -------------------------------------------------------------
10968: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10969: @subsection The @file{mini-oof.fs} model
10970: @cindex mini-oof
1.21 crook 10971:
1.78 anton 10972: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 10973: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 10974: and reduces to the bare minimum of features. This is based on a posting
10975: of Bernd Paysan in comp.lang.forth.
1.21 crook 10976:
1.78 anton 10977: @menu
10978: * Basic Mini-OOF Usage::
10979: * Mini-OOF Example::
10980: * Mini-OOF Implementation::
10981: @end menu
1.21 crook 10982:
1.78 anton 10983: @c -------------------------------------------------------------
10984: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10985: @subsubsection Basic @file{mini-oof.fs} Usage
10986: @cindex mini-oof usage
1.21 crook 10987:
1.78 anton 10988: There is a base class (@code{class}, which allocates one cell for the
10989: object pointer) plus seven other words: to define a method, a variable,
10990: a class; to end a class, to resolve binding, to allocate an object and
10991: to compile a class method.
10992: @comment TODO better description of the last one
1.26 crook 10993:
1.21 crook 10994:
1.78 anton 10995: doc-object
10996: doc-method
10997: doc-var
10998: doc-class
10999: doc-end-class
11000: doc-defines
11001: doc-new
11002: doc-::
1.21 crook 11003:
11004:
11005:
1.78 anton 11006: @c -------------------------------------------------------------
11007: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11008: @subsubsection Mini-OOF Example
11009: @cindex mini-oof example
1.1 anton 11010:
1.78 anton 11011: A short example shows how to use this package. This example, in slightly
11012: extended form, is supplied as @file{moof-exm.fs}
11013: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11014:
1.26 crook 11015: @example
1.78 anton 11016: object class
11017: method init
11018: method draw
11019: end-class graphical
1.26 crook 11020: @end example
1.20 pazsan 11021:
1.78 anton 11022: This code defines a class @code{graphical} with an
11023: operation @code{draw}. We can perform the operation
11024: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11025:
1.26 crook 11026: @example
1.78 anton 11027: 100 100 t-rex draw
1.26 crook 11028: @end example
1.12 anton 11029:
1.78 anton 11030: where @code{t-rex} is an object or object pointer, created with e.g.
11031: @code{graphical new Constant t-rex}.
1.12 anton 11032:
1.78 anton 11033: For concrete graphical objects, we define child classes of the
11034: class @code{graphical}, e.g.:
1.12 anton 11035:
1.26 crook 11036: @example
11037: graphical class
1.78 anton 11038: cell var circle-radius
11039: end-class circle \ "graphical" is the parent class
1.12 anton 11040:
1.78 anton 11041: :noname ( x y -- )
11042: circle-radius @@ draw-circle ; circle defines draw
11043: :noname ( r -- )
11044: circle-radius ! ; circle defines init
11045: @end example
1.12 anton 11046:
1.78 anton 11047: There is no implicit init method, so we have to define one. The creation
11048: code of the object now has to call init explicitely.
1.21 crook 11049:
1.78 anton 11050: @example
11051: circle new Constant my-circle
11052: 50 my-circle init
1.12 anton 11053: @end example
11054:
1.78 anton 11055: It is also possible to add a function to create named objects with
11056: automatic call of @code{init}, given that all objects have @code{init}
11057: on the same place:
1.38 anton 11058:
1.78 anton 11059: @example
11060: : new: ( .. o "name" -- )
11061: new dup Constant init ;
11062: 80 circle new: large-circle
11063: @end example
1.12 anton 11064:
1.78 anton 11065: We can draw this new circle at (100,100) with:
1.12 anton 11066:
1.78 anton 11067: @example
11068: 100 100 my-circle draw
11069: @end example
1.12 anton 11070:
1.78 anton 11071: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11072: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11073:
1.78 anton 11074: Object-oriented systems with late binding typically use a
11075: ``vtable''-approach: the first variable in each object is a pointer to a
11076: table, which contains the methods as function pointers. The vtable
11077: may also contain other information.
1.12 anton 11078:
1.79 anton 11079: So first, let's declare selectors:
1.37 anton 11080:
11081: @example
1.79 anton 11082: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11083: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11084: @end example
1.37 anton 11085:
1.79 anton 11086: During selector declaration, the number of selectors and instance
11087: variables is on the stack (in address units). @code{method} creates one
11088: selector and increments the selector number. To execute a selector, it
1.78 anton 11089: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11090: executes the method @i{xt} stored there. Each selector takes the object
11091: it is invoked with as top of stack parameter; it passes the parameters
11092: (including the object) unchanged to the appropriate method which should
1.78 anton 11093: consume that object.
1.37 anton 11094:
1.78 anton 11095: Now, we also have to declare instance variables
1.37 anton 11096:
1.78 anton 11097: @example
1.79 anton 11098: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11099: DOES> ( o -- addr ) @@ + ;
1.37 anton 11100: @end example
11101:
1.78 anton 11102: As before, a word is created with the current offset. Instance
11103: variables can have different sizes (cells, floats, doubles, chars), so
11104: all we do is take the size and add it to the offset. If your machine
11105: has alignment restrictions, put the proper @code{aligned} or
11106: @code{faligned} before the variable, to adjust the variable
11107: offset. That's why it is on the top of stack.
1.37 anton 11108:
1.78 anton 11109: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11110:
1.78 anton 11111: @example
11112: Create object 1 cells , 2 cells ,
1.79 anton 11113: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11114: @end example
1.12 anton 11115:
1.78 anton 11116: For inheritance, the vtable of the parent object has to be
11117: copied when a new, derived class is declared. This gives all the
11118: methods of the parent class, which can be overridden, though.
1.12 anton 11119:
1.78 anton 11120: @example
1.79 anton 11121: : end-class ( class selectors vars "name" -- )
1.78 anton 11122: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11123: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11124: @end example
1.12 anton 11125:
1.78 anton 11126: The first line creates the vtable, initialized with
11127: @code{noop}s. The second line is the inheritance mechanism, it
11128: copies the xts from the parent vtable.
1.12 anton 11129:
1.78 anton 11130: We still have no way to define new methods, let's do that now:
1.12 anton 11131:
1.26 crook 11132: @example
1.79 anton 11133: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11134: @end example
1.12 anton 11135:
1.78 anton 11136: To allocate a new object, we need a word, too:
1.12 anton 11137:
1.78 anton 11138: @example
11139: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11140: @end example
11141:
1.78 anton 11142: Sometimes derived classes want to access the method of the
11143: parent object. There are two ways to achieve this with Mini-OOF:
11144: first, you could use named words, and second, you could look up the
11145: vtable of the parent object.
1.12 anton 11146:
1.78 anton 11147: @example
11148: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11149: @end example
1.12 anton 11150:
11151:
1.78 anton 11152: Nothing can be more confusing than a good example, so here is
11153: one. First let's declare a text object (called
11154: @code{button}), that stores text and position:
1.12 anton 11155:
1.78 anton 11156: @example
11157: object class
11158: cell var text
11159: cell var len
11160: cell var x
11161: cell var y
11162: method init
11163: method draw
11164: end-class button
11165: @end example
1.12 anton 11166:
1.78 anton 11167: @noindent
11168: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11169:
1.26 crook 11170: @example
1.78 anton 11171: :noname ( o -- )
11172: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11173: button defines draw
11174: :noname ( addr u o -- )
11175: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11176: button defines init
1.26 crook 11177: @end example
1.12 anton 11178:
1.78 anton 11179: @noindent
11180: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11181: new data and no new selectors:
1.78 anton 11182:
11183: @example
11184: button class
11185: end-class bold-button
1.12 anton 11186:
1.78 anton 11187: : bold 27 emit ." [1m" ;
11188: : normal 27 emit ." [0m" ;
11189: @end example
1.1 anton 11190:
1.78 anton 11191: @noindent
11192: The class @code{bold-button} has a different draw method to
11193: @code{button}, but the new method is defined in terms of the draw method
11194: for @code{button}:
1.20 pazsan 11195:
1.78 anton 11196: @example
11197: :noname bold [ button :: draw ] normal ; bold-button defines draw
11198: @end example
1.21 crook 11199:
1.78 anton 11200: @noindent
1.79 anton 11201: Finally, create two objects and apply selectors:
1.21 crook 11202:
1.26 crook 11203: @example
1.78 anton 11204: button new Constant foo
11205: s" thin foo" foo init
11206: page
11207: foo draw
11208: bold-button new Constant bar
11209: s" fat bar" bar init
11210: 1 bar y !
11211: bar draw
1.26 crook 11212: @end example
1.21 crook 11213:
11214:
1.78 anton 11215: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11216: @subsection Comparison with other object models
11217: @cindex comparison of object models
11218: @cindex object models, comparison
11219:
11220: Many object-oriented Forth extensions have been proposed (@cite{A survey
11221: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11222: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11223: relation of the object models described here to two well-known and two
11224: closely-related (by the use of method maps) models. Andras Zsoter
11225: helped us with this section.
11226:
11227: @cindex Neon model
11228: The most popular model currently seems to be the Neon model (see
11229: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11230: 1997) by Andrew McKewan) but this model has a number of limitations
11231: @footnote{A longer version of this critique can be
11232: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11233: Dimensions, May 1997) by Anton Ertl.}:
11234:
11235: @itemize @bullet
11236: @item
11237: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11238: to pass objects on the stack.
1.21 crook 11239:
1.78 anton 11240: @item
11241: It requires that the selector parses the input stream (at
1.79 anton 11242: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11243: hard to find.
1.21 crook 11244:
1.78 anton 11245: @item
1.79 anton 11246: It allows using every selector on every object; this eliminates the
11247: need for interfaces, but makes it harder to create efficient
11248: implementations.
1.78 anton 11249: @end itemize
1.21 crook 11250:
1.78 anton 11251: @cindex Pountain's object-oriented model
11252: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11253: Press, London, 1987) by Dick Pountain. However, it is not really about
11254: object-oriented programming, because it hardly deals with late
11255: binding. Instead, it focuses on features like information hiding and
11256: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11257:
1.78 anton 11258: @cindex Zsoter's object-oriented model
1.79 anton 11259: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11260: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11261: describes a model that makes heavy use of an active object (like
11262: @code{this} in @file{objects.fs}): The active object is not only used
11263: for accessing all fields, but also specifies the receiving object of
11264: every selector invocation; you have to change the active object
11265: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11266: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11267: the method entry point is unnecessary with Zsoter's model, because the
11268: receiving object is the active object already. On the other hand, the
11269: explicit change is absolutely necessary in that model, because otherwise
11270: no one could ever change the active object. An ANS Forth implementation
11271: of this model is available through
11272: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11273:
1.78 anton 11274: @cindex @file{oof.fs}, differences to other models
11275: The @file{oof.fs} model combines information hiding and overloading
11276: resolution (by keeping names in various word lists) with object-oriented
11277: programming. It sets the active object implicitly on method entry, but
11278: also allows explicit changing (with @code{>o...o>} or with
11279: @code{with...endwith}). It uses parsing and state-smart objects and
11280: classes for resolving overloading and for early binding: the object or
11281: class parses the selector and determines the method from this. If the
11282: selector is not parsed by an object or class, it performs a call to the
11283: selector for the active object (late binding), like Zsoter's model.
11284: Fields are always accessed through the active object. The big
11285: disadvantage of this model is the parsing and the state-smartness, which
11286: reduces extensibility and increases the opportunities for subtle bugs;
11287: essentially, you are only safe if you never tick or @code{postpone} an
11288: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11289:
1.78 anton 11290: @cindex @file{mini-oof.fs}, differences to other models
11291: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11292: version of the @file{objects.fs} model, but syntactically it is a
11293: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11294:
11295:
1.78 anton 11296: @c -------------------------------------------------------------
11297: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11298: @section Programming Tools
11299: @cindex programming tools
1.21 crook 11300:
1.78 anton 11301: @c !! move this and assembler down below OO stuff.
1.21 crook 11302:
1.78 anton 11303: @menu
11304: * Examining::
11305: * Forgetting words::
11306: * Debugging:: Simple and quick.
11307: * Assertions:: Making your programs self-checking.
11308: * Singlestep Debugger:: Executing your program word by word.
11309: @end menu
1.21 crook 11310:
1.78 anton 11311: @node Examining, Forgetting words, Programming Tools, Programming Tools
11312: @subsection Examining data and code
11313: @cindex examining data and code
11314: @cindex data examination
11315: @cindex code examination
1.44 crook 11316:
1.78 anton 11317: The following words inspect the stack non-destructively:
1.21 crook 11318:
1.78 anton 11319: doc-.s
11320: doc-f.s
1.44 crook 11321:
1.78 anton 11322: There is a word @code{.r} but it does @i{not} display the return stack!
11323: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11324:
1.78 anton 11325: doc-depth
11326: doc-fdepth
11327: doc-clearstack
1.124 anton 11328: doc-clearstacks
1.21 crook 11329:
1.78 anton 11330: The following words inspect memory.
1.21 crook 11331:
1.78 anton 11332: doc-?
11333: doc-dump
1.21 crook 11334:
1.78 anton 11335: And finally, @code{see} allows to inspect code:
1.21 crook 11336:
1.78 anton 11337: doc-see
11338: doc-xt-see
1.111 anton 11339: doc-simple-see
11340: doc-simple-see-range
1.21 crook 11341:
1.78 anton 11342: @node Forgetting words, Debugging, Examining, Programming Tools
11343: @subsection Forgetting words
11344: @cindex words, forgetting
11345: @cindex forgeting words
1.21 crook 11346:
1.78 anton 11347: @c anton: other, maybe better places for this subsection: Defining Words;
11348: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11349:
1.78 anton 11350: Forth allows you to forget words (and everything that was alloted in the
11351: dictonary after them) in a LIFO manner.
1.21 crook 11352:
1.78 anton 11353: doc-marker
1.21 crook 11354:
1.78 anton 11355: The most common use of this feature is during progam development: when
11356: you change a source file, forget all the words it defined and load it
11357: again (since you also forget everything defined after the source file
11358: was loaded, you have to reload that, too). Note that effects like
11359: storing to variables and destroyed system words are not undone when you
11360: forget words. With a system like Gforth, that is fast enough at
11361: starting up and compiling, I find it more convenient to exit and restart
11362: Gforth, as this gives me a clean slate.
1.21 crook 11363:
1.78 anton 11364: Here's an example of using @code{marker} at the start of a source file
11365: that you are debugging; it ensures that you only ever have one copy of
11366: the file's definitions compiled at any time:
1.21 crook 11367:
1.78 anton 11368: @example
11369: [IFDEF] my-code
11370: my-code
11371: [ENDIF]
1.26 crook 11372:
1.78 anton 11373: marker my-code
11374: init-included-files
1.21 crook 11375:
1.78 anton 11376: \ .. definitions start here
11377: \ .
11378: \ .
11379: \ end
11380: @end example
1.21 crook 11381:
1.26 crook 11382:
1.78 anton 11383: @node Debugging, Assertions, Forgetting words, Programming Tools
11384: @subsection Debugging
11385: @cindex debugging
1.21 crook 11386:
1.78 anton 11387: Languages with a slow edit/compile/link/test development loop tend to
11388: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11389:
1.78 anton 11390: A much better (faster) way in fast-compiling languages is to add
11391: printing code at well-selected places, let the program run, look at
11392: the output, see where things went wrong, add more printing code, etc.,
11393: until the bug is found.
1.21 crook 11394:
1.78 anton 11395: The simple debugging aids provided in @file{debugs.fs}
11396: are meant to support this style of debugging.
1.21 crook 11397:
1.78 anton 11398: The word @code{~~} prints debugging information (by default the source
11399: location and the stack contents). It is easy to insert. If you use Emacs
11400: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11401: query-replace them with nothing). The deferred words
1.101 anton 11402: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11403: @code{~~}. The default source location output format works well with
11404: Emacs' compilation mode, so you can step through the program at the
11405: source level using @kbd{C-x `} (the advantage over a stepping debugger
11406: is that you can step in any direction and you know where the crash has
11407: happened or where the strange data has occurred).
1.21 crook 11408:
1.78 anton 11409: doc-~~
11410: doc-printdebugdata
1.101 anton 11411: doc-.debugline
1.21 crook 11412:
1.106 anton 11413: @cindex filenames in @code{~~} output
11414: @code{~~} (and assertions) will usually print the wrong file name if a
11415: marker is executed in the same file after their occurance. They will
11416: print @samp{*somewhere*} as file name if a marker is executed in the
11417: same file before their occurance.
11418:
11419:
1.78 anton 11420: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11421: @subsection Assertions
11422: @cindex assertions
1.21 crook 11423:
1.78 anton 11424: It is a good idea to make your programs self-checking, especially if you
11425: make an assumption that may become invalid during maintenance (for
11426: example, that a certain field of a data structure is never zero). Gforth
11427: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11428:
11429: @example
1.78 anton 11430: assert( @i{flag} )
1.26 crook 11431: @end example
11432:
1.78 anton 11433: The code between @code{assert(} and @code{)} should compute a flag, that
11434: should be true if everything is alright and false otherwise. It should
11435: not change anything else on the stack. The overall stack effect of the
11436: assertion is @code{( -- )}. E.g.
1.21 crook 11437:
1.26 crook 11438: @example
1.78 anton 11439: assert( 1 1 + 2 = ) \ what we learn in school
11440: assert( dup 0<> ) \ assert that the top of stack is not zero
11441: assert( false ) \ this code should not be reached
1.21 crook 11442: @end example
11443:
1.78 anton 11444: The need for assertions is different at different times. During
11445: debugging, we want more checking, in production we sometimes care more
11446: for speed. Therefore, assertions can be turned off, i.e., the assertion
11447: becomes a comment. Depending on the importance of an assertion and the
11448: time it takes to check it, you may want to turn off some assertions and
11449: keep others turned on. Gforth provides several levels of assertions for
11450: this purpose:
11451:
11452:
11453: doc-assert0(
11454: doc-assert1(
11455: doc-assert2(
11456: doc-assert3(
11457: doc-assert(
11458: doc-)
1.21 crook 11459:
11460:
1.78 anton 11461: The variable @code{assert-level} specifies the highest assertions that
11462: are turned on. I.e., at the default @code{assert-level} of one,
11463: @code{assert0(} and @code{assert1(} assertions perform checking, while
11464: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11465:
1.78 anton 11466: The value of @code{assert-level} is evaluated at compile-time, not at
11467: run-time. Therefore you cannot turn assertions on or off at run-time;
11468: you have to set the @code{assert-level} appropriately before compiling a
11469: piece of code. You can compile different pieces of code at different
11470: @code{assert-level}s (e.g., a trusted library at level 1 and
11471: newly-written code at level 3).
1.26 crook 11472:
11473:
1.78 anton 11474: doc-assert-level
1.26 crook 11475:
11476:
1.78 anton 11477: If an assertion fails, a message compatible with Emacs' compilation mode
11478: is produced and the execution is aborted (currently with @code{ABORT"}.
11479: If there is interest, we will introduce a special throw code. But if you
11480: intend to @code{catch} a specific condition, using @code{throw} is
11481: probably more appropriate than an assertion).
1.106 anton 11482:
11483: @cindex filenames in assertion output
11484: Assertions (and @code{~~}) will usually print the wrong file name if a
11485: marker is executed in the same file after their occurance. They will
11486: print @samp{*somewhere*} as file name if a marker is executed in the
11487: same file before their occurance.
1.44 crook 11488:
1.78 anton 11489: Definitions in ANS Forth for these assertion words are provided
11490: in @file{compat/assert.fs}.
1.26 crook 11491:
1.44 crook 11492:
1.78 anton 11493: @node Singlestep Debugger, , Assertions, Programming Tools
11494: @subsection Singlestep Debugger
11495: @cindex singlestep Debugger
11496: @cindex debugging Singlestep
1.44 crook 11497:
1.112 anton 11498: The singlestep debugger does not work in this release.
11499:
1.78 anton 11500: When you create a new word there's often the need to check whether it
11501: behaves correctly or not. You can do this by typing @code{dbg
11502: badword}. A debug session might look like this:
1.26 crook 11503:
1.78 anton 11504: @example
11505: : badword 0 DO i . LOOP ; ok
11506: 2 dbg badword
11507: : badword
11508: Scanning code...
1.44 crook 11509:
1.78 anton 11510: Nesting debugger ready!
1.44 crook 11511:
1.78 anton 11512: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11513: 400D4740 8049F68 DO -> [ 0 ]
11514: 400D4744 804A0C8 i -> [ 1 ] 00000
11515: 400D4748 400C5E60 . -> 0 [ 0 ]
11516: 400D474C 8049D0C LOOP -> [ 0 ]
11517: 400D4744 804A0C8 i -> [ 1 ] 00001
11518: 400D4748 400C5E60 . -> 1 [ 0 ]
11519: 400D474C 8049D0C LOOP -> [ 0 ]
11520: 400D4758 804B384 ; -> ok
11521: @end example
1.21 crook 11522:
1.78 anton 11523: Each line displayed is one step. You always have to hit return to
11524: execute the next word that is displayed. If you don't want to execute
11525: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11526: an overview what keys are available:
1.44 crook 11527:
1.78 anton 11528: @table @i
1.44 crook 11529:
1.78 anton 11530: @item @key{RET}
11531: Next; Execute the next word.
1.21 crook 11532:
1.78 anton 11533: @item n
11534: Nest; Single step through next word.
1.44 crook 11535:
1.78 anton 11536: @item u
11537: Unnest; Stop debugging and execute rest of word. If we got to this word
11538: with nest, continue debugging with the calling word.
1.44 crook 11539:
1.78 anton 11540: @item d
11541: Done; Stop debugging and execute rest.
1.21 crook 11542:
1.78 anton 11543: @item s
11544: Stop; Abort immediately.
1.44 crook 11545:
1.78 anton 11546: @end table
1.44 crook 11547:
1.78 anton 11548: Debugging large application with this mechanism is very difficult, because
11549: you have to nest very deeply into the program before the interesting part
11550: begins. This takes a lot of time.
1.26 crook 11551:
1.78 anton 11552: To do it more directly put a @code{BREAK:} command into your source code.
11553: When program execution reaches @code{BREAK:} the single step debugger is
11554: invoked and you have all the features described above.
1.44 crook 11555:
1.78 anton 11556: If you have more than one part to debug it is useful to know where the
11557: program has stopped at the moment. You can do this by the
11558: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11559: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11560:
1.26 crook 11561:
1.78 anton 11562: doc-dbg
11563: doc-break:
11564: doc-break"
1.44 crook 11565:
11566:
1.26 crook 11567:
1.78 anton 11568: @c -------------------------------------------------------------
11569: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11570: @section Assembler and Code Words
11571: @cindex assembler
11572: @cindex code words
1.44 crook 11573:
1.78 anton 11574: @menu
11575: * Code and ;code::
11576: * Common Assembler:: Assembler Syntax
11577: * Common Disassembler::
11578: * 386 Assembler:: Deviations and special cases
11579: * Alpha Assembler:: Deviations and special cases
11580: * MIPS assembler:: Deviations and special cases
11581: * Other assemblers:: How to write them
11582: @end menu
1.21 crook 11583:
1.78 anton 11584: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11585: @subsection @code{Code} and @code{;code}
1.26 crook 11586:
1.78 anton 11587: Gforth provides some words for defining primitives (words written in
11588: machine code), and for defining the machine-code equivalent of
11589: @code{DOES>}-based defining words. However, the machine-independent
11590: nature of Gforth poses a few problems: First of all, Gforth runs on
11591: several architectures, so it can provide no standard assembler. What's
11592: worse is that the register allocation not only depends on the processor,
11593: but also on the @code{gcc} version and options used.
1.44 crook 11594:
1.78 anton 11595: The words that Gforth offers encapsulate some system dependences (e.g.,
11596: the header structure), so a system-independent assembler may be used in
11597: Gforth. If you do not have an assembler, you can compile machine code
11598: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11599: because these words emit stuff in @i{data} space; it works because
11600: Gforth has unified code/data spaces. Assembler isn't likely to be
11601: portable anyway.}.
1.21 crook 11602:
1.44 crook 11603:
1.78 anton 11604: doc-assembler
11605: doc-init-asm
11606: doc-code
11607: doc-end-code
11608: doc-;code
11609: doc-flush-icache
1.44 crook 11610:
1.21 crook 11611:
1.78 anton 11612: If @code{flush-icache} does not work correctly, @code{code} words
11613: etc. will not work (reliably), either.
1.44 crook 11614:
1.78 anton 11615: The typical usage of these @code{code} words can be shown most easily by
11616: analogy to the equivalent high-level defining words:
1.44 crook 11617:
1.78 anton 11618: @example
11619: : foo code foo
11620: <high-level Forth words> <assembler>
11621: ; end-code
11622:
11623: : bar : bar
11624: <high-level Forth words> <high-level Forth words>
11625: CREATE CREATE
11626: <high-level Forth words> <high-level Forth words>
11627: DOES> ;code
11628: <high-level Forth words> <assembler>
11629: ; end-code
11630: @end example
1.21 crook 11631:
1.78 anton 11632: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11633:
1.78 anton 11634: @cindex registers of the inner interpreter
11635: In the assembly code you will want to refer to the inner interpreter's
11636: registers (e.g., the data stack pointer) and you may want to use other
11637: registers for temporary storage. Unfortunately, the register allocation
11638: is installation-dependent.
1.44 crook 11639:
1.78 anton 11640: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11641: (return stack pointer) may be in different places in @code{gforth} and
11642: @code{gforth-fast}, or different installations. This means that you
11643: cannot write a @code{NEXT} routine that works reliably on both versions
11644: or different installations; so for doing @code{NEXT}, I recommend
11645: jumping to @code{' noop >code-address}, which contains nothing but a
11646: @code{NEXT}.
1.21 crook 11647:
1.78 anton 11648: For general accesses to the inner interpreter's registers, the easiest
11649: solution is to use explicit register declarations (@pxref{Explicit Reg
11650: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11651: all of the inner interpreter's registers: You have to compile Gforth
11652: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11653: the appropriate declarations must be present in the @code{machine.h}
11654: file (see @code{mips.h} for an example; you can find a full list of all
11655: declarable register symbols with @code{grep register engine.c}). If you
11656: give explicit registers to all variables that are declared at the
11657: beginning of @code{engine()}, you should be able to use the other
11658: caller-saved registers for temporary storage. Alternatively, you can use
11659: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11660: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11661: reserve a register (however, this restriction on register allocation may
11662: slow Gforth significantly).
1.44 crook 11663:
1.78 anton 11664: If this solution is not viable (e.g., because @code{gcc} does not allow
11665: you to explicitly declare all the registers you need), you have to find
11666: out by looking at the code where the inner interpreter's registers
11667: reside and which registers can be used for temporary storage. You can
11668: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11669:
1.78 anton 11670: In any case, it is good practice to abstract your assembly code from the
11671: actual register allocation. E.g., if the data stack pointer resides in
11672: register @code{$17}, create an alias for this register called @code{sp},
11673: and use that in your assembly code.
1.21 crook 11674:
1.78 anton 11675: @cindex code words, portable
11676: Another option for implementing normal and defining words efficiently
11677: is to add the desired functionality to the source of Gforth. For normal
11678: words you just have to edit @file{primitives} (@pxref{Automatic
11679: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11680: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11681: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11682:
1.78 anton 11683: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11684: @subsection Common Assembler
1.44 crook 11685:
1.78 anton 11686: The assemblers in Gforth generally use a postfix syntax, i.e., the
11687: instruction name follows the operands.
1.21 crook 11688:
1.78 anton 11689: The operands are passed in the usual order (the same that is used in the
11690: manual of the architecture). Since they all are Forth words, they have
11691: to be separated by spaces; you can also use Forth words to compute the
11692: operands.
1.44 crook 11693:
1.78 anton 11694: The instruction names usually end with a @code{,}. This makes it easier
11695: to visually separate instructions if you put several of them on one
11696: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11697:
1.78 anton 11698: Registers are usually specified by number; e.g., (decimal) @code{11}
11699: specifies registers R11 and F11 on the Alpha architecture (which one,
11700: depends on the instruction). The usual names are also available, e.g.,
11701: @code{s2} for R11 on Alpha.
1.21 crook 11702:
1.78 anton 11703: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11704: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11705: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11706: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11707: conditions are specified in a way specific to each assembler.
1.1 anton 11708:
1.78 anton 11709: Note that the register assignments of the Gforth engine can change
11710: between Gforth versions, or even between different compilations of the
11711: same Gforth version (e.g., if you use a different GCC version). So if
11712: you want to refer to Gforth's registers (e.g., the stack pointer or
11713: TOS), I recommend defining your own words for refering to these
11714: registers, and using them later on; then you can easily adapt to a
11715: changed register assignment. The stability of the register assignment
11716: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11717:
1.100 anton 11718: The most common use of these registers is to dispatch to the next word
11719: (the @code{next} routine). A portable way to do this is to jump to
11720: @code{' noop >code-address} (of course, this is less efficient than
11721: integrating the @code{next} code and scheduling it well).
1.1 anton 11722:
1.96 anton 11723: Another difference between Gforth version is that the top of stack is
11724: kept in memory in @code{gforth} and, on most platforms, in a register in
11725: @code{gforth-fast}.
11726:
1.78 anton 11727: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11728: @subsection Common Disassembler
1.127 anton 11729: @cindex disassembler, general
11730: @cindex gdb disassembler
1.1 anton 11731:
1.78 anton 11732: You can disassemble a @code{code} word with @code{see}
11733: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11734:
1.127 anton 11735: doc-discode
1.44 crook 11736:
1.127 anton 11737: There are two kinds of disassembler for Gforth: The Forth disassembler
11738: (available on some CPUs) and the gdb disassembler (available on
11739: platforms with @command{gdb} and @command{mktemp}). If both are
11740: available, the Forth disassembler is used by default. If you prefer
11741: the gdb disassembler, say
11742:
11743: @example
11744: ' disasm-gdb is discode
11745: @end example
11746:
11747: If neither is available, @code{discode} performs @code{dump}.
11748:
11749: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11750: assembler (i.e., same syntax, etc.). It also includes additional
11751: information in comments. In particular, the address of the instruction
11752: is given in a comment before the instruction.
1.1 anton 11753:
1.127 anton 11754: The gdb disassembler produces output in the same format as the gdb
11755: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11756: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11757: the 386 and AMD64 architectures).
11758:
1.78 anton 11759: @code{See} may display more or less than the actual code of the word,
11760: because the recognition of the end of the code is unreliable. You can
1.127 anton 11761: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11762: the code word is not immediately followed by a named word. If you have
1.116 anton 11763: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11764: to ensure that the end is recognized.
1.21 crook 11765:
1.78 anton 11766: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11767: @subsection 386 Assembler
1.44 crook 11768:
1.78 anton 11769: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11770: available under GPL, and originally part of bigFORTH.
1.21 crook 11771:
1.78 anton 11772: The 386 disassembler included in Gforth was written by Andrew McKewan
11773: and is in the public domain.
1.21 crook 11774:
1.91 anton 11775: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11776:
1.78 anton 11777: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11778:
1.78 anton 11779: The assembler includes all instruction of the Athlon, i.e. 486 core
11780: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11781: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11782: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11783:
1.78 anton 11784: There are several prefixes to switch between different operation sizes,
11785: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11786: double-word accesses. Addressing modes can be switched with @code{.wa}
11787: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11788: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11789:
1.78 anton 11790: For floating point operations, the prefixes are @code{.fs} (IEEE
11791: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11792: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11793:
1.78 anton 11794: The MMX opcodes don't have size prefixes, they are spelled out like in
11795: the Intel assembler. Instead of move from and to memory, there are
11796: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11797:
1.78 anton 11798: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11799: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11800: e.g., @code{3 #}. Here are some examples of addressing modes in various
11801: syntaxes:
1.21 crook 11802:
1.26 crook 11803: @example
1.91 anton 11804: Gforth Intel (NASM) AT&T (gas) Name
11805: .w ax ax %ax register (16 bit)
11806: ax eax %eax register (32 bit)
11807: 3 # offset 3 $3 immediate
11808: 1000 #) byte ptr 1000 1000 displacement
11809: bx ) [ebx] (%ebx) base
11810: 100 di d) 100[edi] 100(%edi) base+displacement
11811: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11812: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11813: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11814: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11815: @end example
11816:
11817: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11818: @code{DI)} to enforce 32-bit displacement fields (useful for
11819: later patching).
1.21 crook 11820:
1.78 anton 11821: Some example of instructions are:
1.1 anton 11822:
11823: @example
1.78 anton 11824: ax bx mov \ move ebx,eax
11825: 3 # ax mov \ mov eax,3
11826: 100 di ) ax mov \ mov eax,100[edi]
11827: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11828: .w ax bx mov \ mov bx,ax
1.1 anton 11829: @end example
11830:
1.78 anton 11831: The following forms are supported for binary instructions:
1.1 anton 11832:
11833: @example
1.78 anton 11834: <reg> <reg> <inst>
11835: <n> # <reg> <inst>
11836: <mem> <reg> <inst>
11837: <reg> <mem> <inst>
1.1 anton 11838: @end example
11839:
1.78 anton 11840: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11841:
1.26 crook 11842: @example
1.78 anton 11843: <reg/mem> 1 # shl \ shortens to shift without immediate
11844: <reg/mem> 4 # shl
11845: <reg/mem> cl shl
1.26 crook 11846: @end example
1.1 anton 11847:
1.78 anton 11848: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11849: the byte version.
1.1 anton 11850:
1.78 anton 11851: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11852: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11853: pc < >= <= >}. (Note that most of these words shadow some Forth words
11854: when @code{assembler} is in front of @code{forth} in the search path,
11855: e.g., in @code{code} words). Currently the control structure words use
11856: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11857: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11858:
1.78 anton 11859: Here is an example of a @code{code} word (assumes that the stack pointer
11860: is in esi and the TOS is in ebx):
1.21 crook 11861:
1.26 crook 11862: @example
1.78 anton 11863: code my+ ( n1 n2 -- n )
11864: 4 si D) bx add
11865: 4 # si add
11866: Next
11867: end-code
1.26 crook 11868: @end example
1.21 crook 11869:
1.78 anton 11870: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11871: @subsection Alpha Assembler
1.21 crook 11872:
1.78 anton 11873: The Alpha assembler and disassembler were originally written by Bernd
11874: Thallner.
1.26 crook 11875:
1.78 anton 11876: The register names @code{a0}--@code{a5} are not available to avoid
11877: shadowing hex numbers.
1.2 jwilke 11878:
1.78 anton 11879: Immediate forms of arithmetic instructions are distinguished by a
11880: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11881: does not count as arithmetic instruction).
1.2 jwilke 11882:
1.78 anton 11883: You have to specify all operands to an instruction, even those that
11884: other assemblers consider optional, e.g., the destination register for
11885: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11886:
1.78 anton 11887: You can specify conditions for @code{if,} by removing the first @code{b}
11888: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11889:
1.26 crook 11890: @example
1.78 anton 11891: 11 fgt if, \ if F11>0e
11892: ...
11893: endif,
1.26 crook 11894: @end example
1.2 jwilke 11895:
1.78 anton 11896: @code{fbgt,} gives @code{fgt}.
11897:
11898: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11899: @subsection MIPS assembler
1.2 jwilke 11900:
1.78 anton 11901: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11902:
1.78 anton 11903: Currently the assembler and disassembler only cover the MIPS-I
11904: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11905:
1.78 anton 11906: The register names @code{$a0}--@code{$a3} are not available to avoid
11907: shadowing hex numbers.
1.2 jwilke 11908:
1.78 anton 11909: Because there is no way to distinguish registers from immediate values,
11910: you have to explicitly use the immediate forms of instructions, i.e.,
11911: @code{addiu,}, not just @code{addu,} (@command{as} does this
11912: implicitly).
1.2 jwilke 11913:
1.78 anton 11914: If the architecture manual specifies several formats for the instruction
11915: (e.g., for @code{jalr,}), you usually have to use the one with more
11916: arguments (i.e., two for @code{jalr,}). When in doubt, see
11917: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11918:
1.78 anton 11919: Branches and jumps in the MIPS architecture have a delay slot. You have
11920: to fill it yourself (the simplest way is to use @code{nop,}), the
11921: assembler does not do it for you (unlike @command{as}). Even
11922: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11923: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11924: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11925:
1.78 anton 11926: Note that you must not put branches, jumps, or @code{li,} into the delay
11927: slot: @code{li,} may expand to several instructions, and control flow
11928: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11929:
1.78 anton 11930: For branches the argument specifying the target is a relative address;
11931: You have to add the address of the delay slot to get the absolute
11932: address.
1.1 anton 11933:
1.78 anton 11934: The MIPS architecture also has load delay slots and restrictions on
11935: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11936: yourself to satisfy these restrictions, the assembler does not do it for
11937: you.
1.1 anton 11938:
1.78 anton 11939: You can specify the conditions for @code{if,} etc. by taking a
11940: conditional branch and leaving away the @code{b} at the start and the
11941: @code{,} at the end. E.g.,
1.1 anton 11942:
1.26 crook 11943: @example
1.78 anton 11944: 4 5 eq if,
11945: ... \ do something if $4 equals $5
11946: then,
1.26 crook 11947: @end example
1.1 anton 11948:
1.78 anton 11949: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11950: @subsection Other assemblers
11951:
11952: If you want to contribute another assembler/disassembler, please contact
1.103 anton 11953: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11954: an assembler already. If you are writing them from scratch, please use
11955: a similar syntax style as the one we use (i.e., postfix, commas at the
11956: end of the instruction names, @pxref{Common Assembler}); make the output
11957: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 11958: similar to the style we used.
11959:
11960: Hints on implementation: The most important part is to have a good test
11961: suite that contains all instructions. Once you have that, the rest is
11962: easy. For actual coding you can take a look at
11963: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11964: the assembler and disassembler, avoiding redundancy and some potential
11965: bugs. You can also look at that file (and @pxref{Advanced does> usage
11966: example}) to get ideas how to factor a disassembler.
11967:
11968: Start with the disassembler, because it's easier to reuse data from the
11969: disassembler for the assembler than the other way round.
1.1 anton 11970:
1.78 anton 11971: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11972: how simple it can be.
1.1 anton 11973:
1.78 anton 11974: @c -------------------------------------------------------------
11975: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11976: @section Threading Words
11977: @cindex threading words
1.1 anton 11978:
1.78 anton 11979: @cindex code address
11980: These words provide access to code addresses and other threading stuff
11981: in Gforth (and, possibly, other interpretive Forths). It more or less
11982: abstracts away the differences between direct and indirect threading
11983: (and, for direct threading, the machine dependences). However, at
11984: present this wordset is still incomplete. It is also pretty low-level;
11985: some day it will hopefully be made unnecessary by an internals wordset
11986: that abstracts implementation details away completely.
1.1 anton 11987:
1.78 anton 11988: The terminology used here stems from indirect threaded Forth systems; in
11989: such a system, the XT of a word is represented by the CFA (code field
11990: address) of a word; the CFA points to a cell that contains the code
11991: address. The code address is the address of some machine code that
11992: performs the run-time action of invoking the word (e.g., the
11993: @code{dovar:} routine pushes the address of the body of the word (a
11994: variable) on the stack
11995: ).
1.1 anton 11996:
1.78 anton 11997: @cindex code address
11998: @cindex code field address
11999: In an indirect threaded Forth, you can get the code address of @i{name}
12000: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12001: >code-address}, independent of the threading method.
1.1 anton 12002:
1.78 anton 12003: doc-threading-method
12004: doc->code-address
12005: doc-code-address!
1.1 anton 12006:
1.78 anton 12007: @cindex @code{does>}-handler
12008: @cindex @code{does>}-code
12009: For a word defined with @code{DOES>}, the code address usually points to
12010: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12011: routine (in Gforth on some platforms, it can also point to the dodoes
12012: routine itself). What you are typically interested in, though, is
12013: whether a word is a @code{DOES>}-defined word, and what Forth code it
12014: executes; @code{>does-code} tells you that.
1.1 anton 12015:
1.78 anton 12016: doc->does-code
1.1 anton 12017:
1.78 anton 12018: To create a @code{DOES>}-defined word with the following basic words,
12019: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12020: @code{/does-handler} aus behind you have to place your executable Forth
12021: code. Finally you have to create a word and modify its behaviour with
12022: @code{does-handler!}.
1.1 anton 12023:
1.78 anton 12024: doc-does-code!
12025: doc-does-handler!
12026: doc-/does-handler
1.1 anton 12027:
1.78 anton 12028: The code addresses produced by various defining words are produced by
12029: the following words:
1.1 anton 12030:
1.78 anton 12031: doc-docol:
12032: doc-docon:
12033: doc-dovar:
12034: doc-douser:
12035: doc-dodefer:
12036: doc-dofield:
1.1 anton 12037:
1.99 anton 12038: @cindex definer
12039: The following two words generalize @code{>code-address},
12040: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12041:
12042: doc->definer
12043: doc-definer!
12044:
1.26 crook 12045: @c -------------------------------------------------------------
1.78 anton 12046: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12047: @section Passing Commands to the Operating System
12048: @cindex operating system - passing commands
12049: @cindex shell commands
12050:
12051: Gforth allows you to pass an arbitrary string to the host operating
12052: system shell (if such a thing exists) for execution.
12053:
12054: doc-sh
12055: doc-system
12056: doc-$?
1.23 crook 12057: doc-getenv
1.44 crook 12058:
1.26 crook 12059: @c -------------------------------------------------------------
1.47 crook 12060: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12061: @section Keeping track of Time
12062: @cindex time-related words
12063:
12064: doc-ms
12065: doc-time&date
1.79 anton 12066: doc-utime
12067: doc-cputime
1.47 crook 12068:
12069:
12070: @c -------------------------------------------------------------
12071: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12072: @section Miscellaneous Words
12073: @cindex miscellaneous words
12074:
1.29 crook 12075: @comment TODO find homes for these
12076:
1.26 crook 12077: These section lists the ANS Forth words that are not documented
1.21 crook 12078: elsewhere in this manual. Ultimately, they all need proper homes.
12079:
1.68 anton 12080: doc-quit
1.44 crook 12081:
1.26 crook 12082: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12083: (@pxref{ANS conformance}):
1.21 crook 12084:
12085: @code{EDITOR}
12086: @code{EMIT?}
12087: @code{FORGET}
12088:
1.24 anton 12089: @c ******************************************************************
12090: @node Error messages, Tools, Words, Top
12091: @chapter Error messages
12092: @cindex error messages
12093: @cindex backtrace
12094:
12095: A typical Gforth error message looks like this:
12096:
12097: @example
1.86 anton 12098: in file included from \evaluated string/:-1
1.24 anton 12099: in file included from ./yyy.fs:1
12100: ./xxx.fs:4: Invalid memory address
12101: bar
12102: ^^^
1.79 anton 12103: Backtrace:
1.25 anton 12104: $400E664C @@
12105: $400E6664 foo
1.24 anton 12106: @end example
12107:
12108: The message identifying the error is @code{Invalid memory address}. The
12109: error happened when text-interpreting line 4 of the file
12110: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12111: word on the line where the error happened, is pointed out (with
12112: @code{^^^}).
12113:
12114: The file containing the error was included in line 1 of @file{./yyy.fs},
12115: and @file{yyy.fs} was included from a non-file (in this case, by giving
12116: @file{yyy.fs} as command-line parameter to Gforth).
12117:
12118: At the end of the error message you find a return stack dump that can be
12119: interpreted as a backtrace (possibly empty). On top you find the top of
12120: the return stack when the @code{throw} happened, and at the bottom you
12121: find the return stack entry just above the return stack of the topmost
12122: text interpreter.
12123:
12124: To the right of most return stack entries you see a guess for the word
12125: that pushed that return stack entry as its return address. This gives a
12126: backtrace. In our case we see that @code{bar} called @code{foo}, and
12127: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12128: address} exception).
12129:
12130: Note that the backtrace is not perfect: We don't know which return stack
12131: entries are return addresses (so we may get false positives); and in
12132: some cases (e.g., for @code{abort"}) we cannot determine from the return
12133: address the word that pushed the return address, so for some return
12134: addresses you see no names in the return stack dump.
1.25 anton 12135:
12136: @cindex @code{catch} and backtraces
12137: The return stack dump represents the return stack at the time when a
12138: specific @code{throw} was executed. In programs that make use of
12139: @code{catch}, it is not necessarily clear which @code{throw} should be
12140: used for the return stack dump (e.g., consider one @code{throw} that
12141: indicates an error, which is caught, and during recovery another error
1.42 anton 12142: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12143: presents the return stack dump for the first @code{throw} after the last
12144: executed (not returned-to) @code{catch}; this works well in the usual
12145: case.
12146:
12147: @cindex @code{gforth-fast} and backtraces
12148: @cindex @code{gforth-fast}, difference from @code{gforth}
12149: @cindex backtraces with @code{gforth-fast}
12150: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12151: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12152: from primitives (e.g., invalid memory address, stack empty etc.);
12153: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12154: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12155: exception caused by a primitive in @code{gforth-fast}, you will
12156: typically see no return stack dump at all; however, if the exception is
12157: caught by @code{catch} (e.g., for restoring some state), and then
12158: @code{throw}n again, the return stack dump will be for the first such
12159: @code{throw}.
1.2 jwilke 12160:
1.5 anton 12161: @c ******************************************************************
1.24 anton 12162: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12163: @chapter Tools
12164:
12165: @menu
12166: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12167: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12168: @end menu
12169:
12170: See also @ref{Emacs and Gforth}.
12171:
1.126 pazsan 12172: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12173: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12174: @cindex @file{ans-report.fs}
12175: @cindex report the words used in your program
12176: @cindex words used in your program
12177:
12178: If you want to label a Forth program as ANS Forth Program, you must
12179: document which wordsets the program uses; for extension wordsets, it is
12180: helpful to list the words the program requires from these wordsets
12181: (because Forth systems are allowed to provide only some words of them).
12182:
12183: The @file{ans-report.fs} tool makes it easy for you to determine which
12184: words from which wordset and which non-ANS words your application
12185: uses. You simply have to include @file{ans-report.fs} before loading the
12186: program you want to check. After loading your program, you can get the
12187: report with @code{print-ans-report}. A typical use is to run this as
12188: batch job like this:
12189: @example
12190: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12191: @end example
12192:
12193: The output looks like this (for @file{compat/control.fs}):
12194: @example
12195: The program uses the following words
12196: from CORE :
12197: : POSTPONE THEN ; immediate ?dup IF 0=
12198: from BLOCK-EXT :
12199: \
12200: from FILE :
12201: (
12202: @end example
12203:
12204: @subsection Caveats
12205:
12206: Note that @file{ans-report.fs} just checks which words are used, not whether
12207: they are used in an ANS Forth conforming way!
12208:
12209: Some words are defined in several wordsets in the
12210: standard. @file{ans-report.fs} reports them for only one of the
12211: wordsets, and not necessarily the one you expect. It depends on usage
12212: which wordset is the right one to specify. E.g., if you only use the
12213: compilation semantics of @code{S"}, it is a Core word; if you also use
12214: its interpretation semantics, it is a File word.
1.124 anton 12215:
12216:
1.127 anton 12217: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12218: @section Stack depth changes during interpretation
12219: @cindex @file{depth-changes.fs}
12220: @cindex depth changes during interpretation
12221: @cindex stack depth changes during interpretation
12222: @cindex items on the stack after interpretation
12223:
12224: Sometimes you notice that, after loading a file, there are items left
12225: on the stack. The tool @file{depth-changes.fs} helps you find out
12226: quickly where in the file these stack items are coming from.
12227:
12228: The simplest way of using @file{depth-changes.fs} is to include it
12229: before the file(s) you want to check, e.g.:
12230:
12231: @example
12232: gforth depth-changes.fs my-file.fs
12233: @end example
12234:
12235: This will compare the stack depths of the data and FP stack at every
12236: empty line (in interpretation state) against these depths at the last
12237: empty line (in interpretation state). If the depths are not equal,
12238: the position in the file and the stack contents are printed with
12239: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12240: change has occured in the paragraph of non-empty lines before the
12241: indicated line. It is a good idea to leave an empty line at the end
12242: of the file, so the last paragraph is checked, too.
12243:
12244: Checking only at empty lines usually works well, but sometimes you
12245: have big blocks of non-empty lines (e.g., when building a big table),
12246: and you want to know where in this block the stack depth changed. You
12247: can check all interpreted lines with
12248:
12249: @example
12250: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12251: @end example
12252:
12253: This checks the stack depth at every end-of-line. So the depth change
12254: occured in the line reported by the @code{~~} (not in the line
12255: before).
12256:
12257: Note that, while this offers better accuracy in indicating where the
12258: stack depth changes, it will often report many intentional stack depth
12259: changes (e.g., when an interpreted computation stretches across
12260: several lines). You can suppress the checking of some lines by
12261: putting backslashes at the end of these lines (not followed by white
12262: space), and using
12263:
12264: @example
12265: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12266: @end example
1.1 anton 12267:
12268: @c ******************************************************************
1.65 anton 12269: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12270: @chapter ANS conformance
12271: @cindex ANS conformance of Gforth
12272:
12273: To the best of our knowledge, Gforth is an
12274:
12275: ANS Forth System
12276: @itemize @bullet
12277: @item providing the Core Extensions word set
12278: @item providing the Block word set
12279: @item providing the Block Extensions word set
12280: @item providing the Double-Number word set
12281: @item providing the Double-Number Extensions word set
12282: @item providing the Exception word set
12283: @item providing the Exception Extensions word set
12284: @item providing the Facility word set
1.40 anton 12285: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12286: @item providing the File Access word set
12287: @item providing the File Access Extensions word set
12288: @item providing the Floating-Point word set
12289: @item providing the Floating-Point Extensions word set
12290: @item providing the Locals word set
12291: @item providing the Locals Extensions word set
12292: @item providing the Memory-Allocation word set
12293: @item providing the Memory-Allocation Extensions word set (that one's easy)
12294: @item providing the Programming-Tools word set
12295: @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
12296: @item providing the Search-Order word set
12297: @item providing the Search-Order Extensions word set
12298: @item providing the String word set
12299: @item providing the String Extensions word set (another easy one)
12300: @end itemize
12301:
1.118 anton 12302: Gforth has the following environmental restrictions:
12303:
12304: @cindex environmental restrictions
12305: @itemize @bullet
12306: @item
12307: While processing the OS command line, if an exception is not caught,
12308: Gforth exits with a non-zero exit code instyead of performing QUIT.
12309:
12310: @item
12311: When an @code{throw} is performed after a @code{query}, Gforth does not
12312: allways restore the input source specification in effect at the
12313: corresponding catch.
12314:
12315: @end itemize
12316:
12317:
1.1 anton 12318: @cindex system documentation
12319: In addition, ANS Forth systems are required to document certain
12320: implementation choices. This chapter tries to meet these
12321: requirements. In many cases it gives a way to ask the system for the
12322: information instead of providing the information directly, in
12323: particular, if the information depends on the processor, the operating
12324: system or the installation options chosen, or if they are likely to
12325: change during the maintenance of Gforth.
12326:
12327: @comment The framework for the rest has been taken from pfe.
12328:
12329: @menu
12330: * The Core Words::
12331: * The optional Block word set::
12332: * The optional Double Number word set::
12333: * The optional Exception word set::
12334: * The optional Facility word set::
12335: * The optional File-Access word set::
12336: * The optional Floating-Point word set::
12337: * The optional Locals word set::
12338: * The optional Memory-Allocation word set::
12339: * The optional Programming-Tools word set::
12340: * The optional Search-Order word set::
12341: @end menu
12342:
12343:
12344: @c =====================================================================
12345: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12346: @comment node-name, next, previous, up
12347: @section The Core Words
12348: @c =====================================================================
12349: @cindex core words, system documentation
12350: @cindex system documentation, core words
12351:
12352: @menu
12353: * core-idef:: Implementation Defined Options
12354: * core-ambcond:: Ambiguous Conditions
12355: * core-other:: Other System Documentation
12356: @end menu
12357:
12358: @c ---------------------------------------------------------------------
12359: @node core-idef, core-ambcond, The Core Words, The Core Words
12360: @subsection Implementation Defined Options
12361: @c ---------------------------------------------------------------------
12362: @cindex core words, implementation-defined options
12363: @cindex implementation-defined options, core words
12364:
12365:
12366: @table @i
12367: @item (Cell) aligned addresses:
12368: @cindex cell-aligned addresses
12369: @cindex aligned addresses
12370: processor-dependent. Gforth's alignment words perform natural alignment
12371: (e.g., an address aligned for a datum of size 8 is divisible by
12372: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12373:
12374: @item @code{EMIT} and non-graphic characters:
12375: @cindex @code{EMIT} and non-graphic characters
12376: @cindex non-graphic characters and @code{EMIT}
12377: The character is output using the C library function (actually, macro)
12378: @code{putc}.
12379:
12380: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12381: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12382: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12383: @cindex @code{ACCEPT}, editing
12384: @cindex @code{EXPECT}, editing
12385: This is modeled on the GNU readline library (@pxref{Readline
12386: Interaction, , Command Line Editing, readline, The GNU Readline
12387: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12388: producing a full word completion every time you type it (instead of
1.28 crook 12389: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12390:
12391: @item character set:
12392: @cindex character set
12393: The character set of your computer and display device. Gforth is
12394: 8-bit-clean (but some other component in your system may make trouble).
12395:
12396: @item Character-aligned address requirements:
12397: @cindex character-aligned address requirements
12398: installation-dependent. Currently a character is represented by a C
12399: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12400: (Comments on that requested).
12401:
12402: @item character-set extensions and matching of names:
12403: @cindex character-set extensions and matching of names
1.26 crook 12404: @cindex case-sensitivity for name lookup
12405: @cindex name lookup, case-sensitivity
12406: @cindex locale and case-sensitivity
1.21 crook 12407: Any character except the ASCII NUL character can be used in a
1.1 anton 12408: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12409: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12410: function is probably influenced by the locale. E.g., the @code{C} locale
12411: does not know about accents and umlauts, so they are matched
12412: case-sensitively in that locale. For portability reasons it is best to
12413: write programs such that they work in the @code{C} locale. Then one can
12414: use libraries written by a Polish programmer (who might use words
12415: containing ISO Latin-2 encoded characters) and by a French programmer
12416: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12417: funny results for some of the words (which ones, depends on the font you
12418: are using)). Also, the locale you prefer may not be available in other
12419: operating systems. Hopefully, Unicode will solve these problems one day.
12420:
12421: @item conditions under which control characters match a space delimiter:
12422: @cindex space delimiters
12423: @cindex control characters as delimiters
1.117 anton 12424: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12425: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12426: are delimiters. @code{Parse}, on the other hand, treats space like other
12427: delimiters. @code{Parse-word}, which is used by the outer
1.1 anton 12428: interpreter (aka text interpreter) by default, treats all white-space
12429: characters as delimiters.
12430:
1.26 crook 12431: @item format of the control-flow stack:
12432: @cindex control-flow stack, format
12433: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12434: stack item in cells is given by the constant @code{cs-item-size}. At the
12435: time of this writing, an item consists of a (pointer to a) locals list
12436: (third), an address in the code (second), and a tag for identifying the
12437: item (TOS). The following tags are used: @code{defstart},
12438: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12439: @code{scopestart}.
12440:
12441: @item conversion of digits > 35
12442: @cindex digits > 35
12443: The characters @code{[\]^_'} are the digits with the decimal value
12444: 36@minus{}41. There is no way to input many of the larger digits.
12445:
12446: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12447: @cindex @code{EXPECT}, display after end of input
12448: @cindex @code{ACCEPT}, display after end of input
12449: The cursor is moved to the end of the entered string. If the input is
12450: terminated using the @kbd{Return} key, a space is typed.
12451:
12452: @item exception abort sequence of @code{ABORT"}:
12453: @cindex exception abort sequence of @code{ABORT"}
12454: @cindex @code{ABORT"}, exception abort sequence
12455: The error string is stored into the variable @code{"error} and a
12456: @code{-2 throw} is performed.
12457:
12458: @item input line terminator:
12459: @cindex input line terminator
12460: @cindex line terminator on input
1.26 crook 12461: @cindex newline character on input
1.1 anton 12462: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12463: lines. One of these characters is typically produced when you type the
12464: @kbd{Enter} or @kbd{Return} key.
12465:
12466: @item maximum size of a counted string:
12467: @cindex maximum size of a counted string
12468: @cindex counted string, maximum size
12469: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12470: on all platforms, but this may change.
1.1 anton 12471:
12472: @item maximum size of a parsed string:
12473: @cindex maximum size of a parsed string
12474: @cindex parsed string, maximum size
12475: Given by the constant @code{/line}. Currently 255 characters.
12476:
12477: @item maximum size of a definition name, in characters:
12478: @cindex maximum size of a definition name, in characters
12479: @cindex name, maximum length
1.113 anton 12480: MAXU/8
1.1 anton 12481:
12482: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12483: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12484: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12485: MAXU/8
1.1 anton 12486:
12487: @item method of selecting the user input device:
12488: @cindex user input device, method of selecting
12489: The user input device is the standard input. There is currently no way to
12490: change it from within Gforth. However, the input can typically be
12491: redirected in the command line that starts Gforth.
12492:
12493: @item method of selecting the user output device:
12494: @cindex user output device, method of selecting
12495: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12496: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12497: output when the user output device is a terminal, otherwise the output
12498: is buffered.
1.1 anton 12499:
12500: @item methods of dictionary compilation:
12501: What are we expected to document here?
12502:
12503: @item number of bits in one address unit:
12504: @cindex number of bits in one address unit
12505: @cindex address unit, size in bits
12506: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12507: platforms.
1.1 anton 12508:
12509: @item number representation and arithmetic:
12510: @cindex number representation and arithmetic
1.79 anton 12511: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12512:
12513: @item ranges for integer types:
12514: @cindex ranges for integer types
12515: @cindex integer types, ranges
12516: Installation-dependent. Make environmental queries for @code{MAX-N},
12517: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12518: unsigned (and positive) types is 0. The lower bound for signed types on
12519: two's complement and one's complement machines machines can be computed
12520: by adding 1 to the upper bound.
12521:
12522: @item read-only data space regions:
12523: @cindex read-only data space regions
12524: @cindex data-space, read-only regions
12525: The whole Forth data space is writable.
12526:
12527: @item size of buffer at @code{WORD}:
12528: @cindex size of buffer at @code{WORD}
12529: @cindex @code{WORD} buffer size
12530: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12531: shared with the pictured numeric output string. If overwriting
12532: @code{PAD} is acceptable, it is as large as the remaining dictionary
12533: space, although only as much can be sensibly used as fits in a counted
12534: string.
12535:
12536: @item size of one cell in address units:
12537: @cindex cell size
12538: @code{1 cells .}.
12539:
12540: @item size of one character in address units:
12541: @cindex char size
1.79 anton 12542: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12543:
12544: @item size of the keyboard terminal buffer:
12545: @cindex size of the keyboard terminal buffer
12546: @cindex terminal buffer, size
12547: Varies. You can determine the size at a specific time using @code{lp@@
12548: tib - .}. It is shared with the locals stack and TIBs of files that
12549: include the current file. You can change the amount of space for TIBs
12550: and locals stack at Gforth startup with the command line option
12551: @code{-l}.
12552:
12553: @item size of the pictured numeric output buffer:
12554: @cindex size of the pictured numeric output buffer
12555: @cindex pictured numeric output buffer, size
12556: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12557: shared with @code{WORD}.
12558:
12559: @item size of the scratch area returned by @code{PAD}:
12560: @cindex size of the scratch area returned by @code{PAD}
12561: @cindex @code{PAD} size
12562: The remainder of dictionary space. @code{unused pad here - - .}.
12563:
12564: @item system case-sensitivity characteristics:
12565: @cindex case-sensitivity characteristics
1.26 crook 12566: Dictionary searches are case-insensitive (except in
1.1 anton 12567: @code{TABLE}s). However, as explained above under @i{character-set
12568: extensions}, the matching for non-ASCII characters is determined by the
12569: locale you are using. In the default @code{C} locale all non-ASCII
12570: characters are matched case-sensitively.
12571:
12572: @item system prompt:
12573: @cindex system prompt
12574: @cindex prompt
12575: @code{ ok} in interpret state, @code{ compiled} in compile state.
12576:
12577: @item division rounding:
12578: @cindex division rounding
12579: installation dependent. @code{s" floored" environment? drop .}. We leave
12580: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12581: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12582:
12583: @item values of @code{STATE} when true:
12584: @cindex @code{STATE} values
12585: -1.
12586:
12587: @item values returned after arithmetic overflow:
12588: On two's complement machines, arithmetic is performed modulo
12589: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12590: arithmetic (with appropriate mapping for signed types). Division by zero
12591: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12592: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12593:
12594: @item whether the current definition can be found after @t{DOES>}:
12595: @cindex @t{DOES>}, visibility of current definition
12596: No.
12597:
12598: @end table
12599:
12600: @c ---------------------------------------------------------------------
12601: @node core-ambcond, core-other, core-idef, The Core Words
12602: @subsection Ambiguous conditions
12603: @c ---------------------------------------------------------------------
12604: @cindex core words, ambiguous conditions
12605: @cindex ambiguous conditions, core words
12606:
12607: @table @i
12608:
12609: @item a name is neither a word nor a number:
12610: @cindex name not found
1.26 crook 12611: @cindex undefined word
1.80 anton 12612: @code{-13 throw} (Undefined word).
1.1 anton 12613:
12614: @item a definition name exceeds the maximum length allowed:
1.26 crook 12615: @cindex word name too long
1.1 anton 12616: @code{-19 throw} (Word name too long)
12617:
12618: @item addressing a region not inside the various data spaces of the forth system:
12619: @cindex Invalid memory address
1.32 anton 12620: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12621: typically readable. Accessing other addresses gives results dependent on
12622: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12623: address).
12624:
12625: @item argument type incompatible with parameter:
1.26 crook 12626: @cindex argument type mismatch
1.1 anton 12627: This is usually not caught. Some words perform checks, e.g., the control
12628: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12629: mismatch).
12630:
12631: @item attempting to obtain the execution token of a word with undefined execution semantics:
12632: @cindex Interpreting a compile-only word, for @code{'} etc.
12633: @cindex execution token of words with undefined execution semantics
12634: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12635: get an execution token for @code{compile-only-error} (which performs a
12636: @code{-14 throw} when executed).
12637:
12638: @item dividing by zero:
12639: @cindex dividing by zero
12640: @cindex floating point unidentified fault, integer division
1.80 anton 12641: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12642: zero); on other systems, this typically results in a @code{-55 throw}
12643: (Floating-point unidentified fault).
1.1 anton 12644:
12645: @item insufficient data stack or return stack space:
12646: @cindex insufficient data stack or return stack space
12647: @cindex stack overflow
1.26 crook 12648: @cindex address alignment exception, stack overflow
1.1 anton 12649: @cindex Invalid memory address, stack overflow
12650: Depending on the operating system, the installation, and the invocation
12651: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12652: it is not checked. If it is checked, you typically get a @code{-3 throw}
12653: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12654: throw} (Invalid memory address) (depending on the platform and how you
12655: achieved the overflow) as soon as the overflow happens. If it is not
12656: checked, overflows typically result in mysterious illegal memory
12657: accesses, producing @code{-9 throw} (Invalid memory address) or
12658: @code{-23 throw} (Address alignment exception); they might also destroy
12659: the internal data structure of @code{ALLOCATE} and friends, resulting in
12660: various errors in these words.
1.1 anton 12661:
12662: @item insufficient space for loop control parameters:
12663: @cindex insufficient space for loop control parameters
1.80 anton 12664: Like other return stack overflows.
1.1 anton 12665:
12666: @item insufficient space in the dictionary:
12667: @cindex insufficient space in the dictionary
12668: @cindex dictionary overflow
1.12 anton 12669: If you try to allot (either directly with @code{allot}, or indirectly
12670: with @code{,}, @code{create} etc.) more memory than available in the
12671: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12672: to access memory beyond the end of the dictionary, the results are
12673: similar to stack overflows.
1.1 anton 12674:
12675: @item interpreting a word with undefined interpretation semantics:
12676: @cindex interpreting a word with undefined interpretation semantics
12677: @cindex Interpreting a compile-only word
12678: For some words, we have defined interpretation semantics. For the
12679: others: @code{-14 throw} (Interpreting a compile-only word).
12680:
12681: @item modifying the contents of the input buffer or a string literal:
12682: @cindex modifying the contents of the input buffer or a string literal
12683: These are located in writable memory and can be modified.
12684:
12685: @item overflow of the pictured numeric output string:
12686: @cindex overflow of the pictured numeric output string
12687: @cindex pictured numeric output string, overflow
1.24 anton 12688: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12689:
12690: @item parsed string overflow:
12691: @cindex parsed string overflow
12692: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12693:
12694: @item producing a result out of range:
12695: @cindex result out of range
12696: On two's complement machines, arithmetic is performed modulo
12697: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12698: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12699: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12700: throw} (floating point unidentified fault). @code{convert} and
12701: @code{>number} currently overflow silently.
1.1 anton 12702:
12703: @item reading from an empty data or return stack:
12704: @cindex stack empty
12705: @cindex stack underflow
1.24 anton 12706: @cindex return stack underflow
1.1 anton 12707: The data stack is checked by the outer (aka text) interpreter after
12708: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12709: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12710: depending on operating system, installation, and invocation. If they are
12711: caught by a check, they typically result in @code{-4 throw} (Stack
12712: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12713: (Invalid memory address), depending on the platform and which stack
12714: underflows and by how much. Note that even if the system uses checking
12715: (through the MMU), your program may have to underflow by a significant
12716: number of stack items to trigger the reaction (the reason for this is
12717: that the MMU, and therefore the checking, works with a page-size
12718: granularity). If there is no checking, the symptoms resulting from an
12719: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12720: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12721: (Invalid memory address) and Illegal Instruction (typically @code{-260
12722: throw}).
1.1 anton 12723:
12724: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12725: @cindex unexpected end of the input buffer
12726: @cindex zero-length string as a name
12727: @cindex Attempt to use zero-length string as a name
12728: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12729: use zero-length string as a name). Words like @code{'} probably will not
12730: find what they search. Note that it is possible to create zero-length
12731: names with @code{nextname} (should it not?).
12732:
12733: @item @code{>IN} greater than input buffer:
12734: @cindex @code{>IN} greater than input buffer
12735: The next invocation of a parsing word returns a string with length 0.
12736:
12737: @item @code{RECURSE} appears after @code{DOES>}:
12738: @cindex @code{RECURSE} appears after @code{DOES>}
12739: Compiles a recursive call to the defining word, not to the defined word.
12740:
12741: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12742: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12743: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12744: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12745: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12746: the end of the file was reached), its source-id may be
12747: reused. Therefore, restoring an input source specification referencing a
12748: closed file may lead to unpredictable results instead of a @code{-12
12749: THROW}.
12750:
12751: In the future, Gforth may be able to restore input source specifications
12752: from other than the current input source.
12753:
12754: @item data space containing definitions gets de-allocated:
12755: @cindex data space containing definitions gets de-allocated
12756: Deallocation with @code{allot} is not checked. This typically results in
12757: memory access faults or execution of illegal instructions.
12758:
12759: @item data space read/write with incorrect alignment:
12760: @cindex data space read/write with incorrect alignment
12761: @cindex alignment faults
1.26 crook 12762: @cindex address alignment exception
1.1 anton 12763: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12764: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12765: alignment turned on, incorrect alignment results in a @code{-9 throw}
12766: (Invalid memory address). There are reportedly some processors with
1.12 anton 12767: alignment restrictions that do not report violations.
1.1 anton 12768:
12769: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12770: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12771: Like other alignment errors.
12772:
12773: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12774: Like other stack underflows.
12775:
12776: @item loop control parameters not available:
12777: @cindex loop control parameters not available
12778: Not checked. The counted loop words simply assume that the top of return
12779: stack items are loop control parameters and behave accordingly.
12780:
12781: @item most recent definition does not have a name (@code{IMMEDIATE}):
12782: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12783: @cindex last word was headerless
12784: @code{abort" last word was headerless"}.
12785:
12786: @item name not defined by @code{VALUE} used by @code{TO}:
12787: @cindex name not defined by @code{VALUE} used by @code{TO}
12788: @cindex @code{TO} on non-@code{VALUE}s
12789: @cindex Invalid name argument, @code{TO}
12790: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12791: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12792:
12793: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12794: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12795: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12796: @code{-13 throw} (Undefined word)
12797:
12798: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12799: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12800: Gforth behaves as if they were of the same type. I.e., you can predict
12801: the behaviour by interpreting all parameters as, e.g., signed.
12802:
12803: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12804: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12805: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12806: compilation semantics of @code{TO}.
12807:
12808: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12809: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12810: @cindex @code{WORD}, string overflow
12811: Not checked. The string will be ok, but the count will, of course,
12812: contain only the least significant bits of the length.
12813:
12814: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12815: @cindex @code{LSHIFT}, large shift counts
12816: @cindex @code{RSHIFT}, large shift counts
12817: Processor-dependent. Typical behaviours are returning 0 and using only
12818: the low bits of the shift count.
12819:
12820: @item word not defined via @code{CREATE}:
12821: @cindex @code{>BODY} of non-@code{CREATE}d words
12822: @code{>BODY} produces the PFA of the word no matter how it was defined.
12823:
12824: @cindex @code{DOES>} of non-@code{CREATE}d words
12825: @code{DOES>} changes the execution semantics of the last defined word no
12826: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12827: @code{CREATE , DOES>}.
12828:
12829: @item words improperly used outside @code{<#} and @code{#>}:
12830: Not checked. As usual, you can expect memory faults.
12831:
12832: @end table
12833:
12834:
12835: @c ---------------------------------------------------------------------
12836: @node core-other, , core-ambcond, The Core Words
12837: @subsection Other system documentation
12838: @c ---------------------------------------------------------------------
12839: @cindex other system documentation, core words
12840: @cindex core words, other system documentation
12841:
12842: @table @i
12843: @item nonstandard words using @code{PAD}:
12844: @cindex @code{PAD} use by nonstandard words
12845: None.
12846:
12847: @item operator's terminal facilities available:
12848: @cindex operator's terminal facilities available
1.80 anton 12849: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12850: and you can give commands to Gforth interactively. The actual facilities
12851: available depend on how you invoke Gforth.
12852:
12853: @item program data space available:
12854: @cindex program data space available
12855: @cindex data space available
12856: @code{UNUSED .} gives the remaining dictionary space. The total
12857: dictionary space can be specified with the @code{-m} switch
12858: (@pxref{Invoking Gforth}) when Gforth starts up.
12859:
12860: @item return stack space available:
12861: @cindex return stack space available
12862: You can compute the total return stack space in cells with
12863: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12864: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12865:
12866: @item stack space available:
12867: @cindex stack space available
12868: You can compute the total data stack space in cells with
12869: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12870: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12871:
12872: @item system dictionary space required, in address units:
12873: @cindex system dictionary space required, in address units
12874: Type @code{here forthstart - .} after startup. At the time of this
12875: writing, this gives 80080 (bytes) on a 32-bit system.
12876: @end table
12877:
12878:
12879: @c =====================================================================
12880: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12881: @section The optional Block word set
12882: @c =====================================================================
12883: @cindex system documentation, block words
12884: @cindex block words, system documentation
12885:
12886: @menu
12887: * block-idef:: Implementation Defined Options
12888: * block-ambcond:: Ambiguous Conditions
12889: * block-other:: Other System Documentation
12890: @end menu
12891:
12892:
12893: @c ---------------------------------------------------------------------
12894: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12895: @subsection Implementation Defined Options
12896: @c ---------------------------------------------------------------------
12897: @cindex implementation-defined options, block words
12898: @cindex block words, implementation-defined options
12899:
12900: @table @i
12901: @item the format for display by @code{LIST}:
12902: @cindex @code{LIST} display format
12903: First the screen number is displayed, then 16 lines of 64 characters,
12904: each line preceded by the line number.
12905:
12906: @item the length of a line affected by @code{\}:
12907: @cindex length of a line affected by @code{\}
12908: @cindex @code{\}, line length in blocks
12909: 64 characters.
12910: @end table
12911:
12912:
12913: @c ---------------------------------------------------------------------
12914: @node block-ambcond, block-other, block-idef, The optional Block word set
12915: @subsection Ambiguous conditions
12916: @c ---------------------------------------------------------------------
12917: @cindex block words, ambiguous conditions
12918: @cindex ambiguous conditions, block words
12919:
12920: @table @i
12921: @item correct block read was not possible:
12922: @cindex block read not possible
12923: Typically results in a @code{throw} of some OS-derived value (between
12924: -512 and -2048). If the blocks file was just not long enough, blanks are
12925: supplied for the missing portion.
12926:
12927: @item I/O exception in block transfer:
12928: @cindex I/O exception in block transfer
12929: @cindex block transfer, I/O exception
12930: Typically results in a @code{throw} of some OS-derived value (between
12931: -512 and -2048).
12932:
12933: @item invalid block number:
12934: @cindex invalid block number
12935: @cindex block number invalid
12936: @code{-35 throw} (Invalid block number)
12937:
12938: @item a program directly alters the contents of @code{BLK}:
12939: @cindex @code{BLK}, altering @code{BLK}
12940: The input stream is switched to that other block, at the same
12941: position. If the storing to @code{BLK} happens when interpreting
12942: non-block input, the system will get quite confused when the block ends.
12943:
12944: @item no current block buffer for @code{UPDATE}:
12945: @cindex @code{UPDATE}, no current block buffer
12946: @code{UPDATE} has no effect.
12947:
12948: @end table
12949:
12950: @c ---------------------------------------------------------------------
12951: @node block-other, , block-ambcond, The optional Block word set
12952: @subsection Other system documentation
12953: @c ---------------------------------------------------------------------
12954: @cindex other system documentation, block words
12955: @cindex block words, other system documentation
12956:
12957: @table @i
12958: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12959: No restrictions (yet).
12960:
12961: @item the number of blocks available for source and data:
12962: depends on your disk space.
12963:
12964: @end table
12965:
12966:
12967: @c =====================================================================
12968: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12969: @section The optional Double Number word set
12970: @c =====================================================================
12971: @cindex system documentation, double words
12972: @cindex double words, system documentation
12973:
12974: @menu
12975: * double-ambcond:: Ambiguous Conditions
12976: @end menu
12977:
12978:
12979: @c ---------------------------------------------------------------------
12980: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12981: @subsection Ambiguous conditions
12982: @c ---------------------------------------------------------------------
12983: @cindex double words, ambiguous conditions
12984: @cindex ambiguous conditions, double words
12985:
12986: @table @i
1.29 crook 12987: @item @i{d} outside of range of @i{n} in @code{D>S}:
12988: @cindex @code{D>S}, @i{d} out of range of @i{n}
12989: The least significant cell of @i{d} is produced.
1.1 anton 12990:
12991: @end table
12992:
12993:
12994: @c =====================================================================
12995: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12996: @section The optional Exception word set
12997: @c =====================================================================
12998: @cindex system documentation, exception words
12999: @cindex exception words, system documentation
13000:
13001: @menu
13002: * exception-idef:: Implementation Defined Options
13003: @end menu
13004:
13005:
13006: @c ---------------------------------------------------------------------
13007: @node exception-idef, , The optional Exception word set, The optional Exception word set
13008: @subsection Implementation Defined Options
13009: @c ---------------------------------------------------------------------
13010: @cindex implementation-defined options, exception words
13011: @cindex exception words, implementation-defined options
13012:
13013: @table @i
13014: @item @code{THROW}-codes used in the system:
13015: @cindex @code{THROW}-codes used in the system
13016: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13017: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13018: codes -512@minus{}-2047 are used for OS errors (for file and memory
13019: allocation operations). The mapping from OS error numbers to throw codes
13020: is -512@minus{}@code{errno}. One side effect of this mapping is that
13021: undefined OS errors produce a message with a strange number; e.g.,
13022: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13023: @end table
13024:
13025: @c =====================================================================
13026: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13027: @section The optional Facility word set
13028: @c =====================================================================
13029: @cindex system documentation, facility words
13030: @cindex facility words, system documentation
13031:
13032: @menu
13033: * facility-idef:: Implementation Defined Options
13034: * facility-ambcond:: Ambiguous Conditions
13035: @end menu
13036:
13037:
13038: @c ---------------------------------------------------------------------
13039: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13040: @subsection Implementation Defined Options
13041: @c ---------------------------------------------------------------------
13042: @cindex implementation-defined options, facility words
13043: @cindex facility words, implementation-defined options
13044:
13045: @table @i
13046: @item encoding of keyboard events (@code{EKEY}):
13047: @cindex keyboard events, encoding in @code{EKEY}
13048: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13049: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13050: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13051: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13052: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13053: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13054:
1.1 anton 13055:
13056: @item duration of a system clock tick:
13057: @cindex duration of a system clock tick
13058: @cindex clock tick duration
13059: System dependent. With respect to @code{MS}, the time is specified in
13060: microseconds. How well the OS and the hardware implement this, is
13061: another question.
13062:
13063: @item repeatability to be expected from the execution of @code{MS}:
13064: @cindex repeatability to be expected from the execution of @code{MS}
13065: @cindex @code{MS}, repeatability to be expected
13066: System dependent. On Unix, a lot depends on load. If the system is
13067: lightly loaded, and the delay is short enough that Gforth does not get
13068: swapped out, the performance should be acceptable. Under MS-DOS and
13069: other single-tasking systems, it should be good.
13070:
13071: @end table
13072:
13073:
13074: @c ---------------------------------------------------------------------
13075: @node facility-ambcond, , facility-idef, The optional Facility word set
13076: @subsection Ambiguous conditions
13077: @c ---------------------------------------------------------------------
13078: @cindex facility words, ambiguous conditions
13079: @cindex ambiguous conditions, facility words
13080:
13081: @table @i
13082: @item @code{AT-XY} can't be performed on user output device:
13083: @cindex @code{AT-XY} can't be performed on user output device
13084: Largely terminal dependent. No range checks are done on the arguments.
13085: No errors are reported. You may see some garbage appearing, you may see
13086: simply nothing happen.
13087:
13088: @end table
13089:
13090:
13091: @c =====================================================================
13092: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13093: @section The optional File-Access word set
13094: @c =====================================================================
13095: @cindex system documentation, file words
13096: @cindex file words, system documentation
13097:
13098: @menu
13099: * file-idef:: Implementation Defined Options
13100: * file-ambcond:: Ambiguous Conditions
13101: @end menu
13102:
13103: @c ---------------------------------------------------------------------
13104: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13105: @subsection Implementation Defined Options
13106: @c ---------------------------------------------------------------------
13107: @cindex implementation-defined options, file words
13108: @cindex file words, implementation-defined options
13109:
13110: @table @i
13111: @item file access methods used:
13112: @cindex file access methods used
13113: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13114: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13115: @code{wb}): The file is cleared, if it exists, and created, if it does
13116: not (with both @code{open-file} and @code{create-file}). Under Unix
13117: @code{create-file} creates a file with 666 permissions modified by your
13118: umask.
13119:
13120: @item file exceptions:
13121: @cindex file exceptions
13122: The file words do not raise exceptions (except, perhaps, memory access
13123: faults when you pass illegal addresses or file-ids).
13124:
13125: @item file line terminator:
13126: @cindex file line terminator
13127: System-dependent. Gforth uses C's newline character as line
13128: terminator. What the actual character code(s) of this are is
13129: system-dependent.
13130:
13131: @item file name format:
13132: @cindex file name format
13133: System dependent. Gforth just uses the file name format of your OS.
13134:
13135: @item information returned by @code{FILE-STATUS}:
13136: @cindex @code{FILE-STATUS}, returned information
13137: @code{FILE-STATUS} returns the most powerful file access mode allowed
13138: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13139: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13140: along with the returned mode.
13141:
13142: @item input file state after an exception when including source:
13143: @cindex exception when including source
13144: All files that are left via the exception are closed.
13145:
1.29 crook 13146: @item @i{ior} values and meaning:
13147: @cindex @i{ior} values and meaning
1.68 anton 13148: @cindex @i{wior} values and meaning
1.29 crook 13149: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13150: intended as throw codes. They typically are in the range
13151: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13152: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13153:
13154: @item maximum depth of file input nesting:
13155: @cindex maximum depth of file input nesting
13156: @cindex file input nesting, maximum depth
13157: limited by the amount of return stack, locals/TIB stack, and the number
13158: of open files available. This should not give you troubles.
13159:
13160: @item maximum size of input line:
13161: @cindex maximum size of input line
13162: @cindex input line size, maximum
13163: @code{/line}. Currently 255.
13164:
13165: @item methods of mapping block ranges to files:
13166: @cindex mapping block ranges to files
13167: @cindex files containing blocks
13168: @cindex blocks in files
13169: By default, blocks are accessed in the file @file{blocks.fb} in the
13170: current working directory. The file can be switched with @code{USE}.
13171:
13172: @item number of string buffers provided by @code{S"}:
13173: @cindex @code{S"}, number of string buffers
13174: 1
13175:
13176: @item size of string buffer used by @code{S"}:
13177: @cindex @code{S"}, size of string buffer
13178: @code{/line}. currently 255.
13179:
13180: @end table
13181:
13182: @c ---------------------------------------------------------------------
13183: @node file-ambcond, , file-idef, The optional File-Access word set
13184: @subsection Ambiguous conditions
13185: @c ---------------------------------------------------------------------
13186: @cindex file words, ambiguous conditions
13187: @cindex ambiguous conditions, file words
13188:
13189: @table @i
13190: @item attempting to position a file outside its boundaries:
13191: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13192: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13193: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13194:
13195: @item attempting to read from file positions not yet written:
13196: @cindex reading from file positions not yet written
13197: End-of-file, i.e., zero characters are read and no error is reported.
13198:
1.29 crook 13199: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13200: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13201: An appropriate exception may be thrown, but a memory fault or other
13202: problem is more probable.
13203:
1.29 crook 13204: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13205: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13206: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13207: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13208: thrown.
13209:
13210: @item named file cannot be opened (@code{INCLUDED}):
13211: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13212: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13213:
13214: @item requesting an unmapped block number:
13215: @cindex unmapped block numbers
13216: There are no unmapped legal block numbers. On some operating systems,
13217: writing a block with a large number may overflow the file system and
13218: have an error message as consequence.
13219:
13220: @item using @code{source-id} when @code{blk} is non-zero:
13221: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13222: @code{source-id} performs its function. Typically it will give the id of
13223: the source which loaded the block. (Better ideas?)
13224:
13225: @end table
13226:
13227:
13228: @c =====================================================================
13229: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13230: @section The optional Floating-Point word set
13231: @c =====================================================================
13232: @cindex system documentation, floating-point words
13233: @cindex floating-point words, system documentation
13234:
13235: @menu
13236: * floating-idef:: Implementation Defined Options
13237: * floating-ambcond:: Ambiguous Conditions
13238: @end menu
13239:
13240:
13241: @c ---------------------------------------------------------------------
13242: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13243: @subsection Implementation Defined Options
13244: @c ---------------------------------------------------------------------
13245: @cindex implementation-defined options, floating-point words
13246: @cindex floating-point words, implementation-defined options
13247:
13248: @table @i
13249: @item format and range of floating point numbers:
13250: @cindex format and range of floating point numbers
13251: @cindex floating point numbers, format and range
13252: System-dependent; the @code{double} type of C.
13253:
1.29 crook 13254: @item results of @code{REPRESENT} when @i{float} is out of range:
13255: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13256: System dependent; @code{REPRESENT} is implemented using the C library
13257: function @code{ecvt()} and inherits its behaviour in this respect.
13258:
13259: @item rounding or truncation of floating-point numbers:
13260: @cindex rounding of floating-point numbers
13261: @cindex truncation of floating-point numbers
13262: @cindex floating-point numbers, rounding or truncation
13263: System dependent; the rounding behaviour is inherited from the hosting C
13264: compiler. IEEE-FP-based (i.e., most) systems by default round to
13265: nearest, and break ties by rounding to even (i.e., such that the last
13266: bit of the mantissa is 0).
13267:
13268: @item size of floating-point stack:
13269: @cindex floating-point stack size
13270: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13271: the floating-point stack (in floats). You can specify this on startup
13272: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13273:
13274: @item width of floating-point stack:
13275: @cindex floating-point stack width
13276: @code{1 floats}.
13277:
13278: @end table
13279:
13280:
13281: @c ---------------------------------------------------------------------
13282: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13283: @subsection Ambiguous conditions
13284: @c ---------------------------------------------------------------------
13285: @cindex floating-point words, ambiguous conditions
13286: @cindex ambiguous conditions, floating-point words
13287:
13288: @table @i
13289: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13290: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13291: System-dependent. Typically results in a @code{-23 THROW} like other
13292: alignment violations.
13293:
13294: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13295: @cindex @code{f@@} used with an address that is not float aligned
13296: @cindex @code{f!} used with an address that is not float aligned
13297: System-dependent. Typically results in a @code{-23 THROW} like other
13298: alignment violations.
13299:
13300: @item floating-point result out of range:
13301: @cindex floating-point result out of range
1.80 anton 13302: System-dependent. Can result in a @code{-43 throw} (floating point
13303: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13304: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13305: unidentified fault), or can produce a special value representing, e.g.,
13306: Infinity.
13307:
13308: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13309: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13310: System-dependent. Typically results in an alignment fault like other
13311: alignment violations.
13312:
1.35 anton 13313: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13314: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13315: The floating-point number is converted into decimal nonetheless.
13316:
13317: @item Both arguments are equal to zero (@code{FATAN2}):
13318: @cindex @code{FATAN2}, both arguments are equal to zero
13319: System-dependent. @code{FATAN2} is implemented using the C library
13320: function @code{atan2()}.
13321:
1.29 crook 13322: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13323: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13324: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13325: because of small errors and the tan will be a very large (or very small)
13326: but finite number.
13327:
1.29 crook 13328: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13329: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13330: The result is rounded to the nearest float.
13331:
13332: @item dividing by zero:
13333: @cindex dividing by zero, floating-point
13334: @cindex floating-point dividing by zero
13335: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13336: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13337: (floating point divide by zero) or @code{-55 throw} (Floating-point
13338: unidentified fault).
1.1 anton 13339:
13340: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13341: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13342: System dependent. On IEEE-FP based systems the number is converted into
13343: an infinity.
13344:
1.29 crook 13345: @item @i{float}<1 (@code{FACOSH}):
13346: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13347: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13348: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13349:
1.29 crook 13350: @item @i{float}=<-1 (@code{FLNP1}):
13351: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13352: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13353: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13354: negative infinity for @i{float}=-1).
1.1 anton 13355:
1.29 crook 13356: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13357: @cindex @code{FLN}, @i{float}=<0
13358: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13359: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13360: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13361: negative infinity for @i{float}=0).
1.1 anton 13362:
1.29 crook 13363: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13364: @cindex @code{FASINH}, @i{float}<0
13365: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13366: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13367: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13368: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13369: C library?).
1.1 anton 13370:
1.29 crook 13371: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13372: @cindex @code{FACOS}, |@i{float}|>1
13373: @cindex @code{FASIN}, |@i{float}|>1
13374: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13375: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13376: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13377:
1.29 crook 13378: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13379: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13380: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13381: Platform-dependent; typically, some double number is produced and no
13382: error is reported.
1.1 anton 13383:
13384: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13385: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13386: @code{Precision} characters of the numeric output area are used. If
13387: @code{precision} is too high, these words will smash the data or code
13388: close to @code{here}.
1.1 anton 13389: @end table
13390:
13391: @c =====================================================================
13392: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13393: @section The optional Locals word set
13394: @c =====================================================================
13395: @cindex system documentation, locals words
13396: @cindex locals words, system documentation
13397:
13398: @menu
13399: * locals-idef:: Implementation Defined Options
13400: * locals-ambcond:: Ambiguous Conditions
13401: @end menu
13402:
13403:
13404: @c ---------------------------------------------------------------------
13405: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13406: @subsection Implementation Defined Options
13407: @c ---------------------------------------------------------------------
13408: @cindex implementation-defined options, locals words
13409: @cindex locals words, implementation-defined options
13410:
13411: @table @i
13412: @item maximum number of locals in a definition:
13413: @cindex maximum number of locals in a definition
13414: @cindex locals, maximum number in a definition
13415: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13416: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13417: characters. The number of locals in a definition is bounded by the size
13418: of locals-buffer, which contains the names of the locals.
13419:
13420: @end table
13421:
13422:
13423: @c ---------------------------------------------------------------------
13424: @node locals-ambcond, , locals-idef, The optional Locals word set
13425: @subsection Ambiguous conditions
13426: @c ---------------------------------------------------------------------
13427: @cindex locals words, ambiguous conditions
13428: @cindex ambiguous conditions, locals words
13429:
13430: @table @i
13431: @item executing a named local in interpretation state:
13432: @cindex local in interpretation state
13433: @cindex Interpreting a compile-only word, for a local
13434: Locals have no interpretation semantics. If you try to perform the
13435: interpretation semantics, you will get a @code{-14 throw} somewhere
13436: (Interpreting a compile-only word). If you perform the compilation
13437: semantics, the locals access will be compiled (irrespective of state).
13438:
1.29 crook 13439: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13440: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13441: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13442: @cindex Invalid name argument, @code{TO}
13443: @code{-32 throw} (Invalid name argument)
13444:
13445: @end table
13446:
13447:
13448: @c =====================================================================
13449: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13450: @section The optional Memory-Allocation word set
13451: @c =====================================================================
13452: @cindex system documentation, memory-allocation words
13453: @cindex memory-allocation words, system documentation
13454:
13455: @menu
13456: * memory-idef:: Implementation Defined Options
13457: @end menu
13458:
13459:
13460: @c ---------------------------------------------------------------------
13461: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13462: @subsection Implementation Defined Options
13463: @c ---------------------------------------------------------------------
13464: @cindex implementation-defined options, memory-allocation words
13465: @cindex memory-allocation words, implementation-defined options
13466:
13467: @table @i
1.29 crook 13468: @item values and meaning of @i{ior}:
13469: @cindex @i{ior} values and meaning
13470: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13471: intended as throw codes. They typically are in the range
13472: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13473: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13474:
13475: @end table
13476:
13477: @c =====================================================================
13478: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13479: @section The optional Programming-Tools word set
13480: @c =====================================================================
13481: @cindex system documentation, programming-tools words
13482: @cindex programming-tools words, system documentation
13483:
13484: @menu
13485: * programming-idef:: Implementation Defined Options
13486: * programming-ambcond:: Ambiguous Conditions
13487: @end menu
13488:
13489:
13490: @c ---------------------------------------------------------------------
13491: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13492: @subsection Implementation Defined Options
13493: @c ---------------------------------------------------------------------
13494: @cindex implementation-defined options, programming-tools words
13495: @cindex programming-tools words, implementation-defined options
13496:
13497: @table @i
13498: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13499: @cindex @code{;CODE} ending sequence
13500: @cindex @code{CODE} ending sequence
13501: @code{END-CODE}
13502:
13503: @item manner of processing input following @code{;CODE} and @code{CODE}:
13504: @cindex @code{;CODE}, processing input
13505: @cindex @code{CODE}, processing input
13506: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13507: the input is processed by the text interpreter, (starting) in interpret
13508: state.
13509:
13510: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13511: @cindex @code{ASSEMBLER}, search order capability
13512: The ANS Forth search order word set.
13513:
13514: @item source and format of display by @code{SEE}:
13515: @cindex @code{SEE}, source and format of output
1.80 anton 13516: The source for @code{see} is the executable code used by the inner
1.1 anton 13517: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13518: (and on some platforms, assembly code for primitives) as well as
13519: possible.
1.1 anton 13520:
13521: @end table
13522:
13523: @c ---------------------------------------------------------------------
13524: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13525: @subsection Ambiguous conditions
13526: @c ---------------------------------------------------------------------
13527: @cindex programming-tools words, ambiguous conditions
13528: @cindex ambiguous conditions, programming-tools words
13529:
13530: @table @i
13531:
1.21 crook 13532: @item deleting the compilation word list (@code{FORGET}):
13533: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13534: Not implemented (yet).
13535:
1.29 crook 13536: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13537: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13538: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13539: @cindex control-flow stack underflow
13540: This typically results in an @code{abort"} with a descriptive error
13541: message (may change into a @code{-22 throw} (Control structure mismatch)
13542: in the future). You may also get a memory access error. If you are
13543: unlucky, this ambiguous condition is not caught.
13544:
1.29 crook 13545: @item @i{name} can't be found (@code{FORGET}):
13546: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13547: Not implemented (yet).
13548:
1.29 crook 13549: @item @i{name} not defined via @code{CREATE}:
13550: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13551: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13552: the execution semantics of the last defined word no matter how it was
13553: defined.
13554:
13555: @item @code{POSTPONE} applied to @code{[IF]}:
13556: @cindex @code{POSTPONE} applied to @code{[IF]}
13557: @cindex @code{[IF]} and @code{POSTPONE}
13558: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13559: equivalent to @code{[IF]}.
13560:
13561: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13562: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13563: Continue in the same state of conditional compilation in the next outer
13564: input source. Currently there is no warning to the user about this.
13565:
13566: @item removing a needed definition (@code{FORGET}):
13567: @cindex @code{FORGET}, removing a needed definition
13568: Not implemented (yet).
13569:
13570: @end table
13571:
13572:
13573: @c =====================================================================
13574: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13575: @section The optional Search-Order word set
13576: @c =====================================================================
13577: @cindex system documentation, search-order words
13578: @cindex search-order words, system documentation
13579:
13580: @menu
13581: * search-idef:: Implementation Defined Options
13582: * search-ambcond:: Ambiguous Conditions
13583: @end menu
13584:
13585:
13586: @c ---------------------------------------------------------------------
13587: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13588: @subsection Implementation Defined Options
13589: @c ---------------------------------------------------------------------
13590: @cindex implementation-defined options, search-order words
13591: @cindex search-order words, implementation-defined options
13592:
13593: @table @i
13594: @item maximum number of word lists in search order:
13595: @cindex maximum number of word lists in search order
13596: @cindex search order, maximum depth
13597: @code{s" wordlists" environment? drop .}. Currently 16.
13598:
13599: @item minimum search order:
13600: @cindex minimum search order
13601: @cindex search order, minimum
13602: @code{root root}.
13603:
13604: @end table
13605:
13606: @c ---------------------------------------------------------------------
13607: @node search-ambcond, , search-idef, The optional Search-Order word set
13608: @subsection Ambiguous conditions
13609: @c ---------------------------------------------------------------------
13610: @cindex search-order words, ambiguous conditions
13611: @cindex ambiguous conditions, search-order words
13612:
13613: @table @i
1.21 crook 13614: @item changing the compilation word list (during compilation):
13615: @cindex changing the compilation word list (during compilation)
13616: @cindex compilation word list, change before definition ends
13617: The word is entered into the word list that was the compilation word list
1.1 anton 13618: at the start of the definition. Any changes to the name field (e.g.,
13619: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13620: are applied to the latest defined word (as reported by @code{latest} or
13621: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13622:
13623: @item search order empty (@code{previous}):
13624: @cindex @code{previous}, search order empty
1.26 crook 13625: @cindex vocstack empty, @code{previous}
1.1 anton 13626: @code{abort" Vocstack empty"}.
13627:
13628: @item too many word lists in search order (@code{also}):
13629: @cindex @code{also}, too many word lists in search order
1.26 crook 13630: @cindex vocstack full, @code{also}
1.1 anton 13631: @code{abort" Vocstack full"}.
13632:
13633: @end table
13634:
13635: @c ***************************************************************
1.65 anton 13636: @node Standard vs Extensions, Model, ANS conformance, Top
13637: @chapter Should I use Gforth extensions?
13638: @cindex Gforth extensions
13639:
13640: As you read through the rest of this manual, you will see documentation
13641: for @i{Standard} words, and documentation for some appealing Gforth
13642: @i{extensions}. You might ask yourself the question: @i{``Should I
13643: restrict myself to the standard, or should I use the extensions?''}
13644:
13645: The answer depends on the goals you have for the program you are working
13646: on:
13647:
13648: @itemize @bullet
13649:
13650: @item Is it just for yourself or do you want to share it with others?
13651:
13652: @item
13653: If you want to share it, do the others all use Gforth?
13654:
13655: @item
13656: If it is just for yourself, do you want to restrict yourself to Gforth?
13657:
13658: @end itemize
13659:
13660: If restricting the program to Gforth is ok, then there is no reason not
13661: to use extensions. It is still a good idea to keep to the standard
13662: where it is easy, in case you want to reuse these parts in another
13663: program that you want to be portable.
13664:
13665: If you want to be able to port the program to other Forth systems, there
13666: are the following points to consider:
13667:
13668: @itemize @bullet
13669:
13670: @item
13671: Most Forth systems that are being maintained support the ANS Forth
13672: standard. So if your program complies with the standard, it will be
13673: portable among many systems.
13674:
13675: @item
13676: A number of the Gforth extensions can be implemented in ANS Forth using
13677: public-domain files provided in the @file{compat/} directory. These are
13678: mentioned in the text in passing. There is no reason not to use these
13679: extensions, your program will still be ANS Forth compliant; just include
13680: the appropriate compat files with your program.
13681:
13682: @item
13683: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13684: analyse your program and determine what non-Standard words it relies
13685: upon. However, it does not check whether you use standard words in a
13686: non-standard way.
13687:
13688: @item
13689: Some techniques are not standardized by ANS Forth, and are hard or
13690: impossible to implement in a standard way, but can be implemented in
13691: most Forth systems easily, and usually in similar ways (e.g., accessing
13692: word headers). Forth has a rich historical precedent for programmers
13693: taking advantage of implementation-dependent features of their tools
13694: (for example, relying on a knowledge of the dictionary
13695: structure). Sometimes these techniques are necessary to extract every
13696: last bit of performance from the hardware, sometimes they are just a
13697: programming shorthand.
13698:
13699: @item
13700: Does using a Gforth extension save more work than the porting this part
13701: to other Forth systems (if any) will cost?
13702:
13703: @item
13704: Is the additional functionality worth the reduction in portability and
13705: the additional porting problems?
13706:
13707: @end itemize
13708:
13709: In order to perform these consideratios, you need to know what's
13710: standard and what's not. This manual generally states if something is
1.81 anton 13711: non-standard, but the authoritative source is the
13712: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13713: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13714: into the thought processes of the technical committee.
13715:
13716: Note also that portability between Forth systems is not the only
13717: portability issue; there is also the issue of portability between
13718: different platforms (processor/OS combinations).
13719:
13720: @c ***************************************************************
13721: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13722: @chapter Model
13723:
13724: This chapter has yet to be written. It will contain information, on
13725: which internal structures you can rely.
13726:
13727: @c ***************************************************************
13728: @node Integrating Gforth, Emacs and Gforth, Model, Top
13729: @chapter Integrating Gforth into C programs
13730:
13731: This is not yet implemented.
13732:
13733: Several people like to use Forth as scripting language for applications
13734: that are otherwise written in C, C++, or some other language.
13735:
13736: The Forth system ATLAST provides facilities for embedding it into
13737: applications; unfortunately it has several disadvantages: most
13738: importantly, it is not based on ANS Forth, and it is apparently dead
13739: (i.e., not developed further and not supported). The facilities
1.21 crook 13740: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13741: making the switch should not be hard.
13742:
13743: We also tried to design the interface such that it can easily be
13744: implemented by other Forth systems, so that we may one day arrive at a
13745: standardized interface. Such a standard interface would allow you to
13746: replace the Forth system without having to rewrite C code.
13747:
13748: You embed the Gforth interpreter by linking with the library
13749: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13750: global symbols in this library that belong to the interface, have the
13751: prefix @code{forth_}. (Global symbols that are used internally have the
13752: prefix @code{gforth_}).
13753:
13754: You can include the declarations of Forth types and the functions and
13755: variables of the interface with @code{#include <forth.h>}.
13756:
13757: Types.
13758:
13759: Variables.
13760:
13761: Data and FP Stack pointer. Area sizes.
13762:
13763: functions.
13764:
13765: forth_init(imagefile)
13766: forth_evaluate(string) exceptions?
13767: forth_goto(address) (or forth_execute(xt)?)
13768: forth_continue() (a corountining mechanism)
13769:
13770: Adding primitives.
13771:
13772: No checking.
13773:
13774: Signals?
13775:
13776: Accessing the Stacks
13777:
1.26 crook 13778: @c ******************************************************************
1.1 anton 13779: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13780: @chapter Emacs and Gforth
13781: @cindex Emacs and Gforth
13782:
13783: @cindex @file{gforth.el}
13784: @cindex @file{forth.el}
13785: @cindex Rydqvist, Goran
1.107 dvdkhlng 13786: @cindex Kuehling, David
1.1 anton 13787: @cindex comment editing commands
13788: @cindex @code{\}, editing with Emacs
13789: @cindex debug tracer editing commands
13790: @cindex @code{~~}, removal with Emacs
13791: @cindex Forth mode in Emacs
1.107 dvdkhlng 13792:
1.1 anton 13793: Gforth comes with @file{gforth.el}, an improved version of
13794: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13795: improvements are:
13796:
13797: @itemize @bullet
13798: @item
1.107 dvdkhlng 13799: A better handling of indentation.
13800: @item
13801: A custom hilighting engine for Forth-code.
1.26 crook 13802: @item
13803: Comment paragraph filling (@kbd{M-q})
13804: @item
13805: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13806: @item
13807: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13808: @item
13809: Support of the @code{info-lookup} feature for looking up the
13810: documentation of a word.
1.107 dvdkhlng 13811: @item
13812: Support for reading and writing blocks files.
1.26 crook 13813: @end itemize
13814:
1.107 dvdkhlng 13815: To get a basic description of these features, enter Forth mode and
13816: type @kbd{C-h m}.
1.1 anton 13817:
13818: @cindex source location of error or debugging output in Emacs
13819: @cindex error output, finding the source location in Emacs
13820: @cindex debugging output, finding the source location in Emacs
13821: In addition, Gforth supports Emacs quite well: The source code locations
13822: given in error messages, debugging output (from @code{~~}) and failed
13823: assertion messages are in the right format for Emacs' compilation mode
13824: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13825: Manual}) so the source location corresponding to an error or other
13826: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13827: @kbd{C-c C-c} for the error under the cursor).
13828:
1.107 dvdkhlng 13829: @cindex viewing the documentation of a word in Emacs
13830: @cindex context-sensitive help
13831: Moreover, for words documented in this manual, you can look up the
13832: glossary entry quickly by using @kbd{C-h TAB}
13833: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13834: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13835: later and does not work for words containing @code{:}.
13836:
13837: @menu
13838: * Installing gforth.el:: Making Emacs aware of Forth.
13839: * Emacs Tags:: Viewing the source of a word in Emacs.
13840: * Hilighting:: Making Forth code look prettier.
13841: * Auto-Indentation:: Customizing auto-indentation.
13842: * Blocks Files:: Reading and writing blocks files.
13843: @end menu
13844:
13845: @c ----------------------------------
1.109 anton 13846: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13847: @section Installing gforth.el
13848: @cindex @file{.emacs}
13849: @cindex @file{gforth.el}, installation
13850: To make the features from @file{gforth.el} available in Emacs, add
13851: the following lines to your @file{.emacs} file:
13852:
13853: @example
13854: (autoload 'forth-mode "gforth.el")
13855: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13856: auto-mode-alist))
13857: (autoload 'forth-block-mode "gforth.el")
13858: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13859: auto-mode-alist))
13860: (add-hook 'forth-mode-hook (function (lambda ()
13861: ;; customize variables here:
13862: (setq forth-indent-level 4)
13863: (setq forth-minor-indent-level 2)
13864: (setq forth-hilight-level 3)
13865: ;;; ...
13866: )))
13867: @end example
13868:
13869: @c ----------------------------------
13870: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13871: @section Emacs Tags
1.1 anton 13872: @cindex @file{TAGS} file
13873: @cindex @file{etags.fs}
13874: @cindex viewing the source of a word in Emacs
1.43 anton 13875: @cindex @code{require}, placement in files
13876: @cindex @code{include}, placement in files
1.107 dvdkhlng 13877: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13878: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13879: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13880: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13881: several tags files at the same time (e.g., one for the Gforth sources
13882: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13883: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13884: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13885: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13886: with @file{etags.fs}, you should avoid putting definitions both before
13887: and after @code{require} etc., otherwise you will see the same file
13888: visited several times by commands like @code{tags-search}.
1.1 anton 13889:
1.107 dvdkhlng 13890: @c ----------------------------------
13891: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13892: @section Hilighting
13893: @cindex hilighting Forth code in Emacs
13894: @cindex highlighting Forth code in Emacs
13895: @file{gforth.el} comes with a custom source hilighting engine. When
13896: you open a file in @code{forth-mode}, it will be completely parsed,
13897: assigning faces to keywords, comments, strings etc. While you edit
13898: the file, modified regions get parsed and updated on-the-fly.
13899:
13900: Use the variable `forth-hilight-level' to change the level of
13901: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13902: you set the hilighting level to 0, the parser will still work in the
13903: background, collecting information about whether regions of text are
13904: ``compiled'' or ``interpreted''. Those information are required for
13905: auto-indentation to work properly. Set `forth-disable-parser' to
13906: non-nil if your computer is too slow to handle parsing. This will
13907: have an impact on the smartness of the auto-indentation engine,
13908: though.
13909:
13910: Sometimes Forth sources define new features that should be hilighted,
13911: new control structures, defining-words etc. You can use the variable
13912: `forth-custom-words' to make @code{forth-mode} hilight additional
13913: words and constructs. See the docstring of `forth-words' for details
13914: (in Emacs, type @kbd{C-h v forth-words}).
13915:
13916: `forth-custom-words' is meant to be customized in your
13917: @file{.emacs} file. To customize hilighing in a file-specific manner,
13918: set `forth-local-words' in a local-variables section at the end of
13919: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13920:
13921: Example:
13922: @example
13923: 0 [IF]
13924: Local Variables:
13925: forth-local-words:
13926: ((("t:") definition-starter (font-lock-keyword-face . 1)
13927: "[ \t\n]" t name (font-lock-function-name-face . 3))
13928: ((";t") definition-ender (font-lock-keyword-face . 1)))
13929: End:
13930: [THEN]
13931: @end example
13932:
13933: @c ----------------------------------
13934: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13935: @section Auto-Indentation
13936: @cindex auto-indentation of Forth code in Emacs
13937: @cindex indentation of Forth code in Emacs
13938: @code{forth-mode} automatically tries to indent lines in a smart way,
13939: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13940:
13941: Simple customization can be achieved by setting
13942: `forth-indent-level' and `forth-minor-indent-level' in your
13943: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13944: per default by multiples of 4 columns. To use the more traditional
13945: 3-column indentation, add the following lines to your @file{.emacs}:
13946:
13947: @example
13948: (add-hook 'forth-mode-hook (function (lambda ()
13949: ;; customize variables here:
13950: (setq forth-indent-level 3)
13951: (setq forth-minor-indent-level 1)
13952: )))
13953: @end example
13954:
13955: If you want indentation to recognize non-default words, customize it
13956: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
13957: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13958: v forth-indent-words}).
13959:
13960: To customize indentation in a file-specific manner, set
13961: `forth-local-indent-words' in a local-variables section at the end of
13962: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13963: Emacs Manual}).
13964:
13965: Example:
13966: @example
13967: 0 [IF]
13968: Local Variables:
13969: forth-local-indent-words:
13970: ((("t:") (0 . 2) (0 . 2))
13971: ((";t") (-2 . 0) (0 . -2)))
13972: End:
13973: [THEN]
13974: @end example
13975:
13976: @c ----------------------------------
1.109 anton 13977: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 13978: @section Blocks Files
13979: @cindex blocks files, use with Emacs
13980: @code{forth-mode} Autodetects blocks files by checking whether the
13981: length of the first line exceeds 1023 characters. It then tries to
13982: convert the file into normal text format. When you save the file, it
13983: will be written to disk as normal stream-source file.
13984:
13985: If you want to write blocks files, use @code{forth-blocks-mode}. It
13986: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 13987:
1.107 dvdkhlng 13988: @itemize @bullet
13989: @item
13990: Files are written to disk in blocks file format.
13991: @item
13992: Screen numbers are displayed in the mode line (enumerated beginning
13993: with the value of `forth-block-base')
13994: @item
13995: Warnings are displayed when lines exceed 64 characters.
13996: @item
13997: The beginning of the currently edited block is marked with an
13998: overlay-arrow.
13999: @end itemize
1.41 anton 14000:
1.107 dvdkhlng 14001: There are some restrictions you should be aware of. When you open a
14002: blocks file that contains tabulator or newline characters, these
14003: characters will be translated into spaces when the file is written
14004: back to disk. If tabs or newlines are encountered during blocks file
14005: reading, an error is output to the echo area. So have a look at the
14006: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14007:
1.107 dvdkhlng 14008: Please consult the docstring of @code{forth-blocks-mode} for more
14009: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14010:
1.26 crook 14011: @c ******************************************************************
1.1 anton 14012: @node Image Files, Engine, Emacs and Gforth, Top
14013: @chapter Image Files
1.26 crook 14014: @cindex image file
14015: @cindex @file{.fi} files
1.1 anton 14016: @cindex precompiled Forth code
14017: @cindex dictionary in persistent form
14018: @cindex persistent form of dictionary
14019:
14020: An image file is a file containing an image of the Forth dictionary,
14021: i.e., compiled Forth code and data residing in the dictionary. By
14022: convention, we use the extension @code{.fi} for image files.
14023:
14024: @menu
1.18 anton 14025: * Image Licensing Issues:: Distribution terms for images.
14026: * Image File Background:: Why have image files?
1.67 anton 14027: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14028: * Data-Relocatable Image Files:: are better.
1.67 anton 14029: * Fully Relocatable Image Files:: better yet.
1.18 anton 14030: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14031: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14032: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14033: @end menu
14034:
1.18 anton 14035: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14036: @section Image Licensing Issues
14037: @cindex license for images
14038: @cindex image license
14039:
14040: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14041: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14042: original image; i.e., according to copyright law it is a derived work of
14043: the original image.
14044:
14045: Since Gforth is distributed under the GNU GPL, the newly created image
14046: falls under the GNU GPL, too. In particular, this means that if you
14047: distribute the image, you have to make all of the sources for the image
1.113 anton 14048: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14049: GNU General Public License (Section 3)}.
14050:
14051: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14052: contains only code compiled from the sources you gave it; if none of
14053: these sources is under the GPL, the terms discussed above do not apply
14054: to the image. However, if your image needs an engine (a gforth binary)
14055: that is under the GPL, you should make sure that you distribute both in
14056: a way that is at most a @emph{mere aggregation}, if you don't want the
14057: terms of the GPL to apply to the image.
14058:
14059: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14060: @section Image File Background
14061: @cindex image file background
14062:
1.80 anton 14063: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14064: definitions written in Forth. Since the Forth compiler itself belongs to
14065: those definitions, it is not possible to start the system with the
1.80 anton 14066: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14067: code as an image file in nearly executable form. When Gforth starts up,
14068: a C routine loads the image file into memory, optionally relocates the
14069: addresses, then sets up the memory (stacks etc.) according to
14070: information in the image file, and (finally) starts executing Forth
14071: code.
1.1 anton 14072:
14073: The image file variants represent different compromises between the
14074: goals of making it easy to generate image files and making them
14075: portable.
14076:
14077: @cindex relocation at run-time
1.26 crook 14078: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14079: run-time. This avoids many of the complications discussed below (image
14080: files are data relocatable without further ado), but costs performance
14081: (one addition per memory access).
14082:
14083: @cindex relocation at load-time
1.26 crook 14084: By contrast, the Gforth loader performs relocation at image load time. The
14085: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14086: appropriate code-field addresses (or code addresses in the case of
14087: direct threading).
14088:
14089: There are three kinds of image files, with different degrees of
14090: relocatability: non-relocatable, data-relocatable, and fully relocatable
14091: image files.
14092:
14093: @cindex image file loader
14094: @cindex relocating loader
14095: @cindex loader for image files
14096: These image file variants have several restrictions in common; they are
14097: caused by the design of the image file loader:
14098:
14099: @itemize @bullet
14100: @item
14101: There is only one segment; in particular, this means, that an image file
14102: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14103: them). The contents of the stacks are not represented, either.
1.1 anton 14104:
14105: @item
14106: The only kinds of relocation supported are: adding the same offset to
14107: all cells that represent data addresses; and replacing special tokens
14108: with code addresses or with pieces of machine code.
14109:
14110: If any complex computations involving addresses are performed, the
14111: results cannot be represented in the image file. Several applications that
14112: use such computations come to mind:
14113: @itemize @minus
14114: @item
14115: Hashing addresses (or data structures which contain addresses) for table
14116: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14117: purpose, you will have no problem, because the hash tables are
14118: recomputed automatically when the system is started. If you use your own
14119: hash tables, you will have to do something similar.
14120:
14121: @item
14122: There's a cute implementation of doubly-linked lists that uses
14123: @code{XOR}ed addresses. You could represent such lists as singly-linked
14124: in the image file, and restore the doubly-linked representation on
14125: startup.@footnote{In my opinion, though, you should think thrice before
14126: using a doubly-linked list (whatever implementation).}
14127:
14128: @item
14129: The code addresses of run-time routines like @code{docol:} cannot be
14130: represented in the image file (because their tokens would be replaced by
14131: machine code in direct threaded implementations). As a workaround,
14132: compute these addresses at run-time with @code{>code-address} from the
14133: executions tokens of appropriate words (see the definitions of
1.80 anton 14134: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14135:
14136: @item
14137: On many architectures addresses are represented in machine code in some
14138: shifted or mangled form. You cannot put @code{CODE} words that contain
14139: absolute addresses in this form in a relocatable image file. Workarounds
14140: are representing the address in some relative form (e.g., relative to
14141: the CFA, which is present in some register), or loading the address from
14142: a place where it is stored in a non-mangled form.
14143: @end itemize
14144: @end itemize
14145:
14146: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14147: @section Non-Relocatable Image Files
14148: @cindex non-relocatable image files
1.26 crook 14149: @cindex image file, non-relocatable
1.1 anton 14150:
14151: These files are simple memory dumps of the dictionary. They are specific
14152: to the executable (i.e., @file{gforth} file) they were created
14153: with. What's worse, they are specific to the place on which the
14154: dictionary resided when the image was created. Now, there is no
14155: guarantee that the dictionary will reside at the same place the next
14156: time you start Gforth, so there's no guarantee that a non-relocatable
14157: image will work the next time (Gforth will complain instead of crashing,
14158: though).
14159:
14160: You can create a non-relocatable image file with
14161:
1.44 crook 14162:
1.1 anton 14163: doc-savesystem
14164:
1.44 crook 14165:
1.1 anton 14166: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14167: @section Data-Relocatable Image Files
14168: @cindex data-relocatable image files
1.26 crook 14169: @cindex image file, data-relocatable
1.1 anton 14170:
14171: These files contain relocatable data addresses, but fixed code addresses
14172: (instead of tokens). They are specific to the executable (i.e.,
14173: @file{gforth} file) they were created with. For direct threading on some
14174: architectures (e.g., the i386), data-relocatable images do not work. You
14175: get a data-relocatable image, if you use @file{gforthmi} with a
14176: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14177: Relocatable Image Files}).
14178:
14179: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14180: @section Fully Relocatable Image Files
14181: @cindex fully relocatable image files
1.26 crook 14182: @cindex image file, fully relocatable
1.1 anton 14183:
14184: @cindex @file{kern*.fi}, relocatability
14185: @cindex @file{gforth.fi}, relocatability
14186: These image files have relocatable data addresses, and tokens for code
14187: addresses. They can be used with different binaries (e.g., with and
14188: without debugging) on the same machine, and even across machines with
14189: the same data formats (byte order, cell size, floating point
14190: format). However, they are usually specific to the version of Gforth
14191: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14192: are fully relocatable.
14193:
14194: There are two ways to create a fully relocatable image file:
14195:
14196: @menu
1.29 crook 14197: * gforthmi:: The normal way
1.1 anton 14198: * cross.fs:: The hard way
14199: @end menu
14200:
14201: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14202: @subsection @file{gforthmi}
14203: @cindex @file{comp-i.fs}
14204: @cindex @file{gforthmi}
14205:
14206: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14207: image @i{file} that contains everything you would load by invoking
14208: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14209: @example
1.29 crook 14210: gforthmi @i{file} @i{options}
1.1 anton 14211: @end example
14212:
14213: E.g., if you want to create an image @file{asm.fi} that has the file
14214: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14215: like this:
14216:
14217: @example
14218: gforthmi asm.fi asm.fs
14219: @end example
14220:
1.27 crook 14221: @file{gforthmi} is implemented as a sh script and works like this: It
14222: produces two non-relocatable images for different addresses and then
14223: compares them. Its output reflects this: first you see the output (if
1.62 crook 14224: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14225: files, then you see the output of the comparing program: It displays the
14226: offset used for data addresses and the offset used for code addresses;
1.1 anton 14227: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14228: image files, it displays a line like this:
1.1 anton 14229:
14230: @example
14231: 78DC BFFFFA50 BFFFFA40
14232: @end example
14233:
14234: This means that at offset $78dc from @code{forthstart}, one input image
14235: contains $bffffa50, and the other contains $bffffa40. Since these cells
14236: cannot be represented correctly in the output image, you should examine
14237: these places in the dictionary and verify that these cells are dead
14238: (i.e., not read before they are written).
1.39 anton 14239:
14240: @cindex --application, @code{gforthmi} option
14241: If you insert the option @code{--application} in front of the image file
14242: name, you will get an image that uses the @code{--appl-image} option
14243: instead of the @code{--image-file} option (@pxref{Invoking
14244: Gforth}). When you execute such an image on Unix (by typing the image
14245: name as command), the Gforth engine will pass all options to the image
14246: instead of trying to interpret them as engine options.
1.1 anton 14247:
1.27 crook 14248: If you type @file{gforthmi} with no arguments, it prints some usage
14249: instructions.
14250:
1.1 anton 14251: @cindex @code{savesystem} during @file{gforthmi}
14252: @cindex @code{bye} during @file{gforthmi}
14253: @cindex doubly indirect threaded code
1.44 crook 14254: @cindex environment variables
14255: @cindex @code{GFORTHD} -- environment variable
14256: @cindex @code{GFORTH} -- environment variable
1.1 anton 14257: @cindex @code{gforth-ditc}
1.29 crook 14258: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14259: words @code{savesystem} and @code{bye} must be visible. A special doubly
14260: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14261: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14262: this executable through the environment variable @code{GFORTHD}
14263: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14264: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14265: data-relocatable image (because there is no code address offset). The
14266: normal @file{gforth} executable is used for creating the relocatable
14267: image; you can pass the exact filename of this executable through the
14268: environment variable @code{GFORTH}.
1.1 anton 14269:
14270: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14271: @subsection @file{cross.fs}
14272: @cindex @file{cross.fs}
14273: @cindex cross-compiler
14274: @cindex metacompiler
1.47 crook 14275: @cindex target compiler
1.1 anton 14276:
14277: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14278: programming language (@pxref{Cross Compiler}).
1.1 anton 14279:
1.47 crook 14280: @code{cross} allows you to create image files for machines with
1.1 anton 14281: different data sizes and data formats than the one used for generating
14282: the image file. You can also use it to create an application image that
14283: does not contain a Forth compiler. These features are bought with
14284: restrictions and inconveniences in programming. E.g., addresses have to
14285: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14286: order to make the code relocatable.
14287:
14288:
14289: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14290: @section Stack and Dictionary Sizes
14291: @cindex image file, stack and dictionary sizes
14292: @cindex dictionary size default
14293: @cindex stack size default
14294:
14295: If you invoke Gforth with a command line flag for the size
14296: (@pxref{Invoking Gforth}), the size you specify is stored in the
14297: dictionary. If you save the dictionary with @code{savesystem} or create
14298: an image with @file{gforthmi}, this size will become the default
14299: for the resulting image file. E.g., the following will create a
1.21 crook 14300: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14301:
14302: @example
14303: gforthmi gforth.fi -m 1M
14304: @end example
14305:
14306: In other words, if you want to set the default size for the dictionary
14307: and the stacks of an image, just invoke @file{gforthmi} with the
14308: appropriate options when creating the image.
14309:
14310: @cindex stack size, cache-friendly
14311: Note: For cache-friendly behaviour (i.e., good performance), you should
14312: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14313: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14314: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14315:
14316: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14317: @section Running Image Files
14318: @cindex running image files
14319: @cindex invoking image files
14320: @cindex image file invocation
14321:
14322: @cindex -i, invoke image file
14323: @cindex --image file, invoke image file
1.29 crook 14324: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14325: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14326: @example
1.29 crook 14327: gforth -i @i{image}
1.1 anton 14328: @end example
14329:
14330: @cindex executable image file
1.26 crook 14331: @cindex image file, executable
1.1 anton 14332: If your operating system supports starting scripts with a line of the
14333: form @code{#! ...}, you just have to type the image file name to start
14334: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14335: just a convention). I.e., to run Gforth with the image file @i{image},
14336: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14337: This works because every @code{.fi} file starts with a line of this
14338: format:
14339:
14340: @example
14341: #! /usr/local/bin/gforth-0.4.0 -i
14342: @end example
14343:
14344: The file and pathname for the Gforth engine specified on this line is
14345: the specific Gforth executable that it was built against; i.e. the value
14346: of the environment variable @code{GFORTH} at the time that
14347: @file{gforthmi} was executed.
1.1 anton 14348:
1.27 crook 14349: You can make use of the same shell capability to make a Forth source
14350: file into an executable. For example, if you place this text in a file:
1.26 crook 14351:
14352: @example
14353: #! /usr/local/bin/gforth
14354:
14355: ." Hello, world" CR
14356: bye
14357: @end example
14358:
14359: @noindent
1.27 crook 14360: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14361: directly from the command line. The sequence @code{#!} is used in two
14362: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14363: system@footnote{The Unix kernel actually recognises two types of files:
14364: executable files and files of data, where the data is processed by an
14365: interpreter that is specified on the ``interpreter line'' -- the first
14366: line of the file, starting with the sequence #!. There may be a small
14367: limit (e.g., 32) on the number of characters that may be specified on
14368: the interpreter line.} secondly it is treated as a comment character by
14369: Gforth. Because of the second usage, a space is required between
1.80 anton 14370: @code{#!} and the path to the executable (moreover, some Unixes
14371: require the sequence @code{#! /}).
1.27 crook 14372:
14373: The disadvantage of this latter technique, compared with using
1.80 anton 14374: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14375: compiled on-the-fly, each time the program is invoked.
1.26 crook 14376:
1.1 anton 14377: doc-#!
14378:
1.44 crook 14379:
1.1 anton 14380: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14381: @section Modifying the Startup Sequence
14382: @cindex startup sequence for image file
14383: @cindex image file initialization sequence
14384: @cindex initialization sequence of image file
14385:
1.120 anton 14386: You can add your own initialization to the startup sequence of an image
14387: through the deferred word @code{'cold}. @code{'cold} is invoked just
14388: before the image-specific command line processing (i.e., loading files
14389: and evaluating (@code{-e}) strings) starts.
1.1 anton 14390:
14391: A sequence for adding your initialization usually looks like this:
14392:
14393: @example
14394: :noname
14395: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14396: ... \ your stuff
14397: ; IS 'cold
14398: @end example
14399:
14400: @cindex turnkey image files
1.26 crook 14401: @cindex image file, turnkey applications
1.1 anton 14402: You can make a turnkey image by letting @code{'cold} execute a word
14403: (your turnkey application) that never returns; instead, it exits Gforth
14404: via @code{bye} or @code{throw}.
14405:
1.121 anton 14406: You can access the (image-specific) command-line arguments through
14407: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14408: arguments}).
1.1 anton 14409:
1.26 crook 14410: If @code{'cold} exits normally, Gforth processes the command-line
14411: arguments as files to be loaded and strings to be evaluated. Therefore,
14412: @code{'cold} should remove the arguments it has used in this case.
14413:
14414: doc-'cold
1.44 crook 14415:
1.1 anton 14416: @c ******************************************************************
1.113 anton 14417: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14418: @chapter Engine
14419: @cindex engine
14420: @cindex virtual machine
14421:
1.26 crook 14422: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14423: may be helpful for finding your way in the Gforth sources.
14424:
1.109 anton 14425: The ideas in this section have also been published in the following
14426: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14427: Forth-Tagung '93; M. Anton Ertl,
14428: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14429: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14430: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14431: Threaded code variations and optimizations (extended version)}},
14432: Forth-Tagung '02.
1.1 anton 14433:
14434: @menu
14435: * Portability::
14436: * Threading::
14437: * Primitives::
14438: * Performance::
14439: @end menu
14440:
14441: @node Portability, Threading, Engine, Engine
14442: @section Portability
14443: @cindex engine portability
14444:
1.26 crook 14445: An important goal of the Gforth Project is availability across a wide
14446: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14447: achieved this goal by manually coding the engine in assembly language
14448: for several then-popular processors. This approach is very
14449: labor-intensive and the results are short-lived due to progress in
14450: computer architecture.
1.1 anton 14451:
14452: @cindex C, using C for the engine
14453: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14454: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14455: particularly popular for UNIX-based Forths due to the large variety of
14456: architectures of UNIX machines. Unfortunately an implementation in C
14457: does not mix well with the goals of efficiency and with using
14458: traditional techniques: Indirect or direct threading cannot be expressed
14459: in C, and switch threading, the fastest technique available in C, is
14460: significantly slower. Another problem with C is that it is very
14461: cumbersome to express double integer arithmetic.
14462:
14463: @cindex GNU C for the engine
14464: @cindex long long
14465: Fortunately, there is a portable language that does not have these
14466: limitations: GNU C, the version of C processed by the GNU C compiler
14467: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14468: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14469: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14470: threading possible, its @code{long long} type (@pxref{Long Long, ,
14471: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14472: double numbers on many systems. GNU C is freely available on all
1.1 anton 14473: important (and many unimportant) UNIX machines, VMS, 80386s running
14474: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14475: on all these machines.
14476:
14477: Writing in a portable language has the reputation of producing code that
14478: is slower than assembly. For our Forth engine we repeatedly looked at
14479: the code produced by the compiler and eliminated most compiler-induced
14480: inefficiencies by appropriate changes in the source code.
14481:
14482: @cindex explicit register declarations
14483: @cindex --enable-force-reg, configuration flag
14484: @cindex -DFORCE_REG
14485: However, register allocation cannot be portably influenced by the
14486: programmer, leading to some inefficiencies on register-starved
14487: machines. We use explicit register declarations (@pxref{Explicit Reg
14488: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14489: improve the speed on some machines. They are turned on by using the
14490: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14491: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14492: machine, but also on the compiler version: On some machines some
14493: compiler versions produce incorrect code when certain explicit register
14494: declarations are used. So by default @code{-DFORCE_REG} is not used.
14495:
14496: @node Threading, Primitives, Portability, Engine
14497: @section Threading
14498: @cindex inner interpreter implementation
14499: @cindex threaded code implementation
14500:
14501: @cindex labels as values
14502: GNU C's labels as values extension (available since @code{gcc-2.0},
14503: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14504: makes it possible to take the address of @i{label} by writing
14505: @code{&&@i{label}}. This address can then be used in a statement like
14506: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14507: @code{goto x}.
14508:
1.26 crook 14509: @cindex @code{NEXT}, indirect threaded
1.1 anton 14510: @cindex indirect threaded inner interpreter
14511: @cindex inner interpreter, indirect threaded
1.26 crook 14512: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14513: @example
14514: cfa = *ip++;
14515: ca = *cfa;
14516: goto *ca;
14517: @end example
14518: @cindex instruction pointer
14519: For those unfamiliar with the names: @code{ip} is the Forth instruction
14520: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14521: execution token and points to the code field of the next word to be
14522: executed; The @code{ca} (code address) fetched from there points to some
14523: executable code, e.g., a primitive or the colon definition handler
14524: @code{docol}.
14525:
1.26 crook 14526: @cindex @code{NEXT}, direct threaded
1.1 anton 14527: @cindex direct threaded inner interpreter
14528: @cindex inner interpreter, direct threaded
14529: Direct threading is even simpler:
14530: @example
14531: ca = *ip++;
14532: goto *ca;
14533: @end example
14534:
14535: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14536: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14537:
14538: @menu
14539: * Scheduling::
14540: * Direct or Indirect Threaded?::
1.109 anton 14541: * Dynamic Superinstructions::
1.1 anton 14542: * DOES>::
14543: @end menu
14544:
14545: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14546: @subsection Scheduling
14547: @cindex inner interpreter optimization
14548:
14549: There is a little complication: Pipelined and superscalar processors,
14550: i.e., RISC and some modern CISC machines can process independent
14551: instructions while waiting for the results of an instruction. The
14552: compiler usually reorders (schedules) the instructions in a way that
14553: achieves good usage of these delay slots. However, on our first tries
14554: the compiler did not do well on scheduling primitives. E.g., for
14555: @code{+} implemented as
14556: @example
14557: n=sp[0]+sp[1];
14558: sp++;
14559: sp[0]=n;
14560: NEXT;
14561: @end example
1.81 anton 14562: the @code{NEXT} comes strictly after the other code, i.e., there is
14563: nearly no scheduling. After a little thought the problem becomes clear:
14564: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14565: addresses (and the version of @code{gcc} we used would not know it even
14566: if it was possible), so it could not move the load of the cfa above the
14567: store to the TOS. Indeed the pointers could be the same, if code on or
14568: very near the top of stack were executed. In the interest of speed we
14569: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14570: in scheduling: @code{NEXT} is divided into several parts:
14571: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14572: like:
1.1 anton 14573: @example
1.81 anton 14574: NEXT_P0;
1.1 anton 14575: n=sp[0]+sp[1];
14576: sp++;
14577: NEXT_P1;
14578: sp[0]=n;
14579: NEXT_P2;
14580: @end example
14581:
1.81 anton 14582: There are various schemes that distribute the different operations of
14583: NEXT between these parts in several ways; in general, different schemes
14584: perform best on different processors. We use a scheme for most
14585: architectures that performs well for most processors of this
1.109 anton 14586: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14587: the scheme on installation time.
14588:
1.1 anton 14589:
1.109 anton 14590: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14591: @subsection Direct or Indirect Threaded?
14592: @cindex threading, direct or indirect?
14593:
1.109 anton 14594: Threaded forth code consists of references to primitives (simple machine
14595: code routines like @code{+}) and to non-primitives (e.g., colon
14596: definitions, variables, constants); for a specific class of
14597: non-primitives (e.g., variables) there is one code routine (e.g.,
14598: @code{dovar}), but each variable needs a separate reference to its data.
14599:
14600: Traditionally Forth has been implemented as indirect threaded code,
14601: because this allows to use only one cell to reference a non-primitive
14602: (basically you point to the data, and find the code address there).
14603:
14604: @cindex primitive-centric threaded code
14605: However, threaded code in Gforth (since 0.6.0) uses two cells for
14606: non-primitives, one for the code address, and one for the data address;
14607: the data pointer is an immediate argument for the virtual machine
14608: instruction represented by the code address. We call this
14609: @emph{primitive-centric} threaded code, because all code addresses point
14610: to simple primitives. E.g., for a variable, the code address is for
14611: @code{lit} (also used for integer literals like @code{99}).
14612:
14613: Primitive-centric threaded code allows us to use (faster) direct
14614: threading as dispatch method, completely portably (direct threaded code
14615: in Gforth before 0.6.0 required architecture-specific code). It also
14616: eliminates the performance problems related to I-cache consistency that
14617: 386 implementations have with direct threaded code, and allows
14618: additional optimizations.
14619:
14620: @cindex hybrid direct/indirect threaded code
14621: There is a catch, however: the @var{xt} parameter of @code{execute} can
14622: occupy only one cell, so how do we pass non-primitives with their code
14623: @emph{and} data addresses to them? Our answer is to use indirect
14624: threaded dispatch for @code{execute} and other words that use a
14625: single-cell xt. So, normal threaded code in colon definitions uses
14626: direct threading, and @code{execute} and similar words, which dispatch
14627: to xts on the data stack, use indirect threaded code. We call this
14628: @emph{hybrid direct/indirect} threaded code.
14629:
14630: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14631: @cindex gforth engine
14632: @cindex gforth-fast engine
14633: The engines @command{gforth} and @command{gforth-fast} use hybrid
14634: direct/indirect threaded code. This means that with these engines you
14635: cannot use @code{,} to compile an xt. Instead, you have to use
14636: @code{compile,}.
14637:
14638: @cindex gforth-itc engine
1.115 anton 14639: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14640: This engine uses plain old indirect threaded code. It still compiles in
14641: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14642: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14643: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14644: and execute @code{' , is compile,}. Your program can check if it is
14645: running on a hybrid direct/indirect threaded engine or a pure indirect
14646: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14647:
14648:
14649: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14650: @subsection Dynamic Superinstructions
14651: @cindex Dynamic superinstructions with replication
14652: @cindex Superinstructions
14653: @cindex Replication
14654:
14655: The engines @command{gforth} and @command{gforth-fast} use another
14656: optimization: Dynamic superinstructions with replication. As an
14657: example, consider the following colon definition:
14658:
14659: @example
14660: : squared ( n1 -- n2 )
14661: dup * ;
14662: @end example
14663:
14664: Gforth compiles this into the threaded code sequence
14665:
14666: @example
14667: dup
14668: *
14669: ;s
14670: @end example
14671:
14672: In normal direct threaded code there is a code address occupying one
14673: cell for each of these primitives. Each code address points to a
14674: machine code routine, and the interpreter jumps to this machine code in
14675: order to execute the primitive. The routines for these three
14676: primitives are (in @command{gforth-fast} on the 386):
14677:
14678: @example
14679: Code dup
14680: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14681: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14682: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14683: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14684: end-code
14685: Code *
14686: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14687: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14688: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14689: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14690: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14691: end-code
14692: Code ;s
14693: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14694: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14695: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14696: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14697: end-code
14698: @end example
14699:
14700: With dynamic superinstructions and replication the compiler does not
14701: just lay down the threaded code, but also copies the machine code
14702: fragments, usually without the jump at the end.
14703:
14704: @example
14705: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14706: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14707: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14708: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14709: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14710: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14711: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14712: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14713: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14714: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14715: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14716: @end example
14717:
14718: Only when a threaded-code control-flow change happens (e.g., in
14719: @code{;s}), the jump is appended. This optimization eliminates many of
14720: these jumps and makes the rest much more predictable. The speedup
14721: depends on the processor and the application; on the Athlon and Pentium
14722: III this optimization typically produces a speedup by a factor of 2.
14723:
14724: The code addresses in the direct-threaded code are set to point to the
14725: appropriate points in the copied machine code, in this example like
14726: this:
1.1 anton 14727:
1.109 anton 14728: @example
14729: primitive code address
14730: dup $4057D27D
14731: * $4057D286
14732: ;s $4057D292
14733: @end example
14734:
14735: Thus there can be threaded-code jumps to any place in this piece of
14736: code. This also simplifies decompilation quite a bit.
14737:
14738: @cindex --no-dynamic command-line option
14739: @cindex --no-super command-line option
14740: You can disable this optimization with @option{--no-dynamic}. You can
14741: use the copying without eliminating the jumps (i.e., dynamic
14742: replication, but without superinstructions) with @option{--no-super};
14743: this gives the branch prediction benefit alone; the effect on
1.110 anton 14744: performance depends on the CPU; on the Athlon and Pentium III the
14745: speedup is a little less than for dynamic superinstructions with
14746: replication.
14747:
14748: @cindex patching threaded code
14749: One use of these options is if you want to patch the threaded code.
14750: With superinstructions, many of the dispatch jumps are eliminated, so
14751: patching often has no effect. These options preserve all the dispatch
14752: jumps.
1.109 anton 14753:
14754: @cindex --dynamic command-line option
1.110 anton 14755: On some machines dynamic superinstructions are disabled by default,
14756: because it is unsafe on these machines. However, if you feel
14757: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14758:
14759: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14760: @subsection DOES>
14761: @cindex @code{DOES>} implementation
14762:
1.26 crook 14763: @cindex @code{dodoes} routine
14764: @cindex @code{DOES>}-code
1.1 anton 14765: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14766: the chunk of code executed by every word defined by a
1.109 anton 14767: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14768: this is only needed if the xt of the word is @code{execute}d. The main
14769: problem here is: How to find the Forth code to be executed, i.e. the
14770: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14771: solutions:
1.1 anton 14772:
1.21 crook 14773: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14774: @code{DOES>}-code address is stored in the cell after the code address
14775: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14776: illegal in the Forth-79 and all later standards, because in fig-Forth
14777: this address lies in the body (which is illegal in these
14778: standards). However, by making the code field larger for all words this
14779: solution becomes legal again. We use this approach. Leaving a cell
14780: unused in most words is a bit wasteful, but on the machines we are
14781: targeting this is hardly a problem.
14782:
1.1 anton 14783:
14784: @node Primitives, Performance, Threading, Engine
14785: @section Primitives
14786: @cindex primitives, implementation
14787: @cindex virtual machine instructions, implementation
14788:
14789: @menu
14790: * Automatic Generation::
14791: * TOS Optimization::
14792: * Produced code::
14793: @end menu
14794:
14795: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14796: @subsection Automatic Generation
14797: @cindex primitives, automatic generation
14798:
14799: @cindex @file{prims2x.fs}
1.109 anton 14800:
1.1 anton 14801: Since the primitives are implemented in a portable language, there is no
14802: longer any need to minimize the number of primitives. On the contrary,
14803: having many primitives has an advantage: speed. In order to reduce the
14804: number of errors in primitives and to make programming them easier, we
1.109 anton 14805: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14806: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14807: generates most (and sometimes all) of the C code for a primitive from
14808: the stack effect notation. The source for a primitive has the following
14809: form:
1.1 anton 14810:
14811: @cindex primitive source format
14812: @format
1.58 anton 14813: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14814: [@code{""}@i{glossary entry}@code{""}]
14815: @i{C code}
1.1 anton 14816: [@code{:}
1.29 crook 14817: @i{Forth code}]
1.1 anton 14818: @end format
14819:
14820: The items in brackets are optional. The category and glossary fields
14821: are there for generating the documentation, the Forth code is there
14822: for manual implementations on machines without GNU C. E.g., the source
14823: for the primitive @code{+} is:
14824: @example
1.58 anton 14825: + ( n1 n2 -- n ) core plus
1.1 anton 14826: n = n1+n2;
14827: @end example
14828:
14829: This looks like a specification, but in fact @code{n = n1+n2} is C
14830: code. Our primitive generation tool extracts a lot of information from
14831: the stack effect notations@footnote{We use a one-stack notation, even
14832: though we have separate data and floating-point stacks; The separate
14833: notation can be generated easily from the unified notation.}: The number
14834: of items popped from and pushed on the stack, their type, and by what
14835: name they are referred to in the C code. It then generates a C code
14836: prelude and postlude for each primitive. The final C code for @code{+}
14837: looks like this:
14838:
14839: @example
1.46 pazsan 14840: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14841: /* */ /* documentation */
1.81 anton 14842: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14843: @{
14844: DEF_CA /* definition of variable ca (indirect threading) */
14845: Cell n1; /* definitions of variables */
14846: Cell n2;
14847: Cell n;
1.81 anton 14848: NEXT_P0; /* NEXT part 0 */
1.1 anton 14849: n1 = (Cell) sp[1]; /* input */
14850: n2 = (Cell) TOS;
14851: sp += 1; /* stack adjustment */
14852: @{
14853: n = n1+n2; /* C code taken from the source */
14854: @}
14855: NEXT_P1; /* NEXT part 1 */
14856: TOS = (Cell)n; /* output */
14857: NEXT_P2; /* NEXT part 2 */
14858: @}
14859: @end example
14860:
14861: This looks long and inefficient, but the GNU C compiler optimizes quite
14862: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14863: HP RISC machines: Defining the @code{n}s does not produce any code, and
14864: using them as intermediate storage also adds no cost.
14865:
1.26 crook 14866: There are also other optimizations that are not illustrated by this
14867: example: assignments between simple variables are usually for free (copy
1.1 anton 14868: propagation). If one of the stack items is not used by the primitive
14869: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14870: (dead code elimination). On the other hand, there are some things that
14871: the compiler does not do, therefore they are performed by
14872: @file{prims2x.fs}: The compiler does not optimize code away that stores
14873: a stack item to the place where it just came from (e.g., @code{over}).
14874:
14875: While programming a primitive is usually easy, there are a few cases
14876: where the programmer has to take the actions of the generator into
14877: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14878: fall through to @code{NEXT}.
1.109 anton 14879:
14880: For more information
1.1 anton 14881:
14882: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14883: @subsection TOS Optimization
14884: @cindex TOS optimization for primitives
14885: @cindex primitives, keeping the TOS in a register
14886:
14887: An important optimization for stack machine emulators, e.g., Forth
14888: engines, is keeping one or more of the top stack items in
1.29 crook 14889: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14890: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14891: @itemize @bullet
14892: @item
1.29 crook 14893: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14894: due to fewer loads from and stores to the stack.
1.29 crook 14895: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14896: @i{y<n}, due to additional moves between registers.
1.1 anton 14897: @end itemize
14898:
14899: @cindex -DUSE_TOS
14900: @cindex -DUSE_NO_TOS
14901: In particular, keeping one item in a register is never a disadvantage,
14902: if there are enough registers. Keeping two items in registers is a
14903: disadvantage for frequent words like @code{?branch}, constants,
14904: variables, literals and @code{i}. Therefore our generator only produces
14905: code that keeps zero or one items in registers. The generated C code
14906: covers both cases; the selection between these alternatives is made at
14907: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14908: code for @code{+} is just a simple variable name in the one-item case,
14909: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14910: GNU C compiler tries to keep simple variables like @code{TOS} in
14911: registers, and it usually succeeds, if there are enough registers.
14912:
14913: @cindex -DUSE_FTOS
14914: @cindex -DUSE_NO_FTOS
14915: The primitive generator performs the TOS optimization for the
14916: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14917: operations the benefit of this optimization is even larger:
14918: floating-point operations take quite long on most processors, but can be
14919: performed in parallel with other operations as long as their results are
14920: not used. If the FP-TOS is kept in a register, this works. If
14921: it is kept on the stack, i.e., in memory, the store into memory has to
14922: wait for the result of the floating-point operation, lengthening the
14923: execution time of the primitive considerably.
14924:
14925: The TOS optimization makes the automatic generation of primitives a
14926: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14927: @code{TOS} is not sufficient. There are some special cases to
14928: consider:
14929: @itemize @bullet
14930: @item In the case of @code{dup ( w -- w w )} the generator must not
14931: eliminate the store to the original location of the item on the stack,
14932: if the TOS optimization is turned on.
14933: @item Primitives with stack effects of the form @code{--}
1.29 crook 14934: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14935: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14936: must load the TOS from the stack at the end. But for the null stack
14937: effect @code{--} no stores or loads should be generated.
14938: @end itemize
14939:
14940: @node Produced code, , TOS Optimization, Primitives
14941: @subsection Produced code
14942: @cindex primitives, assembly code listing
14943:
14944: @cindex @file{engine.s}
14945: To see what assembly code is produced for the primitives on your machine
14946: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 14947: look at the resulting file @file{engine.s}. Alternatively, you can also
14948: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 14949:
14950: @node Performance, , Primitives, Engine
14951: @section Performance
14952: @cindex performance of some Forth interpreters
14953: @cindex engine performance
14954: @cindex benchmarking Forth systems
14955: @cindex Gforth performance
14956:
14957: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 14958: impossible to write a significantly faster threaded-code engine.
1.1 anton 14959:
14960: On register-starved machines like the 386 architecture processors
14961: improvements are possible, because @code{gcc} does not utilize the
14962: registers as well as a human, even with explicit register declarations;
14963: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14964: and hand-tuned it for the 486; this system is 1.19 times faster on the
14965: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14966: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14967: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14968: registers fit in real registers (and we can even afford to use the TOS
14969: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 14970: earlier results. And dynamic superinstructions provide another speedup
14971: (but only around a factor 1.2 on the 486).
1.1 anton 14972:
14973: @cindex Win32Forth performance
14974: @cindex NT Forth performance
14975: @cindex eforth performance
14976: @cindex ThisForth performance
14977: @cindex PFE performance
14978: @cindex TILE performance
1.81 anton 14979: The potential advantage of assembly language implementations is not
1.112 anton 14980: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 14981: (direct threaded, compiled with @code{gcc-2.95.1} and
14982: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14983: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14984: (with and without peephole (aka pinhole) optimization of the threaded
14985: code); all these systems were written in assembly language. We also
14986: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14987: with @code{gcc-2.6.3} with the default configuration for Linux:
14988: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14989: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14990: employs peephole optimization of the threaded code) and TILE (compiled
14991: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14992: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14993: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14994: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14995: then extended it to run the benchmarks, added the peephole optimizer,
14996: ran the benchmarks and reported the results.
1.40 anton 14997:
1.1 anton 14998: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14999: matrix multiplication come from the Stanford integer benchmarks and have
15000: been translated into Forth by Martin Fraeman; we used the versions
15001: included in the TILE Forth package, but with bigger data set sizes; and
15002: a recursive Fibonacci number computation for benchmarking calling
15003: performance. The following table shows the time taken for the benchmarks
15004: scaled by the time taken by Gforth (in other words, it shows the speedup
15005: factor that Gforth achieved over the other systems).
15006:
15007: @example
1.112 anton 15008: relative Win32- NT eforth This-
15009: time Gforth Forth Forth eforth +opt PFE Forth TILE
15010: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15011: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15012: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15013: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15014: @end example
15015:
1.26 crook 15016: You may be quite surprised by the good performance of Gforth when
15017: compared with systems written in assembly language. One important reason
15018: for the disappointing performance of these other systems is probably
15019: that they are not written optimally for the 486 (e.g., they use the
15020: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15021: but costly method for relocating the Forth image: like @code{cforth}, it
15022: computes the actual addresses at run time, resulting in two address
15023: computations per @code{NEXT} (@pxref{Image File Background}).
15024:
1.1 anton 15025: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15026: explained with the self-imposed restriction of the latter systems to
15027: standard C, which makes efficient threading impossible (however, the
1.4 anton 15028: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15029: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15030: Moreover, current C compilers have a hard time optimizing other aspects
15031: of the ThisForth and the TILE source.
15032:
1.26 crook 15033: The performance of Gforth on 386 architecture processors varies widely
15034: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15035: allocate any of the virtual machine registers into real machine
15036: registers by itself and would not work correctly with explicit register
1.112 anton 15037: declarations, giving a significantly slower engine (on a 486DX2/66
15038: running the Sieve) than the one measured above.
1.1 anton 15039:
1.26 crook 15040: Note that there have been several releases of Win32Forth since the
15041: release presented here, so the results presented above may have little
1.40 anton 15042: predictive value for the performance of Win32Forth today (results for
15043: the current release on an i486DX2/66 are welcome).
1.1 anton 15044:
15045: @cindex @file{Benchres}
1.66 anton 15046: In
15047: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15048: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15049: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15050: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15051: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15052: than the version used here. You can find a newer version of these
15053: measurements at
1.47 crook 15054: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15055: find numbers for Gforth on various machines in @file{Benchres}.
15056:
1.26 crook 15057: @c ******************************************************************
1.113 anton 15058: @c @node Binding to System Library, Cross Compiler, Engine, Top
15059: @c @chapter Binding to System Library
1.13 pazsan 15060:
1.113 anton 15061: @c ****************************************************************
15062: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15063: @chapter Cross Compiler
1.47 crook 15064: @cindex @file{cross.fs}
15065: @cindex cross-compiler
15066: @cindex metacompiler
15067: @cindex target compiler
1.13 pazsan 15068:
1.46 pazsan 15069: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15070: mostly written in Forth, including crucial parts like the outer
15071: interpreter and compiler, it needs compiled Forth code to get
15072: started. The cross compiler allows to create new images for other
15073: architectures, even running under another Forth system.
1.13 pazsan 15074:
15075: @menu
1.67 anton 15076: * Using the Cross Compiler::
15077: * How the Cross Compiler Works::
1.13 pazsan 15078: @end menu
15079:
1.21 crook 15080: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15081: @section Using the Cross Compiler
1.46 pazsan 15082:
15083: The cross compiler uses a language that resembles Forth, but isn't. The
15084: main difference is that you can execute Forth code after definition,
15085: while you usually can't execute the code compiled by cross, because the
15086: code you are compiling is typically for a different computer than the
15087: one you are compiling on.
15088:
1.81 anton 15089: @c anton: This chapter is somewhat different from waht I would expect: I
15090: @c would expect an explanation of the cross language and how to create an
15091: @c application image with it. The section explains some aspects of
15092: @c creating a Gforth kernel.
15093:
1.46 pazsan 15094: The Makefile is already set up to allow you to create kernels for new
15095: architectures with a simple make command. The generic kernels using the
15096: GCC compiled virtual machine are created in the normal build process
15097: with @code{make}. To create a embedded Gforth executable for e.g. the
15098: 8086 processor (running on a DOS machine), type
15099:
15100: @example
15101: make kernl-8086.fi
15102: @end example
15103:
15104: This will use the machine description from the @file{arch/8086}
15105: directory to create a new kernel. A machine file may look like that:
15106:
15107: @example
15108: \ Parameter for target systems 06oct92py
15109:
15110: 4 Constant cell \ cell size in bytes
15111: 2 Constant cell<< \ cell shift to bytes
15112: 5 Constant cell>bit \ cell shift to bits
15113: 8 Constant bits/char \ bits per character
15114: 8 Constant bits/byte \ bits per byte [default: 8]
15115: 8 Constant float \ bytes per float
15116: 8 Constant /maxalign \ maximum alignment in bytes
15117: false Constant bigendian \ byte order
15118: ( true=big, false=little )
15119:
15120: include machpc.fs \ feature list
15121: @end example
15122:
15123: This part is obligatory for the cross compiler itself, the feature list
15124: is used by the kernel to conditionally compile some features in and out,
15125: depending on whether the target supports these features.
15126:
15127: There are some optional features, if you define your own primitives,
15128: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15129: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15130: @code{prims-include} includes primitives, and @code{>boot} prepares for
15131: booting.
15132:
15133: @example
15134: : asm-include ." Include assembler" cr
15135: s" arch/8086/asm.fs" included ;
15136:
15137: : prims-include ." Include primitives" cr
15138: s" arch/8086/prim.fs" included ;
15139:
15140: : >boot ." Prepare booting" cr
15141: s" ' boot >body into-forth 1+ !" evaluate ;
15142: @end example
15143:
15144: These words are used as sort of macro during the cross compilation in
1.81 anton 15145: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15146: be possible --- but more complicated --- to write a new kernel project
15147: file, too.
15148:
15149: @file{kernel/main.fs} expects the machine description file name on the
15150: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15151: @code{mach-file} leaves a counted string on the stack, or
15152: @code{machine-file} leaves an address, count pair of the filename on the
15153: stack.
15154:
15155: The feature list is typically controlled using @code{SetValue}, generic
15156: files that are used by several projects can use @code{DefaultValue}
15157: instead. Both functions work like @code{Value}, when the value isn't
15158: defined, but @code{SetValue} works like @code{to} if the value is
15159: defined, and @code{DefaultValue} doesn't set anything, if the value is
15160: defined.
15161:
15162: @example
15163: \ generic mach file for pc gforth 03sep97jaw
15164:
15165: true DefaultValue NIL \ relocating
15166:
15167: >ENVIRON
15168:
15169: true DefaultValue file \ controls the presence of the
15170: \ file access wordset
15171: true DefaultValue OS \ flag to indicate a operating system
15172:
15173: true DefaultValue prims \ true: primitives are c-code
15174:
15175: true DefaultValue floating \ floating point wordset is present
15176:
15177: true DefaultValue glocals \ gforth locals are present
15178: \ will be loaded
15179: true DefaultValue dcomps \ double number comparisons
15180:
15181: true DefaultValue hash \ hashing primitives are loaded/present
15182:
15183: true DefaultValue xconds \ used together with glocals,
15184: \ special conditionals supporting gforths'
15185: \ local variables
15186: true DefaultValue header \ save a header information
15187:
15188: true DefaultValue backtrace \ enables backtrace code
15189:
15190: false DefaultValue ec
15191: false DefaultValue crlf
15192:
15193: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15194:
15195: &16 KB DefaultValue stack-size
15196: &15 KB &512 + DefaultValue fstack-size
15197: &15 KB DefaultValue rstack-size
15198: &14 KB &512 + DefaultValue lstack-size
15199: @end example
1.13 pazsan 15200:
1.48 anton 15201: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15202: @section How the Cross Compiler Works
1.13 pazsan 15203:
15204: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15205: @appendix Bugs
1.1 anton 15206: @cindex bug reporting
15207:
1.21 crook 15208: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15209:
1.103 anton 15210: If you find a bug, please submit a bug report through
15211: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15212:
15213: @itemize @bullet
15214: @item
1.81 anton 15215: A program (or a sequence of keyboard commands) that reproduces the bug.
15216: @item
15217: A description of what you think constitutes the buggy behaviour.
15218: @item
1.21 crook 15219: The Gforth version used (it is announced at the start of an
15220: interactive Gforth session).
15221: @item
15222: The machine and operating system (on Unix
15223: systems @code{uname -a} will report this information).
15224: @item
1.81 anton 15225: The installation options (you can find the configure options at the
15226: start of @file{config.status}) and configuration (@code{configure}
15227: output or @file{config.cache}).
1.21 crook 15228: @item
15229: A complete list of changes (if any) you (or your installer) have made to the
15230: Gforth sources.
15231: @end itemize
1.1 anton 15232:
15233: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15234: to Report Bugs, gcc.info, GNU C Manual}.
15235:
15236:
1.21 crook 15237: @node Origin, Forth-related information, Bugs, Top
15238: @appendix Authors and Ancestors of Gforth
1.1 anton 15239:
15240: @section Authors and Contributors
15241: @cindex authors of Gforth
15242: @cindex contributors to Gforth
15243:
15244: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15245: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15246: lot to the manual. Assemblers and disassemblers were contributed by
15247: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15248: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15249: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15250: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15251: support for calling C libraries. Helpful comments also came from Paul
15252: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15253: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15254: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15255: Gforth-0.2.1 there were also helpful comments from many others; thank
15256: you all, sorry for not listing you here (but digging through my mailbox
15257: to extract your names is on my to-do list).
1.1 anton 15258:
15259: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15260: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15261: was developed across the Internet, and its authors did not meet
1.20 pazsan 15262: physically for the first 4 years of development.
1.1 anton 15263:
15264: @section Pedigree
1.26 crook 15265: @cindex pedigree of Gforth
1.1 anton 15266:
1.81 anton 15267: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15268: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15269:
1.20 pazsan 15270: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15271: 32 bit native code version of VolksForth for the Atari ST, written
15272: mostly by Dietrich Weineck.
15273:
1.81 anton 15274: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15275: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15276: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15277:
15278: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15279: Forth-83 standard. !! Pedigree? When?
15280:
15281: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15282: 1979. Robert Selzer and Bill Ragsdale developed the original
15283: implementation of fig-Forth for the 6502 based on microForth.
15284:
15285: The principal architect of microForth was Dean Sanderson. microForth was
15286: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15287: the 1802, and subsequently implemented on the 8080, the 6800 and the
15288: Z80.
15289:
15290: All earlier Forth systems were custom-made, usually by Charles Moore,
15291: who discovered (as he puts it) Forth during the late 60s. The first full
15292: Forth existed in 1971.
15293:
1.81 anton 15294: A part of the information in this section comes from
15295: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15296: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15297: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15298: SIGPLAN Notices 28(3), 1993. You can find more historical and
15299: genealogical information about Forth there.
1.1 anton 15300:
1.81 anton 15301: @c ------------------------------------------------------------------
1.113 anton 15302: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15303: @appendix Other Forth-related information
15304: @cindex Forth-related information
15305:
1.81 anton 15306: @c anton: I threw most of this stuff out, because it can be found through
15307: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15308:
15309: @cindex comp.lang.forth
15310: @cindex frequently asked questions
1.81 anton 15311: There is an active news group (comp.lang.forth) discussing Forth
15312: (including Gforth) and Forth-related issues. Its
15313: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15314: (frequently asked questions and their answers) contains a lot of
15315: information on Forth. You should read it before posting to
15316: comp.lang.forth.
1.21 crook 15317:
1.81 anton 15318: The ANS Forth standard is most usable in its
15319: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15320:
1.113 anton 15321: @c ---------------------------------------------------
15322: @node Licenses, Word Index, Forth-related information, Top
15323: @appendix Licenses
15324:
15325: @menu
15326: * GNU Free Documentation License:: License for copying this manual.
15327: * Copying:: GPL (for copying this software).
15328: @end menu
15329:
15330: @include fdl.texi
15331:
15332: @include gpl.texi
15333:
15334:
15335:
1.81 anton 15336: @c ------------------------------------------------------------------
1.113 anton 15337: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15338: @unnumbered Word Index
15339:
1.26 crook 15340: This index is a list of Forth words that have ``glossary'' entries
15341: within this manual. Each word is listed with its stack effect and
15342: wordset.
1.1 anton 15343:
15344: @printindex fn
15345:
1.81 anton 15346: @c anton: the name index seems superfluous given the word and concept indices.
15347:
15348: @c @node Name Index, Concept Index, Word Index, Top
15349: @c @unnumbered Name Index
1.41 anton 15350:
1.81 anton 15351: @c This index is a list of Forth words that have ``glossary'' entries
15352: @c within this manual.
1.41 anton 15353:
1.81 anton 15354: @c @printindex ky
1.41 anton 15355:
1.113 anton 15356: @c -------------------------------------------------------
1.81 anton 15357: @node Concept Index, , Word Index, Top
1.1 anton 15358: @unnumbered Concept and Word Index
15359:
1.26 crook 15360: Not all entries listed in this index are present verbatim in the
15361: text. This index also duplicates, in abbreviated form, all of the words
15362: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15363:
15364: @printindex cp
15365:
15366: @bye
1.81 anton 15367:
15368:
1.1 anton 15369:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>