Annotation of gforth/doc/gforth.ds, revision 1.141
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.135 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004 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:
1.141 ! anton 1297: @quotation Assignment
1.48 anton 1298: What does the stack contain after @code{5 6 7 .}?
1.141 ! anton 1299: @end quotation
1.48 anton 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:
1.141 ! anton 1330: @quotation Assignment
1.48 anton 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).}.
1.141 ! anton 1334: @end quotation
1.48 anton 1335:
1336: To change the sign, use @code{negate}:
1337:
1338: @example
1339: 2 negate .
1340: @end example
1341:
1.141 ! anton 1342: @quotation Assignment
1.48 anton 1343: Convert -(-3)*4-5 to Forth.
1.141 ! anton 1344: @end quotation
1.48 anton 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:
1.141 ! anton 1383: @quotation Assignment
1.48 anton 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
1.141 ! anton 1401: @end quotation
1.48 anton 1402:
1403: @example
1404: 5 dup * .
1405: @end example
1406:
1.141 ! anton 1407: @quotation Assignment
1.48 anton 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)}.
1.141 ! anton 1412: @end quotation
1.48 anton 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:
1.141 ! anton 1532: @quotation Assignment
1.48 anton 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.
1.141 ! anton 1537: @end quotation
1.48 anton 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:
1.141 ! anton 1585: @quotation Assignment
1.48 anton 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}).
1.141 ! anton 1591: @end quotation
1.48 anton 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:
1.141 ! anton 1646: @quotation Assignment
1.48 anton 1647: Write stack-effect comments for all definitions you have written up to
1648: now.
1.141 ! anton 1649: @end quotation
1.48 anton 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:
1.141 ! anton 1826: @quotation Assignment
1.48 anton 1827: Rewrite your definitions until now with locals
1.141 ! anton 1828: @end quotation
1.48 anton 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:
1.141 ! anton 1884: @quotation Assignment
1.48 anton 1885: Write @code{min} without @code{else}-part (hint: what's the definition
1886: of @code{nip}?).
1.141 ! anton 1887: @end quotation
1.48 anton 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:
1.141 ! anton 1961: @quotation Assignment
1.48 anton 1962: Write @code{min} without @code{if}.
1.141 ! anton 1963: @end quotation
1.48 anton 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:
1.141 ! anton 2039: @quotation Assignment
1.48 anton 2040: Write a definition for computing the greatest common divisor.
1.141 ! anton 2041: @end quotation
1.48 anton 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:
1.141 ! anton 2085: @quotation Assignment
1.48 anton 2086: Write a definition for computing the nth Fibonacci number.
1.141 ! anton 2087: @end quotation
1.48 anton 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:
1.141 ! anton 2147: @quotation Assignment
1.48 anton 2148: Write a recursive definition for computing the nth Fibonacci number.
1.141 ! anton 2149: @end quotation
1.48 anton 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:
1.141 ! anton 2247: @quotation Assignment
1.48 anton 2248: Can you rewrite any of the definitions you wrote until now in a better
2249: way using the return stack?
1.141 ! anton 2250: @end quotation
1.48 anton 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:
1.141 ! anton 2311: @quotation Assignment
1.48 anton 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.
1.141 ! anton 2315: @end quotation
1.48 anton 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:
1.141 ! anton 2419: @quotation Assignment
1.48 anton 2420: @code{Emit ( c -- )} types @code{c} as character (not a number).
2421: Implement @code{type ( addr u -- )}.
1.141 ! anton 2422: @end quotation
1.48 anton 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:
1.141 ! anton 2578: @quotation Assignment
1.84 pazsan 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?
1.141 ! anton 2582: @end quotation
1.84 pazsan 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:
1.141 ! anton 2792: @quotation Assignment
1.48 anton 2793: Try the same with @code{execute} instead of @code{catch}.
1.141 ! anton 2794: @end quotation
1.48 anton 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.141 ! anton 2958: @quotation Assignment
1.48 anton 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}.
1.141 ! anton 2964: @end quotation
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.141 ! anton 3059: @quotation Assignment
1.48 anton 3060: Write @code{MY-2DUP} that has compilation semantics equivalent to
3061: @code{2dup}, but compiles @code{over over}.
1.141 ! anton 3062: @end quotation
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.141 ! anton 3099: @quotation Assignment
1.48 anton 3100: Write @code{]L} which allows writing the example above as @code{: bar (
3101: -- n ) [ 2 2 + ]L ;}
1.141 ! anton 3102: @end quotation
1.48 anton 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.141 ! anton 3272: @quotation Assignment
1.48 anton 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).
1.141 ! anton 3278: @end quotation
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.134 anton 3382: *the terminal*:2: Undefined word
3383: >>>qwer341<<<
3384: Backtrace:
3385: $2A95B42A20 throw
3386: $2A95B57FB8 no.extensions
1.29 crook 3387: @end example
1.23 crook 3388:
1.134 anton 3389: The exact text, other than the ``Undefined word'' may differ slightly
3390: on your system, but the effect is the same; when the text interpreter
1.29 crook 3391: detects an error, it discards any remaining text on a line, resets
1.134 anton 3392: certain internal state and prints an error message. For a detailed
3393: description of error messages see @ref{Error 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.134 anton 3443: *the terminal*:3: Undefined word
3444: 12 dup >>>fred<<< dup
3445: Backtrace:
3446: $2A95B42A20 throw
3447: $2A95B57FB8 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.134 anton 3848: *the terminal*:4: Undefined word
3849: : >>>add-two<<< 2 + . ;
1.29 crook 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.141 ! anton 5099: doc-pad
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:
1.140 anton 6160: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 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.132 anton 6622: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 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.132 anton 6638: ' my: IS : \ use special version of :
1.44 crook 6639: \
6640: \ load application here
6641: \
1.132 anton 6642: ' real: IS : \ go back to the original
1.44 crook 6643: @end example
6644:
6645:
1.132 anton 6646: One thing to note is that @code{IS} has special compilation semantics,
6647: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6648:
6649: @example
6650: : set-greet ( xt -- )
1.132 anton 6651: IS greet ;
1.44 crook 6652:
6653: ' greet1 set-greet
6654: @end example
6655:
1.132 anton 6656: In situations where @code{IS} does not fit, use @code{defer!} instead.
6657:
1.69 anton 6658: A deferred word can only inherit execution semantics from the xt
6659: (because that is all that an xt can represent -- for more discussion of
6660: this @pxref{Tokens for Words}); by default it will have default
6661: interpretation and compilation semantics deriving from this execution
6662: semantics. However, you can change the interpretation and compilation
6663: semantics of the deferred word in the usual ways:
1.44 crook 6664:
6665: @example
1.132 anton 6666: : bar .... ; immediate
1.44 crook 6667: Defer fred immediate
6668: Defer jim
6669:
1.132 anton 6670: ' bar IS jim \ jim has default semantics
6671: ' bar IS fred \ fred is immediate
1.44 crook 6672: @end example
6673:
6674: doc-defer
1.132 anton 6675: doc-defer!
1.44 crook 6676: doc-is
1.132 anton 6677: doc-defer@
6678: doc-action-of
1.44 crook 6679: @comment TODO document these: what's defers [is]
6680: doc-defers
6681:
6682: @c Use @code{words-deferred} to see a list of deferred words.
6683:
1.132 anton 6684: Definitions of these words (except @code{defers}) in ANS Forth are
6685: provided in @file{compat/defer.fs}.
1.44 crook 6686:
6687:
1.69 anton 6688: @node Aliases, , Deferred words, Defining Words
1.44 crook 6689: @subsection Aliases
6690: @cindex aliases
1.1 anton 6691:
1.44 crook 6692: The defining word @code{Alias} allows you to define a word by name that
6693: has the same behaviour as some other word. Here are two situation where
6694: this can be useful:
1.1 anton 6695:
1.44 crook 6696: @itemize @bullet
6697: @item
6698: When you want access to a word's definition from a different word list
6699: (for an example of this, see the definition of the @code{Root} word list
6700: in the Gforth source).
6701: @item
6702: When you want to create a synonym; a definition that can be known by
6703: either of two names (for example, @code{THEN} and @code{ENDIF} are
6704: aliases).
6705: @end itemize
1.1 anton 6706:
1.69 anton 6707: Like deferred words, an alias has default compilation and interpretation
6708: semantics at the beginning (not the modifications of the other word),
6709: but you can change them in the usual ways (@code{immediate},
6710: @code{compile-only}). For example:
1.1 anton 6711:
6712: @example
1.44 crook 6713: : foo ... ; immediate
6714:
6715: ' foo Alias bar \ bar is not an immediate word
6716: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6717: @end example
6718:
1.44 crook 6719: Words that are aliases have the same xt, different headers in the
6720: dictionary, and consequently different name tokens (@pxref{Tokens for
6721: Words}) and possibly different immediate flags. An alias can only have
6722: default or immediate compilation semantics; you can define aliases for
6723: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6724:
1.44 crook 6725: doc-alias
1.1 anton 6726:
6727:
1.47 crook 6728: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6729: @section Interpretation and Compilation Semantics
1.26 crook 6730: @cindex semantics, interpretation and compilation
1.1 anton 6731:
1.71 anton 6732: @c !! state and ' are used without explanation
6733: @c example for immediate/compile-only? or is the tutorial enough
6734:
1.26 crook 6735: @cindex interpretation semantics
1.71 anton 6736: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6737: interpreter does when it encounters the word in interpret state. It also
6738: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6739: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6740: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6741: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6742:
1.26 crook 6743: @cindex compilation semantics
1.71 anton 6744: The @dfn{compilation semantics} of a (named) word are what the text
6745: interpreter does when it encounters the word in compile state. It also
6746: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6747: compiles@footnote{In standard terminology, ``appends to the current
6748: definition''.} the compilation semantics of @i{word}.
1.1 anton 6749:
1.26 crook 6750: @cindex execution semantics
6751: The standard also talks about @dfn{execution semantics}. They are used
6752: only for defining the interpretation and compilation semantics of many
6753: words. By default, the interpretation semantics of a word are to
6754: @code{execute} its execution semantics, and the compilation semantics of
6755: a word are to @code{compile,} its execution semantics.@footnote{In
6756: standard terminology: The default interpretation semantics are its
6757: execution semantics; the default compilation semantics are to append its
6758: execution semantics to the execution semantics of the current
6759: definition.}
6760:
1.71 anton 6761: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6762: the text interpreter, ticked, or @code{postpone}d, so they have no
6763: interpretation or compilation semantics. Their behaviour is represented
6764: by their XT (@pxref{Tokens for Words}), and we call it execution
6765: semantics, too.
6766:
1.26 crook 6767: @comment TODO expand, make it co-operate with new sections on text interpreter.
6768:
6769: @cindex immediate words
6770: @cindex compile-only words
6771: You can change the semantics of the most-recently defined word:
6772:
1.44 crook 6773:
1.26 crook 6774: doc-immediate
6775: doc-compile-only
6776: doc-restrict
6777:
1.82 anton 6778: By convention, words with non-default compilation semantics (e.g.,
6779: immediate words) often have names surrounded with brackets (e.g.,
6780: @code{[']}, @pxref{Execution token}).
1.44 crook 6781:
1.26 crook 6782: Note that ticking (@code{'}) a compile-only word gives an error
6783: (``Interpreting a compile-only word'').
1.1 anton 6784:
1.47 crook 6785: @menu
1.67 anton 6786: * Combined words::
1.47 crook 6787: @end menu
1.44 crook 6788:
1.71 anton 6789:
1.48 anton 6790: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6791: @subsection Combined Words
6792: @cindex combined words
6793:
6794: Gforth allows you to define @dfn{combined words} -- words that have an
6795: arbitrary combination of interpretation and compilation semantics.
6796:
1.26 crook 6797: doc-interpret/compile:
1.1 anton 6798:
1.26 crook 6799: This feature was introduced for implementing @code{TO} and @code{S"}. I
6800: recommend that you do not define such words, as cute as they may be:
6801: they make it hard to get at both parts of the word in some contexts.
6802: E.g., assume you want to get an execution token for the compilation
6803: part. Instead, define two words, one that embodies the interpretation
6804: part, and one that embodies the compilation part. Once you have done
6805: that, you can define a combined word with @code{interpret/compile:} for
6806: the convenience of your users.
1.1 anton 6807:
1.26 crook 6808: You might try to use this feature to provide an optimizing
6809: implementation of the default compilation semantics of a word. For
6810: example, by defining:
1.1 anton 6811: @example
1.26 crook 6812: :noname
6813: foo bar ;
6814: :noname
6815: POSTPONE foo POSTPONE bar ;
1.29 crook 6816: interpret/compile: opti-foobar
1.1 anton 6817: @end example
1.26 crook 6818:
1.23 crook 6819: @noindent
1.26 crook 6820: as an optimizing version of:
6821:
1.1 anton 6822: @example
1.26 crook 6823: : foobar
6824: foo bar ;
1.1 anton 6825: @end example
6826:
1.26 crook 6827: Unfortunately, this does not work correctly with @code{[compile]},
6828: because @code{[compile]} assumes that the compilation semantics of all
6829: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6830: opti-foobar} would compile compilation semantics, whereas
6831: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6832:
1.26 crook 6833: @cindex state-smart words (are a bad idea)
1.82 anton 6834: @anchor{state-smartness}
1.29 crook 6835: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6836: by @code{interpret/compile:} (words are state-smart if they check
6837: @code{STATE} during execution). E.g., they would try to code
6838: @code{foobar} like this:
1.1 anton 6839:
1.26 crook 6840: @example
6841: : foobar
6842: STATE @@
6843: IF ( compilation state )
6844: POSTPONE foo POSTPONE bar
6845: ELSE
6846: foo bar
6847: ENDIF ; immediate
6848: @end example
1.1 anton 6849:
1.26 crook 6850: Although this works if @code{foobar} is only processed by the text
6851: interpreter, it does not work in other contexts (like @code{'} or
6852: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6853: for a state-smart word, not for the interpretation semantics of the
6854: original @code{foobar}; when you execute this execution token (directly
6855: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6856: state, the result will not be what you expected (i.e., it will not
6857: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6858: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6859: M. Anton Ertl,
6860: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6861: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6862:
1.26 crook 6863: @cindex defining words with arbitrary semantics combinations
6864: It is also possible to write defining words that define words with
6865: arbitrary combinations of interpretation and compilation semantics. In
6866: general, they look like this:
1.1 anton 6867:
1.26 crook 6868: @example
6869: : def-word
6870: create-interpret/compile
1.29 crook 6871: @i{code1}
1.26 crook 6872: interpretation>
1.29 crook 6873: @i{code2}
1.26 crook 6874: <interpretation
6875: compilation>
1.29 crook 6876: @i{code3}
1.26 crook 6877: <compilation ;
6878: @end example
1.1 anton 6879:
1.29 crook 6880: For a @i{word} defined with @code{def-word}, the interpretation
6881: semantics are to push the address of the body of @i{word} and perform
6882: @i{code2}, and the compilation semantics are to push the address of
6883: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6884: can also be defined like this (except that the defined constants don't
6885: behave correctly when @code{[compile]}d):
1.1 anton 6886:
1.26 crook 6887: @example
6888: : constant ( n "name" -- )
6889: create-interpret/compile
6890: ,
6891: interpretation> ( -- n )
6892: @@
6893: <interpretation
6894: compilation> ( compilation. -- ; run-time. -- n )
6895: @@ postpone literal
6896: <compilation ;
6897: @end example
1.1 anton 6898:
1.44 crook 6899:
1.26 crook 6900: doc-create-interpret/compile
6901: doc-interpretation>
6902: doc-<interpretation
6903: doc-compilation>
6904: doc-<compilation
1.1 anton 6905:
1.44 crook 6906:
1.29 crook 6907: Words defined with @code{interpret/compile:} and
1.26 crook 6908: @code{create-interpret/compile} have an extended header structure that
6909: differs from other words; however, unless you try to access them with
6910: plain address arithmetic, you should not notice this. Words for
6911: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6912: @code{'} @i{word} @code{>body} also gives you the body of a word created
6913: with @code{create-interpret/compile}.
1.1 anton 6914:
1.44 crook 6915:
1.47 crook 6916: @c -------------------------------------------------------------
1.81 anton 6917: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6918: @section Tokens for Words
6919: @cindex tokens for words
6920:
6921: This section describes the creation and use of tokens that represent
6922: words.
6923:
1.71 anton 6924: @menu
6925: * Execution token:: represents execution/interpretation semantics
6926: * Compilation token:: represents compilation semantics
6927: * Name token:: represents named words
6928: @end menu
1.47 crook 6929:
1.71 anton 6930: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6931: @subsection Execution token
1.47 crook 6932:
6933: @cindex xt
6934: @cindex execution token
1.71 anton 6935: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6936: You can use @code{execute} to invoke this behaviour.
1.47 crook 6937:
1.71 anton 6938: @cindex tick (')
6939: You can use @code{'} to get an execution token that represents the
6940: interpretation semantics of a named word:
1.47 crook 6941:
6942: @example
1.97 anton 6943: 5 ' . ( n xt )
6944: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6945: @end example
1.47 crook 6946:
1.71 anton 6947: doc-'
6948:
6949: @code{'} parses at run-time; there is also a word @code{[']} that parses
6950: when it is compiled, and compiles the resulting XT:
6951:
6952: @example
6953: : foo ['] . execute ;
6954: 5 foo
6955: : bar ' execute ; \ by contrast,
6956: 5 bar . \ ' parses "." when bar executes
6957: @end example
6958:
6959: doc-[']
6960:
6961: If you want the execution token of @i{word}, write @code{['] @i{word}}
6962: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6963: @code{'} and @code{[']} behave somewhat unusually by complaining about
6964: compile-only words (because these words have no interpretation
6965: semantics). You might get what you want by using @code{COMP' @i{word}
6966: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6967: token}).
6968:
1.116 anton 6969: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6970: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6971: for the only behaviour the word has (the execution semantics). For
1.116 anton 6972: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6973: would produce if the word was defined anonymously.
6974:
6975: @example
6976: :noname ." hello" ;
6977: execute
1.47 crook 6978: @end example
6979:
1.71 anton 6980: An XT occupies one cell and can be manipulated like any other cell.
6981:
1.47 crook 6982: @cindex code field address
6983: @cindex CFA
1.71 anton 6984: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6985: operations that produce or consume it). For old hands: In Gforth, the
6986: XT is implemented as a code field address (CFA).
6987:
6988: doc-execute
6989: doc-perform
6990:
6991: @node Compilation token, Name token, Execution token, Tokens for Words
6992: @subsection Compilation token
1.47 crook 6993:
6994: @cindex compilation token
1.71 anton 6995: @cindex CT (compilation token)
6996: Gforth represents the compilation semantics of a named word by a
1.47 crook 6997: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6998: @i{xt} is an execution token. The compilation semantics represented by
6999: the compilation token can be performed with @code{execute}, which
7000: consumes the whole compilation token, with an additional stack effect
7001: determined by the represented compilation semantics.
7002:
7003: At present, the @i{w} part of a compilation token is an execution token,
7004: and the @i{xt} part represents either @code{execute} or
7005: @code{compile,}@footnote{Depending upon the compilation semantics of the
7006: word. If the word has default compilation semantics, the @i{xt} will
7007: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7008: @i{xt} will represent @code{execute}.}. However, don't rely on that
7009: knowledge, unless necessary; future versions of Gforth may introduce
7010: unusual compilation tokens (e.g., a compilation token that represents
7011: the compilation semantics of a literal).
7012:
1.71 anton 7013: You can perform the compilation semantics represented by the compilation
7014: token with @code{execute}. You can compile the compilation semantics
7015: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7016: equivalent to @code{postpone @i{word}}.
7017:
7018: doc-[comp']
7019: doc-comp'
7020: doc-postpone,
7021:
7022: @node Name token, , Compilation token, Tokens for Words
7023: @subsection Name token
1.47 crook 7024:
7025: @cindex name token
1.116 anton 7026: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7027: token is an abstract data type that occurs as argument or result of the
7028: words below.
7029:
7030: @c !! put this elswhere?
1.47 crook 7031: @cindex name field address
7032: @cindex NFA
1.116 anton 7033: The closest thing to the nt in older Forth systems is the name field
7034: address (NFA), but there are significant differences: in older Forth
7035: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7036: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7037: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7038: is a link field in the structure identified by the name token, but
7039: searching usually uses a hash table external to these structures; the
7040: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7041: implemented as the address of that count field.
1.47 crook 7042:
7043: doc-find-name
1.116 anton 7044: doc-latest
7045: doc->name
1.47 crook 7046: doc-name>int
7047: doc-name?int
7048: doc-name>comp
7049: doc-name>string
1.109 anton 7050: doc-id.
7051: doc-.name
7052: doc-.id
1.47 crook 7053:
1.81 anton 7054: @c ----------------------------------------------------------
7055: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7056: @section Compiling words
7057: @cindex compiling words
7058: @cindex macros
7059:
7060: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7061: between compilation and run-time. E.g., you can run arbitrary code
7062: between defining words (or for computing data used by defining words
7063: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7064: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7065: running arbitrary code while compiling a colon definition (exception:
7066: you must not allot dictionary space).
7067:
7068: @menu
7069: * Literals:: Compiling data values
7070: * Macros:: Compiling words
7071: @end menu
7072:
7073: @node Literals, Macros, Compiling words, Compiling words
7074: @subsection Literals
7075: @cindex Literals
7076:
7077: The simplest and most frequent example is to compute a literal during
7078: compilation. E.g., the following definition prints an array of strings,
7079: one string per line:
7080:
7081: @example
7082: : .strings ( addr u -- ) \ gforth
7083: 2* cells bounds U+DO
7084: cr i 2@@ type
7085: 2 cells +LOOP ;
7086: @end example
1.81 anton 7087:
1.82 anton 7088: With a simple-minded compiler like Gforth's, this computes @code{2
7089: cells} on every loop iteration. You can compute this value once and for
7090: all at compile time and compile it into the definition like this:
7091:
7092: @example
7093: : .strings ( addr u -- ) \ gforth
7094: 2* cells bounds U+DO
7095: cr i 2@@ type
7096: [ 2 cells ] literal +LOOP ;
7097: @end example
7098:
7099: @code{[} switches the text interpreter to interpret state (you will get
7100: an @code{ok} prompt if you type this example interactively and insert a
7101: newline between @code{[} and @code{]}), so it performs the
7102: interpretation semantics of @code{2 cells}; this computes a number.
7103: @code{]} switches the text interpreter back into compile state. It then
7104: performs @code{Literal}'s compilation semantics, which are to compile
7105: this number into the current word. You can decompile the word with
7106: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7107:
1.82 anton 7108: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7109: *} in this way.
1.81 anton 7110:
1.82 anton 7111: doc-[
7112: doc-]
1.81 anton 7113: doc-literal
7114: doc-]L
1.82 anton 7115:
7116: There are also words for compiling other data types than single cells as
7117: literals:
7118:
1.81 anton 7119: doc-2literal
7120: doc-fliteral
1.82 anton 7121: doc-sliteral
7122:
7123: @cindex colon-sys, passing data across @code{:}
7124: @cindex @code{:}, passing data across
7125: You might be tempted to pass data from outside a colon definition to the
7126: inside on the data stack. This does not work, because @code{:} puhes a
7127: colon-sys, making stuff below unaccessible. E.g., this does not work:
7128:
7129: @example
7130: 5 : foo literal ; \ error: "unstructured"
7131: @end example
7132:
7133: Instead, you have to pass the value in some other way, e.g., through a
7134: variable:
7135:
7136: @example
7137: variable temp
7138: 5 temp !
7139: : foo [ temp @@ ] literal ;
7140: @end example
7141:
7142:
7143: @node Macros, , Literals, Compiling words
7144: @subsection Macros
7145: @cindex Macros
7146: @cindex compiling compilation semantics
7147:
7148: @code{Literal} and friends compile data values into the current
7149: definition. You can also write words that compile other words into the
7150: current definition. E.g.,
7151:
7152: @example
7153: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7154: POSTPONE + ;
7155:
7156: : foo ( n1 n2 -- n )
7157: [ compile-+ ] ;
7158: 1 2 foo .
7159: @end example
7160:
7161: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7162: What happens in this example? @code{Postpone} compiles the compilation
7163: semantics of @code{+} into @code{compile-+}; later the text interpreter
7164: executes @code{compile-+} and thus the compilation semantics of +, which
7165: compile (the execution semantics of) @code{+} into
7166: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7167: should only be executed in compile state, so this example is not
7168: guaranteed to work on all standard systems, but on any decent system it
7169: will work.}
7170:
7171: doc-postpone
7172: doc-[compile]
7173:
7174: Compiling words like @code{compile-+} are usually immediate (or similar)
7175: so you do not have to switch to interpret state to execute them;
7176: mopifying the last example accordingly produces:
7177:
7178: @example
7179: : [compile-+] ( compilation: --; interpretation: -- )
7180: \ compiled code: ( n1 n2 -- n )
7181: POSTPONE + ; immediate
7182:
7183: : foo ( n1 n2 -- n )
7184: [compile-+] ;
7185: 1 2 foo .
7186: @end example
7187:
7188: Immediate compiling words are similar to macros in other languages (in
7189: particular, Lisp). The important differences to macros in, e.g., C are:
7190:
7191: @itemize @bullet
7192:
7193: @item
7194: You use the same language for defining and processing macros, not a
7195: separate preprocessing language and processor.
7196:
7197: @item
7198: Consequently, the full power of Forth is available in macro definitions.
7199: E.g., you can perform arbitrarily complex computations, or generate
7200: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7201: Tutorial}). This power is very useful when writing a parser generators
7202: or other code-generating software.
7203:
7204: @item
7205: Macros defined using @code{postpone} etc. deal with the language at a
7206: higher level than strings; name binding happens at macro definition
7207: time, so you can avoid the pitfalls of name collisions that can happen
7208: in C macros. Of course, Forth is a liberal language and also allows to
7209: shoot yourself in the foot with text-interpreted macros like
7210:
7211: @example
7212: : [compile-+] s" +" evaluate ; immediate
7213: @end example
7214:
7215: Apart from binding the name at macro use time, using @code{evaluate}
7216: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7217: @end itemize
7218:
7219: You may want the macro to compile a number into a word. The word to do
7220: it is @code{literal}, but you have to @code{postpone} it, so its
7221: compilation semantics take effect when the macro is executed, not when
7222: it is compiled:
7223:
7224: @example
7225: : [compile-5] ( -- ) \ compiled code: ( -- n )
7226: 5 POSTPONE literal ; immediate
7227:
7228: : foo [compile-5] ;
7229: foo .
7230: @end example
7231:
7232: You may want to pass parameters to a macro, that the macro should
7233: compile into the current definition. If the parameter is a number, then
7234: you can use @code{postpone literal} (similar for other values).
7235:
7236: If you want to pass a word that is to be compiled, the usual way is to
7237: pass an execution token and @code{compile,} it:
7238:
7239: @example
7240: : twice1 ( xt -- ) \ compiled code: ... -- ...
7241: dup compile, compile, ;
7242:
7243: : 2+ ( n1 -- n2 )
7244: [ ' 1+ twice1 ] ;
7245: @end example
7246:
7247: doc-compile,
7248:
7249: An alternative available in Gforth, that allows you to pass compile-only
7250: words as parameters is to use the compilation token (@pxref{Compilation
7251: token}). The same example in this technique:
7252:
7253: @example
7254: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7255: 2dup 2>r execute 2r> execute ;
7256:
7257: : 2+ ( n1 -- n2 )
7258: [ comp' 1+ twice ] ;
7259: @end example
7260:
7261: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7262: works even if the executed compilation semantics has an effect on the
7263: data stack.
7264:
7265: You can also define complete definitions with these words; this provides
7266: an alternative to using @code{does>} (@pxref{User-defined Defining
7267: Words}). E.g., instead of
7268:
7269: @example
7270: : curry+ ( n1 "name" -- )
7271: CREATE ,
7272: DOES> ( n2 -- n1+n2 )
7273: @@ + ;
7274: @end example
7275:
7276: you could define
7277:
7278: @example
7279: : curry+ ( n1 "name" -- )
7280: \ name execution: ( n2 -- n1+n2 )
7281: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7282:
1.82 anton 7283: -3 curry+ 3-
7284: see 3-
7285: @end example
1.81 anton 7286:
1.82 anton 7287: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7288: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7289:
1.82 anton 7290: This way of writing defining words is sometimes more, sometimes less
7291: convenient than using @code{does>} (@pxref{Advanced does> usage
7292: example}). One advantage of this method is that it can be optimized
7293: better, because the compiler knows that the value compiled with
7294: @code{literal} is fixed, whereas the data associated with a
7295: @code{create}d word can be changed.
1.47 crook 7296:
1.26 crook 7297: @c ----------------------------------------------------------
1.111 anton 7298: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7299: @section The Text Interpreter
7300: @cindex interpreter - outer
7301: @cindex text interpreter
7302: @cindex outer interpreter
1.1 anton 7303:
1.34 anton 7304: @c Should we really describe all these ugly details? IMO the text
7305: @c interpreter should be much cleaner, but that may not be possible within
7306: @c ANS Forth. - anton
1.44 crook 7307: @c nac-> I wanted to explain how it works to show how you can exploit
7308: @c it in your own programs. When I was writing a cross-compiler, figuring out
7309: @c some of these gory details was very helpful to me. None of the textbooks
7310: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7311: @c seems to positively avoid going into too much detail for some of
7312: @c the internals.
1.34 anton 7313:
1.71 anton 7314: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7315: @c it is; for the ugly details, I would prefer another place. I wonder
7316: @c whether we should have a chapter before "Words" that describes some
7317: @c basic concepts referred to in words, and a chapter after "Words" that
7318: @c describes implementation details.
7319:
1.29 crook 7320: The text interpreter@footnote{This is an expanded version of the
7321: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7322: that processes input from the current input device. It is also called
7323: the outer interpreter, in contrast to the inner interpreter
7324: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7325: implementations.
1.27 crook 7326:
1.29 crook 7327: @cindex interpret state
7328: @cindex compile state
7329: The text interpreter operates in one of two states: @dfn{interpret
7330: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7331: aptly-named variable @code{state}.
1.29 crook 7332:
7333: This section starts by describing how the text interpreter behaves when
7334: it is in interpret state, processing input from the user input device --
7335: the keyboard. This is the mode that a Forth system is in after it starts
7336: up.
7337:
7338: @cindex input buffer
7339: @cindex terminal input buffer
7340: The text interpreter works from an area of memory called the @dfn{input
7341: buffer}@footnote{When the text interpreter is processing input from the
7342: keyboard, this area of memory is called the @dfn{terminal input buffer}
7343: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7344: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7345: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7346: leading spaces (called @dfn{delimiters}) then parses a string (a
7347: sequence of non-space characters) until it reaches either a space
7348: character or the end of the buffer. Having parsed a string, it makes two
7349: attempts to process it:
1.27 crook 7350:
1.29 crook 7351: @cindex dictionary
1.27 crook 7352: @itemize @bullet
7353: @item
1.29 crook 7354: It looks for the string in a @dfn{dictionary} of definitions. If the
7355: string is found, the string names a @dfn{definition} (also known as a
7356: @dfn{word}) and the dictionary search returns information that allows
7357: the text interpreter to perform the word's @dfn{interpretation
7358: semantics}. In most cases, this simply means that the word will be
7359: executed.
1.27 crook 7360: @item
7361: If the string is not found in the dictionary, the text interpreter
1.29 crook 7362: attempts to treat it as a number, using the rules described in
7363: @ref{Number Conversion}. If the string represents a legal number in the
7364: current radix, the number is pushed onto a parameter stack (the data
7365: stack for integers, the floating-point stack for floating-point
7366: numbers).
7367: @end itemize
7368:
7369: If both attempts fail, or if the word is found in the dictionary but has
7370: no interpretation semantics@footnote{This happens if the word was
7371: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7372: remainder of the input buffer, issues an error message and waits for
7373: more input. If one of the attempts succeeds, the text interpreter
7374: repeats the parsing process until the whole of the input buffer has been
7375: processed, at which point it prints the status message ``@code{ ok}''
7376: and waits for more input.
7377:
1.71 anton 7378: @c anton: this should be in the input stream subsection (or below it)
7379:
1.29 crook 7380: @cindex parse area
7381: The text interpreter keeps track of its position in the input buffer by
7382: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7383: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7384: of the input buffer. The region from offset @code{>IN @@} to the end of
7385: the input buffer is called the @dfn{parse area}@footnote{In other words,
7386: the text interpreter processes the contents of the input buffer by
7387: parsing strings from the parse area until the parse area is empty.}.
7388: This example shows how @code{>IN} changes as the text interpreter parses
7389: the input buffer:
7390:
7391: @example
7392: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7393: CR ." ->" TYPE ." <-" ; IMMEDIATE
7394:
7395: 1 2 3 remaining + remaining .
7396:
7397: : foo 1 2 3 remaining SWAP remaining ;
7398: @end example
7399:
7400: @noindent
7401: The result is:
7402:
7403: @example
7404: ->+ remaining .<-
7405: ->.<-5 ok
7406:
7407: ->SWAP remaining ;-<
7408: ->;<- ok
7409: @end example
7410:
7411: @cindex parsing words
7412: The value of @code{>IN} can also be modified by a word in the input
7413: buffer that is executed by the text interpreter. This means that a word
7414: can ``trick'' the text interpreter into either skipping a section of the
7415: input buffer@footnote{This is how parsing words work.} or into parsing a
7416: section twice. For example:
1.27 crook 7417:
1.29 crook 7418: @example
1.71 anton 7419: : lat ." <<foo>>" ;
7420: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7421: @end example
7422:
7423: @noindent
7424: When @code{flat} is executed, this output is produced@footnote{Exercise
7425: for the reader: what would happen if the @code{3} were replaced with
7426: @code{4}?}:
7427:
7428: @example
1.71 anton 7429: <<bar>><<foo>>
1.29 crook 7430: @end example
7431:
1.71 anton 7432: This technique can be used to work around some of the interoperability
7433: problems of parsing words. Of course, it's better to avoid parsing
7434: words where possible.
7435:
1.29 crook 7436: @noindent
7437: Two important notes about the behaviour of the text interpreter:
1.27 crook 7438:
7439: @itemize @bullet
7440: @item
7441: It processes each input string to completion before parsing additional
1.29 crook 7442: characters from the input buffer.
7443: @item
7444: It treats the input buffer as a read-only region (and so must your code).
7445: @end itemize
7446:
7447: @noindent
7448: When the text interpreter is in compile state, its behaviour changes in
7449: these ways:
7450:
7451: @itemize @bullet
7452: @item
7453: If a parsed string is found in the dictionary, the text interpreter will
7454: perform the word's @dfn{compilation semantics}. In most cases, this
7455: simply means that the execution semantics of the word will be appended
7456: to the current definition.
1.27 crook 7457: @item
1.29 crook 7458: When a number is encountered, it is compiled into the current definition
7459: (as a literal) rather than being pushed onto a parameter stack.
7460: @item
7461: If an error occurs, @code{state} is modified to put the text interpreter
7462: back into interpret state.
7463: @item
7464: Each time a line is entered from the keyboard, Gforth prints
7465: ``@code{ compiled}'' rather than `` @code{ok}''.
7466: @end itemize
7467:
7468: @cindex text interpreter - input sources
7469: When the text interpreter is using an input device other than the
7470: keyboard, its behaviour changes in these ways:
7471:
7472: @itemize @bullet
7473: @item
7474: When the parse area is empty, the text interpreter attempts to refill
7475: the input buffer from the input source. When the input source is
1.71 anton 7476: exhausted, the input source is set back to the previous input source.
1.29 crook 7477: @item
7478: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7479: time the parse area is emptied.
7480: @item
7481: If an error occurs, the input source is set back to the user input
7482: device.
1.27 crook 7483: @end itemize
1.21 crook 7484:
1.49 anton 7485: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7486:
1.26 crook 7487: doc->in
1.27 crook 7488: doc-source
7489:
1.26 crook 7490: doc-tib
7491: doc-#tib
1.1 anton 7492:
1.44 crook 7493:
1.26 crook 7494: @menu
1.67 anton 7495: * Input Sources::
7496: * Number Conversion::
7497: * Interpret/Compile states::
7498: * Interpreter Directives::
1.26 crook 7499: @end menu
1.1 anton 7500:
1.29 crook 7501: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7502: @subsection Input Sources
7503: @cindex input sources
7504: @cindex text interpreter - input sources
7505:
1.44 crook 7506: By default, the text interpreter processes input from the user input
1.29 crook 7507: device (the keyboard) when Forth starts up. The text interpreter can
7508: process input from any of these sources:
7509:
7510: @itemize @bullet
7511: @item
7512: The user input device -- the keyboard.
7513: @item
7514: A file, using the words described in @ref{Forth source files}.
7515: @item
7516: A block, using the words described in @ref{Blocks}.
7517: @item
7518: A text string, using @code{evaluate}.
7519: @end itemize
7520:
7521: A program can identify the current input device from the values of
7522: @code{source-id} and @code{blk}.
7523:
1.44 crook 7524:
1.29 crook 7525: doc-source-id
7526: doc-blk
7527:
7528: doc-save-input
7529: doc-restore-input
7530:
7531: doc-evaluate
1.111 anton 7532: doc-query
1.1 anton 7533:
1.29 crook 7534:
1.44 crook 7535:
1.29 crook 7536: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7537: @subsection Number Conversion
7538: @cindex number conversion
7539: @cindex double-cell numbers, input format
7540: @cindex input format for double-cell numbers
7541: @cindex single-cell numbers, input format
7542: @cindex input format for single-cell numbers
7543: @cindex floating-point numbers, input format
7544: @cindex input format for floating-point numbers
1.1 anton 7545:
1.29 crook 7546: This section describes the rules that the text interpreter uses when it
7547: tries to convert a string into a number.
1.1 anton 7548:
1.26 crook 7549: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7550: number base@footnote{For example, 0-9 when the number base is decimal or
7551: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7552:
1.26 crook 7553: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7554:
1.29 crook 7555: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7556: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7557:
1.26 crook 7558: Let * represent any number of instances of the previous character
7559: (including none).
1.1 anton 7560:
1.26 crook 7561: Let any other character represent itself.
1.1 anton 7562:
1.29 crook 7563: @noindent
1.26 crook 7564: Now, the conversion rules are:
1.21 crook 7565:
1.26 crook 7566: @itemize @bullet
7567: @item
7568: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7569: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7570: @item
7571: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7572: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7573: arithmetic. Examples are -45 -5681 -0
7574: @item
7575: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7576: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7577: (all three of these represent the same number).
1.26 crook 7578: @item
7579: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7580: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7581: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7582: -34.65 (all three of these represent the same number).
1.26 crook 7583: @item
1.29 crook 7584: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7585: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7586: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7587: number) +12.E-4
1.26 crook 7588: @end itemize
1.1 anton 7589:
1.26 crook 7590: By default, the number base used for integer number conversion is given
1.35 anton 7591: by the contents of the variable @code{base}. Note that a lot of
7592: confusion can result from unexpected values of @code{base}. If you
7593: change @code{base} anywhere, make sure to save the old value and restore
7594: it afterwards. In general I recommend keeping @code{base} decimal, and
7595: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7596:
1.29 crook 7597: doc-dpl
1.26 crook 7598: doc-base
7599: doc-hex
7600: doc-decimal
1.1 anton 7601:
1.26 crook 7602: @cindex '-prefix for character strings
7603: @cindex &-prefix for decimal numbers
1.133 anton 7604: @cindex #-prefix for decimal numbers
1.26 crook 7605: @cindex %-prefix for binary numbers
7606: @cindex $-prefix for hexadecimal numbers
1.133 anton 7607: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7608: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7609: prefix@footnote{Some Forth implementations provide a similar scheme by
7610: implementing @code{$} etc. as parsing words that process the subsequent
7611: number in the input stream and push it onto the stack. For example, see
7612: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7613: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7614: is required between the prefix and the number.} before the first digit
1.133 anton 7615: of an (integer) number. The following prefixes are supported:
1.1 anton 7616:
1.26 crook 7617: @itemize @bullet
7618: @item
1.35 anton 7619: @code{&} -- decimal
1.26 crook 7620: @item
1.133 anton 7621: @code{#} -- decimal
7622: @item
1.35 anton 7623: @code{%} -- binary
1.26 crook 7624: @item
1.35 anton 7625: @code{$} -- hexadecimal
1.26 crook 7626: @item
1.133 anton 7627: @code{0x} -- hexadecimal, if base<33.
7628: @item
7629: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7630: optional @code{'} may be present after the character.
1.26 crook 7631: @end itemize
1.1 anton 7632:
1.26 crook 7633: Here are some examples, with the equivalent decimal number shown after
7634: in braces:
1.1 anton 7635:
1.26 crook 7636: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7637: 'A (65),
7638: -'a' (-97),
1.26 crook 7639: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7640:
1.26 crook 7641: @cindex number conversion - traps for the unwary
1.29 crook 7642: @noindent
1.26 crook 7643: Number conversion has a number of traps for the unwary:
1.1 anton 7644:
1.26 crook 7645: @itemize @bullet
7646: @item
7647: You cannot determine the current number base using the code sequence
1.35 anton 7648: @code{base @@ .} -- the number base is always 10 in the current number
7649: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7650: @item
7651: If the number base is set to a value greater than 14 (for example,
7652: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7653: it to be intepreted as either a single-precision integer or a
7654: floating-point number (Gforth treats it as an integer). The ambiguity
7655: can be resolved by explicitly stating the sign of the mantissa and/or
7656: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7657: ambiguity arises; either representation will be treated as a
7658: floating-point number.
7659: @item
1.29 crook 7660: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7661: It is used to specify file types.
7662: @item
1.72 anton 7663: ANS Forth requires the @code{.} of a double-precision number to be the
7664: final character in the string. Gforth allows the @code{.} to be
7665: anywhere after the first digit.
1.26 crook 7666: @item
7667: The number conversion process does not check for overflow.
7668: @item
1.72 anton 7669: In an ANS Forth program @code{base} is required to be decimal when
7670: converting floating-point numbers. In Gforth, number conversion to
7671: floating-point numbers always uses base &10, irrespective of the value
7672: of @code{base}.
1.26 crook 7673: @end itemize
1.1 anton 7674:
1.49 anton 7675: You can read numbers into your programs with the words described in
7676: @ref{Input}.
1.1 anton 7677:
1.82 anton 7678: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7679: @subsection Interpret/Compile states
7680: @cindex Interpret/Compile states
1.1 anton 7681:
1.29 crook 7682: A standard program is not permitted to change @code{state}
7683: explicitly. However, it can change @code{state} implicitly, using the
7684: words @code{[} and @code{]}. When @code{[} is executed it switches
7685: @code{state} to interpret state, and therefore the text interpreter
7686: starts interpreting. When @code{]} is executed it switches @code{state}
7687: to compile state and therefore the text interpreter starts
1.44 crook 7688: compiling. The most common usage for these words is for switching into
7689: interpret state and back from within a colon definition; this technique
1.49 anton 7690: can be used to compile a literal (for an example, @pxref{Literals}) or
7691: for conditional compilation (for an example, @pxref{Interpreter
7692: Directives}).
1.44 crook 7693:
1.35 anton 7694:
7695: @c This is a bad example: It's non-standard, and it's not necessary.
7696: @c However, I can't think of a good example for switching into compile
7697: @c state when there is no current word (@code{state}-smart words are not a
7698: @c good reason). So maybe we should use an example for switching into
7699: @c interpret @code{state} in a colon def. - anton
1.44 crook 7700: @c nac-> I agree. I started out by putting in the example, then realised
7701: @c that it was non-ANS, so wrote more words around it. I hope this
7702: @c re-written version is acceptable to you. I do want to keep the example
7703: @c as it is helpful for showing what is and what is not portable, particularly
7704: @c where it outlaws a style in common use.
7705:
1.72 anton 7706: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7707: @c that, we can also show what's not. In any case, I have written a
7708: @c section Compiling Words which also deals with [ ].
1.35 anton 7709:
1.95 anton 7710: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7711:
1.95 anton 7712: @c @code{[} and @code{]} also give you the ability to switch into compile
7713: @c state and back, but we cannot think of any useful Standard application
7714: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7715:
7716: @c @example
7717: @c : AA ." this is A" ;
7718: @c : BB ." this is B" ;
7719: @c : CC ." this is C" ;
7720:
7721: @c create table ] aa bb cc [
7722:
7723: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7724: @c cells table + @@ execute ;
7725: @c @end example
7726:
7727: @c This example builds a jump table; @code{0 go} will display ``@code{this
7728: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7729: @c defining @code{table} like this:
7730:
7731: @c @example
7732: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7733: @c @end example
7734:
7735: @c The problem with this code is that the definition of @code{table} is not
7736: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7737: @c @i{may} work on systems where code space and data space co-incide, the
7738: @c Standard only allows data space to be assigned for a @code{CREATE}d
7739: @c word. In addition, the Standard only allows @code{@@} to access data
7740: @c space, whilst this example is using it to access code space. The only
7741: @c portable, Standard way to build this table is to build it in data space,
7742: @c like this:
7743:
7744: @c @example
7745: @c create table ' aa , ' bb , ' cc ,
7746: @c @end example
1.29 crook 7747:
1.95 anton 7748: @c doc-state
1.44 crook 7749:
1.29 crook 7750:
1.82 anton 7751: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7752: @subsection Interpreter Directives
7753: @cindex interpreter directives
1.72 anton 7754: @cindex conditional compilation
1.1 anton 7755:
1.29 crook 7756: These words are usually used in interpret state; typically to control
7757: which parts of a source file are processed by the text
1.26 crook 7758: interpreter. There are only a few ANS Forth Standard words, but Gforth
7759: supplements these with a rich set of immediate control structure words
7760: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7761: used in compile state (@pxref{Control Structures}). Typical usages:
7762:
7763: @example
1.72 anton 7764: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7765: .
7766: .
1.72 anton 7767: HAVE-ASSEMBLER [IF]
1.29 crook 7768: : ASSEMBLER-FEATURE
7769: ...
7770: ;
7771: [ENDIF]
7772: .
7773: .
7774: : SEE
7775: ... \ general-purpose SEE code
1.72 anton 7776: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7777: ... \ assembler-specific SEE code
7778: [ [ENDIF] ]
7779: ;
7780: @end example
1.1 anton 7781:
1.44 crook 7782:
1.26 crook 7783: doc-[IF]
7784: doc-[ELSE]
7785: doc-[THEN]
7786: doc-[ENDIF]
1.1 anton 7787:
1.26 crook 7788: doc-[IFDEF]
7789: doc-[IFUNDEF]
1.1 anton 7790:
1.26 crook 7791: doc-[?DO]
7792: doc-[DO]
7793: doc-[FOR]
7794: doc-[LOOP]
7795: doc-[+LOOP]
7796: doc-[NEXT]
1.1 anton 7797:
1.26 crook 7798: doc-[BEGIN]
7799: doc-[UNTIL]
7800: doc-[AGAIN]
7801: doc-[WHILE]
7802: doc-[REPEAT]
1.1 anton 7803:
1.27 crook 7804:
1.26 crook 7805: @c -------------------------------------------------------------
1.111 anton 7806: @node The Input Stream, Word Lists, The Text Interpreter, Words
7807: @section The Input Stream
7808: @cindex input stream
7809:
7810: @c !! integrate this better with the "Text Interpreter" section
7811: The text interpreter reads from the input stream, which can come from
7812: several sources (@pxref{Input Sources}). Some words, in particular
7813: defining words, but also words like @code{'}, read parameters from the
7814: input stream instead of from the stack.
7815:
7816: Such words are called parsing words, because they parse the input
7817: stream. Parsing words are hard to use in other words, because it is
7818: hard to pass program-generated parameters through the input stream.
7819: They also usually have an unintuitive combination of interpretation and
7820: compilation semantics when implemented naively, leading to various
7821: approaches that try to produce a more intuitive behaviour
7822: (@pxref{Combined words}).
7823:
7824: It should be obvious by now that parsing words are a bad idea. If you
7825: want to implement a parsing word for convenience, also provide a factor
7826: of the word that does not parse, but takes the parameters on the stack.
7827: To implement the parsing word on top if it, you can use the following
7828: words:
7829:
7830: @c anton: these belong in the input stream section
7831: doc-parse
1.138 anton 7832: doc-parse-name
1.111 anton 7833: doc-parse-word
7834: doc-name
7835: doc-word
7836: doc-\"-parse
7837: doc-refill
7838:
7839: Conversely, if you have the bad luck (or lack of foresight) to have to
7840: deal with parsing words without having such factors, how do you pass a
7841: string that is not in the input stream to it?
7842:
7843: doc-execute-parsing
7844:
7845: If you want to run a parsing word on a file, the following word should
7846: help:
7847:
7848: doc-execute-parsing-file
7849:
7850: @c -------------------------------------------------------------
7851: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7852: @section Word Lists
7853: @cindex word lists
1.32 anton 7854: @cindex header space
1.1 anton 7855:
1.36 anton 7856: A wordlist is a list of named words; you can add new words and look up
7857: words by name (and you can remove words in a restricted way with
7858: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7859:
7860: @cindex search order stack
7861: The text interpreter searches the wordlists present in the search order
7862: (a stack of wordlists), from the top to the bottom. Within each
7863: wordlist, the search starts conceptually at the newest word; i.e., if
7864: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7865:
1.26 crook 7866: @cindex compilation word list
1.36 anton 7867: New words are added to the @dfn{compilation wordlist} (aka current
7868: wordlist).
1.1 anton 7869:
1.36 anton 7870: @cindex wid
7871: A word list is identified by a cell-sized word list identifier (@i{wid})
7872: in much the same way as a file is identified by a file handle. The
7873: numerical value of the wid has no (portable) meaning, and might change
7874: from session to session.
1.1 anton 7875:
1.29 crook 7876: The ANS Forth ``Search order'' word set is intended to provide a set of
7877: low-level tools that allow various different schemes to be
1.74 anton 7878: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7879: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7880: Forth.
1.1 anton 7881:
1.27 crook 7882: @comment TODO: locals section refers to here, saying that every word list (aka
7883: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7884: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7885:
1.45 crook 7886: @comment TODO: document markers, reveal, tables, mappedwordlist
7887:
7888: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7889: @comment word from the source files, rather than some alias.
1.44 crook 7890:
1.26 crook 7891: doc-forth-wordlist
7892: doc-definitions
7893: doc-get-current
7894: doc-set-current
7895: doc-get-order
1.45 crook 7896: doc---gforthman-set-order
1.26 crook 7897: doc-wordlist
1.30 anton 7898: doc-table
1.79 anton 7899: doc->order
1.36 anton 7900: doc-previous
1.26 crook 7901: doc-also
1.45 crook 7902: doc---gforthman-forth
1.26 crook 7903: doc-only
1.45 crook 7904: doc---gforthman-order
1.15 anton 7905:
1.26 crook 7906: doc-find
7907: doc-search-wordlist
1.15 anton 7908:
1.26 crook 7909: doc-words
7910: doc-vlist
1.44 crook 7911: @c doc-words-deferred
1.1 anton 7912:
1.74 anton 7913: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7914: doc-root
7915: doc-vocabulary
7916: doc-seal
7917: doc-vocs
7918: doc-current
7919: doc-context
1.1 anton 7920:
1.44 crook 7921:
1.26 crook 7922: @menu
1.75 anton 7923: * Vocabularies::
1.67 anton 7924: * Why use word lists?::
1.75 anton 7925: * Word list example::
1.26 crook 7926: @end menu
7927:
1.75 anton 7928: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7929: @subsection Vocabularies
7930: @cindex Vocabularies, detailed explanation
7931:
7932: Here is an example of creating and using a new wordlist using ANS
7933: Forth words:
7934:
7935: @example
7936: wordlist constant my-new-words-wordlist
7937: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7938:
7939: \ add it to the search order
7940: also my-new-words
7941:
7942: \ alternatively, add it to the search order and make it
7943: \ the compilation word list
7944: also my-new-words definitions
7945: \ type "order" to see the problem
7946: @end example
7947:
7948: The problem with this example is that @code{order} has no way to
7949: associate the name @code{my-new-words} with the wid of the word list (in
7950: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7951: that has no associated name). There is no Standard way of associating a
7952: name with a wid.
7953:
7954: In Gforth, this example can be re-coded using @code{vocabulary}, which
7955: associates a name with a wid:
7956:
7957: @example
7958: vocabulary my-new-words
7959:
7960: \ add it to the search order
7961: also my-new-words
7962:
7963: \ alternatively, add it to the search order and make it
7964: \ the compilation word list
7965: my-new-words definitions
7966: \ type "order" to see that the problem is solved
7967: @end example
7968:
7969:
7970: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7971: @subsection Why use word lists?
7972: @cindex word lists - why use them?
7973:
1.74 anton 7974: Here are some reasons why people use wordlists:
1.26 crook 7975:
7976: @itemize @bullet
1.74 anton 7977:
7978: @c anton: Gforth's hashing implementation makes the search speed
7979: @c independent from the number of words. But it is linear with the number
7980: @c of wordlists that have to be searched, so in effect using more wordlists
7981: @c actually slows down compilation.
7982:
7983: @c @item
7984: @c To improve compilation speed by reducing the number of header space
7985: @c entries that must be searched. This is achieved by creating a new
7986: @c word list that contains all of the definitions that are used in the
7987: @c definition of a Forth system but which would not usually be used by
7988: @c programs running on that system. That word list would be on the search
7989: @c list when the Forth system was compiled but would be removed from the
7990: @c search list for normal operation. This can be a useful technique for
7991: @c low-performance systems (for example, 8-bit processors in embedded
7992: @c systems) but is unlikely to be necessary in high-performance desktop
7993: @c systems.
7994:
1.26 crook 7995: @item
7996: To prevent a set of words from being used outside the context in which
7997: they are valid. Two classic examples of this are an integrated editor
7998: (all of the edit commands are defined in a separate word list; the
7999: search order is set to the editor word list when the editor is invoked;
8000: the old search order is restored when the editor is terminated) and an
8001: integrated assembler (the op-codes for the machine are defined in a
8002: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8003:
8004: @item
8005: To organize the words of an application or library into a user-visible
8006: set (in @code{forth-wordlist} or some other common wordlist) and a set
8007: of helper words used just for the implementation (hidden in a separate
1.75 anton 8008: wordlist). This keeps @code{words}' output smaller, separates
8009: implementation and interface, and reduces the chance of name conflicts
8010: within the common wordlist.
1.74 anton 8011:
1.26 crook 8012: @item
8013: To prevent a name-space clash between multiple definitions with the same
8014: name. For example, when building a cross-compiler you might have a word
8015: @code{IF} that generates conditional code for your target system. By
8016: placing this definition in a different word list you can control whether
8017: the host system's @code{IF} or the target system's @code{IF} get used in
8018: any particular context by controlling the order of the word lists on the
8019: search order stack.
1.74 anton 8020:
1.26 crook 8021: @end itemize
1.1 anton 8022:
1.74 anton 8023: The downsides of using wordlists are:
8024:
8025: @itemize
8026:
8027: @item
8028: Debugging becomes more cumbersome.
8029:
8030: @item
8031: Name conflicts worked around with wordlists are still there, and you
8032: have to arrange the search order carefully to get the desired results;
8033: if you forget to do that, you get hard-to-find errors (as in any case
8034: where you read the code differently from the compiler; @code{see} can
1.75 anton 8035: help seeing which of several possible words the name resolves to in such
8036: cases). @code{See} displays just the name of the words, not what
8037: wordlist they belong to, so it might be misleading. Using unique names
8038: is a better approach to avoid name conflicts.
1.74 anton 8039:
8040: @item
8041: You have to explicitly undo any changes to the search order. In many
8042: cases it would be more convenient if this happened implicitly. Gforth
8043: currently does not provide such a feature, but it may do so in the
8044: future.
8045: @end itemize
8046:
8047:
1.75 anton 8048: @node Word list example, , Why use word lists?, Word Lists
8049: @subsection Word list example
8050: @cindex word lists - example
1.1 anton 8051:
1.74 anton 8052: The following example is from the
8053: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8054: garbage collector} and uses wordlists to separate public words from
8055: helper words:
8056:
8057: @example
8058: get-current ( wid )
8059: vocabulary garbage-collector also garbage-collector definitions
8060: ... \ define helper words
8061: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8062: ... \ define the public (i.e., API) words
8063: \ they can refer to the helper words
8064: previous \ restore original search order (helper words become invisible)
8065: @end example
8066:
1.26 crook 8067: @c -------------------------------------------------------------
8068: @node Environmental Queries, Files, Word Lists, Words
8069: @section Environmental Queries
8070: @cindex environmental queries
1.21 crook 8071:
1.26 crook 8072: ANS Forth introduced the idea of ``environmental queries'' as a way
8073: for a program running on a system to determine certain characteristics of the system.
8074: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8075:
1.32 anton 8076: The Standard requires that the header space used for environmental queries
8077: be distinct from the header space used for definitions.
1.21 crook 8078:
1.26 crook 8079: Typically, environmental queries are supported by creating a set of
1.29 crook 8080: definitions in a word list that is @i{only} used during environmental
1.26 crook 8081: queries; that is what Gforth does. There is no Standard way of adding
8082: definitions to the set of recognised environmental queries, but any
8083: implementation that supports the loading of optional word sets must have
8084: some mechanism for doing this (after loading the word set, the
8085: associated environmental query string must return @code{true}). In
8086: Gforth, the word list used to honour environmental queries can be
8087: manipulated just like any other word list.
1.21 crook 8088:
1.44 crook 8089:
1.26 crook 8090: doc-environment?
8091: doc-environment-wordlist
1.21 crook 8092:
1.26 crook 8093: doc-gforth
8094: doc-os-class
1.21 crook 8095:
1.44 crook 8096:
1.26 crook 8097: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8098: returning two items on the stack, querying it using @code{environment?}
8099: will return an additional item; the @code{true} flag that shows that the
8100: string was recognised.
1.21 crook 8101:
1.26 crook 8102: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8103:
1.26 crook 8104: Here are some examples of using environmental queries:
1.21 crook 8105:
1.26 crook 8106: @example
8107: s" address-unit-bits" environment? 0=
8108: [IF]
8109: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8110: [ELSE]
8111: drop \ ensure balanced stack effect
1.26 crook 8112: [THEN]
1.21 crook 8113:
1.75 anton 8114: \ this might occur in the prelude of a standard program that uses THROW
8115: s" exception" environment? [IF]
8116: 0= [IF]
8117: : throw abort" exception thrown" ;
8118: [THEN]
8119: [ELSE] \ we don't know, so make sure
8120: : throw abort" exception thrown" ;
8121: [THEN]
1.21 crook 8122:
1.26 crook 8123: s" gforth" environment? [IF] .( Gforth version ) TYPE
8124: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8125:
8126: \ a program using v*
8127: s" gforth" environment? [IF]
8128: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8129: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8130: >r swap 2swap swap 0e r> 0 ?DO
8131: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8132: LOOP
8133: 2drop 2drop ;
8134: [THEN]
8135: [ELSE] \
8136: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8137: ...
8138: [THEN]
1.26 crook 8139: @end example
1.21 crook 8140:
1.26 crook 8141: Here is an example of adding a definition to the environment word list:
1.21 crook 8142:
1.26 crook 8143: @example
8144: get-current environment-wordlist set-current
8145: true constant block
8146: true constant block-ext
8147: set-current
8148: @end example
1.21 crook 8149:
1.26 crook 8150: You can see what definitions are in the environment word list like this:
1.21 crook 8151:
1.26 crook 8152: @example
1.79 anton 8153: environment-wordlist >order words previous
1.26 crook 8154: @end example
1.21 crook 8155:
8156:
1.26 crook 8157: @c -------------------------------------------------------------
8158: @node Files, Blocks, Environmental Queries, Words
8159: @section Files
1.28 crook 8160: @cindex files
8161: @cindex I/O - file-handling
1.21 crook 8162:
1.26 crook 8163: Gforth provides facilities for accessing files that are stored in the
8164: host operating system's file-system. Files that are processed by Gforth
8165: can be divided into two categories:
1.21 crook 8166:
1.23 crook 8167: @itemize @bullet
8168: @item
1.29 crook 8169: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8170: @item
1.29 crook 8171: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8172: @end itemize
8173:
8174: @menu
1.48 anton 8175: * Forth source files::
8176: * General files::
8177: * Search Paths::
1.26 crook 8178: @end menu
8179:
8180: @c -------------------------------------------------------------
8181: @node Forth source files, General files, Files, Files
8182: @subsection Forth source files
8183: @cindex including files
8184: @cindex Forth source files
1.21 crook 8185:
1.26 crook 8186: The simplest way to interpret the contents of a file is to use one of
8187: these two formats:
1.21 crook 8188:
1.26 crook 8189: @example
8190: include mysource.fs
8191: s" mysource.fs" included
8192: @end example
1.21 crook 8193:
1.75 anton 8194: You usually want to include a file only if it is not included already
1.26 crook 8195: (by, say, another source file). In that case, you can use one of these
1.45 crook 8196: three formats:
1.21 crook 8197:
1.26 crook 8198: @example
8199: require mysource.fs
8200: needs mysource.fs
8201: s" mysource.fs" required
8202: @end example
1.21 crook 8203:
1.26 crook 8204: @cindex stack effect of included files
8205: @cindex including files, stack effect
1.45 crook 8206: It is good practice to write your source files such that interpreting them
8207: does not change the stack. Source files designed in this way can be used with
1.26 crook 8208: @code{required} and friends without complications. For example:
1.21 crook 8209:
1.26 crook 8210: @example
1.75 anton 8211: 1024 require foo.fs drop
1.26 crook 8212: @end example
1.21 crook 8213:
1.75 anton 8214: Here you want to pass the argument 1024 (e.g., a buffer size) to
8215: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8216: ), which allows its use with @code{require}. Of course with such
8217: parameters to required files, you have to ensure that the first
8218: @code{require} fits for all uses (i.e., @code{require} it early in the
8219: master load file).
1.44 crook 8220:
1.26 crook 8221: doc-include-file
8222: doc-included
1.28 crook 8223: doc-included?
1.26 crook 8224: doc-include
8225: doc-required
8226: doc-require
8227: doc-needs
1.75 anton 8228: @c doc-init-included-files @c internal
8229: doc-sourcefilename
8230: doc-sourceline#
1.44 crook 8231:
1.26 crook 8232: A definition in ANS Forth for @code{required} is provided in
8233: @file{compat/required.fs}.
1.21 crook 8234:
1.26 crook 8235: @c -------------------------------------------------------------
8236: @node General files, Search Paths, Forth source files, Files
8237: @subsection General files
8238: @cindex general files
8239: @cindex file-handling
1.21 crook 8240:
1.75 anton 8241: Files are opened/created by name and type. The following file access
8242: methods (FAMs) are recognised:
1.44 crook 8243:
1.75 anton 8244: @cindex fam (file access method)
1.26 crook 8245: doc-r/o
8246: doc-r/w
8247: doc-w/o
8248: doc-bin
1.1 anton 8249:
1.44 crook 8250:
1.26 crook 8251: When a file is opened/created, it returns a file identifier,
1.29 crook 8252: @i{wfileid} that is used for all other file commands. All file
8253: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8254: successful operation and an implementation-defined non-zero value in the
8255: case of an error.
1.21 crook 8256:
1.44 crook 8257:
1.26 crook 8258: doc-open-file
8259: doc-create-file
1.21 crook 8260:
1.26 crook 8261: doc-close-file
8262: doc-delete-file
8263: doc-rename-file
8264: doc-read-file
8265: doc-read-line
8266: doc-write-file
8267: doc-write-line
8268: doc-emit-file
8269: doc-flush-file
1.21 crook 8270:
1.26 crook 8271: doc-file-status
8272: doc-file-position
8273: doc-reposition-file
8274: doc-file-size
8275: doc-resize-file
1.21 crook 8276:
1.93 anton 8277: doc-slurp-file
8278: doc-slurp-fid
1.112 anton 8279: doc-stdin
8280: doc-stdout
8281: doc-stderr
1.44 crook 8282:
1.26 crook 8283: @c ---------------------------------------------------------
1.48 anton 8284: @node Search Paths, , General files, Files
1.26 crook 8285: @subsection Search Paths
8286: @cindex path for @code{included}
8287: @cindex file search path
8288: @cindex @code{include} search path
8289: @cindex search path for files
1.21 crook 8290:
1.26 crook 8291: If you specify an absolute filename (i.e., a filename starting with
8292: @file{/} or @file{~}, or with @file{:} in the second position (as in
8293: @samp{C:...})) for @code{included} and friends, that file is included
8294: just as you would expect.
1.21 crook 8295:
1.75 anton 8296: If the filename starts with @file{./}, this refers to the directory that
8297: the present file was @code{included} from. This allows files to include
8298: other files relative to their own position (irrespective of the current
8299: working directory or the absolute position). This feature is essential
8300: for libraries consisting of several files, where a file may include
8301: other files from the library. It corresponds to @code{#include "..."}
8302: in C. If the current input source is not a file, @file{.} refers to the
8303: directory of the innermost file being included, or, if there is no file
8304: being included, to the current working directory.
8305:
8306: For relative filenames (not starting with @file{./}), Gforth uses a
8307: search path similar to Forth's search order (@pxref{Word Lists}). It
8308: tries to find the given filename in the directories present in the path,
8309: and includes the first one it finds. There are separate search paths for
8310: Forth source files and general files. If the search path contains the
8311: directory @file{.}, this refers to the directory of the current file, or
8312: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8313:
1.26 crook 8314: Use @file{~+} to refer to the current working directory (as in the
8315: @code{bash}).
1.1 anton 8316:
1.75 anton 8317: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8318:
1.48 anton 8319: @menu
1.75 anton 8320: * Source Search Paths::
1.48 anton 8321: * General Search Paths::
8322: @end menu
8323:
1.26 crook 8324: @c ---------------------------------------------------------
1.75 anton 8325: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8326: @subsubsection Source Search Paths
8327: @cindex search path control, source files
1.5 anton 8328:
1.26 crook 8329: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8330: Gforth}). You can display it and change it using @code{fpath} in
8331: combination with the general path handling words.
1.5 anton 8332:
1.75 anton 8333: doc-fpath
8334: @c the functionality of the following words is easily available through
8335: @c fpath and the general path words. The may go away.
8336: @c doc-.fpath
8337: @c doc-fpath+
8338: @c doc-fpath=
8339: @c doc-open-fpath-file
1.44 crook 8340:
8341: @noindent
1.26 crook 8342: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8343:
1.26 crook 8344: @example
1.75 anton 8345: fpath path= /usr/lib/forth/|./
1.26 crook 8346: require timer.fs
8347: @end example
1.5 anton 8348:
1.75 anton 8349:
1.26 crook 8350: @c ---------------------------------------------------------
1.75 anton 8351: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8352: @subsubsection General Search Paths
1.75 anton 8353: @cindex search path control, source files
1.5 anton 8354:
1.26 crook 8355: Your application may need to search files in several directories, like
8356: @code{included} does. To facilitate this, Gforth allows you to define
8357: and use your own search paths, by providing generic equivalents of the
8358: Forth search path words:
1.5 anton 8359:
1.75 anton 8360: doc-open-path-file
8361: doc-path-allot
8362: doc-clear-path
8363: doc-also-path
1.26 crook 8364: doc-.path
8365: doc-path+
8366: doc-path=
1.5 anton 8367:
1.75 anton 8368: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8369:
1.75 anton 8370: Here's an example of creating an empty search path:
8371: @c
1.26 crook 8372: @example
1.75 anton 8373: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8374: @end example
1.5 anton 8375:
1.26 crook 8376: @c -------------------------------------------------------------
8377: @node Blocks, Other I/O, Files, Words
8378: @section Blocks
1.28 crook 8379: @cindex I/O - blocks
8380: @cindex blocks
8381:
8382: When you run Gforth on a modern desk-top computer, it runs under the
8383: control of an operating system which provides certain services. One of
8384: these services is @var{file services}, which allows Forth source code
8385: and data to be stored in files and read into Gforth (@pxref{Files}).
8386:
8387: Traditionally, Forth has been an important programming language on
8388: systems where it has interfaced directly to the underlying hardware with
8389: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8390: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8391:
8392: A block is a 1024-byte data area, which can be used to hold data or
8393: Forth source code. No structure is imposed on the contents of the
8394: block. A block is identified by its number; blocks are numbered
8395: contiguously from 1 to an implementation-defined maximum.
8396:
8397: A typical system that used blocks but no operating system might use a
8398: single floppy-disk drive for mass storage, with the disks formatted to
8399: provide 256-byte sectors. Blocks would be implemented by assigning the
8400: first four sectors of the disk to block 1, the second four sectors to
8401: block 2 and so on, up to the limit of the capacity of the disk. The disk
8402: would not contain any file system information, just the set of blocks.
8403:
1.29 crook 8404: @cindex blocks file
1.28 crook 8405: On systems that do provide file services, blocks are typically
1.29 crook 8406: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8407: file}. The size of the blocks file will be an exact multiple of 1024
8408: bytes, corresponding to the number of blocks it contains. This is the
8409: mechanism that Gforth uses.
8410:
1.29 crook 8411: @cindex @file{blocks.fb}
1.75 anton 8412: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8413: having specified a blocks file, Gforth defaults to the blocks file
8414: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8415: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8416:
1.29 crook 8417: @cindex block buffers
1.28 crook 8418: When you read and write blocks under program control, Gforth uses a
1.29 crook 8419: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8420: not used when you use @code{load} to interpret the contents of a block.
8421:
1.75 anton 8422: The behaviour of the block buffers is analagous to that of a cache.
8423: Each block buffer has three states:
1.28 crook 8424:
8425: @itemize @bullet
8426: @item
8427: Unassigned
8428: @item
8429: Assigned-clean
8430: @item
8431: Assigned-dirty
8432: @end itemize
8433:
1.29 crook 8434: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8435: block, the block (specified by its block number) must be assigned to a
8436: block buffer.
8437:
8438: The assignment of a block to a block buffer is performed by @code{block}
8439: or @code{buffer}. Use @code{block} when you wish to modify the existing
8440: contents of a block. Use @code{buffer} when you don't care about the
8441: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8442: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8443: with the particular block is already stored in a block buffer due to an
8444: earlier @code{block} command, @code{buffer} will return that block
8445: buffer and the existing contents of the block will be
8446: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8447: block buffer for the block.}.
1.28 crook 8448:
1.47 crook 8449: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8450: @code{buffer}, that block buffer becomes the @i{current block
8451: buffer}. Data may only be manipulated (read or written) within the
8452: current block buffer.
1.47 crook 8453:
8454: When the contents of the current block buffer has been modified it is
1.48 anton 8455: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8456: either abandon the changes (by doing nothing) or mark the block as
8457: changed (assigned-dirty), using @code{update}. Using @code{update} does
8458: not change the blocks file; it simply changes a block buffer's state to
8459: @i{assigned-dirty}. The block will be written implicitly when it's
8460: buffer is needed for another block, or explicitly by @code{flush} or
8461: @code{save-buffers}.
8462:
8463: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8464: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8465: @code{flush}.
1.28 crook 8466:
1.29 crook 8467: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8468: algorithm to assign a block buffer to a block. That means that any
8469: particular block can only be assigned to one specific block buffer,
1.29 crook 8470: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8471: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8472: the new block immediately. If it is @i{assigned-dirty} its current
8473: contents are written back to the blocks file on disk before it is
1.28 crook 8474: allocated to the new block.
8475:
8476: Although no structure is imposed on the contents of a block, it is
8477: traditional to display the contents as 16 lines each of 64 characters. A
8478: block provides a single, continuous stream of input (for example, it
8479: acts as a single parse area) -- there are no end-of-line characters
8480: within a block, and no end-of-file character at the end of a
8481: block. There are two consequences of this:
1.26 crook 8482:
1.28 crook 8483: @itemize @bullet
8484: @item
8485: The last character of one line wraps straight into the first character
8486: of the following line
8487: @item
8488: The word @code{\} -- comment to end of line -- requires special
8489: treatment; in the context of a block it causes all characters until the
8490: end of the current 64-character ``line'' to be ignored.
8491: @end itemize
8492:
8493: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8494: the current blocks file will be extended to the appropriate size and the
1.28 crook 8495: block buffer will be initialised with spaces.
8496:
1.47 crook 8497: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8498: for details) but doesn't encourage the use of blocks; the mechanism is
8499: only provided for backward compatibility -- ANS Forth requires blocks to
8500: be available when files are.
1.28 crook 8501:
8502: Common techniques that are used when working with blocks include:
8503:
8504: @itemize @bullet
8505: @item
8506: A screen editor that allows you to edit blocks without leaving the Forth
8507: environment.
8508: @item
8509: Shadow screens; where every code block has an associated block
8510: containing comments (for example: code in odd block numbers, comments in
8511: even block numbers). Typically, the block editor provides a convenient
8512: mechanism to toggle between code and comments.
8513: @item
8514: Load blocks; a single block (typically block 1) contains a number of
8515: @code{thru} commands which @code{load} the whole of the application.
8516: @end itemize
1.26 crook 8517:
1.29 crook 8518: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8519: integrated into a Forth programming environment.
1.26 crook 8520:
8521: @comment TODO what about errors on open-blocks?
1.44 crook 8522:
1.26 crook 8523: doc-open-blocks
8524: doc-use
1.75 anton 8525: doc-block-offset
1.26 crook 8526: doc-get-block-fid
8527: doc-block-position
1.28 crook 8528:
1.75 anton 8529: doc-list
1.28 crook 8530: doc-scr
8531:
1.45 crook 8532: doc---gforthman-block
1.28 crook 8533: doc-buffer
8534:
1.75 anton 8535: doc-empty-buffers
8536: doc-empty-buffer
1.26 crook 8537: doc-update
1.28 crook 8538: doc-updated?
1.26 crook 8539: doc-save-buffers
1.75 anton 8540: doc-save-buffer
1.26 crook 8541: doc-flush
1.28 crook 8542:
1.26 crook 8543: doc-load
8544: doc-thru
8545: doc-+load
8546: doc-+thru
1.45 crook 8547: doc---gforthman--->
1.26 crook 8548: doc-block-included
8549:
1.44 crook 8550:
1.26 crook 8551: @c -------------------------------------------------------------
1.126 pazsan 8552: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8553: @section Other I/O
1.28 crook 8554: @cindex I/O - keyboard and display
1.26 crook 8555:
8556: @menu
8557: * Simple numeric output:: Predefined formats
8558: * Formatted numeric output:: Formatted (pictured) output
8559: * String Formats:: How Forth stores strings in memory
1.67 anton 8560: * Displaying characters and strings:: Other stuff
1.26 crook 8561: * Input:: Input
1.112 anton 8562: * Pipes:: How to create your own pipes
1.26 crook 8563: @end menu
8564:
8565: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8566: @subsection Simple numeric output
1.28 crook 8567: @cindex numeric output - simple/free-format
1.5 anton 8568:
1.26 crook 8569: The simplest output functions are those that display numbers from the
8570: data or floating-point stacks. Floating-point output is always displayed
8571: using base 10. Numbers displayed from the data stack use the value stored
8572: in @code{base}.
1.5 anton 8573:
1.44 crook 8574:
1.26 crook 8575: doc-.
8576: doc-dec.
8577: doc-hex.
8578: doc-u.
8579: doc-.r
8580: doc-u.r
8581: doc-d.
8582: doc-ud.
8583: doc-d.r
8584: doc-ud.r
8585: doc-f.
8586: doc-fe.
8587: doc-fs.
1.111 anton 8588: doc-f.rdp
1.44 crook 8589:
1.26 crook 8590: Examples of printing the number 1234.5678E23 in the different floating-point output
8591: formats are shown below:
1.5 anton 8592:
8593: @example
1.26 crook 8594: f. 123456779999999000000000000.
8595: fe. 123.456779999999E24
8596: fs. 1.23456779999999E26
1.5 anton 8597: @end example
8598:
8599:
1.26 crook 8600: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8601: @subsection Formatted numeric output
1.28 crook 8602: @cindex formatted numeric output
1.26 crook 8603: @cindex pictured numeric output
1.28 crook 8604: @cindex numeric output - formatted
1.26 crook 8605:
1.29 crook 8606: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8607: output} for formatted printing of integers. In this technique, digits
8608: are extracted from the number (using the current output radix defined by
8609: @code{base}), converted to ASCII codes and appended to a string that is
8610: built in a scratch-pad area of memory (@pxref{core-idef,
8611: Implementation-defined options, Implementation-defined
8612: options}). Arbitrary characters can be appended to the string during the
8613: extraction process. The completed string is specified by an address
8614: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8615: under program control.
1.5 anton 8616:
1.75 anton 8617: All of the integer output words described in the previous section
8618: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8619: numeric output.
1.5 anton 8620:
1.47 crook 8621: Three important things to remember about pictured numeric output:
1.5 anton 8622:
1.26 crook 8623: @itemize @bullet
8624: @item
1.28 crook 8625: It always operates on double-precision numbers; to display a
1.49 anton 8626: single-precision number, convert it first (for ways of doing this
8627: @pxref{Double precision}).
1.26 crook 8628: @item
1.28 crook 8629: It always treats the double-precision number as though it were
8630: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8631: @item
8632: The string is built up from right to left; least significant digit first.
8633: @end itemize
1.5 anton 8634:
1.44 crook 8635:
1.26 crook 8636: doc-<#
1.47 crook 8637: doc-<<#
1.26 crook 8638: doc-#
8639: doc-#s
8640: doc-hold
8641: doc-sign
8642: doc-#>
1.47 crook 8643: doc-#>>
1.5 anton 8644:
1.26 crook 8645: doc-represent
1.111 anton 8646: doc-f>str-rdp
8647: doc-f>buf-rdp
1.5 anton 8648:
1.44 crook 8649:
8650: @noindent
1.26 crook 8651: Here are some examples of using pictured numeric output:
1.5 anton 8652:
8653: @example
1.26 crook 8654: : my-u. ( u -- )
8655: \ Simplest use of pns.. behaves like Standard u.
8656: 0 \ convert to unsigned double
1.75 anton 8657: <<# \ start conversion
1.26 crook 8658: #s \ convert all digits
8659: #> \ complete conversion
1.75 anton 8660: TYPE SPACE \ display, with trailing space
8661: #>> ; \ release hold area
1.5 anton 8662:
1.26 crook 8663: : cents-only ( u -- )
8664: 0 \ convert to unsigned double
1.75 anton 8665: <<# \ start conversion
1.26 crook 8666: # # \ convert two least-significant digits
8667: #> \ complete conversion, discard other digits
1.75 anton 8668: TYPE SPACE \ display, with trailing space
8669: #>> ; \ release hold area
1.5 anton 8670:
1.26 crook 8671: : dollars-and-cents ( u -- )
8672: 0 \ convert to unsigned double
1.75 anton 8673: <<# \ start conversion
1.26 crook 8674: # # \ convert two least-significant digits
8675: [char] . hold \ insert decimal point
8676: #s \ convert remaining digits
8677: [char] $ hold \ append currency symbol
8678: #> \ complete conversion
1.75 anton 8679: TYPE SPACE \ display, with trailing space
8680: #>> ; \ release hold area
1.5 anton 8681:
1.26 crook 8682: : my-. ( n -- )
8683: \ handling negatives.. behaves like Standard .
8684: s>d \ convert to signed double
8685: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8686: <<# \ start conversion
1.26 crook 8687: #s \ convert all digits
8688: rot sign \ get at sign byte, append "-" if needed
8689: #> \ complete conversion
1.75 anton 8690: TYPE SPACE \ display, with trailing space
8691: #>> ; \ release hold area
1.5 anton 8692:
1.26 crook 8693: : account. ( n -- )
1.75 anton 8694: \ accountants don't like minus signs, they use parentheses
1.26 crook 8695: \ for negative numbers
8696: s>d \ convert to signed double
8697: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8698: <<# \ start conversion
1.26 crook 8699: 2 pick \ get copy of sign byte
8700: 0< IF [char] ) hold THEN \ right-most character of output
8701: #s \ convert all digits
8702: rot \ get at sign byte
8703: 0< IF [char] ( hold THEN
8704: #> \ complete conversion
1.75 anton 8705: TYPE SPACE \ display, with trailing space
8706: #>> ; \ release hold area
8707:
1.5 anton 8708: @end example
8709:
1.26 crook 8710: Here are some examples of using these words:
1.5 anton 8711:
8712: @example
1.26 crook 8713: 1 my-u. 1
8714: hex -1 my-u. decimal FFFFFFFF
8715: 1 cents-only 01
8716: 1234 cents-only 34
8717: 2 dollars-and-cents $0.02
8718: 1234 dollars-and-cents $12.34
8719: 123 my-. 123
8720: -123 my. -123
8721: 123 account. 123
8722: -456 account. (456)
1.5 anton 8723: @end example
8724:
8725:
1.26 crook 8726: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8727: @subsection String Formats
1.27 crook 8728: @cindex strings - see character strings
8729: @cindex character strings - formats
1.28 crook 8730: @cindex I/O - see character strings
1.75 anton 8731: @cindex counted strings
8732:
8733: @c anton: this does not really belong here; maybe the memory section,
8734: @c or the principles chapter
1.26 crook 8735:
1.27 crook 8736: Forth commonly uses two different methods for representing character
8737: strings:
1.26 crook 8738:
8739: @itemize @bullet
8740: @item
8741: @cindex address of counted string
1.45 crook 8742: @cindex counted string
1.29 crook 8743: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8744: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8745: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8746: memory.
8747: @item
1.29 crook 8748: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8749: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8750: first byte of the string.
8751: @end itemize
8752:
8753: ANS Forth encourages the use of the second format when representing
1.75 anton 8754: strings.
1.26 crook 8755:
1.44 crook 8756:
1.26 crook 8757: doc-count
8758:
1.44 crook 8759:
1.49 anton 8760: For words that move, copy and search for strings see @ref{Memory
8761: Blocks}. For words that display characters and strings see
8762: @ref{Displaying characters and strings}.
1.26 crook 8763:
8764: @node Displaying characters and strings, Input, String Formats, Other I/O
8765: @subsection Displaying characters and strings
1.27 crook 8766: @cindex characters - compiling and displaying
8767: @cindex character strings - compiling and displaying
1.26 crook 8768:
8769: This section starts with a glossary of Forth words and ends with a set
8770: of examples.
8771:
1.44 crook 8772:
1.26 crook 8773: doc-bl
8774: doc-space
8775: doc-spaces
8776: doc-emit
8777: doc-toupper
8778: doc-."
8779: doc-.(
1.98 anton 8780: doc-.\"
1.26 crook 8781: doc-type
1.44 crook 8782: doc-typewhite
1.26 crook 8783: doc-cr
1.27 crook 8784: @cindex cursor control
1.26 crook 8785: doc-at-xy
8786: doc-page
8787: doc-s"
1.98 anton 8788: doc-s\"
1.26 crook 8789: doc-c"
8790: doc-char
8791: doc-[char]
8792:
1.44 crook 8793:
8794: @noindent
1.26 crook 8795: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8796:
8797: @example
1.26 crook 8798: .( text-1)
8799: : my-word
8800: ." text-2" cr
8801: .( text-3)
8802: ;
8803:
8804: ." text-4"
8805:
8806: : my-char
8807: [char] ALPHABET emit
8808: char emit
8809: ;
1.5 anton 8810: @end example
8811:
1.26 crook 8812: When you load this code into Gforth, the following output is generated:
1.5 anton 8813:
1.26 crook 8814: @example
1.30 anton 8815: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8816: @end example
1.5 anton 8817:
1.26 crook 8818: @itemize @bullet
8819: @item
8820: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8821: is an immediate word; it behaves in the same way whether it is used inside
8822: or outside a colon definition.
8823: @item
8824: Message @code{text-4} is displayed because of Gforth's added interpretation
8825: semantics for @code{."}.
8826: @item
1.29 crook 8827: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8828: performs the compilation semantics for @code{."} within the definition of
8829: @code{my-word}.
8830: @end itemize
1.5 anton 8831:
1.26 crook 8832: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8833:
1.26 crook 8834: @example
1.30 anton 8835: @kbd{my-word @key{RET}} text-2
1.26 crook 8836: ok
1.30 anton 8837: @kbd{my-char fred @key{RET}} Af ok
8838: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8839: @end example
1.5 anton 8840:
8841: @itemize @bullet
8842: @item
1.26 crook 8843: Message @code{text-2} is displayed because of the run-time behaviour of
8844: @code{."}.
8845: @item
8846: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8847: on the stack at run-time. @code{emit} always displays the character
8848: when @code{my-char} is executed.
8849: @item
8850: @code{char} parses a string at run-time and the second @code{emit} displays
8851: the first character of the string.
1.5 anton 8852: @item
1.26 crook 8853: If you type @code{see my-char} you can see that @code{[char]} discarded
8854: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8855: definition of @code{my-char}.
1.5 anton 8856: @end itemize
8857:
8858:
8859:
1.112 anton 8860: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8861: @subsection Input
8862: @cindex input
1.28 crook 8863: @cindex I/O - see input
8864: @cindex parsing a string
1.5 anton 8865:
1.49 anton 8866: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8867:
1.27 crook 8868: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8869: @comment then index them
1.27 crook 8870:
1.44 crook 8871:
1.27 crook 8872: doc-key
8873: doc-key?
1.45 crook 8874: doc-ekey
1.141 ! anton 8875: doc-ekey>char
1.45 crook 8876: doc-ekey?
1.141 ! anton 8877:
! 8878: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
! 8879: you need the ANSI.SYS driver to get that behaviour). These are the
! 8880: keyboard events produced by various common keys:
! 8881:
! 8882: doc-k-left
! 8883: doc-k-right
! 8884: doc-k-up
! 8885: doc-k-down
! 8886: doc-k-home
! 8887: doc-k-end
! 8888: doc-k-prior
! 8889: doc-k-next
! 8890: doc-k-insert
! 8891: doc-k-delete
! 8892:
! 8893: The function keys (aka keypad keys) are:
! 8894:
! 8895: doc-k1
! 8896: doc-k2
! 8897: doc-k3
! 8898: doc-k4
! 8899: doc-k5
! 8900: doc-k6
! 8901: doc-k7
! 8902: doc-k8
! 8903: doc-k9
! 8904: doc-k10
! 8905: doc-k11
! 8906: doc-k12
! 8907:
! 8908: Note that K11 and K12 are not as widely available. The shifted
! 8909: function keys are also not very widely available:
! 8910:
! 8911: doc-s-k8
! 8912: doc-s-k1
! 8913: doc-s-k2
! 8914: doc-s-k3
! 8915: doc-s-k4
! 8916: doc-s-k5
! 8917: doc-s-k6
! 8918: doc-s-k7
! 8919: doc-s-k8
! 8920: doc-s-k9
! 8921: doc-s-k10
! 8922: doc-s-k11
! 8923: doc-s-k12
! 8924:
! 8925: Words for inputting one line from the keyboard:
! 8926:
! 8927: doc-accept
! 8928: doc-edit-line
! 8929:
! 8930: Conversion words:
! 8931:
1.26 crook 8932: doc->number
8933: doc->float
1.141 ! anton 8934:
1.27 crook 8935: @comment obsolescent words..
1.141 ! anton 8936: Obsolescent input and conversion words:
! 8937:
1.27 crook 8938: doc-convert
1.26 crook 8939: doc-expect
1.27 crook 8940: doc-span
1.5 anton 8941:
8942:
1.112 anton 8943: @node Pipes, , Input, Other I/O
8944: @subsection Pipes
8945: @cindex pipes, creating your own
8946:
8947: In addition to using Gforth in pipes created by other processes
8948: (@pxref{Gforth in pipes}), you can create your own pipe with
8949: @code{open-pipe}, and read from or write to it.
8950:
8951: doc-open-pipe
8952: doc-close-pipe
8953:
8954: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8955: you don't catch this exception, Gforth will catch it and exit, usually
8956: silently (@pxref{Gforth in pipes}). Since you probably do not want
8957: this, you should wrap a @code{catch} or @code{try} block around the code
8958: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8959: problem yourself, and then return to regular processing.
8960:
8961: doc-broken-pipe-error
8962:
8963:
1.121 anton 8964: @node OS command line arguments, Locals, Other I/O, Words
8965: @section OS command line arguments
8966: @cindex OS command line arguments
8967: @cindex command line arguments, OS
8968: @cindex arguments, OS command line
8969:
8970: The usual way to pass arguments to Gforth programs on the command line
8971: is via the @option{-e} option, e.g.
8972:
8973: @example
8974: gforth -e "123 456" foo.fs -e bye
8975: @end example
8976:
8977: However, you may want to interpret the command-line arguments directly.
8978: In that case, you can access the (image-specific) command-line arguments
1.123 anton 8979: through @code{next-arg}:
1.121 anton 8980:
1.123 anton 8981: doc-next-arg
1.121 anton 8982:
1.123 anton 8983: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 8984:
8985: @example
8986: : echo ( -- )
1.122 anton 8987: begin
1.123 anton 8988: next-arg 2dup 0 0 d<> while
8989: type space
8990: repeat
8991: 2drop ;
1.121 anton 8992:
8993: echo cr bye
8994: @end example
8995:
8996: This can be invoked with
8997:
8998: @example
8999: gforth echo.fs hello world
9000: @end example
1.123 anton 9001:
9002: and it will print
9003:
9004: @example
9005: hello world
9006: @end example
9007:
9008: The next lower level of dealing with the OS command line are the
9009: following words:
9010:
9011: doc-arg
9012: doc-shift-args
9013:
9014: Finally, at the lowest level Gforth provides the following words:
9015:
9016: doc-argc
9017: doc-argv
1.121 anton 9018:
1.78 anton 9019: @c -------------------------------------------------------------
1.126 pazsan 9020: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9021: @section Locals
9022: @cindex locals
9023:
9024: Local variables can make Forth programming more enjoyable and Forth
9025: programs easier to read. Unfortunately, the locals of ANS Forth are
9026: laden with restrictions. Therefore, we provide not only the ANS Forth
9027: locals wordset, but also our own, more powerful locals wordset (we
9028: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9029:
1.78 anton 9030: The ideas in this section have also been published in M. Anton Ertl,
9031: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9032: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9033:
9034: @menu
1.78 anton 9035: * Gforth locals::
9036: * ANS Forth locals::
1.5 anton 9037: @end menu
9038:
1.78 anton 9039: @node Gforth locals, ANS Forth locals, Locals, Locals
9040: @subsection Gforth locals
9041: @cindex Gforth locals
9042: @cindex locals, Gforth style
1.5 anton 9043:
1.78 anton 9044: Locals can be defined with
1.44 crook 9045:
1.78 anton 9046: @example
9047: @{ local1 local2 ... -- comment @}
9048: @end example
9049: or
9050: @example
9051: @{ local1 local2 ... @}
9052: @end example
1.5 anton 9053:
1.78 anton 9054: E.g.,
9055: @example
9056: : max @{ n1 n2 -- n3 @}
9057: n1 n2 > if
9058: n1
9059: else
9060: n2
9061: endif ;
9062: @end example
1.44 crook 9063:
1.78 anton 9064: The similarity of locals definitions with stack comments is intended. A
9065: locals definition often replaces the stack comment of a word. The order
9066: of the locals corresponds to the order in a stack comment and everything
9067: after the @code{--} is really a comment.
1.77 anton 9068:
1.78 anton 9069: This similarity has one disadvantage: It is too easy to confuse locals
9070: declarations with stack comments, causing bugs and making them hard to
9071: find. However, this problem can be avoided by appropriate coding
9072: conventions: Do not use both notations in the same program. If you do,
9073: they should be distinguished using additional means, e.g. by position.
1.77 anton 9074:
1.78 anton 9075: @cindex types of locals
9076: @cindex locals types
9077: The name of the local may be preceded by a type specifier, e.g.,
9078: @code{F:} for a floating point value:
1.5 anton 9079:
1.78 anton 9080: @example
9081: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9082: \ complex multiplication
9083: Ar Br f* Ai Bi f* f-
9084: Ar Bi f* Ai Br f* f+ ;
9085: @end example
1.44 crook 9086:
1.78 anton 9087: @cindex flavours of locals
9088: @cindex locals flavours
9089: @cindex value-flavoured locals
9090: @cindex variable-flavoured locals
9091: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9092: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9093: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9094: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9095: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9096: produces its address (which becomes invalid when the variable's scope is
9097: left). E.g., the standard word @code{emit} can be defined in terms of
9098: @code{type} like this:
1.5 anton 9099:
1.78 anton 9100: @example
9101: : emit @{ C^ char* -- @}
9102: char* 1 type ;
9103: @end example
1.5 anton 9104:
1.78 anton 9105: @cindex default type of locals
9106: @cindex locals, default type
9107: A local without type specifier is a @code{W:} local. Both flavours of
9108: locals are initialized with values from the data or FP stack.
1.44 crook 9109:
1.78 anton 9110: Currently there is no way to define locals with user-defined data
9111: structures, but we are working on it.
1.5 anton 9112:
1.78 anton 9113: Gforth allows defining locals everywhere in a colon definition. This
9114: poses the following questions:
1.5 anton 9115:
1.78 anton 9116: @menu
9117: * Where are locals visible by name?::
9118: * How long do locals live?::
9119: * Locals programming style::
9120: * Locals implementation::
9121: @end menu
1.44 crook 9122:
1.78 anton 9123: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9124: @subsubsection Where are locals visible by name?
9125: @cindex locals visibility
9126: @cindex visibility of locals
9127: @cindex scope of locals
1.5 anton 9128:
1.78 anton 9129: Basically, the answer is that locals are visible where you would expect
9130: it in block-structured languages, and sometimes a little longer. If you
9131: want to restrict the scope of a local, enclose its definition in
9132: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9133:
9134:
1.78 anton 9135: doc-scope
9136: doc-endscope
1.5 anton 9137:
9138:
1.78 anton 9139: These words behave like control structure words, so you can use them
9140: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9141: arbitrary ways.
1.77 anton 9142:
1.78 anton 9143: If you want a more exact answer to the visibility question, here's the
9144: basic principle: A local is visible in all places that can only be
9145: reached through the definition of the local@footnote{In compiler
9146: construction terminology, all places dominated by the definition of the
9147: local.}. In other words, it is not visible in places that can be reached
9148: without going through the definition of the local. E.g., locals defined
9149: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9150: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9151: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9152:
1.78 anton 9153: The reasoning behind this solution is: We want to have the locals
9154: visible as long as it is meaningful. The user can always make the
9155: visibility shorter by using explicit scoping. In a place that can
9156: only be reached through the definition of a local, the meaning of a
9157: local name is clear. In other places it is not: How is the local
9158: initialized at the control flow path that does not contain the
9159: definition? Which local is meant, if the same name is defined twice in
9160: two independent control flow paths?
1.77 anton 9161:
1.78 anton 9162: This should be enough detail for nearly all users, so you can skip the
9163: rest of this section. If you really must know all the gory details and
9164: options, read on.
1.77 anton 9165:
1.78 anton 9166: In order to implement this rule, the compiler has to know which places
9167: are unreachable. It knows this automatically after @code{AHEAD},
9168: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9169: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9170: compiler that the control flow never reaches that place. If
9171: @code{UNREACHABLE} is not used where it could, the only consequence is
9172: that the visibility of some locals is more limited than the rule above
9173: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9174: lie to the compiler), buggy code will be produced.
1.77 anton 9175:
1.5 anton 9176:
1.78 anton 9177: doc-unreachable
1.5 anton 9178:
1.23 crook 9179:
1.78 anton 9180: Another problem with this rule is that at @code{BEGIN}, the compiler
9181: does not know which locals will be visible on the incoming
9182: back-edge. All problems discussed in the following are due to this
9183: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9184: loops as examples; the discussion also applies to @code{?DO} and other
9185: loops). Perhaps the most insidious example is:
1.26 crook 9186: @example
1.78 anton 9187: AHEAD
9188: BEGIN
9189: x
9190: [ 1 CS-ROLL ] THEN
9191: @{ x @}
9192: ...
9193: UNTIL
1.26 crook 9194: @end example
1.23 crook 9195:
1.78 anton 9196: This should be legal according to the visibility rule. The use of
9197: @code{x} can only be reached through the definition; but that appears
9198: textually below the use.
9199:
9200: From this example it is clear that the visibility rules cannot be fully
9201: implemented without major headaches. Our implementation treats common
9202: cases as advertised and the exceptions are treated in a safe way: The
9203: compiler makes a reasonable guess about the locals visible after a
9204: @code{BEGIN}; if it is too pessimistic, the
9205: user will get a spurious error about the local not being defined; if the
9206: compiler is too optimistic, it will notice this later and issue a
9207: warning. In the case above the compiler would complain about @code{x}
9208: being undefined at its use. You can see from the obscure examples in
9209: this section that it takes quite unusual control structures to get the
9210: compiler into trouble, and even then it will often do fine.
1.23 crook 9211:
1.78 anton 9212: If the @code{BEGIN} is reachable from above, the most optimistic guess
9213: is that all locals visible before the @code{BEGIN} will also be
9214: visible after the @code{BEGIN}. This guess is valid for all loops that
9215: are entered only through the @code{BEGIN}, in particular, for normal
9216: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9217: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9218: compiler. When the branch to the @code{BEGIN} is finally generated by
9219: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9220: warns the user if it was too optimistic:
1.26 crook 9221: @example
1.78 anton 9222: IF
9223: @{ x @}
9224: BEGIN
9225: \ x ?
9226: [ 1 cs-roll ] THEN
9227: ...
9228: UNTIL
1.26 crook 9229: @end example
1.23 crook 9230:
1.78 anton 9231: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9232: optimistically assumes that it lives until the @code{THEN}. It notices
9233: this difference when it compiles the @code{UNTIL} and issues a
9234: warning. The user can avoid the warning, and make sure that @code{x}
9235: is not used in the wrong area by using explicit scoping:
9236: @example
9237: IF
9238: SCOPE
9239: @{ x @}
9240: ENDSCOPE
9241: BEGIN
9242: [ 1 cs-roll ] THEN
9243: ...
9244: UNTIL
9245: @end example
1.23 crook 9246:
1.78 anton 9247: Since the guess is optimistic, there will be no spurious error messages
9248: about undefined locals.
1.44 crook 9249:
1.78 anton 9250: If the @code{BEGIN} is not reachable from above (e.g., after
9251: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9252: optimistic guess, as the locals visible after the @code{BEGIN} may be
9253: defined later. Therefore, the compiler assumes that no locals are
9254: visible after the @code{BEGIN}. However, the user can use
9255: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9256: visible at the BEGIN as at the point where the top control-flow stack
9257: item was created.
1.23 crook 9258:
1.44 crook 9259:
1.78 anton 9260: doc-assume-live
1.26 crook 9261:
1.23 crook 9262:
1.78 anton 9263: @noindent
9264: E.g.,
9265: @example
9266: @{ x @}
9267: AHEAD
9268: ASSUME-LIVE
9269: BEGIN
9270: x
9271: [ 1 CS-ROLL ] THEN
9272: ...
9273: UNTIL
9274: @end example
1.44 crook 9275:
1.78 anton 9276: Other cases where the locals are defined before the @code{BEGIN} can be
9277: handled by inserting an appropriate @code{CS-ROLL} before the
9278: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9279: behind the @code{ASSUME-LIVE}).
1.23 crook 9280:
1.78 anton 9281: Cases where locals are defined after the @code{BEGIN} (but should be
9282: visible immediately after the @code{BEGIN}) can only be handled by
9283: rearranging the loop. E.g., the ``most insidious'' example above can be
9284: arranged into:
9285: @example
9286: BEGIN
9287: @{ x @}
9288: ... 0=
9289: WHILE
9290: x
9291: REPEAT
9292: @end example
1.44 crook 9293:
1.78 anton 9294: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9295: @subsubsection How long do locals live?
9296: @cindex locals lifetime
9297: @cindex lifetime of locals
1.23 crook 9298:
1.78 anton 9299: The right answer for the lifetime question would be: A local lives at
9300: least as long as it can be accessed. For a value-flavoured local this
9301: means: until the end of its visibility. However, a variable-flavoured
9302: local could be accessed through its address far beyond its visibility
9303: scope. Ultimately, this would mean that such locals would have to be
9304: garbage collected. Since this entails un-Forth-like implementation
9305: complexities, I adopted the same cowardly solution as some other
9306: languages (e.g., C): The local lives only as long as it is visible;
9307: afterwards its address is invalid (and programs that access it
9308: afterwards are erroneous).
1.23 crook 9309:
1.78 anton 9310: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9311: @subsubsection Locals programming style
9312: @cindex locals programming style
9313: @cindex programming style, locals
1.23 crook 9314:
1.78 anton 9315: The freedom to define locals anywhere has the potential to change
9316: programming styles dramatically. In particular, the need to use the
9317: return stack for intermediate storage vanishes. Moreover, all stack
9318: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9319: determined arguments) can be eliminated: If the stack items are in the
9320: wrong order, just write a locals definition for all of them; then
9321: write the items in the order you want.
1.23 crook 9322:
1.78 anton 9323: This seems a little far-fetched and eliminating stack manipulations is
9324: unlikely to become a conscious programming objective. Still, the number
9325: of stack manipulations will be reduced dramatically if local variables
9326: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9327: a traditional implementation of @code{max}).
1.23 crook 9328:
1.78 anton 9329: This shows one potential benefit of locals: making Forth programs more
9330: readable. Of course, this benefit will only be realized if the
9331: programmers continue to honour the principle of factoring instead of
9332: using the added latitude to make the words longer.
1.23 crook 9333:
1.78 anton 9334: @cindex single-assignment style for locals
9335: Using @code{TO} can and should be avoided. Without @code{TO},
9336: every value-flavoured local has only a single assignment and many
9337: advantages of functional languages apply to Forth. I.e., programs are
9338: easier to analyse, to optimize and to read: It is clear from the
9339: definition what the local stands for, it does not turn into something
9340: different later.
1.23 crook 9341:
1.78 anton 9342: E.g., a definition using @code{TO} might look like this:
9343: @example
9344: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9345: u1 u2 min 0
9346: ?do
9347: addr1 c@@ addr2 c@@ -
9348: ?dup-if
9349: unloop exit
9350: then
9351: addr1 char+ TO addr1
9352: addr2 char+ TO addr2
9353: loop
9354: u1 u2 - ;
1.26 crook 9355: @end example
1.78 anton 9356: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9357: every loop iteration. @code{strcmp} is a typical example of the
9358: readability problems of using @code{TO}. When you start reading
9359: @code{strcmp}, you think that @code{addr1} refers to the start of the
9360: string. Only near the end of the loop you realize that it is something
9361: else.
1.23 crook 9362:
1.78 anton 9363: This can be avoided by defining two locals at the start of the loop that
9364: are initialized with the right value for the current iteration.
9365: @example
9366: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9367: addr1 addr2
9368: u1 u2 min 0
9369: ?do @{ s1 s2 @}
9370: s1 c@@ s2 c@@ -
9371: ?dup-if
9372: unloop exit
9373: then
9374: s1 char+ s2 char+
9375: loop
9376: 2drop
9377: u1 u2 - ;
9378: @end example
9379: Here it is clear from the start that @code{s1} has a different value
9380: in every loop iteration.
1.23 crook 9381:
1.78 anton 9382: @node Locals implementation, , Locals programming style, Gforth locals
9383: @subsubsection Locals implementation
9384: @cindex locals implementation
9385: @cindex implementation of locals
1.23 crook 9386:
1.78 anton 9387: @cindex locals stack
9388: Gforth uses an extra locals stack. The most compelling reason for
9389: this is that the return stack is not float-aligned; using an extra stack
9390: also eliminates the problems and restrictions of using the return stack
9391: as locals stack. Like the other stacks, the locals stack grows toward
9392: lower addresses. A few primitives allow an efficient implementation:
9393:
9394:
9395: doc-@local#
9396: doc-f@local#
9397: doc-laddr#
9398: doc-lp+!#
9399: doc-lp!
9400: doc->l
9401: doc-f>l
9402:
9403:
9404: In addition to these primitives, some specializations of these
9405: primitives for commonly occurring inline arguments are provided for
9406: efficiency reasons, e.g., @code{@@local0} as specialization of
9407: @code{@@local#} for the inline argument 0. The following compiling words
9408: compile the right specialized version, or the general version, as
9409: appropriate:
1.23 crook 9410:
1.5 anton 9411:
1.107 dvdkhlng 9412: @c doc-compile-@local
9413: @c doc-compile-f@local
1.78 anton 9414: doc-compile-lp+!
1.5 anton 9415:
9416:
1.78 anton 9417: Combinations of conditional branches and @code{lp+!#} like
9418: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9419: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9420:
1.78 anton 9421: A special area in the dictionary space is reserved for keeping the
9422: local variable names. @code{@{} switches the dictionary pointer to this
9423: area and @code{@}} switches it back and generates the locals
9424: initializing code. @code{W:} etc.@ are normal defining words. This
9425: special area is cleared at the start of every colon definition.
1.5 anton 9426:
1.78 anton 9427: @cindex word list for defining locals
9428: A special feature of Gforth's dictionary is used to implement the
9429: definition of locals without type specifiers: every word list (aka
9430: vocabulary) has its own methods for searching
9431: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9432: with a special search method: When it is searched for a word, it
9433: actually creates that word using @code{W:}. @code{@{} changes the search
9434: order to first search the word list containing @code{@}}, @code{W:} etc.,
9435: and then the word list for defining locals without type specifiers.
1.5 anton 9436:
1.78 anton 9437: The lifetime rules support a stack discipline within a colon
9438: definition: The lifetime of a local is either nested with other locals
9439: lifetimes or it does not overlap them.
1.23 crook 9440:
1.78 anton 9441: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9442: pointer manipulation is generated. Between control structure words
9443: locals definitions can push locals onto the locals stack. @code{AGAIN}
9444: is the simplest of the other three control flow words. It has to
9445: restore the locals stack depth of the corresponding @code{BEGIN}
9446: before branching. The code looks like this:
9447: @format
9448: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9449: @code{branch} <begin>
9450: @end format
1.26 crook 9451:
1.78 anton 9452: @code{UNTIL} is a little more complicated: If it branches back, it
9453: must adjust the stack just like @code{AGAIN}. But if it falls through,
9454: the locals stack must not be changed. The compiler generates the
9455: following code:
9456: @format
9457: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9458: @end format
9459: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9460:
1.78 anton 9461: @code{THEN} can produce somewhat inefficient code:
9462: @format
9463: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9464: <orig target>:
9465: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9466: @end format
9467: The second @code{lp+!#} adjusts the locals stack pointer from the
9468: level at the @i{orig} point to the level after the @code{THEN}. The
9469: first @code{lp+!#} adjusts the locals stack pointer from the current
9470: level to the level at the orig point, so the complete effect is an
9471: adjustment from the current level to the right level after the
9472: @code{THEN}.
1.26 crook 9473:
1.78 anton 9474: @cindex locals information on the control-flow stack
9475: @cindex control-flow stack items, locals information
9476: In a conventional Forth implementation a dest control-flow stack entry
9477: is just the target address and an orig entry is just the address to be
9478: patched. Our locals implementation adds a word list to every orig or dest
9479: item. It is the list of locals visible (or assumed visible) at the point
9480: described by the entry. Our implementation also adds a tag to identify
9481: the kind of entry, in particular to differentiate between live and dead
9482: (reachable and unreachable) orig entries.
1.26 crook 9483:
1.78 anton 9484: A few unusual operations have to be performed on locals word lists:
1.44 crook 9485:
1.5 anton 9486:
1.78 anton 9487: doc-common-list
9488: doc-sub-list?
9489: doc-list-size
1.52 anton 9490:
9491:
1.78 anton 9492: Several features of our locals word list implementation make these
9493: operations easy to implement: The locals word lists are organised as
9494: linked lists; the tails of these lists are shared, if the lists
9495: contain some of the same locals; and the address of a name is greater
9496: than the address of the names behind it in the list.
1.5 anton 9497:
1.78 anton 9498: Another important implementation detail is the variable
9499: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9500: determine if they can be reached directly or only through the branch
9501: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9502: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9503: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9504:
1.78 anton 9505: Counted loops are similar to other loops in most respects, but
9506: @code{LEAVE} requires special attention: It performs basically the same
9507: service as @code{AHEAD}, but it does not create a control-flow stack
9508: entry. Therefore the information has to be stored elsewhere;
9509: traditionally, the information was stored in the target fields of the
9510: branches created by the @code{LEAVE}s, by organizing these fields into a
9511: linked list. Unfortunately, this clever trick does not provide enough
9512: space for storing our extended control flow information. Therefore, we
9513: introduce another stack, the leave stack. It contains the control-flow
9514: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9515:
1.78 anton 9516: Local names are kept until the end of the colon definition, even if
9517: they are no longer visible in any control-flow path. In a few cases
9518: this may lead to increased space needs for the locals name area, but
9519: usually less than reclaiming this space would cost in code size.
1.5 anton 9520:
1.44 crook 9521:
1.78 anton 9522: @node ANS Forth locals, , Gforth locals, Locals
9523: @subsection ANS Forth locals
9524: @cindex locals, ANS Forth style
1.5 anton 9525:
1.78 anton 9526: The ANS Forth locals wordset does not define a syntax for locals, but
9527: words that make it possible to define various syntaxes. One of the
9528: possible syntaxes is a subset of the syntax we used in the Gforth locals
9529: wordset, i.e.:
1.29 crook 9530:
9531: @example
1.78 anton 9532: @{ local1 local2 ... -- comment @}
9533: @end example
9534: @noindent
9535: or
9536: @example
9537: @{ local1 local2 ... @}
1.29 crook 9538: @end example
9539:
1.78 anton 9540: The order of the locals corresponds to the order in a stack comment. The
9541: restrictions are:
1.5 anton 9542:
1.78 anton 9543: @itemize @bullet
9544: @item
9545: Locals can only be cell-sized values (no type specifiers are allowed).
9546: @item
9547: Locals can be defined only outside control structures.
9548: @item
9549: Locals can interfere with explicit usage of the return stack. For the
9550: exact (and long) rules, see the standard. If you don't use return stack
9551: accessing words in a definition using locals, you will be all right. The
9552: purpose of this rule is to make locals implementation on the return
9553: stack easier.
9554: @item
9555: The whole definition must be in one line.
9556: @end itemize
1.5 anton 9557:
1.78 anton 9558: Locals defined in ANS Forth behave like @code{VALUE}s
9559: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9560: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9561:
1.78 anton 9562: Since the syntax above is supported by Gforth directly, you need not do
9563: anything to use it. If you want to port a program using this syntax to
9564: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9565: syntax on the other system.
1.5 anton 9566:
1.78 anton 9567: Note that a syntax shown in the standard, section A.13 looks
9568: similar, but is quite different in having the order of locals
9569: reversed. Beware!
1.5 anton 9570:
1.78 anton 9571: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9572:
1.78 anton 9573: doc-(local)
1.5 anton 9574:
1.78 anton 9575: The ANS Forth locals extension wordset defines a syntax using
9576: @code{locals|}, but it is so awful that we strongly recommend not to use
9577: it. We have implemented this syntax to make porting to Gforth easy, but
9578: do not document it here. The problem with this syntax is that the locals
9579: are defined in an order reversed with respect to the standard stack
9580: comment notation, making programs harder to read, and easier to misread
9581: and miswrite. The only merit of this syntax is that it is easy to
9582: implement using the ANS Forth locals wordset.
1.53 anton 9583:
9584:
1.78 anton 9585: @c ----------------------------------------------------------
9586: @node Structures, Object-oriented Forth, Locals, Words
9587: @section Structures
9588: @cindex structures
9589: @cindex records
1.53 anton 9590:
1.78 anton 9591: This section presents the structure package that comes with Gforth. A
9592: version of the package implemented in ANS Forth is available in
9593: @file{compat/struct.fs}. This package was inspired by a posting on
9594: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9595: possibly John Hayes). A version of this section has been published in
9596: M. Anton Ertl,
9597: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9598: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9599: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9600:
1.78 anton 9601: @menu
9602: * Why explicit structure support?::
9603: * Structure Usage::
9604: * Structure Naming Convention::
9605: * Structure Implementation::
9606: * Structure Glossary::
9607: @end menu
1.55 anton 9608:
1.78 anton 9609: @node Why explicit structure support?, Structure Usage, Structures, Structures
9610: @subsection Why explicit structure support?
1.53 anton 9611:
1.78 anton 9612: @cindex address arithmetic for structures
9613: @cindex structures using address arithmetic
9614: If we want to use a structure containing several fields, we could simply
9615: reserve memory for it, and access the fields using address arithmetic
9616: (@pxref{Address arithmetic}). As an example, consider a structure with
9617: the following fields
1.57 anton 9618:
1.78 anton 9619: @table @code
9620: @item a
9621: is a float
9622: @item b
9623: is a cell
9624: @item c
9625: is a float
9626: @end table
1.57 anton 9627:
1.78 anton 9628: Given the (float-aligned) base address of the structure we get the
9629: address of the field
1.52 anton 9630:
1.78 anton 9631: @table @code
9632: @item a
9633: without doing anything further.
9634: @item b
9635: with @code{float+}
9636: @item c
9637: with @code{float+ cell+ faligned}
9638: @end table
1.52 anton 9639:
1.78 anton 9640: It is easy to see that this can become quite tiring.
1.52 anton 9641:
1.78 anton 9642: Moreover, it is not very readable, because seeing a
9643: @code{cell+} tells us neither which kind of structure is
9644: accessed nor what field is accessed; we have to somehow infer the kind
9645: of structure, and then look up in the documentation, which field of
9646: that structure corresponds to that offset.
1.53 anton 9647:
1.78 anton 9648: Finally, this kind of address arithmetic also causes maintenance
9649: troubles: If you add or delete a field somewhere in the middle of the
9650: structure, you have to find and change all computations for the fields
9651: afterwards.
1.52 anton 9652:
1.78 anton 9653: So, instead of using @code{cell+} and friends directly, how
9654: about storing the offsets in constants:
1.52 anton 9655:
1.78 anton 9656: @example
9657: 0 constant a-offset
9658: 0 float+ constant b-offset
9659: 0 float+ cell+ faligned c-offset
9660: @end example
1.64 pazsan 9661:
1.78 anton 9662: Now we can get the address of field @code{x} with @code{x-offset
9663: +}. This is much better in all respects. Of course, you still
9664: have to change all later offset definitions if you add a field. You can
9665: fix this by declaring the offsets in the following way:
1.57 anton 9666:
1.78 anton 9667: @example
9668: 0 constant a-offset
9669: a-offset float+ constant b-offset
9670: b-offset cell+ faligned constant c-offset
9671: @end example
1.57 anton 9672:
1.78 anton 9673: Since we always use the offsets with @code{+}, we could use a defining
9674: word @code{cfield} that includes the @code{+} in the action of the
9675: defined word:
1.64 pazsan 9676:
1.78 anton 9677: @example
9678: : cfield ( n "name" -- )
9679: create ,
9680: does> ( name execution: addr1 -- addr2 )
9681: @@ + ;
1.64 pazsan 9682:
1.78 anton 9683: 0 cfield a
9684: 0 a float+ cfield b
9685: 0 b cell+ faligned cfield c
9686: @end example
1.64 pazsan 9687:
1.78 anton 9688: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9689:
1.78 anton 9690: The structure field words now can be used quite nicely. However,
9691: their definition is still a bit cumbersome: We have to repeat the
9692: name, the information about size and alignment is distributed before
9693: and after the field definitions etc. The structure package presented
9694: here addresses these problems.
1.64 pazsan 9695:
1.78 anton 9696: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9697: @subsection Structure Usage
9698: @cindex structure usage
1.57 anton 9699:
1.78 anton 9700: @cindex @code{field} usage
9701: @cindex @code{struct} usage
9702: @cindex @code{end-struct} usage
9703: You can define a structure for a (data-less) linked list with:
1.57 anton 9704: @example
1.78 anton 9705: struct
9706: cell% field list-next
9707: end-struct list%
1.57 anton 9708: @end example
9709:
1.78 anton 9710: With the address of the list node on the stack, you can compute the
9711: address of the field that contains the address of the next node with
9712: @code{list-next}. E.g., you can determine the length of a list
9713: with:
1.57 anton 9714:
9715: @example
1.78 anton 9716: : list-length ( list -- n )
9717: \ "list" is a pointer to the first element of a linked list
9718: \ "n" is the length of the list
9719: 0 BEGIN ( list1 n1 )
9720: over
9721: WHILE ( list1 n1 )
9722: 1+ swap list-next @@ swap
9723: REPEAT
9724: nip ;
1.57 anton 9725: @end example
9726:
1.78 anton 9727: You can reserve memory for a list node in the dictionary with
9728: @code{list% %allot}, which leaves the address of the list node on the
9729: stack. For the equivalent allocation on the heap you can use @code{list%
9730: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9731: use @code{list% %allocate}). You can get the the size of a list
9732: node with @code{list% %size} and its alignment with @code{list%
9733: %alignment}.
9734:
9735: Note that in ANS Forth the body of a @code{create}d word is
9736: @code{aligned} but not necessarily @code{faligned};
9737: therefore, if you do a:
1.57 anton 9738:
9739: @example
1.78 anton 9740: create @emph{name} foo% %allot drop
1.57 anton 9741: @end example
9742:
1.78 anton 9743: @noindent
9744: then the memory alloted for @code{foo%} is guaranteed to start at the
9745: body of @code{@emph{name}} only if @code{foo%} contains only character,
9746: cell and double fields. Therefore, if your structure contains floats,
9747: better use
1.57 anton 9748:
9749: @example
1.78 anton 9750: foo% %allot constant @emph{name}
1.57 anton 9751: @end example
9752:
1.78 anton 9753: @cindex structures containing structures
9754: You can include a structure @code{foo%} as a field of
9755: another structure, like this:
1.65 anton 9756: @example
1.78 anton 9757: struct
9758: ...
9759: foo% field ...
9760: ...
9761: end-struct ...
1.65 anton 9762: @end example
1.52 anton 9763:
1.78 anton 9764: @cindex structure extension
9765: @cindex extended records
9766: Instead of starting with an empty structure, you can extend an
9767: existing structure. E.g., a plain linked list without data, as defined
9768: above, is hardly useful; You can extend it to a linked list of integers,
9769: like this:@footnote{This feature is also known as @emph{extended
9770: records}. It is the main innovation in the Oberon language; in other
9771: words, adding this feature to Modula-2 led Wirth to create a new
9772: language, write a new compiler etc. Adding this feature to Forth just
9773: required a few lines of code.}
1.52 anton 9774:
1.78 anton 9775: @example
9776: list%
9777: cell% field intlist-int
9778: end-struct intlist%
9779: @end example
1.55 anton 9780:
1.78 anton 9781: @code{intlist%} is a structure with two fields:
9782: @code{list-next} and @code{intlist-int}.
1.55 anton 9783:
1.78 anton 9784: @cindex structures containing arrays
9785: You can specify an array type containing @emph{n} elements of
9786: type @code{foo%} like this:
1.55 anton 9787:
9788: @example
1.78 anton 9789: foo% @emph{n} *
1.56 anton 9790: @end example
1.55 anton 9791:
1.78 anton 9792: You can use this array type in any place where you can use a normal
9793: type, e.g., when defining a @code{field}, or with
9794: @code{%allot}.
9795:
9796: @cindex first field optimization
9797: The first field is at the base address of a structure and the word for
9798: this field (e.g., @code{list-next}) actually does not change the address
9799: on the stack. You may be tempted to leave it away in the interest of
9800: run-time and space efficiency. This is not necessary, because the
9801: structure package optimizes this case: If you compile a first-field
9802: words, no code is generated. So, in the interest of readability and
9803: maintainability you should include the word for the field when accessing
9804: the field.
1.52 anton 9805:
9806:
1.78 anton 9807: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9808: @subsection Structure Naming Convention
9809: @cindex structure naming convention
1.52 anton 9810:
1.78 anton 9811: The field names that come to (my) mind are often quite generic, and,
9812: if used, would cause frequent name clashes. E.g., many structures
9813: probably contain a @code{counter} field. The structure names
9814: that come to (my) mind are often also the logical choice for the names
9815: of words that create such a structure.
1.52 anton 9816:
1.78 anton 9817: Therefore, I have adopted the following naming conventions:
1.52 anton 9818:
1.78 anton 9819: @itemize @bullet
9820: @cindex field naming convention
9821: @item
9822: The names of fields are of the form
9823: @code{@emph{struct}-@emph{field}}, where
9824: @code{@emph{struct}} is the basic name of the structure, and
9825: @code{@emph{field}} is the basic name of the field. You can
9826: think of field words as converting the (address of the)
9827: structure into the (address of the) field.
1.52 anton 9828:
1.78 anton 9829: @cindex structure naming convention
9830: @item
9831: The names of structures are of the form
9832: @code{@emph{struct}%}, where
9833: @code{@emph{struct}} is the basic name of the structure.
9834: @end itemize
1.52 anton 9835:
1.78 anton 9836: This naming convention does not work that well for fields of extended
9837: structures; e.g., the integer list structure has a field
9838: @code{intlist-int}, but has @code{list-next}, not
9839: @code{intlist-next}.
1.53 anton 9840:
1.78 anton 9841: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9842: @subsection Structure Implementation
9843: @cindex structure implementation
9844: @cindex implementation of structures
1.52 anton 9845:
1.78 anton 9846: The central idea in the implementation is to pass the data about the
9847: structure being built on the stack, not in some global
9848: variable. Everything else falls into place naturally once this design
9849: decision is made.
1.53 anton 9850:
1.78 anton 9851: The type description on the stack is of the form @emph{align
9852: size}. Keeping the size on the top-of-stack makes dealing with arrays
9853: very simple.
1.53 anton 9854:
1.78 anton 9855: @code{field} is a defining word that uses @code{Create}
9856: and @code{DOES>}. The body of the field contains the offset
9857: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9858:
9859: @example
1.78 anton 9860: @@ +
1.53 anton 9861: @end example
9862:
1.78 anton 9863: @noindent
9864: i.e., add the offset to the address, giving the stack effect
9865: @i{addr1 -- addr2} for a field.
9866:
9867: @cindex first field optimization, implementation
9868: This simple structure is slightly complicated by the optimization
9869: for fields with offset 0, which requires a different
9870: @code{DOES>}-part (because we cannot rely on there being
9871: something on the stack if such a field is invoked during
9872: compilation). Therefore, we put the different @code{DOES>}-parts
9873: in separate words, and decide which one to invoke based on the
9874: offset. For a zero offset, the field is basically a noop; it is
9875: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9876:
1.78 anton 9877: @node Structure Glossary, , Structure Implementation, Structures
9878: @subsection Structure Glossary
9879: @cindex structure glossary
1.53 anton 9880:
1.5 anton 9881:
1.78 anton 9882: doc-%align
9883: doc-%alignment
9884: doc-%alloc
9885: doc-%allocate
9886: doc-%allot
9887: doc-cell%
9888: doc-char%
9889: doc-dfloat%
9890: doc-double%
9891: doc-end-struct
9892: doc-field
9893: doc-float%
9894: doc-naligned
9895: doc-sfloat%
9896: doc-%size
9897: doc-struct
1.54 anton 9898:
9899:
1.26 crook 9900: @c -------------------------------------------------------------
1.78 anton 9901: @node Object-oriented Forth, Programming Tools, Structures, Words
9902: @section Object-oriented Forth
9903:
9904: Gforth comes with three packages for object-oriented programming:
9905: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9906: is preloaded, so you have to @code{include} them before use. The most
9907: important differences between these packages (and others) are discussed
9908: in @ref{Comparison with other object models}. All packages are written
9909: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9910:
1.78 anton 9911: @menu
9912: * Why object-oriented programming?::
9913: * Object-Oriented Terminology::
9914: * Objects::
9915: * OOF::
9916: * Mini-OOF::
9917: * Comparison with other object models::
9918: @end menu
1.5 anton 9919:
1.78 anton 9920: @c ----------------------------------------------------------------
9921: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9922: @subsection Why object-oriented programming?
9923: @cindex object-oriented programming motivation
9924: @cindex motivation for object-oriented programming
1.44 crook 9925:
1.78 anton 9926: Often we have to deal with several data structures (@emph{objects}),
9927: that have to be treated similarly in some respects, but differently in
9928: others. Graphical objects are the textbook example: circles, triangles,
9929: dinosaurs, icons, and others, and we may want to add more during program
9930: development. We want to apply some operations to any graphical object,
9931: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9932: has to do something different for every kind of object.
9933: @comment TODO add some other operations eg perimeter, area
9934: @comment and tie in to concrete examples later..
1.5 anton 9935:
1.78 anton 9936: We could implement @code{draw} as a big @code{CASE}
9937: control structure that executes the appropriate code depending on the
9938: kind of object to be drawn. This would be not be very elegant, and,
9939: moreover, we would have to change @code{draw} every time we add
9940: a new kind of graphical object (say, a spaceship).
1.44 crook 9941:
1.78 anton 9942: What we would rather do is: When defining spaceships, we would tell
9943: the system: ``Here's how you @code{draw} a spaceship; you figure
9944: out the rest''.
1.5 anton 9945:
1.78 anton 9946: This is the problem that all systems solve that (rightfully) call
9947: themselves object-oriented; the object-oriented packages presented here
9948: solve this problem (and not much else).
9949: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9950:
1.78 anton 9951: @c ------------------------------------------------------------------------
9952: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9953: @subsection Object-Oriented Terminology
9954: @cindex object-oriented terminology
9955: @cindex terminology for object-oriented programming
1.5 anton 9956:
1.78 anton 9957: This section is mainly for reference, so you don't have to understand
9958: all of it right away. The terminology is mainly Smalltalk-inspired. In
9959: short:
1.44 crook 9960:
1.78 anton 9961: @table @emph
9962: @cindex class
9963: @item class
9964: a data structure definition with some extras.
1.5 anton 9965:
1.78 anton 9966: @cindex object
9967: @item object
9968: an instance of the data structure described by the class definition.
1.5 anton 9969:
1.78 anton 9970: @cindex instance variables
9971: @item instance variables
9972: fields of the data structure.
1.5 anton 9973:
1.78 anton 9974: @cindex selector
9975: @cindex method selector
9976: @cindex virtual function
9977: @item selector
9978: (or @emph{method selector}) a word (e.g.,
9979: @code{draw}) that performs an operation on a variety of data
9980: structures (classes). A selector describes @emph{what} operation to
9981: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9982:
1.78 anton 9983: @cindex method
9984: @item method
9985: the concrete definition that performs the operation
9986: described by the selector for a specific class. A method specifies
9987: @emph{how} the operation is performed for a specific class.
1.5 anton 9988:
1.78 anton 9989: @cindex selector invocation
9990: @cindex message send
9991: @cindex invoking a selector
9992: @item selector invocation
9993: a call of a selector. One argument of the call (the TOS (top-of-stack))
9994: is used for determining which method is used. In Smalltalk terminology:
9995: a message (consisting of the selector and the other arguments) is sent
9996: to the object.
1.5 anton 9997:
1.78 anton 9998: @cindex receiving object
9999: @item receiving object
10000: the object used for determining the method executed by a selector
10001: invocation. In the @file{objects.fs} model, it is the object that is on
10002: the TOS when the selector is invoked. (@emph{Receiving} comes from
10003: the Smalltalk @emph{message} terminology.)
1.5 anton 10004:
1.78 anton 10005: @cindex child class
10006: @cindex parent class
10007: @cindex inheritance
10008: @item child class
10009: a class that has (@emph{inherits}) all properties (instance variables,
10010: selectors, methods) from a @emph{parent class}. In Smalltalk
10011: terminology: The subclass inherits from the superclass. In C++
10012: terminology: The derived class inherits from the base class.
1.5 anton 10013:
1.78 anton 10014: @end table
1.5 anton 10015:
1.78 anton 10016: @c If you wonder about the message sending terminology, it comes from
10017: @c a time when each object had it's own task and objects communicated via
10018: @c message passing; eventually the Smalltalk developers realized that
10019: @c they can do most things through simple (indirect) calls. They kept the
10020: @c terminology.
1.5 anton 10021:
1.78 anton 10022: @c --------------------------------------------------------------
10023: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10024: @subsection The @file{objects.fs} model
10025: @cindex objects
10026: @cindex object-oriented programming
1.26 crook 10027:
1.78 anton 10028: @cindex @file{objects.fs}
10029: @cindex @file{oof.fs}
1.26 crook 10030:
1.78 anton 10031: This section describes the @file{objects.fs} package. This material also
10032: has been published in M. Anton Ertl,
10033: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10034: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10035: 37--43.
10036: @c McKewan's and Zsoter's packages
1.26 crook 10037:
1.78 anton 10038: This section assumes that you have read @ref{Structures}.
1.5 anton 10039:
1.78 anton 10040: The techniques on which this model is based have been used to implement
10041: the parser generator, Gray, and have also been used in Gforth for
10042: implementing the various flavours of word lists (hashed or not,
10043: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10044:
10045:
1.26 crook 10046: @menu
1.78 anton 10047: * Properties of the Objects model::
10048: * Basic Objects Usage::
10049: * The Objects base class::
10050: * Creating objects::
10051: * Object-Oriented Programming Style::
10052: * Class Binding::
10053: * Method conveniences::
10054: * Classes and Scoping::
10055: * Dividing classes::
10056: * Object Interfaces::
10057: * Objects Implementation::
10058: * Objects Glossary::
1.26 crook 10059: @end menu
1.5 anton 10060:
1.78 anton 10061: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10062:
1.78 anton 10063: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10064: @subsubsection Properties of the @file{objects.fs} model
10065: @cindex @file{objects.fs} properties
1.5 anton 10066:
1.78 anton 10067: @itemize @bullet
10068: @item
10069: It is straightforward to pass objects on the stack. Passing
10070: selectors on the stack is a little less convenient, but possible.
1.44 crook 10071:
1.78 anton 10072: @item
10073: Objects are just data structures in memory, and are referenced by their
10074: address. You can create words for objects with normal defining words
10075: like @code{constant}. Likewise, there is no difference between instance
10076: variables that contain objects and those that contain other data.
1.5 anton 10077:
1.78 anton 10078: @item
10079: Late binding is efficient and easy to use.
1.44 crook 10080:
1.78 anton 10081: @item
10082: It avoids parsing, and thus avoids problems with state-smartness
10083: and reduced extensibility; for convenience there are a few parsing
10084: words, but they have non-parsing counterparts. There are also a few
10085: defining words that parse. This is hard to avoid, because all standard
10086: defining words parse (except @code{:noname}); however, such
10087: words are not as bad as many other parsing words, because they are not
10088: state-smart.
1.5 anton 10089:
1.78 anton 10090: @item
10091: It does not try to incorporate everything. It does a few things and does
10092: them well (IMO). In particular, this model was not designed to support
10093: information hiding (although it has features that may help); you can use
10094: a separate package for achieving this.
1.5 anton 10095:
1.78 anton 10096: @item
10097: It is layered; you don't have to learn and use all features to use this
10098: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10099: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10100: are optional and independent of each other.
1.5 anton 10101:
1.78 anton 10102: @item
10103: An implementation in ANS Forth is available.
1.5 anton 10104:
1.78 anton 10105: @end itemize
1.5 anton 10106:
1.44 crook 10107:
1.78 anton 10108: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10109: @subsubsection Basic @file{objects.fs} Usage
10110: @cindex basic objects usage
10111: @cindex objects, basic usage
1.5 anton 10112:
1.78 anton 10113: You can define a class for graphical objects like this:
1.44 crook 10114:
1.78 anton 10115: @cindex @code{class} usage
10116: @cindex @code{end-class} usage
10117: @cindex @code{selector} usage
1.5 anton 10118: @example
1.78 anton 10119: object class \ "object" is the parent class
10120: selector draw ( x y graphical -- )
10121: end-class graphical
10122: @end example
10123:
10124: This code defines a class @code{graphical} with an
10125: operation @code{draw}. We can perform the operation
10126: @code{draw} on any @code{graphical} object, e.g.:
10127:
10128: @example
10129: 100 100 t-rex draw
1.26 crook 10130: @end example
1.5 anton 10131:
1.78 anton 10132: @noindent
10133: where @code{t-rex} is a word (say, a constant) that produces a
10134: graphical object.
10135:
10136: @comment TODO add a 2nd operation eg perimeter.. and use for
10137: @comment a concrete example
1.5 anton 10138:
1.78 anton 10139: @cindex abstract class
10140: How do we create a graphical object? With the present definitions,
10141: we cannot create a useful graphical object. The class
10142: @code{graphical} describes graphical objects in general, but not
10143: any concrete graphical object type (C++ users would call it an
10144: @emph{abstract class}); e.g., there is no method for the selector
10145: @code{draw} in the class @code{graphical}.
1.5 anton 10146:
1.78 anton 10147: For concrete graphical objects, we define child classes of the
10148: class @code{graphical}, e.g.:
1.5 anton 10149:
1.78 anton 10150: @cindex @code{overrides} usage
10151: @cindex @code{field} usage in class definition
1.26 crook 10152: @example
1.78 anton 10153: graphical class \ "graphical" is the parent class
10154: cell% field circle-radius
1.5 anton 10155:
1.78 anton 10156: :noname ( x y circle -- )
10157: circle-radius @@ draw-circle ;
10158: overrides draw
1.5 anton 10159:
1.78 anton 10160: :noname ( n-radius circle -- )
10161: circle-radius ! ;
10162: overrides construct
1.5 anton 10163:
1.78 anton 10164: end-class circle
10165: @end example
1.44 crook 10166:
1.78 anton 10167: Here we define a class @code{circle} as a child of @code{graphical},
10168: with field @code{circle-radius} (which behaves just like a field
10169: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10170: for the selectors @code{draw} and @code{construct} (@code{construct} is
10171: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10172:
1.78 anton 10173: Now we can create a circle on the heap (i.e.,
10174: @code{allocate}d memory) with:
1.44 crook 10175:
1.78 anton 10176: @cindex @code{heap-new} usage
1.5 anton 10177: @example
1.78 anton 10178: 50 circle heap-new constant my-circle
1.5 anton 10179: @end example
10180:
1.78 anton 10181: @noindent
10182: @code{heap-new} invokes @code{construct}, thus
10183: initializing the field @code{circle-radius} with 50. We can draw
10184: this new circle at (100,100) with:
1.5 anton 10185:
10186: @example
1.78 anton 10187: 100 100 my-circle draw
1.5 anton 10188: @end example
10189:
1.78 anton 10190: @cindex selector invocation, restrictions
10191: @cindex class definition, restrictions
10192: Note: You can only invoke a selector if the object on the TOS
10193: (the receiving object) belongs to the class where the selector was
10194: defined or one of its descendents; e.g., you can invoke
10195: @code{draw} only for objects belonging to @code{graphical}
10196: or its descendents (e.g., @code{circle}). Immediately before
10197: @code{end-class}, the search order has to be the same as
10198: immediately after @code{class}.
10199:
10200: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10201: @subsubsection The @file{object.fs} base class
10202: @cindex @code{object} class
10203:
10204: When you define a class, you have to specify a parent class. So how do
10205: you start defining classes? There is one class available from the start:
10206: @code{object}. It is ancestor for all classes and so is the
10207: only class that has no parent. It has two selectors: @code{construct}
10208: and @code{print}.
10209:
10210: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10211: @subsubsection Creating objects
10212: @cindex creating objects
10213: @cindex object creation
10214: @cindex object allocation options
10215:
10216: @cindex @code{heap-new} discussion
10217: @cindex @code{dict-new} discussion
10218: @cindex @code{construct} discussion
10219: You can create and initialize an object of a class on the heap with
10220: @code{heap-new} ( ... class -- object ) and in the dictionary
10221: (allocation with @code{allot}) with @code{dict-new} (
10222: ... class -- object ). Both words invoke @code{construct}, which
10223: consumes the stack items indicated by "..." above.
10224:
10225: @cindex @code{init-object} discussion
10226: @cindex @code{class-inst-size} discussion
10227: If you want to allocate memory for an object yourself, you can get its
10228: alignment and size with @code{class-inst-size 2@@} ( class --
10229: align size ). Once you have memory for an object, you can initialize
10230: it with @code{init-object} ( ... class object -- );
10231: @code{construct} does only a part of the necessary work.
10232:
10233: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10234: @subsubsection Object-Oriented Programming Style
10235: @cindex object-oriented programming style
10236: @cindex programming style, object-oriented
1.5 anton 10237:
1.78 anton 10238: This section is not exhaustive.
1.5 anton 10239:
1.78 anton 10240: @cindex stack effects of selectors
10241: @cindex selectors and stack effects
10242: In general, it is a good idea to ensure that all methods for the
10243: same selector have the same stack effect: when you invoke a selector,
10244: you often have no idea which method will be invoked, so, unless all
10245: methods have the same stack effect, you will not know the stack effect
10246: of the selector invocation.
1.5 anton 10247:
1.78 anton 10248: One exception to this rule is methods for the selector
10249: @code{construct}. We know which method is invoked, because we
10250: specify the class to be constructed at the same place. Actually, I
10251: defined @code{construct} as a selector only to give the users a
10252: convenient way to specify initialization. The way it is used, a
10253: mechanism different from selector invocation would be more natural
10254: (but probably would take more code and more space to explain).
1.5 anton 10255:
1.78 anton 10256: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10257: @subsubsection Class Binding
10258: @cindex class binding
10259: @cindex early binding
1.5 anton 10260:
1.78 anton 10261: @cindex late binding
10262: Normal selector invocations determine the method at run-time depending
10263: on the class of the receiving object. This run-time selection is called
10264: @i{late binding}.
1.5 anton 10265:
1.78 anton 10266: Sometimes it's preferable to invoke a different method. For example,
10267: you might want to use the simple method for @code{print}ing
10268: @code{object}s instead of the possibly long-winded @code{print} method
10269: of the receiver class. You can achieve this by replacing the invocation
10270: of @code{print} with:
1.5 anton 10271:
1.78 anton 10272: @cindex @code{[bind]} usage
1.5 anton 10273: @example
1.78 anton 10274: [bind] object print
1.5 anton 10275: @end example
10276:
1.78 anton 10277: @noindent
10278: in compiled code or:
10279:
10280: @cindex @code{bind} usage
1.5 anton 10281: @example
1.78 anton 10282: bind object print
1.5 anton 10283: @end example
10284:
1.78 anton 10285: @cindex class binding, alternative to
10286: @noindent
10287: in interpreted code. Alternatively, you can define the method with a
10288: name (e.g., @code{print-object}), and then invoke it through the
10289: name. Class binding is just a (often more convenient) way to achieve
10290: the same effect; it avoids name clutter and allows you to invoke
10291: methods directly without naming them first.
1.5 anton 10292:
1.78 anton 10293: @cindex superclass binding
10294: @cindex parent class binding
10295: A frequent use of class binding is this: When we define a method
10296: for a selector, we often want the method to do what the selector does
10297: in the parent class, and a little more. There is a special word for
10298: this purpose: @code{[parent]}; @code{[parent]
10299: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10300: selector}}, where @code{@emph{parent}} is the parent
10301: class of the current class. E.g., a method definition might look like:
1.44 crook 10302:
1.78 anton 10303: @cindex @code{[parent]} usage
10304: @example
10305: :noname
10306: dup [parent] foo \ do parent's foo on the receiving object
10307: ... \ do some more
10308: ; overrides foo
10309: @end example
1.6 pazsan 10310:
1.78 anton 10311: @cindex class binding as optimization
10312: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10313: March 1997), Andrew McKewan presents class binding as an optimization
10314: technique. I recommend not using it for this purpose unless you are in
10315: an emergency. Late binding is pretty fast with this model anyway, so the
10316: benefit of using class binding is small; the cost of using class binding
10317: where it is not appropriate is reduced maintainability.
1.44 crook 10318:
1.78 anton 10319: While we are at programming style questions: You should bind
10320: selectors only to ancestor classes of the receiving object. E.g., say,
10321: you know that the receiving object is of class @code{foo} or its
10322: descendents; then you should bind only to @code{foo} and its
10323: ancestors.
1.12 anton 10324:
1.78 anton 10325: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10326: @subsubsection Method conveniences
10327: @cindex method conveniences
1.44 crook 10328:
1.78 anton 10329: In a method you usually access the receiving object pretty often. If
10330: you define the method as a plain colon definition (e.g., with
10331: @code{:noname}), you may have to do a lot of stack
10332: gymnastics. To avoid this, you can define the method with @code{m:
10333: ... ;m}. E.g., you could define the method for
10334: @code{draw}ing a @code{circle} with
1.6 pazsan 10335:
1.78 anton 10336: @cindex @code{this} usage
10337: @cindex @code{m:} usage
10338: @cindex @code{;m} usage
10339: @example
10340: m: ( x y circle -- )
10341: ( x y ) this circle-radius @@ draw-circle ;m
10342: @end example
1.6 pazsan 10343:
1.78 anton 10344: @cindex @code{exit} in @code{m: ... ;m}
10345: @cindex @code{exitm} discussion
10346: @cindex @code{catch} in @code{m: ... ;m}
10347: When this method is executed, the receiver object is removed from the
10348: stack; you can access it with @code{this} (admittedly, in this
10349: example the use of @code{m: ... ;m} offers no advantage). Note
10350: that I specify the stack effect for the whole method (i.e. including
10351: the receiver object), not just for the code between @code{m:}
10352: and @code{;m}. You cannot use @code{exit} in
10353: @code{m:...;m}; instead, use
10354: @code{exitm}.@footnote{Moreover, for any word that calls
10355: @code{catch} and was defined before loading
10356: @code{objects.fs}, you have to redefine it like I redefined
10357: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10358:
1.78 anton 10359: @cindex @code{inst-var} usage
10360: You will frequently use sequences of the form @code{this
10361: @emph{field}} (in the example above: @code{this
10362: circle-radius}). If you use the field only in this way, you can
10363: define it with @code{inst-var} and eliminate the
10364: @code{this} before the field name. E.g., the @code{circle}
10365: class above could also be defined with:
1.6 pazsan 10366:
1.78 anton 10367: @example
10368: graphical class
10369: cell% inst-var radius
1.6 pazsan 10370:
1.78 anton 10371: m: ( x y circle -- )
10372: radius @@ draw-circle ;m
10373: overrides draw
1.6 pazsan 10374:
1.78 anton 10375: m: ( n-radius circle -- )
10376: radius ! ;m
10377: overrides construct
1.6 pazsan 10378:
1.78 anton 10379: end-class circle
10380: @end example
1.6 pazsan 10381:
1.78 anton 10382: @code{radius} can only be used in @code{circle} and its
10383: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10384:
1.78 anton 10385: @cindex @code{inst-value} usage
10386: You can also define fields with @code{inst-value}, which is
10387: to @code{inst-var} what @code{value} is to
10388: @code{variable}. You can change the value of such a field with
10389: @code{[to-inst]}. E.g., we could also define the class
10390: @code{circle} like this:
1.44 crook 10391:
1.78 anton 10392: @example
10393: graphical class
10394: inst-value radius
1.6 pazsan 10395:
1.78 anton 10396: m: ( x y circle -- )
10397: radius draw-circle ;m
10398: overrides draw
1.44 crook 10399:
1.78 anton 10400: m: ( n-radius circle -- )
10401: [to-inst] radius ;m
10402: overrides construct
1.6 pazsan 10403:
1.78 anton 10404: end-class circle
10405: @end example
1.6 pazsan 10406:
1.78 anton 10407: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10408:
1.78 anton 10409: @c Finally, you can define named methods with @code{:m}. One use of this
10410: @c feature is the definition of words that occur only in one class and are
10411: @c not intended to be overridden, but which still need method context
10412: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10413: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10414:
10415:
1.78 anton 10416: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10417: @subsubsection Classes and Scoping
10418: @cindex classes and scoping
10419: @cindex scoping and classes
1.6 pazsan 10420:
1.78 anton 10421: Inheritance is frequent, unlike structure extension. This exacerbates
10422: the problem with the field name convention (@pxref{Structure Naming
10423: Convention}): One always has to remember in which class the field was
10424: originally defined; changing a part of the class structure would require
10425: changes for renaming in otherwise unaffected code.
1.6 pazsan 10426:
1.78 anton 10427: @cindex @code{inst-var} visibility
10428: @cindex @code{inst-value} visibility
10429: To solve this problem, I added a scoping mechanism (which was not in my
10430: original charter): A field defined with @code{inst-var} (or
10431: @code{inst-value}) is visible only in the class where it is defined and in
10432: the descendent classes of this class. Using such fields only makes
10433: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10434:
1.78 anton 10435: This scoping mechanism allows us to use the unadorned field name,
10436: because name clashes with unrelated words become much less likely.
1.6 pazsan 10437:
1.78 anton 10438: @cindex @code{protected} discussion
10439: @cindex @code{private} discussion
10440: Once we have this mechanism, we can also use it for controlling the
10441: visibility of other words: All words defined after
10442: @code{protected} are visible only in the current class and its
10443: descendents. @code{public} restores the compilation
10444: (i.e. @code{current}) word list that was in effect before. If you
10445: have several @code{protected}s without an intervening
10446: @code{public} or @code{set-current}, @code{public}
10447: will restore the compilation word list in effect before the first of
10448: these @code{protected}s.
1.6 pazsan 10449:
1.78 anton 10450: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10451: @subsubsection Dividing classes
10452: @cindex Dividing classes
10453: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10454:
1.78 anton 10455: You may want to do the definition of methods separate from the
10456: definition of the class, its selectors, fields, and instance variables,
10457: i.e., separate the implementation from the definition. You can do this
10458: in the following way:
1.6 pazsan 10459:
1.78 anton 10460: @example
10461: graphical class
10462: inst-value radius
10463: end-class circle
1.6 pazsan 10464:
1.78 anton 10465: ... \ do some other stuff
1.6 pazsan 10466:
1.78 anton 10467: circle methods \ now we are ready
1.44 crook 10468:
1.78 anton 10469: m: ( x y circle -- )
10470: radius draw-circle ;m
10471: overrides draw
1.6 pazsan 10472:
1.78 anton 10473: m: ( n-radius circle -- )
10474: [to-inst] radius ;m
10475: overrides construct
1.44 crook 10476:
1.78 anton 10477: end-methods
10478: @end example
1.7 pazsan 10479:
1.78 anton 10480: You can use several @code{methods}...@code{end-methods} sections. The
10481: only things you can do to the class in these sections are: defining
10482: methods, and overriding the class's selectors. You must not define new
10483: selectors or fields.
1.7 pazsan 10484:
1.78 anton 10485: Note that you often have to override a selector before using it. In
10486: particular, you usually have to override @code{construct} with a new
10487: method before you can invoke @code{heap-new} and friends. E.g., you
10488: must not create a circle before the @code{overrides construct} sequence
10489: in the example above.
1.7 pazsan 10490:
1.78 anton 10491: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10492: @subsubsection Object Interfaces
10493: @cindex object interfaces
10494: @cindex interfaces for objects
1.7 pazsan 10495:
1.78 anton 10496: In this model you can only call selectors defined in the class of the
10497: receiving objects or in one of its ancestors. If you call a selector
10498: with a receiving object that is not in one of these classes, the
10499: result is undefined; if you are lucky, the program crashes
10500: immediately.
1.7 pazsan 10501:
1.78 anton 10502: @cindex selectors common to hardly-related classes
10503: Now consider the case when you want to have a selector (or several)
10504: available in two classes: You would have to add the selector to a
10505: common ancestor class, in the worst case to @code{object}. You
10506: may not want to do this, e.g., because someone else is responsible for
10507: this ancestor class.
1.7 pazsan 10508:
1.78 anton 10509: The solution for this problem is interfaces. An interface is a
10510: collection of selectors. If a class implements an interface, the
10511: selectors become available to the class and its descendents. A class
10512: can implement an unlimited number of interfaces. For the problem
10513: discussed above, we would define an interface for the selector(s), and
10514: both classes would implement the interface.
1.7 pazsan 10515:
1.78 anton 10516: As an example, consider an interface @code{storage} for
10517: writing objects to disk and getting them back, and a class
10518: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10519:
1.78 anton 10520: @cindex @code{interface} usage
10521: @cindex @code{end-interface} usage
10522: @cindex @code{implementation} usage
10523: @example
10524: interface
10525: selector write ( file object -- )
10526: selector read1 ( file object -- )
10527: end-interface storage
1.13 pazsan 10528:
1.78 anton 10529: bar class
10530: storage implementation
1.13 pazsan 10531:
1.78 anton 10532: ... overrides write
10533: ... overrides read1
10534: ...
10535: end-class foo
10536: @end example
1.13 pazsan 10537:
1.78 anton 10538: @noindent
10539: (I would add a word @code{read} @i{( file -- object )} that uses
10540: @code{read1} internally, but that's beyond the point illustrated
10541: here.)
1.13 pazsan 10542:
1.78 anton 10543: Note that you cannot use @code{protected} in an interface; and
10544: of course you cannot define fields.
1.13 pazsan 10545:
1.78 anton 10546: In the Neon model, all selectors are available for all classes;
10547: therefore it does not need interfaces. The price you pay in this model
10548: is slower late binding, and therefore, added complexity to avoid late
10549: binding.
1.13 pazsan 10550:
1.78 anton 10551: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10552: @subsubsection @file{objects.fs} Implementation
10553: @cindex @file{objects.fs} implementation
1.13 pazsan 10554:
1.78 anton 10555: @cindex @code{object-map} discussion
10556: An object is a piece of memory, like one of the data structures
10557: described with @code{struct...end-struct}. It has a field
10558: @code{object-map} that points to the method map for the object's
10559: class.
1.13 pazsan 10560:
1.78 anton 10561: @cindex method map
10562: @cindex virtual function table
10563: The @emph{method map}@footnote{This is Self terminology; in C++
10564: terminology: virtual function table.} is an array that contains the
10565: execution tokens (@i{xt}s) of the methods for the object's class. Each
10566: selector contains an offset into a method map.
1.13 pazsan 10567:
1.78 anton 10568: @cindex @code{selector} implementation, class
10569: @code{selector} is a defining word that uses
10570: @code{CREATE} and @code{DOES>}. The body of the
10571: selector contains the offset; the @code{DOES>} action for a
10572: class selector is, basically:
1.8 pazsan 10573:
10574: @example
1.78 anton 10575: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10576: @end example
10577:
1.78 anton 10578: Since @code{object-map} is the first field of the object, it
10579: does not generate any code. As you can see, calling a selector has a
10580: small, constant cost.
1.26 crook 10581:
1.78 anton 10582: @cindex @code{current-interface} discussion
10583: @cindex class implementation and representation
10584: A class is basically a @code{struct} combined with a method
10585: map. During the class definition the alignment and size of the class
10586: are passed on the stack, just as with @code{struct}s, so
10587: @code{field} can also be used for defining class
10588: fields. However, passing more items on the stack would be
10589: inconvenient, so @code{class} builds a data structure in memory,
10590: which is accessed through the variable
10591: @code{current-interface}. After its definition is complete, the
10592: class is represented on the stack by a pointer (e.g., as parameter for
10593: a child class definition).
1.26 crook 10594:
1.78 anton 10595: A new class starts off with the alignment and size of its parent,
10596: and a copy of the parent's method map. Defining new fields extends the
10597: size and alignment; likewise, defining new selectors extends the
10598: method map. @code{overrides} just stores a new @i{xt} in the method
10599: map at the offset given by the selector.
1.13 pazsan 10600:
1.78 anton 10601: @cindex class binding, implementation
10602: Class binding just gets the @i{xt} at the offset given by the selector
10603: from the class's method map and @code{compile,}s (in the case of
10604: @code{[bind]}) it.
1.13 pazsan 10605:
1.78 anton 10606: @cindex @code{this} implementation
10607: @cindex @code{catch} and @code{this}
10608: @cindex @code{this} and @code{catch}
10609: I implemented @code{this} as a @code{value}. At the
10610: start of an @code{m:...;m} method the old @code{this} is
10611: stored to the return stack and restored at the end; and the object on
10612: the TOS is stored @code{TO this}. This technique has one
10613: disadvantage: If the user does not leave the method via
10614: @code{;m}, but via @code{throw} or @code{exit},
10615: @code{this} is not restored (and @code{exit} may
10616: crash). To deal with the @code{throw} problem, I have redefined
10617: @code{catch} to save and restore @code{this}; the same
10618: should be done with any word that can catch an exception. As for
10619: @code{exit}, I simply forbid it (as a replacement, there is
10620: @code{exitm}).
1.13 pazsan 10621:
1.78 anton 10622: @cindex @code{inst-var} implementation
10623: @code{inst-var} is just the same as @code{field}, with
10624: a different @code{DOES>} action:
1.13 pazsan 10625: @example
1.78 anton 10626: @@ this +
1.8 pazsan 10627: @end example
1.78 anton 10628: Similar for @code{inst-value}.
1.8 pazsan 10629:
1.78 anton 10630: @cindex class scoping implementation
10631: Each class also has a word list that contains the words defined with
10632: @code{inst-var} and @code{inst-value}, and its protected
10633: words. It also has a pointer to its parent. @code{class} pushes
10634: the word lists of the class and all its ancestors onto the search order stack,
10635: and @code{end-class} drops them.
1.20 pazsan 10636:
1.78 anton 10637: @cindex interface implementation
10638: An interface is like a class without fields, parent and protected
10639: words; i.e., it just has a method map. If a class implements an
10640: interface, its method map contains a pointer to the method map of the
10641: interface. The positive offsets in the map are reserved for class
10642: methods, therefore interface map pointers have negative
10643: offsets. Interfaces have offsets that are unique throughout the
10644: system, unlike class selectors, whose offsets are only unique for the
10645: classes where the selector is available (invokable).
1.20 pazsan 10646:
1.78 anton 10647: This structure means that interface selectors have to perform one
10648: indirection more than class selectors to find their method. Their body
10649: contains the interface map pointer offset in the class method map, and
10650: the method offset in the interface method map. The
10651: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10652:
10653: @example
1.78 anton 10654: ( object selector-body )
10655: 2dup selector-interface @@ ( object selector-body object interface-offset )
10656: swap object-map @@ + @@ ( object selector-body map )
10657: swap selector-offset @@ + @@ execute
1.20 pazsan 10658: @end example
10659:
1.78 anton 10660: where @code{object-map} and @code{selector-offset} are
10661: first fields and generate no code.
1.20 pazsan 10662:
1.78 anton 10663: As a concrete example, consider the following code:
1.20 pazsan 10664:
10665: @example
1.78 anton 10666: interface
10667: selector if1sel1
10668: selector if1sel2
10669: end-interface if1
1.20 pazsan 10670:
1.78 anton 10671: object class
10672: if1 implementation
10673: selector cl1sel1
10674: cell% inst-var cl1iv1
1.20 pazsan 10675:
1.78 anton 10676: ' m1 overrides construct
10677: ' m2 overrides if1sel1
10678: ' m3 overrides if1sel2
10679: ' m4 overrides cl1sel2
10680: end-class cl1
1.20 pazsan 10681:
1.78 anton 10682: create obj1 object dict-new drop
10683: create obj2 cl1 dict-new drop
10684: @end example
1.20 pazsan 10685:
1.78 anton 10686: The data structure created by this code (including the data structure
10687: for @code{object}) is shown in the
10688: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10689: @comment TODO add this diagram..
1.20 pazsan 10690:
1.78 anton 10691: @node Objects Glossary, , Objects Implementation, Objects
10692: @subsubsection @file{objects.fs} Glossary
10693: @cindex @file{objects.fs} Glossary
1.20 pazsan 10694:
10695:
1.78 anton 10696: doc---objects-bind
10697: doc---objects-<bind>
10698: doc---objects-bind'
10699: doc---objects-[bind]
10700: doc---objects-class
10701: doc---objects-class->map
10702: doc---objects-class-inst-size
10703: doc---objects-class-override!
1.79 anton 10704: doc---objects-class-previous
10705: doc---objects-class>order
1.78 anton 10706: doc---objects-construct
10707: doc---objects-current'
10708: doc---objects-[current]
10709: doc---objects-current-interface
10710: doc---objects-dict-new
10711: doc---objects-end-class
10712: doc---objects-end-class-noname
10713: doc---objects-end-interface
10714: doc---objects-end-interface-noname
10715: doc---objects-end-methods
10716: doc---objects-exitm
10717: doc---objects-heap-new
10718: doc---objects-implementation
10719: doc---objects-init-object
10720: doc---objects-inst-value
10721: doc---objects-inst-var
10722: doc---objects-interface
10723: doc---objects-m:
10724: doc---objects-:m
10725: doc---objects-;m
10726: doc---objects-method
10727: doc---objects-methods
10728: doc---objects-object
10729: doc---objects-overrides
10730: doc---objects-[parent]
10731: doc---objects-print
10732: doc---objects-protected
10733: doc---objects-public
10734: doc---objects-selector
10735: doc---objects-this
10736: doc---objects-<to-inst>
10737: doc---objects-[to-inst]
10738: doc---objects-to-this
10739: doc---objects-xt-new
1.20 pazsan 10740:
10741:
1.78 anton 10742: @c -------------------------------------------------------------
10743: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10744: @subsection The @file{oof.fs} model
10745: @cindex oof
10746: @cindex object-oriented programming
1.20 pazsan 10747:
1.78 anton 10748: @cindex @file{objects.fs}
10749: @cindex @file{oof.fs}
1.20 pazsan 10750:
1.78 anton 10751: This section describes the @file{oof.fs} package.
1.20 pazsan 10752:
1.78 anton 10753: The package described in this section has been used in bigFORTH since 1991, and
10754: used for two large applications: a chromatographic system used to
10755: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10756:
1.78 anton 10757: You can find a description (in German) of @file{oof.fs} in @cite{Object
10758: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10759: 10(2), 1994.
1.20 pazsan 10760:
1.78 anton 10761: @menu
10762: * Properties of the OOF model::
10763: * Basic OOF Usage::
10764: * The OOF base class::
10765: * Class Declaration::
10766: * Class Implementation::
10767: @end menu
1.20 pazsan 10768:
1.78 anton 10769: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10770: @subsubsection Properties of the @file{oof.fs} model
10771: @cindex @file{oof.fs} properties
1.20 pazsan 10772:
1.78 anton 10773: @itemize @bullet
10774: @item
10775: This model combines object oriented programming with information
10776: hiding. It helps you writing large application, where scoping is
10777: necessary, because it provides class-oriented scoping.
1.20 pazsan 10778:
1.78 anton 10779: @item
10780: Named objects, object pointers, and object arrays can be created,
10781: selector invocation uses the ``object selector'' syntax. Selector invocation
10782: to objects and/or selectors on the stack is a bit less convenient, but
10783: possible.
1.44 crook 10784:
1.78 anton 10785: @item
10786: Selector invocation and instance variable usage of the active object is
10787: straightforward, since both make use of the active object.
1.44 crook 10788:
1.78 anton 10789: @item
10790: Late binding is efficient and easy to use.
1.20 pazsan 10791:
1.78 anton 10792: @item
10793: State-smart objects parse selectors. However, extensibility is provided
10794: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10795:
1.78 anton 10796: @item
10797: An implementation in ANS Forth is available.
1.20 pazsan 10798:
1.78 anton 10799: @end itemize
1.23 crook 10800:
10801:
1.78 anton 10802: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10803: @subsubsection Basic @file{oof.fs} Usage
10804: @cindex @file{oof.fs} usage
1.23 crook 10805:
1.78 anton 10806: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10807:
1.78 anton 10808: You can define a class for graphical objects like this:
1.23 crook 10809:
1.78 anton 10810: @cindex @code{class} usage
10811: @cindex @code{class;} usage
10812: @cindex @code{method} usage
10813: @example
10814: object class graphical \ "object" is the parent class
1.139 pazsan 10815: method draw ( x y -- )
1.78 anton 10816: class;
10817: @end example
1.23 crook 10818:
1.78 anton 10819: This code defines a class @code{graphical} with an
10820: operation @code{draw}. We can perform the operation
10821: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10822:
1.78 anton 10823: @example
10824: 100 100 t-rex draw
10825: @end example
1.23 crook 10826:
1.78 anton 10827: @noindent
10828: where @code{t-rex} is an object or object pointer, created with e.g.
10829: @code{graphical : t-rex}.
1.23 crook 10830:
1.78 anton 10831: @cindex abstract class
10832: How do we create a graphical object? With the present definitions,
10833: we cannot create a useful graphical object. The class
10834: @code{graphical} describes graphical objects in general, but not
10835: any concrete graphical object type (C++ users would call it an
10836: @emph{abstract class}); e.g., there is no method for the selector
10837: @code{draw} in the class @code{graphical}.
1.23 crook 10838:
1.78 anton 10839: For concrete graphical objects, we define child classes of the
10840: class @code{graphical}, e.g.:
1.23 crook 10841:
1.78 anton 10842: @example
10843: graphical class circle \ "graphical" is the parent class
10844: cell var circle-radius
10845: how:
10846: : draw ( x y -- )
10847: circle-radius @@ draw-circle ;
1.23 crook 10848:
1.139 pazsan 10849: : init ( n-radius -- )
1.78 anton 10850: circle-radius ! ;
10851: class;
10852: @end example
1.1 anton 10853:
1.78 anton 10854: Here we define a class @code{circle} as a child of @code{graphical},
10855: with a field @code{circle-radius}; it defines new methods for the
10856: selectors @code{draw} and @code{init} (@code{init} is defined in
10857: @code{object}, the parent class of @code{graphical}).
1.1 anton 10858:
1.78 anton 10859: Now we can create a circle in the dictionary with:
1.1 anton 10860:
1.78 anton 10861: @example
10862: 50 circle : my-circle
10863: @end example
1.21 crook 10864:
1.78 anton 10865: @noindent
10866: @code{:} invokes @code{init}, thus initializing the field
10867: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10868: with:
1.1 anton 10869:
1.78 anton 10870: @example
10871: 100 100 my-circle draw
10872: @end example
1.1 anton 10873:
1.78 anton 10874: @cindex selector invocation, restrictions
10875: @cindex class definition, restrictions
10876: Note: You can only invoke a selector if the receiving object belongs to
10877: the class where the selector was defined or one of its descendents;
10878: e.g., you can invoke @code{draw} only for objects belonging to
10879: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10880: mechanism will check if you try to invoke a selector that is not
10881: defined in this class hierarchy, so you'll get an error at compilation
10882: time.
1.1 anton 10883:
10884:
1.78 anton 10885: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10886: @subsubsection The @file{oof.fs} base class
10887: @cindex @file{oof.fs} base class
1.1 anton 10888:
1.78 anton 10889: When you define a class, you have to specify a parent class. So how do
10890: you start defining classes? There is one class available from the start:
10891: @code{object}. You have to use it as ancestor for all classes. It is the
10892: only class that has no parent. Classes are also objects, except that
10893: they don't have instance variables; class manipulation such as
10894: inheritance or changing definitions of a class is handled through
10895: selectors of the class @code{object}.
1.1 anton 10896:
1.78 anton 10897: @code{object} provides a number of selectors:
1.1 anton 10898:
1.78 anton 10899: @itemize @bullet
10900: @item
10901: @code{class} for subclassing, @code{definitions} to add definitions
10902: later on, and @code{class?} to get type informations (is the class a
10903: subclass of the class passed on the stack?).
1.1 anton 10904:
1.78 anton 10905: doc---object-class
10906: doc---object-definitions
10907: doc---object-class?
1.1 anton 10908:
10909:
1.26 crook 10910: @item
1.78 anton 10911: @code{init} and @code{dispose} as constructor and destructor of the
10912: object. @code{init} is invocated after the object's memory is allocated,
10913: while @code{dispose} also handles deallocation. Thus if you redefine
10914: @code{dispose}, you have to call the parent's dispose with @code{super
10915: dispose}, too.
10916:
10917: doc---object-init
10918: doc---object-dispose
10919:
1.1 anton 10920:
1.26 crook 10921: @item
1.78 anton 10922: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10923: @code{[]} to create named and unnamed objects and object arrays or
10924: object pointers.
10925:
10926: doc---object-new
10927: doc---object-new[]
10928: doc---object-:
10929: doc---object-ptr
10930: doc---object-asptr
10931: doc---object-[]
10932:
1.1 anton 10933:
1.26 crook 10934: @item
1.78 anton 10935: @code{::} and @code{super} for explicit scoping. You should use explicit
10936: scoping only for super classes or classes with the same set of instance
10937: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10938:
1.78 anton 10939: doc---object-::
10940: doc---object-super
1.21 crook 10941:
10942:
1.26 crook 10943: @item
1.78 anton 10944: @code{self} to get the address of the object
1.21 crook 10945:
1.78 anton 10946: doc---object-self
1.21 crook 10947:
10948:
1.78 anton 10949: @item
10950: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10951: pointers and instance defers.
1.21 crook 10952:
1.78 anton 10953: doc---object-bind
10954: doc---object-bound
10955: doc---object-link
10956: doc---object-is
1.21 crook 10957:
10958:
1.78 anton 10959: @item
10960: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10961: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10962:
1.78 anton 10963: doc---object-'
10964: doc---object-postpone
1.21 crook 10965:
10966:
1.78 anton 10967: @item
10968: @code{with} and @code{endwith} to select the active object from the
10969: stack, and enable its scope. Using @code{with} and @code{endwith}
10970: also allows you to create code using selector @code{postpone} without being
10971: trapped by the state-smart objects.
1.21 crook 10972:
1.78 anton 10973: doc---object-with
10974: doc---object-endwith
1.21 crook 10975:
10976:
1.78 anton 10977: @end itemize
1.21 crook 10978:
1.78 anton 10979: @node Class Declaration, Class Implementation, The OOF base class, OOF
10980: @subsubsection Class Declaration
10981: @cindex class declaration
1.21 crook 10982:
1.78 anton 10983: @itemize @bullet
10984: @item
10985: Instance variables
1.21 crook 10986:
1.78 anton 10987: doc---oof-var
1.21 crook 10988:
10989:
1.78 anton 10990: @item
10991: Object pointers
1.21 crook 10992:
1.78 anton 10993: doc---oof-ptr
10994: doc---oof-asptr
1.21 crook 10995:
10996:
1.78 anton 10997: @item
10998: Instance defers
1.21 crook 10999:
1.78 anton 11000: doc---oof-defer
1.21 crook 11001:
11002:
1.78 anton 11003: @item
11004: Method selectors
1.21 crook 11005:
1.78 anton 11006: doc---oof-early
11007: doc---oof-method
1.21 crook 11008:
11009:
1.78 anton 11010: @item
11011: Class-wide variables
1.21 crook 11012:
1.78 anton 11013: doc---oof-static
1.21 crook 11014:
11015:
1.78 anton 11016: @item
11017: End declaration
1.1 anton 11018:
1.78 anton 11019: doc---oof-how:
11020: doc---oof-class;
1.21 crook 11021:
11022:
1.78 anton 11023: @end itemize
1.21 crook 11024:
1.78 anton 11025: @c -------------------------------------------------------------
11026: @node Class Implementation, , Class Declaration, OOF
11027: @subsubsection Class Implementation
11028: @cindex class implementation
1.21 crook 11029:
1.78 anton 11030: @c -------------------------------------------------------------
11031: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11032: @subsection The @file{mini-oof.fs} model
11033: @cindex mini-oof
1.21 crook 11034:
1.78 anton 11035: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11036: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11037: and reduces to the bare minimum of features. This is based on a posting
11038: of Bernd Paysan in comp.lang.forth.
1.21 crook 11039:
1.78 anton 11040: @menu
11041: * Basic Mini-OOF Usage::
11042: * Mini-OOF Example::
11043: * Mini-OOF Implementation::
11044: @end menu
1.21 crook 11045:
1.78 anton 11046: @c -------------------------------------------------------------
11047: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11048: @subsubsection Basic @file{mini-oof.fs} Usage
11049: @cindex mini-oof usage
1.21 crook 11050:
1.78 anton 11051: There is a base class (@code{class}, which allocates one cell for the
11052: object pointer) plus seven other words: to define a method, a variable,
11053: a class; to end a class, to resolve binding, to allocate an object and
11054: to compile a class method.
11055: @comment TODO better description of the last one
1.26 crook 11056:
1.21 crook 11057:
1.78 anton 11058: doc-object
11059: doc-method
11060: doc-var
11061: doc-class
11062: doc-end-class
11063: doc-defines
11064: doc-new
11065: doc-::
1.21 crook 11066:
11067:
11068:
1.78 anton 11069: @c -------------------------------------------------------------
11070: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11071: @subsubsection Mini-OOF Example
11072: @cindex mini-oof example
1.1 anton 11073:
1.78 anton 11074: A short example shows how to use this package. This example, in slightly
11075: extended form, is supplied as @file{moof-exm.fs}
11076: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11077:
1.26 crook 11078: @example
1.78 anton 11079: object class
11080: method init
11081: method draw
11082: end-class graphical
1.26 crook 11083: @end example
1.20 pazsan 11084:
1.78 anton 11085: This code defines a class @code{graphical} with an
11086: operation @code{draw}. We can perform the operation
11087: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11088:
1.26 crook 11089: @example
1.78 anton 11090: 100 100 t-rex draw
1.26 crook 11091: @end example
1.12 anton 11092:
1.78 anton 11093: where @code{t-rex} is an object or object pointer, created with e.g.
11094: @code{graphical new Constant t-rex}.
1.12 anton 11095:
1.78 anton 11096: For concrete graphical objects, we define child classes of the
11097: class @code{graphical}, e.g.:
1.12 anton 11098:
1.26 crook 11099: @example
11100: graphical class
1.78 anton 11101: cell var circle-radius
11102: end-class circle \ "graphical" is the parent class
1.12 anton 11103:
1.78 anton 11104: :noname ( x y -- )
11105: circle-radius @@ draw-circle ; circle defines draw
11106: :noname ( r -- )
11107: circle-radius ! ; circle defines init
11108: @end example
1.12 anton 11109:
1.78 anton 11110: There is no implicit init method, so we have to define one. The creation
11111: code of the object now has to call init explicitely.
1.21 crook 11112:
1.78 anton 11113: @example
11114: circle new Constant my-circle
11115: 50 my-circle init
1.12 anton 11116: @end example
11117:
1.78 anton 11118: It is also possible to add a function to create named objects with
11119: automatic call of @code{init}, given that all objects have @code{init}
11120: on the same place:
1.38 anton 11121:
1.78 anton 11122: @example
11123: : new: ( .. o "name" -- )
11124: new dup Constant init ;
11125: 80 circle new: large-circle
11126: @end example
1.12 anton 11127:
1.78 anton 11128: We can draw this new circle at (100,100) with:
1.12 anton 11129:
1.78 anton 11130: @example
11131: 100 100 my-circle draw
11132: @end example
1.12 anton 11133:
1.78 anton 11134: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11135: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11136:
1.78 anton 11137: Object-oriented systems with late binding typically use a
11138: ``vtable''-approach: the first variable in each object is a pointer to a
11139: table, which contains the methods as function pointers. The vtable
11140: may also contain other information.
1.12 anton 11141:
1.79 anton 11142: So first, let's declare selectors:
1.37 anton 11143:
11144: @example
1.79 anton 11145: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11146: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11147: @end example
1.37 anton 11148:
1.79 anton 11149: During selector declaration, the number of selectors and instance
11150: variables is on the stack (in address units). @code{method} creates one
11151: selector and increments the selector number. To execute a selector, it
1.78 anton 11152: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11153: executes the method @i{xt} stored there. Each selector takes the object
11154: it is invoked with as top of stack parameter; it passes the parameters
11155: (including the object) unchanged to the appropriate method which should
1.78 anton 11156: consume that object.
1.37 anton 11157:
1.78 anton 11158: Now, we also have to declare instance variables
1.37 anton 11159:
1.78 anton 11160: @example
1.79 anton 11161: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11162: DOES> ( o -- addr ) @@ + ;
1.37 anton 11163: @end example
11164:
1.78 anton 11165: As before, a word is created with the current offset. Instance
11166: variables can have different sizes (cells, floats, doubles, chars), so
11167: all we do is take the size and add it to the offset. If your machine
11168: has alignment restrictions, put the proper @code{aligned} or
11169: @code{faligned} before the variable, to adjust the variable
11170: offset. That's why it is on the top of stack.
1.37 anton 11171:
1.78 anton 11172: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11173:
1.78 anton 11174: @example
11175: Create object 1 cells , 2 cells ,
1.79 anton 11176: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11177: @end example
1.12 anton 11178:
1.78 anton 11179: For inheritance, the vtable of the parent object has to be
11180: copied when a new, derived class is declared. This gives all the
11181: methods of the parent class, which can be overridden, though.
1.12 anton 11182:
1.78 anton 11183: @example
1.79 anton 11184: : end-class ( class selectors vars "name" -- )
1.78 anton 11185: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11186: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11187: @end example
1.12 anton 11188:
1.78 anton 11189: The first line creates the vtable, initialized with
11190: @code{noop}s. The second line is the inheritance mechanism, it
11191: copies the xts from the parent vtable.
1.12 anton 11192:
1.78 anton 11193: We still have no way to define new methods, let's do that now:
1.12 anton 11194:
1.26 crook 11195: @example
1.79 anton 11196: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11197: @end example
1.12 anton 11198:
1.78 anton 11199: To allocate a new object, we need a word, too:
1.12 anton 11200:
1.78 anton 11201: @example
11202: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11203: @end example
11204:
1.78 anton 11205: Sometimes derived classes want to access the method of the
11206: parent object. There are two ways to achieve this with Mini-OOF:
11207: first, you could use named words, and second, you could look up the
11208: vtable of the parent object.
1.12 anton 11209:
1.78 anton 11210: @example
11211: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11212: @end example
1.12 anton 11213:
11214:
1.78 anton 11215: Nothing can be more confusing than a good example, so here is
11216: one. First let's declare a text object (called
11217: @code{button}), that stores text and position:
1.12 anton 11218:
1.78 anton 11219: @example
11220: object class
11221: cell var text
11222: cell var len
11223: cell var x
11224: cell var y
11225: method init
11226: method draw
11227: end-class button
11228: @end example
1.12 anton 11229:
1.78 anton 11230: @noindent
11231: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11232:
1.26 crook 11233: @example
1.78 anton 11234: :noname ( o -- )
11235: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11236: button defines draw
11237: :noname ( addr u o -- )
11238: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11239: button defines init
1.26 crook 11240: @end example
1.12 anton 11241:
1.78 anton 11242: @noindent
11243: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11244: new data and no new selectors:
1.78 anton 11245:
11246: @example
11247: button class
11248: end-class bold-button
1.12 anton 11249:
1.78 anton 11250: : bold 27 emit ." [1m" ;
11251: : normal 27 emit ." [0m" ;
11252: @end example
1.1 anton 11253:
1.78 anton 11254: @noindent
11255: The class @code{bold-button} has a different draw method to
11256: @code{button}, but the new method is defined in terms of the draw method
11257: for @code{button}:
1.20 pazsan 11258:
1.78 anton 11259: @example
11260: :noname bold [ button :: draw ] normal ; bold-button defines draw
11261: @end example
1.21 crook 11262:
1.78 anton 11263: @noindent
1.79 anton 11264: Finally, create two objects and apply selectors:
1.21 crook 11265:
1.26 crook 11266: @example
1.78 anton 11267: button new Constant foo
11268: s" thin foo" foo init
11269: page
11270: foo draw
11271: bold-button new Constant bar
11272: s" fat bar" bar init
11273: 1 bar y !
11274: bar draw
1.26 crook 11275: @end example
1.21 crook 11276:
11277:
1.78 anton 11278: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11279: @subsection Comparison with other object models
11280: @cindex comparison of object models
11281: @cindex object models, comparison
11282:
11283: Many object-oriented Forth extensions have been proposed (@cite{A survey
11284: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11285: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11286: relation of the object models described here to two well-known and two
11287: closely-related (by the use of method maps) models. Andras Zsoter
11288: helped us with this section.
11289:
11290: @cindex Neon model
11291: The most popular model currently seems to be the Neon model (see
11292: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11293: 1997) by Andrew McKewan) but this model has a number of limitations
11294: @footnote{A longer version of this critique can be
11295: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11296: Dimensions, May 1997) by Anton Ertl.}:
11297:
11298: @itemize @bullet
11299: @item
11300: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11301: to pass objects on the stack.
1.21 crook 11302:
1.78 anton 11303: @item
11304: It requires that the selector parses the input stream (at
1.79 anton 11305: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11306: hard to find.
1.21 crook 11307:
1.78 anton 11308: @item
1.79 anton 11309: It allows using every selector on every object; this eliminates the
11310: need for interfaces, but makes it harder to create efficient
11311: implementations.
1.78 anton 11312: @end itemize
1.21 crook 11313:
1.78 anton 11314: @cindex Pountain's object-oriented model
11315: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11316: Press, London, 1987) by Dick Pountain. However, it is not really about
11317: object-oriented programming, because it hardly deals with late
11318: binding. Instead, it focuses on features like information hiding and
11319: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11320:
1.78 anton 11321: @cindex Zsoter's object-oriented model
1.79 anton 11322: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11323: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11324: describes a model that makes heavy use of an active object (like
11325: @code{this} in @file{objects.fs}): The active object is not only used
11326: for accessing all fields, but also specifies the receiving object of
11327: every selector invocation; you have to change the active object
11328: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11329: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11330: the method entry point is unnecessary with Zsoter's model, because the
11331: receiving object is the active object already. On the other hand, the
11332: explicit change is absolutely necessary in that model, because otherwise
11333: no one could ever change the active object. An ANS Forth implementation
11334: of this model is available through
11335: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11336:
1.78 anton 11337: @cindex @file{oof.fs}, differences to other models
11338: The @file{oof.fs} model combines information hiding and overloading
11339: resolution (by keeping names in various word lists) with object-oriented
11340: programming. It sets the active object implicitly on method entry, but
11341: also allows explicit changing (with @code{>o...o>} or with
11342: @code{with...endwith}). It uses parsing and state-smart objects and
11343: classes for resolving overloading and for early binding: the object or
11344: class parses the selector and determines the method from this. If the
11345: selector is not parsed by an object or class, it performs a call to the
11346: selector for the active object (late binding), like Zsoter's model.
11347: Fields are always accessed through the active object. The big
11348: disadvantage of this model is the parsing and the state-smartness, which
11349: reduces extensibility and increases the opportunities for subtle bugs;
11350: essentially, you are only safe if you never tick or @code{postpone} an
11351: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11352:
1.78 anton 11353: @cindex @file{mini-oof.fs}, differences to other models
11354: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11355: version of the @file{objects.fs} model, but syntactically it is a
11356: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11357:
11358:
1.78 anton 11359: @c -------------------------------------------------------------
11360: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11361: @section Programming Tools
11362: @cindex programming tools
1.21 crook 11363:
1.78 anton 11364: @c !! move this and assembler down below OO stuff.
1.21 crook 11365:
1.78 anton 11366: @menu
11367: * Examining::
11368: * Forgetting words::
11369: * Debugging:: Simple and quick.
11370: * Assertions:: Making your programs self-checking.
11371: * Singlestep Debugger:: Executing your program word by word.
11372: @end menu
1.21 crook 11373:
1.78 anton 11374: @node Examining, Forgetting words, Programming Tools, Programming Tools
11375: @subsection Examining data and code
11376: @cindex examining data and code
11377: @cindex data examination
11378: @cindex code examination
1.44 crook 11379:
1.78 anton 11380: The following words inspect the stack non-destructively:
1.21 crook 11381:
1.78 anton 11382: doc-.s
11383: doc-f.s
1.44 crook 11384:
1.78 anton 11385: There is a word @code{.r} but it does @i{not} display the return stack!
11386: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11387:
1.78 anton 11388: doc-depth
11389: doc-fdepth
11390: doc-clearstack
1.124 anton 11391: doc-clearstacks
1.21 crook 11392:
1.78 anton 11393: The following words inspect memory.
1.21 crook 11394:
1.78 anton 11395: doc-?
11396: doc-dump
1.21 crook 11397:
1.78 anton 11398: And finally, @code{see} allows to inspect code:
1.21 crook 11399:
1.78 anton 11400: doc-see
11401: doc-xt-see
1.111 anton 11402: doc-simple-see
11403: doc-simple-see-range
1.21 crook 11404:
1.78 anton 11405: @node Forgetting words, Debugging, Examining, Programming Tools
11406: @subsection Forgetting words
11407: @cindex words, forgetting
11408: @cindex forgeting words
1.21 crook 11409:
1.78 anton 11410: @c anton: other, maybe better places for this subsection: Defining Words;
11411: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11412:
1.78 anton 11413: Forth allows you to forget words (and everything that was alloted in the
11414: dictonary after them) in a LIFO manner.
1.21 crook 11415:
1.78 anton 11416: doc-marker
1.21 crook 11417:
1.78 anton 11418: The most common use of this feature is during progam development: when
11419: you change a source file, forget all the words it defined and load it
11420: again (since you also forget everything defined after the source file
11421: was loaded, you have to reload that, too). Note that effects like
11422: storing to variables and destroyed system words are not undone when you
11423: forget words. With a system like Gforth, that is fast enough at
11424: starting up and compiling, I find it more convenient to exit and restart
11425: Gforth, as this gives me a clean slate.
1.21 crook 11426:
1.78 anton 11427: Here's an example of using @code{marker} at the start of a source file
11428: that you are debugging; it ensures that you only ever have one copy of
11429: the file's definitions compiled at any time:
1.21 crook 11430:
1.78 anton 11431: @example
11432: [IFDEF] my-code
11433: my-code
11434: [ENDIF]
1.26 crook 11435:
1.78 anton 11436: marker my-code
11437: init-included-files
1.21 crook 11438:
1.78 anton 11439: \ .. definitions start here
11440: \ .
11441: \ .
11442: \ end
11443: @end example
1.21 crook 11444:
1.26 crook 11445:
1.78 anton 11446: @node Debugging, Assertions, Forgetting words, Programming Tools
11447: @subsection Debugging
11448: @cindex debugging
1.21 crook 11449:
1.78 anton 11450: Languages with a slow edit/compile/link/test development loop tend to
11451: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11452:
1.78 anton 11453: A much better (faster) way in fast-compiling languages is to add
11454: printing code at well-selected places, let the program run, look at
11455: the output, see where things went wrong, add more printing code, etc.,
11456: until the bug is found.
1.21 crook 11457:
1.78 anton 11458: The simple debugging aids provided in @file{debugs.fs}
11459: are meant to support this style of debugging.
1.21 crook 11460:
1.78 anton 11461: The word @code{~~} prints debugging information (by default the source
11462: location and the stack contents). It is easy to insert. If you use Emacs
11463: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11464: query-replace them with nothing). The deferred words
1.101 anton 11465: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11466: @code{~~}. The default source location output format works well with
11467: Emacs' compilation mode, so you can step through the program at the
11468: source level using @kbd{C-x `} (the advantage over a stepping debugger
11469: is that you can step in any direction and you know where the crash has
11470: happened or where the strange data has occurred).
1.21 crook 11471:
1.78 anton 11472: doc-~~
11473: doc-printdebugdata
1.101 anton 11474: doc-.debugline
1.21 crook 11475:
1.106 anton 11476: @cindex filenames in @code{~~} output
11477: @code{~~} (and assertions) will usually print the wrong file name if a
11478: marker is executed in the same file after their occurance. They will
11479: print @samp{*somewhere*} as file name if a marker is executed in the
11480: same file before their occurance.
11481:
11482:
1.78 anton 11483: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11484: @subsection Assertions
11485: @cindex assertions
1.21 crook 11486:
1.78 anton 11487: It is a good idea to make your programs self-checking, especially if you
11488: make an assumption that may become invalid during maintenance (for
11489: example, that a certain field of a data structure is never zero). Gforth
11490: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11491:
11492: @example
1.78 anton 11493: assert( @i{flag} )
1.26 crook 11494: @end example
11495:
1.78 anton 11496: The code between @code{assert(} and @code{)} should compute a flag, that
11497: should be true if everything is alright and false otherwise. It should
11498: not change anything else on the stack. The overall stack effect of the
11499: assertion is @code{( -- )}. E.g.
1.21 crook 11500:
1.26 crook 11501: @example
1.78 anton 11502: assert( 1 1 + 2 = ) \ what we learn in school
11503: assert( dup 0<> ) \ assert that the top of stack is not zero
11504: assert( false ) \ this code should not be reached
1.21 crook 11505: @end example
11506:
1.78 anton 11507: The need for assertions is different at different times. During
11508: debugging, we want more checking, in production we sometimes care more
11509: for speed. Therefore, assertions can be turned off, i.e., the assertion
11510: becomes a comment. Depending on the importance of an assertion and the
11511: time it takes to check it, you may want to turn off some assertions and
11512: keep others turned on. Gforth provides several levels of assertions for
11513: this purpose:
11514:
11515:
11516: doc-assert0(
11517: doc-assert1(
11518: doc-assert2(
11519: doc-assert3(
11520: doc-assert(
11521: doc-)
1.21 crook 11522:
11523:
1.78 anton 11524: The variable @code{assert-level} specifies the highest assertions that
11525: are turned on. I.e., at the default @code{assert-level} of one,
11526: @code{assert0(} and @code{assert1(} assertions perform checking, while
11527: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11528:
1.78 anton 11529: The value of @code{assert-level} is evaluated at compile-time, not at
11530: run-time. Therefore you cannot turn assertions on or off at run-time;
11531: you have to set the @code{assert-level} appropriately before compiling a
11532: piece of code. You can compile different pieces of code at different
11533: @code{assert-level}s (e.g., a trusted library at level 1 and
11534: newly-written code at level 3).
1.26 crook 11535:
11536:
1.78 anton 11537: doc-assert-level
1.26 crook 11538:
11539:
1.78 anton 11540: If an assertion fails, a message compatible with Emacs' compilation mode
11541: is produced and the execution is aborted (currently with @code{ABORT"}.
11542: If there is interest, we will introduce a special throw code. But if you
11543: intend to @code{catch} a specific condition, using @code{throw} is
11544: probably more appropriate than an assertion).
1.106 anton 11545:
11546: @cindex filenames in assertion output
11547: Assertions (and @code{~~}) will usually print the wrong file name if a
11548: marker is executed in the same file after their occurance. They will
11549: print @samp{*somewhere*} as file name if a marker is executed in the
11550: same file before their occurance.
1.44 crook 11551:
1.78 anton 11552: Definitions in ANS Forth for these assertion words are provided
11553: in @file{compat/assert.fs}.
1.26 crook 11554:
1.44 crook 11555:
1.78 anton 11556: @node Singlestep Debugger, , Assertions, Programming Tools
11557: @subsection Singlestep Debugger
11558: @cindex singlestep Debugger
11559: @cindex debugging Singlestep
1.44 crook 11560:
1.112 anton 11561: The singlestep debugger does not work in this release.
11562:
1.78 anton 11563: When you create a new word there's often the need to check whether it
11564: behaves correctly or not. You can do this by typing @code{dbg
11565: badword}. A debug session might look like this:
1.26 crook 11566:
1.78 anton 11567: @example
11568: : badword 0 DO i . LOOP ; ok
11569: 2 dbg badword
11570: : badword
11571: Scanning code...
1.44 crook 11572:
1.78 anton 11573: Nesting debugger ready!
1.44 crook 11574:
1.78 anton 11575: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11576: 400D4740 8049F68 DO -> [ 0 ]
11577: 400D4744 804A0C8 i -> [ 1 ] 00000
11578: 400D4748 400C5E60 . -> 0 [ 0 ]
11579: 400D474C 8049D0C LOOP -> [ 0 ]
11580: 400D4744 804A0C8 i -> [ 1 ] 00001
11581: 400D4748 400C5E60 . -> 1 [ 0 ]
11582: 400D474C 8049D0C LOOP -> [ 0 ]
11583: 400D4758 804B384 ; -> ok
11584: @end example
1.21 crook 11585:
1.78 anton 11586: Each line displayed is one step. You always have to hit return to
11587: execute the next word that is displayed. If you don't want to execute
11588: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11589: an overview what keys are available:
1.44 crook 11590:
1.78 anton 11591: @table @i
1.44 crook 11592:
1.78 anton 11593: @item @key{RET}
11594: Next; Execute the next word.
1.21 crook 11595:
1.78 anton 11596: @item n
11597: Nest; Single step through next word.
1.44 crook 11598:
1.78 anton 11599: @item u
11600: Unnest; Stop debugging and execute rest of word. If we got to this word
11601: with nest, continue debugging with the calling word.
1.44 crook 11602:
1.78 anton 11603: @item d
11604: Done; Stop debugging and execute rest.
1.21 crook 11605:
1.78 anton 11606: @item s
11607: Stop; Abort immediately.
1.44 crook 11608:
1.78 anton 11609: @end table
1.44 crook 11610:
1.78 anton 11611: Debugging large application with this mechanism is very difficult, because
11612: you have to nest very deeply into the program before the interesting part
11613: begins. This takes a lot of time.
1.26 crook 11614:
1.78 anton 11615: To do it more directly put a @code{BREAK:} command into your source code.
11616: When program execution reaches @code{BREAK:} the single step debugger is
11617: invoked and you have all the features described above.
1.44 crook 11618:
1.78 anton 11619: If you have more than one part to debug it is useful to know where the
11620: program has stopped at the moment. You can do this by the
11621: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11622: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11623:
1.26 crook 11624:
1.78 anton 11625: doc-dbg
11626: doc-break:
11627: doc-break"
1.44 crook 11628:
11629:
1.26 crook 11630:
1.78 anton 11631: @c -------------------------------------------------------------
11632: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11633: @section Assembler and Code Words
11634: @cindex assembler
11635: @cindex code words
1.44 crook 11636:
1.78 anton 11637: @menu
11638: * Code and ;code::
11639: * Common Assembler:: Assembler Syntax
11640: * Common Disassembler::
11641: * 386 Assembler:: Deviations and special cases
11642: * Alpha Assembler:: Deviations and special cases
11643: * MIPS assembler:: Deviations and special cases
11644: * Other assemblers:: How to write them
11645: @end menu
1.21 crook 11646:
1.78 anton 11647: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11648: @subsection @code{Code} and @code{;code}
1.26 crook 11649:
1.78 anton 11650: Gforth provides some words for defining primitives (words written in
11651: machine code), and for defining the machine-code equivalent of
11652: @code{DOES>}-based defining words. However, the machine-independent
11653: nature of Gforth poses a few problems: First of all, Gforth runs on
11654: several architectures, so it can provide no standard assembler. What's
11655: worse is that the register allocation not only depends on the processor,
11656: but also on the @code{gcc} version and options used.
1.44 crook 11657:
1.78 anton 11658: The words that Gforth offers encapsulate some system dependences (e.g.,
11659: the header structure), so a system-independent assembler may be used in
11660: Gforth. If you do not have an assembler, you can compile machine code
11661: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11662: because these words emit stuff in @i{data} space; it works because
11663: Gforth has unified code/data spaces. Assembler isn't likely to be
11664: portable anyway.}.
1.21 crook 11665:
1.44 crook 11666:
1.78 anton 11667: doc-assembler
11668: doc-init-asm
11669: doc-code
11670: doc-end-code
11671: doc-;code
11672: doc-flush-icache
1.44 crook 11673:
1.21 crook 11674:
1.78 anton 11675: If @code{flush-icache} does not work correctly, @code{code} words
11676: etc. will not work (reliably), either.
1.44 crook 11677:
1.78 anton 11678: The typical usage of these @code{code} words can be shown most easily by
11679: analogy to the equivalent high-level defining words:
1.44 crook 11680:
1.78 anton 11681: @example
11682: : foo code foo
11683: <high-level Forth words> <assembler>
11684: ; end-code
11685:
11686: : bar : bar
11687: <high-level Forth words> <high-level Forth words>
11688: CREATE CREATE
11689: <high-level Forth words> <high-level Forth words>
11690: DOES> ;code
11691: <high-level Forth words> <assembler>
11692: ; end-code
11693: @end example
1.21 crook 11694:
1.78 anton 11695: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11696:
1.78 anton 11697: @cindex registers of the inner interpreter
11698: In the assembly code you will want to refer to the inner interpreter's
11699: registers (e.g., the data stack pointer) and you may want to use other
11700: registers for temporary storage. Unfortunately, the register allocation
11701: is installation-dependent.
1.44 crook 11702:
1.78 anton 11703: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11704: (return stack pointer) may be in different places in @code{gforth} and
11705: @code{gforth-fast}, or different installations. This means that you
11706: cannot write a @code{NEXT} routine that works reliably on both versions
11707: or different installations; so for doing @code{NEXT}, I recommend
11708: jumping to @code{' noop >code-address}, which contains nothing but a
11709: @code{NEXT}.
1.21 crook 11710:
1.78 anton 11711: For general accesses to the inner interpreter's registers, the easiest
11712: solution is to use explicit register declarations (@pxref{Explicit Reg
11713: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11714: all of the inner interpreter's registers: You have to compile Gforth
11715: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11716: the appropriate declarations must be present in the @code{machine.h}
11717: file (see @code{mips.h} for an example; you can find a full list of all
11718: declarable register symbols with @code{grep register engine.c}). If you
11719: give explicit registers to all variables that are declared at the
11720: beginning of @code{engine()}, you should be able to use the other
11721: caller-saved registers for temporary storage. Alternatively, you can use
11722: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11723: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11724: reserve a register (however, this restriction on register allocation may
11725: slow Gforth significantly).
1.44 crook 11726:
1.78 anton 11727: If this solution is not viable (e.g., because @code{gcc} does not allow
11728: you to explicitly declare all the registers you need), you have to find
11729: out by looking at the code where the inner interpreter's registers
11730: reside and which registers can be used for temporary storage. You can
11731: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11732:
1.78 anton 11733: In any case, it is good practice to abstract your assembly code from the
11734: actual register allocation. E.g., if the data stack pointer resides in
11735: register @code{$17}, create an alias for this register called @code{sp},
11736: and use that in your assembly code.
1.21 crook 11737:
1.78 anton 11738: @cindex code words, portable
11739: Another option for implementing normal and defining words efficiently
11740: is to add the desired functionality to the source of Gforth. For normal
11741: words you just have to edit @file{primitives} (@pxref{Automatic
11742: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11743: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11744: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11745:
1.78 anton 11746: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11747: @subsection Common Assembler
1.44 crook 11748:
1.78 anton 11749: The assemblers in Gforth generally use a postfix syntax, i.e., the
11750: instruction name follows the operands.
1.21 crook 11751:
1.78 anton 11752: The operands are passed in the usual order (the same that is used in the
11753: manual of the architecture). Since they all are Forth words, they have
11754: to be separated by spaces; you can also use Forth words to compute the
11755: operands.
1.44 crook 11756:
1.78 anton 11757: The instruction names usually end with a @code{,}. This makes it easier
11758: to visually separate instructions if you put several of them on one
11759: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11760:
1.78 anton 11761: Registers are usually specified by number; e.g., (decimal) @code{11}
11762: specifies registers R11 and F11 on the Alpha architecture (which one,
11763: depends on the instruction). The usual names are also available, e.g.,
11764: @code{s2} for R11 on Alpha.
1.21 crook 11765:
1.78 anton 11766: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11767: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11768: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11769: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11770: conditions are specified in a way specific to each assembler.
1.1 anton 11771:
1.78 anton 11772: Note that the register assignments of the Gforth engine can change
11773: between Gforth versions, or even between different compilations of the
11774: same Gforth version (e.g., if you use a different GCC version). So if
11775: you want to refer to Gforth's registers (e.g., the stack pointer or
11776: TOS), I recommend defining your own words for refering to these
11777: registers, and using them later on; then you can easily adapt to a
11778: changed register assignment. The stability of the register assignment
11779: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11780:
1.100 anton 11781: The most common use of these registers is to dispatch to the next word
11782: (the @code{next} routine). A portable way to do this is to jump to
11783: @code{' noop >code-address} (of course, this is less efficient than
11784: integrating the @code{next} code and scheduling it well).
1.1 anton 11785:
1.96 anton 11786: Another difference between Gforth version is that the top of stack is
11787: kept in memory in @code{gforth} and, on most platforms, in a register in
11788: @code{gforth-fast}.
11789:
1.78 anton 11790: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11791: @subsection Common Disassembler
1.127 anton 11792: @cindex disassembler, general
11793: @cindex gdb disassembler
1.1 anton 11794:
1.78 anton 11795: You can disassemble a @code{code} word with @code{see}
11796: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11797:
1.127 anton 11798: doc-discode
1.44 crook 11799:
1.127 anton 11800: There are two kinds of disassembler for Gforth: The Forth disassembler
11801: (available on some CPUs) and the gdb disassembler (available on
11802: platforms with @command{gdb} and @command{mktemp}). If both are
11803: available, the Forth disassembler is used by default. If you prefer
11804: the gdb disassembler, say
11805:
11806: @example
11807: ' disasm-gdb is discode
11808: @end example
11809:
11810: If neither is available, @code{discode} performs @code{dump}.
11811:
11812: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11813: assembler (i.e., same syntax, etc.). It also includes additional
11814: information in comments. In particular, the address of the instruction
11815: is given in a comment before the instruction.
1.1 anton 11816:
1.127 anton 11817: The gdb disassembler produces output in the same format as the gdb
11818: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11819: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11820: the 386 and AMD64 architectures).
11821:
1.78 anton 11822: @code{See} may display more or less than the actual code of the word,
11823: because the recognition of the end of the code is unreliable. You can
1.127 anton 11824: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11825: the code word is not immediately followed by a named word. If you have
1.116 anton 11826: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11827: to ensure that the end is recognized.
1.21 crook 11828:
1.78 anton 11829: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11830: @subsection 386 Assembler
1.44 crook 11831:
1.78 anton 11832: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11833: available under GPL, and originally part of bigFORTH.
1.21 crook 11834:
1.78 anton 11835: The 386 disassembler included in Gforth was written by Andrew McKewan
11836: and is in the public domain.
1.21 crook 11837:
1.91 anton 11838: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11839:
1.78 anton 11840: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11841:
1.78 anton 11842: The assembler includes all instruction of the Athlon, i.e. 486 core
11843: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11844: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11845: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11846:
1.78 anton 11847: There are several prefixes to switch between different operation sizes,
11848: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11849: double-word accesses. Addressing modes can be switched with @code{.wa}
11850: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11851: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11852:
1.78 anton 11853: For floating point operations, the prefixes are @code{.fs} (IEEE
11854: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11855: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11856:
1.78 anton 11857: The MMX opcodes don't have size prefixes, they are spelled out like in
11858: the Intel assembler. Instead of move from and to memory, there are
11859: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11860:
1.78 anton 11861: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11862: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11863: e.g., @code{3 #}. Here are some examples of addressing modes in various
11864: syntaxes:
1.21 crook 11865:
1.26 crook 11866: @example
1.91 anton 11867: Gforth Intel (NASM) AT&T (gas) Name
11868: .w ax ax %ax register (16 bit)
11869: ax eax %eax register (32 bit)
11870: 3 # offset 3 $3 immediate
11871: 1000 #) byte ptr 1000 1000 displacement
11872: bx ) [ebx] (%ebx) base
11873: 100 di d) 100[edi] 100(%edi) base+displacement
11874: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11875: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11876: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11877: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11878: @end example
11879:
11880: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11881: @code{DI)} to enforce 32-bit displacement fields (useful for
11882: later patching).
1.21 crook 11883:
1.78 anton 11884: Some example of instructions are:
1.1 anton 11885:
11886: @example
1.78 anton 11887: ax bx mov \ move ebx,eax
11888: 3 # ax mov \ mov eax,3
1.137 pazsan 11889: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 11890: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11891: .w ax bx mov \ mov bx,ax
1.1 anton 11892: @end example
11893:
1.78 anton 11894: The following forms are supported for binary instructions:
1.1 anton 11895:
11896: @example
1.78 anton 11897: <reg> <reg> <inst>
11898: <n> # <reg> <inst>
11899: <mem> <reg> <inst>
11900: <reg> <mem> <inst>
1.136 pazsan 11901: <n> # <mem> <inst>
1.1 anton 11902: @end example
11903:
1.136 pazsan 11904: The shift/rotate syntax is:
1.1 anton 11905:
1.26 crook 11906: @example
1.78 anton 11907: <reg/mem> 1 # shl \ shortens to shift without immediate
11908: <reg/mem> 4 # shl
11909: <reg/mem> cl shl
1.26 crook 11910: @end example
1.1 anton 11911:
1.78 anton 11912: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11913: the byte version.
1.1 anton 11914:
1.78 anton 11915: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11916: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11917: pc < >= <= >}. (Note that most of these words shadow some Forth words
11918: when @code{assembler} is in front of @code{forth} in the search path,
11919: e.g., in @code{code} words). Currently the control structure words use
11920: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11921: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11922:
1.78 anton 11923: Here is an example of a @code{code} word (assumes that the stack pointer
11924: is in esi and the TOS is in ebx):
1.21 crook 11925:
1.26 crook 11926: @example
1.78 anton 11927: code my+ ( n1 n2 -- n )
11928: 4 si D) bx add
11929: 4 # si add
11930: Next
11931: end-code
1.26 crook 11932: @end example
1.21 crook 11933:
1.78 anton 11934: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11935: @subsection Alpha Assembler
1.21 crook 11936:
1.78 anton 11937: The Alpha assembler and disassembler were originally written by Bernd
11938: Thallner.
1.26 crook 11939:
1.78 anton 11940: The register names @code{a0}--@code{a5} are not available to avoid
11941: shadowing hex numbers.
1.2 jwilke 11942:
1.78 anton 11943: Immediate forms of arithmetic instructions are distinguished by a
11944: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11945: does not count as arithmetic instruction).
1.2 jwilke 11946:
1.78 anton 11947: You have to specify all operands to an instruction, even those that
11948: other assemblers consider optional, e.g., the destination register for
11949: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11950:
1.78 anton 11951: You can specify conditions for @code{if,} by removing the first @code{b}
11952: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11953:
1.26 crook 11954: @example
1.78 anton 11955: 11 fgt if, \ if F11>0e
11956: ...
11957: endif,
1.26 crook 11958: @end example
1.2 jwilke 11959:
1.78 anton 11960: @code{fbgt,} gives @code{fgt}.
11961:
11962: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11963: @subsection MIPS assembler
1.2 jwilke 11964:
1.78 anton 11965: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11966:
1.78 anton 11967: Currently the assembler and disassembler only cover the MIPS-I
11968: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11969:
1.78 anton 11970: The register names @code{$a0}--@code{$a3} are not available to avoid
11971: shadowing hex numbers.
1.2 jwilke 11972:
1.78 anton 11973: Because there is no way to distinguish registers from immediate values,
11974: you have to explicitly use the immediate forms of instructions, i.e.,
11975: @code{addiu,}, not just @code{addu,} (@command{as} does this
11976: implicitly).
1.2 jwilke 11977:
1.78 anton 11978: If the architecture manual specifies several formats for the instruction
11979: (e.g., for @code{jalr,}), you usually have to use the one with more
11980: arguments (i.e., two for @code{jalr,}). When in doubt, see
11981: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11982:
1.78 anton 11983: Branches and jumps in the MIPS architecture have a delay slot. You have
11984: to fill it yourself (the simplest way is to use @code{nop,}), the
11985: assembler does not do it for you (unlike @command{as}). Even
11986: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11987: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11988: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11989:
1.78 anton 11990: Note that you must not put branches, jumps, or @code{li,} into the delay
11991: slot: @code{li,} may expand to several instructions, and control flow
11992: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11993:
1.78 anton 11994: For branches the argument specifying the target is a relative address;
11995: You have to add the address of the delay slot to get the absolute
11996: address.
1.1 anton 11997:
1.78 anton 11998: The MIPS architecture also has load delay slots and restrictions on
11999: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12000: yourself to satisfy these restrictions, the assembler does not do it for
12001: you.
1.1 anton 12002:
1.78 anton 12003: You can specify the conditions for @code{if,} etc. by taking a
12004: conditional branch and leaving away the @code{b} at the start and the
12005: @code{,} at the end. E.g.,
1.1 anton 12006:
1.26 crook 12007: @example
1.78 anton 12008: 4 5 eq if,
12009: ... \ do something if $4 equals $5
12010: then,
1.26 crook 12011: @end example
1.1 anton 12012:
1.78 anton 12013: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12014: @subsection Other assemblers
12015:
12016: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12017: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12018: an assembler already. If you are writing them from scratch, please use
12019: a similar syntax style as the one we use (i.e., postfix, commas at the
12020: end of the instruction names, @pxref{Common Assembler}); make the output
12021: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12022: similar to the style we used.
12023:
12024: Hints on implementation: The most important part is to have a good test
12025: suite that contains all instructions. Once you have that, the rest is
12026: easy. For actual coding you can take a look at
12027: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12028: the assembler and disassembler, avoiding redundancy and some potential
12029: bugs. You can also look at that file (and @pxref{Advanced does> usage
12030: example}) to get ideas how to factor a disassembler.
12031:
12032: Start with the disassembler, because it's easier to reuse data from the
12033: disassembler for the assembler than the other way round.
1.1 anton 12034:
1.78 anton 12035: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12036: how simple it can be.
1.1 anton 12037:
1.78 anton 12038: @c -------------------------------------------------------------
12039: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12040: @section Threading Words
12041: @cindex threading words
1.1 anton 12042:
1.78 anton 12043: @cindex code address
12044: These words provide access to code addresses and other threading stuff
12045: in Gforth (and, possibly, other interpretive Forths). It more or less
12046: abstracts away the differences between direct and indirect threading
12047: (and, for direct threading, the machine dependences). However, at
12048: present this wordset is still incomplete. It is also pretty low-level;
12049: some day it will hopefully be made unnecessary by an internals wordset
12050: that abstracts implementation details away completely.
1.1 anton 12051:
1.78 anton 12052: The terminology used here stems from indirect threaded Forth systems; in
12053: such a system, the XT of a word is represented by the CFA (code field
12054: address) of a word; the CFA points to a cell that contains the code
12055: address. The code address is the address of some machine code that
12056: performs the run-time action of invoking the word (e.g., the
12057: @code{dovar:} routine pushes the address of the body of the word (a
12058: variable) on the stack
12059: ).
1.1 anton 12060:
1.78 anton 12061: @cindex code address
12062: @cindex code field address
12063: In an indirect threaded Forth, you can get the code address of @i{name}
12064: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12065: >code-address}, independent of the threading method.
1.1 anton 12066:
1.78 anton 12067: doc-threading-method
12068: doc->code-address
12069: doc-code-address!
1.1 anton 12070:
1.78 anton 12071: @cindex @code{does>}-handler
12072: @cindex @code{does>}-code
12073: For a word defined with @code{DOES>}, the code address usually points to
12074: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12075: routine (in Gforth on some platforms, it can also point to the dodoes
12076: routine itself). What you are typically interested in, though, is
12077: whether a word is a @code{DOES>}-defined word, and what Forth code it
12078: executes; @code{>does-code} tells you that.
1.1 anton 12079:
1.78 anton 12080: doc->does-code
1.1 anton 12081:
1.78 anton 12082: To create a @code{DOES>}-defined word with the following basic words,
12083: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12084: @code{/does-handler} aus behind you have to place your executable Forth
12085: code. Finally you have to create a word and modify its behaviour with
12086: @code{does-handler!}.
1.1 anton 12087:
1.78 anton 12088: doc-does-code!
12089: doc-does-handler!
12090: doc-/does-handler
1.1 anton 12091:
1.78 anton 12092: The code addresses produced by various defining words are produced by
12093: the following words:
1.1 anton 12094:
1.78 anton 12095: doc-docol:
12096: doc-docon:
12097: doc-dovar:
12098: doc-douser:
12099: doc-dodefer:
12100: doc-dofield:
1.1 anton 12101:
1.99 anton 12102: @cindex definer
12103: The following two words generalize @code{>code-address},
12104: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12105:
12106: doc->definer
12107: doc-definer!
12108:
1.26 crook 12109: @c -------------------------------------------------------------
1.78 anton 12110: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12111: @section Passing Commands to the Operating System
12112: @cindex operating system - passing commands
12113: @cindex shell commands
12114:
12115: Gforth allows you to pass an arbitrary string to the host operating
12116: system shell (if such a thing exists) for execution.
12117:
12118: doc-sh
12119: doc-system
12120: doc-$?
1.23 crook 12121: doc-getenv
1.44 crook 12122:
1.26 crook 12123: @c -------------------------------------------------------------
1.47 crook 12124: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12125: @section Keeping track of Time
12126: @cindex time-related words
12127:
12128: doc-ms
12129: doc-time&date
1.79 anton 12130: doc-utime
12131: doc-cputime
1.47 crook 12132:
12133:
12134: @c -------------------------------------------------------------
12135: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12136: @section Miscellaneous Words
12137: @cindex miscellaneous words
12138:
1.29 crook 12139: @comment TODO find homes for these
12140:
1.26 crook 12141: These section lists the ANS Forth words that are not documented
1.21 crook 12142: elsewhere in this manual. Ultimately, they all need proper homes.
12143:
1.68 anton 12144: doc-quit
1.44 crook 12145:
1.26 crook 12146: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12147: (@pxref{ANS conformance}):
1.21 crook 12148:
12149: @code{EDITOR}
12150: @code{EMIT?}
12151: @code{FORGET}
12152:
1.24 anton 12153: @c ******************************************************************
12154: @node Error messages, Tools, Words, Top
12155: @chapter Error messages
12156: @cindex error messages
12157: @cindex backtrace
12158:
12159: A typical Gforth error message looks like this:
12160:
12161: @example
1.86 anton 12162: in file included from \evaluated string/:-1
1.24 anton 12163: in file included from ./yyy.fs:1
12164: ./xxx.fs:4: Invalid memory address
1.134 anton 12165: >>>bar<<<
1.79 anton 12166: Backtrace:
1.25 anton 12167: $400E664C @@
12168: $400E6664 foo
1.24 anton 12169: @end example
12170:
12171: The message identifying the error is @code{Invalid memory address}. The
12172: error happened when text-interpreting line 4 of the file
12173: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12174: word on the line where the error happened, is pointed out (with
1.134 anton 12175: @code{>>>} and @code{<<<}).
1.24 anton 12176:
12177: The file containing the error was included in line 1 of @file{./yyy.fs},
12178: and @file{yyy.fs} was included from a non-file (in this case, by giving
12179: @file{yyy.fs} as command-line parameter to Gforth).
12180:
12181: At the end of the error message you find a return stack dump that can be
12182: interpreted as a backtrace (possibly empty). On top you find the top of
12183: the return stack when the @code{throw} happened, and at the bottom you
12184: find the return stack entry just above the return stack of the topmost
12185: text interpreter.
12186:
12187: To the right of most return stack entries you see a guess for the word
12188: that pushed that return stack entry as its return address. This gives a
12189: backtrace. In our case we see that @code{bar} called @code{foo}, and
12190: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12191: address} exception).
12192:
12193: Note that the backtrace is not perfect: We don't know which return stack
12194: entries are return addresses (so we may get false positives); and in
12195: some cases (e.g., for @code{abort"}) we cannot determine from the return
12196: address the word that pushed the return address, so for some return
12197: addresses you see no names in the return stack dump.
1.25 anton 12198:
12199: @cindex @code{catch} and backtraces
12200: The return stack dump represents the return stack at the time when a
12201: specific @code{throw} was executed. In programs that make use of
12202: @code{catch}, it is not necessarily clear which @code{throw} should be
12203: used for the return stack dump (e.g., consider one @code{throw} that
12204: indicates an error, which is caught, and during recovery another error
1.42 anton 12205: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12206: presents the return stack dump for the first @code{throw} after the last
12207: executed (not returned-to) @code{catch}; this works well in the usual
12208: case.
12209:
12210: @cindex @code{gforth-fast} and backtraces
12211: @cindex @code{gforth-fast}, difference from @code{gforth}
12212: @cindex backtraces with @code{gforth-fast}
12213: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12214: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12215: from primitives (e.g., invalid memory address, stack empty etc.);
12216: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12217: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12218: exception caused by a primitive in @code{gforth-fast}, you will
12219: typically see no return stack dump at all; however, if the exception is
12220: caught by @code{catch} (e.g., for restoring some state), and then
12221: @code{throw}n again, the return stack dump will be for the first such
12222: @code{throw}.
1.2 jwilke 12223:
1.5 anton 12224: @c ******************************************************************
1.24 anton 12225: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12226: @chapter Tools
12227:
12228: @menu
12229: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12230: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12231: @end menu
12232:
12233: See also @ref{Emacs and Gforth}.
12234:
1.126 pazsan 12235: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12236: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12237: @cindex @file{ans-report.fs}
12238: @cindex report the words used in your program
12239: @cindex words used in your program
12240:
12241: If you want to label a Forth program as ANS Forth Program, you must
12242: document which wordsets the program uses; for extension wordsets, it is
12243: helpful to list the words the program requires from these wordsets
12244: (because Forth systems are allowed to provide only some words of them).
12245:
12246: The @file{ans-report.fs} tool makes it easy for you to determine which
12247: words from which wordset and which non-ANS words your application
12248: uses. You simply have to include @file{ans-report.fs} before loading the
12249: program you want to check. After loading your program, you can get the
12250: report with @code{print-ans-report}. A typical use is to run this as
12251: batch job like this:
12252: @example
12253: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12254: @end example
12255:
12256: The output looks like this (for @file{compat/control.fs}):
12257: @example
12258: The program uses the following words
12259: from CORE :
12260: : POSTPONE THEN ; immediate ?dup IF 0=
12261: from BLOCK-EXT :
12262: \
12263: from FILE :
12264: (
12265: @end example
12266:
12267: @subsection Caveats
12268:
12269: Note that @file{ans-report.fs} just checks which words are used, not whether
12270: they are used in an ANS Forth conforming way!
12271:
12272: Some words are defined in several wordsets in the
12273: standard. @file{ans-report.fs} reports them for only one of the
12274: wordsets, and not necessarily the one you expect. It depends on usage
12275: which wordset is the right one to specify. E.g., if you only use the
12276: compilation semantics of @code{S"}, it is a Core word; if you also use
12277: its interpretation semantics, it is a File word.
1.124 anton 12278:
12279:
1.127 anton 12280: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12281: @section Stack depth changes during interpretation
12282: @cindex @file{depth-changes.fs}
12283: @cindex depth changes during interpretation
12284: @cindex stack depth changes during interpretation
12285: @cindex items on the stack after interpretation
12286:
12287: Sometimes you notice that, after loading a file, there are items left
12288: on the stack. The tool @file{depth-changes.fs} helps you find out
12289: quickly where in the file these stack items are coming from.
12290:
12291: The simplest way of using @file{depth-changes.fs} is to include it
12292: before the file(s) you want to check, e.g.:
12293:
12294: @example
12295: gforth depth-changes.fs my-file.fs
12296: @end example
12297:
12298: This will compare the stack depths of the data and FP stack at every
12299: empty line (in interpretation state) against these depths at the last
12300: empty line (in interpretation state). If the depths are not equal,
12301: the position in the file and the stack contents are printed with
12302: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12303: change has occured in the paragraph of non-empty lines before the
12304: indicated line. It is a good idea to leave an empty line at the end
12305: of the file, so the last paragraph is checked, too.
12306:
12307: Checking only at empty lines usually works well, but sometimes you
12308: have big blocks of non-empty lines (e.g., when building a big table),
12309: and you want to know where in this block the stack depth changed. You
12310: can check all interpreted lines with
12311:
12312: @example
12313: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12314: @end example
12315:
12316: This checks the stack depth at every end-of-line. So the depth change
12317: occured in the line reported by the @code{~~} (not in the line
12318: before).
12319:
12320: Note that, while this offers better accuracy in indicating where the
12321: stack depth changes, it will often report many intentional stack depth
12322: changes (e.g., when an interpreted computation stretches across
12323: several lines). You can suppress the checking of some lines by
12324: putting backslashes at the end of these lines (not followed by white
12325: space), and using
12326:
12327: @example
12328: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12329: @end example
1.1 anton 12330:
12331: @c ******************************************************************
1.65 anton 12332: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12333: @chapter ANS conformance
12334: @cindex ANS conformance of Gforth
12335:
12336: To the best of our knowledge, Gforth is an
12337:
12338: ANS Forth System
12339: @itemize @bullet
12340: @item providing the Core Extensions word set
12341: @item providing the Block word set
12342: @item providing the Block Extensions word set
12343: @item providing the Double-Number word set
12344: @item providing the Double-Number Extensions word set
12345: @item providing the Exception word set
12346: @item providing the Exception Extensions word set
12347: @item providing the Facility word set
1.40 anton 12348: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12349: @item providing the File Access word set
12350: @item providing the File Access Extensions word set
12351: @item providing the Floating-Point word set
12352: @item providing the Floating-Point Extensions word set
12353: @item providing the Locals word set
12354: @item providing the Locals Extensions word set
12355: @item providing the Memory-Allocation word set
12356: @item providing the Memory-Allocation Extensions word set (that one's easy)
12357: @item providing the Programming-Tools word set
12358: @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
12359: @item providing the Search-Order word set
12360: @item providing the Search-Order Extensions word set
12361: @item providing the String word set
12362: @item providing the String Extensions word set (another easy one)
12363: @end itemize
12364:
1.118 anton 12365: Gforth has the following environmental restrictions:
12366:
12367: @cindex environmental restrictions
12368: @itemize @bullet
12369: @item
12370: While processing the OS command line, if an exception is not caught,
12371: Gforth exits with a non-zero exit code instyead of performing QUIT.
12372:
12373: @item
12374: When an @code{throw} is performed after a @code{query}, Gforth does not
12375: allways restore the input source specification in effect at the
12376: corresponding catch.
12377:
12378: @end itemize
12379:
12380:
1.1 anton 12381: @cindex system documentation
12382: In addition, ANS Forth systems are required to document certain
12383: implementation choices. This chapter tries to meet these
12384: requirements. In many cases it gives a way to ask the system for the
12385: information instead of providing the information directly, in
12386: particular, if the information depends on the processor, the operating
12387: system or the installation options chosen, or if they are likely to
12388: change during the maintenance of Gforth.
12389:
12390: @comment The framework for the rest has been taken from pfe.
12391:
12392: @menu
12393: * The Core Words::
12394: * The optional Block word set::
12395: * The optional Double Number word set::
12396: * The optional Exception word set::
12397: * The optional Facility word set::
12398: * The optional File-Access word set::
12399: * The optional Floating-Point word set::
12400: * The optional Locals word set::
12401: * The optional Memory-Allocation word set::
12402: * The optional Programming-Tools word set::
12403: * The optional Search-Order word set::
12404: @end menu
12405:
12406:
12407: @c =====================================================================
12408: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12409: @comment node-name, next, previous, up
12410: @section The Core Words
12411: @c =====================================================================
12412: @cindex core words, system documentation
12413: @cindex system documentation, core words
12414:
12415: @menu
12416: * core-idef:: Implementation Defined Options
12417: * core-ambcond:: Ambiguous Conditions
12418: * core-other:: Other System Documentation
12419: @end menu
12420:
12421: @c ---------------------------------------------------------------------
12422: @node core-idef, core-ambcond, The Core Words, The Core Words
12423: @subsection Implementation Defined Options
12424: @c ---------------------------------------------------------------------
12425: @cindex core words, implementation-defined options
12426: @cindex implementation-defined options, core words
12427:
12428:
12429: @table @i
12430: @item (Cell) aligned addresses:
12431: @cindex cell-aligned addresses
12432: @cindex aligned addresses
12433: processor-dependent. Gforth's alignment words perform natural alignment
12434: (e.g., an address aligned for a datum of size 8 is divisible by
12435: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12436:
12437: @item @code{EMIT} and non-graphic characters:
12438: @cindex @code{EMIT} and non-graphic characters
12439: @cindex non-graphic characters and @code{EMIT}
12440: The character is output using the C library function (actually, macro)
12441: @code{putc}.
12442:
12443: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12444: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12445: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12446: @cindex @code{ACCEPT}, editing
12447: @cindex @code{EXPECT}, editing
12448: This is modeled on the GNU readline library (@pxref{Readline
12449: Interaction, , Command Line Editing, readline, The GNU Readline
12450: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12451: producing a full word completion every time you type it (instead of
1.28 crook 12452: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12453:
12454: @item character set:
12455: @cindex character set
12456: The character set of your computer and display device. Gforth is
12457: 8-bit-clean (but some other component in your system may make trouble).
12458:
12459: @item Character-aligned address requirements:
12460: @cindex character-aligned address requirements
12461: installation-dependent. Currently a character is represented by a C
12462: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12463: (Comments on that requested).
12464:
12465: @item character-set extensions and matching of names:
12466: @cindex character-set extensions and matching of names
1.26 crook 12467: @cindex case-sensitivity for name lookup
12468: @cindex name lookup, case-sensitivity
12469: @cindex locale and case-sensitivity
1.21 crook 12470: Any character except the ASCII NUL character can be used in a
1.1 anton 12471: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12472: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12473: function is probably influenced by the locale. E.g., the @code{C} locale
12474: does not know about accents and umlauts, so they are matched
12475: case-sensitively in that locale. For portability reasons it is best to
12476: write programs such that they work in the @code{C} locale. Then one can
12477: use libraries written by a Polish programmer (who might use words
12478: containing ISO Latin-2 encoded characters) and by a French programmer
12479: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12480: funny results for some of the words (which ones, depends on the font you
12481: are using)). Also, the locale you prefer may not be available in other
12482: operating systems. Hopefully, Unicode will solve these problems one day.
12483:
12484: @item conditions under which control characters match a space delimiter:
12485: @cindex space delimiters
12486: @cindex control characters as delimiters
1.117 anton 12487: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12488: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12489: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12490: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12491: interpreter (aka text interpreter) by default, treats all white-space
12492: characters as delimiters.
12493:
1.26 crook 12494: @item format of the control-flow stack:
12495: @cindex control-flow stack, format
12496: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12497: stack item in cells is given by the constant @code{cs-item-size}. At the
12498: time of this writing, an item consists of a (pointer to a) locals list
12499: (third), an address in the code (second), and a tag for identifying the
12500: item (TOS). The following tags are used: @code{defstart},
12501: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12502: @code{scopestart}.
12503:
12504: @item conversion of digits > 35
12505: @cindex digits > 35
12506: The characters @code{[\]^_'} are the digits with the decimal value
12507: 36@minus{}41. There is no way to input many of the larger digits.
12508:
12509: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12510: @cindex @code{EXPECT}, display after end of input
12511: @cindex @code{ACCEPT}, display after end of input
12512: The cursor is moved to the end of the entered string. If the input is
12513: terminated using the @kbd{Return} key, a space is typed.
12514:
12515: @item exception abort sequence of @code{ABORT"}:
12516: @cindex exception abort sequence of @code{ABORT"}
12517: @cindex @code{ABORT"}, exception abort sequence
12518: The error string is stored into the variable @code{"error} and a
12519: @code{-2 throw} is performed.
12520:
12521: @item input line terminator:
12522: @cindex input line terminator
12523: @cindex line terminator on input
1.26 crook 12524: @cindex newline character on input
1.1 anton 12525: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12526: lines. One of these characters is typically produced when you type the
12527: @kbd{Enter} or @kbd{Return} key.
12528:
12529: @item maximum size of a counted string:
12530: @cindex maximum size of a counted string
12531: @cindex counted string, maximum size
12532: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12533: on all platforms, but this may change.
1.1 anton 12534:
12535: @item maximum size of a parsed string:
12536: @cindex maximum size of a parsed string
12537: @cindex parsed string, maximum size
12538: Given by the constant @code{/line}. Currently 255 characters.
12539:
12540: @item maximum size of a definition name, in characters:
12541: @cindex maximum size of a definition name, in characters
12542: @cindex name, maximum length
1.113 anton 12543: MAXU/8
1.1 anton 12544:
12545: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12546: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12547: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12548: MAXU/8
1.1 anton 12549:
12550: @item method of selecting the user input device:
12551: @cindex user input device, method of selecting
12552: The user input device is the standard input. There is currently no way to
12553: change it from within Gforth. However, the input can typically be
12554: redirected in the command line that starts Gforth.
12555:
12556: @item method of selecting the user output device:
12557: @cindex user output device, method of selecting
12558: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12559: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12560: output when the user output device is a terminal, otherwise the output
12561: is buffered.
1.1 anton 12562:
12563: @item methods of dictionary compilation:
12564: What are we expected to document here?
12565:
12566: @item number of bits in one address unit:
12567: @cindex number of bits in one address unit
12568: @cindex address unit, size in bits
12569: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12570: platforms.
1.1 anton 12571:
12572: @item number representation and arithmetic:
12573: @cindex number representation and arithmetic
1.79 anton 12574: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12575:
12576: @item ranges for integer types:
12577: @cindex ranges for integer types
12578: @cindex integer types, ranges
12579: Installation-dependent. Make environmental queries for @code{MAX-N},
12580: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12581: unsigned (and positive) types is 0. The lower bound for signed types on
12582: two's complement and one's complement machines machines can be computed
12583: by adding 1 to the upper bound.
12584:
12585: @item read-only data space regions:
12586: @cindex read-only data space regions
12587: @cindex data-space, read-only regions
12588: The whole Forth data space is writable.
12589:
12590: @item size of buffer at @code{WORD}:
12591: @cindex size of buffer at @code{WORD}
12592: @cindex @code{WORD} buffer size
12593: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12594: shared with the pictured numeric output string. If overwriting
12595: @code{PAD} is acceptable, it is as large as the remaining dictionary
12596: space, although only as much can be sensibly used as fits in a counted
12597: string.
12598:
12599: @item size of one cell in address units:
12600: @cindex cell size
12601: @code{1 cells .}.
12602:
12603: @item size of one character in address units:
12604: @cindex char size
1.79 anton 12605: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12606:
12607: @item size of the keyboard terminal buffer:
12608: @cindex size of the keyboard terminal buffer
12609: @cindex terminal buffer, size
12610: Varies. You can determine the size at a specific time using @code{lp@@
12611: tib - .}. It is shared with the locals stack and TIBs of files that
12612: include the current file. You can change the amount of space for TIBs
12613: and locals stack at Gforth startup with the command line option
12614: @code{-l}.
12615:
12616: @item size of the pictured numeric output buffer:
12617: @cindex size of the pictured numeric output buffer
12618: @cindex pictured numeric output buffer, size
12619: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12620: shared with @code{WORD}.
12621:
12622: @item size of the scratch area returned by @code{PAD}:
12623: @cindex size of the scratch area returned by @code{PAD}
12624: @cindex @code{PAD} size
12625: The remainder of dictionary space. @code{unused pad here - - .}.
12626:
12627: @item system case-sensitivity characteristics:
12628: @cindex case-sensitivity characteristics
1.26 crook 12629: Dictionary searches are case-insensitive (except in
1.1 anton 12630: @code{TABLE}s). However, as explained above under @i{character-set
12631: extensions}, the matching for non-ASCII characters is determined by the
12632: locale you are using. In the default @code{C} locale all non-ASCII
12633: characters are matched case-sensitively.
12634:
12635: @item system prompt:
12636: @cindex system prompt
12637: @cindex prompt
12638: @code{ ok} in interpret state, @code{ compiled} in compile state.
12639:
12640: @item division rounding:
12641: @cindex division rounding
12642: installation dependent. @code{s" floored" environment? drop .}. We leave
12643: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12644: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12645:
12646: @item values of @code{STATE} when true:
12647: @cindex @code{STATE} values
12648: -1.
12649:
12650: @item values returned after arithmetic overflow:
12651: On two's complement machines, arithmetic is performed modulo
12652: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12653: arithmetic (with appropriate mapping for signed types). Division by zero
12654: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12655: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12656:
12657: @item whether the current definition can be found after @t{DOES>}:
12658: @cindex @t{DOES>}, visibility of current definition
12659: No.
12660:
12661: @end table
12662:
12663: @c ---------------------------------------------------------------------
12664: @node core-ambcond, core-other, core-idef, The Core Words
12665: @subsection Ambiguous conditions
12666: @c ---------------------------------------------------------------------
12667: @cindex core words, ambiguous conditions
12668: @cindex ambiguous conditions, core words
12669:
12670: @table @i
12671:
12672: @item a name is neither a word nor a number:
12673: @cindex name not found
1.26 crook 12674: @cindex undefined word
1.80 anton 12675: @code{-13 throw} (Undefined word).
1.1 anton 12676:
12677: @item a definition name exceeds the maximum length allowed:
1.26 crook 12678: @cindex word name too long
1.1 anton 12679: @code{-19 throw} (Word name too long)
12680:
12681: @item addressing a region not inside the various data spaces of the forth system:
12682: @cindex Invalid memory address
1.32 anton 12683: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12684: typically readable. Accessing other addresses gives results dependent on
12685: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12686: address).
12687:
12688: @item argument type incompatible with parameter:
1.26 crook 12689: @cindex argument type mismatch
1.1 anton 12690: This is usually not caught. Some words perform checks, e.g., the control
12691: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12692: mismatch).
12693:
12694: @item attempting to obtain the execution token of a word with undefined execution semantics:
12695: @cindex Interpreting a compile-only word, for @code{'} etc.
12696: @cindex execution token of words with undefined execution semantics
12697: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12698: get an execution token for @code{compile-only-error} (which performs a
12699: @code{-14 throw} when executed).
12700:
12701: @item dividing by zero:
12702: @cindex dividing by zero
12703: @cindex floating point unidentified fault, integer division
1.80 anton 12704: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12705: zero); on other systems, this typically results in a @code{-55 throw}
12706: (Floating-point unidentified fault).
1.1 anton 12707:
12708: @item insufficient data stack or return stack space:
12709: @cindex insufficient data stack or return stack space
12710: @cindex stack overflow
1.26 crook 12711: @cindex address alignment exception, stack overflow
1.1 anton 12712: @cindex Invalid memory address, stack overflow
12713: Depending on the operating system, the installation, and the invocation
12714: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12715: it is not checked. If it is checked, you typically get a @code{-3 throw}
12716: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12717: throw} (Invalid memory address) (depending on the platform and how you
12718: achieved the overflow) as soon as the overflow happens. If it is not
12719: checked, overflows typically result in mysterious illegal memory
12720: accesses, producing @code{-9 throw} (Invalid memory address) or
12721: @code{-23 throw} (Address alignment exception); they might also destroy
12722: the internal data structure of @code{ALLOCATE} and friends, resulting in
12723: various errors in these words.
1.1 anton 12724:
12725: @item insufficient space for loop control parameters:
12726: @cindex insufficient space for loop control parameters
1.80 anton 12727: Like other return stack overflows.
1.1 anton 12728:
12729: @item insufficient space in the dictionary:
12730: @cindex insufficient space in the dictionary
12731: @cindex dictionary overflow
1.12 anton 12732: If you try to allot (either directly with @code{allot}, or indirectly
12733: with @code{,}, @code{create} etc.) more memory than available in the
12734: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12735: to access memory beyond the end of the dictionary, the results are
12736: similar to stack overflows.
1.1 anton 12737:
12738: @item interpreting a word with undefined interpretation semantics:
12739: @cindex interpreting a word with undefined interpretation semantics
12740: @cindex Interpreting a compile-only word
12741: For some words, we have defined interpretation semantics. For the
12742: others: @code{-14 throw} (Interpreting a compile-only word).
12743:
12744: @item modifying the contents of the input buffer or a string literal:
12745: @cindex modifying the contents of the input buffer or a string literal
12746: These are located in writable memory and can be modified.
12747:
12748: @item overflow of the pictured numeric output string:
12749: @cindex overflow of the pictured numeric output string
12750: @cindex pictured numeric output string, overflow
1.24 anton 12751: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12752:
12753: @item parsed string overflow:
12754: @cindex parsed string overflow
12755: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12756:
12757: @item producing a result out of range:
12758: @cindex result out of range
12759: On two's complement machines, arithmetic is performed modulo
12760: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12761: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12762: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12763: throw} (floating point unidentified fault). @code{convert} and
12764: @code{>number} currently overflow silently.
1.1 anton 12765:
12766: @item reading from an empty data or return stack:
12767: @cindex stack empty
12768: @cindex stack underflow
1.24 anton 12769: @cindex return stack underflow
1.1 anton 12770: The data stack is checked by the outer (aka text) interpreter after
12771: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12772: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12773: depending on operating system, installation, and invocation. If they are
12774: caught by a check, they typically result in @code{-4 throw} (Stack
12775: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12776: (Invalid memory address), depending on the platform and which stack
12777: underflows and by how much. Note that even if the system uses checking
12778: (through the MMU), your program may have to underflow by a significant
12779: number of stack items to trigger the reaction (the reason for this is
12780: that the MMU, and therefore the checking, works with a page-size
12781: granularity). If there is no checking, the symptoms resulting from an
12782: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12783: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12784: (Invalid memory address) and Illegal Instruction (typically @code{-260
12785: throw}).
1.1 anton 12786:
12787: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12788: @cindex unexpected end of the input buffer
12789: @cindex zero-length string as a name
12790: @cindex Attempt to use zero-length string as a name
12791: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12792: use zero-length string as a name). Words like @code{'} probably will not
12793: find what they search. Note that it is possible to create zero-length
12794: names with @code{nextname} (should it not?).
12795:
12796: @item @code{>IN} greater than input buffer:
12797: @cindex @code{>IN} greater than input buffer
12798: The next invocation of a parsing word returns a string with length 0.
12799:
12800: @item @code{RECURSE} appears after @code{DOES>}:
12801: @cindex @code{RECURSE} appears after @code{DOES>}
12802: Compiles a recursive call to the defining word, not to the defined word.
12803:
12804: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12805: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12806: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12807: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12808: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12809: the end of the file was reached), its source-id may be
12810: reused. Therefore, restoring an input source specification referencing a
12811: closed file may lead to unpredictable results instead of a @code{-12
12812: THROW}.
12813:
12814: In the future, Gforth may be able to restore input source specifications
12815: from other than the current input source.
12816:
12817: @item data space containing definitions gets de-allocated:
12818: @cindex data space containing definitions gets de-allocated
12819: Deallocation with @code{allot} is not checked. This typically results in
12820: memory access faults or execution of illegal instructions.
12821:
12822: @item data space read/write with incorrect alignment:
12823: @cindex data space read/write with incorrect alignment
12824: @cindex alignment faults
1.26 crook 12825: @cindex address alignment exception
1.1 anton 12826: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12827: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12828: alignment turned on, incorrect alignment results in a @code{-9 throw}
12829: (Invalid memory address). There are reportedly some processors with
1.12 anton 12830: alignment restrictions that do not report violations.
1.1 anton 12831:
12832: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12833: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12834: Like other alignment errors.
12835:
12836: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12837: Like other stack underflows.
12838:
12839: @item loop control parameters not available:
12840: @cindex loop control parameters not available
12841: Not checked. The counted loop words simply assume that the top of return
12842: stack items are loop control parameters and behave accordingly.
12843:
12844: @item most recent definition does not have a name (@code{IMMEDIATE}):
12845: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12846: @cindex last word was headerless
12847: @code{abort" last word was headerless"}.
12848:
12849: @item name not defined by @code{VALUE} used by @code{TO}:
12850: @cindex name not defined by @code{VALUE} used by @code{TO}
12851: @cindex @code{TO} on non-@code{VALUE}s
12852: @cindex Invalid name argument, @code{TO}
12853: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12854: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12855:
12856: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12857: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12858: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12859: @code{-13 throw} (Undefined word)
12860:
12861: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12862: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12863: Gforth behaves as if they were of the same type. I.e., you can predict
12864: the behaviour by interpreting all parameters as, e.g., signed.
12865:
12866: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12867: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12868: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12869: compilation semantics of @code{TO}.
12870:
12871: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12872: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12873: @cindex @code{WORD}, string overflow
12874: Not checked. The string will be ok, but the count will, of course,
12875: contain only the least significant bits of the length.
12876:
12877: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12878: @cindex @code{LSHIFT}, large shift counts
12879: @cindex @code{RSHIFT}, large shift counts
12880: Processor-dependent. Typical behaviours are returning 0 and using only
12881: the low bits of the shift count.
12882:
12883: @item word not defined via @code{CREATE}:
12884: @cindex @code{>BODY} of non-@code{CREATE}d words
12885: @code{>BODY} produces the PFA of the word no matter how it was defined.
12886:
12887: @cindex @code{DOES>} of non-@code{CREATE}d words
12888: @code{DOES>} changes the execution semantics of the last defined word no
12889: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12890: @code{CREATE , DOES>}.
12891:
12892: @item words improperly used outside @code{<#} and @code{#>}:
12893: Not checked. As usual, you can expect memory faults.
12894:
12895: @end table
12896:
12897:
12898: @c ---------------------------------------------------------------------
12899: @node core-other, , core-ambcond, The Core Words
12900: @subsection Other system documentation
12901: @c ---------------------------------------------------------------------
12902: @cindex other system documentation, core words
12903: @cindex core words, other system documentation
12904:
12905: @table @i
12906: @item nonstandard words using @code{PAD}:
12907: @cindex @code{PAD} use by nonstandard words
12908: None.
12909:
12910: @item operator's terminal facilities available:
12911: @cindex operator's terminal facilities available
1.80 anton 12912: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12913: and you can give commands to Gforth interactively. The actual facilities
12914: available depend on how you invoke Gforth.
12915:
12916: @item program data space available:
12917: @cindex program data space available
12918: @cindex data space available
12919: @code{UNUSED .} gives the remaining dictionary space. The total
12920: dictionary space can be specified with the @code{-m} switch
12921: (@pxref{Invoking Gforth}) when Gforth starts up.
12922:
12923: @item return stack space available:
12924: @cindex return stack space available
12925: You can compute the total return stack space in cells with
12926: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12927: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12928:
12929: @item stack space available:
12930: @cindex stack space available
12931: You can compute the total data stack space in cells with
12932: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12933: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12934:
12935: @item system dictionary space required, in address units:
12936: @cindex system dictionary space required, in address units
12937: Type @code{here forthstart - .} after startup. At the time of this
12938: writing, this gives 80080 (bytes) on a 32-bit system.
12939: @end table
12940:
12941:
12942: @c =====================================================================
12943: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12944: @section The optional Block word set
12945: @c =====================================================================
12946: @cindex system documentation, block words
12947: @cindex block words, system documentation
12948:
12949: @menu
12950: * block-idef:: Implementation Defined Options
12951: * block-ambcond:: Ambiguous Conditions
12952: * block-other:: Other System Documentation
12953: @end menu
12954:
12955:
12956: @c ---------------------------------------------------------------------
12957: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12958: @subsection Implementation Defined Options
12959: @c ---------------------------------------------------------------------
12960: @cindex implementation-defined options, block words
12961: @cindex block words, implementation-defined options
12962:
12963: @table @i
12964: @item the format for display by @code{LIST}:
12965: @cindex @code{LIST} display format
12966: First the screen number is displayed, then 16 lines of 64 characters,
12967: each line preceded by the line number.
12968:
12969: @item the length of a line affected by @code{\}:
12970: @cindex length of a line affected by @code{\}
12971: @cindex @code{\}, line length in blocks
12972: 64 characters.
12973: @end table
12974:
12975:
12976: @c ---------------------------------------------------------------------
12977: @node block-ambcond, block-other, block-idef, The optional Block word set
12978: @subsection Ambiguous conditions
12979: @c ---------------------------------------------------------------------
12980: @cindex block words, ambiguous conditions
12981: @cindex ambiguous conditions, block words
12982:
12983: @table @i
12984: @item correct block read was not possible:
12985: @cindex block read not possible
12986: Typically results in a @code{throw} of some OS-derived value (between
12987: -512 and -2048). If the blocks file was just not long enough, blanks are
12988: supplied for the missing portion.
12989:
12990: @item I/O exception in block transfer:
12991: @cindex I/O exception in block transfer
12992: @cindex block transfer, I/O exception
12993: Typically results in a @code{throw} of some OS-derived value (between
12994: -512 and -2048).
12995:
12996: @item invalid block number:
12997: @cindex invalid block number
12998: @cindex block number invalid
12999: @code{-35 throw} (Invalid block number)
13000:
13001: @item a program directly alters the contents of @code{BLK}:
13002: @cindex @code{BLK}, altering @code{BLK}
13003: The input stream is switched to that other block, at the same
13004: position. If the storing to @code{BLK} happens when interpreting
13005: non-block input, the system will get quite confused when the block ends.
13006:
13007: @item no current block buffer for @code{UPDATE}:
13008: @cindex @code{UPDATE}, no current block buffer
13009: @code{UPDATE} has no effect.
13010:
13011: @end table
13012:
13013: @c ---------------------------------------------------------------------
13014: @node block-other, , block-ambcond, The optional Block word set
13015: @subsection Other system documentation
13016: @c ---------------------------------------------------------------------
13017: @cindex other system documentation, block words
13018: @cindex block words, other system documentation
13019:
13020: @table @i
13021: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13022: No restrictions (yet).
13023:
13024: @item the number of blocks available for source and data:
13025: depends on your disk space.
13026:
13027: @end table
13028:
13029:
13030: @c =====================================================================
13031: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13032: @section The optional Double Number word set
13033: @c =====================================================================
13034: @cindex system documentation, double words
13035: @cindex double words, system documentation
13036:
13037: @menu
13038: * double-ambcond:: Ambiguous Conditions
13039: @end menu
13040:
13041:
13042: @c ---------------------------------------------------------------------
13043: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13044: @subsection Ambiguous conditions
13045: @c ---------------------------------------------------------------------
13046: @cindex double words, ambiguous conditions
13047: @cindex ambiguous conditions, double words
13048:
13049: @table @i
1.29 crook 13050: @item @i{d} outside of range of @i{n} in @code{D>S}:
13051: @cindex @code{D>S}, @i{d} out of range of @i{n}
13052: The least significant cell of @i{d} is produced.
1.1 anton 13053:
13054: @end table
13055:
13056:
13057: @c =====================================================================
13058: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13059: @section The optional Exception word set
13060: @c =====================================================================
13061: @cindex system documentation, exception words
13062: @cindex exception words, system documentation
13063:
13064: @menu
13065: * exception-idef:: Implementation Defined Options
13066: @end menu
13067:
13068:
13069: @c ---------------------------------------------------------------------
13070: @node exception-idef, , The optional Exception word set, The optional Exception word set
13071: @subsection Implementation Defined Options
13072: @c ---------------------------------------------------------------------
13073: @cindex implementation-defined options, exception words
13074: @cindex exception words, implementation-defined options
13075:
13076: @table @i
13077: @item @code{THROW}-codes used in the system:
13078: @cindex @code{THROW}-codes used in the system
13079: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13080: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13081: codes -512@minus{}-2047 are used for OS errors (for file and memory
13082: allocation operations). The mapping from OS error numbers to throw codes
13083: is -512@minus{}@code{errno}. One side effect of this mapping is that
13084: undefined OS errors produce a message with a strange number; e.g.,
13085: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13086: @end table
13087:
13088: @c =====================================================================
13089: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13090: @section The optional Facility word set
13091: @c =====================================================================
13092: @cindex system documentation, facility words
13093: @cindex facility words, system documentation
13094:
13095: @menu
13096: * facility-idef:: Implementation Defined Options
13097: * facility-ambcond:: Ambiguous Conditions
13098: @end menu
13099:
13100:
13101: @c ---------------------------------------------------------------------
13102: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13103: @subsection Implementation Defined Options
13104: @c ---------------------------------------------------------------------
13105: @cindex implementation-defined options, facility words
13106: @cindex facility words, implementation-defined options
13107:
13108: @table @i
13109: @item encoding of keyboard events (@code{EKEY}):
13110: @cindex keyboard events, encoding in @code{EKEY}
13111: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13112: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13113: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13114: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13115: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13116: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13117:
1.1 anton 13118:
13119: @item duration of a system clock tick:
13120: @cindex duration of a system clock tick
13121: @cindex clock tick duration
13122: System dependent. With respect to @code{MS}, the time is specified in
13123: microseconds. How well the OS and the hardware implement this, is
13124: another question.
13125:
13126: @item repeatability to be expected from the execution of @code{MS}:
13127: @cindex repeatability to be expected from the execution of @code{MS}
13128: @cindex @code{MS}, repeatability to be expected
13129: System dependent. On Unix, a lot depends on load. If the system is
13130: lightly loaded, and the delay is short enough that Gforth does not get
13131: swapped out, the performance should be acceptable. Under MS-DOS and
13132: other single-tasking systems, it should be good.
13133:
13134: @end table
13135:
13136:
13137: @c ---------------------------------------------------------------------
13138: @node facility-ambcond, , facility-idef, The optional Facility word set
13139: @subsection Ambiguous conditions
13140: @c ---------------------------------------------------------------------
13141: @cindex facility words, ambiguous conditions
13142: @cindex ambiguous conditions, facility words
13143:
13144: @table @i
13145: @item @code{AT-XY} can't be performed on user output device:
13146: @cindex @code{AT-XY} can't be performed on user output device
13147: Largely terminal dependent. No range checks are done on the arguments.
13148: No errors are reported. You may see some garbage appearing, you may see
13149: simply nothing happen.
13150:
13151: @end table
13152:
13153:
13154: @c =====================================================================
13155: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13156: @section The optional File-Access word set
13157: @c =====================================================================
13158: @cindex system documentation, file words
13159: @cindex file words, system documentation
13160:
13161: @menu
13162: * file-idef:: Implementation Defined Options
13163: * file-ambcond:: Ambiguous Conditions
13164: @end menu
13165:
13166: @c ---------------------------------------------------------------------
13167: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13168: @subsection Implementation Defined Options
13169: @c ---------------------------------------------------------------------
13170: @cindex implementation-defined options, file words
13171: @cindex file words, implementation-defined options
13172:
13173: @table @i
13174: @item file access methods used:
13175: @cindex file access methods used
13176: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13177: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13178: @code{wb}): The file is cleared, if it exists, and created, if it does
13179: not (with both @code{open-file} and @code{create-file}). Under Unix
13180: @code{create-file} creates a file with 666 permissions modified by your
13181: umask.
13182:
13183: @item file exceptions:
13184: @cindex file exceptions
13185: The file words do not raise exceptions (except, perhaps, memory access
13186: faults when you pass illegal addresses or file-ids).
13187:
13188: @item file line terminator:
13189: @cindex file line terminator
13190: System-dependent. Gforth uses C's newline character as line
13191: terminator. What the actual character code(s) of this are is
13192: system-dependent.
13193:
13194: @item file name format:
13195: @cindex file name format
13196: System dependent. Gforth just uses the file name format of your OS.
13197:
13198: @item information returned by @code{FILE-STATUS}:
13199: @cindex @code{FILE-STATUS}, returned information
13200: @code{FILE-STATUS} returns the most powerful file access mode allowed
13201: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13202: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13203: along with the returned mode.
13204:
13205: @item input file state after an exception when including source:
13206: @cindex exception when including source
13207: All files that are left via the exception are closed.
13208:
1.29 crook 13209: @item @i{ior} values and meaning:
13210: @cindex @i{ior} values and meaning
1.68 anton 13211: @cindex @i{wior} values and meaning
1.29 crook 13212: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13213: intended as throw codes. They typically are in the range
13214: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13215: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13216:
13217: @item maximum depth of file input nesting:
13218: @cindex maximum depth of file input nesting
13219: @cindex file input nesting, maximum depth
13220: limited by the amount of return stack, locals/TIB stack, and the number
13221: of open files available. This should not give you troubles.
13222:
13223: @item maximum size of input line:
13224: @cindex maximum size of input line
13225: @cindex input line size, maximum
13226: @code{/line}. Currently 255.
13227:
13228: @item methods of mapping block ranges to files:
13229: @cindex mapping block ranges to files
13230: @cindex files containing blocks
13231: @cindex blocks in files
13232: By default, blocks are accessed in the file @file{blocks.fb} in the
13233: current working directory. The file can be switched with @code{USE}.
13234:
13235: @item number of string buffers provided by @code{S"}:
13236: @cindex @code{S"}, number of string buffers
13237: 1
13238:
13239: @item size of string buffer used by @code{S"}:
13240: @cindex @code{S"}, size of string buffer
13241: @code{/line}. currently 255.
13242:
13243: @end table
13244:
13245: @c ---------------------------------------------------------------------
13246: @node file-ambcond, , file-idef, The optional File-Access word set
13247: @subsection Ambiguous conditions
13248: @c ---------------------------------------------------------------------
13249: @cindex file words, ambiguous conditions
13250: @cindex ambiguous conditions, file words
13251:
13252: @table @i
13253: @item attempting to position a file outside its boundaries:
13254: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13255: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13256: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13257:
13258: @item attempting to read from file positions not yet written:
13259: @cindex reading from file positions not yet written
13260: End-of-file, i.e., zero characters are read and no error is reported.
13261:
1.29 crook 13262: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13263: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13264: An appropriate exception may be thrown, but a memory fault or other
13265: problem is more probable.
13266:
1.29 crook 13267: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13268: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13269: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13270: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13271: thrown.
13272:
13273: @item named file cannot be opened (@code{INCLUDED}):
13274: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13275: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13276:
13277: @item requesting an unmapped block number:
13278: @cindex unmapped block numbers
13279: There are no unmapped legal block numbers. On some operating systems,
13280: writing a block with a large number may overflow the file system and
13281: have an error message as consequence.
13282:
13283: @item using @code{source-id} when @code{blk} is non-zero:
13284: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13285: @code{source-id} performs its function. Typically it will give the id of
13286: the source which loaded the block. (Better ideas?)
13287:
13288: @end table
13289:
13290:
13291: @c =====================================================================
13292: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13293: @section The optional Floating-Point word set
13294: @c =====================================================================
13295: @cindex system documentation, floating-point words
13296: @cindex floating-point words, system documentation
13297:
13298: @menu
13299: * floating-idef:: Implementation Defined Options
13300: * floating-ambcond:: Ambiguous Conditions
13301: @end menu
13302:
13303:
13304: @c ---------------------------------------------------------------------
13305: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13306: @subsection Implementation Defined Options
13307: @c ---------------------------------------------------------------------
13308: @cindex implementation-defined options, floating-point words
13309: @cindex floating-point words, implementation-defined options
13310:
13311: @table @i
13312: @item format and range of floating point numbers:
13313: @cindex format and range of floating point numbers
13314: @cindex floating point numbers, format and range
13315: System-dependent; the @code{double} type of C.
13316:
1.29 crook 13317: @item results of @code{REPRESENT} when @i{float} is out of range:
13318: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13319: System dependent; @code{REPRESENT} is implemented using the C library
13320: function @code{ecvt()} and inherits its behaviour in this respect.
13321:
13322: @item rounding or truncation of floating-point numbers:
13323: @cindex rounding of floating-point numbers
13324: @cindex truncation of floating-point numbers
13325: @cindex floating-point numbers, rounding or truncation
13326: System dependent; the rounding behaviour is inherited from the hosting C
13327: compiler. IEEE-FP-based (i.e., most) systems by default round to
13328: nearest, and break ties by rounding to even (i.e., such that the last
13329: bit of the mantissa is 0).
13330:
13331: @item size of floating-point stack:
13332: @cindex floating-point stack size
13333: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13334: the floating-point stack (in floats). You can specify this on startup
13335: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13336:
13337: @item width of floating-point stack:
13338: @cindex floating-point stack width
13339: @code{1 floats}.
13340:
13341: @end table
13342:
13343:
13344: @c ---------------------------------------------------------------------
13345: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13346: @subsection Ambiguous conditions
13347: @c ---------------------------------------------------------------------
13348: @cindex floating-point words, ambiguous conditions
13349: @cindex ambiguous conditions, floating-point words
13350:
13351: @table @i
13352: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13353: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13354: System-dependent. Typically results in a @code{-23 THROW} like other
13355: alignment violations.
13356:
13357: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13358: @cindex @code{f@@} used with an address that is not float aligned
13359: @cindex @code{f!} used with an address that is not float aligned
13360: System-dependent. Typically results in a @code{-23 THROW} like other
13361: alignment violations.
13362:
13363: @item floating-point result out of range:
13364: @cindex floating-point result out of range
1.80 anton 13365: System-dependent. Can result in a @code{-43 throw} (floating point
13366: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13367: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13368: unidentified fault), or can produce a special value representing, e.g.,
13369: Infinity.
13370:
13371: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13372: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13373: System-dependent. Typically results in an alignment fault like other
13374: alignment violations.
13375:
1.35 anton 13376: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13377: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13378: The floating-point number is converted into decimal nonetheless.
13379:
13380: @item Both arguments are equal to zero (@code{FATAN2}):
13381: @cindex @code{FATAN2}, both arguments are equal to zero
13382: System-dependent. @code{FATAN2} is implemented using the C library
13383: function @code{atan2()}.
13384:
1.29 crook 13385: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13386: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13387: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13388: because of small errors and the tan will be a very large (or very small)
13389: but finite number.
13390:
1.29 crook 13391: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13392: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13393: The result is rounded to the nearest float.
13394:
13395: @item dividing by zero:
13396: @cindex dividing by zero, floating-point
13397: @cindex floating-point dividing by zero
13398: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13399: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13400: (floating point divide by zero) or @code{-55 throw} (Floating-point
13401: unidentified fault).
1.1 anton 13402:
13403: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13404: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13405: System dependent. On IEEE-FP based systems the number is converted into
13406: an infinity.
13407:
1.29 crook 13408: @item @i{float}<1 (@code{FACOSH}):
13409: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13410: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13411: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13412:
1.29 crook 13413: @item @i{float}=<-1 (@code{FLNP1}):
13414: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13415: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13416: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13417: negative infinity for @i{float}=-1).
1.1 anton 13418:
1.29 crook 13419: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13420: @cindex @code{FLN}, @i{float}=<0
13421: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13422: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13423: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13424: negative infinity for @i{float}=0).
1.1 anton 13425:
1.29 crook 13426: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13427: @cindex @code{FASINH}, @i{float}<0
13428: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13429: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13430: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13431: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13432: C library?).
1.1 anton 13433:
1.29 crook 13434: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13435: @cindex @code{FACOS}, |@i{float}|>1
13436: @cindex @code{FASIN}, |@i{float}|>1
13437: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13438: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13439: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13440:
1.29 crook 13441: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13442: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13443: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13444: Platform-dependent; typically, some double number is produced and no
13445: error is reported.
1.1 anton 13446:
13447: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13448: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13449: @code{Precision} characters of the numeric output area are used. If
13450: @code{precision} is too high, these words will smash the data or code
13451: close to @code{here}.
1.1 anton 13452: @end table
13453:
13454: @c =====================================================================
13455: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13456: @section The optional Locals word set
13457: @c =====================================================================
13458: @cindex system documentation, locals words
13459: @cindex locals words, system documentation
13460:
13461: @menu
13462: * locals-idef:: Implementation Defined Options
13463: * locals-ambcond:: Ambiguous Conditions
13464: @end menu
13465:
13466:
13467: @c ---------------------------------------------------------------------
13468: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13469: @subsection Implementation Defined Options
13470: @c ---------------------------------------------------------------------
13471: @cindex implementation-defined options, locals words
13472: @cindex locals words, implementation-defined options
13473:
13474: @table @i
13475: @item maximum number of locals in a definition:
13476: @cindex maximum number of locals in a definition
13477: @cindex locals, maximum number in a definition
13478: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13479: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13480: characters. The number of locals in a definition is bounded by the size
13481: of locals-buffer, which contains the names of the locals.
13482:
13483: @end table
13484:
13485:
13486: @c ---------------------------------------------------------------------
13487: @node locals-ambcond, , locals-idef, The optional Locals word set
13488: @subsection Ambiguous conditions
13489: @c ---------------------------------------------------------------------
13490: @cindex locals words, ambiguous conditions
13491: @cindex ambiguous conditions, locals words
13492:
13493: @table @i
13494: @item executing a named local in interpretation state:
13495: @cindex local in interpretation state
13496: @cindex Interpreting a compile-only word, for a local
13497: Locals have no interpretation semantics. If you try to perform the
13498: interpretation semantics, you will get a @code{-14 throw} somewhere
13499: (Interpreting a compile-only word). If you perform the compilation
13500: semantics, the locals access will be compiled (irrespective of state).
13501:
1.29 crook 13502: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13503: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13504: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13505: @cindex Invalid name argument, @code{TO}
13506: @code{-32 throw} (Invalid name argument)
13507:
13508: @end table
13509:
13510:
13511: @c =====================================================================
13512: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13513: @section The optional Memory-Allocation word set
13514: @c =====================================================================
13515: @cindex system documentation, memory-allocation words
13516: @cindex memory-allocation words, system documentation
13517:
13518: @menu
13519: * memory-idef:: Implementation Defined Options
13520: @end menu
13521:
13522:
13523: @c ---------------------------------------------------------------------
13524: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13525: @subsection Implementation Defined Options
13526: @c ---------------------------------------------------------------------
13527: @cindex implementation-defined options, memory-allocation words
13528: @cindex memory-allocation words, implementation-defined options
13529:
13530: @table @i
1.29 crook 13531: @item values and meaning of @i{ior}:
13532: @cindex @i{ior} values and meaning
13533: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13534: intended as throw codes. They typically are in the range
13535: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13536: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13537:
13538: @end table
13539:
13540: @c =====================================================================
13541: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13542: @section The optional Programming-Tools word set
13543: @c =====================================================================
13544: @cindex system documentation, programming-tools words
13545: @cindex programming-tools words, system documentation
13546:
13547: @menu
13548: * programming-idef:: Implementation Defined Options
13549: * programming-ambcond:: Ambiguous Conditions
13550: @end menu
13551:
13552:
13553: @c ---------------------------------------------------------------------
13554: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13555: @subsection Implementation Defined Options
13556: @c ---------------------------------------------------------------------
13557: @cindex implementation-defined options, programming-tools words
13558: @cindex programming-tools words, implementation-defined options
13559:
13560: @table @i
13561: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13562: @cindex @code{;CODE} ending sequence
13563: @cindex @code{CODE} ending sequence
13564: @code{END-CODE}
13565:
13566: @item manner of processing input following @code{;CODE} and @code{CODE}:
13567: @cindex @code{;CODE}, processing input
13568: @cindex @code{CODE}, processing input
13569: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13570: the input is processed by the text interpreter, (starting) in interpret
13571: state.
13572:
13573: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13574: @cindex @code{ASSEMBLER}, search order capability
13575: The ANS Forth search order word set.
13576:
13577: @item source and format of display by @code{SEE}:
13578: @cindex @code{SEE}, source and format of output
1.80 anton 13579: The source for @code{see} is the executable code used by the inner
1.1 anton 13580: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13581: (and on some platforms, assembly code for primitives) as well as
13582: possible.
1.1 anton 13583:
13584: @end table
13585:
13586: @c ---------------------------------------------------------------------
13587: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13588: @subsection Ambiguous conditions
13589: @c ---------------------------------------------------------------------
13590: @cindex programming-tools words, ambiguous conditions
13591: @cindex ambiguous conditions, programming-tools words
13592:
13593: @table @i
13594:
1.21 crook 13595: @item deleting the compilation word list (@code{FORGET}):
13596: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13597: Not implemented (yet).
13598:
1.29 crook 13599: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13600: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13601: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13602: @cindex control-flow stack underflow
13603: This typically results in an @code{abort"} with a descriptive error
13604: message (may change into a @code{-22 throw} (Control structure mismatch)
13605: in the future). You may also get a memory access error. If you are
13606: unlucky, this ambiguous condition is not caught.
13607:
1.29 crook 13608: @item @i{name} can't be found (@code{FORGET}):
13609: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13610: Not implemented (yet).
13611:
1.29 crook 13612: @item @i{name} not defined via @code{CREATE}:
13613: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13614: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13615: the execution semantics of the last defined word no matter how it was
13616: defined.
13617:
13618: @item @code{POSTPONE} applied to @code{[IF]}:
13619: @cindex @code{POSTPONE} applied to @code{[IF]}
13620: @cindex @code{[IF]} and @code{POSTPONE}
13621: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13622: equivalent to @code{[IF]}.
13623:
13624: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13625: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13626: Continue in the same state of conditional compilation in the next outer
13627: input source. Currently there is no warning to the user about this.
13628:
13629: @item removing a needed definition (@code{FORGET}):
13630: @cindex @code{FORGET}, removing a needed definition
13631: Not implemented (yet).
13632:
13633: @end table
13634:
13635:
13636: @c =====================================================================
13637: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13638: @section The optional Search-Order word set
13639: @c =====================================================================
13640: @cindex system documentation, search-order words
13641: @cindex search-order words, system documentation
13642:
13643: @menu
13644: * search-idef:: Implementation Defined Options
13645: * search-ambcond:: Ambiguous Conditions
13646: @end menu
13647:
13648:
13649: @c ---------------------------------------------------------------------
13650: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13651: @subsection Implementation Defined Options
13652: @c ---------------------------------------------------------------------
13653: @cindex implementation-defined options, search-order words
13654: @cindex search-order words, implementation-defined options
13655:
13656: @table @i
13657: @item maximum number of word lists in search order:
13658: @cindex maximum number of word lists in search order
13659: @cindex search order, maximum depth
13660: @code{s" wordlists" environment? drop .}. Currently 16.
13661:
13662: @item minimum search order:
13663: @cindex minimum search order
13664: @cindex search order, minimum
13665: @code{root root}.
13666:
13667: @end table
13668:
13669: @c ---------------------------------------------------------------------
13670: @node search-ambcond, , search-idef, The optional Search-Order word set
13671: @subsection Ambiguous conditions
13672: @c ---------------------------------------------------------------------
13673: @cindex search-order words, ambiguous conditions
13674: @cindex ambiguous conditions, search-order words
13675:
13676: @table @i
1.21 crook 13677: @item changing the compilation word list (during compilation):
13678: @cindex changing the compilation word list (during compilation)
13679: @cindex compilation word list, change before definition ends
13680: The word is entered into the word list that was the compilation word list
1.1 anton 13681: at the start of the definition. Any changes to the name field (e.g.,
13682: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13683: are applied to the latest defined word (as reported by @code{latest} or
13684: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13685:
13686: @item search order empty (@code{previous}):
13687: @cindex @code{previous}, search order empty
1.26 crook 13688: @cindex vocstack empty, @code{previous}
1.1 anton 13689: @code{abort" Vocstack empty"}.
13690:
13691: @item too many word lists in search order (@code{also}):
13692: @cindex @code{also}, too many word lists in search order
1.26 crook 13693: @cindex vocstack full, @code{also}
1.1 anton 13694: @code{abort" Vocstack full"}.
13695:
13696: @end table
13697:
13698: @c ***************************************************************
1.65 anton 13699: @node Standard vs Extensions, Model, ANS conformance, Top
13700: @chapter Should I use Gforth extensions?
13701: @cindex Gforth extensions
13702:
13703: As you read through the rest of this manual, you will see documentation
13704: for @i{Standard} words, and documentation for some appealing Gforth
13705: @i{extensions}. You might ask yourself the question: @i{``Should I
13706: restrict myself to the standard, or should I use the extensions?''}
13707:
13708: The answer depends on the goals you have for the program you are working
13709: on:
13710:
13711: @itemize @bullet
13712:
13713: @item Is it just for yourself or do you want to share it with others?
13714:
13715: @item
13716: If you want to share it, do the others all use Gforth?
13717:
13718: @item
13719: If it is just for yourself, do you want to restrict yourself to Gforth?
13720:
13721: @end itemize
13722:
13723: If restricting the program to Gforth is ok, then there is no reason not
13724: to use extensions. It is still a good idea to keep to the standard
13725: where it is easy, in case you want to reuse these parts in another
13726: program that you want to be portable.
13727:
13728: If you want to be able to port the program to other Forth systems, there
13729: are the following points to consider:
13730:
13731: @itemize @bullet
13732:
13733: @item
13734: Most Forth systems that are being maintained support the ANS Forth
13735: standard. So if your program complies with the standard, it will be
13736: portable among many systems.
13737:
13738: @item
13739: A number of the Gforth extensions can be implemented in ANS Forth using
13740: public-domain files provided in the @file{compat/} directory. These are
13741: mentioned in the text in passing. There is no reason not to use these
13742: extensions, your program will still be ANS Forth compliant; just include
13743: the appropriate compat files with your program.
13744:
13745: @item
13746: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13747: analyse your program and determine what non-Standard words it relies
13748: upon. However, it does not check whether you use standard words in a
13749: non-standard way.
13750:
13751: @item
13752: Some techniques are not standardized by ANS Forth, and are hard or
13753: impossible to implement in a standard way, but can be implemented in
13754: most Forth systems easily, and usually in similar ways (e.g., accessing
13755: word headers). Forth has a rich historical precedent for programmers
13756: taking advantage of implementation-dependent features of their tools
13757: (for example, relying on a knowledge of the dictionary
13758: structure). Sometimes these techniques are necessary to extract every
13759: last bit of performance from the hardware, sometimes they are just a
13760: programming shorthand.
13761:
13762: @item
13763: Does using a Gforth extension save more work than the porting this part
13764: to other Forth systems (if any) will cost?
13765:
13766: @item
13767: Is the additional functionality worth the reduction in portability and
13768: the additional porting problems?
13769:
13770: @end itemize
13771:
13772: In order to perform these consideratios, you need to know what's
13773: standard and what's not. This manual generally states if something is
1.81 anton 13774: non-standard, but the authoritative source is the
13775: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13776: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13777: into the thought processes of the technical committee.
13778:
13779: Note also that portability between Forth systems is not the only
13780: portability issue; there is also the issue of portability between
13781: different platforms (processor/OS combinations).
13782:
13783: @c ***************************************************************
13784: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13785: @chapter Model
13786:
13787: This chapter has yet to be written. It will contain information, on
13788: which internal structures you can rely.
13789:
13790: @c ***************************************************************
13791: @node Integrating Gforth, Emacs and Gforth, Model, Top
13792: @chapter Integrating Gforth into C programs
13793:
13794: This is not yet implemented.
13795:
13796: Several people like to use Forth as scripting language for applications
13797: that are otherwise written in C, C++, or some other language.
13798:
13799: The Forth system ATLAST provides facilities for embedding it into
13800: applications; unfortunately it has several disadvantages: most
13801: importantly, it is not based on ANS Forth, and it is apparently dead
13802: (i.e., not developed further and not supported). The facilities
1.21 crook 13803: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13804: making the switch should not be hard.
13805:
13806: We also tried to design the interface such that it can easily be
13807: implemented by other Forth systems, so that we may one day arrive at a
13808: standardized interface. Such a standard interface would allow you to
13809: replace the Forth system without having to rewrite C code.
13810:
13811: You embed the Gforth interpreter by linking with the library
13812: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13813: global symbols in this library that belong to the interface, have the
13814: prefix @code{forth_}. (Global symbols that are used internally have the
13815: prefix @code{gforth_}).
13816:
13817: You can include the declarations of Forth types and the functions and
13818: variables of the interface with @code{#include <forth.h>}.
13819:
13820: Types.
13821:
13822: Variables.
13823:
13824: Data and FP Stack pointer. Area sizes.
13825:
13826: functions.
13827:
13828: forth_init(imagefile)
13829: forth_evaluate(string) exceptions?
13830: forth_goto(address) (or forth_execute(xt)?)
13831: forth_continue() (a corountining mechanism)
13832:
13833: Adding primitives.
13834:
13835: No checking.
13836:
13837: Signals?
13838:
13839: Accessing the Stacks
13840:
1.26 crook 13841: @c ******************************************************************
1.1 anton 13842: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13843: @chapter Emacs and Gforth
13844: @cindex Emacs and Gforth
13845:
13846: @cindex @file{gforth.el}
13847: @cindex @file{forth.el}
13848: @cindex Rydqvist, Goran
1.107 dvdkhlng 13849: @cindex Kuehling, David
1.1 anton 13850: @cindex comment editing commands
13851: @cindex @code{\}, editing with Emacs
13852: @cindex debug tracer editing commands
13853: @cindex @code{~~}, removal with Emacs
13854: @cindex Forth mode in Emacs
1.107 dvdkhlng 13855:
1.1 anton 13856: Gforth comes with @file{gforth.el}, an improved version of
13857: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13858: improvements are:
13859:
13860: @itemize @bullet
13861: @item
1.107 dvdkhlng 13862: A better handling of indentation.
13863: @item
13864: A custom hilighting engine for Forth-code.
1.26 crook 13865: @item
13866: Comment paragraph filling (@kbd{M-q})
13867: @item
13868: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13869: @item
13870: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13871: @item
13872: Support of the @code{info-lookup} feature for looking up the
13873: documentation of a word.
1.107 dvdkhlng 13874: @item
13875: Support for reading and writing blocks files.
1.26 crook 13876: @end itemize
13877:
1.107 dvdkhlng 13878: To get a basic description of these features, enter Forth mode and
13879: type @kbd{C-h m}.
1.1 anton 13880:
13881: @cindex source location of error or debugging output in Emacs
13882: @cindex error output, finding the source location in Emacs
13883: @cindex debugging output, finding the source location in Emacs
13884: In addition, Gforth supports Emacs quite well: The source code locations
13885: given in error messages, debugging output (from @code{~~}) and failed
13886: assertion messages are in the right format for Emacs' compilation mode
13887: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13888: Manual}) so the source location corresponding to an error or other
13889: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13890: @kbd{C-c C-c} for the error under the cursor).
13891:
1.107 dvdkhlng 13892: @cindex viewing the documentation of a word in Emacs
13893: @cindex context-sensitive help
13894: Moreover, for words documented in this manual, you can look up the
13895: glossary entry quickly by using @kbd{C-h TAB}
13896: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13897: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13898: later and does not work for words containing @code{:}.
13899:
13900: @menu
13901: * Installing gforth.el:: Making Emacs aware of Forth.
13902: * Emacs Tags:: Viewing the source of a word in Emacs.
13903: * Hilighting:: Making Forth code look prettier.
13904: * Auto-Indentation:: Customizing auto-indentation.
13905: * Blocks Files:: Reading and writing blocks files.
13906: @end menu
13907:
13908: @c ----------------------------------
1.109 anton 13909: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13910: @section Installing gforth.el
13911: @cindex @file{.emacs}
13912: @cindex @file{gforth.el}, installation
13913: To make the features from @file{gforth.el} available in Emacs, add
13914: the following lines to your @file{.emacs} file:
13915:
13916: @example
13917: (autoload 'forth-mode "gforth.el")
13918: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13919: auto-mode-alist))
13920: (autoload 'forth-block-mode "gforth.el")
13921: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13922: auto-mode-alist))
13923: (add-hook 'forth-mode-hook (function (lambda ()
13924: ;; customize variables here:
13925: (setq forth-indent-level 4)
13926: (setq forth-minor-indent-level 2)
13927: (setq forth-hilight-level 3)
13928: ;;; ...
13929: )))
13930: @end example
13931:
13932: @c ----------------------------------
13933: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13934: @section Emacs Tags
1.1 anton 13935: @cindex @file{TAGS} file
13936: @cindex @file{etags.fs}
13937: @cindex viewing the source of a word in Emacs
1.43 anton 13938: @cindex @code{require}, placement in files
13939: @cindex @code{include}, placement in files
1.107 dvdkhlng 13940: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13941: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13942: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13943: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13944: several tags files at the same time (e.g., one for the Gforth sources
13945: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13946: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13947: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13948: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13949: with @file{etags.fs}, you should avoid putting definitions both before
13950: and after @code{require} etc., otherwise you will see the same file
13951: visited several times by commands like @code{tags-search}.
1.1 anton 13952:
1.107 dvdkhlng 13953: @c ----------------------------------
13954: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13955: @section Hilighting
13956: @cindex hilighting Forth code in Emacs
13957: @cindex highlighting Forth code in Emacs
13958: @file{gforth.el} comes with a custom source hilighting engine. When
13959: you open a file in @code{forth-mode}, it will be completely parsed,
13960: assigning faces to keywords, comments, strings etc. While you edit
13961: the file, modified regions get parsed and updated on-the-fly.
13962:
13963: Use the variable `forth-hilight-level' to change the level of
13964: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13965: you set the hilighting level to 0, the parser will still work in the
13966: background, collecting information about whether regions of text are
13967: ``compiled'' or ``interpreted''. Those information are required for
13968: auto-indentation to work properly. Set `forth-disable-parser' to
13969: non-nil if your computer is too slow to handle parsing. This will
13970: have an impact on the smartness of the auto-indentation engine,
13971: though.
13972:
13973: Sometimes Forth sources define new features that should be hilighted,
13974: new control structures, defining-words etc. You can use the variable
13975: `forth-custom-words' to make @code{forth-mode} hilight additional
13976: words and constructs. See the docstring of `forth-words' for details
13977: (in Emacs, type @kbd{C-h v forth-words}).
13978:
13979: `forth-custom-words' is meant to be customized in your
13980: @file{.emacs} file. To customize hilighing in a file-specific manner,
13981: set `forth-local-words' in a local-variables section at the end of
13982: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13983:
13984: Example:
13985: @example
13986: 0 [IF]
13987: Local Variables:
13988: forth-local-words:
13989: ((("t:") definition-starter (font-lock-keyword-face . 1)
13990: "[ \t\n]" t name (font-lock-function-name-face . 3))
13991: ((";t") definition-ender (font-lock-keyword-face . 1)))
13992: End:
13993: [THEN]
13994: @end example
13995:
13996: @c ----------------------------------
13997: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13998: @section Auto-Indentation
13999: @cindex auto-indentation of Forth code in Emacs
14000: @cindex indentation of Forth code in Emacs
14001: @code{forth-mode} automatically tries to indent lines in a smart way,
14002: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14003:
14004: Simple customization can be achieved by setting
14005: `forth-indent-level' and `forth-minor-indent-level' in your
14006: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14007: per default by multiples of 4 columns. To use the more traditional
14008: 3-column indentation, add the following lines to your @file{.emacs}:
14009:
14010: @example
14011: (add-hook 'forth-mode-hook (function (lambda ()
14012: ;; customize variables here:
14013: (setq forth-indent-level 3)
14014: (setq forth-minor-indent-level 1)
14015: )))
14016: @end example
14017:
14018: If you want indentation to recognize non-default words, customize it
14019: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14020: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14021: v forth-indent-words}).
14022:
14023: To customize indentation in a file-specific manner, set
14024: `forth-local-indent-words' in a local-variables section at the end of
14025: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14026: Emacs Manual}).
14027:
14028: Example:
14029: @example
14030: 0 [IF]
14031: Local Variables:
14032: forth-local-indent-words:
14033: ((("t:") (0 . 2) (0 . 2))
14034: ((";t") (-2 . 0) (0 . -2)))
14035: End:
14036: [THEN]
14037: @end example
14038:
14039: @c ----------------------------------
1.109 anton 14040: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14041: @section Blocks Files
14042: @cindex blocks files, use with Emacs
14043: @code{forth-mode} Autodetects blocks files by checking whether the
14044: length of the first line exceeds 1023 characters. It then tries to
14045: convert the file into normal text format. When you save the file, it
14046: will be written to disk as normal stream-source file.
14047:
14048: If you want to write blocks files, use @code{forth-blocks-mode}. It
14049: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14050:
1.107 dvdkhlng 14051: @itemize @bullet
14052: @item
14053: Files are written to disk in blocks file format.
14054: @item
14055: Screen numbers are displayed in the mode line (enumerated beginning
14056: with the value of `forth-block-base')
14057: @item
14058: Warnings are displayed when lines exceed 64 characters.
14059: @item
14060: The beginning of the currently edited block is marked with an
14061: overlay-arrow.
14062: @end itemize
1.41 anton 14063:
1.107 dvdkhlng 14064: There are some restrictions you should be aware of. When you open a
14065: blocks file that contains tabulator or newline characters, these
14066: characters will be translated into spaces when the file is written
14067: back to disk. If tabs or newlines are encountered during blocks file
14068: reading, an error is output to the echo area. So have a look at the
14069: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14070:
1.107 dvdkhlng 14071: Please consult the docstring of @code{forth-blocks-mode} for more
14072: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14073:
1.26 crook 14074: @c ******************************************************************
1.1 anton 14075: @node Image Files, Engine, Emacs and Gforth, Top
14076: @chapter Image Files
1.26 crook 14077: @cindex image file
14078: @cindex @file{.fi} files
1.1 anton 14079: @cindex precompiled Forth code
14080: @cindex dictionary in persistent form
14081: @cindex persistent form of dictionary
14082:
14083: An image file is a file containing an image of the Forth dictionary,
14084: i.e., compiled Forth code and data residing in the dictionary. By
14085: convention, we use the extension @code{.fi} for image files.
14086:
14087: @menu
1.18 anton 14088: * Image Licensing Issues:: Distribution terms for images.
14089: * Image File Background:: Why have image files?
1.67 anton 14090: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14091: * Data-Relocatable Image Files:: are better.
1.67 anton 14092: * Fully Relocatable Image Files:: better yet.
1.18 anton 14093: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14094: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14095: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14096: @end menu
14097:
1.18 anton 14098: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14099: @section Image Licensing Issues
14100: @cindex license for images
14101: @cindex image license
14102:
14103: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14104: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14105: original image; i.e., according to copyright law it is a derived work of
14106: the original image.
14107:
14108: Since Gforth is distributed under the GNU GPL, the newly created image
14109: falls under the GNU GPL, too. In particular, this means that if you
14110: distribute the image, you have to make all of the sources for the image
1.113 anton 14111: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14112: GNU General Public License (Section 3)}.
14113:
14114: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14115: contains only code compiled from the sources you gave it; if none of
14116: these sources is under the GPL, the terms discussed above do not apply
14117: to the image. However, if your image needs an engine (a gforth binary)
14118: that is under the GPL, you should make sure that you distribute both in
14119: a way that is at most a @emph{mere aggregation}, if you don't want the
14120: terms of the GPL to apply to the image.
14121:
14122: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14123: @section Image File Background
14124: @cindex image file background
14125:
1.80 anton 14126: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14127: definitions written in Forth. Since the Forth compiler itself belongs to
14128: those definitions, it is not possible to start the system with the
1.80 anton 14129: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14130: code as an image file in nearly executable form. When Gforth starts up,
14131: a C routine loads the image file into memory, optionally relocates the
14132: addresses, then sets up the memory (stacks etc.) according to
14133: information in the image file, and (finally) starts executing Forth
14134: code.
1.1 anton 14135:
14136: The image file variants represent different compromises between the
14137: goals of making it easy to generate image files and making them
14138: portable.
14139:
14140: @cindex relocation at run-time
1.26 crook 14141: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14142: run-time. This avoids many of the complications discussed below (image
14143: files are data relocatable without further ado), but costs performance
14144: (one addition per memory access).
14145:
14146: @cindex relocation at load-time
1.26 crook 14147: By contrast, the Gforth loader performs relocation at image load time. The
14148: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14149: appropriate code-field addresses (or code addresses in the case of
14150: direct threading).
14151:
14152: There are three kinds of image files, with different degrees of
14153: relocatability: non-relocatable, data-relocatable, and fully relocatable
14154: image files.
14155:
14156: @cindex image file loader
14157: @cindex relocating loader
14158: @cindex loader for image files
14159: These image file variants have several restrictions in common; they are
14160: caused by the design of the image file loader:
14161:
14162: @itemize @bullet
14163: @item
14164: There is only one segment; in particular, this means, that an image file
14165: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14166: them). The contents of the stacks are not represented, either.
1.1 anton 14167:
14168: @item
14169: The only kinds of relocation supported are: adding the same offset to
14170: all cells that represent data addresses; and replacing special tokens
14171: with code addresses or with pieces of machine code.
14172:
14173: If any complex computations involving addresses are performed, the
14174: results cannot be represented in the image file. Several applications that
14175: use such computations come to mind:
14176: @itemize @minus
14177: @item
14178: Hashing addresses (or data structures which contain addresses) for table
14179: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14180: purpose, you will have no problem, because the hash tables are
14181: recomputed automatically when the system is started. If you use your own
14182: hash tables, you will have to do something similar.
14183:
14184: @item
14185: There's a cute implementation of doubly-linked lists that uses
14186: @code{XOR}ed addresses. You could represent such lists as singly-linked
14187: in the image file, and restore the doubly-linked representation on
14188: startup.@footnote{In my opinion, though, you should think thrice before
14189: using a doubly-linked list (whatever implementation).}
14190:
14191: @item
14192: The code addresses of run-time routines like @code{docol:} cannot be
14193: represented in the image file (because their tokens would be replaced by
14194: machine code in direct threaded implementations). As a workaround,
14195: compute these addresses at run-time with @code{>code-address} from the
14196: executions tokens of appropriate words (see the definitions of
1.80 anton 14197: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14198:
14199: @item
14200: On many architectures addresses are represented in machine code in some
14201: shifted or mangled form. You cannot put @code{CODE} words that contain
14202: absolute addresses in this form in a relocatable image file. Workarounds
14203: are representing the address in some relative form (e.g., relative to
14204: the CFA, which is present in some register), or loading the address from
14205: a place where it is stored in a non-mangled form.
14206: @end itemize
14207: @end itemize
14208:
14209: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14210: @section Non-Relocatable Image Files
14211: @cindex non-relocatable image files
1.26 crook 14212: @cindex image file, non-relocatable
1.1 anton 14213:
14214: These files are simple memory dumps of the dictionary. They are specific
14215: to the executable (i.e., @file{gforth} file) they were created
14216: with. What's worse, they are specific to the place on which the
14217: dictionary resided when the image was created. Now, there is no
14218: guarantee that the dictionary will reside at the same place the next
14219: time you start Gforth, so there's no guarantee that a non-relocatable
14220: image will work the next time (Gforth will complain instead of crashing,
14221: though).
14222:
14223: You can create a non-relocatable image file with
14224:
1.44 crook 14225:
1.1 anton 14226: doc-savesystem
14227:
1.44 crook 14228:
1.1 anton 14229: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14230: @section Data-Relocatable Image Files
14231: @cindex data-relocatable image files
1.26 crook 14232: @cindex image file, data-relocatable
1.1 anton 14233:
14234: These files contain relocatable data addresses, but fixed code addresses
14235: (instead of tokens). They are specific to the executable (i.e.,
14236: @file{gforth} file) they were created with. For direct threading on some
14237: architectures (e.g., the i386), data-relocatable images do not work. You
14238: get a data-relocatable image, if you use @file{gforthmi} with a
14239: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14240: Relocatable Image Files}).
14241:
14242: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14243: @section Fully Relocatable Image Files
14244: @cindex fully relocatable image files
1.26 crook 14245: @cindex image file, fully relocatable
1.1 anton 14246:
14247: @cindex @file{kern*.fi}, relocatability
14248: @cindex @file{gforth.fi}, relocatability
14249: These image files have relocatable data addresses, and tokens for code
14250: addresses. They can be used with different binaries (e.g., with and
14251: without debugging) on the same machine, and even across machines with
14252: the same data formats (byte order, cell size, floating point
14253: format). However, they are usually specific to the version of Gforth
14254: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14255: are fully relocatable.
14256:
14257: There are two ways to create a fully relocatable image file:
14258:
14259: @menu
1.29 crook 14260: * gforthmi:: The normal way
1.1 anton 14261: * cross.fs:: The hard way
14262: @end menu
14263:
14264: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14265: @subsection @file{gforthmi}
14266: @cindex @file{comp-i.fs}
14267: @cindex @file{gforthmi}
14268:
14269: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14270: image @i{file} that contains everything you would load by invoking
14271: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14272: @example
1.29 crook 14273: gforthmi @i{file} @i{options}
1.1 anton 14274: @end example
14275:
14276: E.g., if you want to create an image @file{asm.fi} that has the file
14277: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14278: like this:
14279:
14280: @example
14281: gforthmi asm.fi asm.fs
14282: @end example
14283:
1.27 crook 14284: @file{gforthmi} is implemented as a sh script and works like this: It
14285: produces two non-relocatable images for different addresses and then
14286: compares them. Its output reflects this: first you see the output (if
1.62 crook 14287: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14288: files, then you see the output of the comparing program: It displays the
14289: offset used for data addresses and the offset used for code addresses;
1.1 anton 14290: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14291: image files, it displays a line like this:
1.1 anton 14292:
14293: @example
14294: 78DC BFFFFA50 BFFFFA40
14295: @end example
14296:
14297: This means that at offset $78dc from @code{forthstart}, one input image
14298: contains $bffffa50, and the other contains $bffffa40. Since these cells
14299: cannot be represented correctly in the output image, you should examine
14300: these places in the dictionary and verify that these cells are dead
14301: (i.e., not read before they are written).
1.39 anton 14302:
14303: @cindex --application, @code{gforthmi} option
14304: If you insert the option @code{--application} in front of the image file
14305: name, you will get an image that uses the @code{--appl-image} option
14306: instead of the @code{--image-file} option (@pxref{Invoking
14307: Gforth}). When you execute such an image on Unix (by typing the image
14308: name as command), the Gforth engine will pass all options to the image
14309: instead of trying to interpret them as engine options.
1.1 anton 14310:
1.27 crook 14311: If you type @file{gforthmi} with no arguments, it prints some usage
14312: instructions.
14313:
1.1 anton 14314: @cindex @code{savesystem} during @file{gforthmi}
14315: @cindex @code{bye} during @file{gforthmi}
14316: @cindex doubly indirect threaded code
1.44 crook 14317: @cindex environment variables
14318: @cindex @code{GFORTHD} -- environment variable
14319: @cindex @code{GFORTH} -- environment variable
1.1 anton 14320: @cindex @code{gforth-ditc}
1.29 crook 14321: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14322: words @code{savesystem} and @code{bye} must be visible. A special doubly
14323: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14324: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14325: this executable through the environment variable @code{GFORTHD}
14326: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14327: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14328: data-relocatable image (because there is no code address offset). The
14329: normal @file{gforth} executable is used for creating the relocatable
14330: image; you can pass the exact filename of this executable through the
14331: environment variable @code{GFORTH}.
1.1 anton 14332:
14333: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14334: @subsection @file{cross.fs}
14335: @cindex @file{cross.fs}
14336: @cindex cross-compiler
14337: @cindex metacompiler
1.47 crook 14338: @cindex target compiler
1.1 anton 14339:
14340: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14341: programming language (@pxref{Cross Compiler}).
1.1 anton 14342:
1.47 crook 14343: @code{cross} allows you to create image files for machines with
1.1 anton 14344: different data sizes and data formats than the one used for generating
14345: the image file. You can also use it to create an application image that
14346: does not contain a Forth compiler. These features are bought with
14347: restrictions and inconveniences in programming. E.g., addresses have to
14348: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14349: order to make the code relocatable.
14350:
14351:
14352: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14353: @section Stack and Dictionary Sizes
14354: @cindex image file, stack and dictionary sizes
14355: @cindex dictionary size default
14356: @cindex stack size default
14357:
14358: If you invoke Gforth with a command line flag for the size
14359: (@pxref{Invoking Gforth}), the size you specify is stored in the
14360: dictionary. If you save the dictionary with @code{savesystem} or create
14361: an image with @file{gforthmi}, this size will become the default
14362: for the resulting image file. E.g., the following will create a
1.21 crook 14363: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14364:
14365: @example
14366: gforthmi gforth.fi -m 1M
14367: @end example
14368:
14369: In other words, if you want to set the default size for the dictionary
14370: and the stacks of an image, just invoke @file{gforthmi} with the
14371: appropriate options when creating the image.
14372:
14373: @cindex stack size, cache-friendly
14374: Note: For cache-friendly behaviour (i.e., good performance), you should
14375: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14376: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14377: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14378:
14379: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14380: @section Running Image Files
14381: @cindex running image files
14382: @cindex invoking image files
14383: @cindex image file invocation
14384:
14385: @cindex -i, invoke image file
14386: @cindex --image file, invoke image file
1.29 crook 14387: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14388: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14389: @example
1.29 crook 14390: gforth -i @i{image}
1.1 anton 14391: @end example
14392:
14393: @cindex executable image file
1.26 crook 14394: @cindex image file, executable
1.1 anton 14395: If your operating system supports starting scripts with a line of the
14396: form @code{#! ...}, you just have to type the image file name to start
14397: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14398: just a convention). I.e., to run Gforth with the image file @i{image},
14399: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14400: This works because every @code{.fi} file starts with a line of this
14401: format:
14402:
14403: @example
14404: #! /usr/local/bin/gforth-0.4.0 -i
14405: @end example
14406:
14407: The file and pathname for the Gforth engine specified on this line is
14408: the specific Gforth executable that it was built against; i.e. the value
14409: of the environment variable @code{GFORTH} at the time that
14410: @file{gforthmi} was executed.
1.1 anton 14411:
1.27 crook 14412: You can make use of the same shell capability to make a Forth source
14413: file into an executable. For example, if you place this text in a file:
1.26 crook 14414:
14415: @example
14416: #! /usr/local/bin/gforth
14417:
14418: ." Hello, world" CR
14419: bye
14420: @end example
14421:
14422: @noindent
1.27 crook 14423: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14424: directly from the command line. The sequence @code{#!} is used in two
14425: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14426: system@footnote{The Unix kernel actually recognises two types of files:
14427: executable files and files of data, where the data is processed by an
14428: interpreter that is specified on the ``interpreter line'' -- the first
14429: line of the file, starting with the sequence #!. There may be a small
14430: limit (e.g., 32) on the number of characters that may be specified on
14431: the interpreter line.} secondly it is treated as a comment character by
14432: Gforth. Because of the second usage, a space is required between
1.80 anton 14433: @code{#!} and the path to the executable (moreover, some Unixes
14434: require the sequence @code{#! /}).
1.27 crook 14435:
14436: The disadvantage of this latter technique, compared with using
1.80 anton 14437: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14438: compiled on-the-fly, each time the program is invoked.
1.26 crook 14439:
1.1 anton 14440: doc-#!
14441:
1.44 crook 14442:
1.1 anton 14443: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14444: @section Modifying the Startup Sequence
14445: @cindex startup sequence for image file
14446: @cindex image file initialization sequence
14447: @cindex initialization sequence of image file
14448:
1.120 anton 14449: You can add your own initialization to the startup sequence of an image
14450: through the deferred word @code{'cold}. @code{'cold} is invoked just
14451: before the image-specific command line processing (i.e., loading files
14452: and evaluating (@code{-e}) strings) starts.
1.1 anton 14453:
14454: A sequence for adding your initialization usually looks like this:
14455:
14456: @example
14457: :noname
14458: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14459: ... \ your stuff
14460: ; IS 'cold
14461: @end example
14462:
14463: @cindex turnkey image files
1.26 crook 14464: @cindex image file, turnkey applications
1.1 anton 14465: You can make a turnkey image by letting @code{'cold} execute a word
14466: (your turnkey application) that never returns; instead, it exits Gforth
14467: via @code{bye} or @code{throw}.
14468:
1.121 anton 14469: You can access the (image-specific) command-line arguments through
14470: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14471: arguments}).
1.1 anton 14472:
1.26 crook 14473: If @code{'cold} exits normally, Gforth processes the command-line
14474: arguments as files to be loaded and strings to be evaluated. Therefore,
14475: @code{'cold} should remove the arguments it has used in this case.
14476:
14477: doc-'cold
1.44 crook 14478:
1.1 anton 14479: @c ******************************************************************
1.113 anton 14480: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14481: @chapter Engine
14482: @cindex engine
14483: @cindex virtual machine
14484:
1.26 crook 14485: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14486: may be helpful for finding your way in the Gforth sources.
14487:
1.109 anton 14488: The ideas in this section have also been published in the following
14489: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14490: Forth-Tagung '93; M. Anton Ertl,
14491: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14492: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14493: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14494: Threaded code variations and optimizations (extended version)}},
14495: Forth-Tagung '02.
1.1 anton 14496:
14497: @menu
14498: * Portability::
14499: * Threading::
14500: * Primitives::
14501: * Performance::
14502: @end menu
14503:
14504: @node Portability, Threading, Engine, Engine
14505: @section Portability
14506: @cindex engine portability
14507:
1.26 crook 14508: An important goal of the Gforth Project is availability across a wide
14509: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14510: achieved this goal by manually coding the engine in assembly language
14511: for several then-popular processors. This approach is very
14512: labor-intensive and the results are short-lived due to progress in
14513: computer architecture.
1.1 anton 14514:
14515: @cindex C, using C for the engine
14516: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14517: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14518: particularly popular for UNIX-based Forths due to the large variety of
14519: architectures of UNIX machines. Unfortunately an implementation in C
14520: does not mix well with the goals of efficiency and with using
14521: traditional techniques: Indirect or direct threading cannot be expressed
14522: in C, and switch threading, the fastest technique available in C, is
14523: significantly slower. Another problem with C is that it is very
14524: cumbersome to express double integer arithmetic.
14525:
14526: @cindex GNU C for the engine
14527: @cindex long long
14528: Fortunately, there is a portable language that does not have these
14529: limitations: GNU C, the version of C processed by the GNU C compiler
14530: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14531: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14532: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14533: threading possible, its @code{long long} type (@pxref{Long Long, ,
14534: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14535: double numbers on many systems. GNU C is freely available on all
1.1 anton 14536: important (and many unimportant) UNIX machines, VMS, 80386s running
14537: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14538: on all these machines.
14539:
14540: Writing in a portable language has the reputation of producing code that
14541: is slower than assembly. For our Forth engine we repeatedly looked at
14542: the code produced by the compiler and eliminated most compiler-induced
14543: inefficiencies by appropriate changes in the source code.
14544:
14545: @cindex explicit register declarations
14546: @cindex --enable-force-reg, configuration flag
14547: @cindex -DFORCE_REG
14548: However, register allocation cannot be portably influenced by the
14549: programmer, leading to some inefficiencies on register-starved
14550: machines. We use explicit register declarations (@pxref{Explicit Reg
14551: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14552: improve the speed on some machines. They are turned on by using the
14553: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14554: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14555: machine, but also on the compiler version: On some machines some
14556: compiler versions produce incorrect code when certain explicit register
14557: declarations are used. So by default @code{-DFORCE_REG} is not used.
14558:
14559: @node Threading, Primitives, Portability, Engine
14560: @section Threading
14561: @cindex inner interpreter implementation
14562: @cindex threaded code implementation
14563:
14564: @cindex labels as values
14565: GNU C's labels as values extension (available since @code{gcc-2.0},
14566: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14567: makes it possible to take the address of @i{label} by writing
14568: @code{&&@i{label}}. This address can then be used in a statement like
14569: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14570: @code{goto x}.
14571:
1.26 crook 14572: @cindex @code{NEXT}, indirect threaded
1.1 anton 14573: @cindex indirect threaded inner interpreter
14574: @cindex inner interpreter, indirect threaded
1.26 crook 14575: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14576: @example
14577: cfa = *ip++;
14578: ca = *cfa;
14579: goto *ca;
14580: @end example
14581: @cindex instruction pointer
14582: For those unfamiliar with the names: @code{ip} is the Forth instruction
14583: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14584: execution token and points to the code field of the next word to be
14585: executed; The @code{ca} (code address) fetched from there points to some
14586: executable code, e.g., a primitive or the colon definition handler
14587: @code{docol}.
14588:
1.26 crook 14589: @cindex @code{NEXT}, direct threaded
1.1 anton 14590: @cindex direct threaded inner interpreter
14591: @cindex inner interpreter, direct threaded
14592: Direct threading is even simpler:
14593: @example
14594: ca = *ip++;
14595: goto *ca;
14596: @end example
14597:
14598: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14599: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14600:
14601: @menu
14602: * Scheduling::
14603: * Direct or Indirect Threaded?::
1.109 anton 14604: * Dynamic Superinstructions::
1.1 anton 14605: * DOES>::
14606: @end menu
14607:
14608: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14609: @subsection Scheduling
14610: @cindex inner interpreter optimization
14611:
14612: There is a little complication: Pipelined and superscalar processors,
14613: i.e., RISC and some modern CISC machines can process independent
14614: instructions while waiting for the results of an instruction. The
14615: compiler usually reorders (schedules) the instructions in a way that
14616: achieves good usage of these delay slots. However, on our first tries
14617: the compiler did not do well on scheduling primitives. E.g., for
14618: @code{+} implemented as
14619: @example
14620: n=sp[0]+sp[1];
14621: sp++;
14622: sp[0]=n;
14623: NEXT;
14624: @end example
1.81 anton 14625: the @code{NEXT} comes strictly after the other code, i.e., there is
14626: nearly no scheduling. After a little thought the problem becomes clear:
14627: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14628: addresses (and the version of @code{gcc} we used would not know it even
14629: if it was possible), so it could not move the load of the cfa above the
14630: store to the TOS. Indeed the pointers could be the same, if code on or
14631: very near the top of stack were executed. In the interest of speed we
14632: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14633: in scheduling: @code{NEXT} is divided into several parts:
14634: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14635: like:
1.1 anton 14636: @example
1.81 anton 14637: NEXT_P0;
1.1 anton 14638: n=sp[0]+sp[1];
14639: sp++;
14640: NEXT_P1;
14641: sp[0]=n;
14642: NEXT_P2;
14643: @end example
14644:
1.81 anton 14645: There are various schemes that distribute the different operations of
14646: NEXT between these parts in several ways; in general, different schemes
14647: perform best on different processors. We use a scheme for most
14648: architectures that performs well for most processors of this
1.109 anton 14649: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14650: the scheme on installation time.
14651:
1.1 anton 14652:
1.109 anton 14653: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14654: @subsection Direct or Indirect Threaded?
14655: @cindex threading, direct or indirect?
14656:
1.109 anton 14657: Threaded forth code consists of references to primitives (simple machine
14658: code routines like @code{+}) and to non-primitives (e.g., colon
14659: definitions, variables, constants); for a specific class of
14660: non-primitives (e.g., variables) there is one code routine (e.g.,
14661: @code{dovar}), but each variable needs a separate reference to its data.
14662:
14663: Traditionally Forth has been implemented as indirect threaded code,
14664: because this allows to use only one cell to reference a non-primitive
14665: (basically you point to the data, and find the code address there).
14666:
14667: @cindex primitive-centric threaded code
14668: However, threaded code in Gforth (since 0.6.0) uses two cells for
14669: non-primitives, one for the code address, and one for the data address;
14670: the data pointer is an immediate argument for the virtual machine
14671: instruction represented by the code address. We call this
14672: @emph{primitive-centric} threaded code, because all code addresses point
14673: to simple primitives. E.g., for a variable, the code address is for
14674: @code{lit} (also used for integer literals like @code{99}).
14675:
14676: Primitive-centric threaded code allows us to use (faster) direct
14677: threading as dispatch method, completely portably (direct threaded code
14678: in Gforth before 0.6.0 required architecture-specific code). It also
14679: eliminates the performance problems related to I-cache consistency that
14680: 386 implementations have with direct threaded code, and allows
14681: additional optimizations.
14682:
14683: @cindex hybrid direct/indirect threaded code
14684: There is a catch, however: the @var{xt} parameter of @code{execute} can
14685: occupy only one cell, so how do we pass non-primitives with their code
14686: @emph{and} data addresses to them? Our answer is to use indirect
14687: threaded dispatch for @code{execute} and other words that use a
14688: single-cell xt. So, normal threaded code in colon definitions uses
14689: direct threading, and @code{execute} and similar words, which dispatch
14690: to xts on the data stack, use indirect threaded code. We call this
14691: @emph{hybrid direct/indirect} threaded code.
14692:
14693: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14694: @cindex gforth engine
14695: @cindex gforth-fast engine
14696: The engines @command{gforth} and @command{gforth-fast} use hybrid
14697: direct/indirect threaded code. This means that with these engines you
14698: cannot use @code{,} to compile an xt. Instead, you have to use
14699: @code{compile,}.
14700:
14701: @cindex gforth-itc engine
1.115 anton 14702: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14703: This engine uses plain old indirect threaded code. It still compiles in
14704: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14705: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14706: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14707: and execute @code{' , is compile,}. Your program can check if it is
14708: running on a hybrid direct/indirect threaded engine or a pure indirect
14709: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14710:
14711:
14712: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14713: @subsection Dynamic Superinstructions
14714: @cindex Dynamic superinstructions with replication
14715: @cindex Superinstructions
14716: @cindex Replication
14717:
14718: The engines @command{gforth} and @command{gforth-fast} use another
14719: optimization: Dynamic superinstructions with replication. As an
14720: example, consider the following colon definition:
14721:
14722: @example
14723: : squared ( n1 -- n2 )
14724: dup * ;
14725: @end example
14726:
14727: Gforth compiles this into the threaded code sequence
14728:
14729: @example
14730: dup
14731: *
14732: ;s
14733: @end example
14734:
14735: In normal direct threaded code there is a code address occupying one
14736: cell for each of these primitives. Each code address points to a
14737: machine code routine, and the interpreter jumps to this machine code in
14738: order to execute the primitive. The routines for these three
14739: primitives are (in @command{gforth-fast} on the 386):
14740:
14741: @example
14742: Code dup
14743: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14744: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14745: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14746: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14747: end-code
14748: Code *
14749: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14750: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14751: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14752: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14753: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14754: end-code
14755: Code ;s
14756: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14757: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14758: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14759: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14760: end-code
14761: @end example
14762:
14763: With dynamic superinstructions and replication the compiler does not
14764: just lay down the threaded code, but also copies the machine code
14765: fragments, usually without the jump at the end.
14766:
14767: @example
14768: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14769: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14770: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14771: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14772: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14773: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14774: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14775: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14776: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14777: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14778: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14779: @end example
14780:
14781: Only when a threaded-code control-flow change happens (e.g., in
14782: @code{;s}), the jump is appended. This optimization eliminates many of
14783: these jumps and makes the rest much more predictable. The speedup
14784: depends on the processor and the application; on the Athlon and Pentium
14785: III this optimization typically produces a speedup by a factor of 2.
14786:
14787: The code addresses in the direct-threaded code are set to point to the
14788: appropriate points in the copied machine code, in this example like
14789: this:
1.1 anton 14790:
1.109 anton 14791: @example
14792: primitive code address
14793: dup $4057D27D
14794: * $4057D286
14795: ;s $4057D292
14796: @end example
14797:
14798: Thus there can be threaded-code jumps to any place in this piece of
14799: code. This also simplifies decompilation quite a bit.
14800:
14801: @cindex --no-dynamic command-line option
14802: @cindex --no-super command-line option
14803: You can disable this optimization with @option{--no-dynamic}. You can
14804: use the copying without eliminating the jumps (i.e., dynamic
14805: replication, but without superinstructions) with @option{--no-super};
14806: this gives the branch prediction benefit alone; the effect on
1.110 anton 14807: performance depends on the CPU; on the Athlon and Pentium III the
14808: speedup is a little less than for dynamic superinstructions with
14809: replication.
14810:
14811: @cindex patching threaded code
14812: One use of these options is if you want to patch the threaded code.
14813: With superinstructions, many of the dispatch jumps are eliminated, so
14814: patching often has no effect. These options preserve all the dispatch
14815: jumps.
1.109 anton 14816:
14817: @cindex --dynamic command-line option
1.110 anton 14818: On some machines dynamic superinstructions are disabled by default,
14819: because it is unsafe on these machines. However, if you feel
14820: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14821:
14822: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14823: @subsection DOES>
14824: @cindex @code{DOES>} implementation
14825:
1.26 crook 14826: @cindex @code{dodoes} routine
14827: @cindex @code{DOES>}-code
1.1 anton 14828: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14829: the chunk of code executed by every word defined by a
1.109 anton 14830: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14831: this is only needed if the xt of the word is @code{execute}d. The main
14832: problem here is: How to find the Forth code to be executed, i.e. the
14833: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14834: solutions:
1.1 anton 14835:
1.21 crook 14836: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14837: @code{DOES>}-code address is stored in the cell after the code address
14838: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14839: illegal in the Forth-79 and all later standards, because in fig-Forth
14840: this address lies in the body (which is illegal in these
14841: standards). However, by making the code field larger for all words this
14842: solution becomes legal again. We use this approach. Leaving a cell
14843: unused in most words is a bit wasteful, but on the machines we are
14844: targeting this is hardly a problem.
14845:
1.1 anton 14846:
14847: @node Primitives, Performance, Threading, Engine
14848: @section Primitives
14849: @cindex primitives, implementation
14850: @cindex virtual machine instructions, implementation
14851:
14852: @menu
14853: * Automatic Generation::
14854: * TOS Optimization::
14855: * Produced code::
14856: @end menu
14857:
14858: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14859: @subsection Automatic Generation
14860: @cindex primitives, automatic generation
14861:
14862: @cindex @file{prims2x.fs}
1.109 anton 14863:
1.1 anton 14864: Since the primitives are implemented in a portable language, there is no
14865: longer any need to minimize the number of primitives. On the contrary,
14866: having many primitives has an advantage: speed. In order to reduce the
14867: number of errors in primitives and to make programming them easier, we
1.109 anton 14868: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14869: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14870: generates most (and sometimes all) of the C code for a primitive from
14871: the stack effect notation. The source for a primitive has the following
14872: form:
1.1 anton 14873:
14874: @cindex primitive source format
14875: @format
1.58 anton 14876: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14877: [@code{""}@i{glossary entry}@code{""}]
14878: @i{C code}
1.1 anton 14879: [@code{:}
1.29 crook 14880: @i{Forth code}]
1.1 anton 14881: @end format
14882:
14883: The items in brackets are optional. The category and glossary fields
14884: are there for generating the documentation, the Forth code is there
14885: for manual implementations on machines without GNU C. E.g., the source
14886: for the primitive @code{+} is:
14887: @example
1.58 anton 14888: + ( n1 n2 -- n ) core plus
1.1 anton 14889: n = n1+n2;
14890: @end example
14891:
14892: This looks like a specification, but in fact @code{n = n1+n2} is C
14893: code. Our primitive generation tool extracts a lot of information from
14894: the stack effect notations@footnote{We use a one-stack notation, even
14895: though we have separate data and floating-point stacks; The separate
14896: notation can be generated easily from the unified notation.}: The number
14897: of items popped from and pushed on the stack, their type, and by what
14898: name they are referred to in the C code. It then generates a C code
14899: prelude and postlude for each primitive. The final C code for @code{+}
14900: looks like this:
14901:
14902: @example
1.46 pazsan 14903: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14904: /* */ /* documentation */
1.81 anton 14905: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14906: @{
14907: DEF_CA /* definition of variable ca (indirect threading) */
14908: Cell n1; /* definitions of variables */
14909: Cell n2;
14910: Cell n;
1.81 anton 14911: NEXT_P0; /* NEXT part 0 */
1.1 anton 14912: n1 = (Cell) sp[1]; /* input */
14913: n2 = (Cell) TOS;
14914: sp += 1; /* stack adjustment */
14915: @{
14916: n = n1+n2; /* C code taken from the source */
14917: @}
14918: NEXT_P1; /* NEXT part 1 */
14919: TOS = (Cell)n; /* output */
14920: NEXT_P2; /* NEXT part 2 */
14921: @}
14922: @end example
14923:
14924: This looks long and inefficient, but the GNU C compiler optimizes quite
14925: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14926: HP RISC machines: Defining the @code{n}s does not produce any code, and
14927: using them as intermediate storage also adds no cost.
14928:
1.26 crook 14929: There are also other optimizations that are not illustrated by this
14930: example: assignments between simple variables are usually for free (copy
1.1 anton 14931: propagation). If one of the stack items is not used by the primitive
14932: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14933: (dead code elimination). On the other hand, there are some things that
14934: the compiler does not do, therefore they are performed by
14935: @file{prims2x.fs}: The compiler does not optimize code away that stores
14936: a stack item to the place where it just came from (e.g., @code{over}).
14937:
14938: While programming a primitive is usually easy, there are a few cases
14939: where the programmer has to take the actions of the generator into
14940: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14941: fall through to @code{NEXT}.
1.109 anton 14942:
14943: For more information
1.1 anton 14944:
14945: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14946: @subsection TOS Optimization
14947: @cindex TOS optimization for primitives
14948: @cindex primitives, keeping the TOS in a register
14949:
14950: An important optimization for stack machine emulators, e.g., Forth
14951: engines, is keeping one or more of the top stack items in
1.29 crook 14952: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14953: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14954: @itemize @bullet
14955: @item
1.29 crook 14956: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14957: due to fewer loads from and stores to the stack.
1.29 crook 14958: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14959: @i{y<n}, due to additional moves between registers.
1.1 anton 14960: @end itemize
14961:
14962: @cindex -DUSE_TOS
14963: @cindex -DUSE_NO_TOS
14964: In particular, keeping one item in a register is never a disadvantage,
14965: if there are enough registers. Keeping two items in registers is a
14966: disadvantage for frequent words like @code{?branch}, constants,
14967: variables, literals and @code{i}. Therefore our generator only produces
14968: code that keeps zero or one items in registers. The generated C code
14969: covers both cases; the selection between these alternatives is made at
14970: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14971: code for @code{+} is just a simple variable name in the one-item case,
14972: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14973: GNU C compiler tries to keep simple variables like @code{TOS} in
14974: registers, and it usually succeeds, if there are enough registers.
14975:
14976: @cindex -DUSE_FTOS
14977: @cindex -DUSE_NO_FTOS
14978: The primitive generator performs the TOS optimization for the
14979: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14980: operations the benefit of this optimization is even larger:
14981: floating-point operations take quite long on most processors, but can be
14982: performed in parallel with other operations as long as their results are
14983: not used. If the FP-TOS is kept in a register, this works. If
14984: it is kept on the stack, i.e., in memory, the store into memory has to
14985: wait for the result of the floating-point operation, lengthening the
14986: execution time of the primitive considerably.
14987:
14988: The TOS optimization makes the automatic generation of primitives a
14989: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14990: @code{TOS} is not sufficient. There are some special cases to
14991: consider:
14992: @itemize @bullet
14993: @item In the case of @code{dup ( w -- w w )} the generator must not
14994: eliminate the store to the original location of the item on the stack,
14995: if the TOS optimization is turned on.
14996: @item Primitives with stack effects of the form @code{--}
1.29 crook 14997: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14998: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14999: must load the TOS from the stack at the end. But for the null stack
15000: effect @code{--} no stores or loads should be generated.
15001: @end itemize
15002:
15003: @node Produced code, , TOS Optimization, Primitives
15004: @subsection Produced code
15005: @cindex primitives, assembly code listing
15006:
15007: @cindex @file{engine.s}
15008: To see what assembly code is produced for the primitives on your machine
15009: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15010: look at the resulting file @file{engine.s}. Alternatively, you can also
15011: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15012:
15013: @node Performance, , Primitives, Engine
15014: @section Performance
15015: @cindex performance of some Forth interpreters
15016: @cindex engine performance
15017: @cindex benchmarking Forth systems
15018: @cindex Gforth performance
15019:
15020: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15021: impossible to write a significantly faster threaded-code engine.
1.1 anton 15022:
15023: On register-starved machines like the 386 architecture processors
15024: improvements are possible, because @code{gcc} does not utilize the
15025: registers as well as a human, even with explicit register declarations;
15026: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15027: and hand-tuned it for the 486; this system is 1.19 times faster on the
15028: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15029: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15030: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15031: registers fit in real registers (and we can even afford to use the TOS
15032: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15033: earlier results. And dynamic superinstructions provide another speedup
15034: (but only around a factor 1.2 on the 486).
1.1 anton 15035:
15036: @cindex Win32Forth performance
15037: @cindex NT Forth performance
15038: @cindex eforth performance
15039: @cindex ThisForth performance
15040: @cindex PFE performance
15041: @cindex TILE performance
1.81 anton 15042: The potential advantage of assembly language implementations is not
1.112 anton 15043: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15044: (direct threaded, compiled with @code{gcc-2.95.1} and
15045: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15046: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15047: (with and without peephole (aka pinhole) optimization of the threaded
15048: code); all these systems were written in assembly language. We also
15049: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15050: with @code{gcc-2.6.3} with the default configuration for Linux:
15051: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15052: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15053: employs peephole optimization of the threaded code) and TILE (compiled
15054: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15055: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15056: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15057: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15058: then extended it to run the benchmarks, added the peephole optimizer,
15059: ran the benchmarks and reported the results.
1.40 anton 15060:
1.1 anton 15061: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15062: matrix multiplication come from the Stanford integer benchmarks and have
15063: been translated into Forth by Martin Fraeman; we used the versions
15064: included in the TILE Forth package, but with bigger data set sizes; and
15065: a recursive Fibonacci number computation for benchmarking calling
15066: performance. The following table shows the time taken for the benchmarks
15067: scaled by the time taken by Gforth (in other words, it shows the speedup
15068: factor that Gforth achieved over the other systems).
15069:
15070: @example
1.112 anton 15071: relative Win32- NT eforth This-
15072: time Gforth Forth Forth eforth +opt PFE Forth TILE
15073: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15074: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15075: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15076: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15077: @end example
15078:
1.26 crook 15079: You may be quite surprised by the good performance of Gforth when
15080: compared with systems written in assembly language. One important reason
15081: for the disappointing performance of these other systems is probably
15082: that they are not written optimally for the 486 (e.g., they use the
15083: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15084: but costly method for relocating the Forth image: like @code{cforth}, it
15085: computes the actual addresses at run time, resulting in two address
15086: computations per @code{NEXT} (@pxref{Image File Background}).
15087:
1.1 anton 15088: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15089: explained with the self-imposed restriction of the latter systems to
15090: standard C, which makes efficient threading impossible (however, the
1.4 anton 15091: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15092: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15093: Moreover, current C compilers have a hard time optimizing other aspects
15094: of the ThisForth and the TILE source.
15095:
1.26 crook 15096: The performance of Gforth on 386 architecture processors varies widely
15097: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15098: allocate any of the virtual machine registers into real machine
15099: registers by itself and would not work correctly with explicit register
1.112 anton 15100: declarations, giving a significantly slower engine (on a 486DX2/66
15101: running the Sieve) than the one measured above.
1.1 anton 15102:
1.26 crook 15103: Note that there have been several releases of Win32Forth since the
15104: release presented here, so the results presented above may have little
1.40 anton 15105: predictive value for the performance of Win32Forth today (results for
15106: the current release on an i486DX2/66 are welcome).
1.1 anton 15107:
15108: @cindex @file{Benchres}
1.66 anton 15109: In
15110: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15111: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15112: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15113: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15114: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15115: than the version used here. You can find a newer version of these
15116: measurements at
1.47 crook 15117: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15118: find numbers for Gforth on various machines in @file{Benchres}.
15119:
1.26 crook 15120: @c ******************************************************************
1.113 anton 15121: @c @node Binding to System Library, Cross Compiler, Engine, Top
15122: @c @chapter Binding to System Library
1.13 pazsan 15123:
1.113 anton 15124: @c ****************************************************************
15125: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15126: @chapter Cross Compiler
1.47 crook 15127: @cindex @file{cross.fs}
15128: @cindex cross-compiler
15129: @cindex metacompiler
15130: @cindex target compiler
1.13 pazsan 15131:
1.46 pazsan 15132: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15133: mostly written in Forth, including crucial parts like the outer
15134: interpreter and compiler, it needs compiled Forth code to get
15135: started. The cross compiler allows to create new images for other
15136: architectures, even running under another Forth system.
1.13 pazsan 15137:
15138: @menu
1.67 anton 15139: * Using the Cross Compiler::
15140: * How the Cross Compiler Works::
1.13 pazsan 15141: @end menu
15142:
1.21 crook 15143: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15144: @section Using the Cross Compiler
1.46 pazsan 15145:
15146: The cross compiler uses a language that resembles Forth, but isn't. The
15147: main difference is that you can execute Forth code after definition,
15148: while you usually can't execute the code compiled by cross, because the
15149: code you are compiling is typically for a different computer than the
15150: one you are compiling on.
15151:
1.81 anton 15152: @c anton: This chapter is somewhat different from waht I would expect: I
15153: @c would expect an explanation of the cross language and how to create an
15154: @c application image with it. The section explains some aspects of
15155: @c creating a Gforth kernel.
15156:
1.46 pazsan 15157: The Makefile is already set up to allow you to create kernels for new
15158: architectures with a simple make command. The generic kernels using the
15159: GCC compiled virtual machine are created in the normal build process
15160: with @code{make}. To create a embedded Gforth executable for e.g. the
15161: 8086 processor (running on a DOS machine), type
15162:
15163: @example
15164: make kernl-8086.fi
15165: @end example
15166:
15167: This will use the machine description from the @file{arch/8086}
15168: directory to create a new kernel. A machine file may look like that:
15169:
15170: @example
15171: \ Parameter for target systems 06oct92py
15172:
15173: 4 Constant cell \ cell size in bytes
15174: 2 Constant cell<< \ cell shift to bytes
15175: 5 Constant cell>bit \ cell shift to bits
15176: 8 Constant bits/char \ bits per character
15177: 8 Constant bits/byte \ bits per byte [default: 8]
15178: 8 Constant float \ bytes per float
15179: 8 Constant /maxalign \ maximum alignment in bytes
15180: false Constant bigendian \ byte order
15181: ( true=big, false=little )
15182:
15183: include machpc.fs \ feature list
15184: @end example
15185:
15186: This part is obligatory for the cross compiler itself, the feature list
15187: is used by the kernel to conditionally compile some features in and out,
15188: depending on whether the target supports these features.
15189:
15190: There are some optional features, if you define your own primitives,
15191: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15192: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15193: @code{prims-include} includes primitives, and @code{>boot} prepares for
15194: booting.
15195:
15196: @example
15197: : asm-include ." Include assembler" cr
15198: s" arch/8086/asm.fs" included ;
15199:
15200: : prims-include ." Include primitives" cr
15201: s" arch/8086/prim.fs" included ;
15202:
15203: : >boot ." Prepare booting" cr
15204: s" ' boot >body into-forth 1+ !" evaluate ;
15205: @end example
15206:
15207: These words are used as sort of macro during the cross compilation in
1.81 anton 15208: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15209: be possible --- but more complicated --- to write a new kernel project
15210: file, too.
15211:
15212: @file{kernel/main.fs} expects the machine description file name on the
15213: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15214: @code{mach-file} leaves a counted string on the stack, or
15215: @code{machine-file} leaves an address, count pair of the filename on the
15216: stack.
15217:
15218: The feature list is typically controlled using @code{SetValue}, generic
15219: files that are used by several projects can use @code{DefaultValue}
15220: instead. Both functions work like @code{Value}, when the value isn't
15221: defined, but @code{SetValue} works like @code{to} if the value is
15222: defined, and @code{DefaultValue} doesn't set anything, if the value is
15223: defined.
15224:
15225: @example
15226: \ generic mach file for pc gforth 03sep97jaw
15227:
15228: true DefaultValue NIL \ relocating
15229:
15230: >ENVIRON
15231:
15232: true DefaultValue file \ controls the presence of the
15233: \ file access wordset
15234: true DefaultValue OS \ flag to indicate a operating system
15235:
15236: true DefaultValue prims \ true: primitives are c-code
15237:
15238: true DefaultValue floating \ floating point wordset is present
15239:
15240: true DefaultValue glocals \ gforth locals are present
15241: \ will be loaded
15242: true DefaultValue dcomps \ double number comparisons
15243:
15244: true DefaultValue hash \ hashing primitives are loaded/present
15245:
15246: true DefaultValue xconds \ used together with glocals,
15247: \ special conditionals supporting gforths'
15248: \ local variables
15249: true DefaultValue header \ save a header information
15250:
15251: true DefaultValue backtrace \ enables backtrace code
15252:
15253: false DefaultValue ec
15254: false DefaultValue crlf
15255:
15256: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15257:
15258: &16 KB DefaultValue stack-size
15259: &15 KB &512 + DefaultValue fstack-size
15260: &15 KB DefaultValue rstack-size
15261: &14 KB &512 + DefaultValue lstack-size
15262: @end example
1.13 pazsan 15263:
1.48 anton 15264: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15265: @section How the Cross Compiler Works
1.13 pazsan 15266:
15267: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15268: @appendix Bugs
1.1 anton 15269: @cindex bug reporting
15270:
1.21 crook 15271: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15272:
1.103 anton 15273: If you find a bug, please submit a bug report through
15274: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15275:
15276: @itemize @bullet
15277: @item
1.81 anton 15278: A program (or a sequence of keyboard commands) that reproduces the bug.
15279: @item
15280: A description of what you think constitutes the buggy behaviour.
15281: @item
1.21 crook 15282: The Gforth version used (it is announced at the start of an
15283: interactive Gforth session).
15284: @item
15285: The machine and operating system (on Unix
15286: systems @code{uname -a} will report this information).
15287: @item
1.81 anton 15288: The installation options (you can find the configure options at the
15289: start of @file{config.status}) and configuration (@code{configure}
15290: output or @file{config.cache}).
1.21 crook 15291: @item
15292: A complete list of changes (if any) you (or your installer) have made to the
15293: Gforth sources.
15294: @end itemize
1.1 anton 15295:
15296: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15297: to Report Bugs, gcc.info, GNU C Manual}.
15298:
15299:
1.21 crook 15300: @node Origin, Forth-related information, Bugs, Top
15301: @appendix Authors and Ancestors of Gforth
1.1 anton 15302:
15303: @section Authors and Contributors
15304: @cindex authors of Gforth
15305: @cindex contributors to Gforth
15306:
15307: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15308: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15309: lot to the manual. Assemblers and disassemblers were contributed by
15310: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15311: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15312: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15313: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15314: support for calling C libraries. Helpful comments also came from Paul
15315: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15316: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15317: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15318: Gforth-0.2.1 there were also helpful comments from many others; thank
15319: you all, sorry for not listing you here (but digging through my mailbox
15320: to extract your names is on my to-do list).
1.1 anton 15321:
15322: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15323: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15324: was developed across the Internet, and its authors did not meet
1.20 pazsan 15325: physically for the first 4 years of development.
1.1 anton 15326:
15327: @section Pedigree
1.26 crook 15328: @cindex pedigree of Gforth
1.1 anton 15329:
1.81 anton 15330: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15331: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15332:
1.20 pazsan 15333: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15334: 32 bit native code version of VolksForth for the Atari ST, written
15335: mostly by Dietrich Weineck.
15336:
1.81 anton 15337: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15338: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15339: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15340:
15341: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15342: Forth-83 standard. !! Pedigree? When?
15343:
15344: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15345: 1979. Robert Selzer and Bill Ragsdale developed the original
15346: implementation of fig-Forth for the 6502 based on microForth.
15347:
15348: The principal architect of microForth was Dean Sanderson. microForth was
15349: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15350: the 1802, and subsequently implemented on the 8080, the 6800 and the
15351: Z80.
15352:
15353: All earlier Forth systems were custom-made, usually by Charles Moore,
15354: who discovered (as he puts it) Forth during the late 60s. The first full
15355: Forth existed in 1971.
15356:
1.81 anton 15357: A part of the information in this section comes from
15358: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15359: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15360: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15361: SIGPLAN Notices 28(3), 1993. You can find more historical and
15362: genealogical information about Forth there.
1.1 anton 15363:
1.81 anton 15364: @c ------------------------------------------------------------------
1.113 anton 15365: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15366: @appendix Other Forth-related information
15367: @cindex Forth-related information
15368:
1.81 anton 15369: @c anton: I threw most of this stuff out, because it can be found through
15370: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15371:
15372: @cindex comp.lang.forth
15373: @cindex frequently asked questions
1.81 anton 15374: There is an active news group (comp.lang.forth) discussing Forth
15375: (including Gforth) and Forth-related issues. Its
15376: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15377: (frequently asked questions and their answers) contains a lot of
15378: information on Forth. You should read it before posting to
15379: comp.lang.forth.
1.21 crook 15380:
1.81 anton 15381: The ANS Forth standard is most usable in its
15382: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15383:
1.113 anton 15384: @c ---------------------------------------------------
15385: @node Licenses, Word Index, Forth-related information, Top
15386: @appendix Licenses
15387:
15388: @menu
15389: * GNU Free Documentation License:: License for copying this manual.
15390: * Copying:: GPL (for copying this software).
15391: @end menu
15392:
15393: @include fdl.texi
15394:
15395: @include gpl.texi
15396:
15397:
15398:
1.81 anton 15399: @c ------------------------------------------------------------------
1.113 anton 15400: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15401: @unnumbered Word Index
15402:
1.26 crook 15403: This index is a list of Forth words that have ``glossary'' entries
15404: within this manual. Each word is listed with its stack effect and
15405: wordset.
1.1 anton 15406:
15407: @printindex fn
15408:
1.81 anton 15409: @c anton: the name index seems superfluous given the word and concept indices.
15410:
15411: @c @node Name Index, Concept Index, Word Index, Top
15412: @c @unnumbered Name Index
1.41 anton 15413:
1.81 anton 15414: @c This index is a list of Forth words that have ``glossary'' entries
15415: @c within this manual.
1.41 anton 15416:
1.81 anton 15417: @c @printindex ky
1.41 anton 15418:
1.113 anton 15419: @c -------------------------------------------------------
1.81 anton 15420: @node Concept Index, , Word Index, Top
1.1 anton 15421: @unnumbered Concept and Word Index
15422:
1.26 crook 15423: Not all entries listed in this index are present verbatim in the
15424: text. This index also duplicates, in abbreviated form, all of the words
15425: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15426:
15427: @printindex cp
15428:
15429: @bye
1.81 anton 15430:
15431:
1.1 anton 15432:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>