Annotation of gforth/doc/gforth.ds, revision 1.145
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.142 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
226: * Assembler and Code Words::
227: * Threading Words::
1.65 anton 228: * Passing Commands to the OS::
229: * Keeping track of Time::
230: * Miscellaneous Words::
1.12 anton 231:
232: Arithmetic
233:
234: * Single precision::
1.67 anton 235: * Double precision:: Double-cell integer arithmetic
1.12 anton 236: * Bitwise operations::
1.67 anton 237: * Numeric comparison::
1.32 anton 238: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 239: * Floating Point::
240:
241: Stack Manipulation
242:
243: * Data stack::
244: * Floating point stack::
245: * Return stack::
246: * Locals stack::
247: * Stack pointer manipulation::
248:
249: Memory
250:
1.32 anton 251: * Memory model::
252: * Dictionary allocation::
253: * Heap Allocation::
254: * Memory Access::
255: * Address arithmetic::
256: * Memory Blocks::
1.12 anton 257:
258: Control Structures
259:
1.41 anton 260: * Selection:: IF ... ELSE ... ENDIF
261: * Simple Loops:: BEGIN ...
1.32 anton 262: * Counted Loops:: DO
1.67 anton 263: * Arbitrary control structures::
264: * Calls and returns::
1.12 anton 265: * Exception Handling::
266:
267: Defining Words
268:
1.67 anton 269: * CREATE::
1.44 crook 270: * Variables:: Variables and user variables
1.67 anton 271: * Constants::
1.44 crook 272: * Values:: Initialised variables
1.67 anton 273: * Colon Definitions::
1.44 crook 274: * Anonymous Definitions:: Definitions without names
1.71 anton 275: * Supplying names:: Passing definition names as strings
1.67 anton 276: * User-defined Defining Words::
1.44 crook 277: * Deferred words:: Allow forward references
1.67 anton 278: * Aliases::
1.47 crook 279:
1.63 anton 280: User-defined Defining Words
281:
282: * CREATE..DOES> applications::
283: * CREATE..DOES> details::
284: * Advanced does> usage example::
1.91 anton 285: * @code{Const-does>}::
1.63 anton 286:
1.47 crook 287: Interpretation and Compilation Semantics
288:
1.67 anton 289: * Combined words::
1.12 anton 290:
1.71 anton 291: Tokens for Words
292:
293: * Execution token:: represents execution/interpretation semantics
294: * Compilation token:: represents compilation semantics
295: * Name token:: represents named words
296:
1.82 anton 297: Compiling words
298:
299: * Literals:: Compiling data values
300: * Macros:: Compiling words
301:
1.21 crook 302: The Text Interpreter
303:
1.67 anton 304: * Input Sources::
305: * Number Conversion::
306: * Interpret/Compile states::
307: * Interpreter Directives::
1.21 crook 308:
1.26 crook 309: Word Lists
310:
1.75 anton 311: * Vocabularies::
1.67 anton 312: * Why use word lists?::
1.75 anton 313: * Word list example::
1.26 crook 314:
315: Files
316:
1.48 anton 317: * Forth source files::
318: * General files::
319: * Search Paths::
320:
321: Search Paths
322:
1.75 anton 323: * Source Search Paths::
1.26 crook 324: * General Search Paths::
325:
326: Other I/O
327:
1.32 anton 328: * Simple numeric output:: Predefined formats
329: * Formatted numeric output:: Formatted (pictured) output
330: * String Formats:: How Forth stores strings in memory
1.67 anton 331: * Displaying characters and strings:: Other stuff
1.32 anton 332: * Input:: Input
1.112 anton 333: * Pipes:: How to create your own pipes
1.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!
1.144 anton 4985: doc-sw@
4986: doc-uw@
4987: doc-w!
4988: doc-sl@
4989: doc-ul@
4990: doc-l!
1.68 anton 4991:
1.32 anton 4992: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4993: @subsection Address arithmetic
1.1 anton 4994: @cindex address arithmetic words
4995:
1.67 anton 4996: Address arithmetic is the foundation on which you can build data
4997: structures like arrays, records (@pxref{Structures}) and objects
4998: (@pxref{Object-oriented Forth}).
1.32 anton 4999:
1.68 anton 5000: @cindex address unit
5001: @cindex au (address unit)
1.1 anton 5002: ANS Forth does not specify the sizes of the data types. Instead, it
5003: offers a number of words for computing sizes and doing address
1.29 crook 5004: arithmetic. Address arithmetic is performed in terms of address units
5005: (aus); on most systems the address unit is one byte. Note that a
5006: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5007: platforms where it is a noop, it compiles to nothing).
1.1 anton 5008:
1.67 anton 5009: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5010: you have the address of a cell, perform @code{1 cells +}, and you will
5011: have the address of the next cell.
5012:
1.68 anton 5013: @cindex contiguous regions and address arithmetic
1.67 anton 5014: In ANS Forth you can perform address arithmetic only within a contiguous
5015: region, i.e., if you have an address into one region, you can only add
5016: and subtract such that the result is still within the region; you can
5017: only subtract or compare addresses from within the same contiguous
5018: region. Reasons: several contiguous regions can be arranged in memory
5019: in any way; on segmented systems addresses may have unusual
5020: representations, such that address arithmetic only works within a
5021: region. Gforth provides a few more guarantees (linear address space,
5022: dictionary grows upwards), but in general I have found it easy to stay
5023: within contiguous regions (exception: computing and comparing to the
5024: address just beyond the end of an array).
5025:
1.1 anton 5026: @cindex alignment of addresses for types
5027: ANS Forth also defines words for aligning addresses for specific
5028: types. Many computers require that accesses to specific data types
5029: must only occur at specific addresses; e.g., that cells may only be
5030: accessed at addresses divisible by 4. Even if a machine allows unaligned
5031: accesses, it can usually perform aligned accesses faster.
5032:
5033: For the performance-conscious: alignment operations are usually only
5034: necessary during the definition of a data structure, not during the
5035: (more frequent) accesses to it.
5036:
5037: ANS Forth defines no words for character-aligning addresses. This is not
5038: an oversight, but reflects the fact that addresses that are not
5039: char-aligned have no use in the standard and therefore will not be
5040: created.
5041:
5042: @cindex @code{CREATE} and alignment
1.29 crook 5043: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5044: are cell-aligned; in addition, Gforth guarantees that these addresses
5045: are aligned for all purposes.
5046:
1.26 crook 5047: Note that the ANS Forth word @code{char} has nothing to do with address
5048: arithmetic.
1.1 anton 5049:
1.44 crook 5050:
1.1 anton 5051: doc-chars
5052: doc-char+
5053: doc-cells
5054: doc-cell+
5055: doc-cell
5056: doc-aligned
5057: doc-floats
5058: doc-float+
5059: doc-float
5060: doc-faligned
5061: doc-sfloats
5062: doc-sfloat+
5063: doc-sfaligned
5064: doc-dfloats
5065: doc-dfloat+
5066: doc-dfaligned
5067: doc-maxaligned
5068: doc-cfaligned
5069: doc-address-unit-bits
1.145 ! anton 5070: doc-/w
! 5071: doc-/l
1.44 crook 5072:
1.32 anton 5073: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5074: @subsection Memory Blocks
5075: @cindex memory block words
1.27 crook 5076: @cindex character strings - moving and copying
5077:
1.49 anton 5078: Memory blocks often represent character strings; For ways of storing
5079: character strings in memory see @ref{String Formats}. For other
5080: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5081:
1.67 anton 5082: A few of these words work on address unit blocks. In that case, you
5083: usually have to insert @code{CHARS} before the word when working on
5084: character strings. Most words work on character blocks, and expect a
5085: char-aligned address.
5086:
5087: When copying characters between overlapping memory regions, use
5088: @code{chars move} or choose carefully between @code{cmove} and
5089: @code{cmove>}.
1.44 crook 5090:
1.1 anton 5091: doc-move
5092: doc-erase
5093: doc-cmove
5094: doc-cmove>
5095: doc-fill
5096: doc-blank
1.21 crook 5097: doc-compare
1.111 anton 5098: doc-str=
5099: doc-str<
5100: doc-string-prefix?
1.21 crook 5101: doc-search
1.27 crook 5102: doc--trailing
5103: doc-/string
1.82 anton 5104: doc-bounds
1.141 anton 5105: doc-pad
1.111 anton 5106:
1.27 crook 5107: @comment TODO examples
5108:
1.1 anton 5109:
1.26 crook 5110: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5111: @section Control Structures
5112: @cindex control structures
5113:
1.33 anton 5114: Control structures in Forth cannot be used interpretively, only in a
5115: colon definition@footnote{To be precise, they have no interpretation
5116: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5117: not like this limitation, but have not seen a satisfying way around it
5118: yet, although many schemes have been proposed.
1.1 anton 5119:
5120: @menu
1.33 anton 5121: * Selection:: IF ... ELSE ... ENDIF
5122: * Simple Loops:: BEGIN ...
1.29 crook 5123: * Counted Loops:: DO
1.67 anton 5124: * Arbitrary control structures::
5125: * Calls and returns::
1.1 anton 5126: * Exception Handling::
5127: @end menu
5128:
5129: @node Selection, Simple Loops, Control Structures, Control Structures
5130: @subsection Selection
5131: @cindex selection control structures
5132: @cindex control structures for selection
5133:
5134: @cindex @code{IF} control structure
5135: @example
1.29 crook 5136: @i{flag}
1.1 anton 5137: IF
1.29 crook 5138: @i{code}
1.1 anton 5139: ENDIF
5140: @end example
1.21 crook 5141: @noindent
1.33 anton 5142:
1.44 crook 5143: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5144: with any bit set represents truth) @i{code} is executed.
1.33 anton 5145:
1.1 anton 5146: @example
1.29 crook 5147: @i{flag}
1.1 anton 5148: IF
1.29 crook 5149: @i{code1}
1.1 anton 5150: ELSE
1.29 crook 5151: @i{code2}
1.1 anton 5152: ENDIF
5153: @end example
5154:
1.44 crook 5155: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5156: executed.
1.33 anton 5157:
1.1 anton 5158: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5159: standard, and @code{ENDIF} is not, although it is quite popular. We
5160: recommend using @code{ENDIF}, because it is less confusing for people
5161: who also know other languages (and is not prone to reinforcing negative
5162: prejudices against Forth in these people). Adding @code{ENDIF} to a
5163: system that only supplies @code{THEN} is simple:
5164: @example
1.82 anton 5165: : ENDIF POSTPONE then ; immediate
1.1 anton 5166: @end example
5167:
5168: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5169: (adv.)} has the following meanings:
5170: @quotation
5171: ... 2b: following next after in order ... 3d: as a necessary consequence
5172: (if you were there, then you saw them).
5173: @end quotation
5174: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5175: and many other programming languages has the meaning 3d.]
5176:
1.21 crook 5177: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5178: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5179: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5180: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5181: @file{compat/control.fs}.
5182:
5183: @cindex @code{CASE} control structure
5184: @example
1.29 crook 5185: @i{n}
1.1 anton 5186: CASE
1.29 crook 5187: @i{n1} OF @i{code1} ENDOF
5188: @i{n2} OF @i{code2} ENDOF
1.1 anton 5189: @dots{}
1.68 anton 5190: ( n ) @i{default-code} ( n )
1.131 anton 5191: ENDCASE ( )
1.1 anton 5192: @end example
5193:
1.131 anton 5194: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5195: no @i{ni} matches, the optional @i{default-code} is executed. The
5196: optional default case can be added by simply writing the code after
5197: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5198: but must not consume it. The value @i{n} is consumed by this
5199: construction (either by a OF that matches, or by the ENDCASE, if no OF
5200: matches).
1.1 anton 5201:
1.69 anton 5202: @progstyle
1.131 anton 5203: To keep the code understandable, you should ensure that you change the
5204: stack in the same way (wrt. number and types of stack items consumed
5205: and pushed) on all paths through a selection construct.
1.69 anton 5206:
1.1 anton 5207: @node Simple Loops, Counted Loops, Selection, Control Structures
5208: @subsection Simple Loops
5209: @cindex simple loops
5210: @cindex loops without count
5211:
5212: @cindex @code{WHILE} loop
5213: @example
5214: BEGIN
1.29 crook 5215: @i{code1}
5216: @i{flag}
1.1 anton 5217: WHILE
1.29 crook 5218: @i{code2}
1.1 anton 5219: REPEAT
5220: @end example
5221:
1.29 crook 5222: @i{code1} is executed and @i{flag} is computed. If it is true,
5223: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5224: false, execution continues after the @code{REPEAT}.
5225:
5226: @cindex @code{UNTIL} loop
5227: @example
5228: BEGIN
1.29 crook 5229: @i{code}
5230: @i{flag}
1.1 anton 5231: UNTIL
5232: @end example
5233:
1.29 crook 5234: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5235:
1.69 anton 5236: @progstyle
5237: To keep the code understandable, a complete iteration of the loop should
5238: not change the number and types of the items on the stacks.
5239:
1.1 anton 5240: @cindex endless loop
5241: @cindex loops, endless
5242: @example
5243: BEGIN
1.29 crook 5244: @i{code}
1.1 anton 5245: AGAIN
5246: @end example
5247:
5248: This is an endless loop.
5249:
5250: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5251: @subsection Counted Loops
5252: @cindex counted loops
5253: @cindex loops, counted
5254: @cindex @code{DO} loops
5255:
5256: The basic counted loop is:
5257: @example
1.29 crook 5258: @i{limit} @i{start}
1.1 anton 5259: ?DO
1.29 crook 5260: @i{body}
1.1 anton 5261: LOOP
5262: @end example
5263:
1.29 crook 5264: This performs one iteration for every integer, starting from @i{start}
5265: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5266: accessed with @code{i}. For example, the loop:
1.1 anton 5267: @example
5268: 10 0 ?DO
5269: i .
5270: LOOP
5271: @end example
1.21 crook 5272: @noindent
5273: prints @code{0 1 2 3 4 5 6 7 8 9}
5274:
1.1 anton 5275: The index of the innermost loop can be accessed with @code{i}, the index
5276: of the next loop with @code{j}, and the index of the third loop with
5277: @code{k}.
5278:
1.44 crook 5279:
1.1 anton 5280: doc-i
5281: doc-j
5282: doc-k
5283:
1.44 crook 5284:
1.1 anton 5285: The loop control data are kept on the return stack, so there are some
1.21 crook 5286: restrictions on mixing return stack accesses and counted loop words. In
5287: particuler, if you put values on the return stack outside the loop, you
5288: cannot read them inside the loop@footnote{well, not in a way that is
5289: portable.}. If you put values on the return stack within a loop, you
5290: have to remove them before the end of the loop and before accessing the
5291: index of the loop.
1.1 anton 5292:
5293: There are several variations on the counted loop:
5294:
1.21 crook 5295: @itemize @bullet
5296: @item
5297: @code{LEAVE} leaves the innermost counted loop immediately; execution
5298: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5299:
5300: @example
5301: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5302: @end example
5303: prints @code{0 1 2 3}
5304:
1.1 anton 5305:
1.21 crook 5306: @item
5307: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5308: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5309: return stack so @code{EXIT} can get to its return address. For example:
5310:
5311: @example
5312: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5313: @end example
5314: prints @code{0 1 2 3}
5315:
5316:
5317: @item
1.29 crook 5318: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5319: (and @code{LOOP} iterates until they become equal by wrap-around
5320: arithmetic). This behaviour is usually not what you want. Therefore,
5321: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5322: @code{?DO}), which do not enter the loop if @i{start} is greater than
5323: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5324: unsigned loop parameters.
5325:
1.21 crook 5326: @item
5327: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5328: the loop, independent of the loop parameters. Do not use @code{DO}, even
5329: if you know that the loop is entered in any case. Such knowledge tends
5330: to become invalid during maintenance of a program, and then the
5331: @code{DO} will make trouble.
5332:
5333: @item
1.29 crook 5334: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5335: index by @i{n} instead of by 1. The loop is terminated when the border
5336: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5337:
1.21 crook 5338: @example
5339: 4 0 +DO i . 2 +LOOP
5340: @end example
5341: @noindent
5342: prints @code{0 2}
5343:
5344: @example
5345: 4 1 +DO i . 2 +LOOP
5346: @end example
5347: @noindent
5348: prints @code{1 3}
1.1 anton 5349:
1.68 anton 5350: @item
1.1 anton 5351: @cindex negative increment for counted loops
5352: @cindex counted loops with negative increment
1.29 crook 5353: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5354:
1.21 crook 5355: @example
5356: -1 0 ?DO i . -1 +LOOP
5357: @end example
5358: @noindent
5359: prints @code{0 -1}
1.1 anton 5360:
1.21 crook 5361: @example
5362: 0 0 ?DO i . -1 +LOOP
5363: @end example
5364: prints nothing.
1.1 anton 5365:
1.29 crook 5366: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5367: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5368: index by @i{u} each iteration. The loop is terminated when the border
5369: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5370: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5371:
1.21 crook 5372: @example
5373: -2 0 -DO i . 1 -LOOP
5374: @end example
5375: @noindent
5376: prints @code{0 -1}
1.1 anton 5377:
1.21 crook 5378: @example
5379: -1 0 -DO i . 1 -LOOP
5380: @end example
5381: @noindent
5382: prints @code{0}
5383:
5384: @example
5385: 0 0 -DO i . 1 -LOOP
5386: @end example
5387: @noindent
5388: prints nothing.
1.1 anton 5389:
1.21 crook 5390: @end itemize
1.1 anton 5391:
5392: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5393: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5394: for these words that uses only standard words is provided in
5395: @file{compat/loops.fs}.
1.1 anton 5396:
5397:
5398: @cindex @code{FOR} loops
1.26 crook 5399: Another counted loop is:
1.1 anton 5400: @example
1.29 crook 5401: @i{n}
1.1 anton 5402: FOR
1.29 crook 5403: @i{body}
1.1 anton 5404: NEXT
5405: @end example
5406: This is the preferred loop of native code compiler writers who are too
1.26 crook 5407: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5408: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5409: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5410: Forth systems may behave differently, even if they support @code{FOR}
5411: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5412:
5413: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5414: @subsection Arbitrary control structures
5415: @cindex control structures, user-defined
5416:
5417: @cindex control-flow stack
5418: ANS Forth permits and supports using control structures in a non-nested
5419: way. Information about incomplete control structures is stored on the
5420: control-flow stack. This stack may be implemented on the Forth data
5421: stack, and this is what we have done in Gforth.
5422:
5423: @cindex @code{orig}, control-flow stack item
5424: @cindex @code{dest}, control-flow stack item
5425: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5426: entry represents a backward branch target. A few words are the basis for
5427: building any control structure possible (except control structures that
5428: need storage, like calls, coroutines, and backtracking).
5429:
1.44 crook 5430:
1.1 anton 5431: doc-if
5432: doc-ahead
5433: doc-then
5434: doc-begin
5435: doc-until
5436: doc-again
5437: doc-cs-pick
5438: doc-cs-roll
5439:
1.44 crook 5440:
1.21 crook 5441: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5442: manipulate the control-flow stack in a portable way. Without them, you
5443: would need to know how many stack items are occupied by a control-flow
5444: entry (many systems use one cell. In Gforth they currently take three,
5445: but this may change in the future).
5446:
1.1 anton 5447: Some standard control structure words are built from these words:
5448:
1.44 crook 5449:
1.1 anton 5450: doc-else
5451: doc-while
5452: doc-repeat
5453:
1.44 crook 5454:
5455: @noindent
1.1 anton 5456: Gforth adds some more control-structure words:
5457:
1.44 crook 5458:
1.1 anton 5459: doc-endif
5460: doc-?dup-if
5461: doc-?dup-0=-if
5462:
1.44 crook 5463:
5464: @noindent
1.1 anton 5465: Counted loop words constitute a separate group of words:
5466:
1.44 crook 5467:
1.1 anton 5468: doc-?do
5469: doc-+do
5470: doc-u+do
5471: doc--do
5472: doc-u-do
5473: doc-do
5474: doc-for
5475: doc-loop
5476: doc-+loop
5477: doc--loop
5478: doc-next
5479: doc-leave
5480: doc-?leave
5481: doc-unloop
5482: doc-done
5483:
1.44 crook 5484:
1.21 crook 5485: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5486: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5487: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5488: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5489: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5490: resolved (by using one of the loop-ending words or @code{DONE}).
5491:
1.44 crook 5492: @noindent
1.26 crook 5493: Another group of control structure words are:
1.1 anton 5494:
1.44 crook 5495:
1.1 anton 5496: doc-case
5497: doc-endcase
5498: doc-of
5499: doc-endof
5500:
1.44 crook 5501:
1.21 crook 5502: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5503: @code{CS-ROLL}.
1.1 anton 5504:
5505: @subsubsection Programming Style
1.47 crook 5506: @cindex control structures programming style
5507: @cindex programming style, arbitrary control structures
1.1 anton 5508:
5509: In order to ensure readability we recommend that you do not create
5510: arbitrary control structures directly, but define new control structure
5511: words for the control structure you want and use these words in your
1.26 crook 5512: program. For example, instead of writing:
1.1 anton 5513:
5514: @example
1.26 crook 5515: BEGIN
1.1 anton 5516: ...
1.26 crook 5517: IF [ 1 CS-ROLL ]
1.1 anton 5518: ...
1.26 crook 5519: AGAIN THEN
1.1 anton 5520: @end example
5521:
1.21 crook 5522: @noindent
1.1 anton 5523: we recommend defining control structure words, e.g.,
5524:
5525: @example
1.26 crook 5526: : WHILE ( DEST -- ORIG DEST )
5527: POSTPONE IF
5528: 1 CS-ROLL ; immediate
5529:
5530: : REPEAT ( orig dest -- )
5531: POSTPONE AGAIN
5532: POSTPONE THEN ; immediate
1.1 anton 5533: @end example
5534:
1.21 crook 5535: @noindent
1.1 anton 5536: and then using these to create the control structure:
5537:
5538: @example
1.26 crook 5539: BEGIN
1.1 anton 5540: ...
1.26 crook 5541: WHILE
1.1 anton 5542: ...
1.26 crook 5543: REPEAT
1.1 anton 5544: @end example
5545:
5546: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5547: @code{WHILE} are predefined, so in this example it would not be
5548: necessary to define them.
5549:
5550: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5551: @subsection Calls and returns
5552: @cindex calling a definition
5553: @cindex returning from a definition
5554:
1.3 anton 5555: @cindex recursive definitions
5556: A definition can be called simply be writing the name of the definition
1.26 crook 5557: to be called. Normally a definition is invisible during its own
1.3 anton 5558: definition. If you want to write a directly recursive definition, you
1.26 crook 5559: can use @code{recursive} to make the current definition visible, or
5560: @code{recurse} to call the current definition directly.
1.3 anton 5561:
1.44 crook 5562:
1.3 anton 5563: doc-recursive
5564: doc-recurse
5565:
1.44 crook 5566:
1.21 crook 5567: @comment TODO add example of the two recursion methods
1.12 anton 5568: @quotation
5569: @progstyle
5570: I prefer using @code{recursive} to @code{recurse}, because calling the
5571: definition by name is more descriptive (if the name is well-chosen) than
5572: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5573: implementation, it is much better to read (and think) ``now sort the
5574: partitions'' than to read ``now do a recursive call''.
5575: @end quotation
1.3 anton 5576:
1.29 crook 5577: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5578:
5579: @example
1.28 crook 5580: Defer foo
1.3 anton 5581:
5582: : bar ( ... -- ... )
5583: ... foo ... ;
5584:
5585: :noname ( ... -- ... )
5586: ... bar ... ;
5587: IS foo
5588: @end example
5589:
1.44 crook 5590: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5591:
1.26 crook 5592: The current definition returns control to the calling definition when
1.33 anton 5593: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5594:
5595: doc-exit
5596: doc-;s
5597:
1.44 crook 5598:
1.1 anton 5599: @node Exception Handling, , Calls and returns, Control Structures
5600: @subsection Exception Handling
1.26 crook 5601: @cindex exceptions
1.1 anton 5602:
1.68 anton 5603: @c quit is a very bad idea for error handling,
5604: @c because it does not translate into a THROW
5605: @c it also does not belong into this chapter
5606:
5607: If a word detects an error condition that it cannot handle, it can
5608: @code{throw} an exception. In the simplest case, this will terminate
5609: your program, and report an appropriate error.
1.21 crook 5610:
1.68 anton 5611: doc-throw
1.1 anton 5612:
1.69 anton 5613: @code{Throw} consumes a cell-sized error number on the stack. There are
5614: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5615: Gforth (and most other systems) you can use the iors produced by various
5616: words as error numbers (e.g., a typical use of @code{allocate} is
5617: @code{allocate throw}). Gforth also provides the word @code{exception}
5618: to define your own error numbers (with decent error reporting); an ANS
5619: Forth version of this word (but without the error messages) is available
5620: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5621: numbers (anything outside the range -4095..0), but won't get nice error
5622: messages, only numbers. For example, try:
5623:
5624: @example
1.69 anton 5625: -10 throw \ ANS defined
5626: -267 throw \ system defined
5627: s" my error" exception throw \ user defined
5628: 7 throw \ arbitrary number
1.68 anton 5629: @end example
5630:
5631: doc---exception-exception
1.1 anton 5632:
1.69 anton 5633: A common idiom to @code{THROW} a specific error if a flag is true is
5634: this:
5635:
5636: @example
5637: @code{( flag ) 0<> @i{errno} and throw}
5638: @end example
5639:
5640: Your program can provide exception handlers to catch exceptions. An
5641: exception handler can be used to correct the problem, or to clean up
5642: some data structures and just throw the exception to the next exception
5643: handler. Note that @code{throw} jumps to the dynamically innermost
5644: exception handler. The system's exception handler is outermost, and just
5645: prints an error and restarts command-line interpretation (or, in batch
5646: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5647:
1.68 anton 5648: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5649:
1.68 anton 5650: doc-catch
5651:
5652: The most common use of exception handlers is to clean up the state when
5653: an error happens. E.g.,
1.1 anton 5654:
1.26 crook 5655: @example
1.68 anton 5656: base @ >r hex \ actually the hex should be inside foo, or we h
5657: ['] foo catch ( nerror|0 )
5658: r> base !
1.69 anton 5659: ( nerror|0 ) throw \ pass it on
1.26 crook 5660: @end example
1.1 anton 5661:
1.69 anton 5662: A use of @code{catch} for handling the error @code{myerror} might look
5663: like this:
1.44 crook 5664:
1.68 anton 5665: @example
1.69 anton 5666: ['] foo catch
5667: CASE
5668: myerror OF ... ( do something about it ) ENDOF
5669: dup throw \ default: pass other errors on, do nothing on non-errors
5670: ENDCASE
1.68 anton 5671: @end example
1.44 crook 5672:
1.68 anton 5673: Having to wrap the code into a separate word is often cumbersome,
5674: therefore Gforth provides an alternative syntax:
1.1 anton 5675:
5676: @example
1.69 anton 5677: TRY
1.68 anton 5678: @i{code1}
1.69 anton 5679: RECOVER \ optional
1.68 anton 5680: @i{code2} \ optional
1.69 anton 5681: ENDTRY
1.1 anton 5682: @end example
5683:
1.68 anton 5684: This performs @i{Code1}. If @i{code1} completes normally, execution
5685: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5686: reset to the state during @code{try}, the throw value is pushed on the
5687: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5688: through the @code{endtry} into the following code.
1.26 crook 5689:
1.68 anton 5690: doc-try
5691: doc-recover
5692: doc-endtry
1.26 crook 5693:
1.69 anton 5694: The cleanup example from above in this syntax:
1.26 crook 5695:
1.68 anton 5696: @example
1.69 anton 5697: base @ >r TRY
1.68 anton 5698: hex foo \ now the hex is placed correctly
1.69 anton 5699: 0 \ value for throw
1.92 anton 5700: RECOVER ENDTRY
1.68 anton 5701: r> base ! throw
1.1 anton 5702: @end example
5703:
1.69 anton 5704: And here's the error handling example:
1.1 anton 5705:
1.68 anton 5706: @example
1.69 anton 5707: TRY
1.68 anton 5708: foo
1.69 anton 5709: RECOVER
5710: CASE
5711: myerror OF ... ( do something about it ) ENDOF
5712: throw \ pass other errors on
5713: ENDCASE
5714: ENDTRY
1.68 anton 5715: @end example
1.1 anton 5716:
1.69 anton 5717: @progstyle
5718: As usual, you should ensure that the stack depth is statically known at
5719: the end: either after the @code{throw} for passing on errors, or after
5720: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5721: selection construct for handling the error).
5722:
1.68 anton 5723: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5724: and you can provide an error message. @code{Abort} just produces an
5725: ``Aborted'' error.
1.1 anton 5726:
1.68 anton 5727: The problem with these words is that exception handlers cannot
5728: differentiate between different @code{abort"}s; they just look like
5729: @code{-2 throw} to them (the error message cannot be accessed by
5730: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5731: exception handlers.
1.44 crook 5732:
1.68 anton 5733: doc-abort"
1.26 crook 5734: doc-abort
1.29 crook 5735:
5736:
1.44 crook 5737:
1.29 crook 5738: @c -------------------------------------------------------------
1.47 crook 5739: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5740: @section Defining Words
5741: @cindex defining words
5742:
1.47 crook 5743: Defining words are used to extend Forth by creating new entries in the dictionary.
5744:
1.29 crook 5745: @menu
1.67 anton 5746: * CREATE::
1.44 crook 5747: * Variables:: Variables and user variables
1.67 anton 5748: * Constants::
1.44 crook 5749: * Values:: Initialised variables
1.67 anton 5750: * Colon Definitions::
1.44 crook 5751: * Anonymous Definitions:: Definitions without names
1.69 anton 5752: * Supplying names:: Passing definition names as strings
1.67 anton 5753: * User-defined Defining Words::
1.44 crook 5754: * Deferred words:: Allow forward references
1.67 anton 5755: * Aliases::
1.29 crook 5756: @end menu
5757:
1.44 crook 5758: @node CREATE, Variables, Defining Words, Defining Words
5759: @subsection @code{CREATE}
1.29 crook 5760: @cindex simple defining words
5761: @cindex defining words, simple
5762:
5763: Defining words are used to create new entries in the dictionary. The
5764: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5765: this:
5766:
5767: @example
5768: CREATE new-word1
5769: @end example
5770:
1.69 anton 5771: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5772: input stream (@code{new-word1} in our example). It generates a
5773: dictionary entry for @code{new-word1}. When @code{new-word1} is
5774: executed, all that it does is leave an address on the stack. The address
5775: represents the value of the data space pointer (@code{HERE}) at the time
5776: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5777: associating a name with the address of a region of memory.
1.29 crook 5778:
1.34 anton 5779: doc-create
5780:
1.69 anton 5781: Note that in ANS Forth guarantees only for @code{create} that its body
5782: is in dictionary data space (i.e., where @code{here}, @code{allot}
5783: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5784: @code{create}d words can be modified with @code{does>}
5785: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5786: can only be applied to @code{create}d words.
5787:
1.29 crook 5788: By extending this example to reserve some memory in data space, we end
1.69 anton 5789: up with something like a @i{variable}. Here are two different ways to do
5790: it:
1.29 crook 5791:
5792: @example
5793: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5794: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5795: @end example
5796:
5797: The variable can be examined and modified using @code{@@} (``fetch'') and
5798: @code{!} (``store'') like this:
5799:
5800: @example
5801: new-word2 @@ . \ get address, fetch from it and display
5802: 1234 new-word2 ! \ new value, get address, store to it
5803: @end example
5804:
1.44 crook 5805: @cindex arrays
5806: A similar mechanism can be used to create arrays. For example, an
5807: 80-character text input buffer:
1.29 crook 5808:
5809: @example
1.44 crook 5810: CREATE text-buf 80 chars allot
5811:
5812: text-buf 0 chars c@@ \ the 1st character (offset 0)
5813: text-buf 3 chars c@@ \ the 4th character (offset 3)
5814: @end example
1.29 crook 5815:
1.44 crook 5816: You can build arbitrarily complex data structures by allocating
1.49 anton 5817: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5818: learn about some Gforth tools that make it easier,
1.49 anton 5819: @xref{Structures}.
1.44 crook 5820:
5821:
5822: @node Variables, Constants, CREATE, Defining Words
5823: @subsection Variables
5824: @cindex variables
5825:
5826: The previous section showed how a sequence of commands could be used to
5827: generate a variable. As a final refinement, the whole code sequence can
5828: be wrapped up in a defining word (pre-empting the subject of the next
5829: section), making it easier to create new variables:
5830:
5831: @example
5832: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5833: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5834:
5835: myvariableX foo \ variable foo starts off with an unknown value
5836: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5837:
5838: 45 3 * foo ! \ set foo to 135
5839: 1234 joe ! \ set joe to 1234
5840: 3 joe +! \ increment joe by 3.. to 1237
5841: @end example
5842:
5843: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5844: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5845: guarantee that a @code{Variable} is initialised when it is created
5846: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5847: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5848: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5849: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5850: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5851: store a boolean, you can use @code{on} and @code{off} to toggle its
5852: state.
1.29 crook 5853:
1.34 anton 5854: doc-variable
5855: doc-2variable
5856: doc-fvariable
5857:
1.29 crook 5858: @cindex user variables
5859: @cindex user space
5860: The defining word @code{User} behaves in the same way as @code{Variable}.
5861: The difference is that it reserves space in @i{user (data) space} rather
5862: than normal data space. In a Forth system that has a multi-tasker, each
5863: task has its own set of user variables.
5864:
1.34 anton 5865: doc-user
1.67 anton 5866: @c doc-udp
5867: @c doc-uallot
1.34 anton 5868:
1.29 crook 5869: @comment TODO is that stuff about user variables strictly correct? Is it
5870: @comment just terminal tasks that have user variables?
5871: @comment should document tasker.fs (with some examples) elsewhere
5872: @comment in this manual, then expand on user space and user variables.
5873:
1.44 crook 5874: @node Constants, Values, Variables, Defining Words
5875: @subsection Constants
5876: @cindex constants
5877:
5878: @code{Constant} allows you to declare a fixed value and refer to it by
5879: name. For example:
1.29 crook 5880:
5881: @example
5882: 12 Constant INCHES-PER-FOOT
5883: 3E+08 fconstant SPEED-O-LIGHT
5884: @end example
5885:
5886: A @code{Variable} can be both read and written, so its run-time
5887: behaviour is to supply an address through which its current value can be
5888: manipulated. In contrast, the value of a @code{Constant} cannot be
5889: changed once it has been declared@footnote{Well, often it can be -- but
5890: not in a Standard, portable way. It's safer to use a @code{Value} (read
5891: on).} so it's not necessary to supply the address -- it is more
5892: efficient to return the value of the constant directly. That's exactly
5893: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5894: the top of the stack (You can find one
5895: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5896:
1.69 anton 5897: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5898: double and floating-point constants, respectively.
5899:
1.34 anton 5900: doc-constant
5901: doc-2constant
5902: doc-fconstant
5903:
5904: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5905: @c nac-> How could that not be true in an ANS Forth? You can't define a
5906: @c constant, use it and then delete the definition of the constant..
1.69 anton 5907:
5908: @c anton->An ANS Forth system can compile a constant to a literal; On
5909: @c decompilation you would see only the number, just as if it had been used
5910: @c in the first place. The word will stay, of course, but it will only be
5911: @c used by the text interpreter (no run-time duties, except when it is
5912: @c POSTPONEd or somesuch).
5913:
5914: @c nac:
1.44 crook 5915: @c I agree that it's rather deep, but IMO it is an important difference
5916: @c relative to other programming languages.. often it's annoying: it
5917: @c certainly changes my programming style relative to C.
5918:
1.69 anton 5919: @c anton: In what way?
5920:
1.29 crook 5921: Constants in Forth behave differently from their equivalents in other
5922: programming languages. In other languages, a constant (such as an EQU in
5923: assembler or a #define in C) only exists at compile-time; in the
5924: executable program the constant has been translated into an absolute
5925: number and, unless you are using a symbolic debugger, it's impossible to
5926: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5927: an entry in the header space and remains there after the code that uses
5928: it has been defined. In fact, it must remain in the dictionary since it
5929: has run-time duties to perform. For example:
1.29 crook 5930:
5931: @example
5932: 12 Constant INCHES-PER-FOOT
5933: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5934: @end example
5935:
5936: @cindex in-lining of constants
5937: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5938: associated with the constant @code{INCHES-PER-FOOT}. If you use
5939: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5940: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5941: attempt to optimise constants by in-lining them where they are used. You
5942: can force Gforth to in-line a constant like this:
5943:
5944: @example
5945: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5946: @end example
5947:
5948: If you use @code{see} to decompile @i{this} version of
5949: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5950: longer present. To understand how this works, read
5951: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5952:
5953: In-lining constants in this way might improve execution time
5954: fractionally, and can ensure that a constant is now only referenced at
5955: compile-time. However, the definition of the constant still remains in
5956: the dictionary. Some Forth compilers provide a mechanism for controlling
5957: a second dictionary for holding transient words such that this second
5958: dictionary can be deleted later in order to recover memory
5959: space. However, there is no standard way of doing this.
5960:
5961:
1.44 crook 5962: @node Values, Colon Definitions, Constants, Defining Words
5963: @subsection Values
5964: @cindex values
1.34 anton 5965:
1.69 anton 5966: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5967: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5968: (not in ANS Forth) you can access (and change) a @code{value} also with
5969: @code{>body}.
5970:
5971: Here are some
5972: examples:
1.29 crook 5973:
5974: @example
1.69 anton 5975: 12 Value APPLES \ Define APPLES with an initial value of 12
5976: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5977: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5978: APPLES \ puts 35 on the top of the stack.
1.29 crook 5979: @end example
5980:
1.44 crook 5981: doc-value
5982: doc-to
1.29 crook 5983:
1.35 anton 5984:
1.69 anton 5985:
1.44 crook 5986: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5987: @subsection Colon Definitions
5988: @cindex colon definitions
1.35 anton 5989:
5990: @example
1.44 crook 5991: : name ( ... -- ... )
5992: word1 word2 word3 ;
1.29 crook 5993: @end example
5994:
1.44 crook 5995: @noindent
5996: Creates a word called @code{name} that, upon execution, executes
5997: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 5998:
1.49 anton 5999: The explanation above is somewhat superficial. For simple examples of
6000: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6001: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6002: Compilation Semantics}.
1.29 crook 6003:
1.44 crook 6004: doc-:
6005: doc-;
1.1 anton 6006:
1.34 anton 6007:
1.69 anton 6008: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6009: @subsection Anonymous Definitions
6010: @cindex colon definitions
6011: @cindex defining words without name
1.34 anton 6012:
1.44 crook 6013: Sometimes you want to define an @dfn{anonymous word}; a word without a
6014: name. You can do this with:
1.1 anton 6015:
1.44 crook 6016: doc-:noname
1.1 anton 6017:
1.44 crook 6018: This leaves the execution token for the word on the stack after the
6019: closing @code{;}. Here's an example in which a deferred word is
6020: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6021:
1.29 crook 6022: @example
1.44 crook 6023: Defer deferred
6024: :noname ( ... -- ... )
6025: ... ;
6026: IS deferred
1.29 crook 6027: @end example
1.26 crook 6028:
1.44 crook 6029: @noindent
6030: Gforth provides an alternative way of doing this, using two separate
6031: words:
1.27 crook 6032:
1.44 crook 6033: doc-noname
6034: @cindex execution token of last defined word
1.116 anton 6035: doc-latestxt
1.1 anton 6036:
1.44 crook 6037: @noindent
6038: The previous example can be rewritten using @code{noname} and
1.116 anton 6039: @code{latestxt}:
1.1 anton 6040:
1.26 crook 6041: @example
1.44 crook 6042: Defer deferred
6043: noname : ( ... -- ... )
6044: ... ;
1.116 anton 6045: latestxt IS deferred
1.26 crook 6046: @end example
1.1 anton 6047:
1.29 crook 6048: @noindent
1.44 crook 6049: @code{noname} works with any defining word, not just @code{:}.
6050:
1.116 anton 6051: @code{latestxt} also works when the last word was not defined as
1.71 anton 6052: @code{noname}. It does not work for combined words, though. It also has
6053: the useful property that is is valid as soon as the header for a
6054: definition has been built. Thus:
1.44 crook 6055:
6056: @example
1.116 anton 6057: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6058: @end example
1.1 anton 6059:
1.44 crook 6060: @noindent
6061: prints 3 numbers; the last two are the same.
1.26 crook 6062:
1.69 anton 6063: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6064: @subsection Supplying the name of a defined word
6065: @cindex names for defined words
6066: @cindex defining words, name given in a string
6067:
6068: By default, a defining word takes the name for the defined word from the
6069: input stream. Sometimes you want to supply the name from a string. You
6070: can do this with:
6071:
6072: doc-nextname
6073:
6074: For example:
6075:
6076: @example
6077: s" foo" nextname create
6078: @end example
6079:
6080: @noindent
6081: is equivalent to:
6082:
6083: @example
6084: create foo
6085: @end example
6086:
6087: @noindent
6088: @code{nextname} works with any defining word.
6089:
1.1 anton 6090:
1.69 anton 6091: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6092: @subsection User-defined Defining Words
6093: @cindex user-defined defining words
6094: @cindex defining words, user-defined
1.1 anton 6095:
1.29 crook 6096: You can create a new defining word by wrapping defining-time code around
6097: an existing defining word and putting the sequence in a colon
1.69 anton 6098: definition.
6099:
6100: @c anton: This example is very complex and leads in a quite different
6101: @c direction from the CREATE-DOES> stuff that follows. It should probably
6102: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6103: @c subsection of Defining Words)
6104:
6105: For example, suppose that you have a word @code{stats} that
1.29 crook 6106: gathers statistics about colon definitions given the @i{xt} of the
6107: definition, and you want every colon definition in your application to
6108: make a call to @code{stats}. You can define and use a new version of
6109: @code{:} like this:
6110:
6111: @example
6112: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6113: ... ; \ other code
6114:
1.116 anton 6115: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6116:
6117: my: foo + - ;
6118: @end example
6119:
6120: When @code{foo} is defined using @code{my:} these steps occur:
6121:
6122: @itemize @bullet
6123: @item
6124: @code{my:} is executed.
6125: @item
6126: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6127: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6128: the input stream for a name, builds a dictionary header for the name
6129: @code{foo} and switches @code{state} from interpret to compile.
6130: @item
1.116 anton 6131: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6132: being defined -- @code{foo} -- onto the stack.
6133: @item
6134: The code that was produced by @code{postpone literal} is executed; this
6135: causes the value on the stack to be compiled as a literal in the code
6136: area of @code{foo}.
6137: @item
6138: The code @code{['] stats} compiles a literal into the definition of
6139: @code{my:}. When @code{compile,} is executed, that literal -- the
6140: execution token for @code{stats} -- is layed down in the code area of
6141: @code{foo} , following the literal@footnote{Strictly speaking, the
6142: mechanism that @code{compile,} uses to convert an @i{xt} into something
6143: in the code area is implementation-dependent. A threaded implementation
6144: might spit out the execution token directly whilst another
6145: implementation might spit out a native code sequence.}.
6146: @item
6147: At this point, the execution of @code{my:} is complete, and control
6148: returns to the text interpreter. The text interpreter is in compile
6149: state, so subsequent text @code{+ -} is compiled into the definition of
6150: @code{foo} and the @code{;} terminates the definition as always.
6151: @end itemize
6152:
6153: You can use @code{see} to decompile a word that was defined using
6154: @code{my:} and see how it is different from a normal @code{:}
6155: definition. For example:
6156:
6157: @example
6158: : bar + - ; \ like foo but using : rather than my:
6159: see bar
6160: : bar
6161: + - ;
6162: see foo
6163: : foo
6164: 107645672 stats + - ;
6165:
1.140 anton 6166: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6167: @end example
6168:
6169: You can use techniques like this to make new defining words in terms of
6170: @i{any} existing defining word.
1.1 anton 6171:
6172:
1.29 crook 6173: @cindex defining defining words
1.26 crook 6174: @cindex @code{CREATE} ... @code{DOES>}
6175: If you want the words defined with your defining words to behave
6176: differently from words defined with standard defining words, you can
6177: write your defining word like this:
1.1 anton 6178:
6179: @example
1.26 crook 6180: : def-word ( "name" -- )
1.29 crook 6181: CREATE @i{code1}
1.26 crook 6182: DOES> ( ... -- ... )
1.29 crook 6183: @i{code2} ;
1.26 crook 6184:
6185: def-word name
1.1 anton 6186: @end example
6187:
1.29 crook 6188: @cindex child words
6189: This fragment defines a @dfn{defining word} @code{def-word} and then
6190: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6191: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6192: is not executed at this time. The word @code{name} is sometimes called a
6193: @dfn{child} of @code{def-word}.
6194:
6195: When you execute @code{name}, the address of the body of @code{name} is
6196: put on the data stack and @i{code2} is executed (the address of the body
6197: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6198: @code{CREATE}, i.e., the address a @code{create}d word returns by
6199: default).
6200:
6201: @c anton:
6202: @c www.dictionary.com says:
6203: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6204: @c several generations of absence, usually caused by the chance
6205: @c recombination of genes. 2.An individual or a part that exhibits
6206: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6207: @c of previous behavior after a period of absence.
6208: @c
6209: @c Doesn't seem to fit.
1.29 crook 6210:
1.69 anton 6211: @c @cindex atavism in child words
1.33 anton 6212: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6213: similarly; they all have a common run-time behaviour determined by
6214: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6215: body of the child word. The structure of the data is common to all
6216: children of @code{def-word}, but the data values are specific -- and
6217: private -- to each child word. When a child word is executed, the
6218: address of its private data area is passed as a parameter on TOS to be
6219: used and manipulated@footnote{It is legitimate both to read and write to
6220: this data area.} by @i{code2}.
1.29 crook 6221:
6222: The two fragments of code that make up the defining words act (are
6223: executed) at two completely separate times:
1.1 anton 6224:
1.29 crook 6225: @itemize @bullet
6226: @item
6227: At @i{define time}, the defining word executes @i{code1} to generate a
6228: child word
6229: @item
6230: At @i{child execution time}, when a child word is invoked, @i{code2}
6231: is executed, using parameters (data) that are private and specific to
6232: the child word.
6233: @end itemize
6234:
1.44 crook 6235: Another way of understanding the behaviour of @code{def-word} and
6236: @code{name} is to say that, if you make the following definitions:
1.33 anton 6237: @example
6238: : def-word1 ( "name" -- )
6239: CREATE @i{code1} ;
6240:
6241: : action1 ( ... -- ... )
6242: @i{code2} ;
6243:
6244: def-word1 name1
6245: @end example
6246:
1.44 crook 6247: @noindent
6248: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6249:
1.29 crook 6250: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6251:
1.1 anton 6252: @example
1.29 crook 6253: : CONSTANT ( w "name" -- )
6254: CREATE ,
1.26 crook 6255: DOES> ( -- w )
6256: @@ ;
1.1 anton 6257: @end example
6258:
1.29 crook 6259: @comment There is a beautiful description of how this works and what
6260: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6261: @comment commentary on the Counting Fruits problem.
6262:
6263: When you create a constant with @code{5 CONSTANT five}, a set of
6264: define-time actions take place; first a new word @code{five} is created,
6265: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6266: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6267: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6268: no code of its own; it simply contains a data field and a pointer to the
6269: code that follows @code{DOES>} in its defining word. That makes words
6270: created in this way very compact.
6271:
6272: The final example in this section is intended to remind you that space
6273: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6274: both read and written by a Standard program@footnote{Exercise: use this
6275: example as a starting point for your own implementation of @code{Value}
6276: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6277: @code{[']}.}:
6278:
6279: @example
6280: : foo ( "name" -- )
6281: CREATE -1 ,
6282: DOES> ( -- )
1.33 anton 6283: @@ . ;
1.29 crook 6284:
6285: foo first-word
6286: foo second-word
6287:
6288: 123 ' first-word >BODY !
6289: @end example
6290:
6291: If @code{first-word} had been a @code{CREATE}d word, we could simply
6292: have executed it to get the address of its data field. However, since it
6293: was defined to have @code{DOES>} actions, its execution semantics are to
6294: perform those @code{DOES>} actions. To get the address of its data field
6295: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6296: translate the xt into the address of the data field. When you execute
6297: @code{first-word}, it will display @code{123}. When you execute
6298: @code{second-word} it will display @code{-1}.
1.26 crook 6299:
6300: @cindex stack effect of @code{DOES>}-parts
6301: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6302: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6303: the stack effect of the defined words, not the stack effect of the
6304: following code (the following code expects the address of the body on
6305: the top of stack, which is not reflected in the stack comment). This is
6306: the convention that I use and recommend (it clashes a bit with using
6307: locals declarations for stack effect specification, though).
1.1 anton 6308:
1.53 anton 6309: @menu
6310: * CREATE..DOES> applications::
6311: * CREATE..DOES> details::
1.63 anton 6312: * Advanced does> usage example::
1.91 anton 6313: * @code{Const-does>}::
1.53 anton 6314: @end menu
6315:
6316: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6317: @subsubsection Applications of @code{CREATE..DOES>}
6318: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6319:
1.26 crook 6320: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6321:
1.26 crook 6322: @cindex factoring similar colon definitions
6323: When you see a sequence of code occurring several times, and you can
6324: identify a meaning, you will factor it out as a colon definition. When
6325: you see similar colon definitions, you can factor them using
6326: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6327: that look very similar:
1.1 anton 6328: @example
1.26 crook 6329: : ori, ( reg-target reg-source n -- )
6330: 0 asm-reg-reg-imm ;
6331: : andi, ( reg-target reg-source n -- )
6332: 1 asm-reg-reg-imm ;
1.1 anton 6333: @end example
6334:
1.26 crook 6335: @noindent
6336: This could be factored with:
6337: @example
6338: : reg-reg-imm ( op-code -- )
6339: CREATE ,
6340: DOES> ( reg-target reg-source n -- )
6341: @@ asm-reg-reg-imm ;
6342:
6343: 0 reg-reg-imm ori,
6344: 1 reg-reg-imm andi,
6345: @end example
1.1 anton 6346:
1.26 crook 6347: @cindex currying
6348: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6349: supply a part of the parameters for a word (known as @dfn{currying} in
6350: the functional language community). E.g., @code{+} needs two
6351: parameters. Creating versions of @code{+} with one parameter fixed can
6352: be done like this:
1.82 anton 6353:
1.1 anton 6354: @example
1.82 anton 6355: : curry+ ( n1 "name" -- )
1.26 crook 6356: CREATE ,
6357: DOES> ( n2 -- n1+n2 )
6358: @@ + ;
6359:
6360: 3 curry+ 3+
6361: -2 curry+ 2-
1.1 anton 6362: @end example
6363:
1.91 anton 6364:
1.63 anton 6365: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6366: @subsubsection The gory details of @code{CREATE..DOES>}
6367: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6368:
1.26 crook 6369: doc-does>
1.1 anton 6370:
1.26 crook 6371: @cindex @code{DOES>} in a separate definition
6372: This means that you need not use @code{CREATE} and @code{DOES>} in the
6373: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6374: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6375: @example
6376: : does1
6377: DOES> ( ... -- ... )
1.44 crook 6378: ... ;
6379:
6380: : does2
6381: DOES> ( ... -- ... )
6382: ... ;
6383:
6384: : def-word ( ... -- ... )
6385: create ...
6386: IF
6387: does1
6388: ELSE
6389: does2
6390: ENDIF ;
6391: @end example
6392:
6393: In this example, the selection of whether to use @code{does1} or
1.69 anton 6394: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6395: @code{CREATE}d.
6396:
6397: @cindex @code{DOES>} in interpretation state
6398: In a standard program you can apply a @code{DOES>}-part only if the last
6399: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6400: will override the behaviour of the last word defined in any case. In a
6401: standard program, you can use @code{DOES>} only in a colon
6402: definition. In Gforth, you can also use it in interpretation state, in a
6403: kind of one-shot mode; for example:
6404: @example
6405: CREATE name ( ... -- ... )
6406: @i{initialization}
6407: DOES>
6408: @i{code} ;
6409: @end example
6410:
6411: @noindent
6412: is equivalent to the standard:
6413: @example
6414: :noname
6415: DOES>
6416: @i{code} ;
6417: CREATE name EXECUTE ( ... -- ... )
6418: @i{initialization}
6419: @end example
6420:
1.53 anton 6421: doc->body
6422:
1.91 anton 6423: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6424: @subsubsection Advanced does> usage example
6425:
6426: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6427: for disassembling instructions, that follow a very repetetive scheme:
6428:
6429: @example
6430: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6431: @var{entry-num} cells @var{table} + !
6432: @end example
6433:
6434: Of course, this inspires the idea to factor out the commonalities to
6435: allow a definition like
6436:
6437: @example
6438: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6439: @end example
6440:
6441: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6442: correlated. Moreover, before I wrote the disassembler, there already
6443: existed code that defines instructions like this:
1.63 anton 6444:
6445: @example
6446: @var{entry-num} @var{inst-format} @var{inst-name}
6447: @end example
6448:
6449: This code comes from the assembler and resides in
6450: @file{arch/mips/insts.fs}.
6451:
6452: So I had to define the @var{inst-format} words that performed the scheme
6453: above when executed. At first I chose to use run-time code-generation:
6454:
6455: @example
6456: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6457: :noname Postpone @var{disasm-operands}
6458: name Postpone sliteral Postpone type Postpone ;
6459: swap cells @var{table} + ! ;
6460: @end example
6461:
6462: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6463:
1.63 anton 6464: An alternative would have been to write this using
6465: @code{create}/@code{does>}:
6466:
6467: @example
6468: : @var{inst-format} ( entry-num "name" -- )
6469: here name string, ( entry-num c-addr ) \ parse and save "name"
6470: noname create , ( entry-num )
1.116 anton 6471: latestxt swap cells @var{table} + !
1.63 anton 6472: does> ( addr w -- )
6473: \ disassemble instruction w at addr
6474: @@ >r
6475: @var{disasm-operands}
6476: r> count type ;
6477: @end example
6478:
6479: Somehow the first solution is simpler, mainly because it's simpler to
6480: shift a string from definition-time to use-time with @code{sliteral}
6481: than with @code{string,} and friends.
6482:
6483: I wrote a lot of words following this scheme and soon thought about
6484: factoring out the commonalities among them. Note that this uses a
6485: two-level defining word, i.e., a word that defines ordinary defining
6486: words.
6487:
6488: This time a solution involving @code{postpone} and friends seemed more
6489: difficult (try it as an exercise), so I decided to use a
6490: @code{create}/@code{does>} word; since I was already at it, I also used
6491: @code{create}/@code{does>} for the lower level (try using
6492: @code{postpone} etc. as an exercise), resulting in the following
6493: definition:
6494:
6495: @example
6496: : define-format ( disasm-xt table-xt -- )
6497: \ define an instruction format that uses disasm-xt for
6498: \ disassembling and enters the defined instructions into table
6499: \ table-xt
6500: create 2,
6501: does> ( u "inst" -- )
6502: \ defines an anonymous word for disassembling instruction inst,
6503: \ and enters it as u-th entry into table-xt
6504: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6505: noname create 2, \ define anonymous word
1.116 anton 6506: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6507: does> ( addr w -- )
6508: \ disassemble instruction w at addr
6509: 2@@ >r ( addr w disasm-xt R: c-addr )
6510: execute ( R: c-addr ) \ disassemble operands
6511: r> count type ; \ print name
6512: @end example
6513:
6514: Note that the tables here (in contrast to above) do the @code{cells +}
6515: by themselves (that's why you have to pass an xt). This word is used in
6516: the following way:
6517:
6518: @example
6519: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6520: @end example
6521:
1.71 anton 6522: As shown above, the defined instruction format is then used like this:
6523:
6524: @example
6525: @var{entry-num} @var{inst-format} @var{inst-name}
6526: @end example
6527:
1.63 anton 6528: In terms of currying, this kind of two-level defining word provides the
6529: parameters in three stages: first @var{disasm-operands} and @var{table},
6530: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6531: the instruction to be disassembled.
6532:
6533: Of course this did not quite fit all the instruction format names used
6534: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6535: the parameters into the right form.
6536:
6537: If you have trouble following this section, don't worry. First, this is
6538: involved and takes time (and probably some playing around) to
6539: understand; second, this is the first two-level
6540: @code{create}/@code{does>} word I have written in seventeen years of
6541: Forth; and if I did not have @file{insts.fs} to start with, I may well
6542: have elected to use just a one-level defining word (with some repeating
6543: of parameters when using the defining word). So it is not necessary to
6544: understand this, but it may improve your understanding of Forth.
1.44 crook 6545:
6546:
1.91 anton 6547: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6548: @subsubsection @code{Const-does>}
6549:
6550: A frequent use of @code{create}...@code{does>} is for transferring some
6551: values from definition-time to run-time. Gforth supports this use with
6552:
6553: doc-const-does>
6554:
6555: A typical use of this word is:
6556:
6557: @example
6558: : curry+ ( n1 "name" -- )
6559: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6560: + ;
6561:
6562: 3 curry+ 3+
6563: @end example
6564:
6565: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6566: definition to run-time.
6567:
6568: The advantages of using @code{const-does>} are:
6569:
6570: @itemize
6571:
6572: @item
6573: You don't have to deal with storing and retrieving the values, i.e.,
6574: your program becomes more writable and readable.
6575:
6576: @item
6577: When using @code{does>}, you have to introduce a @code{@@} that cannot
6578: be optimized away (because you could change the data using
6579: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6580:
6581: @end itemize
6582:
6583: An ANS Forth implementation of @code{const-does>} is available in
6584: @file{compat/const-does.fs}.
6585:
6586:
1.44 crook 6587: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6588: @subsection Deferred words
6589: @cindex deferred words
6590:
6591: The defining word @code{Defer} allows you to define a word by name
6592: without defining its behaviour; the definition of its behaviour is
6593: deferred. Here are two situation where this can be useful:
6594:
6595: @itemize @bullet
6596: @item
6597: Where you want to allow the behaviour of a word to be altered later, and
6598: for all precompiled references to the word to change when its behaviour
6599: is changed.
6600: @item
6601: For mutual recursion; @xref{Calls and returns}.
6602: @end itemize
6603:
6604: In the following example, @code{foo} always invokes the version of
6605: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6606: always invokes the version that prints ``@code{Hello}''. There is no way
6607: of getting @code{foo} to use the later version without re-ordering the
6608: source code and recompiling it.
6609:
6610: @example
6611: : greet ." Good morning" ;
6612: : foo ... greet ... ;
6613: : greet ." Hello" ;
6614: : bar ... greet ... ;
6615: @end example
6616:
6617: This problem can be solved by defining @code{greet} as a @code{Defer}red
6618: word. The behaviour of a @code{Defer}red word can be defined and
6619: redefined at any time by using @code{IS} to associate the xt of a
6620: previously-defined word with it. The previous example becomes:
6621:
6622: @example
1.69 anton 6623: Defer greet ( -- )
1.44 crook 6624: : foo ... greet ... ;
6625: : bar ... greet ... ;
1.69 anton 6626: : greet1 ( -- ) ." Good morning" ;
6627: : greet2 ( -- ) ." Hello" ;
1.132 anton 6628: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6629: @end example
6630:
1.69 anton 6631: @progstyle
6632: You should write a stack comment for every deferred word, and put only
6633: XTs into deferred words that conform to this stack effect. Otherwise
6634: it's too difficult to use the deferred word.
6635:
1.44 crook 6636: A deferred word can be used to improve the statistics-gathering example
6637: from @ref{User-defined Defining Words}; rather than edit the
6638: application's source code to change every @code{:} to a @code{my:}, do
6639: this:
6640:
6641: @example
6642: : real: : ; \ retain access to the original
6643: defer : \ redefine as a deferred word
1.132 anton 6644: ' my: IS : \ use special version of :
1.44 crook 6645: \
6646: \ load application here
6647: \
1.132 anton 6648: ' real: IS : \ go back to the original
1.44 crook 6649: @end example
6650:
6651:
1.132 anton 6652: One thing to note is that @code{IS} has special compilation semantics,
6653: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6654:
6655: @example
6656: : set-greet ( xt -- )
1.132 anton 6657: IS greet ;
1.44 crook 6658:
6659: ' greet1 set-greet
6660: @end example
6661:
1.132 anton 6662: In situations where @code{IS} does not fit, use @code{defer!} instead.
6663:
1.69 anton 6664: A deferred word can only inherit execution semantics from the xt
6665: (because that is all that an xt can represent -- for more discussion of
6666: this @pxref{Tokens for Words}); by default it will have default
6667: interpretation and compilation semantics deriving from this execution
6668: semantics. However, you can change the interpretation and compilation
6669: semantics of the deferred word in the usual ways:
1.44 crook 6670:
6671: @example
1.132 anton 6672: : bar .... ; immediate
1.44 crook 6673: Defer fred immediate
6674: Defer jim
6675:
1.132 anton 6676: ' bar IS jim \ jim has default semantics
6677: ' bar IS fred \ fred is immediate
1.44 crook 6678: @end example
6679:
6680: doc-defer
1.132 anton 6681: doc-defer!
1.44 crook 6682: doc-is
1.132 anton 6683: doc-defer@
6684: doc-action-of
1.44 crook 6685: @comment TODO document these: what's defers [is]
6686: doc-defers
6687:
6688: @c Use @code{words-deferred} to see a list of deferred words.
6689:
1.132 anton 6690: Definitions of these words (except @code{defers}) in ANS Forth are
6691: provided in @file{compat/defer.fs}.
1.44 crook 6692:
6693:
1.69 anton 6694: @node Aliases, , Deferred words, Defining Words
1.44 crook 6695: @subsection Aliases
6696: @cindex aliases
1.1 anton 6697:
1.44 crook 6698: The defining word @code{Alias} allows you to define a word by name that
6699: has the same behaviour as some other word. Here are two situation where
6700: this can be useful:
1.1 anton 6701:
1.44 crook 6702: @itemize @bullet
6703: @item
6704: When you want access to a word's definition from a different word list
6705: (for an example of this, see the definition of the @code{Root} word list
6706: in the Gforth source).
6707: @item
6708: When you want to create a synonym; a definition that can be known by
6709: either of two names (for example, @code{THEN} and @code{ENDIF} are
6710: aliases).
6711: @end itemize
1.1 anton 6712:
1.69 anton 6713: Like deferred words, an alias has default compilation and interpretation
6714: semantics at the beginning (not the modifications of the other word),
6715: but you can change them in the usual ways (@code{immediate},
6716: @code{compile-only}). For example:
1.1 anton 6717:
6718: @example
1.44 crook 6719: : foo ... ; immediate
6720:
6721: ' foo Alias bar \ bar is not an immediate word
6722: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6723: @end example
6724:
1.44 crook 6725: Words that are aliases have the same xt, different headers in the
6726: dictionary, and consequently different name tokens (@pxref{Tokens for
6727: Words}) and possibly different immediate flags. An alias can only have
6728: default or immediate compilation semantics; you can define aliases for
6729: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6730:
1.44 crook 6731: doc-alias
1.1 anton 6732:
6733:
1.47 crook 6734: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6735: @section Interpretation and Compilation Semantics
1.26 crook 6736: @cindex semantics, interpretation and compilation
1.1 anton 6737:
1.71 anton 6738: @c !! state and ' are used without explanation
6739: @c example for immediate/compile-only? or is the tutorial enough
6740:
1.26 crook 6741: @cindex interpretation semantics
1.71 anton 6742: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6743: interpreter does when it encounters the word in interpret state. It also
6744: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6745: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6746: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6747: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6748:
1.26 crook 6749: @cindex compilation semantics
1.71 anton 6750: The @dfn{compilation semantics} of a (named) word are what the text
6751: interpreter does when it encounters the word in compile state. It also
6752: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6753: compiles@footnote{In standard terminology, ``appends to the current
6754: definition''.} the compilation semantics of @i{word}.
1.1 anton 6755:
1.26 crook 6756: @cindex execution semantics
6757: The standard also talks about @dfn{execution semantics}. They are used
6758: only for defining the interpretation and compilation semantics of many
6759: words. By default, the interpretation semantics of a word are to
6760: @code{execute} its execution semantics, and the compilation semantics of
6761: a word are to @code{compile,} its execution semantics.@footnote{In
6762: standard terminology: The default interpretation semantics are its
6763: execution semantics; the default compilation semantics are to append its
6764: execution semantics to the execution semantics of the current
6765: definition.}
6766:
1.71 anton 6767: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6768: the text interpreter, ticked, or @code{postpone}d, so they have no
6769: interpretation or compilation semantics. Their behaviour is represented
6770: by their XT (@pxref{Tokens for Words}), and we call it execution
6771: semantics, too.
6772:
1.26 crook 6773: @comment TODO expand, make it co-operate with new sections on text interpreter.
6774:
6775: @cindex immediate words
6776: @cindex compile-only words
6777: You can change the semantics of the most-recently defined word:
6778:
1.44 crook 6779:
1.26 crook 6780: doc-immediate
6781: doc-compile-only
6782: doc-restrict
6783:
1.82 anton 6784: By convention, words with non-default compilation semantics (e.g.,
6785: immediate words) often have names surrounded with brackets (e.g.,
6786: @code{[']}, @pxref{Execution token}).
1.44 crook 6787:
1.26 crook 6788: Note that ticking (@code{'}) a compile-only word gives an error
6789: (``Interpreting a compile-only word'').
1.1 anton 6790:
1.47 crook 6791: @menu
1.67 anton 6792: * Combined words::
1.47 crook 6793: @end menu
1.44 crook 6794:
1.71 anton 6795:
1.48 anton 6796: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6797: @subsection Combined Words
6798: @cindex combined words
6799:
6800: Gforth allows you to define @dfn{combined words} -- words that have an
6801: arbitrary combination of interpretation and compilation semantics.
6802:
1.26 crook 6803: doc-interpret/compile:
1.1 anton 6804:
1.26 crook 6805: This feature was introduced for implementing @code{TO} and @code{S"}. I
6806: recommend that you do not define such words, as cute as they may be:
6807: they make it hard to get at both parts of the word in some contexts.
6808: E.g., assume you want to get an execution token for the compilation
6809: part. Instead, define two words, one that embodies the interpretation
6810: part, and one that embodies the compilation part. Once you have done
6811: that, you can define a combined word with @code{interpret/compile:} for
6812: the convenience of your users.
1.1 anton 6813:
1.26 crook 6814: You might try to use this feature to provide an optimizing
6815: implementation of the default compilation semantics of a word. For
6816: example, by defining:
1.1 anton 6817: @example
1.26 crook 6818: :noname
6819: foo bar ;
6820: :noname
6821: POSTPONE foo POSTPONE bar ;
1.29 crook 6822: interpret/compile: opti-foobar
1.1 anton 6823: @end example
1.26 crook 6824:
1.23 crook 6825: @noindent
1.26 crook 6826: as an optimizing version of:
6827:
1.1 anton 6828: @example
1.26 crook 6829: : foobar
6830: foo bar ;
1.1 anton 6831: @end example
6832:
1.26 crook 6833: Unfortunately, this does not work correctly with @code{[compile]},
6834: because @code{[compile]} assumes that the compilation semantics of all
6835: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6836: opti-foobar} would compile compilation semantics, whereas
6837: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6838:
1.26 crook 6839: @cindex state-smart words (are a bad idea)
1.82 anton 6840: @anchor{state-smartness}
1.29 crook 6841: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6842: by @code{interpret/compile:} (words are state-smart if they check
6843: @code{STATE} during execution). E.g., they would try to code
6844: @code{foobar} like this:
1.1 anton 6845:
1.26 crook 6846: @example
6847: : foobar
6848: STATE @@
6849: IF ( compilation state )
6850: POSTPONE foo POSTPONE bar
6851: ELSE
6852: foo bar
6853: ENDIF ; immediate
6854: @end example
1.1 anton 6855:
1.26 crook 6856: Although this works if @code{foobar} is only processed by the text
6857: interpreter, it does not work in other contexts (like @code{'} or
6858: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6859: for a state-smart word, not for the interpretation semantics of the
6860: original @code{foobar}; when you execute this execution token (directly
6861: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6862: state, the result will not be what you expected (i.e., it will not
6863: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6864: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6865: M. Anton Ertl,
6866: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6867: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6868:
1.26 crook 6869: @cindex defining words with arbitrary semantics combinations
6870: It is also possible to write defining words that define words with
6871: arbitrary combinations of interpretation and compilation semantics. In
6872: general, they look like this:
1.1 anton 6873:
1.26 crook 6874: @example
6875: : def-word
6876: create-interpret/compile
1.29 crook 6877: @i{code1}
1.26 crook 6878: interpretation>
1.29 crook 6879: @i{code2}
1.26 crook 6880: <interpretation
6881: compilation>
1.29 crook 6882: @i{code3}
1.26 crook 6883: <compilation ;
6884: @end example
1.1 anton 6885:
1.29 crook 6886: For a @i{word} defined with @code{def-word}, the interpretation
6887: semantics are to push the address of the body of @i{word} and perform
6888: @i{code2}, and the compilation semantics are to push the address of
6889: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6890: can also be defined like this (except that the defined constants don't
6891: behave correctly when @code{[compile]}d):
1.1 anton 6892:
1.26 crook 6893: @example
6894: : constant ( n "name" -- )
6895: create-interpret/compile
6896: ,
6897: interpretation> ( -- n )
6898: @@
6899: <interpretation
6900: compilation> ( compilation. -- ; run-time. -- n )
6901: @@ postpone literal
6902: <compilation ;
6903: @end example
1.1 anton 6904:
1.44 crook 6905:
1.26 crook 6906: doc-create-interpret/compile
6907: doc-interpretation>
6908: doc-<interpretation
6909: doc-compilation>
6910: doc-<compilation
1.1 anton 6911:
1.44 crook 6912:
1.29 crook 6913: Words defined with @code{interpret/compile:} and
1.26 crook 6914: @code{create-interpret/compile} have an extended header structure that
6915: differs from other words; however, unless you try to access them with
6916: plain address arithmetic, you should not notice this. Words for
6917: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6918: @code{'} @i{word} @code{>body} also gives you the body of a word created
6919: with @code{create-interpret/compile}.
1.1 anton 6920:
1.44 crook 6921:
1.47 crook 6922: @c -------------------------------------------------------------
1.81 anton 6923: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6924: @section Tokens for Words
6925: @cindex tokens for words
6926:
6927: This section describes the creation and use of tokens that represent
6928: words.
6929:
1.71 anton 6930: @menu
6931: * Execution token:: represents execution/interpretation semantics
6932: * Compilation token:: represents compilation semantics
6933: * Name token:: represents named words
6934: @end menu
1.47 crook 6935:
1.71 anton 6936: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6937: @subsection Execution token
1.47 crook 6938:
6939: @cindex xt
6940: @cindex execution token
1.71 anton 6941: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6942: You can use @code{execute} to invoke this behaviour.
1.47 crook 6943:
1.71 anton 6944: @cindex tick (')
6945: You can use @code{'} to get an execution token that represents the
6946: interpretation semantics of a named word:
1.47 crook 6947:
6948: @example
1.97 anton 6949: 5 ' . ( n xt )
6950: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6951: @end example
1.47 crook 6952:
1.71 anton 6953: doc-'
6954:
6955: @code{'} parses at run-time; there is also a word @code{[']} that parses
6956: when it is compiled, and compiles the resulting XT:
6957:
6958: @example
6959: : foo ['] . execute ;
6960: 5 foo
6961: : bar ' execute ; \ by contrast,
6962: 5 bar . \ ' parses "." when bar executes
6963: @end example
6964:
6965: doc-[']
6966:
6967: If you want the execution token of @i{word}, write @code{['] @i{word}}
6968: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6969: @code{'} and @code{[']} behave somewhat unusually by complaining about
6970: compile-only words (because these words have no interpretation
6971: semantics). You might get what you want by using @code{COMP' @i{word}
6972: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6973: token}).
6974:
1.116 anton 6975: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6976: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6977: for the only behaviour the word has (the execution semantics). For
1.116 anton 6978: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6979: would produce if the word was defined anonymously.
6980:
6981: @example
6982: :noname ." hello" ;
6983: execute
1.47 crook 6984: @end example
6985:
1.71 anton 6986: An XT occupies one cell and can be manipulated like any other cell.
6987:
1.47 crook 6988: @cindex code field address
6989: @cindex CFA
1.71 anton 6990: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6991: operations that produce or consume it). For old hands: In Gforth, the
6992: XT is implemented as a code field address (CFA).
6993:
6994: doc-execute
6995: doc-perform
6996:
6997: @node Compilation token, Name token, Execution token, Tokens for Words
6998: @subsection Compilation token
1.47 crook 6999:
7000: @cindex compilation token
1.71 anton 7001: @cindex CT (compilation token)
7002: Gforth represents the compilation semantics of a named word by a
1.47 crook 7003: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7004: @i{xt} is an execution token. The compilation semantics represented by
7005: the compilation token can be performed with @code{execute}, which
7006: consumes the whole compilation token, with an additional stack effect
7007: determined by the represented compilation semantics.
7008:
7009: At present, the @i{w} part of a compilation token is an execution token,
7010: and the @i{xt} part represents either @code{execute} or
7011: @code{compile,}@footnote{Depending upon the compilation semantics of the
7012: word. If the word has default compilation semantics, the @i{xt} will
7013: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7014: @i{xt} will represent @code{execute}.}. However, don't rely on that
7015: knowledge, unless necessary; future versions of Gforth may introduce
7016: unusual compilation tokens (e.g., a compilation token that represents
7017: the compilation semantics of a literal).
7018:
1.71 anton 7019: You can perform the compilation semantics represented by the compilation
7020: token with @code{execute}. You can compile the compilation semantics
7021: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7022: equivalent to @code{postpone @i{word}}.
7023:
7024: doc-[comp']
7025: doc-comp'
7026: doc-postpone,
7027:
7028: @node Name token, , Compilation token, Tokens for Words
7029: @subsection Name token
1.47 crook 7030:
7031: @cindex name token
1.116 anton 7032: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7033: token is an abstract data type that occurs as argument or result of the
7034: words below.
7035:
7036: @c !! put this elswhere?
1.47 crook 7037: @cindex name field address
7038: @cindex NFA
1.116 anton 7039: The closest thing to the nt in older Forth systems is the name field
7040: address (NFA), but there are significant differences: in older Forth
7041: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7042: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7043: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7044: is a link field in the structure identified by the name token, but
7045: searching usually uses a hash table external to these structures; the
7046: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7047: implemented as the address of that count field.
1.47 crook 7048:
7049: doc-find-name
1.116 anton 7050: doc-latest
7051: doc->name
1.47 crook 7052: doc-name>int
7053: doc-name?int
7054: doc-name>comp
7055: doc-name>string
1.109 anton 7056: doc-id.
7057: doc-.name
7058: doc-.id
1.47 crook 7059:
1.81 anton 7060: @c ----------------------------------------------------------
7061: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7062: @section Compiling words
7063: @cindex compiling words
7064: @cindex macros
7065:
7066: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7067: between compilation and run-time. E.g., you can run arbitrary code
7068: between defining words (or for computing data used by defining words
7069: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7070: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7071: running arbitrary code while compiling a colon definition (exception:
7072: you must not allot dictionary space).
7073:
7074: @menu
7075: * Literals:: Compiling data values
7076: * Macros:: Compiling words
7077: @end menu
7078:
7079: @node Literals, Macros, Compiling words, Compiling words
7080: @subsection Literals
7081: @cindex Literals
7082:
7083: The simplest and most frequent example is to compute a literal during
7084: compilation. E.g., the following definition prints an array of strings,
7085: one string per line:
7086:
7087: @example
7088: : .strings ( addr u -- ) \ gforth
7089: 2* cells bounds U+DO
7090: cr i 2@@ type
7091: 2 cells +LOOP ;
7092: @end example
1.81 anton 7093:
1.82 anton 7094: With a simple-minded compiler like Gforth's, this computes @code{2
7095: cells} on every loop iteration. You can compute this value once and for
7096: all at compile time and compile it into the definition like this:
7097:
7098: @example
7099: : .strings ( addr u -- ) \ gforth
7100: 2* cells bounds U+DO
7101: cr i 2@@ type
7102: [ 2 cells ] literal +LOOP ;
7103: @end example
7104:
7105: @code{[} switches the text interpreter to interpret state (you will get
7106: an @code{ok} prompt if you type this example interactively and insert a
7107: newline between @code{[} and @code{]}), so it performs the
7108: interpretation semantics of @code{2 cells}; this computes a number.
7109: @code{]} switches the text interpreter back into compile state. It then
7110: performs @code{Literal}'s compilation semantics, which are to compile
7111: this number into the current word. You can decompile the word with
7112: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7113:
1.82 anton 7114: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7115: *} in this way.
1.81 anton 7116:
1.82 anton 7117: doc-[
7118: doc-]
1.81 anton 7119: doc-literal
7120: doc-]L
1.82 anton 7121:
7122: There are also words for compiling other data types than single cells as
7123: literals:
7124:
1.81 anton 7125: doc-2literal
7126: doc-fliteral
1.82 anton 7127: doc-sliteral
7128:
7129: @cindex colon-sys, passing data across @code{:}
7130: @cindex @code{:}, passing data across
7131: You might be tempted to pass data from outside a colon definition to the
7132: inside on the data stack. This does not work, because @code{:} puhes a
7133: colon-sys, making stuff below unaccessible. E.g., this does not work:
7134:
7135: @example
7136: 5 : foo literal ; \ error: "unstructured"
7137: @end example
7138:
7139: Instead, you have to pass the value in some other way, e.g., through a
7140: variable:
7141:
7142: @example
7143: variable temp
7144: 5 temp !
7145: : foo [ temp @@ ] literal ;
7146: @end example
7147:
7148:
7149: @node Macros, , Literals, Compiling words
7150: @subsection Macros
7151: @cindex Macros
7152: @cindex compiling compilation semantics
7153:
7154: @code{Literal} and friends compile data values into the current
7155: definition. You can also write words that compile other words into the
7156: current definition. E.g.,
7157:
7158: @example
7159: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7160: POSTPONE + ;
7161:
7162: : foo ( n1 n2 -- n )
7163: [ compile-+ ] ;
7164: 1 2 foo .
7165: @end example
7166:
7167: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7168: What happens in this example? @code{Postpone} compiles the compilation
7169: semantics of @code{+} into @code{compile-+}; later the text interpreter
7170: executes @code{compile-+} and thus the compilation semantics of +, which
7171: compile (the execution semantics of) @code{+} into
7172: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7173: should only be executed in compile state, so this example is not
7174: guaranteed to work on all standard systems, but on any decent system it
7175: will work.}
7176:
7177: doc-postpone
7178: doc-[compile]
7179:
7180: Compiling words like @code{compile-+} are usually immediate (or similar)
7181: so you do not have to switch to interpret state to execute them;
7182: mopifying the last example accordingly produces:
7183:
7184: @example
7185: : [compile-+] ( compilation: --; interpretation: -- )
7186: \ compiled code: ( n1 n2 -- n )
7187: POSTPONE + ; immediate
7188:
7189: : foo ( n1 n2 -- n )
7190: [compile-+] ;
7191: 1 2 foo .
7192: @end example
7193:
7194: Immediate compiling words are similar to macros in other languages (in
7195: particular, Lisp). The important differences to macros in, e.g., C are:
7196:
7197: @itemize @bullet
7198:
7199: @item
7200: You use the same language for defining and processing macros, not a
7201: separate preprocessing language and processor.
7202:
7203: @item
7204: Consequently, the full power of Forth is available in macro definitions.
7205: E.g., you can perform arbitrarily complex computations, or generate
7206: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7207: Tutorial}). This power is very useful when writing a parser generators
7208: or other code-generating software.
7209:
7210: @item
7211: Macros defined using @code{postpone} etc. deal with the language at a
7212: higher level than strings; name binding happens at macro definition
7213: time, so you can avoid the pitfalls of name collisions that can happen
7214: in C macros. Of course, Forth is a liberal language and also allows to
7215: shoot yourself in the foot with text-interpreted macros like
7216:
7217: @example
7218: : [compile-+] s" +" evaluate ; immediate
7219: @end example
7220:
7221: Apart from binding the name at macro use time, using @code{evaluate}
7222: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7223: @end itemize
7224:
7225: You may want the macro to compile a number into a word. The word to do
7226: it is @code{literal}, but you have to @code{postpone} it, so its
7227: compilation semantics take effect when the macro is executed, not when
7228: it is compiled:
7229:
7230: @example
7231: : [compile-5] ( -- ) \ compiled code: ( -- n )
7232: 5 POSTPONE literal ; immediate
7233:
7234: : foo [compile-5] ;
7235: foo .
7236: @end example
7237:
7238: You may want to pass parameters to a macro, that the macro should
7239: compile into the current definition. If the parameter is a number, then
7240: you can use @code{postpone literal} (similar for other values).
7241:
7242: If you want to pass a word that is to be compiled, the usual way is to
7243: pass an execution token and @code{compile,} it:
7244:
7245: @example
7246: : twice1 ( xt -- ) \ compiled code: ... -- ...
7247: dup compile, compile, ;
7248:
7249: : 2+ ( n1 -- n2 )
7250: [ ' 1+ twice1 ] ;
7251: @end example
7252:
7253: doc-compile,
7254:
7255: An alternative available in Gforth, that allows you to pass compile-only
7256: words as parameters is to use the compilation token (@pxref{Compilation
7257: token}). The same example in this technique:
7258:
7259: @example
7260: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7261: 2dup 2>r execute 2r> execute ;
7262:
7263: : 2+ ( n1 -- n2 )
7264: [ comp' 1+ twice ] ;
7265: @end example
7266:
7267: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7268: works even if the executed compilation semantics has an effect on the
7269: data stack.
7270:
7271: You can also define complete definitions with these words; this provides
7272: an alternative to using @code{does>} (@pxref{User-defined Defining
7273: Words}). E.g., instead of
7274:
7275: @example
7276: : curry+ ( n1 "name" -- )
7277: CREATE ,
7278: DOES> ( n2 -- n1+n2 )
7279: @@ + ;
7280: @end example
7281:
7282: you could define
7283:
7284: @example
7285: : curry+ ( n1 "name" -- )
7286: \ name execution: ( n2 -- n1+n2 )
7287: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7288:
1.82 anton 7289: -3 curry+ 3-
7290: see 3-
7291: @end example
1.81 anton 7292:
1.82 anton 7293: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7294: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7295:
1.82 anton 7296: This way of writing defining words is sometimes more, sometimes less
7297: convenient than using @code{does>} (@pxref{Advanced does> usage
7298: example}). One advantage of this method is that it can be optimized
7299: better, because the compiler knows that the value compiled with
7300: @code{literal} is fixed, whereas the data associated with a
7301: @code{create}d word can be changed.
1.47 crook 7302:
1.26 crook 7303: @c ----------------------------------------------------------
1.111 anton 7304: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7305: @section The Text Interpreter
7306: @cindex interpreter - outer
7307: @cindex text interpreter
7308: @cindex outer interpreter
1.1 anton 7309:
1.34 anton 7310: @c Should we really describe all these ugly details? IMO the text
7311: @c interpreter should be much cleaner, but that may not be possible within
7312: @c ANS Forth. - anton
1.44 crook 7313: @c nac-> I wanted to explain how it works to show how you can exploit
7314: @c it in your own programs. When I was writing a cross-compiler, figuring out
7315: @c some of these gory details was very helpful to me. None of the textbooks
7316: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7317: @c seems to positively avoid going into too much detail for some of
7318: @c the internals.
1.34 anton 7319:
1.71 anton 7320: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7321: @c it is; for the ugly details, I would prefer another place. I wonder
7322: @c whether we should have a chapter before "Words" that describes some
7323: @c basic concepts referred to in words, and a chapter after "Words" that
7324: @c describes implementation details.
7325:
1.29 crook 7326: The text interpreter@footnote{This is an expanded version of the
7327: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7328: that processes input from the current input device. It is also called
7329: the outer interpreter, in contrast to the inner interpreter
7330: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7331: implementations.
1.27 crook 7332:
1.29 crook 7333: @cindex interpret state
7334: @cindex compile state
7335: The text interpreter operates in one of two states: @dfn{interpret
7336: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7337: aptly-named variable @code{state}.
1.29 crook 7338:
7339: This section starts by describing how the text interpreter behaves when
7340: it is in interpret state, processing input from the user input device --
7341: the keyboard. This is the mode that a Forth system is in after it starts
7342: up.
7343:
7344: @cindex input buffer
7345: @cindex terminal input buffer
7346: The text interpreter works from an area of memory called the @dfn{input
7347: buffer}@footnote{When the text interpreter is processing input from the
7348: keyboard, this area of memory is called the @dfn{terminal input buffer}
7349: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7350: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7351: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7352: leading spaces (called @dfn{delimiters}) then parses a string (a
7353: sequence of non-space characters) until it reaches either a space
7354: character or the end of the buffer. Having parsed a string, it makes two
7355: attempts to process it:
1.27 crook 7356:
1.29 crook 7357: @cindex dictionary
1.27 crook 7358: @itemize @bullet
7359: @item
1.29 crook 7360: It looks for the string in a @dfn{dictionary} of definitions. If the
7361: string is found, the string names a @dfn{definition} (also known as a
7362: @dfn{word}) and the dictionary search returns information that allows
7363: the text interpreter to perform the word's @dfn{interpretation
7364: semantics}. In most cases, this simply means that the word will be
7365: executed.
1.27 crook 7366: @item
7367: If the string is not found in the dictionary, the text interpreter
1.29 crook 7368: attempts to treat it as a number, using the rules described in
7369: @ref{Number Conversion}. If the string represents a legal number in the
7370: current radix, the number is pushed onto a parameter stack (the data
7371: stack for integers, the floating-point stack for floating-point
7372: numbers).
7373: @end itemize
7374:
7375: If both attempts fail, or if the word is found in the dictionary but has
7376: no interpretation semantics@footnote{This happens if the word was
7377: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7378: remainder of the input buffer, issues an error message and waits for
7379: more input. If one of the attempts succeeds, the text interpreter
7380: repeats the parsing process until the whole of the input buffer has been
7381: processed, at which point it prints the status message ``@code{ ok}''
7382: and waits for more input.
7383:
1.71 anton 7384: @c anton: this should be in the input stream subsection (or below it)
7385:
1.29 crook 7386: @cindex parse area
7387: The text interpreter keeps track of its position in the input buffer by
7388: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7389: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7390: of the input buffer. The region from offset @code{>IN @@} to the end of
7391: the input buffer is called the @dfn{parse area}@footnote{In other words,
7392: the text interpreter processes the contents of the input buffer by
7393: parsing strings from the parse area until the parse area is empty.}.
7394: This example shows how @code{>IN} changes as the text interpreter parses
7395: the input buffer:
7396:
7397: @example
7398: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7399: CR ." ->" TYPE ." <-" ; IMMEDIATE
7400:
7401: 1 2 3 remaining + remaining .
7402:
7403: : foo 1 2 3 remaining SWAP remaining ;
7404: @end example
7405:
7406: @noindent
7407: The result is:
7408:
7409: @example
7410: ->+ remaining .<-
7411: ->.<-5 ok
7412:
7413: ->SWAP remaining ;-<
7414: ->;<- ok
7415: @end example
7416:
7417: @cindex parsing words
7418: The value of @code{>IN} can also be modified by a word in the input
7419: buffer that is executed by the text interpreter. This means that a word
7420: can ``trick'' the text interpreter into either skipping a section of the
7421: input buffer@footnote{This is how parsing words work.} or into parsing a
7422: section twice. For example:
1.27 crook 7423:
1.29 crook 7424: @example
1.71 anton 7425: : lat ." <<foo>>" ;
7426: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7427: @end example
7428:
7429: @noindent
7430: When @code{flat} is executed, this output is produced@footnote{Exercise
7431: for the reader: what would happen if the @code{3} were replaced with
7432: @code{4}?}:
7433:
7434: @example
1.71 anton 7435: <<bar>><<foo>>
1.29 crook 7436: @end example
7437:
1.71 anton 7438: This technique can be used to work around some of the interoperability
7439: problems of parsing words. Of course, it's better to avoid parsing
7440: words where possible.
7441:
1.29 crook 7442: @noindent
7443: Two important notes about the behaviour of the text interpreter:
1.27 crook 7444:
7445: @itemize @bullet
7446: @item
7447: It processes each input string to completion before parsing additional
1.29 crook 7448: characters from the input buffer.
7449: @item
7450: It treats the input buffer as a read-only region (and so must your code).
7451: @end itemize
7452:
7453: @noindent
7454: When the text interpreter is in compile state, its behaviour changes in
7455: these ways:
7456:
7457: @itemize @bullet
7458: @item
7459: If a parsed string is found in the dictionary, the text interpreter will
7460: perform the word's @dfn{compilation semantics}. In most cases, this
7461: simply means that the execution semantics of the word will be appended
7462: to the current definition.
1.27 crook 7463: @item
1.29 crook 7464: When a number is encountered, it is compiled into the current definition
7465: (as a literal) rather than being pushed onto a parameter stack.
7466: @item
7467: If an error occurs, @code{state} is modified to put the text interpreter
7468: back into interpret state.
7469: @item
7470: Each time a line is entered from the keyboard, Gforth prints
7471: ``@code{ compiled}'' rather than `` @code{ok}''.
7472: @end itemize
7473:
7474: @cindex text interpreter - input sources
7475: When the text interpreter is using an input device other than the
7476: keyboard, its behaviour changes in these ways:
7477:
7478: @itemize @bullet
7479: @item
7480: When the parse area is empty, the text interpreter attempts to refill
7481: the input buffer from the input source. When the input source is
1.71 anton 7482: exhausted, the input source is set back to the previous input source.
1.29 crook 7483: @item
7484: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7485: time the parse area is emptied.
7486: @item
7487: If an error occurs, the input source is set back to the user input
7488: device.
1.27 crook 7489: @end itemize
1.21 crook 7490:
1.49 anton 7491: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7492:
1.26 crook 7493: doc->in
1.27 crook 7494: doc-source
7495:
1.26 crook 7496: doc-tib
7497: doc-#tib
1.1 anton 7498:
1.44 crook 7499:
1.26 crook 7500: @menu
1.67 anton 7501: * Input Sources::
7502: * Number Conversion::
7503: * Interpret/Compile states::
7504: * Interpreter Directives::
1.26 crook 7505: @end menu
1.1 anton 7506:
1.29 crook 7507: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7508: @subsection Input Sources
7509: @cindex input sources
7510: @cindex text interpreter - input sources
7511:
1.44 crook 7512: By default, the text interpreter processes input from the user input
1.29 crook 7513: device (the keyboard) when Forth starts up. The text interpreter can
7514: process input from any of these sources:
7515:
7516: @itemize @bullet
7517: @item
7518: The user input device -- the keyboard.
7519: @item
7520: A file, using the words described in @ref{Forth source files}.
7521: @item
7522: A block, using the words described in @ref{Blocks}.
7523: @item
7524: A text string, using @code{evaluate}.
7525: @end itemize
7526:
7527: A program can identify the current input device from the values of
7528: @code{source-id} and @code{blk}.
7529:
1.44 crook 7530:
1.29 crook 7531: doc-source-id
7532: doc-blk
7533:
7534: doc-save-input
7535: doc-restore-input
7536:
7537: doc-evaluate
1.111 anton 7538: doc-query
1.1 anton 7539:
1.29 crook 7540:
1.44 crook 7541:
1.29 crook 7542: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7543: @subsection Number Conversion
7544: @cindex number conversion
7545: @cindex double-cell numbers, input format
7546: @cindex input format for double-cell numbers
7547: @cindex single-cell numbers, input format
7548: @cindex input format for single-cell numbers
7549: @cindex floating-point numbers, input format
7550: @cindex input format for floating-point numbers
1.1 anton 7551:
1.29 crook 7552: This section describes the rules that the text interpreter uses when it
7553: tries to convert a string into a number.
1.1 anton 7554:
1.26 crook 7555: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7556: number base@footnote{For example, 0-9 when the number base is decimal or
7557: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7558:
1.26 crook 7559: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7560:
1.29 crook 7561: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7562: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7563:
1.26 crook 7564: Let * represent any number of instances of the previous character
7565: (including none).
1.1 anton 7566:
1.26 crook 7567: Let any other character represent itself.
1.1 anton 7568:
1.29 crook 7569: @noindent
1.26 crook 7570: Now, the conversion rules are:
1.21 crook 7571:
1.26 crook 7572: @itemize @bullet
7573: @item
7574: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7575: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7576: @item
7577: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7578: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7579: arithmetic. Examples are -45 -5681 -0
7580: @item
7581: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7582: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7583: (all three of these represent the same number).
1.26 crook 7584: @item
7585: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7586: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7587: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7588: -34.65 (all three of these represent the same number).
1.26 crook 7589: @item
1.29 crook 7590: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7591: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7592: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7593: number) +12.E-4
1.26 crook 7594: @end itemize
1.1 anton 7595:
1.26 crook 7596: By default, the number base used for integer number conversion is given
1.35 anton 7597: by the contents of the variable @code{base}. Note that a lot of
7598: confusion can result from unexpected values of @code{base}. If you
7599: change @code{base} anywhere, make sure to save the old value and restore
7600: it afterwards. In general I recommend keeping @code{base} decimal, and
7601: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7602:
1.29 crook 7603: doc-dpl
1.26 crook 7604: doc-base
7605: doc-hex
7606: doc-decimal
1.1 anton 7607:
1.26 crook 7608: @cindex '-prefix for character strings
7609: @cindex &-prefix for decimal numbers
1.133 anton 7610: @cindex #-prefix for decimal numbers
1.26 crook 7611: @cindex %-prefix for binary numbers
7612: @cindex $-prefix for hexadecimal numbers
1.133 anton 7613: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7614: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7615: prefix@footnote{Some Forth implementations provide a similar scheme by
7616: implementing @code{$} etc. as parsing words that process the subsequent
7617: number in the input stream and push it onto the stack. For example, see
7618: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7619: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7620: is required between the prefix and the number.} before the first digit
1.133 anton 7621: of an (integer) number. The following prefixes are supported:
1.1 anton 7622:
1.26 crook 7623: @itemize @bullet
7624: @item
1.35 anton 7625: @code{&} -- decimal
1.26 crook 7626: @item
1.133 anton 7627: @code{#} -- decimal
7628: @item
1.35 anton 7629: @code{%} -- binary
1.26 crook 7630: @item
1.35 anton 7631: @code{$} -- hexadecimal
1.26 crook 7632: @item
1.133 anton 7633: @code{0x} -- hexadecimal, if base<33.
7634: @item
7635: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7636: optional @code{'} may be present after the character.
1.26 crook 7637: @end itemize
1.1 anton 7638:
1.26 crook 7639: Here are some examples, with the equivalent decimal number shown after
7640: in braces:
1.1 anton 7641:
1.26 crook 7642: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7643: 'A (65),
7644: -'a' (-97),
1.26 crook 7645: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7646:
1.26 crook 7647: @cindex number conversion - traps for the unwary
1.29 crook 7648: @noindent
1.26 crook 7649: Number conversion has a number of traps for the unwary:
1.1 anton 7650:
1.26 crook 7651: @itemize @bullet
7652: @item
7653: You cannot determine the current number base using the code sequence
1.35 anton 7654: @code{base @@ .} -- the number base is always 10 in the current number
7655: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7656: @item
7657: If the number base is set to a value greater than 14 (for example,
7658: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7659: it to be intepreted as either a single-precision integer or a
7660: floating-point number (Gforth treats it as an integer). The ambiguity
7661: can be resolved by explicitly stating the sign of the mantissa and/or
7662: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7663: ambiguity arises; either representation will be treated as a
7664: floating-point number.
7665: @item
1.29 crook 7666: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7667: It is used to specify file types.
7668: @item
1.72 anton 7669: ANS Forth requires the @code{.} of a double-precision number to be the
7670: final character in the string. Gforth allows the @code{.} to be
7671: anywhere after the first digit.
1.26 crook 7672: @item
7673: The number conversion process does not check for overflow.
7674: @item
1.72 anton 7675: In an ANS Forth program @code{base} is required to be decimal when
7676: converting floating-point numbers. In Gforth, number conversion to
7677: floating-point numbers always uses base &10, irrespective of the value
7678: of @code{base}.
1.26 crook 7679: @end itemize
1.1 anton 7680:
1.49 anton 7681: You can read numbers into your programs with the words described in
7682: @ref{Input}.
1.1 anton 7683:
1.82 anton 7684: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7685: @subsection Interpret/Compile states
7686: @cindex Interpret/Compile states
1.1 anton 7687:
1.29 crook 7688: A standard program is not permitted to change @code{state}
7689: explicitly. However, it can change @code{state} implicitly, using the
7690: words @code{[} and @code{]}. When @code{[} is executed it switches
7691: @code{state} to interpret state, and therefore the text interpreter
7692: starts interpreting. When @code{]} is executed it switches @code{state}
7693: to compile state and therefore the text interpreter starts
1.44 crook 7694: compiling. The most common usage for these words is for switching into
7695: interpret state and back from within a colon definition; this technique
1.49 anton 7696: can be used to compile a literal (for an example, @pxref{Literals}) or
7697: for conditional compilation (for an example, @pxref{Interpreter
7698: Directives}).
1.44 crook 7699:
1.35 anton 7700:
7701: @c This is a bad example: It's non-standard, and it's not necessary.
7702: @c However, I can't think of a good example for switching into compile
7703: @c state when there is no current word (@code{state}-smart words are not a
7704: @c good reason). So maybe we should use an example for switching into
7705: @c interpret @code{state} in a colon def. - anton
1.44 crook 7706: @c nac-> I agree. I started out by putting in the example, then realised
7707: @c that it was non-ANS, so wrote more words around it. I hope this
7708: @c re-written version is acceptable to you. I do want to keep the example
7709: @c as it is helpful for showing what is and what is not portable, particularly
7710: @c where it outlaws a style in common use.
7711:
1.72 anton 7712: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7713: @c that, we can also show what's not. In any case, I have written a
7714: @c section Compiling Words which also deals with [ ].
1.35 anton 7715:
1.95 anton 7716: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7717:
1.95 anton 7718: @c @code{[} and @code{]} also give you the ability to switch into compile
7719: @c state and back, but we cannot think of any useful Standard application
7720: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7721:
7722: @c @example
7723: @c : AA ." this is A" ;
7724: @c : BB ." this is B" ;
7725: @c : CC ." this is C" ;
7726:
7727: @c create table ] aa bb cc [
7728:
7729: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7730: @c cells table + @@ execute ;
7731: @c @end example
7732:
7733: @c This example builds a jump table; @code{0 go} will display ``@code{this
7734: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7735: @c defining @code{table} like this:
7736:
7737: @c @example
7738: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7739: @c @end example
7740:
7741: @c The problem with this code is that the definition of @code{table} is not
7742: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7743: @c @i{may} work on systems where code space and data space co-incide, the
7744: @c Standard only allows data space to be assigned for a @code{CREATE}d
7745: @c word. In addition, the Standard only allows @code{@@} to access data
7746: @c space, whilst this example is using it to access code space. The only
7747: @c portable, Standard way to build this table is to build it in data space,
7748: @c like this:
7749:
7750: @c @example
7751: @c create table ' aa , ' bb , ' cc ,
7752: @c @end example
1.29 crook 7753:
1.95 anton 7754: @c doc-state
1.44 crook 7755:
1.29 crook 7756:
1.82 anton 7757: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7758: @subsection Interpreter Directives
7759: @cindex interpreter directives
1.72 anton 7760: @cindex conditional compilation
1.1 anton 7761:
1.29 crook 7762: These words are usually used in interpret state; typically to control
7763: which parts of a source file are processed by the text
1.26 crook 7764: interpreter. There are only a few ANS Forth Standard words, but Gforth
7765: supplements these with a rich set of immediate control structure words
7766: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7767: used in compile state (@pxref{Control Structures}). Typical usages:
7768:
7769: @example
1.72 anton 7770: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7771: .
7772: .
1.72 anton 7773: HAVE-ASSEMBLER [IF]
1.29 crook 7774: : ASSEMBLER-FEATURE
7775: ...
7776: ;
7777: [ENDIF]
7778: .
7779: .
7780: : SEE
7781: ... \ general-purpose SEE code
1.72 anton 7782: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7783: ... \ assembler-specific SEE code
7784: [ [ENDIF] ]
7785: ;
7786: @end example
1.1 anton 7787:
1.44 crook 7788:
1.26 crook 7789: doc-[IF]
7790: doc-[ELSE]
7791: doc-[THEN]
7792: doc-[ENDIF]
1.1 anton 7793:
1.26 crook 7794: doc-[IFDEF]
7795: doc-[IFUNDEF]
1.1 anton 7796:
1.26 crook 7797: doc-[?DO]
7798: doc-[DO]
7799: doc-[FOR]
7800: doc-[LOOP]
7801: doc-[+LOOP]
7802: doc-[NEXT]
1.1 anton 7803:
1.26 crook 7804: doc-[BEGIN]
7805: doc-[UNTIL]
7806: doc-[AGAIN]
7807: doc-[WHILE]
7808: doc-[REPEAT]
1.1 anton 7809:
1.27 crook 7810:
1.26 crook 7811: @c -------------------------------------------------------------
1.111 anton 7812: @node The Input Stream, Word Lists, The Text Interpreter, Words
7813: @section The Input Stream
7814: @cindex input stream
7815:
7816: @c !! integrate this better with the "Text Interpreter" section
7817: The text interpreter reads from the input stream, which can come from
7818: several sources (@pxref{Input Sources}). Some words, in particular
7819: defining words, but also words like @code{'}, read parameters from the
7820: input stream instead of from the stack.
7821:
7822: Such words are called parsing words, because they parse the input
7823: stream. Parsing words are hard to use in other words, because it is
7824: hard to pass program-generated parameters through the input stream.
7825: They also usually have an unintuitive combination of interpretation and
7826: compilation semantics when implemented naively, leading to various
7827: approaches that try to produce a more intuitive behaviour
7828: (@pxref{Combined words}).
7829:
7830: It should be obvious by now that parsing words are a bad idea. If you
7831: want to implement a parsing word for convenience, also provide a factor
7832: of the word that does not parse, but takes the parameters on the stack.
7833: To implement the parsing word on top if it, you can use the following
7834: words:
7835:
7836: @c anton: these belong in the input stream section
7837: doc-parse
1.138 anton 7838: doc-parse-name
1.111 anton 7839: doc-parse-word
7840: doc-name
7841: doc-word
7842: doc-\"-parse
7843: doc-refill
7844:
7845: Conversely, if you have the bad luck (or lack of foresight) to have to
7846: deal with parsing words without having such factors, how do you pass a
7847: string that is not in the input stream to it?
7848:
7849: doc-execute-parsing
7850:
7851: If you want to run a parsing word on a file, the following word should
7852: help:
7853:
7854: doc-execute-parsing-file
7855:
7856: @c -------------------------------------------------------------
7857: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7858: @section Word Lists
7859: @cindex word lists
1.32 anton 7860: @cindex header space
1.1 anton 7861:
1.36 anton 7862: A wordlist is a list of named words; you can add new words and look up
7863: words by name (and you can remove words in a restricted way with
7864: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7865:
7866: @cindex search order stack
7867: The text interpreter searches the wordlists present in the search order
7868: (a stack of wordlists), from the top to the bottom. Within each
7869: wordlist, the search starts conceptually at the newest word; i.e., if
7870: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7871:
1.26 crook 7872: @cindex compilation word list
1.36 anton 7873: New words are added to the @dfn{compilation wordlist} (aka current
7874: wordlist).
1.1 anton 7875:
1.36 anton 7876: @cindex wid
7877: A word list is identified by a cell-sized word list identifier (@i{wid})
7878: in much the same way as a file is identified by a file handle. The
7879: numerical value of the wid has no (portable) meaning, and might change
7880: from session to session.
1.1 anton 7881:
1.29 crook 7882: The ANS Forth ``Search order'' word set is intended to provide a set of
7883: low-level tools that allow various different schemes to be
1.74 anton 7884: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7885: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7886: Forth.
1.1 anton 7887:
1.27 crook 7888: @comment TODO: locals section refers to here, saying that every word list (aka
7889: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7890: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7891:
1.45 crook 7892: @comment TODO: document markers, reveal, tables, mappedwordlist
7893:
7894: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7895: @comment word from the source files, rather than some alias.
1.44 crook 7896:
1.26 crook 7897: doc-forth-wordlist
7898: doc-definitions
7899: doc-get-current
7900: doc-set-current
7901: doc-get-order
1.45 crook 7902: doc---gforthman-set-order
1.26 crook 7903: doc-wordlist
1.30 anton 7904: doc-table
1.79 anton 7905: doc->order
1.36 anton 7906: doc-previous
1.26 crook 7907: doc-also
1.45 crook 7908: doc---gforthman-forth
1.26 crook 7909: doc-only
1.45 crook 7910: doc---gforthman-order
1.15 anton 7911:
1.26 crook 7912: doc-find
7913: doc-search-wordlist
1.15 anton 7914:
1.26 crook 7915: doc-words
7916: doc-vlist
1.44 crook 7917: @c doc-words-deferred
1.1 anton 7918:
1.74 anton 7919: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7920: doc-root
7921: doc-vocabulary
7922: doc-seal
7923: doc-vocs
7924: doc-current
7925: doc-context
1.1 anton 7926:
1.44 crook 7927:
1.26 crook 7928: @menu
1.75 anton 7929: * Vocabularies::
1.67 anton 7930: * Why use word lists?::
1.75 anton 7931: * Word list example::
1.26 crook 7932: @end menu
7933:
1.75 anton 7934: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7935: @subsection Vocabularies
7936: @cindex Vocabularies, detailed explanation
7937:
7938: Here is an example of creating and using a new wordlist using ANS
7939: Forth words:
7940:
7941: @example
7942: wordlist constant my-new-words-wordlist
7943: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7944:
7945: \ add it to the search order
7946: also my-new-words
7947:
7948: \ alternatively, add it to the search order and make it
7949: \ the compilation word list
7950: also my-new-words definitions
7951: \ type "order" to see the problem
7952: @end example
7953:
7954: The problem with this example is that @code{order} has no way to
7955: associate the name @code{my-new-words} with the wid of the word list (in
7956: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7957: that has no associated name). There is no Standard way of associating a
7958: name with a wid.
7959:
7960: In Gforth, this example can be re-coded using @code{vocabulary}, which
7961: associates a name with a wid:
7962:
7963: @example
7964: vocabulary my-new-words
7965:
7966: \ add it to the search order
7967: also my-new-words
7968:
7969: \ alternatively, add it to the search order and make it
7970: \ the compilation word list
7971: my-new-words definitions
7972: \ type "order" to see that the problem is solved
7973: @end example
7974:
7975:
7976: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7977: @subsection Why use word lists?
7978: @cindex word lists - why use them?
7979:
1.74 anton 7980: Here are some reasons why people use wordlists:
1.26 crook 7981:
7982: @itemize @bullet
1.74 anton 7983:
7984: @c anton: Gforth's hashing implementation makes the search speed
7985: @c independent from the number of words. But it is linear with the number
7986: @c of wordlists that have to be searched, so in effect using more wordlists
7987: @c actually slows down compilation.
7988:
7989: @c @item
7990: @c To improve compilation speed by reducing the number of header space
7991: @c entries that must be searched. This is achieved by creating a new
7992: @c word list that contains all of the definitions that are used in the
7993: @c definition of a Forth system but which would not usually be used by
7994: @c programs running on that system. That word list would be on the search
7995: @c list when the Forth system was compiled but would be removed from the
7996: @c search list for normal operation. This can be a useful technique for
7997: @c low-performance systems (for example, 8-bit processors in embedded
7998: @c systems) but is unlikely to be necessary in high-performance desktop
7999: @c systems.
8000:
1.26 crook 8001: @item
8002: To prevent a set of words from being used outside the context in which
8003: they are valid. Two classic examples of this are an integrated editor
8004: (all of the edit commands are defined in a separate word list; the
8005: search order is set to the editor word list when the editor is invoked;
8006: the old search order is restored when the editor is terminated) and an
8007: integrated assembler (the op-codes for the machine are defined in a
8008: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8009:
8010: @item
8011: To organize the words of an application or library into a user-visible
8012: set (in @code{forth-wordlist} or some other common wordlist) and a set
8013: of helper words used just for the implementation (hidden in a separate
1.75 anton 8014: wordlist). This keeps @code{words}' output smaller, separates
8015: implementation and interface, and reduces the chance of name conflicts
8016: within the common wordlist.
1.74 anton 8017:
1.26 crook 8018: @item
8019: To prevent a name-space clash between multiple definitions with the same
8020: name. For example, when building a cross-compiler you might have a word
8021: @code{IF} that generates conditional code for your target system. By
8022: placing this definition in a different word list you can control whether
8023: the host system's @code{IF} or the target system's @code{IF} get used in
8024: any particular context by controlling the order of the word lists on the
8025: search order stack.
1.74 anton 8026:
1.26 crook 8027: @end itemize
1.1 anton 8028:
1.74 anton 8029: The downsides of using wordlists are:
8030:
8031: @itemize
8032:
8033: @item
8034: Debugging becomes more cumbersome.
8035:
8036: @item
8037: Name conflicts worked around with wordlists are still there, and you
8038: have to arrange the search order carefully to get the desired results;
8039: if you forget to do that, you get hard-to-find errors (as in any case
8040: where you read the code differently from the compiler; @code{see} can
1.75 anton 8041: help seeing which of several possible words the name resolves to in such
8042: cases). @code{See} displays just the name of the words, not what
8043: wordlist they belong to, so it might be misleading. Using unique names
8044: is a better approach to avoid name conflicts.
1.74 anton 8045:
8046: @item
8047: You have to explicitly undo any changes to the search order. In many
8048: cases it would be more convenient if this happened implicitly. Gforth
8049: currently does not provide such a feature, but it may do so in the
8050: future.
8051: @end itemize
8052:
8053:
1.75 anton 8054: @node Word list example, , Why use word lists?, Word Lists
8055: @subsection Word list example
8056: @cindex word lists - example
1.1 anton 8057:
1.74 anton 8058: The following example is from the
8059: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8060: garbage collector} and uses wordlists to separate public words from
8061: helper words:
8062:
8063: @example
8064: get-current ( wid )
8065: vocabulary garbage-collector also garbage-collector definitions
8066: ... \ define helper words
8067: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8068: ... \ define the public (i.e., API) words
8069: \ they can refer to the helper words
8070: previous \ restore original search order (helper words become invisible)
8071: @end example
8072:
1.26 crook 8073: @c -------------------------------------------------------------
8074: @node Environmental Queries, Files, Word Lists, Words
8075: @section Environmental Queries
8076: @cindex environmental queries
1.21 crook 8077:
1.26 crook 8078: ANS Forth introduced the idea of ``environmental queries'' as a way
8079: for a program running on a system to determine certain characteristics of the system.
8080: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8081:
1.32 anton 8082: The Standard requires that the header space used for environmental queries
8083: be distinct from the header space used for definitions.
1.21 crook 8084:
1.26 crook 8085: Typically, environmental queries are supported by creating a set of
1.29 crook 8086: definitions in a word list that is @i{only} used during environmental
1.26 crook 8087: queries; that is what Gforth does. There is no Standard way of adding
8088: definitions to the set of recognised environmental queries, but any
8089: implementation that supports the loading of optional word sets must have
8090: some mechanism for doing this (after loading the word set, the
8091: associated environmental query string must return @code{true}). In
8092: Gforth, the word list used to honour environmental queries can be
8093: manipulated just like any other word list.
1.21 crook 8094:
1.44 crook 8095:
1.26 crook 8096: doc-environment?
8097: doc-environment-wordlist
1.21 crook 8098:
1.26 crook 8099: doc-gforth
8100: doc-os-class
1.21 crook 8101:
1.44 crook 8102:
1.26 crook 8103: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8104: returning two items on the stack, querying it using @code{environment?}
8105: will return an additional item; the @code{true} flag that shows that the
8106: string was recognised.
1.21 crook 8107:
1.26 crook 8108: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8109:
1.26 crook 8110: Here are some examples of using environmental queries:
1.21 crook 8111:
1.26 crook 8112: @example
8113: s" address-unit-bits" environment? 0=
8114: [IF]
8115: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8116: [ELSE]
8117: drop \ ensure balanced stack effect
1.26 crook 8118: [THEN]
1.21 crook 8119:
1.75 anton 8120: \ this might occur in the prelude of a standard program that uses THROW
8121: s" exception" environment? [IF]
8122: 0= [IF]
8123: : throw abort" exception thrown" ;
8124: [THEN]
8125: [ELSE] \ we don't know, so make sure
8126: : throw abort" exception thrown" ;
8127: [THEN]
1.21 crook 8128:
1.26 crook 8129: s" gforth" environment? [IF] .( Gforth version ) TYPE
8130: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8131:
8132: \ a program using v*
8133: s" gforth" environment? [IF]
8134: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8135: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8136: >r swap 2swap swap 0e r> 0 ?DO
8137: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8138: LOOP
8139: 2drop 2drop ;
8140: [THEN]
8141: [ELSE] \
8142: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8143: ...
8144: [THEN]
1.26 crook 8145: @end example
1.21 crook 8146:
1.26 crook 8147: Here is an example of adding a definition to the environment word list:
1.21 crook 8148:
1.26 crook 8149: @example
8150: get-current environment-wordlist set-current
8151: true constant block
8152: true constant block-ext
8153: set-current
8154: @end example
1.21 crook 8155:
1.26 crook 8156: You can see what definitions are in the environment word list like this:
1.21 crook 8157:
1.26 crook 8158: @example
1.79 anton 8159: environment-wordlist >order words previous
1.26 crook 8160: @end example
1.21 crook 8161:
8162:
1.26 crook 8163: @c -------------------------------------------------------------
8164: @node Files, Blocks, Environmental Queries, Words
8165: @section Files
1.28 crook 8166: @cindex files
8167: @cindex I/O - file-handling
1.21 crook 8168:
1.26 crook 8169: Gforth provides facilities for accessing files that are stored in the
8170: host operating system's file-system. Files that are processed by Gforth
8171: can be divided into two categories:
1.21 crook 8172:
1.23 crook 8173: @itemize @bullet
8174: @item
1.29 crook 8175: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8176: @item
1.29 crook 8177: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8178: @end itemize
8179:
8180: @menu
1.48 anton 8181: * Forth source files::
8182: * General files::
8183: * Search Paths::
1.26 crook 8184: @end menu
8185:
8186: @c -------------------------------------------------------------
8187: @node Forth source files, General files, Files, Files
8188: @subsection Forth source files
8189: @cindex including files
8190: @cindex Forth source files
1.21 crook 8191:
1.26 crook 8192: The simplest way to interpret the contents of a file is to use one of
8193: these two formats:
1.21 crook 8194:
1.26 crook 8195: @example
8196: include mysource.fs
8197: s" mysource.fs" included
8198: @end example
1.21 crook 8199:
1.75 anton 8200: You usually want to include a file only if it is not included already
1.26 crook 8201: (by, say, another source file). In that case, you can use one of these
1.45 crook 8202: three formats:
1.21 crook 8203:
1.26 crook 8204: @example
8205: require mysource.fs
8206: needs mysource.fs
8207: s" mysource.fs" required
8208: @end example
1.21 crook 8209:
1.26 crook 8210: @cindex stack effect of included files
8211: @cindex including files, stack effect
1.45 crook 8212: It is good practice to write your source files such that interpreting them
8213: does not change the stack. Source files designed in this way can be used with
1.26 crook 8214: @code{required} and friends without complications. For example:
1.21 crook 8215:
1.26 crook 8216: @example
1.75 anton 8217: 1024 require foo.fs drop
1.26 crook 8218: @end example
1.21 crook 8219:
1.75 anton 8220: Here you want to pass the argument 1024 (e.g., a buffer size) to
8221: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8222: ), which allows its use with @code{require}. Of course with such
8223: parameters to required files, you have to ensure that the first
8224: @code{require} fits for all uses (i.e., @code{require} it early in the
8225: master load file).
1.44 crook 8226:
1.26 crook 8227: doc-include-file
8228: doc-included
1.28 crook 8229: doc-included?
1.26 crook 8230: doc-include
8231: doc-required
8232: doc-require
8233: doc-needs
1.75 anton 8234: @c doc-init-included-files @c internal
8235: doc-sourcefilename
8236: doc-sourceline#
1.44 crook 8237:
1.26 crook 8238: A definition in ANS Forth for @code{required} is provided in
8239: @file{compat/required.fs}.
1.21 crook 8240:
1.26 crook 8241: @c -------------------------------------------------------------
8242: @node General files, Search Paths, Forth source files, Files
8243: @subsection General files
8244: @cindex general files
8245: @cindex file-handling
1.21 crook 8246:
1.75 anton 8247: Files are opened/created by name and type. The following file access
8248: methods (FAMs) are recognised:
1.44 crook 8249:
1.75 anton 8250: @cindex fam (file access method)
1.26 crook 8251: doc-r/o
8252: doc-r/w
8253: doc-w/o
8254: doc-bin
1.1 anton 8255:
1.44 crook 8256:
1.26 crook 8257: When a file is opened/created, it returns a file identifier,
1.29 crook 8258: @i{wfileid} that is used for all other file commands. All file
8259: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8260: successful operation and an implementation-defined non-zero value in the
8261: case of an error.
1.21 crook 8262:
1.44 crook 8263:
1.26 crook 8264: doc-open-file
8265: doc-create-file
1.21 crook 8266:
1.26 crook 8267: doc-close-file
8268: doc-delete-file
8269: doc-rename-file
8270: doc-read-file
8271: doc-read-line
8272: doc-write-file
8273: doc-write-line
8274: doc-emit-file
8275: doc-flush-file
1.21 crook 8276:
1.26 crook 8277: doc-file-status
8278: doc-file-position
8279: doc-reposition-file
8280: doc-file-size
8281: doc-resize-file
1.21 crook 8282:
1.93 anton 8283: doc-slurp-file
8284: doc-slurp-fid
1.112 anton 8285: doc-stdin
8286: doc-stdout
8287: doc-stderr
1.44 crook 8288:
1.26 crook 8289: @c ---------------------------------------------------------
1.48 anton 8290: @node Search Paths, , General files, Files
1.26 crook 8291: @subsection Search Paths
8292: @cindex path for @code{included}
8293: @cindex file search path
8294: @cindex @code{include} search path
8295: @cindex search path for files
1.21 crook 8296:
1.26 crook 8297: If you specify an absolute filename (i.e., a filename starting with
8298: @file{/} or @file{~}, or with @file{:} in the second position (as in
8299: @samp{C:...})) for @code{included} and friends, that file is included
8300: just as you would expect.
1.21 crook 8301:
1.75 anton 8302: If the filename starts with @file{./}, this refers to the directory that
8303: the present file was @code{included} from. This allows files to include
8304: other files relative to their own position (irrespective of the current
8305: working directory or the absolute position). This feature is essential
8306: for libraries consisting of several files, where a file may include
8307: other files from the library. It corresponds to @code{#include "..."}
8308: in C. If the current input source is not a file, @file{.} refers to the
8309: directory of the innermost file being included, or, if there is no file
8310: being included, to the current working directory.
8311:
8312: For relative filenames (not starting with @file{./}), Gforth uses a
8313: search path similar to Forth's search order (@pxref{Word Lists}). It
8314: tries to find the given filename in the directories present in the path,
8315: and includes the first one it finds. There are separate search paths for
8316: Forth source files and general files. If the search path contains the
8317: directory @file{.}, this refers to the directory of the current file, or
8318: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8319:
1.26 crook 8320: Use @file{~+} to refer to the current working directory (as in the
8321: @code{bash}).
1.1 anton 8322:
1.75 anton 8323: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8324:
1.48 anton 8325: @menu
1.75 anton 8326: * Source Search Paths::
1.48 anton 8327: * General Search Paths::
8328: @end menu
8329:
1.26 crook 8330: @c ---------------------------------------------------------
1.75 anton 8331: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8332: @subsubsection Source Search Paths
8333: @cindex search path control, source files
1.5 anton 8334:
1.26 crook 8335: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8336: Gforth}). You can display it and change it using @code{fpath} in
8337: combination with the general path handling words.
1.5 anton 8338:
1.75 anton 8339: doc-fpath
8340: @c the functionality of the following words is easily available through
8341: @c fpath and the general path words. The may go away.
8342: @c doc-.fpath
8343: @c doc-fpath+
8344: @c doc-fpath=
8345: @c doc-open-fpath-file
1.44 crook 8346:
8347: @noindent
1.26 crook 8348: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8349:
1.26 crook 8350: @example
1.75 anton 8351: fpath path= /usr/lib/forth/|./
1.26 crook 8352: require timer.fs
8353: @end example
1.5 anton 8354:
1.75 anton 8355:
1.26 crook 8356: @c ---------------------------------------------------------
1.75 anton 8357: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8358: @subsubsection General Search Paths
1.75 anton 8359: @cindex search path control, source files
1.5 anton 8360:
1.26 crook 8361: Your application may need to search files in several directories, like
8362: @code{included} does. To facilitate this, Gforth allows you to define
8363: and use your own search paths, by providing generic equivalents of the
8364: Forth search path words:
1.5 anton 8365:
1.75 anton 8366: doc-open-path-file
8367: doc-path-allot
8368: doc-clear-path
8369: doc-also-path
1.26 crook 8370: doc-.path
8371: doc-path+
8372: doc-path=
1.5 anton 8373:
1.75 anton 8374: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8375:
1.75 anton 8376: Here's an example of creating an empty search path:
8377: @c
1.26 crook 8378: @example
1.75 anton 8379: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8380: @end example
1.5 anton 8381:
1.26 crook 8382: @c -------------------------------------------------------------
8383: @node Blocks, Other I/O, Files, Words
8384: @section Blocks
1.28 crook 8385: @cindex I/O - blocks
8386: @cindex blocks
8387:
8388: When you run Gforth on a modern desk-top computer, it runs under the
8389: control of an operating system which provides certain services. One of
8390: these services is @var{file services}, which allows Forth source code
8391: and data to be stored in files and read into Gforth (@pxref{Files}).
8392:
8393: Traditionally, Forth has been an important programming language on
8394: systems where it has interfaced directly to the underlying hardware with
8395: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8396: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8397:
8398: A block is a 1024-byte data area, which can be used to hold data or
8399: Forth source code. No structure is imposed on the contents of the
8400: block. A block is identified by its number; blocks are numbered
8401: contiguously from 1 to an implementation-defined maximum.
8402:
8403: A typical system that used blocks but no operating system might use a
8404: single floppy-disk drive for mass storage, with the disks formatted to
8405: provide 256-byte sectors. Blocks would be implemented by assigning the
8406: first four sectors of the disk to block 1, the second four sectors to
8407: block 2 and so on, up to the limit of the capacity of the disk. The disk
8408: would not contain any file system information, just the set of blocks.
8409:
1.29 crook 8410: @cindex blocks file
1.28 crook 8411: On systems that do provide file services, blocks are typically
1.29 crook 8412: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8413: file}. The size of the blocks file will be an exact multiple of 1024
8414: bytes, corresponding to the number of blocks it contains. This is the
8415: mechanism that Gforth uses.
8416:
1.29 crook 8417: @cindex @file{blocks.fb}
1.75 anton 8418: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8419: having specified a blocks file, Gforth defaults to the blocks file
8420: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8421: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8422:
1.29 crook 8423: @cindex block buffers
1.28 crook 8424: When you read and write blocks under program control, Gforth uses a
1.29 crook 8425: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8426: not used when you use @code{load} to interpret the contents of a block.
8427:
1.75 anton 8428: The behaviour of the block buffers is analagous to that of a cache.
8429: Each block buffer has three states:
1.28 crook 8430:
8431: @itemize @bullet
8432: @item
8433: Unassigned
8434: @item
8435: Assigned-clean
8436: @item
8437: Assigned-dirty
8438: @end itemize
8439:
1.29 crook 8440: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8441: block, the block (specified by its block number) must be assigned to a
8442: block buffer.
8443:
8444: The assignment of a block to a block buffer is performed by @code{block}
8445: or @code{buffer}. Use @code{block} when you wish to modify the existing
8446: contents of a block. Use @code{buffer} when you don't care about the
8447: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8448: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8449: with the particular block is already stored in a block buffer due to an
8450: earlier @code{block} command, @code{buffer} will return that block
8451: buffer and the existing contents of the block will be
8452: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8453: block buffer for the block.}.
1.28 crook 8454:
1.47 crook 8455: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8456: @code{buffer}, that block buffer becomes the @i{current block
8457: buffer}. Data may only be manipulated (read or written) within the
8458: current block buffer.
1.47 crook 8459:
8460: When the contents of the current block buffer has been modified it is
1.48 anton 8461: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8462: either abandon the changes (by doing nothing) or mark the block as
8463: changed (assigned-dirty), using @code{update}. Using @code{update} does
8464: not change the blocks file; it simply changes a block buffer's state to
8465: @i{assigned-dirty}. The block will be written implicitly when it's
8466: buffer is needed for another block, or explicitly by @code{flush} or
8467: @code{save-buffers}.
8468:
8469: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8470: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8471: @code{flush}.
1.28 crook 8472:
1.29 crook 8473: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8474: algorithm to assign a block buffer to a block. That means that any
8475: particular block can only be assigned to one specific block buffer,
1.29 crook 8476: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8477: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8478: the new block immediately. If it is @i{assigned-dirty} its current
8479: contents are written back to the blocks file on disk before it is
1.28 crook 8480: allocated to the new block.
8481:
8482: Although no structure is imposed on the contents of a block, it is
8483: traditional to display the contents as 16 lines each of 64 characters. A
8484: block provides a single, continuous stream of input (for example, it
8485: acts as a single parse area) -- there are no end-of-line characters
8486: within a block, and no end-of-file character at the end of a
8487: block. There are two consequences of this:
1.26 crook 8488:
1.28 crook 8489: @itemize @bullet
8490: @item
8491: The last character of one line wraps straight into the first character
8492: of the following line
8493: @item
8494: The word @code{\} -- comment to end of line -- requires special
8495: treatment; in the context of a block it causes all characters until the
8496: end of the current 64-character ``line'' to be ignored.
8497: @end itemize
8498:
8499: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8500: the current blocks file will be extended to the appropriate size and the
1.28 crook 8501: block buffer will be initialised with spaces.
8502:
1.47 crook 8503: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8504: for details) but doesn't encourage the use of blocks; the mechanism is
8505: only provided for backward compatibility -- ANS Forth requires blocks to
8506: be available when files are.
1.28 crook 8507:
8508: Common techniques that are used when working with blocks include:
8509:
8510: @itemize @bullet
8511: @item
8512: A screen editor that allows you to edit blocks without leaving the Forth
8513: environment.
8514: @item
8515: Shadow screens; where every code block has an associated block
8516: containing comments (for example: code in odd block numbers, comments in
8517: even block numbers). Typically, the block editor provides a convenient
8518: mechanism to toggle between code and comments.
8519: @item
8520: Load blocks; a single block (typically block 1) contains a number of
8521: @code{thru} commands which @code{load} the whole of the application.
8522: @end itemize
1.26 crook 8523:
1.29 crook 8524: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8525: integrated into a Forth programming environment.
1.26 crook 8526:
8527: @comment TODO what about errors on open-blocks?
1.44 crook 8528:
1.26 crook 8529: doc-open-blocks
8530: doc-use
1.75 anton 8531: doc-block-offset
1.26 crook 8532: doc-get-block-fid
8533: doc-block-position
1.28 crook 8534:
1.75 anton 8535: doc-list
1.28 crook 8536: doc-scr
8537:
1.45 crook 8538: doc---gforthman-block
1.28 crook 8539: doc-buffer
8540:
1.75 anton 8541: doc-empty-buffers
8542: doc-empty-buffer
1.26 crook 8543: doc-update
1.28 crook 8544: doc-updated?
1.26 crook 8545: doc-save-buffers
1.75 anton 8546: doc-save-buffer
1.26 crook 8547: doc-flush
1.28 crook 8548:
1.26 crook 8549: doc-load
8550: doc-thru
8551: doc-+load
8552: doc-+thru
1.45 crook 8553: doc---gforthman--->
1.26 crook 8554: doc-block-included
8555:
1.44 crook 8556:
1.26 crook 8557: @c -------------------------------------------------------------
1.126 pazsan 8558: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8559: @section Other I/O
1.28 crook 8560: @cindex I/O - keyboard and display
1.26 crook 8561:
8562: @menu
8563: * Simple numeric output:: Predefined formats
8564: * Formatted numeric output:: Formatted (pictured) output
8565: * String Formats:: How Forth stores strings in memory
1.67 anton 8566: * Displaying characters and strings:: Other stuff
1.26 crook 8567: * Input:: Input
1.112 anton 8568: * Pipes:: How to create your own pipes
1.26 crook 8569: @end menu
8570:
8571: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8572: @subsection Simple numeric output
1.28 crook 8573: @cindex numeric output - simple/free-format
1.5 anton 8574:
1.26 crook 8575: The simplest output functions are those that display numbers from the
8576: data or floating-point stacks. Floating-point output is always displayed
8577: using base 10. Numbers displayed from the data stack use the value stored
8578: in @code{base}.
1.5 anton 8579:
1.44 crook 8580:
1.26 crook 8581: doc-.
8582: doc-dec.
8583: doc-hex.
8584: doc-u.
8585: doc-.r
8586: doc-u.r
8587: doc-d.
8588: doc-ud.
8589: doc-d.r
8590: doc-ud.r
8591: doc-f.
8592: doc-fe.
8593: doc-fs.
1.111 anton 8594: doc-f.rdp
1.44 crook 8595:
1.26 crook 8596: Examples of printing the number 1234.5678E23 in the different floating-point output
8597: formats are shown below:
1.5 anton 8598:
8599: @example
1.26 crook 8600: f. 123456779999999000000000000.
8601: fe. 123.456779999999E24
8602: fs. 1.23456779999999E26
1.5 anton 8603: @end example
8604:
8605:
1.26 crook 8606: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8607: @subsection Formatted numeric output
1.28 crook 8608: @cindex formatted numeric output
1.26 crook 8609: @cindex pictured numeric output
1.28 crook 8610: @cindex numeric output - formatted
1.26 crook 8611:
1.29 crook 8612: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8613: output} for formatted printing of integers. In this technique, digits
8614: are extracted from the number (using the current output radix defined by
8615: @code{base}), converted to ASCII codes and appended to a string that is
8616: built in a scratch-pad area of memory (@pxref{core-idef,
8617: Implementation-defined options, Implementation-defined
8618: options}). Arbitrary characters can be appended to the string during the
8619: extraction process. The completed string is specified by an address
8620: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8621: under program control.
1.5 anton 8622:
1.75 anton 8623: All of the integer output words described in the previous section
8624: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8625: numeric output.
1.5 anton 8626:
1.47 crook 8627: Three important things to remember about pictured numeric output:
1.5 anton 8628:
1.26 crook 8629: @itemize @bullet
8630: @item
1.28 crook 8631: It always operates on double-precision numbers; to display a
1.49 anton 8632: single-precision number, convert it first (for ways of doing this
8633: @pxref{Double precision}).
1.26 crook 8634: @item
1.28 crook 8635: It always treats the double-precision number as though it were
8636: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8637: @item
8638: The string is built up from right to left; least significant digit first.
8639: @end itemize
1.5 anton 8640:
1.44 crook 8641:
1.26 crook 8642: doc-<#
1.47 crook 8643: doc-<<#
1.26 crook 8644: doc-#
8645: doc-#s
8646: doc-hold
8647: doc-sign
8648: doc-#>
1.47 crook 8649: doc-#>>
1.5 anton 8650:
1.26 crook 8651: doc-represent
1.111 anton 8652: doc-f>str-rdp
8653: doc-f>buf-rdp
1.5 anton 8654:
1.44 crook 8655:
8656: @noindent
1.26 crook 8657: Here are some examples of using pictured numeric output:
1.5 anton 8658:
8659: @example
1.26 crook 8660: : my-u. ( u -- )
8661: \ Simplest use of pns.. behaves like Standard u.
8662: 0 \ convert to unsigned double
1.75 anton 8663: <<# \ start conversion
1.26 crook 8664: #s \ convert all digits
8665: #> \ complete conversion
1.75 anton 8666: TYPE SPACE \ display, with trailing space
8667: #>> ; \ release hold area
1.5 anton 8668:
1.26 crook 8669: : cents-only ( u -- )
8670: 0 \ convert to unsigned double
1.75 anton 8671: <<# \ start conversion
1.26 crook 8672: # # \ convert two least-significant digits
8673: #> \ complete conversion, discard other digits
1.75 anton 8674: TYPE SPACE \ display, with trailing space
8675: #>> ; \ release hold area
1.5 anton 8676:
1.26 crook 8677: : dollars-and-cents ( u -- )
8678: 0 \ convert to unsigned double
1.75 anton 8679: <<# \ start conversion
1.26 crook 8680: # # \ convert two least-significant digits
8681: [char] . hold \ insert decimal point
8682: #s \ convert remaining digits
8683: [char] $ hold \ append currency symbol
8684: #> \ complete conversion
1.75 anton 8685: TYPE SPACE \ display, with trailing space
8686: #>> ; \ release hold area
1.5 anton 8687:
1.26 crook 8688: : my-. ( n -- )
8689: \ handling negatives.. behaves like Standard .
8690: s>d \ convert to signed double
8691: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8692: <<# \ start conversion
1.26 crook 8693: #s \ convert all digits
8694: rot sign \ get at sign byte, append "-" if needed
8695: #> \ complete conversion
1.75 anton 8696: TYPE SPACE \ display, with trailing space
8697: #>> ; \ release hold area
1.5 anton 8698:
1.26 crook 8699: : account. ( n -- )
1.75 anton 8700: \ accountants don't like minus signs, they use parentheses
1.26 crook 8701: \ for negative numbers
8702: s>d \ convert to signed double
8703: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8704: <<# \ start conversion
1.26 crook 8705: 2 pick \ get copy of sign byte
8706: 0< IF [char] ) hold THEN \ right-most character of output
8707: #s \ convert all digits
8708: rot \ get at sign byte
8709: 0< IF [char] ( hold THEN
8710: #> \ complete conversion
1.75 anton 8711: TYPE SPACE \ display, with trailing space
8712: #>> ; \ release hold area
8713:
1.5 anton 8714: @end example
8715:
1.26 crook 8716: Here are some examples of using these words:
1.5 anton 8717:
8718: @example
1.26 crook 8719: 1 my-u. 1
8720: hex -1 my-u. decimal FFFFFFFF
8721: 1 cents-only 01
8722: 1234 cents-only 34
8723: 2 dollars-and-cents $0.02
8724: 1234 dollars-and-cents $12.34
8725: 123 my-. 123
8726: -123 my. -123
8727: 123 account. 123
8728: -456 account. (456)
1.5 anton 8729: @end example
8730:
8731:
1.26 crook 8732: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8733: @subsection String Formats
1.27 crook 8734: @cindex strings - see character strings
8735: @cindex character strings - formats
1.28 crook 8736: @cindex I/O - see character strings
1.75 anton 8737: @cindex counted strings
8738:
8739: @c anton: this does not really belong here; maybe the memory section,
8740: @c or the principles chapter
1.26 crook 8741:
1.27 crook 8742: Forth commonly uses two different methods for representing character
8743: strings:
1.26 crook 8744:
8745: @itemize @bullet
8746: @item
8747: @cindex address of counted string
1.45 crook 8748: @cindex counted string
1.29 crook 8749: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8750: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8751: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8752: memory.
8753: @item
1.29 crook 8754: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8755: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8756: first byte of the string.
8757: @end itemize
8758:
8759: ANS Forth encourages the use of the second format when representing
1.75 anton 8760: strings.
1.26 crook 8761:
1.44 crook 8762:
1.26 crook 8763: doc-count
8764:
1.44 crook 8765:
1.49 anton 8766: For words that move, copy and search for strings see @ref{Memory
8767: Blocks}. For words that display characters and strings see
8768: @ref{Displaying characters and strings}.
1.26 crook 8769:
8770: @node Displaying characters and strings, Input, String Formats, Other I/O
8771: @subsection Displaying characters and strings
1.27 crook 8772: @cindex characters - compiling and displaying
8773: @cindex character strings - compiling and displaying
1.26 crook 8774:
8775: This section starts with a glossary of Forth words and ends with a set
8776: of examples.
8777:
1.44 crook 8778:
1.26 crook 8779: doc-bl
8780: doc-space
8781: doc-spaces
8782: doc-emit
8783: doc-toupper
8784: doc-."
8785: doc-.(
1.98 anton 8786: doc-.\"
1.26 crook 8787: doc-type
1.44 crook 8788: doc-typewhite
1.26 crook 8789: doc-cr
1.27 crook 8790: @cindex cursor control
1.26 crook 8791: doc-at-xy
8792: doc-page
8793: doc-s"
1.98 anton 8794: doc-s\"
1.26 crook 8795: doc-c"
8796: doc-char
8797: doc-[char]
8798:
1.44 crook 8799:
8800: @noindent
1.26 crook 8801: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8802:
8803: @example
1.26 crook 8804: .( text-1)
8805: : my-word
8806: ." text-2" cr
8807: .( text-3)
8808: ;
8809:
8810: ." text-4"
8811:
8812: : my-char
8813: [char] ALPHABET emit
8814: char emit
8815: ;
1.5 anton 8816: @end example
8817:
1.26 crook 8818: When you load this code into Gforth, the following output is generated:
1.5 anton 8819:
1.26 crook 8820: @example
1.30 anton 8821: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8822: @end example
1.5 anton 8823:
1.26 crook 8824: @itemize @bullet
8825: @item
8826: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8827: is an immediate word; it behaves in the same way whether it is used inside
8828: or outside a colon definition.
8829: @item
8830: Message @code{text-4} is displayed because of Gforth's added interpretation
8831: semantics for @code{."}.
8832: @item
1.29 crook 8833: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8834: performs the compilation semantics for @code{."} within the definition of
8835: @code{my-word}.
8836: @end itemize
1.5 anton 8837:
1.26 crook 8838: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8839:
1.26 crook 8840: @example
1.30 anton 8841: @kbd{my-word @key{RET}} text-2
1.26 crook 8842: ok
1.30 anton 8843: @kbd{my-char fred @key{RET}} Af ok
8844: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8845: @end example
1.5 anton 8846:
8847: @itemize @bullet
8848: @item
1.26 crook 8849: Message @code{text-2} is displayed because of the run-time behaviour of
8850: @code{."}.
8851: @item
8852: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8853: on the stack at run-time. @code{emit} always displays the character
8854: when @code{my-char} is executed.
8855: @item
8856: @code{char} parses a string at run-time and the second @code{emit} displays
8857: the first character of the string.
1.5 anton 8858: @item
1.26 crook 8859: If you type @code{see my-char} you can see that @code{[char]} discarded
8860: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8861: definition of @code{my-char}.
1.5 anton 8862: @end itemize
8863:
8864:
8865:
1.112 anton 8866: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8867: @subsection Input
8868: @cindex input
1.28 crook 8869: @cindex I/O - see input
8870: @cindex parsing a string
1.5 anton 8871:
1.49 anton 8872: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8873:
1.27 crook 8874: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8875: @comment then index them
1.27 crook 8876:
1.44 crook 8877:
1.27 crook 8878: doc-key
8879: doc-key?
1.45 crook 8880: doc-ekey
1.141 anton 8881: doc-ekey>char
1.45 crook 8882: doc-ekey?
1.141 anton 8883:
8884: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8885: you need the ANSI.SYS driver to get that behaviour). These are the
8886: keyboard events produced by various common keys:
8887:
8888: doc-k-left
8889: doc-k-right
8890: doc-k-up
8891: doc-k-down
8892: doc-k-home
8893: doc-k-end
8894: doc-k-prior
8895: doc-k-next
8896: doc-k-insert
8897: doc-k-delete
8898:
8899: The function keys (aka keypad keys) are:
8900:
8901: doc-k1
8902: doc-k2
8903: doc-k3
8904: doc-k4
8905: doc-k5
8906: doc-k6
8907: doc-k7
8908: doc-k8
8909: doc-k9
8910: doc-k10
8911: doc-k11
8912: doc-k12
8913:
8914: Note that K11 and K12 are not as widely available. The shifted
8915: function keys are also not very widely available:
8916:
8917: doc-s-k8
8918: doc-s-k1
8919: doc-s-k2
8920: doc-s-k3
8921: doc-s-k4
8922: doc-s-k5
8923: doc-s-k6
8924: doc-s-k7
8925: doc-s-k8
8926: doc-s-k9
8927: doc-s-k10
8928: doc-s-k11
8929: doc-s-k12
8930:
8931: Words for inputting one line from the keyboard:
8932:
8933: doc-accept
8934: doc-edit-line
8935:
8936: Conversion words:
8937:
1.143 anton 8938: doc-s>number?
8939: doc-s>unumber?
1.26 crook 8940: doc->number
8941: doc->float
1.143 anton 8942:
1.141 anton 8943:
1.27 crook 8944: @comment obsolescent words..
1.141 anton 8945: Obsolescent input and conversion words:
8946:
1.27 crook 8947: doc-convert
1.26 crook 8948: doc-expect
1.27 crook 8949: doc-span
1.5 anton 8950:
8951:
1.112 anton 8952: @node Pipes, , Input, Other I/O
8953: @subsection Pipes
8954: @cindex pipes, creating your own
8955:
8956: In addition to using Gforth in pipes created by other processes
8957: (@pxref{Gforth in pipes}), you can create your own pipe with
8958: @code{open-pipe}, and read from or write to it.
8959:
8960: doc-open-pipe
8961: doc-close-pipe
8962:
8963: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8964: you don't catch this exception, Gforth will catch it and exit, usually
8965: silently (@pxref{Gforth in pipes}). Since you probably do not want
8966: this, you should wrap a @code{catch} or @code{try} block around the code
8967: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8968: problem yourself, and then return to regular processing.
8969:
8970: doc-broken-pipe-error
8971:
8972:
1.121 anton 8973: @node OS command line arguments, Locals, Other I/O, Words
8974: @section OS command line arguments
8975: @cindex OS command line arguments
8976: @cindex command line arguments, OS
8977: @cindex arguments, OS command line
8978:
8979: The usual way to pass arguments to Gforth programs on the command line
8980: is via the @option{-e} option, e.g.
8981:
8982: @example
8983: gforth -e "123 456" foo.fs -e bye
8984: @end example
8985:
8986: However, you may want to interpret the command-line arguments directly.
8987: In that case, you can access the (image-specific) command-line arguments
1.123 anton 8988: through @code{next-arg}:
1.121 anton 8989:
1.123 anton 8990: doc-next-arg
1.121 anton 8991:
1.123 anton 8992: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 8993:
8994: @example
8995: : echo ( -- )
1.122 anton 8996: begin
1.123 anton 8997: next-arg 2dup 0 0 d<> while
8998: type space
8999: repeat
9000: 2drop ;
1.121 anton 9001:
9002: echo cr bye
9003: @end example
9004:
9005: This can be invoked with
9006:
9007: @example
9008: gforth echo.fs hello world
9009: @end example
1.123 anton 9010:
9011: and it will print
9012:
9013: @example
9014: hello world
9015: @end example
9016:
9017: The next lower level of dealing with the OS command line are the
9018: following words:
9019:
9020: doc-arg
9021: doc-shift-args
9022:
9023: Finally, at the lowest level Gforth provides the following words:
9024:
9025: doc-argc
9026: doc-argv
1.121 anton 9027:
1.78 anton 9028: @c -------------------------------------------------------------
1.126 pazsan 9029: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9030: @section Locals
9031: @cindex locals
9032:
9033: Local variables can make Forth programming more enjoyable and Forth
9034: programs easier to read. Unfortunately, the locals of ANS Forth are
9035: laden with restrictions. Therefore, we provide not only the ANS Forth
9036: locals wordset, but also our own, more powerful locals wordset (we
9037: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9038:
1.78 anton 9039: The ideas in this section have also been published in M. Anton Ertl,
9040: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9041: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9042:
9043: @menu
1.78 anton 9044: * Gforth locals::
9045: * ANS Forth locals::
1.5 anton 9046: @end menu
9047:
1.78 anton 9048: @node Gforth locals, ANS Forth locals, Locals, Locals
9049: @subsection Gforth locals
9050: @cindex Gforth locals
9051: @cindex locals, Gforth style
1.5 anton 9052:
1.78 anton 9053: Locals can be defined with
1.44 crook 9054:
1.78 anton 9055: @example
9056: @{ local1 local2 ... -- comment @}
9057: @end example
9058: or
9059: @example
9060: @{ local1 local2 ... @}
9061: @end example
1.5 anton 9062:
1.78 anton 9063: E.g.,
9064: @example
9065: : max @{ n1 n2 -- n3 @}
9066: n1 n2 > if
9067: n1
9068: else
9069: n2
9070: endif ;
9071: @end example
1.44 crook 9072:
1.78 anton 9073: The similarity of locals definitions with stack comments is intended. A
9074: locals definition often replaces the stack comment of a word. The order
9075: of the locals corresponds to the order in a stack comment and everything
9076: after the @code{--} is really a comment.
1.77 anton 9077:
1.78 anton 9078: This similarity has one disadvantage: It is too easy to confuse locals
9079: declarations with stack comments, causing bugs and making them hard to
9080: find. However, this problem can be avoided by appropriate coding
9081: conventions: Do not use both notations in the same program. If you do,
9082: they should be distinguished using additional means, e.g. by position.
1.77 anton 9083:
1.78 anton 9084: @cindex types of locals
9085: @cindex locals types
9086: The name of the local may be preceded by a type specifier, e.g.,
9087: @code{F:} for a floating point value:
1.5 anton 9088:
1.78 anton 9089: @example
9090: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9091: \ complex multiplication
9092: Ar Br f* Ai Bi f* f-
9093: Ar Bi f* Ai Br f* f+ ;
9094: @end example
1.44 crook 9095:
1.78 anton 9096: @cindex flavours of locals
9097: @cindex locals flavours
9098: @cindex value-flavoured locals
9099: @cindex variable-flavoured locals
9100: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9101: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9102: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9103: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9104: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9105: produces its address (which becomes invalid when the variable's scope is
9106: left). E.g., the standard word @code{emit} can be defined in terms of
9107: @code{type} like this:
1.5 anton 9108:
1.78 anton 9109: @example
9110: : emit @{ C^ char* -- @}
9111: char* 1 type ;
9112: @end example
1.5 anton 9113:
1.78 anton 9114: @cindex default type of locals
9115: @cindex locals, default type
9116: A local without type specifier is a @code{W:} local. Both flavours of
9117: locals are initialized with values from the data or FP stack.
1.44 crook 9118:
1.78 anton 9119: Currently there is no way to define locals with user-defined data
9120: structures, but we are working on it.
1.5 anton 9121:
1.78 anton 9122: Gforth allows defining locals everywhere in a colon definition. This
9123: poses the following questions:
1.5 anton 9124:
1.78 anton 9125: @menu
9126: * Where are locals visible by name?::
9127: * How long do locals live?::
9128: * Locals programming style::
9129: * Locals implementation::
9130: @end menu
1.44 crook 9131:
1.78 anton 9132: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9133: @subsubsection Where are locals visible by name?
9134: @cindex locals visibility
9135: @cindex visibility of locals
9136: @cindex scope of locals
1.5 anton 9137:
1.78 anton 9138: Basically, the answer is that locals are visible where you would expect
9139: it in block-structured languages, and sometimes a little longer. If you
9140: want to restrict the scope of a local, enclose its definition in
9141: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9142:
9143:
1.78 anton 9144: doc-scope
9145: doc-endscope
1.5 anton 9146:
9147:
1.78 anton 9148: These words behave like control structure words, so you can use them
9149: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9150: arbitrary ways.
1.77 anton 9151:
1.78 anton 9152: If you want a more exact answer to the visibility question, here's the
9153: basic principle: A local is visible in all places that can only be
9154: reached through the definition of the local@footnote{In compiler
9155: construction terminology, all places dominated by the definition of the
9156: local.}. In other words, it is not visible in places that can be reached
9157: without going through the definition of the local. E.g., locals defined
9158: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9159: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9160: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9161:
1.78 anton 9162: The reasoning behind this solution is: We want to have the locals
9163: visible as long as it is meaningful. The user can always make the
9164: visibility shorter by using explicit scoping. In a place that can
9165: only be reached through the definition of a local, the meaning of a
9166: local name is clear. In other places it is not: How is the local
9167: initialized at the control flow path that does not contain the
9168: definition? Which local is meant, if the same name is defined twice in
9169: two independent control flow paths?
1.77 anton 9170:
1.78 anton 9171: This should be enough detail for nearly all users, so you can skip the
9172: rest of this section. If you really must know all the gory details and
9173: options, read on.
1.77 anton 9174:
1.78 anton 9175: In order to implement this rule, the compiler has to know which places
9176: are unreachable. It knows this automatically after @code{AHEAD},
9177: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9178: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9179: compiler that the control flow never reaches that place. If
9180: @code{UNREACHABLE} is not used where it could, the only consequence is
9181: that the visibility of some locals is more limited than the rule above
9182: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9183: lie to the compiler), buggy code will be produced.
1.77 anton 9184:
1.5 anton 9185:
1.78 anton 9186: doc-unreachable
1.5 anton 9187:
1.23 crook 9188:
1.78 anton 9189: Another problem with this rule is that at @code{BEGIN}, the compiler
9190: does not know which locals will be visible on the incoming
9191: back-edge. All problems discussed in the following are due to this
9192: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9193: loops as examples; the discussion also applies to @code{?DO} and other
9194: loops). Perhaps the most insidious example is:
1.26 crook 9195: @example
1.78 anton 9196: AHEAD
9197: BEGIN
9198: x
9199: [ 1 CS-ROLL ] THEN
9200: @{ x @}
9201: ...
9202: UNTIL
1.26 crook 9203: @end example
1.23 crook 9204:
1.78 anton 9205: This should be legal according to the visibility rule. The use of
9206: @code{x} can only be reached through the definition; but that appears
9207: textually below the use.
9208:
9209: From this example it is clear that the visibility rules cannot be fully
9210: implemented without major headaches. Our implementation treats common
9211: cases as advertised and the exceptions are treated in a safe way: The
9212: compiler makes a reasonable guess about the locals visible after a
9213: @code{BEGIN}; if it is too pessimistic, the
9214: user will get a spurious error about the local not being defined; if the
9215: compiler is too optimistic, it will notice this later and issue a
9216: warning. In the case above the compiler would complain about @code{x}
9217: being undefined at its use. You can see from the obscure examples in
9218: this section that it takes quite unusual control structures to get the
9219: compiler into trouble, and even then it will often do fine.
1.23 crook 9220:
1.78 anton 9221: If the @code{BEGIN} is reachable from above, the most optimistic guess
9222: is that all locals visible before the @code{BEGIN} will also be
9223: visible after the @code{BEGIN}. This guess is valid for all loops that
9224: are entered only through the @code{BEGIN}, in particular, for normal
9225: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9226: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9227: compiler. When the branch to the @code{BEGIN} is finally generated by
9228: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9229: warns the user if it was too optimistic:
1.26 crook 9230: @example
1.78 anton 9231: IF
9232: @{ x @}
9233: BEGIN
9234: \ x ?
9235: [ 1 cs-roll ] THEN
9236: ...
9237: UNTIL
1.26 crook 9238: @end example
1.23 crook 9239:
1.78 anton 9240: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9241: optimistically assumes that it lives until the @code{THEN}. It notices
9242: this difference when it compiles the @code{UNTIL} and issues a
9243: warning. The user can avoid the warning, and make sure that @code{x}
9244: is not used in the wrong area by using explicit scoping:
9245: @example
9246: IF
9247: SCOPE
9248: @{ x @}
9249: ENDSCOPE
9250: BEGIN
9251: [ 1 cs-roll ] THEN
9252: ...
9253: UNTIL
9254: @end example
1.23 crook 9255:
1.78 anton 9256: Since the guess is optimistic, there will be no spurious error messages
9257: about undefined locals.
1.44 crook 9258:
1.78 anton 9259: If the @code{BEGIN} is not reachable from above (e.g., after
9260: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9261: optimistic guess, as the locals visible after the @code{BEGIN} may be
9262: defined later. Therefore, the compiler assumes that no locals are
9263: visible after the @code{BEGIN}. However, the user can use
9264: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9265: visible at the BEGIN as at the point where the top control-flow stack
9266: item was created.
1.23 crook 9267:
1.44 crook 9268:
1.78 anton 9269: doc-assume-live
1.26 crook 9270:
1.23 crook 9271:
1.78 anton 9272: @noindent
9273: E.g.,
9274: @example
9275: @{ x @}
9276: AHEAD
9277: ASSUME-LIVE
9278: BEGIN
9279: x
9280: [ 1 CS-ROLL ] THEN
9281: ...
9282: UNTIL
9283: @end example
1.44 crook 9284:
1.78 anton 9285: Other cases where the locals are defined before the @code{BEGIN} can be
9286: handled by inserting an appropriate @code{CS-ROLL} before the
9287: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9288: behind the @code{ASSUME-LIVE}).
1.23 crook 9289:
1.78 anton 9290: Cases where locals are defined after the @code{BEGIN} (but should be
9291: visible immediately after the @code{BEGIN}) can only be handled by
9292: rearranging the loop. E.g., the ``most insidious'' example above can be
9293: arranged into:
9294: @example
9295: BEGIN
9296: @{ x @}
9297: ... 0=
9298: WHILE
9299: x
9300: REPEAT
9301: @end example
1.44 crook 9302:
1.78 anton 9303: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9304: @subsubsection How long do locals live?
9305: @cindex locals lifetime
9306: @cindex lifetime of locals
1.23 crook 9307:
1.78 anton 9308: The right answer for the lifetime question would be: A local lives at
9309: least as long as it can be accessed. For a value-flavoured local this
9310: means: until the end of its visibility. However, a variable-flavoured
9311: local could be accessed through its address far beyond its visibility
9312: scope. Ultimately, this would mean that such locals would have to be
9313: garbage collected. Since this entails un-Forth-like implementation
9314: complexities, I adopted the same cowardly solution as some other
9315: languages (e.g., C): The local lives only as long as it is visible;
9316: afterwards its address is invalid (and programs that access it
9317: afterwards are erroneous).
1.23 crook 9318:
1.78 anton 9319: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9320: @subsubsection Locals programming style
9321: @cindex locals programming style
9322: @cindex programming style, locals
1.23 crook 9323:
1.78 anton 9324: The freedom to define locals anywhere has the potential to change
9325: programming styles dramatically. In particular, the need to use the
9326: return stack for intermediate storage vanishes. Moreover, all stack
9327: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9328: determined arguments) can be eliminated: If the stack items are in the
9329: wrong order, just write a locals definition for all of them; then
9330: write the items in the order you want.
1.23 crook 9331:
1.78 anton 9332: This seems a little far-fetched and eliminating stack manipulations is
9333: unlikely to become a conscious programming objective. Still, the number
9334: of stack manipulations will be reduced dramatically if local variables
9335: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9336: a traditional implementation of @code{max}).
1.23 crook 9337:
1.78 anton 9338: This shows one potential benefit of locals: making Forth programs more
9339: readable. Of course, this benefit will only be realized if the
9340: programmers continue to honour the principle of factoring instead of
9341: using the added latitude to make the words longer.
1.23 crook 9342:
1.78 anton 9343: @cindex single-assignment style for locals
9344: Using @code{TO} can and should be avoided. Without @code{TO},
9345: every value-flavoured local has only a single assignment and many
9346: advantages of functional languages apply to Forth. I.e., programs are
9347: easier to analyse, to optimize and to read: It is clear from the
9348: definition what the local stands for, it does not turn into something
9349: different later.
1.23 crook 9350:
1.78 anton 9351: E.g., a definition using @code{TO} might look like this:
9352: @example
9353: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9354: u1 u2 min 0
9355: ?do
9356: addr1 c@@ addr2 c@@ -
9357: ?dup-if
9358: unloop exit
9359: then
9360: addr1 char+ TO addr1
9361: addr2 char+ TO addr2
9362: loop
9363: u1 u2 - ;
1.26 crook 9364: @end example
1.78 anton 9365: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9366: every loop iteration. @code{strcmp} is a typical example of the
9367: readability problems of using @code{TO}. When you start reading
9368: @code{strcmp}, you think that @code{addr1} refers to the start of the
9369: string. Only near the end of the loop you realize that it is something
9370: else.
1.23 crook 9371:
1.78 anton 9372: This can be avoided by defining two locals at the start of the loop that
9373: are initialized with the right value for the current iteration.
9374: @example
9375: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9376: addr1 addr2
9377: u1 u2 min 0
9378: ?do @{ s1 s2 @}
9379: s1 c@@ s2 c@@ -
9380: ?dup-if
9381: unloop exit
9382: then
9383: s1 char+ s2 char+
9384: loop
9385: 2drop
9386: u1 u2 - ;
9387: @end example
9388: Here it is clear from the start that @code{s1} has a different value
9389: in every loop iteration.
1.23 crook 9390:
1.78 anton 9391: @node Locals implementation, , Locals programming style, Gforth locals
9392: @subsubsection Locals implementation
9393: @cindex locals implementation
9394: @cindex implementation of locals
1.23 crook 9395:
1.78 anton 9396: @cindex locals stack
9397: Gforth uses an extra locals stack. The most compelling reason for
9398: this is that the return stack is not float-aligned; using an extra stack
9399: also eliminates the problems and restrictions of using the return stack
9400: as locals stack. Like the other stacks, the locals stack grows toward
9401: lower addresses. A few primitives allow an efficient implementation:
9402:
9403:
9404: doc-@local#
9405: doc-f@local#
9406: doc-laddr#
9407: doc-lp+!#
9408: doc-lp!
9409: doc->l
9410: doc-f>l
9411:
9412:
9413: In addition to these primitives, some specializations of these
9414: primitives for commonly occurring inline arguments are provided for
9415: efficiency reasons, e.g., @code{@@local0} as specialization of
9416: @code{@@local#} for the inline argument 0. The following compiling words
9417: compile the right specialized version, or the general version, as
9418: appropriate:
1.23 crook 9419:
1.5 anton 9420:
1.107 dvdkhlng 9421: @c doc-compile-@local
9422: @c doc-compile-f@local
1.78 anton 9423: doc-compile-lp+!
1.5 anton 9424:
9425:
1.78 anton 9426: Combinations of conditional branches and @code{lp+!#} like
9427: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9428: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9429:
1.78 anton 9430: A special area in the dictionary space is reserved for keeping the
9431: local variable names. @code{@{} switches the dictionary pointer to this
9432: area and @code{@}} switches it back and generates the locals
9433: initializing code. @code{W:} etc.@ are normal defining words. This
9434: special area is cleared at the start of every colon definition.
1.5 anton 9435:
1.78 anton 9436: @cindex word list for defining locals
9437: A special feature of Gforth's dictionary is used to implement the
9438: definition of locals without type specifiers: every word list (aka
9439: vocabulary) has its own methods for searching
9440: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9441: with a special search method: When it is searched for a word, it
9442: actually creates that word using @code{W:}. @code{@{} changes the search
9443: order to first search the word list containing @code{@}}, @code{W:} etc.,
9444: and then the word list for defining locals without type specifiers.
1.5 anton 9445:
1.78 anton 9446: The lifetime rules support a stack discipline within a colon
9447: definition: The lifetime of a local is either nested with other locals
9448: lifetimes or it does not overlap them.
1.23 crook 9449:
1.78 anton 9450: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9451: pointer manipulation is generated. Between control structure words
9452: locals definitions can push locals onto the locals stack. @code{AGAIN}
9453: is the simplest of the other three control flow words. It has to
9454: restore the locals stack depth of the corresponding @code{BEGIN}
9455: before branching. The code looks like this:
9456: @format
9457: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9458: @code{branch} <begin>
9459: @end format
1.26 crook 9460:
1.78 anton 9461: @code{UNTIL} is a little more complicated: If it branches back, it
9462: must adjust the stack just like @code{AGAIN}. But if it falls through,
9463: the locals stack must not be changed. The compiler generates the
9464: following code:
9465: @format
9466: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9467: @end format
9468: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9469:
1.78 anton 9470: @code{THEN} can produce somewhat inefficient code:
9471: @format
9472: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9473: <orig target>:
9474: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9475: @end format
9476: The second @code{lp+!#} adjusts the locals stack pointer from the
9477: level at the @i{orig} point to the level after the @code{THEN}. The
9478: first @code{lp+!#} adjusts the locals stack pointer from the current
9479: level to the level at the orig point, so the complete effect is an
9480: adjustment from the current level to the right level after the
9481: @code{THEN}.
1.26 crook 9482:
1.78 anton 9483: @cindex locals information on the control-flow stack
9484: @cindex control-flow stack items, locals information
9485: In a conventional Forth implementation a dest control-flow stack entry
9486: is just the target address and an orig entry is just the address to be
9487: patched. Our locals implementation adds a word list to every orig or dest
9488: item. It is the list of locals visible (or assumed visible) at the point
9489: described by the entry. Our implementation also adds a tag to identify
9490: the kind of entry, in particular to differentiate between live and dead
9491: (reachable and unreachable) orig entries.
1.26 crook 9492:
1.78 anton 9493: A few unusual operations have to be performed on locals word lists:
1.44 crook 9494:
1.5 anton 9495:
1.78 anton 9496: doc-common-list
9497: doc-sub-list?
9498: doc-list-size
1.52 anton 9499:
9500:
1.78 anton 9501: Several features of our locals word list implementation make these
9502: operations easy to implement: The locals word lists are organised as
9503: linked lists; the tails of these lists are shared, if the lists
9504: contain some of the same locals; and the address of a name is greater
9505: than the address of the names behind it in the list.
1.5 anton 9506:
1.78 anton 9507: Another important implementation detail is the variable
9508: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9509: determine if they can be reached directly or only through the branch
9510: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9511: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9512: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9513:
1.78 anton 9514: Counted loops are similar to other loops in most respects, but
9515: @code{LEAVE} requires special attention: It performs basically the same
9516: service as @code{AHEAD}, but it does not create a control-flow stack
9517: entry. Therefore the information has to be stored elsewhere;
9518: traditionally, the information was stored in the target fields of the
9519: branches created by the @code{LEAVE}s, by organizing these fields into a
9520: linked list. Unfortunately, this clever trick does not provide enough
9521: space for storing our extended control flow information. Therefore, we
9522: introduce another stack, the leave stack. It contains the control-flow
9523: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9524:
1.78 anton 9525: Local names are kept until the end of the colon definition, even if
9526: they are no longer visible in any control-flow path. In a few cases
9527: this may lead to increased space needs for the locals name area, but
9528: usually less than reclaiming this space would cost in code size.
1.5 anton 9529:
1.44 crook 9530:
1.78 anton 9531: @node ANS Forth locals, , Gforth locals, Locals
9532: @subsection ANS Forth locals
9533: @cindex locals, ANS Forth style
1.5 anton 9534:
1.78 anton 9535: The ANS Forth locals wordset does not define a syntax for locals, but
9536: words that make it possible to define various syntaxes. One of the
9537: possible syntaxes is a subset of the syntax we used in the Gforth locals
9538: wordset, i.e.:
1.29 crook 9539:
9540: @example
1.78 anton 9541: @{ local1 local2 ... -- comment @}
9542: @end example
9543: @noindent
9544: or
9545: @example
9546: @{ local1 local2 ... @}
1.29 crook 9547: @end example
9548:
1.78 anton 9549: The order of the locals corresponds to the order in a stack comment. The
9550: restrictions are:
1.5 anton 9551:
1.78 anton 9552: @itemize @bullet
9553: @item
9554: Locals can only be cell-sized values (no type specifiers are allowed).
9555: @item
9556: Locals can be defined only outside control structures.
9557: @item
9558: Locals can interfere with explicit usage of the return stack. For the
9559: exact (and long) rules, see the standard. If you don't use return stack
9560: accessing words in a definition using locals, you will be all right. The
9561: purpose of this rule is to make locals implementation on the return
9562: stack easier.
9563: @item
9564: The whole definition must be in one line.
9565: @end itemize
1.5 anton 9566:
1.78 anton 9567: Locals defined in ANS Forth behave like @code{VALUE}s
9568: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9569: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9570:
1.78 anton 9571: Since the syntax above is supported by Gforth directly, you need not do
9572: anything to use it. If you want to port a program using this syntax to
9573: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9574: syntax on the other system.
1.5 anton 9575:
1.78 anton 9576: Note that a syntax shown in the standard, section A.13 looks
9577: similar, but is quite different in having the order of locals
9578: reversed. Beware!
1.5 anton 9579:
1.78 anton 9580: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9581:
1.78 anton 9582: doc-(local)
1.5 anton 9583:
1.78 anton 9584: The ANS Forth locals extension wordset defines a syntax using
9585: @code{locals|}, but it is so awful that we strongly recommend not to use
9586: it. We have implemented this syntax to make porting to Gforth easy, but
9587: do not document it here. The problem with this syntax is that the locals
9588: are defined in an order reversed with respect to the standard stack
9589: comment notation, making programs harder to read, and easier to misread
9590: and miswrite. The only merit of this syntax is that it is easy to
9591: implement using the ANS Forth locals wordset.
1.53 anton 9592:
9593:
1.78 anton 9594: @c ----------------------------------------------------------
9595: @node Structures, Object-oriented Forth, Locals, Words
9596: @section Structures
9597: @cindex structures
9598: @cindex records
1.53 anton 9599:
1.78 anton 9600: This section presents the structure package that comes with Gforth. A
9601: version of the package implemented in ANS Forth is available in
9602: @file{compat/struct.fs}. This package was inspired by a posting on
9603: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9604: possibly John Hayes). A version of this section has been published in
9605: M. Anton Ertl,
9606: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9607: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9608: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9609:
1.78 anton 9610: @menu
9611: * Why explicit structure support?::
9612: * Structure Usage::
9613: * Structure Naming Convention::
9614: * Structure Implementation::
9615: * Structure Glossary::
9616: @end menu
1.55 anton 9617:
1.78 anton 9618: @node Why explicit structure support?, Structure Usage, Structures, Structures
9619: @subsection Why explicit structure support?
1.53 anton 9620:
1.78 anton 9621: @cindex address arithmetic for structures
9622: @cindex structures using address arithmetic
9623: If we want to use a structure containing several fields, we could simply
9624: reserve memory for it, and access the fields using address arithmetic
9625: (@pxref{Address arithmetic}). As an example, consider a structure with
9626: the following fields
1.57 anton 9627:
1.78 anton 9628: @table @code
9629: @item a
9630: is a float
9631: @item b
9632: is a cell
9633: @item c
9634: is a float
9635: @end table
1.57 anton 9636:
1.78 anton 9637: Given the (float-aligned) base address of the structure we get the
9638: address of the field
1.52 anton 9639:
1.78 anton 9640: @table @code
9641: @item a
9642: without doing anything further.
9643: @item b
9644: with @code{float+}
9645: @item c
9646: with @code{float+ cell+ faligned}
9647: @end table
1.52 anton 9648:
1.78 anton 9649: It is easy to see that this can become quite tiring.
1.52 anton 9650:
1.78 anton 9651: Moreover, it is not very readable, because seeing a
9652: @code{cell+} tells us neither which kind of structure is
9653: accessed nor what field is accessed; we have to somehow infer the kind
9654: of structure, and then look up in the documentation, which field of
9655: that structure corresponds to that offset.
1.53 anton 9656:
1.78 anton 9657: Finally, this kind of address arithmetic also causes maintenance
9658: troubles: If you add or delete a field somewhere in the middle of the
9659: structure, you have to find and change all computations for the fields
9660: afterwards.
1.52 anton 9661:
1.78 anton 9662: So, instead of using @code{cell+} and friends directly, how
9663: about storing the offsets in constants:
1.52 anton 9664:
1.78 anton 9665: @example
9666: 0 constant a-offset
9667: 0 float+ constant b-offset
9668: 0 float+ cell+ faligned c-offset
9669: @end example
1.64 pazsan 9670:
1.78 anton 9671: Now we can get the address of field @code{x} with @code{x-offset
9672: +}. This is much better in all respects. Of course, you still
9673: have to change all later offset definitions if you add a field. You can
9674: fix this by declaring the offsets in the following way:
1.57 anton 9675:
1.78 anton 9676: @example
9677: 0 constant a-offset
9678: a-offset float+ constant b-offset
9679: b-offset cell+ faligned constant c-offset
9680: @end example
1.57 anton 9681:
1.78 anton 9682: Since we always use the offsets with @code{+}, we could use a defining
9683: word @code{cfield} that includes the @code{+} in the action of the
9684: defined word:
1.64 pazsan 9685:
1.78 anton 9686: @example
9687: : cfield ( n "name" -- )
9688: create ,
9689: does> ( name execution: addr1 -- addr2 )
9690: @@ + ;
1.64 pazsan 9691:
1.78 anton 9692: 0 cfield a
9693: 0 a float+ cfield b
9694: 0 b cell+ faligned cfield c
9695: @end example
1.64 pazsan 9696:
1.78 anton 9697: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9698:
1.78 anton 9699: The structure field words now can be used quite nicely. However,
9700: their definition is still a bit cumbersome: We have to repeat the
9701: name, the information about size and alignment is distributed before
9702: and after the field definitions etc. The structure package presented
9703: here addresses these problems.
1.64 pazsan 9704:
1.78 anton 9705: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9706: @subsection Structure Usage
9707: @cindex structure usage
1.57 anton 9708:
1.78 anton 9709: @cindex @code{field} usage
9710: @cindex @code{struct} usage
9711: @cindex @code{end-struct} usage
9712: You can define a structure for a (data-less) linked list with:
1.57 anton 9713: @example
1.78 anton 9714: struct
9715: cell% field list-next
9716: end-struct list%
1.57 anton 9717: @end example
9718:
1.78 anton 9719: With the address of the list node on the stack, you can compute the
9720: address of the field that contains the address of the next node with
9721: @code{list-next}. E.g., you can determine the length of a list
9722: with:
1.57 anton 9723:
9724: @example
1.78 anton 9725: : list-length ( list -- n )
9726: \ "list" is a pointer to the first element of a linked list
9727: \ "n" is the length of the list
9728: 0 BEGIN ( list1 n1 )
9729: over
9730: WHILE ( list1 n1 )
9731: 1+ swap list-next @@ swap
9732: REPEAT
9733: nip ;
1.57 anton 9734: @end example
9735:
1.78 anton 9736: You can reserve memory for a list node in the dictionary with
9737: @code{list% %allot}, which leaves the address of the list node on the
9738: stack. For the equivalent allocation on the heap you can use @code{list%
9739: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9740: use @code{list% %allocate}). You can get the the size of a list
9741: node with @code{list% %size} and its alignment with @code{list%
9742: %alignment}.
9743:
9744: Note that in ANS Forth the body of a @code{create}d word is
9745: @code{aligned} but not necessarily @code{faligned};
9746: therefore, if you do a:
1.57 anton 9747:
9748: @example
1.78 anton 9749: create @emph{name} foo% %allot drop
1.57 anton 9750: @end example
9751:
1.78 anton 9752: @noindent
9753: then the memory alloted for @code{foo%} is guaranteed to start at the
9754: body of @code{@emph{name}} only if @code{foo%} contains only character,
9755: cell and double fields. Therefore, if your structure contains floats,
9756: better use
1.57 anton 9757:
9758: @example
1.78 anton 9759: foo% %allot constant @emph{name}
1.57 anton 9760: @end example
9761:
1.78 anton 9762: @cindex structures containing structures
9763: You can include a structure @code{foo%} as a field of
9764: another structure, like this:
1.65 anton 9765: @example
1.78 anton 9766: struct
9767: ...
9768: foo% field ...
9769: ...
9770: end-struct ...
1.65 anton 9771: @end example
1.52 anton 9772:
1.78 anton 9773: @cindex structure extension
9774: @cindex extended records
9775: Instead of starting with an empty structure, you can extend an
9776: existing structure. E.g., a plain linked list without data, as defined
9777: above, is hardly useful; You can extend it to a linked list of integers,
9778: like this:@footnote{This feature is also known as @emph{extended
9779: records}. It is the main innovation in the Oberon language; in other
9780: words, adding this feature to Modula-2 led Wirth to create a new
9781: language, write a new compiler etc. Adding this feature to Forth just
9782: required a few lines of code.}
1.52 anton 9783:
1.78 anton 9784: @example
9785: list%
9786: cell% field intlist-int
9787: end-struct intlist%
9788: @end example
1.55 anton 9789:
1.78 anton 9790: @code{intlist%} is a structure with two fields:
9791: @code{list-next} and @code{intlist-int}.
1.55 anton 9792:
1.78 anton 9793: @cindex structures containing arrays
9794: You can specify an array type containing @emph{n} elements of
9795: type @code{foo%} like this:
1.55 anton 9796:
9797: @example
1.78 anton 9798: foo% @emph{n} *
1.56 anton 9799: @end example
1.55 anton 9800:
1.78 anton 9801: You can use this array type in any place where you can use a normal
9802: type, e.g., when defining a @code{field}, or with
9803: @code{%allot}.
9804:
9805: @cindex first field optimization
9806: The first field is at the base address of a structure and the word for
9807: this field (e.g., @code{list-next}) actually does not change the address
9808: on the stack. You may be tempted to leave it away in the interest of
9809: run-time and space efficiency. This is not necessary, because the
9810: structure package optimizes this case: If you compile a first-field
9811: words, no code is generated. So, in the interest of readability and
9812: maintainability you should include the word for the field when accessing
9813: the field.
1.52 anton 9814:
9815:
1.78 anton 9816: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9817: @subsection Structure Naming Convention
9818: @cindex structure naming convention
1.52 anton 9819:
1.78 anton 9820: The field names that come to (my) mind are often quite generic, and,
9821: if used, would cause frequent name clashes. E.g., many structures
9822: probably contain a @code{counter} field. The structure names
9823: that come to (my) mind are often also the logical choice for the names
9824: of words that create such a structure.
1.52 anton 9825:
1.78 anton 9826: Therefore, I have adopted the following naming conventions:
1.52 anton 9827:
1.78 anton 9828: @itemize @bullet
9829: @cindex field naming convention
9830: @item
9831: The names of fields are of the form
9832: @code{@emph{struct}-@emph{field}}, where
9833: @code{@emph{struct}} is the basic name of the structure, and
9834: @code{@emph{field}} is the basic name of the field. You can
9835: think of field words as converting the (address of the)
9836: structure into the (address of the) field.
1.52 anton 9837:
1.78 anton 9838: @cindex structure naming convention
9839: @item
9840: The names of structures are of the form
9841: @code{@emph{struct}%}, where
9842: @code{@emph{struct}} is the basic name of the structure.
9843: @end itemize
1.52 anton 9844:
1.78 anton 9845: This naming convention does not work that well for fields of extended
9846: structures; e.g., the integer list structure has a field
9847: @code{intlist-int}, but has @code{list-next}, not
9848: @code{intlist-next}.
1.53 anton 9849:
1.78 anton 9850: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9851: @subsection Structure Implementation
9852: @cindex structure implementation
9853: @cindex implementation of structures
1.52 anton 9854:
1.78 anton 9855: The central idea in the implementation is to pass the data about the
9856: structure being built on the stack, not in some global
9857: variable. Everything else falls into place naturally once this design
9858: decision is made.
1.53 anton 9859:
1.78 anton 9860: The type description on the stack is of the form @emph{align
9861: size}. Keeping the size on the top-of-stack makes dealing with arrays
9862: very simple.
1.53 anton 9863:
1.78 anton 9864: @code{field} is a defining word that uses @code{Create}
9865: and @code{DOES>}. The body of the field contains the offset
9866: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9867:
9868: @example
1.78 anton 9869: @@ +
1.53 anton 9870: @end example
9871:
1.78 anton 9872: @noindent
9873: i.e., add the offset to the address, giving the stack effect
9874: @i{addr1 -- addr2} for a field.
9875:
9876: @cindex first field optimization, implementation
9877: This simple structure is slightly complicated by the optimization
9878: for fields with offset 0, which requires a different
9879: @code{DOES>}-part (because we cannot rely on there being
9880: something on the stack if such a field is invoked during
9881: compilation). Therefore, we put the different @code{DOES>}-parts
9882: in separate words, and decide which one to invoke based on the
9883: offset. For a zero offset, the field is basically a noop; it is
9884: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9885:
1.78 anton 9886: @node Structure Glossary, , Structure Implementation, Structures
9887: @subsection Structure Glossary
9888: @cindex structure glossary
1.53 anton 9889:
1.5 anton 9890:
1.78 anton 9891: doc-%align
9892: doc-%alignment
9893: doc-%alloc
9894: doc-%allocate
9895: doc-%allot
9896: doc-cell%
9897: doc-char%
9898: doc-dfloat%
9899: doc-double%
9900: doc-end-struct
9901: doc-field
9902: doc-float%
9903: doc-naligned
9904: doc-sfloat%
9905: doc-%size
9906: doc-struct
1.54 anton 9907:
9908:
1.26 crook 9909: @c -------------------------------------------------------------
1.78 anton 9910: @node Object-oriented Forth, Programming Tools, Structures, Words
9911: @section Object-oriented Forth
9912:
9913: Gforth comes with three packages for object-oriented programming:
9914: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9915: is preloaded, so you have to @code{include} them before use. The most
9916: important differences between these packages (and others) are discussed
9917: in @ref{Comparison with other object models}. All packages are written
9918: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9919:
1.78 anton 9920: @menu
9921: * Why object-oriented programming?::
9922: * Object-Oriented Terminology::
9923: * Objects::
9924: * OOF::
9925: * Mini-OOF::
9926: * Comparison with other object models::
9927: @end menu
1.5 anton 9928:
1.78 anton 9929: @c ----------------------------------------------------------------
9930: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9931: @subsection Why object-oriented programming?
9932: @cindex object-oriented programming motivation
9933: @cindex motivation for object-oriented programming
1.44 crook 9934:
1.78 anton 9935: Often we have to deal with several data structures (@emph{objects}),
9936: that have to be treated similarly in some respects, but differently in
9937: others. Graphical objects are the textbook example: circles, triangles,
9938: dinosaurs, icons, and others, and we may want to add more during program
9939: development. We want to apply some operations to any graphical object,
9940: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9941: has to do something different for every kind of object.
9942: @comment TODO add some other operations eg perimeter, area
9943: @comment and tie in to concrete examples later..
1.5 anton 9944:
1.78 anton 9945: We could implement @code{draw} as a big @code{CASE}
9946: control structure that executes the appropriate code depending on the
9947: kind of object to be drawn. This would be not be very elegant, and,
9948: moreover, we would have to change @code{draw} every time we add
9949: a new kind of graphical object (say, a spaceship).
1.44 crook 9950:
1.78 anton 9951: What we would rather do is: When defining spaceships, we would tell
9952: the system: ``Here's how you @code{draw} a spaceship; you figure
9953: out the rest''.
1.5 anton 9954:
1.78 anton 9955: This is the problem that all systems solve that (rightfully) call
9956: themselves object-oriented; the object-oriented packages presented here
9957: solve this problem (and not much else).
9958: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9959:
1.78 anton 9960: @c ------------------------------------------------------------------------
9961: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9962: @subsection Object-Oriented Terminology
9963: @cindex object-oriented terminology
9964: @cindex terminology for object-oriented programming
1.5 anton 9965:
1.78 anton 9966: This section is mainly for reference, so you don't have to understand
9967: all of it right away. The terminology is mainly Smalltalk-inspired. In
9968: short:
1.44 crook 9969:
1.78 anton 9970: @table @emph
9971: @cindex class
9972: @item class
9973: a data structure definition with some extras.
1.5 anton 9974:
1.78 anton 9975: @cindex object
9976: @item object
9977: an instance of the data structure described by the class definition.
1.5 anton 9978:
1.78 anton 9979: @cindex instance variables
9980: @item instance variables
9981: fields of the data structure.
1.5 anton 9982:
1.78 anton 9983: @cindex selector
9984: @cindex method selector
9985: @cindex virtual function
9986: @item selector
9987: (or @emph{method selector}) a word (e.g.,
9988: @code{draw}) that performs an operation on a variety of data
9989: structures (classes). A selector describes @emph{what} operation to
9990: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9991:
1.78 anton 9992: @cindex method
9993: @item method
9994: the concrete definition that performs the operation
9995: described by the selector for a specific class. A method specifies
9996: @emph{how} the operation is performed for a specific class.
1.5 anton 9997:
1.78 anton 9998: @cindex selector invocation
9999: @cindex message send
10000: @cindex invoking a selector
10001: @item selector invocation
10002: a call of a selector. One argument of the call (the TOS (top-of-stack))
10003: is used for determining which method is used. In Smalltalk terminology:
10004: a message (consisting of the selector and the other arguments) is sent
10005: to the object.
1.5 anton 10006:
1.78 anton 10007: @cindex receiving object
10008: @item receiving object
10009: the object used for determining the method executed by a selector
10010: invocation. In the @file{objects.fs} model, it is the object that is on
10011: the TOS when the selector is invoked. (@emph{Receiving} comes from
10012: the Smalltalk @emph{message} terminology.)
1.5 anton 10013:
1.78 anton 10014: @cindex child class
10015: @cindex parent class
10016: @cindex inheritance
10017: @item child class
10018: a class that has (@emph{inherits}) all properties (instance variables,
10019: selectors, methods) from a @emph{parent class}. In Smalltalk
10020: terminology: The subclass inherits from the superclass. In C++
10021: terminology: The derived class inherits from the base class.
1.5 anton 10022:
1.78 anton 10023: @end table
1.5 anton 10024:
1.78 anton 10025: @c If you wonder about the message sending terminology, it comes from
10026: @c a time when each object had it's own task and objects communicated via
10027: @c message passing; eventually the Smalltalk developers realized that
10028: @c they can do most things through simple (indirect) calls. They kept the
10029: @c terminology.
1.5 anton 10030:
1.78 anton 10031: @c --------------------------------------------------------------
10032: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10033: @subsection The @file{objects.fs} model
10034: @cindex objects
10035: @cindex object-oriented programming
1.26 crook 10036:
1.78 anton 10037: @cindex @file{objects.fs}
10038: @cindex @file{oof.fs}
1.26 crook 10039:
1.78 anton 10040: This section describes the @file{objects.fs} package. This material also
10041: has been published in M. Anton Ertl,
10042: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10043: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10044: 37--43.
10045: @c McKewan's and Zsoter's packages
1.26 crook 10046:
1.78 anton 10047: This section assumes that you have read @ref{Structures}.
1.5 anton 10048:
1.78 anton 10049: The techniques on which this model is based have been used to implement
10050: the parser generator, Gray, and have also been used in Gforth for
10051: implementing the various flavours of word lists (hashed or not,
10052: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10053:
10054:
1.26 crook 10055: @menu
1.78 anton 10056: * Properties of the Objects model::
10057: * Basic Objects Usage::
10058: * The Objects base class::
10059: * Creating objects::
10060: * Object-Oriented Programming Style::
10061: * Class Binding::
10062: * Method conveniences::
10063: * Classes and Scoping::
10064: * Dividing classes::
10065: * Object Interfaces::
10066: * Objects Implementation::
10067: * Objects Glossary::
1.26 crook 10068: @end menu
1.5 anton 10069:
1.78 anton 10070: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10071:
1.78 anton 10072: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10073: @subsubsection Properties of the @file{objects.fs} model
10074: @cindex @file{objects.fs} properties
1.5 anton 10075:
1.78 anton 10076: @itemize @bullet
10077: @item
10078: It is straightforward to pass objects on the stack. Passing
10079: selectors on the stack is a little less convenient, but possible.
1.44 crook 10080:
1.78 anton 10081: @item
10082: Objects are just data structures in memory, and are referenced by their
10083: address. You can create words for objects with normal defining words
10084: like @code{constant}. Likewise, there is no difference between instance
10085: variables that contain objects and those that contain other data.
1.5 anton 10086:
1.78 anton 10087: @item
10088: Late binding is efficient and easy to use.
1.44 crook 10089:
1.78 anton 10090: @item
10091: It avoids parsing, and thus avoids problems with state-smartness
10092: and reduced extensibility; for convenience there are a few parsing
10093: words, but they have non-parsing counterparts. There are also a few
10094: defining words that parse. This is hard to avoid, because all standard
10095: defining words parse (except @code{:noname}); however, such
10096: words are not as bad as many other parsing words, because they are not
10097: state-smart.
1.5 anton 10098:
1.78 anton 10099: @item
10100: It does not try to incorporate everything. It does a few things and does
10101: them well (IMO). In particular, this model was not designed to support
10102: information hiding (although it has features that may help); you can use
10103: a separate package for achieving this.
1.5 anton 10104:
1.78 anton 10105: @item
10106: It is layered; you don't have to learn and use all features to use this
10107: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10108: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10109: are optional and independent of each other.
1.5 anton 10110:
1.78 anton 10111: @item
10112: An implementation in ANS Forth is available.
1.5 anton 10113:
1.78 anton 10114: @end itemize
1.5 anton 10115:
1.44 crook 10116:
1.78 anton 10117: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10118: @subsubsection Basic @file{objects.fs} Usage
10119: @cindex basic objects usage
10120: @cindex objects, basic usage
1.5 anton 10121:
1.78 anton 10122: You can define a class for graphical objects like this:
1.44 crook 10123:
1.78 anton 10124: @cindex @code{class} usage
10125: @cindex @code{end-class} usage
10126: @cindex @code{selector} usage
1.5 anton 10127: @example
1.78 anton 10128: object class \ "object" is the parent class
10129: selector draw ( x y graphical -- )
10130: end-class graphical
10131: @end example
10132:
10133: This code defines a class @code{graphical} with an
10134: operation @code{draw}. We can perform the operation
10135: @code{draw} on any @code{graphical} object, e.g.:
10136:
10137: @example
10138: 100 100 t-rex draw
1.26 crook 10139: @end example
1.5 anton 10140:
1.78 anton 10141: @noindent
10142: where @code{t-rex} is a word (say, a constant) that produces a
10143: graphical object.
10144:
10145: @comment TODO add a 2nd operation eg perimeter.. and use for
10146: @comment a concrete example
1.5 anton 10147:
1.78 anton 10148: @cindex abstract class
10149: How do we create a graphical object? With the present definitions,
10150: we cannot create a useful graphical object. The class
10151: @code{graphical} describes graphical objects in general, but not
10152: any concrete graphical object type (C++ users would call it an
10153: @emph{abstract class}); e.g., there is no method for the selector
10154: @code{draw} in the class @code{graphical}.
1.5 anton 10155:
1.78 anton 10156: For concrete graphical objects, we define child classes of the
10157: class @code{graphical}, e.g.:
1.5 anton 10158:
1.78 anton 10159: @cindex @code{overrides} usage
10160: @cindex @code{field} usage in class definition
1.26 crook 10161: @example
1.78 anton 10162: graphical class \ "graphical" is the parent class
10163: cell% field circle-radius
1.5 anton 10164:
1.78 anton 10165: :noname ( x y circle -- )
10166: circle-radius @@ draw-circle ;
10167: overrides draw
1.5 anton 10168:
1.78 anton 10169: :noname ( n-radius circle -- )
10170: circle-radius ! ;
10171: overrides construct
1.5 anton 10172:
1.78 anton 10173: end-class circle
10174: @end example
1.44 crook 10175:
1.78 anton 10176: Here we define a class @code{circle} as a child of @code{graphical},
10177: with field @code{circle-radius} (which behaves just like a field
10178: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10179: for the selectors @code{draw} and @code{construct} (@code{construct} is
10180: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10181:
1.78 anton 10182: Now we can create a circle on the heap (i.e.,
10183: @code{allocate}d memory) with:
1.44 crook 10184:
1.78 anton 10185: @cindex @code{heap-new} usage
1.5 anton 10186: @example
1.78 anton 10187: 50 circle heap-new constant my-circle
1.5 anton 10188: @end example
10189:
1.78 anton 10190: @noindent
10191: @code{heap-new} invokes @code{construct}, thus
10192: initializing the field @code{circle-radius} with 50. We can draw
10193: this new circle at (100,100) with:
1.5 anton 10194:
10195: @example
1.78 anton 10196: 100 100 my-circle draw
1.5 anton 10197: @end example
10198:
1.78 anton 10199: @cindex selector invocation, restrictions
10200: @cindex class definition, restrictions
10201: Note: You can only invoke a selector if the object on the TOS
10202: (the receiving object) belongs to the class where the selector was
10203: defined or one of its descendents; e.g., you can invoke
10204: @code{draw} only for objects belonging to @code{graphical}
10205: or its descendents (e.g., @code{circle}). Immediately before
10206: @code{end-class}, the search order has to be the same as
10207: immediately after @code{class}.
10208:
10209: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10210: @subsubsection The @file{object.fs} base class
10211: @cindex @code{object} class
10212:
10213: When you define a class, you have to specify a parent class. So how do
10214: you start defining classes? There is one class available from the start:
10215: @code{object}. It is ancestor for all classes and so is the
10216: only class that has no parent. It has two selectors: @code{construct}
10217: and @code{print}.
10218:
10219: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10220: @subsubsection Creating objects
10221: @cindex creating objects
10222: @cindex object creation
10223: @cindex object allocation options
10224:
10225: @cindex @code{heap-new} discussion
10226: @cindex @code{dict-new} discussion
10227: @cindex @code{construct} discussion
10228: You can create and initialize an object of a class on the heap with
10229: @code{heap-new} ( ... class -- object ) and in the dictionary
10230: (allocation with @code{allot}) with @code{dict-new} (
10231: ... class -- object ). Both words invoke @code{construct}, which
10232: consumes the stack items indicated by "..." above.
10233:
10234: @cindex @code{init-object} discussion
10235: @cindex @code{class-inst-size} discussion
10236: If you want to allocate memory for an object yourself, you can get its
10237: alignment and size with @code{class-inst-size 2@@} ( class --
10238: align size ). Once you have memory for an object, you can initialize
10239: it with @code{init-object} ( ... class object -- );
10240: @code{construct} does only a part of the necessary work.
10241:
10242: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10243: @subsubsection Object-Oriented Programming Style
10244: @cindex object-oriented programming style
10245: @cindex programming style, object-oriented
1.5 anton 10246:
1.78 anton 10247: This section is not exhaustive.
1.5 anton 10248:
1.78 anton 10249: @cindex stack effects of selectors
10250: @cindex selectors and stack effects
10251: In general, it is a good idea to ensure that all methods for the
10252: same selector have the same stack effect: when you invoke a selector,
10253: you often have no idea which method will be invoked, so, unless all
10254: methods have the same stack effect, you will not know the stack effect
10255: of the selector invocation.
1.5 anton 10256:
1.78 anton 10257: One exception to this rule is methods for the selector
10258: @code{construct}. We know which method is invoked, because we
10259: specify the class to be constructed at the same place. Actually, I
10260: defined @code{construct} as a selector only to give the users a
10261: convenient way to specify initialization. The way it is used, a
10262: mechanism different from selector invocation would be more natural
10263: (but probably would take more code and more space to explain).
1.5 anton 10264:
1.78 anton 10265: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10266: @subsubsection Class Binding
10267: @cindex class binding
10268: @cindex early binding
1.5 anton 10269:
1.78 anton 10270: @cindex late binding
10271: Normal selector invocations determine the method at run-time depending
10272: on the class of the receiving object. This run-time selection is called
10273: @i{late binding}.
1.5 anton 10274:
1.78 anton 10275: Sometimes it's preferable to invoke a different method. For example,
10276: you might want to use the simple method for @code{print}ing
10277: @code{object}s instead of the possibly long-winded @code{print} method
10278: of the receiver class. You can achieve this by replacing the invocation
10279: of @code{print} with:
1.5 anton 10280:
1.78 anton 10281: @cindex @code{[bind]} usage
1.5 anton 10282: @example
1.78 anton 10283: [bind] object print
1.5 anton 10284: @end example
10285:
1.78 anton 10286: @noindent
10287: in compiled code or:
10288:
10289: @cindex @code{bind} usage
1.5 anton 10290: @example
1.78 anton 10291: bind object print
1.5 anton 10292: @end example
10293:
1.78 anton 10294: @cindex class binding, alternative to
10295: @noindent
10296: in interpreted code. Alternatively, you can define the method with a
10297: name (e.g., @code{print-object}), and then invoke it through the
10298: name. Class binding is just a (often more convenient) way to achieve
10299: the same effect; it avoids name clutter and allows you to invoke
10300: methods directly without naming them first.
1.5 anton 10301:
1.78 anton 10302: @cindex superclass binding
10303: @cindex parent class binding
10304: A frequent use of class binding is this: When we define a method
10305: for a selector, we often want the method to do what the selector does
10306: in the parent class, and a little more. There is a special word for
10307: this purpose: @code{[parent]}; @code{[parent]
10308: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10309: selector}}, where @code{@emph{parent}} is the parent
10310: class of the current class. E.g., a method definition might look like:
1.44 crook 10311:
1.78 anton 10312: @cindex @code{[parent]} usage
10313: @example
10314: :noname
10315: dup [parent] foo \ do parent's foo on the receiving object
10316: ... \ do some more
10317: ; overrides foo
10318: @end example
1.6 pazsan 10319:
1.78 anton 10320: @cindex class binding as optimization
10321: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10322: March 1997), Andrew McKewan presents class binding as an optimization
10323: technique. I recommend not using it for this purpose unless you are in
10324: an emergency. Late binding is pretty fast with this model anyway, so the
10325: benefit of using class binding is small; the cost of using class binding
10326: where it is not appropriate is reduced maintainability.
1.44 crook 10327:
1.78 anton 10328: While we are at programming style questions: You should bind
10329: selectors only to ancestor classes of the receiving object. E.g., say,
10330: you know that the receiving object is of class @code{foo} or its
10331: descendents; then you should bind only to @code{foo} and its
10332: ancestors.
1.12 anton 10333:
1.78 anton 10334: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10335: @subsubsection Method conveniences
10336: @cindex method conveniences
1.44 crook 10337:
1.78 anton 10338: In a method you usually access the receiving object pretty often. If
10339: you define the method as a plain colon definition (e.g., with
10340: @code{:noname}), you may have to do a lot of stack
10341: gymnastics. To avoid this, you can define the method with @code{m:
10342: ... ;m}. E.g., you could define the method for
10343: @code{draw}ing a @code{circle} with
1.6 pazsan 10344:
1.78 anton 10345: @cindex @code{this} usage
10346: @cindex @code{m:} usage
10347: @cindex @code{;m} usage
10348: @example
10349: m: ( x y circle -- )
10350: ( x y ) this circle-radius @@ draw-circle ;m
10351: @end example
1.6 pazsan 10352:
1.78 anton 10353: @cindex @code{exit} in @code{m: ... ;m}
10354: @cindex @code{exitm} discussion
10355: @cindex @code{catch} in @code{m: ... ;m}
10356: When this method is executed, the receiver object is removed from the
10357: stack; you can access it with @code{this} (admittedly, in this
10358: example the use of @code{m: ... ;m} offers no advantage). Note
10359: that I specify the stack effect for the whole method (i.e. including
10360: the receiver object), not just for the code between @code{m:}
10361: and @code{;m}. You cannot use @code{exit} in
10362: @code{m:...;m}; instead, use
10363: @code{exitm}.@footnote{Moreover, for any word that calls
10364: @code{catch} and was defined before loading
10365: @code{objects.fs}, you have to redefine it like I redefined
10366: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10367:
1.78 anton 10368: @cindex @code{inst-var} usage
10369: You will frequently use sequences of the form @code{this
10370: @emph{field}} (in the example above: @code{this
10371: circle-radius}). If you use the field only in this way, you can
10372: define it with @code{inst-var} and eliminate the
10373: @code{this} before the field name. E.g., the @code{circle}
10374: class above could also be defined with:
1.6 pazsan 10375:
1.78 anton 10376: @example
10377: graphical class
10378: cell% inst-var radius
1.6 pazsan 10379:
1.78 anton 10380: m: ( x y circle -- )
10381: radius @@ draw-circle ;m
10382: overrides draw
1.6 pazsan 10383:
1.78 anton 10384: m: ( n-radius circle -- )
10385: radius ! ;m
10386: overrides construct
1.6 pazsan 10387:
1.78 anton 10388: end-class circle
10389: @end example
1.6 pazsan 10390:
1.78 anton 10391: @code{radius} can only be used in @code{circle} and its
10392: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10393:
1.78 anton 10394: @cindex @code{inst-value} usage
10395: You can also define fields with @code{inst-value}, which is
10396: to @code{inst-var} what @code{value} is to
10397: @code{variable}. You can change the value of such a field with
10398: @code{[to-inst]}. E.g., we could also define the class
10399: @code{circle} like this:
1.44 crook 10400:
1.78 anton 10401: @example
10402: graphical class
10403: inst-value radius
1.6 pazsan 10404:
1.78 anton 10405: m: ( x y circle -- )
10406: radius draw-circle ;m
10407: overrides draw
1.44 crook 10408:
1.78 anton 10409: m: ( n-radius circle -- )
10410: [to-inst] radius ;m
10411: overrides construct
1.6 pazsan 10412:
1.78 anton 10413: end-class circle
10414: @end example
1.6 pazsan 10415:
1.78 anton 10416: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10417:
1.78 anton 10418: @c Finally, you can define named methods with @code{:m}. One use of this
10419: @c feature is the definition of words that occur only in one class and are
10420: @c not intended to be overridden, but which still need method context
10421: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10422: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10423:
10424:
1.78 anton 10425: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10426: @subsubsection Classes and Scoping
10427: @cindex classes and scoping
10428: @cindex scoping and classes
1.6 pazsan 10429:
1.78 anton 10430: Inheritance is frequent, unlike structure extension. This exacerbates
10431: the problem with the field name convention (@pxref{Structure Naming
10432: Convention}): One always has to remember in which class the field was
10433: originally defined; changing a part of the class structure would require
10434: changes for renaming in otherwise unaffected code.
1.6 pazsan 10435:
1.78 anton 10436: @cindex @code{inst-var} visibility
10437: @cindex @code{inst-value} visibility
10438: To solve this problem, I added a scoping mechanism (which was not in my
10439: original charter): A field defined with @code{inst-var} (or
10440: @code{inst-value}) is visible only in the class where it is defined and in
10441: the descendent classes of this class. Using such fields only makes
10442: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10443:
1.78 anton 10444: This scoping mechanism allows us to use the unadorned field name,
10445: because name clashes with unrelated words become much less likely.
1.6 pazsan 10446:
1.78 anton 10447: @cindex @code{protected} discussion
10448: @cindex @code{private} discussion
10449: Once we have this mechanism, we can also use it for controlling the
10450: visibility of other words: All words defined after
10451: @code{protected} are visible only in the current class and its
10452: descendents. @code{public} restores the compilation
10453: (i.e. @code{current}) word list that was in effect before. If you
10454: have several @code{protected}s without an intervening
10455: @code{public} or @code{set-current}, @code{public}
10456: will restore the compilation word list in effect before the first of
10457: these @code{protected}s.
1.6 pazsan 10458:
1.78 anton 10459: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10460: @subsubsection Dividing classes
10461: @cindex Dividing classes
10462: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10463:
1.78 anton 10464: You may want to do the definition of methods separate from the
10465: definition of the class, its selectors, fields, and instance variables,
10466: i.e., separate the implementation from the definition. You can do this
10467: in the following way:
1.6 pazsan 10468:
1.78 anton 10469: @example
10470: graphical class
10471: inst-value radius
10472: end-class circle
1.6 pazsan 10473:
1.78 anton 10474: ... \ do some other stuff
1.6 pazsan 10475:
1.78 anton 10476: circle methods \ now we are ready
1.44 crook 10477:
1.78 anton 10478: m: ( x y circle -- )
10479: radius draw-circle ;m
10480: overrides draw
1.6 pazsan 10481:
1.78 anton 10482: m: ( n-radius circle -- )
10483: [to-inst] radius ;m
10484: overrides construct
1.44 crook 10485:
1.78 anton 10486: end-methods
10487: @end example
1.7 pazsan 10488:
1.78 anton 10489: You can use several @code{methods}...@code{end-methods} sections. The
10490: only things you can do to the class in these sections are: defining
10491: methods, and overriding the class's selectors. You must not define new
10492: selectors or fields.
1.7 pazsan 10493:
1.78 anton 10494: Note that you often have to override a selector before using it. In
10495: particular, you usually have to override @code{construct} with a new
10496: method before you can invoke @code{heap-new} and friends. E.g., you
10497: must not create a circle before the @code{overrides construct} sequence
10498: in the example above.
1.7 pazsan 10499:
1.78 anton 10500: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10501: @subsubsection Object Interfaces
10502: @cindex object interfaces
10503: @cindex interfaces for objects
1.7 pazsan 10504:
1.78 anton 10505: In this model you can only call selectors defined in the class of the
10506: receiving objects or in one of its ancestors. If you call a selector
10507: with a receiving object that is not in one of these classes, the
10508: result is undefined; if you are lucky, the program crashes
10509: immediately.
1.7 pazsan 10510:
1.78 anton 10511: @cindex selectors common to hardly-related classes
10512: Now consider the case when you want to have a selector (or several)
10513: available in two classes: You would have to add the selector to a
10514: common ancestor class, in the worst case to @code{object}. You
10515: may not want to do this, e.g., because someone else is responsible for
10516: this ancestor class.
1.7 pazsan 10517:
1.78 anton 10518: The solution for this problem is interfaces. An interface is a
10519: collection of selectors. If a class implements an interface, the
10520: selectors become available to the class and its descendents. A class
10521: can implement an unlimited number of interfaces. For the problem
10522: discussed above, we would define an interface for the selector(s), and
10523: both classes would implement the interface.
1.7 pazsan 10524:
1.78 anton 10525: As an example, consider an interface @code{storage} for
10526: writing objects to disk and getting them back, and a class
10527: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10528:
1.78 anton 10529: @cindex @code{interface} usage
10530: @cindex @code{end-interface} usage
10531: @cindex @code{implementation} usage
10532: @example
10533: interface
10534: selector write ( file object -- )
10535: selector read1 ( file object -- )
10536: end-interface storage
1.13 pazsan 10537:
1.78 anton 10538: bar class
10539: storage implementation
1.13 pazsan 10540:
1.78 anton 10541: ... overrides write
10542: ... overrides read1
10543: ...
10544: end-class foo
10545: @end example
1.13 pazsan 10546:
1.78 anton 10547: @noindent
10548: (I would add a word @code{read} @i{( file -- object )} that uses
10549: @code{read1} internally, but that's beyond the point illustrated
10550: here.)
1.13 pazsan 10551:
1.78 anton 10552: Note that you cannot use @code{protected} in an interface; and
10553: of course you cannot define fields.
1.13 pazsan 10554:
1.78 anton 10555: In the Neon model, all selectors are available for all classes;
10556: therefore it does not need interfaces. The price you pay in this model
10557: is slower late binding, and therefore, added complexity to avoid late
10558: binding.
1.13 pazsan 10559:
1.78 anton 10560: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10561: @subsubsection @file{objects.fs} Implementation
10562: @cindex @file{objects.fs} implementation
1.13 pazsan 10563:
1.78 anton 10564: @cindex @code{object-map} discussion
10565: An object is a piece of memory, like one of the data structures
10566: described with @code{struct...end-struct}. It has a field
10567: @code{object-map} that points to the method map for the object's
10568: class.
1.13 pazsan 10569:
1.78 anton 10570: @cindex method map
10571: @cindex virtual function table
10572: The @emph{method map}@footnote{This is Self terminology; in C++
10573: terminology: virtual function table.} is an array that contains the
10574: execution tokens (@i{xt}s) of the methods for the object's class. Each
10575: selector contains an offset into a method map.
1.13 pazsan 10576:
1.78 anton 10577: @cindex @code{selector} implementation, class
10578: @code{selector} is a defining word that uses
10579: @code{CREATE} and @code{DOES>}. The body of the
10580: selector contains the offset; the @code{DOES>} action for a
10581: class selector is, basically:
1.8 pazsan 10582:
10583: @example
1.78 anton 10584: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10585: @end example
10586:
1.78 anton 10587: Since @code{object-map} is the first field of the object, it
10588: does not generate any code. As you can see, calling a selector has a
10589: small, constant cost.
1.26 crook 10590:
1.78 anton 10591: @cindex @code{current-interface} discussion
10592: @cindex class implementation and representation
10593: A class is basically a @code{struct} combined with a method
10594: map. During the class definition the alignment and size of the class
10595: are passed on the stack, just as with @code{struct}s, so
10596: @code{field} can also be used for defining class
10597: fields. However, passing more items on the stack would be
10598: inconvenient, so @code{class} builds a data structure in memory,
10599: which is accessed through the variable
10600: @code{current-interface}. After its definition is complete, the
10601: class is represented on the stack by a pointer (e.g., as parameter for
10602: a child class definition).
1.26 crook 10603:
1.78 anton 10604: A new class starts off with the alignment and size of its parent,
10605: and a copy of the parent's method map. Defining new fields extends the
10606: size and alignment; likewise, defining new selectors extends the
10607: method map. @code{overrides} just stores a new @i{xt} in the method
10608: map at the offset given by the selector.
1.13 pazsan 10609:
1.78 anton 10610: @cindex class binding, implementation
10611: Class binding just gets the @i{xt} at the offset given by the selector
10612: from the class's method map and @code{compile,}s (in the case of
10613: @code{[bind]}) it.
1.13 pazsan 10614:
1.78 anton 10615: @cindex @code{this} implementation
10616: @cindex @code{catch} and @code{this}
10617: @cindex @code{this} and @code{catch}
10618: I implemented @code{this} as a @code{value}. At the
10619: start of an @code{m:...;m} method the old @code{this} is
10620: stored to the return stack and restored at the end; and the object on
10621: the TOS is stored @code{TO this}. This technique has one
10622: disadvantage: If the user does not leave the method via
10623: @code{;m}, but via @code{throw} or @code{exit},
10624: @code{this} is not restored (and @code{exit} may
10625: crash). To deal with the @code{throw} problem, I have redefined
10626: @code{catch} to save and restore @code{this}; the same
10627: should be done with any word that can catch an exception. As for
10628: @code{exit}, I simply forbid it (as a replacement, there is
10629: @code{exitm}).
1.13 pazsan 10630:
1.78 anton 10631: @cindex @code{inst-var} implementation
10632: @code{inst-var} is just the same as @code{field}, with
10633: a different @code{DOES>} action:
1.13 pazsan 10634: @example
1.78 anton 10635: @@ this +
1.8 pazsan 10636: @end example
1.78 anton 10637: Similar for @code{inst-value}.
1.8 pazsan 10638:
1.78 anton 10639: @cindex class scoping implementation
10640: Each class also has a word list that contains the words defined with
10641: @code{inst-var} and @code{inst-value}, and its protected
10642: words. It also has a pointer to its parent. @code{class} pushes
10643: the word lists of the class and all its ancestors onto the search order stack,
10644: and @code{end-class} drops them.
1.20 pazsan 10645:
1.78 anton 10646: @cindex interface implementation
10647: An interface is like a class without fields, parent and protected
10648: words; i.e., it just has a method map. If a class implements an
10649: interface, its method map contains a pointer to the method map of the
10650: interface. The positive offsets in the map are reserved for class
10651: methods, therefore interface map pointers have negative
10652: offsets. Interfaces have offsets that are unique throughout the
10653: system, unlike class selectors, whose offsets are only unique for the
10654: classes where the selector is available (invokable).
1.20 pazsan 10655:
1.78 anton 10656: This structure means that interface selectors have to perform one
10657: indirection more than class selectors to find their method. Their body
10658: contains the interface map pointer offset in the class method map, and
10659: the method offset in the interface method map. The
10660: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10661:
10662: @example
1.78 anton 10663: ( object selector-body )
10664: 2dup selector-interface @@ ( object selector-body object interface-offset )
10665: swap object-map @@ + @@ ( object selector-body map )
10666: swap selector-offset @@ + @@ execute
1.20 pazsan 10667: @end example
10668:
1.78 anton 10669: where @code{object-map} and @code{selector-offset} are
10670: first fields and generate no code.
1.20 pazsan 10671:
1.78 anton 10672: As a concrete example, consider the following code:
1.20 pazsan 10673:
10674: @example
1.78 anton 10675: interface
10676: selector if1sel1
10677: selector if1sel2
10678: end-interface if1
1.20 pazsan 10679:
1.78 anton 10680: object class
10681: if1 implementation
10682: selector cl1sel1
10683: cell% inst-var cl1iv1
1.20 pazsan 10684:
1.78 anton 10685: ' m1 overrides construct
10686: ' m2 overrides if1sel1
10687: ' m3 overrides if1sel2
10688: ' m4 overrides cl1sel2
10689: end-class cl1
1.20 pazsan 10690:
1.78 anton 10691: create obj1 object dict-new drop
10692: create obj2 cl1 dict-new drop
10693: @end example
1.20 pazsan 10694:
1.78 anton 10695: The data structure created by this code (including the data structure
10696: for @code{object}) is shown in the
10697: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10698: @comment TODO add this diagram..
1.20 pazsan 10699:
1.78 anton 10700: @node Objects Glossary, , Objects Implementation, Objects
10701: @subsubsection @file{objects.fs} Glossary
10702: @cindex @file{objects.fs} Glossary
1.20 pazsan 10703:
10704:
1.78 anton 10705: doc---objects-bind
10706: doc---objects-<bind>
10707: doc---objects-bind'
10708: doc---objects-[bind]
10709: doc---objects-class
10710: doc---objects-class->map
10711: doc---objects-class-inst-size
10712: doc---objects-class-override!
1.79 anton 10713: doc---objects-class-previous
10714: doc---objects-class>order
1.78 anton 10715: doc---objects-construct
10716: doc---objects-current'
10717: doc---objects-[current]
10718: doc---objects-current-interface
10719: doc---objects-dict-new
10720: doc---objects-end-class
10721: doc---objects-end-class-noname
10722: doc---objects-end-interface
10723: doc---objects-end-interface-noname
10724: doc---objects-end-methods
10725: doc---objects-exitm
10726: doc---objects-heap-new
10727: doc---objects-implementation
10728: doc---objects-init-object
10729: doc---objects-inst-value
10730: doc---objects-inst-var
10731: doc---objects-interface
10732: doc---objects-m:
10733: doc---objects-:m
10734: doc---objects-;m
10735: doc---objects-method
10736: doc---objects-methods
10737: doc---objects-object
10738: doc---objects-overrides
10739: doc---objects-[parent]
10740: doc---objects-print
10741: doc---objects-protected
10742: doc---objects-public
10743: doc---objects-selector
10744: doc---objects-this
10745: doc---objects-<to-inst>
10746: doc---objects-[to-inst]
10747: doc---objects-to-this
10748: doc---objects-xt-new
1.20 pazsan 10749:
10750:
1.78 anton 10751: @c -------------------------------------------------------------
10752: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10753: @subsection The @file{oof.fs} model
10754: @cindex oof
10755: @cindex object-oriented programming
1.20 pazsan 10756:
1.78 anton 10757: @cindex @file{objects.fs}
10758: @cindex @file{oof.fs}
1.20 pazsan 10759:
1.78 anton 10760: This section describes the @file{oof.fs} package.
1.20 pazsan 10761:
1.78 anton 10762: The package described in this section has been used in bigFORTH since 1991, and
10763: used for two large applications: a chromatographic system used to
10764: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10765:
1.78 anton 10766: You can find a description (in German) of @file{oof.fs} in @cite{Object
10767: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10768: 10(2), 1994.
1.20 pazsan 10769:
1.78 anton 10770: @menu
10771: * Properties of the OOF model::
10772: * Basic OOF Usage::
10773: * The OOF base class::
10774: * Class Declaration::
10775: * Class Implementation::
10776: @end menu
1.20 pazsan 10777:
1.78 anton 10778: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10779: @subsubsection Properties of the @file{oof.fs} model
10780: @cindex @file{oof.fs} properties
1.20 pazsan 10781:
1.78 anton 10782: @itemize @bullet
10783: @item
10784: This model combines object oriented programming with information
10785: hiding. It helps you writing large application, where scoping is
10786: necessary, because it provides class-oriented scoping.
1.20 pazsan 10787:
1.78 anton 10788: @item
10789: Named objects, object pointers, and object arrays can be created,
10790: selector invocation uses the ``object selector'' syntax. Selector invocation
10791: to objects and/or selectors on the stack is a bit less convenient, but
10792: possible.
1.44 crook 10793:
1.78 anton 10794: @item
10795: Selector invocation and instance variable usage of the active object is
10796: straightforward, since both make use of the active object.
1.44 crook 10797:
1.78 anton 10798: @item
10799: Late binding is efficient and easy to use.
1.20 pazsan 10800:
1.78 anton 10801: @item
10802: State-smart objects parse selectors. However, extensibility is provided
10803: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10804:
1.78 anton 10805: @item
10806: An implementation in ANS Forth is available.
1.20 pazsan 10807:
1.78 anton 10808: @end itemize
1.23 crook 10809:
10810:
1.78 anton 10811: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10812: @subsubsection Basic @file{oof.fs} Usage
10813: @cindex @file{oof.fs} usage
1.23 crook 10814:
1.78 anton 10815: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10816:
1.78 anton 10817: You can define a class for graphical objects like this:
1.23 crook 10818:
1.78 anton 10819: @cindex @code{class} usage
10820: @cindex @code{class;} usage
10821: @cindex @code{method} usage
10822: @example
10823: object class graphical \ "object" is the parent class
1.139 pazsan 10824: method draw ( x y -- )
1.78 anton 10825: class;
10826: @end example
1.23 crook 10827:
1.78 anton 10828: This code defines a class @code{graphical} with an
10829: operation @code{draw}. We can perform the operation
10830: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10831:
1.78 anton 10832: @example
10833: 100 100 t-rex draw
10834: @end example
1.23 crook 10835:
1.78 anton 10836: @noindent
10837: where @code{t-rex} is an object or object pointer, created with e.g.
10838: @code{graphical : t-rex}.
1.23 crook 10839:
1.78 anton 10840: @cindex abstract class
10841: How do we create a graphical object? With the present definitions,
10842: we cannot create a useful graphical object. The class
10843: @code{graphical} describes graphical objects in general, but not
10844: any concrete graphical object type (C++ users would call it an
10845: @emph{abstract class}); e.g., there is no method for the selector
10846: @code{draw} in the class @code{graphical}.
1.23 crook 10847:
1.78 anton 10848: For concrete graphical objects, we define child classes of the
10849: class @code{graphical}, e.g.:
1.23 crook 10850:
1.78 anton 10851: @example
10852: graphical class circle \ "graphical" is the parent class
10853: cell var circle-radius
10854: how:
10855: : draw ( x y -- )
10856: circle-radius @@ draw-circle ;
1.23 crook 10857:
1.139 pazsan 10858: : init ( n-radius -- )
1.78 anton 10859: circle-radius ! ;
10860: class;
10861: @end example
1.1 anton 10862:
1.78 anton 10863: Here we define a class @code{circle} as a child of @code{graphical},
10864: with a field @code{circle-radius}; it defines new methods for the
10865: selectors @code{draw} and @code{init} (@code{init} is defined in
10866: @code{object}, the parent class of @code{graphical}).
1.1 anton 10867:
1.78 anton 10868: Now we can create a circle in the dictionary with:
1.1 anton 10869:
1.78 anton 10870: @example
10871: 50 circle : my-circle
10872: @end example
1.21 crook 10873:
1.78 anton 10874: @noindent
10875: @code{:} invokes @code{init}, thus initializing the field
10876: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10877: with:
1.1 anton 10878:
1.78 anton 10879: @example
10880: 100 100 my-circle draw
10881: @end example
1.1 anton 10882:
1.78 anton 10883: @cindex selector invocation, restrictions
10884: @cindex class definition, restrictions
10885: Note: You can only invoke a selector if the receiving object belongs to
10886: the class where the selector was defined or one of its descendents;
10887: e.g., you can invoke @code{draw} only for objects belonging to
10888: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10889: mechanism will check if you try to invoke a selector that is not
10890: defined in this class hierarchy, so you'll get an error at compilation
10891: time.
1.1 anton 10892:
10893:
1.78 anton 10894: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10895: @subsubsection The @file{oof.fs} base class
10896: @cindex @file{oof.fs} base class
1.1 anton 10897:
1.78 anton 10898: When you define a class, you have to specify a parent class. So how do
10899: you start defining classes? There is one class available from the start:
10900: @code{object}. You have to use it as ancestor for all classes. It is the
10901: only class that has no parent. Classes are also objects, except that
10902: they don't have instance variables; class manipulation such as
10903: inheritance or changing definitions of a class is handled through
10904: selectors of the class @code{object}.
1.1 anton 10905:
1.78 anton 10906: @code{object} provides a number of selectors:
1.1 anton 10907:
1.78 anton 10908: @itemize @bullet
10909: @item
10910: @code{class} for subclassing, @code{definitions} to add definitions
10911: later on, and @code{class?} to get type informations (is the class a
10912: subclass of the class passed on the stack?).
1.1 anton 10913:
1.78 anton 10914: doc---object-class
10915: doc---object-definitions
10916: doc---object-class?
1.1 anton 10917:
10918:
1.26 crook 10919: @item
1.78 anton 10920: @code{init} and @code{dispose} as constructor and destructor of the
10921: object. @code{init} is invocated after the object's memory is allocated,
10922: while @code{dispose} also handles deallocation. Thus if you redefine
10923: @code{dispose}, you have to call the parent's dispose with @code{super
10924: dispose}, too.
10925:
10926: doc---object-init
10927: doc---object-dispose
10928:
1.1 anton 10929:
1.26 crook 10930: @item
1.78 anton 10931: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10932: @code{[]} to create named and unnamed objects and object arrays or
10933: object pointers.
10934:
10935: doc---object-new
10936: doc---object-new[]
10937: doc---object-:
10938: doc---object-ptr
10939: doc---object-asptr
10940: doc---object-[]
10941:
1.1 anton 10942:
1.26 crook 10943: @item
1.78 anton 10944: @code{::} and @code{super} for explicit scoping. You should use explicit
10945: scoping only for super classes or classes with the same set of instance
10946: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10947:
1.78 anton 10948: doc---object-::
10949: doc---object-super
1.21 crook 10950:
10951:
1.26 crook 10952: @item
1.78 anton 10953: @code{self} to get the address of the object
1.21 crook 10954:
1.78 anton 10955: doc---object-self
1.21 crook 10956:
10957:
1.78 anton 10958: @item
10959: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10960: pointers and instance defers.
1.21 crook 10961:
1.78 anton 10962: doc---object-bind
10963: doc---object-bound
10964: doc---object-link
10965: doc---object-is
1.21 crook 10966:
10967:
1.78 anton 10968: @item
10969: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10970: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10971:
1.78 anton 10972: doc---object-'
10973: doc---object-postpone
1.21 crook 10974:
10975:
1.78 anton 10976: @item
10977: @code{with} and @code{endwith} to select the active object from the
10978: stack, and enable its scope. Using @code{with} and @code{endwith}
10979: also allows you to create code using selector @code{postpone} without being
10980: trapped by the state-smart objects.
1.21 crook 10981:
1.78 anton 10982: doc---object-with
10983: doc---object-endwith
1.21 crook 10984:
10985:
1.78 anton 10986: @end itemize
1.21 crook 10987:
1.78 anton 10988: @node Class Declaration, Class Implementation, The OOF base class, OOF
10989: @subsubsection Class Declaration
10990: @cindex class declaration
1.21 crook 10991:
1.78 anton 10992: @itemize @bullet
10993: @item
10994: Instance variables
1.21 crook 10995:
1.78 anton 10996: doc---oof-var
1.21 crook 10997:
10998:
1.78 anton 10999: @item
11000: Object pointers
1.21 crook 11001:
1.78 anton 11002: doc---oof-ptr
11003: doc---oof-asptr
1.21 crook 11004:
11005:
1.78 anton 11006: @item
11007: Instance defers
1.21 crook 11008:
1.78 anton 11009: doc---oof-defer
1.21 crook 11010:
11011:
1.78 anton 11012: @item
11013: Method selectors
1.21 crook 11014:
1.78 anton 11015: doc---oof-early
11016: doc---oof-method
1.21 crook 11017:
11018:
1.78 anton 11019: @item
11020: Class-wide variables
1.21 crook 11021:
1.78 anton 11022: doc---oof-static
1.21 crook 11023:
11024:
1.78 anton 11025: @item
11026: End declaration
1.1 anton 11027:
1.78 anton 11028: doc---oof-how:
11029: doc---oof-class;
1.21 crook 11030:
11031:
1.78 anton 11032: @end itemize
1.21 crook 11033:
1.78 anton 11034: @c -------------------------------------------------------------
11035: @node Class Implementation, , Class Declaration, OOF
11036: @subsubsection Class Implementation
11037: @cindex class implementation
1.21 crook 11038:
1.78 anton 11039: @c -------------------------------------------------------------
11040: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11041: @subsection The @file{mini-oof.fs} model
11042: @cindex mini-oof
1.21 crook 11043:
1.78 anton 11044: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11045: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11046: and reduces to the bare minimum of features. This is based on a posting
11047: of Bernd Paysan in comp.lang.forth.
1.21 crook 11048:
1.78 anton 11049: @menu
11050: * Basic Mini-OOF Usage::
11051: * Mini-OOF Example::
11052: * Mini-OOF Implementation::
11053: @end menu
1.21 crook 11054:
1.78 anton 11055: @c -------------------------------------------------------------
11056: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11057: @subsubsection Basic @file{mini-oof.fs} Usage
11058: @cindex mini-oof usage
1.21 crook 11059:
1.78 anton 11060: There is a base class (@code{class}, which allocates one cell for the
11061: object pointer) plus seven other words: to define a method, a variable,
11062: a class; to end a class, to resolve binding, to allocate an object and
11063: to compile a class method.
11064: @comment TODO better description of the last one
1.26 crook 11065:
1.21 crook 11066:
1.78 anton 11067: doc-object
11068: doc-method
11069: doc-var
11070: doc-class
11071: doc-end-class
11072: doc-defines
11073: doc-new
11074: doc-::
1.21 crook 11075:
11076:
11077:
1.78 anton 11078: @c -------------------------------------------------------------
11079: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11080: @subsubsection Mini-OOF Example
11081: @cindex mini-oof example
1.1 anton 11082:
1.78 anton 11083: A short example shows how to use this package. This example, in slightly
11084: extended form, is supplied as @file{moof-exm.fs}
11085: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11086:
1.26 crook 11087: @example
1.78 anton 11088: object class
11089: method init
11090: method draw
11091: end-class graphical
1.26 crook 11092: @end example
1.20 pazsan 11093:
1.78 anton 11094: This code defines a class @code{graphical} with an
11095: operation @code{draw}. We can perform the operation
11096: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11097:
1.26 crook 11098: @example
1.78 anton 11099: 100 100 t-rex draw
1.26 crook 11100: @end example
1.12 anton 11101:
1.78 anton 11102: where @code{t-rex} is an object or object pointer, created with e.g.
11103: @code{graphical new Constant t-rex}.
1.12 anton 11104:
1.78 anton 11105: For concrete graphical objects, we define child classes of the
11106: class @code{graphical}, e.g.:
1.12 anton 11107:
1.26 crook 11108: @example
11109: graphical class
1.78 anton 11110: cell var circle-radius
11111: end-class circle \ "graphical" is the parent class
1.12 anton 11112:
1.78 anton 11113: :noname ( x y -- )
11114: circle-radius @@ draw-circle ; circle defines draw
11115: :noname ( r -- )
11116: circle-radius ! ; circle defines init
11117: @end example
1.12 anton 11118:
1.78 anton 11119: There is no implicit init method, so we have to define one. The creation
11120: code of the object now has to call init explicitely.
1.21 crook 11121:
1.78 anton 11122: @example
11123: circle new Constant my-circle
11124: 50 my-circle init
1.12 anton 11125: @end example
11126:
1.78 anton 11127: It is also possible to add a function to create named objects with
11128: automatic call of @code{init}, given that all objects have @code{init}
11129: on the same place:
1.38 anton 11130:
1.78 anton 11131: @example
11132: : new: ( .. o "name" -- )
11133: new dup Constant init ;
11134: 80 circle new: large-circle
11135: @end example
1.12 anton 11136:
1.78 anton 11137: We can draw this new circle at (100,100) with:
1.12 anton 11138:
1.78 anton 11139: @example
11140: 100 100 my-circle draw
11141: @end example
1.12 anton 11142:
1.78 anton 11143: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11144: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11145:
1.78 anton 11146: Object-oriented systems with late binding typically use a
11147: ``vtable''-approach: the first variable in each object is a pointer to a
11148: table, which contains the methods as function pointers. The vtable
11149: may also contain other information.
1.12 anton 11150:
1.79 anton 11151: So first, let's declare selectors:
1.37 anton 11152:
11153: @example
1.79 anton 11154: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11155: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11156: @end example
1.37 anton 11157:
1.79 anton 11158: During selector declaration, the number of selectors and instance
11159: variables is on the stack (in address units). @code{method} creates one
11160: selector and increments the selector number. To execute a selector, it
1.78 anton 11161: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11162: executes the method @i{xt} stored there. Each selector takes the object
11163: it is invoked with as top of stack parameter; it passes the parameters
11164: (including the object) unchanged to the appropriate method which should
1.78 anton 11165: consume that object.
1.37 anton 11166:
1.78 anton 11167: Now, we also have to declare instance variables
1.37 anton 11168:
1.78 anton 11169: @example
1.79 anton 11170: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11171: DOES> ( o -- addr ) @@ + ;
1.37 anton 11172: @end example
11173:
1.78 anton 11174: As before, a word is created with the current offset. Instance
11175: variables can have different sizes (cells, floats, doubles, chars), so
11176: all we do is take the size and add it to the offset. If your machine
11177: has alignment restrictions, put the proper @code{aligned} or
11178: @code{faligned} before the variable, to adjust the variable
11179: offset. That's why it is on the top of stack.
1.37 anton 11180:
1.78 anton 11181: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11182:
1.78 anton 11183: @example
11184: Create object 1 cells , 2 cells ,
1.79 anton 11185: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11186: @end example
1.12 anton 11187:
1.78 anton 11188: For inheritance, the vtable of the parent object has to be
11189: copied when a new, derived class is declared. This gives all the
11190: methods of the parent class, which can be overridden, though.
1.12 anton 11191:
1.78 anton 11192: @example
1.79 anton 11193: : end-class ( class selectors vars "name" -- )
1.78 anton 11194: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11195: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11196: @end example
1.12 anton 11197:
1.78 anton 11198: The first line creates the vtable, initialized with
11199: @code{noop}s. The second line is the inheritance mechanism, it
11200: copies the xts from the parent vtable.
1.12 anton 11201:
1.78 anton 11202: We still have no way to define new methods, let's do that now:
1.12 anton 11203:
1.26 crook 11204: @example
1.79 anton 11205: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11206: @end example
1.12 anton 11207:
1.78 anton 11208: To allocate a new object, we need a word, too:
1.12 anton 11209:
1.78 anton 11210: @example
11211: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11212: @end example
11213:
1.78 anton 11214: Sometimes derived classes want to access the method of the
11215: parent object. There are two ways to achieve this with Mini-OOF:
11216: first, you could use named words, and second, you could look up the
11217: vtable of the parent object.
1.12 anton 11218:
1.78 anton 11219: @example
11220: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11221: @end example
1.12 anton 11222:
11223:
1.78 anton 11224: Nothing can be more confusing than a good example, so here is
11225: one. First let's declare a text object (called
11226: @code{button}), that stores text and position:
1.12 anton 11227:
1.78 anton 11228: @example
11229: object class
11230: cell var text
11231: cell var len
11232: cell var x
11233: cell var y
11234: method init
11235: method draw
11236: end-class button
11237: @end example
1.12 anton 11238:
1.78 anton 11239: @noindent
11240: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11241:
1.26 crook 11242: @example
1.78 anton 11243: :noname ( o -- )
11244: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11245: button defines draw
11246: :noname ( addr u o -- )
11247: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11248: button defines init
1.26 crook 11249: @end example
1.12 anton 11250:
1.78 anton 11251: @noindent
11252: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11253: new data and no new selectors:
1.78 anton 11254:
11255: @example
11256: button class
11257: end-class bold-button
1.12 anton 11258:
1.78 anton 11259: : bold 27 emit ." [1m" ;
11260: : normal 27 emit ." [0m" ;
11261: @end example
1.1 anton 11262:
1.78 anton 11263: @noindent
11264: The class @code{bold-button} has a different draw method to
11265: @code{button}, but the new method is defined in terms of the draw method
11266: for @code{button}:
1.20 pazsan 11267:
1.78 anton 11268: @example
11269: :noname bold [ button :: draw ] normal ; bold-button defines draw
11270: @end example
1.21 crook 11271:
1.78 anton 11272: @noindent
1.79 anton 11273: Finally, create two objects and apply selectors:
1.21 crook 11274:
1.26 crook 11275: @example
1.78 anton 11276: button new Constant foo
11277: s" thin foo" foo init
11278: page
11279: foo draw
11280: bold-button new Constant bar
11281: s" fat bar" bar init
11282: 1 bar y !
11283: bar draw
1.26 crook 11284: @end example
1.21 crook 11285:
11286:
1.78 anton 11287: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11288: @subsection Comparison with other object models
11289: @cindex comparison of object models
11290: @cindex object models, comparison
11291:
11292: Many object-oriented Forth extensions have been proposed (@cite{A survey
11293: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11294: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11295: relation of the object models described here to two well-known and two
11296: closely-related (by the use of method maps) models. Andras Zsoter
11297: helped us with this section.
11298:
11299: @cindex Neon model
11300: The most popular model currently seems to be the Neon model (see
11301: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11302: 1997) by Andrew McKewan) but this model has a number of limitations
11303: @footnote{A longer version of this critique can be
11304: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11305: Dimensions, May 1997) by Anton Ertl.}:
11306:
11307: @itemize @bullet
11308: @item
11309: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11310: to pass objects on the stack.
1.21 crook 11311:
1.78 anton 11312: @item
11313: It requires that the selector parses the input stream (at
1.79 anton 11314: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11315: hard to find.
1.21 crook 11316:
1.78 anton 11317: @item
1.79 anton 11318: It allows using every selector on every object; this eliminates the
11319: need for interfaces, but makes it harder to create efficient
11320: implementations.
1.78 anton 11321: @end itemize
1.21 crook 11322:
1.78 anton 11323: @cindex Pountain's object-oriented model
11324: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11325: Press, London, 1987) by Dick Pountain. However, it is not really about
11326: object-oriented programming, because it hardly deals with late
11327: binding. Instead, it focuses on features like information hiding and
11328: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11329:
1.78 anton 11330: @cindex Zsoter's object-oriented model
1.79 anton 11331: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11332: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11333: describes a model that makes heavy use of an active object (like
11334: @code{this} in @file{objects.fs}): The active object is not only used
11335: for accessing all fields, but also specifies the receiving object of
11336: every selector invocation; you have to change the active object
11337: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11338: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11339: the method entry point is unnecessary with Zsoter's model, because the
11340: receiving object is the active object already. On the other hand, the
11341: explicit change is absolutely necessary in that model, because otherwise
11342: no one could ever change the active object. An ANS Forth implementation
11343: of this model is available through
11344: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11345:
1.78 anton 11346: @cindex @file{oof.fs}, differences to other models
11347: The @file{oof.fs} model combines information hiding and overloading
11348: resolution (by keeping names in various word lists) with object-oriented
11349: programming. It sets the active object implicitly on method entry, but
11350: also allows explicit changing (with @code{>o...o>} or with
11351: @code{with...endwith}). It uses parsing and state-smart objects and
11352: classes for resolving overloading and for early binding: the object or
11353: class parses the selector and determines the method from this. If the
11354: selector is not parsed by an object or class, it performs a call to the
11355: selector for the active object (late binding), like Zsoter's model.
11356: Fields are always accessed through the active object. The big
11357: disadvantage of this model is the parsing and the state-smartness, which
11358: reduces extensibility and increases the opportunities for subtle bugs;
11359: essentially, you are only safe if you never tick or @code{postpone} an
11360: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11361:
1.78 anton 11362: @cindex @file{mini-oof.fs}, differences to other models
11363: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11364: version of the @file{objects.fs} model, but syntactically it is a
11365: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11366:
11367:
1.78 anton 11368: @c -------------------------------------------------------------
11369: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11370: @section Programming Tools
11371: @cindex programming tools
1.21 crook 11372:
1.78 anton 11373: @c !! move this and assembler down below OO stuff.
1.21 crook 11374:
1.78 anton 11375: @menu
11376: * Examining::
11377: * Forgetting words::
11378: * Debugging:: Simple and quick.
11379: * Assertions:: Making your programs self-checking.
11380: * Singlestep Debugger:: Executing your program word by word.
11381: @end menu
1.21 crook 11382:
1.78 anton 11383: @node Examining, Forgetting words, Programming Tools, Programming Tools
11384: @subsection Examining data and code
11385: @cindex examining data and code
11386: @cindex data examination
11387: @cindex code examination
1.44 crook 11388:
1.78 anton 11389: The following words inspect the stack non-destructively:
1.21 crook 11390:
1.78 anton 11391: doc-.s
11392: doc-f.s
1.44 crook 11393:
1.78 anton 11394: There is a word @code{.r} but it does @i{not} display the return stack!
11395: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11396:
1.78 anton 11397: doc-depth
11398: doc-fdepth
11399: doc-clearstack
1.124 anton 11400: doc-clearstacks
1.21 crook 11401:
1.78 anton 11402: The following words inspect memory.
1.21 crook 11403:
1.78 anton 11404: doc-?
11405: doc-dump
1.21 crook 11406:
1.78 anton 11407: And finally, @code{see} allows to inspect code:
1.21 crook 11408:
1.78 anton 11409: doc-see
11410: doc-xt-see
1.111 anton 11411: doc-simple-see
11412: doc-simple-see-range
1.21 crook 11413:
1.78 anton 11414: @node Forgetting words, Debugging, Examining, Programming Tools
11415: @subsection Forgetting words
11416: @cindex words, forgetting
11417: @cindex forgeting words
1.21 crook 11418:
1.78 anton 11419: @c anton: other, maybe better places for this subsection: Defining Words;
11420: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11421:
1.78 anton 11422: Forth allows you to forget words (and everything that was alloted in the
11423: dictonary after them) in a LIFO manner.
1.21 crook 11424:
1.78 anton 11425: doc-marker
1.21 crook 11426:
1.78 anton 11427: The most common use of this feature is during progam development: when
11428: you change a source file, forget all the words it defined and load it
11429: again (since you also forget everything defined after the source file
11430: was loaded, you have to reload that, too). Note that effects like
11431: storing to variables and destroyed system words are not undone when you
11432: forget words. With a system like Gforth, that is fast enough at
11433: starting up and compiling, I find it more convenient to exit and restart
11434: Gforth, as this gives me a clean slate.
1.21 crook 11435:
1.78 anton 11436: Here's an example of using @code{marker} at the start of a source file
11437: that you are debugging; it ensures that you only ever have one copy of
11438: the file's definitions compiled at any time:
1.21 crook 11439:
1.78 anton 11440: @example
11441: [IFDEF] my-code
11442: my-code
11443: [ENDIF]
1.26 crook 11444:
1.78 anton 11445: marker my-code
11446: init-included-files
1.21 crook 11447:
1.78 anton 11448: \ .. definitions start here
11449: \ .
11450: \ .
11451: \ end
11452: @end example
1.21 crook 11453:
1.26 crook 11454:
1.78 anton 11455: @node Debugging, Assertions, Forgetting words, Programming Tools
11456: @subsection Debugging
11457: @cindex debugging
1.21 crook 11458:
1.78 anton 11459: Languages with a slow edit/compile/link/test development loop tend to
11460: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11461:
1.78 anton 11462: A much better (faster) way in fast-compiling languages is to add
11463: printing code at well-selected places, let the program run, look at
11464: the output, see where things went wrong, add more printing code, etc.,
11465: until the bug is found.
1.21 crook 11466:
1.78 anton 11467: The simple debugging aids provided in @file{debugs.fs}
11468: are meant to support this style of debugging.
1.21 crook 11469:
1.78 anton 11470: The word @code{~~} prints debugging information (by default the source
11471: location and the stack contents). It is easy to insert. If you use Emacs
11472: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11473: query-replace them with nothing). The deferred words
1.101 anton 11474: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11475: @code{~~}. The default source location output format works well with
11476: Emacs' compilation mode, so you can step through the program at the
11477: source level using @kbd{C-x `} (the advantage over a stepping debugger
11478: is that you can step in any direction and you know where the crash has
11479: happened or where the strange data has occurred).
1.21 crook 11480:
1.78 anton 11481: doc-~~
11482: doc-printdebugdata
1.101 anton 11483: doc-.debugline
1.21 crook 11484:
1.106 anton 11485: @cindex filenames in @code{~~} output
11486: @code{~~} (and assertions) will usually print the wrong file name if a
11487: marker is executed in the same file after their occurance. They will
11488: print @samp{*somewhere*} as file name if a marker is executed in the
11489: same file before their occurance.
11490:
11491:
1.78 anton 11492: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11493: @subsection Assertions
11494: @cindex assertions
1.21 crook 11495:
1.78 anton 11496: It is a good idea to make your programs self-checking, especially if you
11497: make an assumption that may become invalid during maintenance (for
11498: example, that a certain field of a data structure is never zero). Gforth
11499: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11500:
11501: @example
1.78 anton 11502: assert( @i{flag} )
1.26 crook 11503: @end example
11504:
1.78 anton 11505: The code between @code{assert(} and @code{)} should compute a flag, that
11506: should be true if everything is alright and false otherwise. It should
11507: not change anything else on the stack. The overall stack effect of the
11508: assertion is @code{( -- )}. E.g.
1.21 crook 11509:
1.26 crook 11510: @example
1.78 anton 11511: assert( 1 1 + 2 = ) \ what we learn in school
11512: assert( dup 0<> ) \ assert that the top of stack is not zero
11513: assert( false ) \ this code should not be reached
1.21 crook 11514: @end example
11515:
1.78 anton 11516: The need for assertions is different at different times. During
11517: debugging, we want more checking, in production we sometimes care more
11518: for speed. Therefore, assertions can be turned off, i.e., the assertion
11519: becomes a comment. Depending on the importance of an assertion and the
11520: time it takes to check it, you may want to turn off some assertions and
11521: keep others turned on. Gforth provides several levels of assertions for
11522: this purpose:
11523:
11524:
11525: doc-assert0(
11526: doc-assert1(
11527: doc-assert2(
11528: doc-assert3(
11529: doc-assert(
11530: doc-)
1.21 crook 11531:
11532:
1.78 anton 11533: The variable @code{assert-level} specifies the highest assertions that
11534: are turned on. I.e., at the default @code{assert-level} of one,
11535: @code{assert0(} and @code{assert1(} assertions perform checking, while
11536: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11537:
1.78 anton 11538: The value of @code{assert-level} is evaluated at compile-time, not at
11539: run-time. Therefore you cannot turn assertions on or off at run-time;
11540: you have to set the @code{assert-level} appropriately before compiling a
11541: piece of code. You can compile different pieces of code at different
11542: @code{assert-level}s (e.g., a trusted library at level 1 and
11543: newly-written code at level 3).
1.26 crook 11544:
11545:
1.78 anton 11546: doc-assert-level
1.26 crook 11547:
11548:
1.78 anton 11549: If an assertion fails, a message compatible with Emacs' compilation mode
11550: is produced and the execution is aborted (currently with @code{ABORT"}.
11551: If there is interest, we will introduce a special throw code. But if you
11552: intend to @code{catch} a specific condition, using @code{throw} is
11553: probably more appropriate than an assertion).
1.106 anton 11554:
11555: @cindex filenames in assertion output
11556: Assertions (and @code{~~}) will usually print the wrong file name if a
11557: marker is executed in the same file after their occurance. They will
11558: print @samp{*somewhere*} as file name if a marker is executed in the
11559: same file before their occurance.
1.44 crook 11560:
1.78 anton 11561: Definitions in ANS Forth for these assertion words are provided
11562: in @file{compat/assert.fs}.
1.26 crook 11563:
1.44 crook 11564:
1.78 anton 11565: @node Singlestep Debugger, , Assertions, Programming Tools
11566: @subsection Singlestep Debugger
11567: @cindex singlestep Debugger
11568: @cindex debugging Singlestep
1.44 crook 11569:
1.112 anton 11570: The singlestep debugger does not work in this release.
11571:
1.78 anton 11572: When you create a new word there's often the need to check whether it
11573: behaves correctly or not. You can do this by typing @code{dbg
11574: badword}. A debug session might look like this:
1.26 crook 11575:
1.78 anton 11576: @example
11577: : badword 0 DO i . LOOP ; ok
11578: 2 dbg badword
11579: : badword
11580: Scanning code...
1.44 crook 11581:
1.78 anton 11582: Nesting debugger ready!
1.44 crook 11583:
1.78 anton 11584: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11585: 400D4740 8049F68 DO -> [ 0 ]
11586: 400D4744 804A0C8 i -> [ 1 ] 00000
11587: 400D4748 400C5E60 . -> 0 [ 0 ]
11588: 400D474C 8049D0C LOOP -> [ 0 ]
11589: 400D4744 804A0C8 i -> [ 1 ] 00001
11590: 400D4748 400C5E60 . -> 1 [ 0 ]
11591: 400D474C 8049D0C LOOP -> [ 0 ]
11592: 400D4758 804B384 ; -> ok
11593: @end example
1.21 crook 11594:
1.78 anton 11595: Each line displayed is one step. You always have to hit return to
11596: execute the next word that is displayed. If you don't want to execute
11597: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11598: an overview what keys are available:
1.44 crook 11599:
1.78 anton 11600: @table @i
1.44 crook 11601:
1.78 anton 11602: @item @key{RET}
11603: Next; Execute the next word.
1.21 crook 11604:
1.78 anton 11605: @item n
11606: Nest; Single step through next word.
1.44 crook 11607:
1.78 anton 11608: @item u
11609: Unnest; Stop debugging and execute rest of word. If we got to this word
11610: with nest, continue debugging with the calling word.
1.44 crook 11611:
1.78 anton 11612: @item d
11613: Done; Stop debugging and execute rest.
1.21 crook 11614:
1.78 anton 11615: @item s
11616: Stop; Abort immediately.
1.44 crook 11617:
1.78 anton 11618: @end table
1.44 crook 11619:
1.78 anton 11620: Debugging large application with this mechanism is very difficult, because
11621: you have to nest very deeply into the program before the interesting part
11622: begins. This takes a lot of time.
1.26 crook 11623:
1.78 anton 11624: To do it more directly put a @code{BREAK:} command into your source code.
11625: When program execution reaches @code{BREAK:} the single step debugger is
11626: invoked and you have all the features described above.
1.44 crook 11627:
1.78 anton 11628: If you have more than one part to debug it is useful to know where the
11629: program has stopped at the moment. You can do this by the
11630: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11631: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11632:
1.26 crook 11633:
1.78 anton 11634: doc-dbg
11635: doc-break:
11636: doc-break"
1.44 crook 11637:
11638:
1.26 crook 11639:
1.78 anton 11640: @c -------------------------------------------------------------
11641: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11642: @section Assembler and Code Words
11643: @cindex assembler
11644: @cindex code words
1.44 crook 11645:
1.78 anton 11646: @menu
11647: * Code and ;code::
11648: * Common Assembler:: Assembler Syntax
11649: * Common Disassembler::
11650: * 386 Assembler:: Deviations and special cases
11651: * Alpha Assembler:: Deviations and special cases
11652: * MIPS assembler:: Deviations and special cases
11653: * Other assemblers:: How to write them
11654: @end menu
1.21 crook 11655:
1.78 anton 11656: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11657: @subsection @code{Code} and @code{;code}
1.26 crook 11658:
1.78 anton 11659: Gforth provides some words for defining primitives (words written in
11660: machine code), and for defining the machine-code equivalent of
11661: @code{DOES>}-based defining words. However, the machine-independent
11662: nature of Gforth poses a few problems: First of all, Gforth runs on
11663: several architectures, so it can provide no standard assembler. What's
11664: worse is that the register allocation not only depends on the processor,
11665: but also on the @code{gcc} version and options used.
1.44 crook 11666:
1.78 anton 11667: The words that Gforth offers encapsulate some system dependences (e.g.,
11668: the header structure), so a system-independent assembler may be used in
11669: Gforth. If you do not have an assembler, you can compile machine code
11670: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11671: because these words emit stuff in @i{data} space; it works because
11672: Gforth has unified code/data spaces. Assembler isn't likely to be
11673: portable anyway.}.
1.21 crook 11674:
1.44 crook 11675:
1.78 anton 11676: doc-assembler
11677: doc-init-asm
11678: doc-code
11679: doc-end-code
11680: doc-;code
11681: doc-flush-icache
1.44 crook 11682:
1.21 crook 11683:
1.78 anton 11684: If @code{flush-icache} does not work correctly, @code{code} words
11685: etc. will not work (reliably), either.
1.44 crook 11686:
1.78 anton 11687: The typical usage of these @code{code} words can be shown most easily by
11688: analogy to the equivalent high-level defining words:
1.44 crook 11689:
1.78 anton 11690: @example
11691: : foo code foo
11692: <high-level Forth words> <assembler>
11693: ; end-code
11694:
11695: : bar : bar
11696: <high-level Forth words> <high-level Forth words>
11697: CREATE CREATE
11698: <high-level Forth words> <high-level Forth words>
11699: DOES> ;code
11700: <high-level Forth words> <assembler>
11701: ; end-code
11702: @end example
1.21 crook 11703:
1.78 anton 11704: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11705:
1.78 anton 11706: @cindex registers of the inner interpreter
11707: In the assembly code you will want to refer to the inner interpreter's
11708: registers (e.g., the data stack pointer) and you may want to use other
11709: registers for temporary storage. Unfortunately, the register allocation
11710: is installation-dependent.
1.44 crook 11711:
1.78 anton 11712: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11713: (return stack pointer) may be in different places in @code{gforth} and
11714: @code{gforth-fast}, or different installations. This means that you
11715: cannot write a @code{NEXT} routine that works reliably on both versions
11716: or different installations; so for doing @code{NEXT}, I recommend
11717: jumping to @code{' noop >code-address}, which contains nothing but a
11718: @code{NEXT}.
1.21 crook 11719:
1.78 anton 11720: For general accesses to the inner interpreter's registers, the easiest
11721: solution is to use explicit register declarations (@pxref{Explicit Reg
11722: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11723: all of the inner interpreter's registers: You have to compile Gforth
11724: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11725: the appropriate declarations must be present in the @code{machine.h}
11726: file (see @code{mips.h} for an example; you can find a full list of all
11727: declarable register symbols with @code{grep register engine.c}). If you
11728: give explicit registers to all variables that are declared at the
11729: beginning of @code{engine()}, you should be able to use the other
11730: caller-saved registers for temporary storage. Alternatively, you can use
11731: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11732: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11733: reserve a register (however, this restriction on register allocation may
11734: slow Gforth significantly).
1.44 crook 11735:
1.78 anton 11736: If this solution is not viable (e.g., because @code{gcc} does not allow
11737: you to explicitly declare all the registers you need), you have to find
11738: out by looking at the code where the inner interpreter's registers
11739: reside and which registers can be used for temporary storage. You can
11740: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11741:
1.78 anton 11742: In any case, it is good practice to abstract your assembly code from the
11743: actual register allocation. E.g., if the data stack pointer resides in
11744: register @code{$17}, create an alias for this register called @code{sp},
11745: and use that in your assembly code.
1.21 crook 11746:
1.78 anton 11747: @cindex code words, portable
11748: Another option for implementing normal and defining words efficiently
11749: is to add the desired functionality to the source of Gforth. For normal
11750: words you just have to edit @file{primitives} (@pxref{Automatic
11751: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11752: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11753: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11754:
1.78 anton 11755: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11756: @subsection Common Assembler
1.44 crook 11757:
1.78 anton 11758: The assemblers in Gforth generally use a postfix syntax, i.e., the
11759: instruction name follows the operands.
1.21 crook 11760:
1.78 anton 11761: The operands are passed in the usual order (the same that is used in the
11762: manual of the architecture). Since they all are Forth words, they have
11763: to be separated by spaces; you can also use Forth words to compute the
11764: operands.
1.44 crook 11765:
1.78 anton 11766: The instruction names usually end with a @code{,}. This makes it easier
11767: to visually separate instructions if you put several of them on one
11768: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11769:
1.78 anton 11770: Registers are usually specified by number; e.g., (decimal) @code{11}
11771: specifies registers R11 and F11 on the Alpha architecture (which one,
11772: depends on the instruction). The usual names are also available, e.g.,
11773: @code{s2} for R11 on Alpha.
1.21 crook 11774:
1.78 anton 11775: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11776: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11777: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11778: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11779: conditions are specified in a way specific to each assembler.
1.1 anton 11780:
1.78 anton 11781: Note that the register assignments of the Gforth engine can change
11782: between Gforth versions, or even between different compilations of the
11783: same Gforth version (e.g., if you use a different GCC version). So if
11784: you want to refer to Gforth's registers (e.g., the stack pointer or
11785: TOS), I recommend defining your own words for refering to these
11786: registers, and using them later on; then you can easily adapt to a
11787: changed register assignment. The stability of the register assignment
11788: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11789:
1.100 anton 11790: The most common use of these registers is to dispatch to the next word
11791: (the @code{next} routine). A portable way to do this is to jump to
11792: @code{' noop >code-address} (of course, this is less efficient than
11793: integrating the @code{next} code and scheduling it well).
1.1 anton 11794:
1.96 anton 11795: Another difference between Gforth version is that the top of stack is
11796: kept in memory in @code{gforth} and, on most platforms, in a register in
11797: @code{gforth-fast}.
11798:
1.78 anton 11799: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11800: @subsection Common Disassembler
1.127 anton 11801: @cindex disassembler, general
11802: @cindex gdb disassembler
1.1 anton 11803:
1.78 anton 11804: You can disassemble a @code{code} word with @code{see}
11805: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11806:
1.127 anton 11807: doc-discode
1.44 crook 11808:
1.127 anton 11809: There are two kinds of disassembler for Gforth: The Forth disassembler
11810: (available on some CPUs) and the gdb disassembler (available on
11811: platforms with @command{gdb} and @command{mktemp}). If both are
11812: available, the Forth disassembler is used by default. If you prefer
11813: the gdb disassembler, say
11814:
11815: @example
11816: ' disasm-gdb is discode
11817: @end example
11818:
11819: If neither is available, @code{discode} performs @code{dump}.
11820:
11821: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11822: assembler (i.e., same syntax, etc.). It also includes additional
11823: information in comments. In particular, the address of the instruction
11824: is given in a comment before the instruction.
1.1 anton 11825:
1.127 anton 11826: The gdb disassembler produces output in the same format as the gdb
11827: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11828: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11829: the 386 and AMD64 architectures).
11830:
1.78 anton 11831: @code{See} may display more or less than the actual code of the word,
11832: because the recognition of the end of the code is unreliable. You can
1.127 anton 11833: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11834: the code word is not immediately followed by a named word. If you have
1.116 anton 11835: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11836: to ensure that the end is recognized.
1.21 crook 11837:
1.78 anton 11838: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11839: @subsection 386 Assembler
1.44 crook 11840:
1.78 anton 11841: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11842: available under GPL, and originally part of bigFORTH.
1.21 crook 11843:
1.78 anton 11844: The 386 disassembler included in Gforth was written by Andrew McKewan
11845: and is in the public domain.
1.21 crook 11846:
1.91 anton 11847: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11848:
1.78 anton 11849: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11850:
1.78 anton 11851: The assembler includes all instruction of the Athlon, i.e. 486 core
11852: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11853: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11854: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11855:
1.78 anton 11856: There are several prefixes to switch between different operation sizes,
11857: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11858: double-word accesses. Addressing modes can be switched with @code{.wa}
11859: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11860: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11861:
1.78 anton 11862: For floating point operations, the prefixes are @code{.fs} (IEEE
11863: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11864: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11865:
1.78 anton 11866: The MMX opcodes don't have size prefixes, they are spelled out like in
11867: the Intel assembler. Instead of move from and to memory, there are
11868: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11869:
1.78 anton 11870: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11871: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11872: e.g., @code{3 #}. Here are some examples of addressing modes in various
11873: syntaxes:
1.21 crook 11874:
1.26 crook 11875: @example
1.91 anton 11876: Gforth Intel (NASM) AT&T (gas) Name
11877: .w ax ax %ax register (16 bit)
11878: ax eax %eax register (32 bit)
11879: 3 # offset 3 $3 immediate
11880: 1000 #) byte ptr 1000 1000 displacement
11881: bx ) [ebx] (%ebx) base
11882: 100 di d) 100[edi] 100(%edi) base+displacement
11883: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11884: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11885: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11886: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11887: @end example
11888:
11889: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11890: @code{DI)} to enforce 32-bit displacement fields (useful for
11891: later patching).
1.21 crook 11892:
1.78 anton 11893: Some example of instructions are:
1.1 anton 11894:
11895: @example
1.78 anton 11896: ax bx mov \ move ebx,eax
11897: 3 # ax mov \ mov eax,3
1.137 pazsan 11898: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 11899: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11900: .w ax bx mov \ mov bx,ax
1.1 anton 11901: @end example
11902:
1.78 anton 11903: The following forms are supported for binary instructions:
1.1 anton 11904:
11905: @example
1.78 anton 11906: <reg> <reg> <inst>
11907: <n> # <reg> <inst>
11908: <mem> <reg> <inst>
11909: <reg> <mem> <inst>
1.136 pazsan 11910: <n> # <mem> <inst>
1.1 anton 11911: @end example
11912:
1.136 pazsan 11913: The shift/rotate syntax is:
1.1 anton 11914:
1.26 crook 11915: @example
1.78 anton 11916: <reg/mem> 1 # shl \ shortens to shift without immediate
11917: <reg/mem> 4 # shl
11918: <reg/mem> cl shl
1.26 crook 11919: @end example
1.1 anton 11920:
1.78 anton 11921: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11922: the byte version.
1.1 anton 11923:
1.78 anton 11924: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11925: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11926: pc < >= <= >}. (Note that most of these words shadow some Forth words
11927: when @code{assembler} is in front of @code{forth} in the search path,
11928: e.g., in @code{code} words). Currently the control structure words use
11929: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11930: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11931:
1.78 anton 11932: Here is an example of a @code{code} word (assumes that the stack pointer
11933: is in esi and the TOS is in ebx):
1.21 crook 11934:
1.26 crook 11935: @example
1.78 anton 11936: code my+ ( n1 n2 -- n )
11937: 4 si D) bx add
11938: 4 # si add
11939: Next
11940: end-code
1.26 crook 11941: @end example
1.21 crook 11942:
1.78 anton 11943: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11944: @subsection Alpha Assembler
1.21 crook 11945:
1.78 anton 11946: The Alpha assembler and disassembler were originally written by Bernd
11947: Thallner.
1.26 crook 11948:
1.78 anton 11949: The register names @code{a0}--@code{a5} are not available to avoid
11950: shadowing hex numbers.
1.2 jwilke 11951:
1.78 anton 11952: Immediate forms of arithmetic instructions are distinguished by a
11953: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11954: does not count as arithmetic instruction).
1.2 jwilke 11955:
1.78 anton 11956: You have to specify all operands to an instruction, even those that
11957: other assemblers consider optional, e.g., the destination register for
11958: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11959:
1.78 anton 11960: You can specify conditions for @code{if,} by removing the first @code{b}
11961: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11962:
1.26 crook 11963: @example
1.78 anton 11964: 11 fgt if, \ if F11>0e
11965: ...
11966: endif,
1.26 crook 11967: @end example
1.2 jwilke 11968:
1.78 anton 11969: @code{fbgt,} gives @code{fgt}.
11970:
11971: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11972: @subsection MIPS assembler
1.2 jwilke 11973:
1.78 anton 11974: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11975:
1.78 anton 11976: Currently the assembler and disassembler only cover the MIPS-I
11977: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11978:
1.78 anton 11979: The register names @code{$a0}--@code{$a3} are not available to avoid
11980: shadowing hex numbers.
1.2 jwilke 11981:
1.78 anton 11982: Because there is no way to distinguish registers from immediate values,
11983: you have to explicitly use the immediate forms of instructions, i.e.,
11984: @code{addiu,}, not just @code{addu,} (@command{as} does this
11985: implicitly).
1.2 jwilke 11986:
1.78 anton 11987: If the architecture manual specifies several formats for the instruction
11988: (e.g., for @code{jalr,}), you usually have to use the one with more
11989: arguments (i.e., two for @code{jalr,}). When in doubt, see
11990: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11991:
1.78 anton 11992: Branches and jumps in the MIPS architecture have a delay slot. You have
11993: to fill it yourself (the simplest way is to use @code{nop,}), the
11994: assembler does not do it for you (unlike @command{as}). Even
11995: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11996: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11997: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11998:
1.78 anton 11999: Note that you must not put branches, jumps, or @code{li,} into the delay
12000: slot: @code{li,} may expand to several instructions, and control flow
12001: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12002:
1.78 anton 12003: For branches the argument specifying the target is a relative address;
12004: You have to add the address of the delay slot to get the absolute
12005: address.
1.1 anton 12006:
1.78 anton 12007: The MIPS architecture also has load delay slots and restrictions on
12008: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12009: yourself to satisfy these restrictions, the assembler does not do it for
12010: you.
1.1 anton 12011:
1.78 anton 12012: You can specify the conditions for @code{if,} etc. by taking a
12013: conditional branch and leaving away the @code{b} at the start and the
12014: @code{,} at the end. E.g.,
1.1 anton 12015:
1.26 crook 12016: @example
1.78 anton 12017: 4 5 eq if,
12018: ... \ do something if $4 equals $5
12019: then,
1.26 crook 12020: @end example
1.1 anton 12021:
1.78 anton 12022: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12023: @subsection Other assemblers
12024:
12025: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12026: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12027: an assembler already. If you are writing them from scratch, please use
12028: a similar syntax style as the one we use (i.e., postfix, commas at the
12029: end of the instruction names, @pxref{Common Assembler}); make the output
12030: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12031: similar to the style we used.
12032:
12033: Hints on implementation: The most important part is to have a good test
12034: suite that contains all instructions. Once you have that, the rest is
12035: easy. For actual coding you can take a look at
12036: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12037: the assembler and disassembler, avoiding redundancy and some potential
12038: bugs. You can also look at that file (and @pxref{Advanced does> usage
12039: example}) to get ideas how to factor a disassembler.
12040:
12041: Start with the disassembler, because it's easier to reuse data from the
12042: disassembler for the assembler than the other way round.
1.1 anton 12043:
1.78 anton 12044: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12045: how simple it can be.
1.1 anton 12046:
1.78 anton 12047: @c -------------------------------------------------------------
12048: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12049: @section Threading Words
12050: @cindex threading words
1.1 anton 12051:
1.78 anton 12052: @cindex code address
12053: These words provide access to code addresses and other threading stuff
12054: in Gforth (and, possibly, other interpretive Forths). It more or less
12055: abstracts away the differences between direct and indirect threading
12056: (and, for direct threading, the machine dependences). However, at
12057: present this wordset is still incomplete. It is also pretty low-level;
12058: some day it will hopefully be made unnecessary by an internals wordset
12059: that abstracts implementation details away completely.
1.1 anton 12060:
1.78 anton 12061: The terminology used here stems from indirect threaded Forth systems; in
12062: such a system, the XT of a word is represented by the CFA (code field
12063: address) of a word; the CFA points to a cell that contains the code
12064: address. The code address is the address of some machine code that
12065: performs the run-time action of invoking the word (e.g., the
12066: @code{dovar:} routine pushes the address of the body of the word (a
12067: variable) on the stack
12068: ).
1.1 anton 12069:
1.78 anton 12070: @cindex code address
12071: @cindex code field address
12072: In an indirect threaded Forth, you can get the code address of @i{name}
12073: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12074: >code-address}, independent of the threading method.
1.1 anton 12075:
1.78 anton 12076: doc-threading-method
12077: doc->code-address
12078: doc-code-address!
1.1 anton 12079:
1.78 anton 12080: @cindex @code{does>}-handler
12081: @cindex @code{does>}-code
12082: For a word defined with @code{DOES>}, the code address usually points to
12083: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12084: routine (in Gforth on some platforms, it can also point to the dodoes
12085: routine itself). What you are typically interested in, though, is
12086: whether a word is a @code{DOES>}-defined word, and what Forth code it
12087: executes; @code{>does-code} tells you that.
1.1 anton 12088:
1.78 anton 12089: doc->does-code
1.1 anton 12090:
1.78 anton 12091: To create a @code{DOES>}-defined word with the following basic words,
12092: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12093: @code{/does-handler} aus behind you have to place your executable Forth
12094: code. Finally you have to create a word and modify its behaviour with
12095: @code{does-handler!}.
1.1 anton 12096:
1.78 anton 12097: doc-does-code!
12098: doc-does-handler!
12099: doc-/does-handler
1.1 anton 12100:
1.78 anton 12101: The code addresses produced by various defining words are produced by
12102: the following words:
1.1 anton 12103:
1.78 anton 12104: doc-docol:
12105: doc-docon:
12106: doc-dovar:
12107: doc-douser:
12108: doc-dodefer:
12109: doc-dofield:
1.1 anton 12110:
1.99 anton 12111: @cindex definer
12112: The following two words generalize @code{>code-address},
12113: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12114:
12115: doc->definer
12116: doc-definer!
12117:
1.26 crook 12118: @c -------------------------------------------------------------
1.78 anton 12119: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12120: @section Passing Commands to the Operating System
12121: @cindex operating system - passing commands
12122: @cindex shell commands
12123:
12124: Gforth allows you to pass an arbitrary string to the host operating
12125: system shell (if such a thing exists) for execution.
12126:
12127: doc-sh
12128: doc-system
12129: doc-$?
1.23 crook 12130: doc-getenv
1.44 crook 12131:
1.26 crook 12132: @c -------------------------------------------------------------
1.47 crook 12133: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12134: @section Keeping track of Time
12135: @cindex time-related words
12136:
12137: doc-ms
12138: doc-time&date
1.79 anton 12139: doc-utime
12140: doc-cputime
1.47 crook 12141:
12142:
12143: @c -------------------------------------------------------------
12144: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12145: @section Miscellaneous Words
12146: @cindex miscellaneous words
12147:
1.29 crook 12148: @comment TODO find homes for these
12149:
1.26 crook 12150: These section lists the ANS Forth words that are not documented
1.21 crook 12151: elsewhere in this manual. Ultimately, they all need proper homes.
12152:
1.68 anton 12153: doc-quit
1.44 crook 12154:
1.26 crook 12155: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12156: (@pxref{ANS conformance}):
1.21 crook 12157:
12158: @code{EDITOR}
12159: @code{EMIT?}
12160: @code{FORGET}
12161:
1.24 anton 12162: @c ******************************************************************
12163: @node Error messages, Tools, Words, Top
12164: @chapter Error messages
12165: @cindex error messages
12166: @cindex backtrace
12167:
12168: A typical Gforth error message looks like this:
12169:
12170: @example
1.86 anton 12171: in file included from \evaluated string/:-1
1.24 anton 12172: in file included from ./yyy.fs:1
12173: ./xxx.fs:4: Invalid memory address
1.134 anton 12174: >>>bar<<<
1.79 anton 12175: Backtrace:
1.25 anton 12176: $400E664C @@
12177: $400E6664 foo
1.24 anton 12178: @end example
12179:
12180: The message identifying the error is @code{Invalid memory address}. The
12181: error happened when text-interpreting line 4 of the file
12182: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12183: word on the line where the error happened, is pointed out (with
1.134 anton 12184: @code{>>>} and @code{<<<}).
1.24 anton 12185:
12186: The file containing the error was included in line 1 of @file{./yyy.fs},
12187: and @file{yyy.fs} was included from a non-file (in this case, by giving
12188: @file{yyy.fs} as command-line parameter to Gforth).
12189:
12190: At the end of the error message you find a return stack dump that can be
12191: interpreted as a backtrace (possibly empty). On top you find the top of
12192: the return stack when the @code{throw} happened, and at the bottom you
12193: find the return stack entry just above the return stack of the topmost
12194: text interpreter.
12195:
12196: To the right of most return stack entries you see a guess for the word
12197: that pushed that return stack entry as its return address. This gives a
12198: backtrace. In our case we see that @code{bar} called @code{foo}, and
12199: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12200: address} exception).
12201:
12202: Note that the backtrace is not perfect: We don't know which return stack
12203: entries are return addresses (so we may get false positives); and in
12204: some cases (e.g., for @code{abort"}) we cannot determine from the return
12205: address the word that pushed the return address, so for some return
12206: addresses you see no names in the return stack dump.
1.25 anton 12207:
12208: @cindex @code{catch} and backtraces
12209: The return stack dump represents the return stack at the time when a
12210: specific @code{throw} was executed. In programs that make use of
12211: @code{catch}, it is not necessarily clear which @code{throw} should be
12212: used for the return stack dump (e.g., consider one @code{throw} that
12213: indicates an error, which is caught, and during recovery another error
1.42 anton 12214: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12215: presents the return stack dump for the first @code{throw} after the last
12216: executed (not returned-to) @code{catch}; this works well in the usual
12217: case.
12218:
12219: @cindex @code{gforth-fast} and backtraces
12220: @cindex @code{gforth-fast}, difference from @code{gforth}
12221: @cindex backtraces with @code{gforth-fast}
12222: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12223: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12224: from primitives (e.g., invalid memory address, stack empty etc.);
12225: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12226: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12227: exception caused by a primitive in @code{gforth-fast}, you will
12228: typically see no return stack dump at all; however, if the exception is
12229: caught by @code{catch} (e.g., for restoring some state), and then
12230: @code{throw}n again, the return stack dump will be for the first such
12231: @code{throw}.
1.2 jwilke 12232:
1.5 anton 12233: @c ******************************************************************
1.24 anton 12234: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12235: @chapter Tools
12236:
12237: @menu
12238: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12239: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12240: @end menu
12241:
12242: See also @ref{Emacs and Gforth}.
12243:
1.126 pazsan 12244: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12245: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12246: @cindex @file{ans-report.fs}
12247: @cindex report the words used in your program
12248: @cindex words used in your program
12249:
12250: If you want to label a Forth program as ANS Forth Program, you must
12251: document which wordsets the program uses; for extension wordsets, it is
12252: helpful to list the words the program requires from these wordsets
12253: (because Forth systems are allowed to provide only some words of them).
12254:
12255: The @file{ans-report.fs} tool makes it easy for you to determine which
12256: words from which wordset and which non-ANS words your application
12257: uses. You simply have to include @file{ans-report.fs} before loading the
12258: program you want to check. After loading your program, you can get the
12259: report with @code{print-ans-report}. A typical use is to run this as
12260: batch job like this:
12261: @example
12262: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12263: @end example
12264:
12265: The output looks like this (for @file{compat/control.fs}):
12266: @example
12267: The program uses the following words
12268: from CORE :
12269: : POSTPONE THEN ; immediate ?dup IF 0=
12270: from BLOCK-EXT :
12271: \
12272: from FILE :
12273: (
12274: @end example
12275:
12276: @subsection Caveats
12277:
12278: Note that @file{ans-report.fs} just checks which words are used, not whether
12279: they are used in an ANS Forth conforming way!
12280:
12281: Some words are defined in several wordsets in the
12282: standard. @file{ans-report.fs} reports them for only one of the
12283: wordsets, and not necessarily the one you expect. It depends on usage
12284: which wordset is the right one to specify. E.g., if you only use the
12285: compilation semantics of @code{S"}, it is a Core word; if you also use
12286: its interpretation semantics, it is a File word.
1.124 anton 12287:
12288:
1.127 anton 12289: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12290: @section Stack depth changes during interpretation
12291: @cindex @file{depth-changes.fs}
12292: @cindex depth changes during interpretation
12293: @cindex stack depth changes during interpretation
12294: @cindex items on the stack after interpretation
12295:
12296: Sometimes you notice that, after loading a file, there are items left
12297: on the stack. The tool @file{depth-changes.fs} helps you find out
12298: quickly where in the file these stack items are coming from.
12299:
12300: The simplest way of using @file{depth-changes.fs} is to include it
12301: before the file(s) you want to check, e.g.:
12302:
12303: @example
12304: gforth depth-changes.fs my-file.fs
12305: @end example
12306:
12307: This will compare the stack depths of the data and FP stack at every
12308: empty line (in interpretation state) against these depths at the last
12309: empty line (in interpretation state). If the depths are not equal,
12310: the position in the file and the stack contents are printed with
12311: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12312: change has occured in the paragraph of non-empty lines before the
12313: indicated line. It is a good idea to leave an empty line at the end
12314: of the file, so the last paragraph is checked, too.
12315:
12316: Checking only at empty lines usually works well, but sometimes you
12317: have big blocks of non-empty lines (e.g., when building a big table),
12318: and you want to know where in this block the stack depth changed. You
12319: can check all interpreted lines with
12320:
12321: @example
12322: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12323: @end example
12324:
12325: This checks the stack depth at every end-of-line. So the depth change
12326: occured in the line reported by the @code{~~} (not in the line
12327: before).
12328:
12329: Note that, while this offers better accuracy in indicating where the
12330: stack depth changes, it will often report many intentional stack depth
12331: changes (e.g., when an interpreted computation stretches across
12332: several lines). You can suppress the checking of some lines by
12333: putting backslashes at the end of these lines (not followed by white
12334: space), and using
12335:
12336: @example
12337: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12338: @end example
1.1 anton 12339:
12340: @c ******************************************************************
1.65 anton 12341: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12342: @chapter ANS conformance
12343: @cindex ANS conformance of Gforth
12344:
12345: To the best of our knowledge, Gforth is an
12346:
12347: ANS Forth System
12348: @itemize @bullet
12349: @item providing the Core Extensions word set
12350: @item providing the Block word set
12351: @item providing the Block Extensions word set
12352: @item providing the Double-Number word set
12353: @item providing the Double-Number Extensions word set
12354: @item providing the Exception word set
12355: @item providing the Exception Extensions word set
12356: @item providing the Facility word set
1.40 anton 12357: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12358: @item providing the File Access word set
12359: @item providing the File Access Extensions word set
12360: @item providing the Floating-Point word set
12361: @item providing the Floating-Point Extensions word set
12362: @item providing the Locals word set
12363: @item providing the Locals Extensions word set
12364: @item providing the Memory-Allocation word set
12365: @item providing the Memory-Allocation Extensions word set (that one's easy)
12366: @item providing the Programming-Tools word set
12367: @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
12368: @item providing the Search-Order word set
12369: @item providing the Search-Order Extensions word set
12370: @item providing the String word set
12371: @item providing the String Extensions word set (another easy one)
12372: @end itemize
12373:
1.118 anton 12374: Gforth has the following environmental restrictions:
12375:
12376: @cindex environmental restrictions
12377: @itemize @bullet
12378: @item
12379: While processing the OS command line, if an exception is not caught,
12380: Gforth exits with a non-zero exit code instyead of performing QUIT.
12381:
12382: @item
12383: When an @code{throw} is performed after a @code{query}, Gforth does not
12384: allways restore the input source specification in effect at the
12385: corresponding catch.
12386:
12387: @end itemize
12388:
12389:
1.1 anton 12390: @cindex system documentation
12391: In addition, ANS Forth systems are required to document certain
12392: implementation choices. This chapter tries to meet these
12393: requirements. In many cases it gives a way to ask the system for the
12394: information instead of providing the information directly, in
12395: particular, if the information depends on the processor, the operating
12396: system or the installation options chosen, or if they are likely to
12397: change during the maintenance of Gforth.
12398:
12399: @comment The framework for the rest has been taken from pfe.
12400:
12401: @menu
12402: * The Core Words::
12403: * The optional Block word set::
12404: * The optional Double Number word set::
12405: * The optional Exception word set::
12406: * The optional Facility word set::
12407: * The optional File-Access word set::
12408: * The optional Floating-Point word set::
12409: * The optional Locals word set::
12410: * The optional Memory-Allocation word set::
12411: * The optional Programming-Tools word set::
12412: * The optional Search-Order word set::
12413: @end menu
12414:
12415:
12416: @c =====================================================================
12417: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12418: @comment node-name, next, previous, up
12419: @section The Core Words
12420: @c =====================================================================
12421: @cindex core words, system documentation
12422: @cindex system documentation, core words
12423:
12424: @menu
12425: * core-idef:: Implementation Defined Options
12426: * core-ambcond:: Ambiguous Conditions
12427: * core-other:: Other System Documentation
12428: @end menu
12429:
12430: @c ---------------------------------------------------------------------
12431: @node core-idef, core-ambcond, The Core Words, The Core Words
12432: @subsection Implementation Defined Options
12433: @c ---------------------------------------------------------------------
12434: @cindex core words, implementation-defined options
12435: @cindex implementation-defined options, core words
12436:
12437:
12438: @table @i
12439: @item (Cell) aligned addresses:
12440: @cindex cell-aligned addresses
12441: @cindex aligned addresses
12442: processor-dependent. Gforth's alignment words perform natural alignment
12443: (e.g., an address aligned for a datum of size 8 is divisible by
12444: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12445:
12446: @item @code{EMIT} and non-graphic characters:
12447: @cindex @code{EMIT} and non-graphic characters
12448: @cindex non-graphic characters and @code{EMIT}
12449: The character is output using the C library function (actually, macro)
12450: @code{putc}.
12451:
12452: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12453: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12454: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12455: @cindex @code{ACCEPT}, editing
12456: @cindex @code{EXPECT}, editing
12457: This is modeled on the GNU readline library (@pxref{Readline
12458: Interaction, , Command Line Editing, readline, The GNU Readline
12459: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12460: producing a full word completion every time you type it (instead of
1.28 crook 12461: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12462:
12463: @item character set:
12464: @cindex character set
12465: The character set of your computer and display device. Gforth is
12466: 8-bit-clean (but some other component in your system may make trouble).
12467:
12468: @item Character-aligned address requirements:
12469: @cindex character-aligned address requirements
12470: installation-dependent. Currently a character is represented by a C
12471: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12472: (Comments on that requested).
12473:
12474: @item character-set extensions and matching of names:
12475: @cindex character-set extensions and matching of names
1.26 crook 12476: @cindex case-sensitivity for name lookup
12477: @cindex name lookup, case-sensitivity
12478: @cindex locale and case-sensitivity
1.21 crook 12479: Any character except the ASCII NUL character can be used in a
1.1 anton 12480: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12481: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12482: function is probably influenced by the locale. E.g., the @code{C} locale
12483: does not know about accents and umlauts, so they are matched
12484: case-sensitively in that locale. For portability reasons it is best to
12485: write programs such that they work in the @code{C} locale. Then one can
12486: use libraries written by a Polish programmer (who might use words
12487: containing ISO Latin-2 encoded characters) and by a French programmer
12488: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12489: funny results for some of the words (which ones, depends on the font you
12490: are using)). Also, the locale you prefer may not be available in other
12491: operating systems. Hopefully, Unicode will solve these problems one day.
12492:
12493: @item conditions under which control characters match a space delimiter:
12494: @cindex space delimiters
12495: @cindex control characters as delimiters
1.117 anton 12496: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12497: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12498: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12499: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12500: interpreter (aka text interpreter) by default, treats all white-space
12501: characters as delimiters.
12502:
1.26 crook 12503: @item format of the control-flow stack:
12504: @cindex control-flow stack, format
12505: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12506: stack item in cells is given by the constant @code{cs-item-size}. At the
12507: time of this writing, an item consists of a (pointer to a) locals list
12508: (third), an address in the code (second), and a tag for identifying the
12509: item (TOS). The following tags are used: @code{defstart},
12510: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12511: @code{scopestart}.
12512:
12513: @item conversion of digits > 35
12514: @cindex digits > 35
12515: The characters @code{[\]^_'} are the digits with the decimal value
12516: 36@minus{}41. There is no way to input many of the larger digits.
12517:
12518: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12519: @cindex @code{EXPECT}, display after end of input
12520: @cindex @code{ACCEPT}, display after end of input
12521: The cursor is moved to the end of the entered string. If the input is
12522: terminated using the @kbd{Return} key, a space is typed.
12523:
12524: @item exception abort sequence of @code{ABORT"}:
12525: @cindex exception abort sequence of @code{ABORT"}
12526: @cindex @code{ABORT"}, exception abort sequence
12527: The error string is stored into the variable @code{"error} and a
12528: @code{-2 throw} is performed.
12529:
12530: @item input line terminator:
12531: @cindex input line terminator
12532: @cindex line terminator on input
1.26 crook 12533: @cindex newline character on input
1.1 anton 12534: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12535: lines. One of these characters is typically produced when you type the
12536: @kbd{Enter} or @kbd{Return} key.
12537:
12538: @item maximum size of a counted string:
12539: @cindex maximum size of a counted string
12540: @cindex counted string, maximum size
12541: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12542: on all platforms, but this may change.
1.1 anton 12543:
12544: @item maximum size of a parsed string:
12545: @cindex maximum size of a parsed string
12546: @cindex parsed string, maximum size
12547: Given by the constant @code{/line}. Currently 255 characters.
12548:
12549: @item maximum size of a definition name, in characters:
12550: @cindex maximum size of a definition name, in characters
12551: @cindex name, maximum length
1.113 anton 12552: MAXU/8
1.1 anton 12553:
12554: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12555: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12556: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12557: MAXU/8
1.1 anton 12558:
12559: @item method of selecting the user input device:
12560: @cindex user input device, method of selecting
12561: The user input device is the standard input. There is currently no way to
12562: change it from within Gforth. However, the input can typically be
12563: redirected in the command line that starts Gforth.
12564:
12565: @item method of selecting the user output device:
12566: @cindex user output device, method of selecting
12567: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12568: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12569: output when the user output device is a terminal, otherwise the output
12570: is buffered.
1.1 anton 12571:
12572: @item methods of dictionary compilation:
12573: What are we expected to document here?
12574:
12575: @item number of bits in one address unit:
12576: @cindex number of bits in one address unit
12577: @cindex address unit, size in bits
12578: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12579: platforms.
1.1 anton 12580:
12581: @item number representation and arithmetic:
12582: @cindex number representation and arithmetic
1.79 anton 12583: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12584:
12585: @item ranges for integer types:
12586: @cindex ranges for integer types
12587: @cindex integer types, ranges
12588: Installation-dependent. Make environmental queries for @code{MAX-N},
12589: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12590: unsigned (and positive) types is 0. The lower bound for signed types on
12591: two's complement and one's complement machines machines can be computed
12592: by adding 1 to the upper bound.
12593:
12594: @item read-only data space regions:
12595: @cindex read-only data space regions
12596: @cindex data-space, read-only regions
12597: The whole Forth data space is writable.
12598:
12599: @item size of buffer at @code{WORD}:
12600: @cindex size of buffer at @code{WORD}
12601: @cindex @code{WORD} buffer size
12602: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12603: shared with the pictured numeric output string. If overwriting
12604: @code{PAD} is acceptable, it is as large as the remaining dictionary
12605: space, although only as much can be sensibly used as fits in a counted
12606: string.
12607:
12608: @item size of one cell in address units:
12609: @cindex cell size
12610: @code{1 cells .}.
12611:
12612: @item size of one character in address units:
12613: @cindex char size
1.79 anton 12614: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12615:
12616: @item size of the keyboard terminal buffer:
12617: @cindex size of the keyboard terminal buffer
12618: @cindex terminal buffer, size
12619: Varies. You can determine the size at a specific time using @code{lp@@
12620: tib - .}. It is shared with the locals stack and TIBs of files that
12621: include the current file. You can change the amount of space for TIBs
12622: and locals stack at Gforth startup with the command line option
12623: @code{-l}.
12624:
12625: @item size of the pictured numeric output buffer:
12626: @cindex size of the pictured numeric output buffer
12627: @cindex pictured numeric output buffer, size
12628: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12629: shared with @code{WORD}.
12630:
12631: @item size of the scratch area returned by @code{PAD}:
12632: @cindex size of the scratch area returned by @code{PAD}
12633: @cindex @code{PAD} size
12634: The remainder of dictionary space. @code{unused pad here - - .}.
12635:
12636: @item system case-sensitivity characteristics:
12637: @cindex case-sensitivity characteristics
1.26 crook 12638: Dictionary searches are case-insensitive (except in
1.1 anton 12639: @code{TABLE}s). However, as explained above under @i{character-set
12640: extensions}, the matching for non-ASCII characters is determined by the
12641: locale you are using. In the default @code{C} locale all non-ASCII
12642: characters are matched case-sensitively.
12643:
12644: @item system prompt:
12645: @cindex system prompt
12646: @cindex prompt
12647: @code{ ok} in interpret state, @code{ compiled} in compile state.
12648:
12649: @item division rounding:
12650: @cindex division rounding
12651: installation dependent. @code{s" floored" environment? drop .}. We leave
12652: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12653: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12654:
12655: @item values of @code{STATE} when true:
12656: @cindex @code{STATE} values
12657: -1.
12658:
12659: @item values returned after arithmetic overflow:
12660: On two's complement machines, arithmetic is performed modulo
12661: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12662: arithmetic (with appropriate mapping for signed types). Division by zero
12663: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12664: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12665:
12666: @item whether the current definition can be found after @t{DOES>}:
12667: @cindex @t{DOES>}, visibility of current definition
12668: No.
12669:
12670: @end table
12671:
12672: @c ---------------------------------------------------------------------
12673: @node core-ambcond, core-other, core-idef, The Core Words
12674: @subsection Ambiguous conditions
12675: @c ---------------------------------------------------------------------
12676: @cindex core words, ambiguous conditions
12677: @cindex ambiguous conditions, core words
12678:
12679: @table @i
12680:
12681: @item a name is neither a word nor a number:
12682: @cindex name not found
1.26 crook 12683: @cindex undefined word
1.80 anton 12684: @code{-13 throw} (Undefined word).
1.1 anton 12685:
12686: @item a definition name exceeds the maximum length allowed:
1.26 crook 12687: @cindex word name too long
1.1 anton 12688: @code{-19 throw} (Word name too long)
12689:
12690: @item addressing a region not inside the various data spaces of the forth system:
12691: @cindex Invalid memory address
1.32 anton 12692: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12693: typically readable. Accessing other addresses gives results dependent on
12694: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12695: address).
12696:
12697: @item argument type incompatible with parameter:
1.26 crook 12698: @cindex argument type mismatch
1.1 anton 12699: This is usually not caught. Some words perform checks, e.g., the control
12700: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12701: mismatch).
12702:
12703: @item attempting to obtain the execution token of a word with undefined execution semantics:
12704: @cindex Interpreting a compile-only word, for @code{'} etc.
12705: @cindex execution token of words with undefined execution semantics
12706: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12707: get an execution token for @code{compile-only-error} (which performs a
12708: @code{-14 throw} when executed).
12709:
12710: @item dividing by zero:
12711: @cindex dividing by zero
12712: @cindex floating point unidentified fault, integer division
1.80 anton 12713: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12714: zero); on other systems, this typically results in a @code{-55 throw}
12715: (Floating-point unidentified fault).
1.1 anton 12716:
12717: @item insufficient data stack or return stack space:
12718: @cindex insufficient data stack or return stack space
12719: @cindex stack overflow
1.26 crook 12720: @cindex address alignment exception, stack overflow
1.1 anton 12721: @cindex Invalid memory address, stack overflow
12722: Depending on the operating system, the installation, and the invocation
12723: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12724: it is not checked. If it is checked, you typically get a @code{-3 throw}
12725: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12726: throw} (Invalid memory address) (depending on the platform and how you
12727: achieved the overflow) as soon as the overflow happens. If it is not
12728: checked, overflows typically result in mysterious illegal memory
12729: accesses, producing @code{-9 throw} (Invalid memory address) or
12730: @code{-23 throw} (Address alignment exception); they might also destroy
12731: the internal data structure of @code{ALLOCATE} and friends, resulting in
12732: various errors in these words.
1.1 anton 12733:
12734: @item insufficient space for loop control parameters:
12735: @cindex insufficient space for loop control parameters
1.80 anton 12736: Like other return stack overflows.
1.1 anton 12737:
12738: @item insufficient space in the dictionary:
12739: @cindex insufficient space in the dictionary
12740: @cindex dictionary overflow
1.12 anton 12741: If you try to allot (either directly with @code{allot}, or indirectly
12742: with @code{,}, @code{create} etc.) more memory than available in the
12743: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12744: to access memory beyond the end of the dictionary, the results are
12745: similar to stack overflows.
1.1 anton 12746:
12747: @item interpreting a word with undefined interpretation semantics:
12748: @cindex interpreting a word with undefined interpretation semantics
12749: @cindex Interpreting a compile-only word
12750: For some words, we have defined interpretation semantics. For the
12751: others: @code{-14 throw} (Interpreting a compile-only word).
12752:
12753: @item modifying the contents of the input buffer or a string literal:
12754: @cindex modifying the contents of the input buffer or a string literal
12755: These are located in writable memory and can be modified.
12756:
12757: @item overflow of the pictured numeric output string:
12758: @cindex overflow of the pictured numeric output string
12759: @cindex pictured numeric output string, overflow
1.24 anton 12760: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12761:
12762: @item parsed string overflow:
12763: @cindex parsed string overflow
12764: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12765:
12766: @item producing a result out of range:
12767: @cindex result out of range
12768: On two's complement machines, arithmetic is performed modulo
12769: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12770: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12771: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12772: throw} (floating point unidentified fault). @code{convert} and
12773: @code{>number} currently overflow silently.
1.1 anton 12774:
12775: @item reading from an empty data or return stack:
12776: @cindex stack empty
12777: @cindex stack underflow
1.24 anton 12778: @cindex return stack underflow
1.1 anton 12779: The data stack is checked by the outer (aka text) interpreter after
12780: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12781: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12782: depending on operating system, installation, and invocation. If they are
12783: caught by a check, they typically result in @code{-4 throw} (Stack
12784: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12785: (Invalid memory address), depending on the platform and which stack
12786: underflows and by how much. Note that even if the system uses checking
12787: (through the MMU), your program may have to underflow by a significant
12788: number of stack items to trigger the reaction (the reason for this is
12789: that the MMU, and therefore the checking, works with a page-size
12790: granularity). If there is no checking, the symptoms resulting from an
12791: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12792: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12793: (Invalid memory address) and Illegal Instruction (typically @code{-260
12794: throw}).
1.1 anton 12795:
12796: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12797: @cindex unexpected end of the input buffer
12798: @cindex zero-length string as a name
12799: @cindex Attempt to use zero-length string as a name
12800: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12801: use zero-length string as a name). Words like @code{'} probably will not
12802: find what they search. Note that it is possible to create zero-length
12803: names with @code{nextname} (should it not?).
12804:
12805: @item @code{>IN} greater than input buffer:
12806: @cindex @code{>IN} greater than input buffer
12807: The next invocation of a parsing word returns a string with length 0.
12808:
12809: @item @code{RECURSE} appears after @code{DOES>}:
12810: @cindex @code{RECURSE} appears after @code{DOES>}
12811: Compiles a recursive call to the defining word, not to the defined word.
12812:
12813: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12814: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12815: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12816: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12817: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12818: the end of the file was reached), its source-id may be
12819: reused. Therefore, restoring an input source specification referencing a
12820: closed file may lead to unpredictable results instead of a @code{-12
12821: THROW}.
12822:
12823: In the future, Gforth may be able to restore input source specifications
12824: from other than the current input source.
12825:
12826: @item data space containing definitions gets de-allocated:
12827: @cindex data space containing definitions gets de-allocated
12828: Deallocation with @code{allot} is not checked. This typically results in
12829: memory access faults or execution of illegal instructions.
12830:
12831: @item data space read/write with incorrect alignment:
12832: @cindex data space read/write with incorrect alignment
12833: @cindex alignment faults
1.26 crook 12834: @cindex address alignment exception
1.1 anton 12835: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12836: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12837: alignment turned on, incorrect alignment results in a @code{-9 throw}
12838: (Invalid memory address). There are reportedly some processors with
1.12 anton 12839: alignment restrictions that do not report violations.
1.1 anton 12840:
12841: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12842: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12843: Like other alignment errors.
12844:
12845: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12846: Like other stack underflows.
12847:
12848: @item loop control parameters not available:
12849: @cindex loop control parameters not available
12850: Not checked. The counted loop words simply assume that the top of return
12851: stack items are loop control parameters and behave accordingly.
12852:
12853: @item most recent definition does not have a name (@code{IMMEDIATE}):
12854: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12855: @cindex last word was headerless
12856: @code{abort" last word was headerless"}.
12857:
12858: @item name not defined by @code{VALUE} used by @code{TO}:
12859: @cindex name not defined by @code{VALUE} used by @code{TO}
12860: @cindex @code{TO} on non-@code{VALUE}s
12861: @cindex Invalid name argument, @code{TO}
12862: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12863: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12864:
12865: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12866: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12867: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12868: @code{-13 throw} (Undefined word)
12869:
12870: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12871: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12872: Gforth behaves as if they were of the same type. I.e., you can predict
12873: the behaviour by interpreting all parameters as, e.g., signed.
12874:
12875: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12876: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12877: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12878: compilation semantics of @code{TO}.
12879:
12880: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12881: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12882: @cindex @code{WORD}, string overflow
12883: Not checked. The string will be ok, but the count will, of course,
12884: contain only the least significant bits of the length.
12885:
12886: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12887: @cindex @code{LSHIFT}, large shift counts
12888: @cindex @code{RSHIFT}, large shift counts
12889: Processor-dependent. Typical behaviours are returning 0 and using only
12890: the low bits of the shift count.
12891:
12892: @item word not defined via @code{CREATE}:
12893: @cindex @code{>BODY} of non-@code{CREATE}d words
12894: @code{>BODY} produces the PFA of the word no matter how it was defined.
12895:
12896: @cindex @code{DOES>} of non-@code{CREATE}d words
12897: @code{DOES>} changes the execution semantics of the last defined word no
12898: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12899: @code{CREATE , DOES>}.
12900:
12901: @item words improperly used outside @code{<#} and @code{#>}:
12902: Not checked. As usual, you can expect memory faults.
12903:
12904: @end table
12905:
12906:
12907: @c ---------------------------------------------------------------------
12908: @node core-other, , core-ambcond, The Core Words
12909: @subsection Other system documentation
12910: @c ---------------------------------------------------------------------
12911: @cindex other system documentation, core words
12912: @cindex core words, other system documentation
12913:
12914: @table @i
12915: @item nonstandard words using @code{PAD}:
12916: @cindex @code{PAD} use by nonstandard words
12917: None.
12918:
12919: @item operator's terminal facilities available:
12920: @cindex operator's terminal facilities available
1.80 anton 12921: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12922: and you can give commands to Gforth interactively. The actual facilities
12923: available depend on how you invoke Gforth.
12924:
12925: @item program data space available:
12926: @cindex program data space available
12927: @cindex data space available
12928: @code{UNUSED .} gives the remaining dictionary space. The total
12929: dictionary space can be specified with the @code{-m} switch
12930: (@pxref{Invoking Gforth}) when Gforth starts up.
12931:
12932: @item return stack space available:
12933: @cindex return stack space available
12934: You can compute the total return stack space in cells with
12935: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12936: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12937:
12938: @item stack space available:
12939: @cindex stack space available
12940: You can compute the total data stack space in cells with
12941: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12942: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12943:
12944: @item system dictionary space required, in address units:
12945: @cindex system dictionary space required, in address units
12946: Type @code{here forthstart - .} after startup. At the time of this
12947: writing, this gives 80080 (bytes) on a 32-bit system.
12948: @end table
12949:
12950:
12951: @c =====================================================================
12952: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12953: @section The optional Block word set
12954: @c =====================================================================
12955: @cindex system documentation, block words
12956: @cindex block words, system documentation
12957:
12958: @menu
12959: * block-idef:: Implementation Defined Options
12960: * block-ambcond:: Ambiguous Conditions
12961: * block-other:: Other System Documentation
12962: @end menu
12963:
12964:
12965: @c ---------------------------------------------------------------------
12966: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12967: @subsection Implementation Defined Options
12968: @c ---------------------------------------------------------------------
12969: @cindex implementation-defined options, block words
12970: @cindex block words, implementation-defined options
12971:
12972: @table @i
12973: @item the format for display by @code{LIST}:
12974: @cindex @code{LIST} display format
12975: First the screen number is displayed, then 16 lines of 64 characters,
12976: each line preceded by the line number.
12977:
12978: @item the length of a line affected by @code{\}:
12979: @cindex length of a line affected by @code{\}
12980: @cindex @code{\}, line length in blocks
12981: 64 characters.
12982: @end table
12983:
12984:
12985: @c ---------------------------------------------------------------------
12986: @node block-ambcond, block-other, block-idef, The optional Block word set
12987: @subsection Ambiguous conditions
12988: @c ---------------------------------------------------------------------
12989: @cindex block words, ambiguous conditions
12990: @cindex ambiguous conditions, block words
12991:
12992: @table @i
12993: @item correct block read was not possible:
12994: @cindex block read not possible
12995: Typically results in a @code{throw} of some OS-derived value (between
12996: -512 and -2048). If the blocks file was just not long enough, blanks are
12997: supplied for the missing portion.
12998:
12999: @item I/O exception in block transfer:
13000: @cindex I/O exception in block transfer
13001: @cindex block transfer, I/O exception
13002: Typically results in a @code{throw} of some OS-derived value (between
13003: -512 and -2048).
13004:
13005: @item invalid block number:
13006: @cindex invalid block number
13007: @cindex block number invalid
13008: @code{-35 throw} (Invalid block number)
13009:
13010: @item a program directly alters the contents of @code{BLK}:
13011: @cindex @code{BLK}, altering @code{BLK}
13012: The input stream is switched to that other block, at the same
13013: position. If the storing to @code{BLK} happens when interpreting
13014: non-block input, the system will get quite confused when the block ends.
13015:
13016: @item no current block buffer for @code{UPDATE}:
13017: @cindex @code{UPDATE}, no current block buffer
13018: @code{UPDATE} has no effect.
13019:
13020: @end table
13021:
13022: @c ---------------------------------------------------------------------
13023: @node block-other, , block-ambcond, The optional Block word set
13024: @subsection Other system documentation
13025: @c ---------------------------------------------------------------------
13026: @cindex other system documentation, block words
13027: @cindex block words, other system documentation
13028:
13029: @table @i
13030: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13031: No restrictions (yet).
13032:
13033: @item the number of blocks available for source and data:
13034: depends on your disk space.
13035:
13036: @end table
13037:
13038:
13039: @c =====================================================================
13040: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13041: @section The optional Double Number word set
13042: @c =====================================================================
13043: @cindex system documentation, double words
13044: @cindex double words, system documentation
13045:
13046: @menu
13047: * double-ambcond:: Ambiguous Conditions
13048: @end menu
13049:
13050:
13051: @c ---------------------------------------------------------------------
13052: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13053: @subsection Ambiguous conditions
13054: @c ---------------------------------------------------------------------
13055: @cindex double words, ambiguous conditions
13056: @cindex ambiguous conditions, double words
13057:
13058: @table @i
1.29 crook 13059: @item @i{d} outside of range of @i{n} in @code{D>S}:
13060: @cindex @code{D>S}, @i{d} out of range of @i{n}
13061: The least significant cell of @i{d} is produced.
1.1 anton 13062:
13063: @end table
13064:
13065:
13066: @c =====================================================================
13067: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13068: @section The optional Exception word set
13069: @c =====================================================================
13070: @cindex system documentation, exception words
13071: @cindex exception words, system documentation
13072:
13073: @menu
13074: * exception-idef:: Implementation Defined Options
13075: @end menu
13076:
13077:
13078: @c ---------------------------------------------------------------------
13079: @node exception-idef, , The optional Exception word set, The optional Exception word set
13080: @subsection Implementation Defined Options
13081: @c ---------------------------------------------------------------------
13082: @cindex implementation-defined options, exception words
13083: @cindex exception words, implementation-defined options
13084:
13085: @table @i
13086: @item @code{THROW}-codes used in the system:
13087: @cindex @code{THROW}-codes used in the system
13088: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13089: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13090: codes -512@minus{}-2047 are used for OS errors (for file and memory
13091: allocation operations). The mapping from OS error numbers to throw codes
13092: is -512@minus{}@code{errno}. One side effect of this mapping is that
13093: undefined OS errors produce a message with a strange number; e.g.,
13094: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13095: @end table
13096:
13097: @c =====================================================================
13098: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13099: @section The optional Facility word set
13100: @c =====================================================================
13101: @cindex system documentation, facility words
13102: @cindex facility words, system documentation
13103:
13104: @menu
13105: * facility-idef:: Implementation Defined Options
13106: * facility-ambcond:: Ambiguous Conditions
13107: @end menu
13108:
13109:
13110: @c ---------------------------------------------------------------------
13111: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13112: @subsection Implementation Defined Options
13113: @c ---------------------------------------------------------------------
13114: @cindex implementation-defined options, facility words
13115: @cindex facility words, implementation-defined options
13116:
13117: @table @i
13118: @item encoding of keyboard events (@code{EKEY}):
13119: @cindex keyboard events, encoding in @code{EKEY}
13120: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13121: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13122: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13123: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13124: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13125: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13126:
1.1 anton 13127:
13128: @item duration of a system clock tick:
13129: @cindex duration of a system clock tick
13130: @cindex clock tick duration
13131: System dependent. With respect to @code{MS}, the time is specified in
13132: microseconds. How well the OS and the hardware implement this, is
13133: another question.
13134:
13135: @item repeatability to be expected from the execution of @code{MS}:
13136: @cindex repeatability to be expected from the execution of @code{MS}
13137: @cindex @code{MS}, repeatability to be expected
13138: System dependent. On Unix, a lot depends on load. If the system is
13139: lightly loaded, and the delay is short enough that Gforth does not get
13140: swapped out, the performance should be acceptable. Under MS-DOS and
13141: other single-tasking systems, it should be good.
13142:
13143: @end table
13144:
13145:
13146: @c ---------------------------------------------------------------------
13147: @node facility-ambcond, , facility-idef, The optional Facility word set
13148: @subsection Ambiguous conditions
13149: @c ---------------------------------------------------------------------
13150: @cindex facility words, ambiguous conditions
13151: @cindex ambiguous conditions, facility words
13152:
13153: @table @i
13154: @item @code{AT-XY} can't be performed on user output device:
13155: @cindex @code{AT-XY} can't be performed on user output device
13156: Largely terminal dependent. No range checks are done on the arguments.
13157: No errors are reported. You may see some garbage appearing, you may see
13158: simply nothing happen.
13159:
13160: @end table
13161:
13162:
13163: @c =====================================================================
13164: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13165: @section The optional File-Access word set
13166: @c =====================================================================
13167: @cindex system documentation, file words
13168: @cindex file words, system documentation
13169:
13170: @menu
13171: * file-idef:: Implementation Defined Options
13172: * file-ambcond:: Ambiguous Conditions
13173: @end menu
13174:
13175: @c ---------------------------------------------------------------------
13176: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13177: @subsection Implementation Defined Options
13178: @c ---------------------------------------------------------------------
13179: @cindex implementation-defined options, file words
13180: @cindex file words, implementation-defined options
13181:
13182: @table @i
13183: @item file access methods used:
13184: @cindex file access methods used
13185: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13186: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13187: @code{wb}): The file is cleared, if it exists, and created, if it does
13188: not (with both @code{open-file} and @code{create-file}). Under Unix
13189: @code{create-file} creates a file with 666 permissions modified by your
13190: umask.
13191:
13192: @item file exceptions:
13193: @cindex file exceptions
13194: The file words do not raise exceptions (except, perhaps, memory access
13195: faults when you pass illegal addresses or file-ids).
13196:
13197: @item file line terminator:
13198: @cindex file line terminator
13199: System-dependent. Gforth uses C's newline character as line
13200: terminator. What the actual character code(s) of this are is
13201: system-dependent.
13202:
13203: @item file name format:
13204: @cindex file name format
13205: System dependent. Gforth just uses the file name format of your OS.
13206:
13207: @item information returned by @code{FILE-STATUS}:
13208: @cindex @code{FILE-STATUS}, returned information
13209: @code{FILE-STATUS} returns the most powerful file access mode allowed
13210: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13211: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13212: along with the returned mode.
13213:
13214: @item input file state after an exception when including source:
13215: @cindex exception when including source
13216: All files that are left via the exception are closed.
13217:
1.29 crook 13218: @item @i{ior} values and meaning:
13219: @cindex @i{ior} values and meaning
1.68 anton 13220: @cindex @i{wior} values and meaning
1.29 crook 13221: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13222: intended as throw codes. They typically are in the range
13223: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13224: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13225:
13226: @item maximum depth of file input nesting:
13227: @cindex maximum depth of file input nesting
13228: @cindex file input nesting, maximum depth
13229: limited by the amount of return stack, locals/TIB stack, and the number
13230: of open files available. This should not give you troubles.
13231:
13232: @item maximum size of input line:
13233: @cindex maximum size of input line
13234: @cindex input line size, maximum
13235: @code{/line}. Currently 255.
13236:
13237: @item methods of mapping block ranges to files:
13238: @cindex mapping block ranges to files
13239: @cindex files containing blocks
13240: @cindex blocks in files
13241: By default, blocks are accessed in the file @file{blocks.fb} in the
13242: current working directory. The file can be switched with @code{USE}.
13243:
13244: @item number of string buffers provided by @code{S"}:
13245: @cindex @code{S"}, number of string buffers
13246: 1
13247:
13248: @item size of string buffer used by @code{S"}:
13249: @cindex @code{S"}, size of string buffer
13250: @code{/line}. currently 255.
13251:
13252: @end table
13253:
13254: @c ---------------------------------------------------------------------
13255: @node file-ambcond, , file-idef, The optional File-Access word set
13256: @subsection Ambiguous conditions
13257: @c ---------------------------------------------------------------------
13258: @cindex file words, ambiguous conditions
13259: @cindex ambiguous conditions, file words
13260:
13261: @table @i
13262: @item attempting to position a file outside its boundaries:
13263: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13264: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13265: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13266:
13267: @item attempting to read from file positions not yet written:
13268: @cindex reading from file positions not yet written
13269: End-of-file, i.e., zero characters are read and no error is reported.
13270:
1.29 crook 13271: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13272: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13273: An appropriate exception may be thrown, but a memory fault or other
13274: problem is more probable.
13275:
1.29 crook 13276: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13277: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13278: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13279: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13280: thrown.
13281:
13282: @item named file cannot be opened (@code{INCLUDED}):
13283: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13284: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13285:
13286: @item requesting an unmapped block number:
13287: @cindex unmapped block numbers
13288: There are no unmapped legal block numbers. On some operating systems,
13289: writing a block with a large number may overflow the file system and
13290: have an error message as consequence.
13291:
13292: @item using @code{source-id} when @code{blk} is non-zero:
13293: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13294: @code{source-id} performs its function. Typically it will give the id of
13295: the source which loaded the block. (Better ideas?)
13296:
13297: @end table
13298:
13299:
13300: @c =====================================================================
13301: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13302: @section The optional Floating-Point word set
13303: @c =====================================================================
13304: @cindex system documentation, floating-point words
13305: @cindex floating-point words, system documentation
13306:
13307: @menu
13308: * floating-idef:: Implementation Defined Options
13309: * floating-ambcond:: Ambiguous Conditions
13310: @end menu
13311:
13312:
13313: @c ---------------------------------------------------------------------
13314: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13315: @subsection Implementation Defined Options
13316: @c ---------------------------------------------------------------------
13317: @cindex implementation-defined options, floating-point words
13318: @cindex floating-point words, implementation-defined options
13319:
13320: @table @i
13321: @item format and range of floating point numbers:
13322: @cindex format and range of floating point numbers
13323: @cindex floating point numbers, format and range
13324: System-dependent; the @code{double} type of C.
13325:
1.29 crook 13326: @item results of @code{REPRESENT} when @i{float} is out of range:
13327: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13328: System dependent; @code{REPRESENT} is implemented using the C library
13329: function @code{ecvt()} and inherits its behaviour in this respect.
13330:
13331: @item rounding or truncation of floating-point numbers:
13332: @cindex rounding of floating-point numbers
13333: @cindex truncation of floating-point numbers
13334: @cindex floating-point numbers, rounding or truncation
13335: System dependent; the rounding behaviour is inherited from the hosting C
13336: compiler. IEEE-FP-based (i.e., most) systems by default round to
13337: nearest, and break ties by rounding to even (i.e., such that the last
13338: bit of the mantissa is 0).
13339:
13340: @item size of floating-point stack:
13341: @cindex floating-point stack size
13342: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13343: the floating-point stack (in floats). You can specify this on startup
13344: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13345:
13346: @item width of floating-point stack:
13347: @cindex floating-point stack width
13348: @code{1 floats}.
13349:
13350: @end table
13351:
13352:
13353: @c ---------------------------------------------------------------------
13354: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13355: @subsection Ambiguous conditions
13356: @c ---------------------------------------------------------------------
13357: @cindex floating-point words, ambiguous conditions
13358: @cindex ambiguous conditions, floating-point words
13359:
13360: @table @i
13361: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13362: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13363: System-dependent. Typically results in a @code{-23 THROW} like other
13364: alignment violations.
13365:
13366: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13367: @cindex @code{f@@} used with an address that is not float aligned
13368: @cindex @code{f!} used with an address that is not float aligned
13369: System-dependent. Typically results in a @code{-23 THROW} like other
13370: alignment violations.
13371:
13372: @item floating-point result out of range:
13373: @cindex floating-point result out of range
1.80 anton 13374: System-dependent. Can result in a @code{-43 throw} (floating point
13375: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13376: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13377: unidentified fault), or can produce a special value representing, e.g.,
13378: Infinity.
13379:
13380: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13381: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13382: System-dependent. Typically results in an alignment fault like other
13383: alignment violations.
13384:
1.35 anton 13385: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13386: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13387: The floating-point number is converted into decimal nonetheless.
13388:
13389: @item Both arguments are equal to zero (@code{FATAN2}):
13390: @cindex @code{FATAN2}, both arguments are equal to zero
13391: System-dependent. @code{FATAN2} is implemented using the C library
13392: function @code{atan2()}.
13393:
1.29 crook 13394: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13395: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13396: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13397: because of small errors and the tan will be a very large (or very small)
13398: but finite number.
13399:
1.29 crook 13400: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13401: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13402: The result is rounded to the nearest float.
13403:
13404: @item dividing by zero:
13405: @cindex dividing by zero, floating-point
13406: @cindex floating-point dividing by zero
13407: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13408: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13409: (floating point divide by zero) or @code{-55 throw} (Floating-point
13410: unidentified fault).
1.1 anton 13411:
13412: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13413: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13414: System dependent. On IEEE-FP based systems the number is converted into
13415: an infinity.
13416:
1.29 crook 13417: @item @i{float}<1 (@code{FACOSH}):
13418: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13419: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13420: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13421:
1.29 crook 13422: @item @i{float}=<-1 (@code{FLNP1}):
13423: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13424: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13425: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13426: negative infinity for @i{float}=-1).
1.1 anton 13427:
1.29 crook 13428: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13429: @cindex @code{FLN}, @i{float}=<0
13430: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13431: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13432: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13433: negative infinity for @i{float}=0).
1.1 anton 13434:
1.29 crook 13435: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13436: @cindex @code{FASINH}, @i{float}<0
13437: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13438: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13439: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13440: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13441: C library?).
1.1 anton 13442:
1.29 crook 13443: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13444: @cindex @code{FACOS}, |@i{float}|>1
13445: @cindex @code{FASIN}, |@i{float}|>1
13446: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13447: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13448: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13449:
1.29 crook 13450: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13451: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13452: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13453: Platform-dependent; typically, some double number is produced and no
13454: error is reported.
1.1 anton 13455:
13456: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13457: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13458: @code{Precision} characters of the numeric output area are used. If
13459: @code{precision} is too high, these words will smash the data or code
13460: close to @code{here}.
1.1 anton 13461: @end table
13462:
13463: @c =====================================================================
13464: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13465: @section The optional Locals word set
13466: @c =====================================================================
13467: @cindex system documentation, locals words
13468: @cindex locals words, system documentation
13469:
13470: @menu
13471: * locals-idef:: Implementation Defined Options
13472: * locals-ambcond:: Ambiguous Conditions
13473: @end menu
13474:
13475:
13476: @c ---------------------------------------------------------------------
13477: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13478: @subsection Implementation Defined Options
13479: @c ---------------------------------------------------------------------
13480: @cindex implementation-defined options, locals words
13481: @cindex locals words, implementation-defined options
13482:
13483: @table @i
13484: @item maximum number of locals in a definition:
13485: @cindex maximum number of locals in a definition
13486: @cindex locals, maximum number in a definition
13487: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13488: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13489: characters. The number of locals in a definition is bounded by the size
13490: of locals-buffer, which contains the names of the locals.
13491:
13492: @end table
13493:
13494:
13495: @c ---------------------------------------------------------------------
13496: @node locals-ambcond, , locals-idef, The optional Locals word set
13497: @subsection Ambiguous conditions
13498: @c ---------------------------------------------------------------------
13499: @cindex locals words, ambiguous conditions
13500: @cindex ambiguous conditions, locals words
13501:
13502: @table @i
13503: @item executing a named local in interpretation state:
13504: @cindex local in interpretation state
13505: @cindex Interpreting a compile-only word, for a local
13506: Locals have no interpretation semantics. If you try to perform the
13507: interpretation semantics, you will get a @code{-14 throw} somewhere
13508: (Interpreting a compile-only word). If you perform the compilation
13509: semantics, the locals access will be compiled (irrespective of state).
13510:
1.29 crook 13511: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13512: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13513: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13514: @cindex Invalid name argument, @code{TO}
13515: @code{-32 throw} (Invalid name argument)
13516:
13517: @end table
13518:
13519:
13520: @c =====================================================================
13521: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13522: @section The optional Memory-Allocation word set
13523: @c =====================================================================
13524: @cindex system documentation, memory-allocation words
13525: @cindex memory-allocation words, system documentation
13526:
13527: @menu
13528: * memory-idef:: Implementation Defined Options
13529: @end menu
13530:
13531:
13532: @c ---------------------------------------------------------------------
13533: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13534: @subsection Implementation Defined Options
13535: @c ---------------------------------------------------------------------
13536: @cindex implementation-defined options, memory-allocation words
13537: @cindex memory-allocation words, implementation-defined options
13538:
13539: @table @i
1.29 crook 13540: @item values and meaning of @i{ior}:
13541: @cindex @i{ior} values and meaning
13542: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13543: intended as throw codes. They typically are in the range
13544: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13545: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13546:
13547: @end table
13548:
13549: @c =====================================================================
13550: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13551: @section The optional Programming-Tools word set
13552: @c =====================================================================
13553: @cindex system documentation, programming-tools words
13554: @cindex programming-tools words, system documentation
13555:
13556: @menu
13557: * programming-idef:: Implementation Defined Options
13558: * programming-ambcond:: Ambiguous Conditions
13559: @end menu
13560:
13561:
13562: @c ---------------------------------------------------------------------
13563: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13564: @subsection Implementation Defined Options
13565: @c ---------------------------------------------------------------------
13566: @cindex implementation-defined options, programming-tools words
13567: @cindex programming-tools words, implementation-defined options
13568:
13569: @table @i
13570: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13571: @cindex @code{;CODE} ending sequence
13572: @cindex @code{CODE} ending sequence
13573: @code{END-CODE}
13574:
13575: @item manner of processing input following @code{;CODE} and @code{CODE}:
13576: @cindex @code{;CODE}, processing input
13577: @cindex @code{CODE}, processing input
13578: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13579: the input is processed by the text interpreter, (starting) in interpret
13580: state.
13581:
13582: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13583: @cindex @code{ASSEMBLER}, search order capability
13584: The ANS Forth search order word set.
13585:
13586: @item source and format of display by @code{SEE}:
13587: @cindex @code{SEE}, source and format of output
1.80 anton 13588: The source for @code{see} is the executable code used by the inner
1.1 anton 13589: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13590: (and on some platforms, assembly code for primitives) as well as
13591: possible.
1.1 anton 13592:
13593: @end table
13594:
13595: @c ---------------------------------------------------------------------
13596: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13597: @subsection Ambiguous conditions
13598: @c ---------------------------------------------------------------------
13599: @cindex programming-tools words, ambiguous conditions
13600: @cindex ambiguous conditions, programming-tools words
13601:
13602: @table @i
13603:
1.21 crook 13604: @item deleting the compilation word list (@code{FORGET}):
13605: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13606: Not implemented (yet).
13607:
1.29 crook 13608: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13609: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13610: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13611: @cindex control-flow stack underflow
13612: This typically results in an @code{abort"} with a descriptive error
13613: message (may change into a @code{-22 throw} (Control structure mismatch)
13614: in the future). You may also get a memory access error. If you are
13615: unlucky, this ambiguous condition is not caught.
13616:
1.29 crook 13617: @item @i{name} can't be found (@code{FORGET}):
13618: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13619: Not implemented (yet).
13620:
1.29 crook 13621: @item @i{name} not defined via @code{CREATE}:
13622: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13623: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13624: the execution semantics of the last defined word no matter how it was
13625: defined.
13626:
13627: @item @code{POSTPONE} applied to @code{[IF]}:
13628: @cindex @code{POSTPONE} applied to @code{[IF]}
13629: @cindex @code{[IF]} and @code{POSTPONE}
13630: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13631: equivalent to @code{[IF]}.
13632:
13633: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13634: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13635: Continue in the same state of conditional compilation in the next outer
13636: input source. Currently there is no warning to the user about this.
13637:
13638: @item removing a needed definition (@code{FORGET}):
13639: @cindex @code{FORGET}, removing a needed definition
13640: Not implemented (yet).
13641:
13642: @end table
13643:
13644:
13645: @c =====================================================================
13646: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13647: @section The optional Search-Order word set
13648: @c =====================================================================
13649: @cindex system documentation, search-order words
13650: @cindex search-order words, system documentation
13651:
13652: @menu
13653: * search-idef:: Implementation Defined Options
13654: * search-ambcond:: Ambiguous Conditions
13655: @end menu
13656:
13657:
13658: @c ---------------------------------------------------------------------
13659: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13660: @subsection Implementation Defined Options
13661: @c ---------------------------------------------------------------------
13662: @cindex implementation-defined options, search-order words
13663: @cindex search-order words, implementation-defined options
13664:
13665: @table @i
13666: @item maximum number of word lists in search order:
13667: @cindex maximum number of word lists in search order
13668: @cindex search order, maximum depth
13669: @code{s" wordlists" environment? drop .}. Currently 16.
13670:
13671: @item minimum search order:
13672: @cindex minimum search order
13673: @cindex search order, minimum
13674: @code{root root}.
13675:
13676: @end table
13677:
13678: @c ---------------------------------------------------------------------
13679: @node search-ambcond, , search-idef, The optional Search-Order word set
13680: @subsection Ambiguous conditions
13681: @c ---------------------------------------------------------------------
13682: @cindex search-order words, ambiguous conditions
13683: @cindex ambiguous conditions, search-order words
13684:
13685: @table @i
1.21 crook 13686: @item changing the compilation word list (during compilation):
13687: @cindex changing the compilation word list (during compilation)
13688: @cindex compilation word list, change before definition ends
13689: The word is entered into the word list that was the compilation word list
1.1 anton 13690: at the start of the definition. Any changes to the name field (e.g.,
13691: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13692: are applied to the latest defined word (as reported by @code{latest} or
13693: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13694:
13695: @item search order empty (@code{previous}):
13696: @cindex @code{previous}, search order empty
1.26 crook 13697: @cindex vocstack empty, @code{previous}
1.1 anton 13698: @code{abort" Vocstack empty"}.
13699:
13700: @item too many word lists in search order (@code{also}):
13701: @cindex @code{also}, too many word lists in search order
1.26 crook 13702: @cindex vocstack full, @code{also}
1.1 anton 13703: @code{abort" Vocstack full"}.
13704:
13705: @end table
13706:
13707: @c ***************************************************************
1.65 anton 13708: @node Standard vs Extensions, Model, ANS conformance, Top
13709: @chapter Should I use Gforth extensions?
13710: @cindex Gforth extensions
13711:
13712: As you read through the rest of this manual, you will see documentation
13713: for @i{Standard} words, and documentation for some appealing Gforth
13714: @i{extensions}. You might ask yourself the question: @i{``Should I
13715: restrict myself to the standard, or should I use the extensions?''}
13716:
13717: The answer depends on the goals you have for the program you are working
13718: on:
13719:
13720: @itemize @bullet
13721:
13722: @item Is it just for yourself or do you want to share it with others?
13723:
13724: @item
13725: If you want to share it, do the others all use Gforth?
13726:
13727: @item
13728: If it is just for yourself, do you want to restrict yourself to Gforth?
13729:
13730: @end itemize
13731:
13732: If restricting the program to Gforth is ok, then there is no reason not
13733: to use extensions. It is still a good idea to keep to the standard
13734: where it is easy, in case you want to reuse these parts in another
13735: program that you want to be portable.
13736:
13737: If you want to be able to port the program to other Forth systems, there
13738: are the following points to consider:
13739:
13740: @itemize @bullet
13741:
13742: @item
13743: Most Forth systems that are being maintained support the ANS Forth
13744: standard. So if your program complies with the standard, it will be
13745: portable among many systems.
13746:
13747: @item
13748: A number of the Gforth extensions can be implemented in ANS Forth using
13749: public-domain files provided in the @file{compat/} directory. These are
13750: mentioned in the text in passing. There is no reason not to use these
13751: extensions, your program will still be ANS Forth compliant; just include
13752: the appropriate compat files with your program.
13753:
13754: @item
13755: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13756: analyse your program and determine what non-Standard words it relies
13757: upon. However, it does not check whether you use standard words in a
13758: non-standard way.
13759:
13760: @item
13761: Some techniques are not standardized by ANS Forth, and are hard or
13762: impossible to implement in a standard way, but can be implemented in
13763: most Forth systems easily, and usually in similar ways (e.g., accessing
13764: word headers). Forth has a rich historical precedent for programmers
13765: taking advantage of implementation-dependent features of their tools
13766: (for example, relying on a knowledge of the dictionary
13767: structure). Sometimes these techniques are necessary to extract every
13768: last bit of performance from the hardware, sometimes they are just a
13769: programming shorthand.
13770:
13771: @item
13772: Does using a Gforth extension save more work than the porting this part
13773: to other Forth systems (if any) will cost?
13774:
13775: @item
13776: Is the additional functionality worth the reduction in portability and
13777: the additional porting problems?
13778:
13779: @end itemize
13780:
13781: In order to perform these consideratios, you need to know what's
13782: standard and what's not. This manual generally states if something is
1.81 anton 13783: non-standard, but the authoritative source is the
13784: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13785: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13786: into the thought processes of the technical committee.
13787:
13788: Note also that portability between Forth systems is not the only
13789: portability issue; there is also the issue of portability between
13790: different platforms (processor/OS combinations).
13791:
13792: @c ***************************************************************
13793: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13794: @chapter Model
13795:
13796: This chapter has yet to be written. It will contain information, on
13797: which internal structures you can rely.
13798:
13799: @c ***************************************************************
13800: @node Integrating Gforth, Emacs and Gforth, Model, Top
13801: @chapter Integrating Gforth into C programs
13802:
13803: This is not yet implemented.
13804:
13805: Several people like to use Forth as scripting language for applications
13806: that are otherwise written in C, C++, or some other language.
13807:
13808: The Forth system ATLAST provides facilities for embedding it into
13809: applications; unfortunately it has several disadvantages: most
13810: importantly, it is not based on ANS Forth, and it is apparently dead
13811: (i.e., not developed further and not supported). The facilities
1.21 crook 13812: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13813: making the switch should not be hard.
13814:
13815: We also tried to design the interface such that it can easily be
13816: implemented by other Forth systems, so that we may one day arrive at a
13817: standardized interface. Such a standard interface would allow you to
13818: replace the Forth system without having to rewrite C code.
13819:
13820: You embed the Gforth interpreter by linking with the library
13821: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13822: global symbols in this library that belong to the interface, have the
13823: prefix @code{forth_}. (Global symbols that are used internally have the
13824: prefix @code{gforth_}).
13825:
13826: You can include the declarations of Forth types and the functions and
13827: variables of the interface with @code{#include <forth.h>}.
13828:
13829: Types.
13830:
13831: Variables.
13832:
13833: Data and FP Stack pointer. Area sizes.
13834:
13835: functions.
13836:
13837: forth_init(imagefile)
13838: forth_evaluate(string) exceptions?
13839: forth_goto(address) (or forth_execute(xt)?)
13840: forth_continue() (a corountining mechanism)
13841:
13842: Adding primitives.
13843:
13844: No checking.
13845:
13846: Signals?
13847:
13848: Accessing the Stacks
13849:
1.26 crook 13850: @c ******************************************************************
1.1 anton 13851: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13852: @chapter Emacs and Gforth
13853: @cindex Emacs and Gforth
13854:
13855: @cindex @file{gforth.el}
13856: @cindex @file{forth.el}
13857: @cindex Rydqvist, Goran
1.107 dvdkhlng 13858: @cindex Kuehling, David
1.1 anton 13859: @cindex comment editing commands
13860: @cindex @code{\}, editing with Emacs
13861: @cindex debug tracer editing commands
13862: @cindex @code{~~}, removal with Emacs
13863: @cindex Forth mode in Emacs
1.107 dvdkhlng 13864:
1.1 anton 13865: Gforth comes with @file{gforth.el}, an improved version of
13866: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13867: improvements are:
13868:
13869: @itemize @bullet
13870: @item
1.107 dvdkhlng 13871: A better handling of indentation.
13872: @item
13873: A custom hilighting engine for Forth-code.
1.26 crook 13874: @item
13875: Comment paragraph filling (@kbd{M-q})
13876: @item
13877: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13878: @item
13879: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13880: @item
13881: Support of the @code{info-lookup} feature for looking up the
13882: documentation of a word.
1.107 dvdkhlng 13883: @item
13884: Support for reading and writing blocks files.
1.26 crook 13885: @end itemize
13886:
1.107 dvdkhlng 13887: To get a basic description of these features, enter Forth mode and
13888: type @kbd{C-h m}.
1.1 anton 13889:
13890: @cindex source location of error or debugging output in Emacs
13891: @cindex error output, finding the source location in Emacs
13892: @cindex debugging output, finding the source location in Emacs
13893: In addition, Gforth supports Emacs quite well: The source code locations
13894: given in error messages, debugging output (from @code{~~}) and failed
13895: assertion messages are in the right format for Emacs' compilation mode
13896: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13897: Manual}) so the source location corresponding to an error or other
13898: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13899: @kbd{C-c C-c} for the error under the cursor).
13900:
1.107 dvdkhlng 13901: @cindex viewing the documentation of a word in Emacs
13902: @cindex context-sensitive help
13903: Moreover, for words documented in this manual, you can look up the
13904: glossary entry quickly by using @kbd{C-h TAB}
13905: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13906: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13907: later and does not work for words containing @code{:}.
13908:
13909: @menu
13910: * Installing gforth.el:: Making Emacs aware of Forth.
13911: * Emacs Tags:: Viewing the source of a word in Emacs.
13912: * Hilighting:: Making Forth code look prettier.
13913: * Auto-Indentation:: Customizing auto-indentation.
13914: * Blocks Files:: Reading and writing blocks files.
13915: @end menu
13916:
13917: @c ----------------------------------
1.109 anton 13918: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13919: @section Installing gforth.el
13920: @cindex @file{.emacs}
13921: @cindex @file{gforth.el}, installation
13922: To make the features from @file{gforth.el} available in Emacs, add
13923: the following lines to your @file{.emacs} file:
13924:
13925: @example
13926: (autoload 'forth-mode "gforth.el")
13927: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13928: auto-mode-alist))
13929: (autoload 'forth-block-mode "gforth.el")
13930: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13931: auto-mode-alist))
13932: (add-hook 'forth-mode-hook (function (lambda ()
13933: ;; customize variables here:
13934: (setq forth-indent-level 4)
13935: (setq forth-minor-indent-level 2)
13936: (setq forth-hilight-level 3)
13937: ;;; ...
13938: )))
13939: @end example
13940:
13941: @c ----------------------------------
13942: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13943: @section Emacs Tags
1.1 anton 13944: @cindex @file{TAGS} file
13945: @cindex @file{etags.fs}
13946: @cindex viewing the source of a word in Emacs
1.43 anton 13947: @cindex @code{require}, placement in files
13948: @cindex @code{include}, placement in files
1.107 dvdkhlng 13949: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13950: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13951: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13952: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13953: several tags files at the same time (e.g., one for the Gforth sources
13954: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13955: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13956: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13957: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13958: with @file{etags.fs}, you should avoid putting definitions both before
13959: and after @code{require} etc., otherwise you will see the same file
13960: visited several times by commands like @code{tags-search}.
1.1 anton 13961:
1.107 dvdkhlng 13962: @c ----------------------------------
13963: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13964: @section Hilighting
13965: @cindex hilighting Forth code in Emacs
13966: @cindex highlighting Forth code in Emacs
13967: @file{gforth.el} comes with a custom source hilighting engine. When
13968: you open a file in @code{forth-mode}, it will be completely parsed,
13969: assigning faces to keywords, comments, strings etc. While you edit
13970: the file, modified regions get parsed and updated on-the-fly.
13971:
13972: Use the variable `forth-hilight-level' to change the level of
13973: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13974: you set the hilighting level to 0, the parser will still work in the
13975: background, collecting information about whether regions of text are
13976: ``compiled'' or ``interpreted''. Those information are required for
13977: auto-indentation to work properly. Set `forth-disable-parser' to
13978: non-nil if your computer is too slow to handle parsing. This will
13979: have an impact on the smartness of the auto-indentation engine,
13980: though.
13981:
13982: Sometimes Forth sources define new features that should be hilighted,
13983: new control structures, defining-words etc. You can use the variable
13984: `forth-custom-words' to make @code{forth-mode} hilight additional
13985: words and constructs. See the docstring of `forth-words' for details
13986: (in Emacs, type @kbd{C-h v forth-words}).
13987:
13988: `forth-custom-words' is meant to be customized in your
13989: @file{.emacs} file. To customize hilighing in a file-specific manner,
13990: set `forth-local-words' in a local-variables section at the end of
13991: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13992:
13993: Example:
13994: @example
13995: 0 [IF]
13996: Local Variables:
13997: forth-local-words:
13998: ((("t:") definition-starter (font-lock-keyword-face . 1)
13999: "[ \t\n]" t name (font-lock-function-name-face . 3))
14000: ((";t") definition-ender (font-lock-keyword-face . 1)))
14001: End:
14002: [THEN]
14003: @end example
14004:
14005: @c ----------------------------------
14006: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14007: @section Auto-Indentation
14008: @cindex auto-indentation of Forth code in Emacs
14009: @cindex indentation of Forth code in Emacs
14010: @code{forth-mode} automatically tries to indent lines in a smart way,
14011: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14012:
14013: Simple customization can be achieved by setting
14014: `forth-indent-level' and `forth-minor-indent-level' in your
14015: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14016: per default by multiples of 4 columns. To use the more traditional
14017: 3-column indentation, add the following lines to your @file{.emacs}:
14018:
14019: @example
14020: (add-hook 'forth-mode-hook (function (lambda ()
14021: ;; customize variables here:
14022: (setq forth-indent-level 3)
14023: (setq forth-minor-indent-level 1)
14024: )))
14025: @end example
14026:
14027: If you want indentation to recognize non-default words, customize it
14028: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14029: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14030: v forth-indent-words}).
14031:
14032: To customize indentation in a file-specific manner, set
14033: `forth-local-indent-words' in a local-variables section at the end of
14034: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14035: Emacs Manual}).
14036:
14037: Example:
14038: @example
14039: 0 [IF]
14040: Local Variables:
14041: forth-local-indent-words:
14042: ((("t:") (0 . 2) (0 . 2))
14043: ((";t") (-2 . 0) (0 . -2)))
14044: End:
14045: [THEN]
14046: @end example
14047:
14048: @c ----------------------------------
1.109 anton 14049: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14050: @section Blocks Files
14051: @cindex blocks files, use with Emacs
14052: @code{forth-mode} Autodetects blocks files by checking whether the
14053: length of the first line exceeds 1023 characters. It then tries to
14054: convert the file into normal text format. When you save the file, it
14055: will be written to disk as normal stream-source file.
14056:
14057: If you want to write blocks files, use @code{forth-blocks-mode}. It
14058: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14059:
1.107 dvdkhlng 14060: @itemize @bullet
14061: @item
14062: Files are written to disk in blocks file format.
14063: @item
14064: Screen numbers are displayed in the mode line (enumerated beginning
14065: with the value of `forth-block-base')
14066: @item
14067: Warnings are displayed when lines exceed 64 characters.
14068: @item
14069: The beginning of the currently edited block is marked with an
14070: overlay-arrow.
14071: @end itemize
1.41 anton 14072:
1.107 dvdkhlng 14073: There are some restrictions you should be aware of. When you open a
14074: blocks file that contains tabulator or newline characters, these
14075: characters will be translated into spaces when the file is written
14076: back to disk. If tabs or newlines are encountered during blocks file
14077: reading, an error is output to the echo area. So have a look at the
14078: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14079:
1.107 dvdkhlng 14080: Please consult the docstring of @code{forth-blocks-mode} for more
14081: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14082:
1.26 crook 14083: @c ******************************************************************
1.1 anton 14084: @node Image Files, Engine, Emacs and Gforth, Top
14085: @chapter Image Files
1.26 crook 14086: @cindex image file
14087: @cindex @file{.fi} files
1.1 anton 14088: @cindex precompiled Forth code
14089: @cindex dictionary in persistent form
14090: @cindex persistent form of dictionary
14091:
14092: An image file is a file containing an image of the Forth dictionary,
14093: i.e., compiled Forth code and data residing in the dictionary. By
14094: convention, we use the extension @code{.fi} for image files.
14095:
14096: @menu
1.18 anton 14097: * Image Licensing Issues:: Distribution terms for images.
14098: * Image File Background:: Why have image files?
1.67 anton 14099: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14100: * Data-Relocatable Image Files:: are better.
1.67 anton 14101: * Fully Relocatable Image Files:: better yet.
1.18 anton 14102: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14103: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14104: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14105: @end menu
14106:
1.18 anton 14107: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14108: @section Image Licensing Issues
14109: @cindex license for images
14110: @cindex image license
14111:
14112: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14113: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14114: original image; i.e., according to copyright law it is a derived work of
14115: the original image.
14116:
14117: Since Gforth is distributed under the GNU GPL, the newly created image
14118: falls under the GNU GPL, too. In particular, this means that if you
14119: distribute the image, you have to make all of the sources for the image
1.113 anton 14120: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14121: GNU General Public License (Section 3)}.
14122:
14123: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14124: contains only code compiled from the sources you gave it; if none of
14125: these sources is under the GPL, the terms discussed above do not apply
14126: to the image. However, if your image needs an engine (a gforth binary)
14127: that is under the GPL, you should make sure that you distribute both in
14128: a way that is at most a @emph{mere aggregation}, if you don't want the
14129: terms of the GPL to apply to the image.
14130:
14131: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14132: @section Image File Background
14133: @cindex image file background
14134:
1.80 anton 14135: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14136: definitions written in Forth. Since the Forth compiler itself belongs to
14137: those definitions, it is not possible to start the system with the
1.80 anton 14138: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14139: code as an image file in nearly executable form. When Gforth starts up,
14140: a C routine loads the image file into memory, optionally relocates the
14141: addresses, then sets up the memory (stacks etc.) according to
14142: information in the image file, and (finally) starts executing Forth
14143: code.
1.1 anton 14144:
14145: The image file variants represent different compromises between the
14146: goals of making it easy to generate image files and making them
14147: portable.
14148:
14149: @cindex relocation at run-time
1.26 crook 14150: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14151: run-time. This avoids many of the complications discussed below (image
14152: files are data relocatable without further ado), but costs performance
14153: (one addition per memory access).
14154:
14155: @cindex relocation at load-time
1.26 crook 14156: By contrast, the Gforth loader performs relocation at image load time. The
14157: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14158: appropriate code-field addresses (or code addresses in the case of
14159: direct threading).
14160:
14161: There are three kinds of image files, with different degrees of
14162: relocatability: non-relocatable, data-relocatable, and fully relocatable
14163: image files.
14164:
14165: @cindex image file loader
14166: @cindex relocating loader
14167: @cindex loader for image files
14168: These image file variants have several restrictions in common; they are
14169: caused by the design of the image file loader:
14170:
14171: @itemize @bullet
14172: @item
14173: There is only one segment; in particular, this means, that an image file
14174: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14175: them). The contents of the stacks are not represented, either.
1.1 anton 14176:
14177: @item
14178: The only kinds of relocation supported are: adding the same offset to
14179: all cells that represent data addresses; and replacing special tokens
14180: with code addresses or with pieces of machine code.
14181:
14182: If any complex computations involving addresses are performed, the
14183: results cannot be represented in the image file. Several applications that
14184: use such computations come to mind:
14185: @itemize @minus
14186: @item
14187: Hashing addresses (or data structures which contain addresses) for table
14188: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14189: purpose, you will have no problem, because the hash tables are
14190: recomputed automatically when the system is started. If you use your own
14191: hash tables, you will have to do something similar.
14192:
14193: @item
14194: There's a cute implementation of doubly-linked lists that uses
14195: @code{XOR}ed addresses. You could represent such lists as singly-linked
14196: in the image file, and restore the doubly-linked representation on
14197: startup.@footnote{In my opinion, though, you should think thrice before
14198: using a doubly-linked list (whatever implementation).}
14199:
14200: @item
14201: The code addresses of run-time routines like @code{docol:} cannot be
14202: represented in the image file (because their tokens would be replaced by
14203: machine code in direct threaded implementations). As a workaround,
14204: compute these addresses at run-time with @code{>code-address} from the
14205: executions tokens of appropriate words (see the definitions of
1.80 anton 14206: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14207:
14208: @item
14209: On many architectures addresses are represented in machine code in some
14210: shifted or mangled form. You cannot put @code{CODE} words that contain
14211: absolute addresses in this form in a relocatable image file. Workarounds
14212: are representing the address in some relative form (e.g., relative to
14213: the CFA, which is present in some register), or loading the address from
14214: a place where it is stored in a non-mangled form.
14215: @end itemize
14216: @end itemize
14217:
14218: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14219: @section Non-Relocatable Image Files
14220: @cindex non-relocatable image files
1.26 crook 14221: @cindex image file, non-relocatable
1.1 anton 14222:
14223: These files are simple memory dumps of the dictionary. They are specific
14224: to the executable (i.e., @file{gforth} file) they were created
14225: with. What's worse, they are specific to the place on which the
14226: dictionary resided when the image was created. Now, there is no
14227: guarantee that the dictionary will reside at the same place the next
14228: time you start Gforth, so there's no guarantee that a non-relocatable
14229: image will work the next time (Gforth will complain instead of crashing,
14230: though).
14231:
14232: You can create a non-relocatable image file with
14233:
1.44 crook 14234:
1.1 anton 14235: doc-savesystem
14236:
1.44 crook 14237:
1.1 anton 14238: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14239: @section Data-Relocatable Image Files
14240: @cindex data-relocatable image files
1.26 crook 14241: @cindex image file, data-relocatable
1.1 anton 14242:
14243: These files contain relocatable data addresses, but fixed code addresses
14244: (instead of tokens). They are specific to the executable (i.e.,
14245: @file{gforth} file) they were created with. For direct threading on some
14246: architectures (e.g., the i386), data-relocatable images do not work. You
14247: get a data-relocatable image, if you use @file{gforthmi} with a
14248: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14249: Relocatable Image Files}).
14250:
14251: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14252: @section Fully Relocatable Image Files
14253: @cindex fully relocatable image files
1.26 crook 14254: @cindex image file, fully relocatable
1.1 anton 14255:
14256: @cindex @file{kern*.fi}, relocatability
14257: @cindex @file{gforth.fi}, relocatability
14258: These image files have relocatable data addresses, and tokens for code
14259: addresses. They can be used with different binaries (e.g., with and
14260: without debugging) on the same machine, and even across machines with
14261: the same data formats (byte order, cell size, floating point
14262: format). However, they are usually specific to the version of Gforth
14263: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14264: are fully relocatable.
14265:
14266: There are two ways to create a fully relocatable image file:
14267:
14268: @menu
1.29 crook 14269: * gforthmi:: The normal way
1.1 anton 14270: * cross.fs:: The hard way
14271: @end menu
14272:
14273: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14274: @subsection @file{gforthmi}
14275: @cindex @file{comp-i.fs}
14276: @cindex @file{gforthmi}
14277:
14278: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14279: image @i{file} that contains everything you would load by invoking
14280: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14281: @example
1.29 crook 14282: gforthmi @i{file} @i{options}
1.1 anton 14283: @end example
14284:
14285: E.g., if you want to create an image @file{asm.fi} that has the file
14286: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14287: like this:
14288:
14289: @example
14290: gforthmi asm.fi asm.fs
14291: @end example
14292:
1.27 crook 14293: @file{gforthmi} is implemented as a sh script and works like this: It
14294: produces two non-relocatable images for different addresses and then
14295: compares them. Its output reflects this: first you see the output (if
1.62 crook 14296: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14297: files, then you see the output of the comparing program: It displays the
14298: offset used for data addresses and the offset used for code addresses;
1.1 anton 14299: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14300: image files, it displays a line like this:
1.1 anton 14301:
14302: @example
14303: 78DC BFFFFA50 BFFFFA40
14304: @end example
14305:
14306: This means that at offset $78dc from @code{forthstart}, one input image
14307: contains $bffffa50, and the other contains $bffffa40. Since these cells
14308: cannot be represented correctly in the output image, you should examine
14309: these places in the dictionary and verify that these cells are dead
14310: (i.e., not read before they are written).
1.39 anton 14311:
14312: @cindex --application, @code{gforthmi} option
14313: If you insert the option @code{--application} in front of the image file
14314: name, you will get an image that uses the @code{--appl-image} option
14315: instead of the @code{--image-file} option (@pxref{Invoking
14316: Gforth}). When you execute such an image on Unix (by typing the image
14317: name as command), the Gforth engine will pass all options to the image
14318: instead of trying to interpret them as engine options.
1.1 anton 14319:
1.27 crook 14320: If you type @file{gforthmi} with no arguments, it prints some usage
14321: instructions.
14322:
1.1 anton 14323: @cindex @code{savesystem} during @file{gforthmi}
14324: @cindex @code{bye} during @file{gforthmi}
14325: @cindex doubly indirect threaded code
1.44 crook 14326: @cindex environment variables
14327: @cindex @code{GFORTHD} -- environment variable
14328: @cindex @code{GFORTH} -- environment variable
1.1 anton 14329: @cindex @code{gforth-ditc}
1.29 crook 14330: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14331: words @code{savesystem} and @code{bye} must be visible. A special doubly
14332: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14333: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14334: this executable through the environment variable @code{GFORTHD}
14335: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14336: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14337: data-relocatable image (because there is no code address offset). The
14338: normal @file{gforth} executable is used for creating the relocatable
14339: image; you can pass the exact filename of this executable through the
14340: environment variable @code{GFORTH}.
1.1 anton 14341:
14342: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14343: @subsection @file{cross.fs}
14344: @cindex @file{cross.fs}
14345: @cindex cross-compiler
14346: @cindex metacompiler
1.47 crook 14347: @cindex target compiler
1.1 anton 14348:
14349: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14350: programming language (@pxref{Cross Compiler}).
1.1 anton 14351:
1.47 crook 14352: @code{cross} allows you to create image files for machines with
1.1 anton 14353: different data sizes and data formats than the one used for generating
14354: the image file. You can also use it to create an application image that
14355: does not contain a Forth compiler. These features are bought with
14356: restrictions and inconveniences in programming. E.g., addresses have to
14357: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14358: order to make the code relocatable.
14359:
14360:
14361: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14362: @section Stack and Dictionary Sizes
14363: @cindex image file, stack and dictionary sizes
14364: @cindex dictionary size default
14365: @cindex stack size default
14366:
14367: If you invoke Gforth with a command line flag for the size
14368: (@pxref{Invoking Gforth}), the size you specify is stored in the
14369: dictionary. If you save the dictionary with @code{savesystem} or create
14370: an image with @file{gforthmi}, this size will become the default
14371: for the resulting image file. E.g., the following will create a
1.21 crook 14372: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14373:
14374: @example
14375: gforthmi gforth.fi -m 1M
14376: @end example
14377:
14378: In other words, if you want to set the default size for the dictionary
14379: and the stacks of an image, just invoke @file{gforthmi} with the
14380: appropriate options when creating the image.
14381:
14382: @cindex stack size, cache-friendly
14383: Note: For cache-friendly behaviour (i.e., good performance), you should
14384: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14385: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14386: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14387:
14388: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14389: @section Running Image Files
14390: @cindex running image files
14391: @cindex invoking image files
14392: @cindex image file invocation
14393:
14394: @cindex -i, invoke image file
14395: @cindex --image file, invoke image file
1.29 crook 14396: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14397: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14398: @example
1.29 crook 14399: gforth -i @i{image}
1.1 anton 14400: @end example
14401:
14402: @cindex executable image file
1.26 crook 14403: @cindex image file, executable
1.1 anton 14404: If your operating system supports starting scripts with a line of the
14405: form @code{#! ...}, you just have to type the image file name to start
14406: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14407: just a convention). I.e., to run Gforth with the image file @i{image},
14408: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14409: This works because every @code{.fi} file starts with a line of this
14410: format:
14411:
14412: @example
14413: #! /usr/local/bin/gforth-0.4.0 -i
14414: @end example
14415:
14416: The file and pathname for the Gforth engine specified on this line is
14417: the specific Gforth executable that it was built against; i.e. the value
14418: of the environment variable @code{GFORTH} at the time that
14419: @file{gforthmi} was executed.
1.1 anton 14420:
1.27 crook 14421: You can make use of the same shell capability to make a Forth source
14422: file into an executable. For example, if you place this text in a file:
1.26 crook 14423:
14424: @example
14425: #! /usr/local/bin/gforth
14426:
14427: ." Hello, world" CR
14428: bye
14429: @end example
14430:
14431: @noindent
1.27 crook 14432: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14433: directly from the command line. The sequence @code{#!} is used in two
14434: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14435: system@footnote{The Unix kernel actually recognises two types of files:
14436: executable files and files of data, where the data is processed by an
14437: interpreter that is specified on the ``interpreter line'' -- the first
14438: line of the file, starting with the sequence #!. There may be a small
14439: limit (e.g., 32) on the number of characters that may be specified on
14440: the interpreter line.} secondly it is treated as a comment character by
14441: Gforth. Because of the second usage, a space is required between
1.80 anton 14442: @code{#!} and the path to the executable (moreover, some Unixes
14443: require the sequence @code{#! /}).
1.27 crook 14444:
14445: The disadvantage of this latter technique, compared with using
1.80 anton 14446: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14447: compiled on-the-fly, each time the program is invoked.
1.26 crook 14448:
1.1 anton 14449: doc-#!
14450:
1.44 crook 14451:
1.1 anton 14452: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14453: @section Modifying the Startup Sequence
14454: @cindex startup sequence for image file
14455: @cindex image file initialization sequence
14456: @cindex initialization sequence of image file
14457:
1.120 anton 14458: You can add your own initialization to the startup sequence of an image
14459: through the deferred word @code{'cold}. @code{'cold} is invoked just
14460: before the image-specific command line processing (i.e., loading files
14461: and evaluating (@code{-e}) strings) starts.
1.1 anton 14462:
14463: A sequence for adding your initialization usually looks like this:
14464:
14465: @example
14466: :noname
14467: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14468: ... \ your stuff
14469: ; IS 'cold
14470: @end example
14471:
14472: @cindex turnkey image files
1.26 crook 14473: @cindex image file, turnkey applications
1.1 anton 14474: You can make a turnkey image by letting @code{'cold} execute a word
14475: (your turnkey application) that never returns; instead, it exits Gforth
14476: via @code{bye} or @code{throw}.
14477:
1.121 anton 14478: You can access the (image-specific) command-line arguments through
14479: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14480: arguments}).
1.1 anton 14481:
1.26 crook 14482: If @code{'cold} exits normally, Gforth processes the command-line
14483: arguments as files to be loaded and strings to be evaluated. Therefore,
14484: @code{'cold} should remove the arguments it has used in this case.
14485:
14486: doc-'cold
1.44 crook 14487:
1.1 anton 14488: @c ******************************************************************
1.113 anton 14489: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14490: @chapter Engine
14491: @cindex engine
14492: @cindex virtual machine
14493:
1.26 crook 14494: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14495: may be helpful for finding your way in the Gforth sources.
14496:
1.109 anton 14497: The ideas in this section have also been published in the following
14498: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14499: Forth-Tagung '93; M. Anton Ertl,
14500: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14501: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14502: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14503: Threaded code variations and optimizations (extended version)}},
14504: Forth-Tagung '02.
1.1 anton 14505:
14506: @menu
14507: * Portability::
14508: * Threading::
14509: * Primitives::
14510: * Performance::
14511: @end menu
14512:
14513: @node Portability, Threading, Engine, Engine
14514: @section Portability
14515: @cindex engine portability
14516:
1.26 crook 14517: An important goal of the Gforth Project is availability across a wide
14518: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14519: achieved this goal by manually coding the engine in assembly language
14520: for several then-popular processors. This approach is very
14521: labor-intensive and the results are short-lived due to progress in
14522: computer architecture.
1.1 anton 14523:
14524: @cindex C, using C for the engine
14525: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14526: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14527: particularly popular for UNIX-based Forths due to the large variety of
14528: architectures of UNIX machines. Unfortunately an implementation in C
14529: does not mix well with the goals of efficiency and with using
14530: traditional techniques: Indirect or direct threading cannot be expressed
14531: in C, and switch threading, the fastest technique available in C, is
14532: significantly slower. Another problem with C is that it is very
14533: cumbersome to express double integer arithmetic.
14534:
14535: @cindex GNU C for the engine
14536: @cindex long long
14537: Fortunately, there is a portable language that does not have these
14538: limitations: GNU C, the version of C processed by the GNU C compiler
14539: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14540: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14541: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14542: threading possible, its @code{long long} type (@pxref{Long Long, ,
14543: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14544: double numbers on many systems. GNU C is freely available on all
1.1 anton 14545: important (and many unimportant) UNIX machines, VMS, 80386s running
14546: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14547: on all these machines.
14548:
14549: Writing in a portable language has the reputation of producing code that
14550: is slower than assembly. For our Forth engine we repeatedly looked at
14551: the code produced by the compiler and eliminated most compiler-induced
14552: inefficiencies by appropriate changes in the source code.
14553:
14554: @cindex explicit register declarations
14555: @cindex --enable-force-reg, configuration flag
14556: @cindex -DFORCE_REG
14557: However, register allocation cannot be portably influenced by the
14558: programmer, leading to some inefficiencies on register-starved
14559: machines. We use explicit register declarations (@pxref{Explicit Reg
14560: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14561: improve the speed on some machines. They are turned on by using the
14562: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14563: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14564: machine, but also on the compiler version: On some machines some
14565: compiler versions produce incorrect code when certain explicit register
14566: declarations are used. So by default @code{-DFORCE_REG} is not used.
14567:
14568: @node Threading, Primitives, Portability, Engine
14569: @section Threading
14570: @cindex inner interpreter implementation
14571: @cindex threaded code implementation
14572:
14573: @cindex labels as values
14574: GNU C's labels as values extension (available since @code{gcc-2.0},
14575: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14576: makes it possible to take the address of @i{label} by writing
14577: @code{&&@i{label}}. This address can then be used in a statement like
14578: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14579: @code{goto x}.
14580:
1.26 crook 14581: @cindex @code{NEXT}, indirect threaded
1.1 anton 14582: @cindex indirect threaded inner interpreter
14583: @cindex inner interpreter, indirect threaded
1.26 crook 14584: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14585: @example
14586: cfa = *ip++;
14587: ca = *cfa;
14588: goto *ca;
14589: @end example
14590: @cindex instruction pointer
14591: For those unfamiliar with the names: @code{ip} is the Forth instruction
14592: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14593: execution token and points to the code field of the next word to be
14594: executed; The @code{ca} (code address) fetched from there points to some
14595: executable code, e.g., a primitive or the colon definition handler
14596: @code{docol}.
14597:
1.26 crook 14598: @cindex @code{NEXT}, direct threaded
1.1 anton 14599: @cindex direct threaded inner interpreter
14600: @cindex inner interpreter, direct threaded
14601: Direct threading is even simpler:
14602: @example
14603: ca = *ip++;
14604: goto *ca;
14605: @end example
14606:
14607: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14608: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14609:
14610: @menu
14611: * Scheduling::
14612: * Direct or Indirect Threaded?::
1.109 anton 14613: * Dynamic Superinstructions::
1.1 anton 14614: * DOES>::
14615: @end menu
14616:
14617: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14618: @subsection Scheduling
14619: @cindex inner interpreter optimization
14620:
14621: There is a little complication: Pipelined and superscalar processors,
14622: i.e., RISC and some modern CISC machines can process independent
14623: instructions while waiting for the results of an instruction. The
14624: compiler usually reorders (schedules) the instructions in a way that
14625: achieves good usage of these delay slots. However, on our first tries
14626: the compiler did not do well on scheduling primitives. E.g., for
14627: @code{+} implemented as
14628: @example
14629: n=sp[0]+sp[1];
14630: sp++;
14631: sp[0]=n;
14632: NEXT;
14633: @end example
1.81 anton 14634: the @code{NEXT} comes strictly after the other code, i.e., there is
14635: nearly no scheduling. After a little thought the problem becomes clear:
14636: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14637: addresses (and the version of @code{gcc} we used would not know it even
14638: if it was possible), so it could not move the load of the cfa above the
14639: store to the TOS. Indeed the pointers could be the same, if code on or
14640: very near the top of stack were executed. In the interest of speed we
14641: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14642: in scheduling: @code{NEXT} is divided into several parts:
14643: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14644: like:
1.1 anton 14645: @example
1.81 anton 14646: NEXT_P0;
1.1 anton 14647: n=sp[0]+sp[1];
14648: sp++;
14649: NEXT_P1;
14650: sp[0]=n;
14651: NEXT_P2;
14652: @end example
14653:
1.81 anton 14654: There are various schemes that distribute the different operations of
14655: NEXT between these parts in several ways; in general, different schemes
14656: perform best on different processors. We use a scheme for most
14657: architectures that performs well for most processors of this
1.109 anton 14658: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14659: the scheme on installation time.
14660:
1.1 anton 14661:
1.109 anton 14662: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14663: @subsection Direct or Indirect Threaded?
14664: @cindex threading, direct or indirect?
14665:
1.109 anton 14666: Threaded forth code consists of references to primitives (simple machine
14667: code routines like @code{+}) and to non-primitives (e.g., colon
14668: definitions, variables, constants); for a specific class of
14669: non-primitives (e.g., variables) there is one code routine (e.g.,
14670: @code{dovar}), but each variable needs a separate reference to its data.
14671:
14672: Traditionally Forth has been implemented as indirect threaded code,
14673: because this allows to use only one cell to reference a non-primitive
14674: (basically you point to the data, and find the code address there).
14675:
14676: @cindex primitive-centric threaded code
14677: However, threaded code in Gforth (since 0.6.0) uses two cells for
14678: non-primitives, one for the code address, and one for the data address;
14679: the data pointer is an immediate argument for the virtual machine
14680: instruction represented by the code address. We call this
14681: @emph{primitive-centric} threaded code, because all code addresses point
14682: to simple primitives. E.g., for a variable, the code address is for
14683: @code{lit} (also used for integer literals like @code{99}).
14684:
14685: Primitive-centric threaded code allows us to use (faster) direct
14686: threading as dispatch method, completely portably (direct threaded code
14687: in Gforth before 0.6.0 required architecture-specific code). It also
14688: eliminates the performance problems related to I-cache consistency that
14689: 386 implementations have with direct threaded code, and allows
14690: additional optimizations.
14691:
14692: @cindex hybrid direct/indirect threaded code
14693: There is a catch, however: the @var{xt} parameter of @code{execute} can
14694: occupy only one cell, so how do we pass non-primitives with their code
14695: @emph{and} data addresses to them? Our answer is to use indirect
14696: threaded dispatch for @code{execute} and other words that use a
14697: single-cell xt. So, normal threaded code in colon definitions uses
14698: direct threading, and @code{execute} and similar words, which dispatch
14699: to xts on the data stack, use indirect threaded code. We call this
14700: @emph{hybrid direct/indirect} threaded code.
14701:
14702: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14703: @cindex gforth engine
14704: @cindex gforth-fast engine
14705: The engines @command{gforth} and @command{gforth-fast} use hybrid
14706: direct/indirect threaded code. This means that with these engines you
14707: cannot use @code{,} to compile an xt. Instead, you have to use
14708: @code{compile,}.
14709:
14710: @cindex gforth-itc engine
1.115 anton 14711: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14712: This engine uses plain old indirect threaded code. It still compiles in
14713: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14714: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14715: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14716: and execute @code{' , is compile,}. Your program can check if it is
14717: running on a hybrid direct/indirect threaded engine or a pure indirect
14718: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14719:
14720:
14721: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14722: @subsection Dynamic Superinstructions
14723: @cindex Dynamic superinstructions with replication
14724: @cindex Superinstructions
14725: @cindex Replication
14726:
14727: The engines @command{gforth} and @command{gforth-fast} use another
14728: optimization: Dynamic superinstructions with replication. As an
14729: example, consider the following colon definition:
14730:
14731: @example
14732: : squared ( n1 -- n2 )
14733: dup * ;
14734: @end example
14735:
14736: Gforth compiles this into the threaded code sequence
14737:
14738: @example
14739: dup
14740: *
14741: ;s
14742: @end example
14743:
14744: In normal direct threaded code there is a code address occupying one
14745: cell for each of these primitives. Each code address points to a
14746: machine code routine, and the interpreter jumps to this machine code in
14747: order to execute the primitive. The routines for these three
14748: primitives are (in @command{gforth-fast} on the 386):
14749:
14750: @example
14751: Code dup
14752: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14753: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14754: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14755: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14756: end-code
14757: Code *
14758: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14759: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14760: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14761: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14762: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14763: end-code
14764: Code ;s
14765: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14766: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14767: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14768: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14769: end-code
14770: @end example
14771:
14772: With dynamic superinstructions and replication the compiler does not
14773: just lay down the threaded code, but also copies the machine code
14774: fragments, usually without the jump at the end.
14775:
14776: @example
14777: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14778: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14779: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14780: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14781: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14782: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14783: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14784: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14785: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14786: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14787: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14788: @end example
14789:
14790: Only when a threaded-code control-flow change happens (e.g., in
14791: @code{;s}), the jump is appended. This optimization eliminates many of
14792: these jumps and makes the rest much more predictable. The speedup
14793: depends on the processor and the application; on the Athlon and Pentium
14794: III this optimization typically produces a speedup by a factor of 2.
14795:
14796: The code addresses in the direct-threaded code are set to point to the
14797: appropriate points in the copied machine code, in this example like
14798: this:
1.1 anton 14799:
1.109 anton 14800: @example
14801: primitive code address
14802: dup $4057D27D
14803: * $4057D286
14804: ;s $4057D292
14805: @end example
14806:
14807: Thus there can be threaded-code jumps to any place in this piece of
14808: code. This also simplifies decompilation quite a bit.
14809:
14810: @cindex --no-dynamic command-line option
14811: @cindex --no-super command-line option
14812: You can disable this optimization with @option{--no-dynamic}. You can
14813: use the copying without eliminating the jumps (i.e., dynamic
14814: replication, but without superinstructions) with @option{--no-super};
14815: this gives the branch prediction benefit alone; the effect on
1.110 anton 14816: performance depends on the CPU; on the Athlon and Pentium III the
14817: speedup is a little less than for dynamic superinstructions with
14818: replication.
14819:
14820: @cindex patching threaded code
14821: One use of these options is if you want to patch the threaded code.
14822: With superinstructions, many of the dispatch jumps are eliminated, so
14823: patching often has no effect. These options preserve all the dispatch
14824: jumps.
1.109 anton 14825:
14826: @cindex --dynamic command-line option
1.110 anton 14827: On some machines dynamic superinstructions are disabled by default,
14828: because it is unsafe on these machines. However, if you feel
14829: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14830:
14831: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14832: @subsection DOES>
14833: @cindex @code{DOES>} implementation
14834:
1.26 crook 14835: @cindex @code{dodoes} routine
14836: @cindex @code{DOES>}-code
1.1 anton 14837: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14838: the chunk of code executed by every word defined by a
1.109 anton 14839: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14840: this is only needed if the xt of the word is @code{execute}d. The main
14841: problem here is: How to find the Forth code to be executed, i.e. the
14842: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14843: solutions:
1.1 anton 14844:
1.21 crook 14845: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14846: @code{DOES>}-code address is stored in the cell after the code address
14847: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14848: illegal in the Forth-79 and all later standards, because in fig-Forth
14849: this address lies in the body (which is illegal in these
14850: standards). However, by making the code field larger for all words this
14851: solution becomes legal again. We use this approach. Leaving a cell
14852: unused in most words is a bit wasteful, but on the machines we are
14853: targeting this is hardly a problem.
14854:
1.1 anton 14855:
14856: @node Primitives, Performance, Threading, Engine
14857: @section Primitives
14858: @cindex primitives, implementation
14859: @cindex virtual machine instructions, implementation
14860:
14861: @menu
14862: * Automatic Generation::
14863: * TOS Optimization::
14864: * Produced code::
14865: @end menu
14866:
14867: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14868: @subsection Automatic Generation
14869: @cindex primitives, automatic generation
14870:
14871: @cindex @file{prims2x.fs}
1.109 anton 14872:
1.1 anton 14873: Since the primitives are implemented in a portable language, there is no
14874: longer any need to minimize the number of primitives. On the contrary,
14875: having many primitives has an advantage: speed. In order to reduce the
14876: number of errors in primitives and to make programming them easier, we
1.109 anton 14877: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14878: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14879: generates most (and sometimes all) of the C code for a primitive from
14880: the stack effect notation. The source for a primitive has the following
14881: form:
1.1 anton 14882:
14883: @cindex primitive source format
14884: @format
1.58 anton 14885: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14886: [@code{""}@i{glossary entry}@code{""}]
14887: @i{C code}
1.1 anton 14888: [@code{:}
1.29 crook 14889: @i{Forth code}]
1.1 anton 14890: @end format
14891:
14892: The items in brackets are optional. The category and glossary fields
14893: are there for generating the documentation, the Forth code is there
14894: for manual implementations on machines without GNU C. E.g., the source
14895: for the primitive @code{+} is:
14896: @example
1.58 anton 14897: + ( n1 n2 -- n ) core plus
1.1 anton 14898: n = n1+n2;
14899: @end example
14900:
14901: This looks like a specification, but in fact @code{n = n1+n2} is C
14902: code. Our primitive generation tool extracts a lot of information from
14903: the stack effect notations@footnote{We use a one-stack notation, even
14904: though we have separate data and floating-point stacks; The separate
14905: notation can be generated easily from the unified notation.}: The number
14906: of items popped from and pushed on the stack, their type, and by what
14907: name they are referred to in the C code. It then generates a C code
14908: prelude and postlude for each primitive. The final C code for @code{+}
14909: looks like this:
14910:
14911: @example
1.46 pazsan 14912: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14913: /* */ /* documentation */
1.81 anton 14914: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14915: @{
14916: DEF_CA /* definition of variable ca (indirect threading) */
14917: Cell n1; /* definitions of variables */
14918: Cell n2;
14919: Cell n;
1.81 anton 14920: NEXT_P0; /* NEXT part 0 */
1.1 anton 14921: n1 = (Cell) sp[1]; /* input */
14922: n2 = (Cell) TOS;
14923: sp += 1; /* stack adjustment */
14924: @{
14925: n = n1+n2; /* C code taken from the source */
14926: @}
14927: NEXT_P1; /* NEXT part 1 */
14928: TOS = (Cell)n; /* output */
14929: NEXT_P2; /* NEXT part 2 */
14930: @}
14931: @end example
14932:
14933: This looks long and inefficient, but the GNU C compiler optimizes quite
14934: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14935: HP RISC machines: Defining the @code{n}s does not produce any code, and
14936: using them as intermediate storage also adds no cost.
14937:
1.26 crook 14938: There are also other optimizations that are not illustrated by this
14939: example: assignments between simple variables are usually for free (copy
1.1 anton 14940: propagation). If one of the stack items is not used by the primitive
14941: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14942: (dead code elimination). On the other hand, there are some things that
14943: the compiler does not do, therefore they are performed by
14944: @file{prims2x.fs}: The compiler does not optimize code away that stores
14945: a stack item to the place where it just came from (e.g., @code{over}).
14946:
14947: While programming a primitive is usually easy, there are a few cases
14948: where the programmer has to take the actions of the generator into
14949: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14950: fall through to @code{NEXT}.
1.109 anton 14951:
14952: For more information
1.1 anton 14953:
14954: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14955: @subsection TOS Optimization
14956: @cindex TOS optimization for primitives
14957: @cindex primitives, keeping the TOS in a register
14958:
14959: An important optimization for stack machine emulators, e.g., Forth
14960: engines, is keeping one or more of the top stack items in
1.29 crook 14961: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14962: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14963: @itemize @bullet
14964: @item
1.29 crook 14965: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14966: due to fewer loads from and stores to the stack.
1.29 crook 14967: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14968: @i{y<n}, due to additional moves between registers.
1.1 anton 14969: @end itemize
14970:
14971: @cindex -DUSE_TOS
14972: @cindex -DUSE_NO_TOS
14973: In particular, keeping one item in a register is never a disadvantage,
14974: if there are enough registers. Keeping two items in registers is a
14975: disadvantage for frequent words like @code{?branch}, constants,
14976: variables, literals and @code{i}. Therefore our generator only produces
14977: code that keeps zero or one items in registers. The generated C code
14978: covers both cases; the selection between these alternatives is made at
14979: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14980: code for @code{+} is just a simple variable name in the one-item case,
14981: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14982: GNU C compiler tries to keep simple variables like @code{TOS} in
14983: registers, and it usually succeeds, if there are enough registers.
14984:
14985: @cindex -DUSE_FTOS
14986: @cindex -DUSE_NO_FTOS
14987: The primitive generator performs the TOS optimization for the
14988: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14989: operations the benefit of this optimization is even larger:
14990: floating-point operations take quite long on most processors, but can be
14991: performed in parallel with other operations as long as their results are
14992: not used. If the FP-TOS is kept in a register, this works. If
14993: it is kept on the stack, i.e., in memory, the store into memory has to
14994: wait for the result of the floating-point operation, lengthening the
14995: execution time of the primitive considerably.
14996:
14997: The TOS optimization makes the automatic generation of primitives a
14998: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14999: @code{TOS} is not sufficient. There are some special cases to
15000: consider:
15001: @itemize @bullet
15002: @item In the case of @code{dup ( w -- w w )} the generator must not
15003: eliminate the store to the original location of the item on the stack,
15004: if the TOS optimization is turned on.
15005: @item Primitives with stack effects of the form @code{--}
1.29 crook 15006: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15007: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15008: must load the TOS from the stack at the end. But for the null stack
15009: effect @code{--} no stores or loads should be generated.
15010: @end itemize
15011:
15012: @node Produced code, , TOS Optimization, Primitives
15013: @subsection Produced code
15014: @cindex primitives, assembly code listing
15015:
15016: @cindex @file{engine.s}
15017: To see what assembly code is produced for the primitives on your machine
15018: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15019: look at the resulting file @file{engine.s}. Alternatively, you can also
15020: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15021:
15022: @node Performance, , Primitives, Engine
15023: @section Performance
15024: @cindex performance of some Forth interpreters
15025: @cindex engine performance
15026: @cindex benchmarking Forth systems
15027: @cindex Gforth performance
15028:
15029: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15030: impossible to write a significantly faster threaded-code engine.
1.1 anton 15031:
15032: On register-starved machines like the 386 architecture processors
15033: improvements are possible, because @code{gcc} does not utilize the
15034: registers as well as a human, even with explicit register declarations;
15035: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15036: and hand-tuned it for the 486; this system is 1.19 times faster on the
15037: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15038: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15039: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15040: registers fit in real registers (and we can even afford to use the TOS
15041: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15042: earlier results. And dynamic superinstructions provide another speedup
15043: (but only around a factor 1.2 on the 486).
1.1 anton 15044:
15045: @cindex Win32Forth performance
15046: @cindex NT Forth performance
15047: @cindex eforth performance
15048: @cindex ThisForth performance
15049: @cindex PFE performance
15050: @cindex TILE performance
1.81 anton 15051: The potential advantage of assembly language implementations is not
1.112 anton 15052: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15053: (direct threaded, compiled with @code{gcc-2.95.1} and
15054: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15055: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15056: (with and without peephole (aka pinhole) optimization of the threaded
15057: code); all these systems were written in assembly language. We also
15058: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15059: with @code{gcc-2.6.3} with the default configuration for Linux:
15060: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15061: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15062: employs peephole optimization of the threaded code) and TILE (compiled
15063: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15064: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15065: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15066: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15067: then extended it to run the benchmarks, added the peephole optimizer,
15068: ran the benchmarks and reported the results.
1.40 anton 15069:
1.1 anton 15070: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15071: matrix multiplication come from the Stanford integer benchmarks and have
15072: been translated into Forth by Martin Fraeman; we used the versions
15073: included in the TILE Forth package, but with bigger data set sizes; and
15074: a recursive Fibonacci number computation for benchmarking calling
15075: performance. The following table shows the time taken for the benchmarks
15076: scaled by the time taken by Gforth (in other words, it shows the speedup
15077: factor that Gforth achieved over the other systems).
15078:
15079: @example
1.112 anton 15080: relative Win32- NT eforth This-
15081: time Gforth Forth Forth eforth +opt PFE Forth TILE
15082: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15083: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15084: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15085: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15086: @end example
15087:
1.26 crook 15088: You may be quite surprised by the good performance of Gforth when
15089: compared with systems written in assembly language. One important reason
15090: for the disappointing performance of these other systems is probably
15091: that they are not written optimally for the 486 (e.g., they use the
15092: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15093: but costly method for relocating the Forth image: like @code{cforth}, it
15094: computes the actual addresses at run time, resulting in two address
15095: computations per @code{NEXT} (@pxref{Image File Background}).
15096:
1.1 anton 15097: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15098: explained with the self-imposed restriction of the latter systems to
15099: standard C, which makes efficient threading impossible (however, the
1.4 anton 15100: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15101: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15102: Moreover, current C compilers have a hard time optimizing other aspects
15103: of the ThisForth and the TILE source.
15104:
1.26 crook 15105: The performance of Gforth on 386 architecture processors varies widely
15106: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15107: allocate any of the virtual machine registers into real machine
15108: registers by itself and would not work correctly with explicit register
1.112 anton 15109: declarations, giving a significantly slower engine (on a 486DX2/66
15110: running the Sieve) than the one measured above.
1.1 anton 15111:
1.26 crook 15112: Note that there have been several releases of Win32Forth since the
15113: release presented here, so the results presented above may have little
1.40 anton 15114: predictive value for the performance of Win32Forth today (results for
15115: the current release on an i486DX2/66 are welcome).
1.1 anton 15116:
15117: @cindex @file{Benchres}
1.66 anton 15118: In
15119: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15120: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15121: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15122: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15123: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15124: than the version used here. You can find a newer version of these
15125: measurements at
1.47 crook 15126: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15127: find numbers for Gforth on various machines in @file{Benchres}.
15128:
1.26 crook 15129: @c ******************************************************************
1.113 anton 15130: @c @node Binding to System Library, Cross Compiler, Engine, Top
15131: @c @chapter Binding to System Library
1.13 pazsan 15132:
1.113 anton 15133: @c ****************************************************************
15134: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15135: @chapter Cross Compiler
1.47 crook 15136: @cindex @file{cross.fs}
15137: @cindex cross-compiler
15138: @cindex metacompiler
15139: @cindex target compiler
1.13 pazsan 15140:
1.46 pazsan 15141: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15142: mostly written in Forth, including crucial parts like the outer
15143: interpreter and compiler, it needs compiled Forth code to get
15144: started. The cross compiler allows to create new images for other
15145: architectures, even running under another Forth system.
1.13 pazsan 15146:
15147: @menu
1.67 anton 15148: * Using the Cross Compiler::
15149: * How the Cross Compiler Works::
1.13 pazsan 15150: @end menu
15151:
1.21 crook 15152: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15153: @section Using the Cross Compiler
1.46 pazsan 15154:
15155: The cross compiler uses a language that resembles Forth, but isn't. The
15156: main difference is that you can execute Forth code after definition,
15157: while you usually can't execute the code compiled by cross, because the
15158: code you are compiling is typically for a different computer than the
15159: one you are compiling on.
15160:
1.81 anton 15161: @c anton: This chapter is somewhat different from waht I would expect: I
15162: @c would expect an explanation of the cross language and how to create an
15163: @c application image with it. The section explains some aspects of
15164: @c creating a Gforth kernel.
15165:
1.46 pazsan 15166: The Makefile is already set up to allow you to create kernels for new
15167: architectures with a simple make command. The generic kernels using the
15168: GCC compiled virtual machine are created in the normal build process
15169: with @code{make}. To create a embedded Gforth executable for e.g. the
15170: 8086 processor (running on a DOS machine), type
15171:
15172: @example
15173: make kernl-8086.fi
15174: @end example
15175:
15176: This will use the machine description from the @file{arch/8086}
15177: directory to create a new kernel. A machine file may look like that:
15178:
15179: @example
15180: \ Parameter for target systems 06oct92py
15181:
15182: 4 Constant cell \ cell size in bytes
15183: 2 Constant cell<< \ cell shift to bytes
15184: 5 Constant cell>bit \ cell shift to bits
15185: 8 Constant bits/char \ bits per character
15186: 8 Constant bits/byte \ bits per byte [default: 8]
15187: 8 Constant float \ bytes per float
15188: 8 Constant /maxalign \ maximum alignment in bytes
15189: false Constant bigendian \ byte order
15190: ( true=big, false=little )
15191:
15192: include machpc.fs \ feature list
15193: @end example
15194:
15195: This part is obligatory for the cross compiler itself, the feature list
15196: is used by the kernel to conditionally compile some features in and out,
15197: depending on whether the target supports these features.
15198:
15199: There are some optional features, if you define your own primitives,
15200: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15201: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15202: @code{prims-include} includes primitives, and @code{>boot} prepares for
15203: booting.
15204:
15205: @example
15206: : asm-include ." Include assembler" cr
15207: s" arch/8086/asm.fs" included ;
15208:
15209: : prims-include ." Include primitives" cr
15210: s" arch/8086/prim.fs" included ;
15211:
15212: : >boot ." Prepare booting" cr
15213: s" ' boot >body into-forth 1+ !" evaluate ;
15214: @end example
15215:
15216: These words are used as sort of macro during the cross compilation in
1.81 anton 15217: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15218: be possible --- but more complicated --- to write a new kernel project
15219: file, too.
15220:
15221: @file{kernel/main.fs} expects the machine description file name on the
15222: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15223: @code{mach-file} leaves a counted string on the stack, or
15224: @code{machine-file} leaves an address, count pair of the filename on the
15225: stack.
15226:
15227: The feature list is typically controlled using @code{SetValue}, generic
15228: files that are used by several projects can use @code{DefaultValue}
15229: instead. Both functions work like @code{Value}, when the value isn't
15230: defined, but @code{SetValue} works like @code{to} if the value is
15231: defined, and @code{DefaultValue} doesn't set anything, if the value is
15232: defined.
15233:
15234: @example
15235: \ generic mach file for pc gforth 03sep97jaw
15236:
15237: true DefaultValue NIL \ relocating
15238:
15239: >ENVIRON
15240:
15241: true DefaultValue file \ controls the presence of the
15242: \ file access wordset
15243: true DefaultValue OS \ flag to indicate a operating system
15244:
15245: true DefaultValue prims \ true: primitives are c-code
15246:
15247: true DefaultValue floating \ floating point wordset is present
15248:
15249: true DefaultValue glocals \ gforth locals are present
15250: \ will be loaded
15251: true DefaultValue dcomps \ double number comparisons
15252:
15253: true DefaultValue hash \ hashing primitives are loaded/present
15254:
15255: true DefaultValue xconds \ used together with glocals,
15256: \ special conditionals supporting gforths'
15257: \ local variables
15258: true DefaultValue header \ save a header information
15259:
15260: true DefaultValue backtrace \ enables backtrace code
15261:
15262: false DefaultValue ec
15263: false DefaultValue crlf
15264:
15265: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15266:
15267: &16 KB DefaultValue stack-size
15268: &15 KB &512 + DefaultValue fstack-size
15269: &15 KB DefaultValue rstack-size
15270: &14 KB &512 + DefaultValue lstack-size
15271: @end example
1.13 pazsan 15272:
1.48 anton 15273: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15274: @section How the Cross Compiler Works
1.13 pazsan 15275:
15276: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15277: @appendix Bugs
1.1 anton 15278: @cindex bug reporting
15279:
1.21 crook 15280: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15281:
1.103 anton 15282: If you find a bug, please submit a bug report through
15283: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15284:
15285: @itemize @bullet
15286: @item
1.81 anton 15287: A program (or a sequence of keyboard commands) that reproduces the bug.
15288: @item
15289: A description of what you think constitutes the buggy behaviour.
15290: @item
1.21 crook 15291: The Gforth version used (it is announced at the start of an
15292: interactive Gforth session).
15293: @item
15294: The machine and operating system (on Unix
15295: systems @code{uname -a} will report this information).
15296: @item
1.81 anton 15297: The installation options (you can find the configure options at the
15298: start of @file{config.status}) and configuration (@code{configure}
15299: output or @file{config.cache}).
1.21 crook 15300: @item
15301: A complete list of changes (if any) you (or your installer) have made to the
15302: Gforth sources.
15303: @end itemize
1.1 anton 15304:
15305: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15306: to Report Bugs, gcc.info, GNU C Manual}.
15307:
15308:
1.21 crook 15309: @node Origin, Forth-related information, Bugs, Top
15310: @appendix Authors and Ancestors of Gforth
1.1 anton 15311:
15312: @section Authors and Contributors
15313: @cindex authors of Gforth
15314: @cindex contributors to Gforth
15315:
15316: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15317: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15318: lot to the manual. Assemblers and disassemblers were contributed by
15319: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15320: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15321: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15322: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15323: support for calling C libraries. Helpful comments also came from Paul
15324: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15325: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15326: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15327: Gforth-0.2.1 there were also helpful comments from many others; thank
15328: you all, sorry for not listing you here (but digging through my mailbox
15329: to extract your names is on my to-do list).
1.1 anton 15330:
15331: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15332: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15333: was developed across the Internet, and its authors did not meet
1.20 pazsan 15334: physically for the first 4 years of development.
1.1 anton 15335:
15336: @section Pedigree
1.26 crook 15337: @cindex pedigree of Gforth
1.1 anton 15338:
1.81 anton 15339: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15340: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15341:
1.20 pazsan 15342: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15343: 32 bit native code version of VolksForth for the Atari ST, written
15344: mostly by Dietrich Weineck.
15345:
1.81 anton 15346: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15347: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15348: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15349:
15350: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15351: Forth-83 standard. !! Pedigree? When?
15352:
15353: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15354: 1979. Robert Selzer and Bill Ragsdale developed the original
15355: implementation of fig-Forth for the 6502 based on microForth.
15356:
15357: The principal architect of microForth was Dean Sanderson. microForth was
15358: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15359: the 1802, and subsequently implemented on the 8080, the 6800 and the
15360: Z80.
15361:
15362: All earlier Forth systems were custom-made, usually by Charles Moore,
15363: who discovered (as he puts it) Forth during the late 60s. The first full
15364: Forth existed in 1971.
15365:
1.81 anton 15366: A part of the information in this section comes from
15367: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15368: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15369: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15370: SIGPLAN Notices 28(3), 1993. You can find more historical and
15371: genealogical information about Forth there.
1.1 anton 15372:
1.81 anton 15373: @c ------------------------------------------------------------------
1.113 anton 15374: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15375: @appendix Other Forth-related information
15376: @cindex Forth-related information
15377:
1.81 anton 15378: @c anton: I threw most of this stuff out, because it can be found through
15379: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15380:
15381: @cindex comp.lang.forth
15382: @cindex frequently asked questions
1.81 anton 15383: There is an active news group (comp.lang.forth) discussing Forth
15384: (including Gforth) and Forth-related issues. Its
15385: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15386: (frequently asked questions and their answers) contains a lot of
15387: information on Forth. You should read it before posting to
15388: comp.lang.forth.
1.21 crook 15389:
1.81 anton 15390: The ANS Forth standard is most usable in its
15391: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15392:
1.113 anton 15393: @c ---------------------------------------------------
15394: @node Licenses, Word Index, Forth-related information, Top
15395: @appendix Licenses
15396:
15397: @menu
15398: * GNU Free Documentation License:: License for copying this manual.
15399: * Copying:: GPL (for copying this software).
15400: @end menu
15401:
15402: @include fdl.texi
15403:
15404: @include gpl.texi
15405:
15406:
15407:
1.81 anton 15408: @c ------------------------------------------------------------------
1.113 anton 15409: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15410: @unnumbered Word Index
15411:
1.26 crook 15412: This index is a list of Forth words that have ``glossary'' entries
15413: within this manual. Each word is listed with its stack effect and
15414: wordset.
1.1 anton 15415:
15416: @printindex fn
15417:
1.81 anton 15418: @c anton: the name index seems superfluous given the word and concept indices.
15419:
15420: @c @node Name Index, Concept Index, Word Index, Top
15421: @c @unnumbered Name Index
1.41 anton 15422:
1.81 anton 15423: @c This index is a list of Forth words that have ``glossary'' entries
15424: @c within this manual.
1.41 anton 15425:
1.81 anton 15426: @c @printindex ky
1.41 anton 15427:
1.113 anton 15428: @c -------------------------------------------------------
1.81 anton 15429: @node Concept Index, , Word Index, Top
1.1 anton 15430: @unnumbered Concept and Word Index
15431:
1.26 crook 15432: Not all entries listed in this index are present verbatim in the
15433: text. This index also duplicates, in abbreviated form, all of the words
15434: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15435:
15436: @printindex cp
15437:
15438: @bye
1.81 anton 15439:
15440:
1.1 anton 15441:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>