Annotation of gforth/doc/gforth.ds, revision 1.133
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.113 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
226: * Assembler and Code Words::
227: * Threading Words::
1.65 anton 228: * Passing Commands to the OS::
229: * Keeping track of Time::
230: * Miscellaneous Words::
1.12 anton 231:
232: Arithmetic
233:
234: * Single precision::
1.67 anton 235: * Double precision:: Double-cell integer arithmetic
1.12 anton 236: * Bitwise operations::
1.67 anton 237: * Numeric comparison::
1.32 anton 238: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 239: * Floating Point::
240:
241: Stack Manipulation
242:
243: * Data stack::
244: * Floating point stack::
245: * Return stack::
246: * Locals stack::
247: * Stack pointer manipulation::
248:
249: Memory
250:
1.32 anton 251: * Memory model::
252: * Dictionary allocation::
253: * Heap Allocation::
254: * Memory Access::
255: * Address arithmetic::
256: * Memory Blocks::
1.12 anton 257:
258: Control Structures
259:
1.41 anton 260: * Selection:: IF ... ELSE ... ENDIF
261: * Simple Loops:: BEGIN ...
1.32 anton 262: * Counted Loops:: DO
1.67 anton 263: * Arbitrary control structures::
264: * Calls and returns::
1.12 anton 265: * Exception Handling::
266:
267: Defining Words
268:
1.67 anton 269: * CREATE::
1.44 crook 270: * Variables:: Variables and user variables
1.67 anton 271: * Constants::
1.44 crook 272: * Values:: Initialised variables
1.67 anton 273: * Colon Definitions::
1.44 crook 274: * Anonymous Definitions:: Definitions without names
1.71 anton 275: * Supplying names:: Passing definition names as strings
1.67 anton 276: * User-defined Defining Words::
1.44 crook 277: * Deferred words:: Allow forward references
1.67 anton 278: * Aliases::
1.47 crook 279:
1.63 anton 280: User-defined Defining Words
281:
282: * CREATE..DOES> applications::
283: * CREATE..DOES> details::
284: * Advanced does> usage example::
1.91 anton 285: * @code{Const-does>}::
1.63 anton 286:
1.47 crook 287: Interpretation and Compilation Semantics
288:
1.67 anton 289: * Combined words::
1.12 anton 290:
1.71 anton 291: Tokens for Words
292:
293: * Execution token:: represents execution/interpretation semantics
294: * Compilation token:: represents compilation semantics
295: * Name token:: represents named words
296:
1.82 anton 297: Compiling words
298:
299: * Literals:: Compiling data values
300: * Macros:: Compiling words
301:
1.21 crook 302: The Text Interpreter
303:
1.67 anton 304: * Input Sources::
305: * Number Conversion::
306: * Interpret/Compile states::
307: * Interpreter Directives::
1.21 crook 308:
1.26 crook 309: Word Lists
310:
1.75 anton 311: * Vocabularies::
1.67 anton 312: * Why use word lists?::
1.75 anton 313: * Word list example::
1.26 crook 314:
315: Files
316:
1.48 anton 317: * Forth source files::
318: * General files::
319: * Search Paths::
320:
321: Search Paths
322:
1.75 anton 323: * Source Search Paths::
1.26 crook 324: * General Search Paths::
325:
326: Other I/O
327:
1.32 anton 328: * Simple numeric output:: Predefined formats
329: * Formatted numeric output:: Formatted (pictured) output
330: * String Formats:: How Forth stores strings in memory
1.67 anton 331: * Displaying characters and strings:: Other stuff
1.32 anton 332: * Input:: Input
1.112 anton 333: * Pipes:: How to create your own pipes
1.26 crook 334:
335: Locals
336:
337: * Gforth locals::
338: * ANS Forth locals::
339:
340: Gforth locals
341:
342: * Where are locals visible by name?::
343: * How long do locals live?::
1.78 anton 344: * Locals programming style::
345: * Locals implementation::
1.26 crook 346:
1.12 anton 347: Structures
348:
349: * Why explicit structure support?::
350: * Structure Usage::
351: * Structure Naming Convention::
352: * Structure Implementation::
353: * Structure Glossary::
354:
355: Object-oriented Forth
356:
1.48 anton 357: * Why object-oriented programming?::
358: * Object-Oriented Terminology::
359: * Objects::
360: * OOF::
361: * Mini-OOF::
1.23 crook 362: * Comparison with other object models::
1.12 anton 363:
1.24 anton 364: The @file{objects.fs} model
1.12 anton 365:
366: * Properties of the Objects model::
367: * Basic Objects Usage::
1.41 anton 368: * The Objects base class::
1.12 anton 369: * Creating objects::
370: * Object-Oriented Programming Style::
371: * Class Binding::
372: * Method conveniences::
373: * Classes and Scoping::
1.41 anton 374: * Dividing classes::
1.12 anton 375: * Object Interfaces::
376: * Objects Implementation::
377: * Objects Glossary::
378:
1.24 anton 379: The @file{oof.fs} model
1.12 anton 380:
1.67 anton 381: * Properties of the OOF model::
382: * Basic OOF Usage::
383: * The OOF base class::
384: * Class Declaration::
385: * Class Implementation::
1.12 anton 386:
1.24 anton 387: The @file{mini-oof.fs} model
1.23 crook 388:
1.48 anton 389: * Basic Mini-OOF Usage::
390: * Mini-OOF Example::
391: * Mini-OOF Implementation::
1.23 crook 392:
1.78 anton 393: Programming Tools
394:
395: * Examining::
396: * Forgetting words::
397: * Debugging:: Simple and quick.
398: * Assertions:: Making your programs self-checking.
399: * Singlestep Debugger:: Executing your program word by word.
400:
401: Assembler and Code Words
402:
403: * Code and ;code::
404: * Common Assembler:: Assembler Syntax
405: * Common Disassembler::
406: * 386 Assembler:: Deviations and special cases
407: * Alpha Assembler:: Deviations and special cases
408: * MIPS assembler:: Deviations and special cases
409: * Other assemblers:: How to write them
410:
1.12 anton 411: Tools
412:
413: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 414: * Stack depth changes:: Where does this stack item come from?
1.12 anton 415:
416: ANS conformance
417:
418: * The Core Words::
419: * The optional Block word set::
420: * The optional Double Number word set::
421: * The optional Exception word set::
422: * The optional Facility word set::
423: * The optional File-Access word set::
424: * The optional Floating-Point word set::
425: * The optional Locals word set::
426: * The optional Memory-Allocation word set::
427: * The optional Programming-Tools word set::
428: * The optional Search-Order word set::
429:
430: The Core Words
431:
432: * core-idef:: Implementation Defined Options
433: * core-ambcond:: Ambiguous Conditions
434: * core-other:: Other System Documentation
435:
436: The optional Block word set
437:
438: * block-idef:: Implementation Defined Options
439: * block-ambcond:: Ambiguous Conditions
440: * block-other:: Other System Documentation
441:
442: The optional Double Number word set
443:
444: * double-ambcond:: Ambiguous Conditions
445:
446: The optional Exception word set
447:
448: * exception-idef:: Implementation Defined Options
449:
450: The optional Facility word set
451:
452: * facility-idef:: Implementation Defined Options
453: * facility-ambcond:: Ambiguous Conditions
454:
455: The optional File-Access word set
456:
457: * file-idef:: Implementation Defined Options
458: * file-ambcond:: Ambiguous Conditions
459:
460: The optional Floating-Point word set
461:
462: * floating-idef:: Implementation Defined Options
463: * floating-ambcond:: Ambiguous Conditions
464:
465: The optional Locals word set
466:
467: * locals-idef:: Implementation Defined Options
468: * locals-ambcond:: Ambiguous Conditions
469:
470: The optional Memory-Allocation word set
471:
472: * memory-idef:: Implementation Defined Options
473:
474: The optional Programming-Tools word set
475:
476: * programming-idef:: Implementation Defined Options
477: * programming-ambcond:: Ambiguous Conditions
478:
479: The optional Search-Order word set
480:
481: * search-idef:: Implementation Defined Options
482: * search-ambcond:: Ambiguous Conditions
483:
1.109 anton 484: Emacs and Gforth
485:
486: * Installing gforth.el:: Making Emacs aware of Forth.
487: * Emacs Tags:: Viewing the source of a word in Emacs.
488: * Hilighting:: Making Forth code look prettier.
489: * Auto-Indentation:: Customizing auto-indentation.
490: * Blocks Files:: Reading and writing blocks files.
491:
1.12 anton 492: Image Files
493:
1.24 anton 494: * Image Licensing Issues:: Distribution terms for images.
495: * Image File Background:: Why have image files?
1.67 anton 496: * Non-Relocatable Image Files:: don't always work.
1.24 anton 497: * Data-Relocatable Image Files:: are better.
1.67 anton 498: * Fully Relocatable Image Files:: better yet.
1.24 anton 499: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 500: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 501: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 502:
503: Fully Relocatable Image Files
504:
1.27 crook 505: * gforthmi:: The normal way
1.12 anton 506: * cross.fs:: The hard way
507:
508: Engine
509:
510: * Portability::
511: * Threading::
512: * Primitives::
513: * Performance::
514:
515: Threading
516:
517: * Scheduling::
518: * Direct or Indirect Threaded?::
1.109 anton 519: * Dynamic Superinstructions::
1.12 anton 520: * DOES>::
521:
522: Primitives
523:
524: * Automatic Generation::
525: * TOS Optimization::
526: * Produced code::
1.13 pazsan 527:
528: Cross Compiler
529:
1.67 anton 530: * Using the Cross Compiler::
531: * How the Cross Compiler Works::
1.13 pazsan 532:
1.113 anton 533: Licenses
534:
535: * GNU Free Documentation License:: License for copying this manual.
536: * Copying:: GPL (for copying this software).
537:
1.24 anton 538: @end detailmenu
1.1 anton 539: @end menu
540:
1.113 anton 541: @c ----------------------------------------------------------
1.1 anton 542: @iftex
543: @unnumbered Preface
544: @cindex Preface
1.21 crook 545: This manual documents Gforth. Some introductory material is provided for
546: readers who are unfamiliar with Forth or who are migrating to Gforth
547: from other Forth compilers. However, this manual is primarily a
548: reference manual.
1.1 anton 549: @end iftex
550:
1.28 crook 551: @comment TODO much more blurb here.
1.26 crook 552:
553: @c ******************************************************************
1.113 anton 554: @node Goals, Gforth Environment, Top, Top
1.26 crook 555: @comment node-name, next, previous, up
556: @chapter Goals of Gforth
557: @cindex goals of the Gforth project
558: The goal of the Gforth Project is to develop a standard model for
559: ANS Forth. This can be split into several subgoals:
560:
561: @itemize @bullet
562: @item
563: Gforth should conform to the ANS Forth Standard.
564: @item
565: It should be a model, i.e. it should define all the
566: implementation-dependent things.
567: @item
568: It should become standard, i.e. widely accepted and used. This goal
569: is the most difficult one.
570: @end itemize
571:
572: To achieve these goals Gforth should be
573: @itemize @bullet
574: @item
575: Similar to previous models (fig-Forth, F83)
576: @item
577: Powerful. It should provide for all the things that are considered
578: necessary today and even some that are not yet considered necessary.
579: @item
580: Efficient. It should not get the reputation of being exceptionally
581: slow.
582: @item
583: Free.
584: @item
585: Available on many machines/easy to port.
586: @end itemize
587:
588: Have we achieved these goals? Gforth conforms to the ANS Forth
589: standard. It may be considered a model, but we have not yet documented
590: which parts of the model are stable and which parts we are likely to
591: change. It certainly has not yet become a de facto standard, but it
592: appears to be quite popular. It has some similarities to and some
593: differences from previous models. It has some powerful features, but not
594: yet everything that we envisioned. We certainly have achieved our
1.65 anton 595: execution speed goals (@pxref{Performance})@footnote{However, in 1998
596: the bar was raised when the major commercial Forth vendors switched to
597: native code compilers.}. It is free and available on many machines.
1.29 crook 598:
1.26 crook 599: @c ******************************************************************
1.48 anton 600: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 601: @chapter Gforth Environment
602: @cindex Gforth environment
1.21 crook 603:
1.45 crook 604: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 605: material in this chapter.
1.21 crook 606:
607: @menu
1.29 crook 608: * Invoking Gforth:: Getting in
609: * Leaving Gforth:: Getting out
610: * Command-line editing::
1.48 anton 611: * Environment variables:: that affect how Gforth starts up
1.29 crook 612: * Gforth Files:: What gets installed and where
1.112 anton 613: * Gforth in pipes::
1.48 anton 614: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 615: @end menu
616:
1.49 anton 617: For related information about the creation of images see @ref{Image Files}.
1.29 crook 618:
1.21 crook 619: @comment ----------------------------------------------
1.48 anton 620: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 621: @section Invoking Gforth
622: @cindex invoking Gforth
623: @cindex running Gforth
624: @cindex command-line options
625: @cindex options on the command line
626: @cindex flags on the command line
1.21 crook 627:
1.30 anton 628: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 629: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 630: will usually just say @code{gforth} -- this automatically loads the
631: default image file @file{gforth.fi}. In many other cases the default
632: Gforth image will be invoked like this:
1.21 crook 633: @example
1.30 anton 634: gforth [file | -e forth-code] ...
1.21 crook 635: @end example
1.29 crook 636: @noindent
637: This interprets the contents of the files and the Forth code in the order they
638: are given.
1.21 crook 639:
1.109 anton 640: In addition to the @command{gforth} engine, there is also an engine
641: called @command{gforth-fast}, which is faster, but gives less
642: informative error messages (@pxref{Error messages}) and may catch some
643: stack underflows later or not at all. You should use it for debugged,
644: performance-critical programs.
645:
646: Moreover, there is an engine called @command{gforth-itc}, which is
647: useful in some backwards-compatibility situations (@pxref{Direct or
648: Indirect Threaded?}).
1.30 anton 649:
1.29 crook 650: In general, the command line looks like this:
1.21 crook 651:
652: @example
1.30 anton 653: gforth[-fast] [engine options] [image options]
1.21 crook 654: @end example
655:
1.30 anton 656: The engine options must come before the rest of the command
1.29 crook 657: line. They are:
1.26 crook 658:
1.29 crook 659: @table @code
660: @cindex -i, command-line option
661: @cindex --image-file, command-line option
662: @item --image-file @i{file}
663: @itemx -i @i{file}
664: Loads the Forth image @i{file} instead of the default
665: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 666:
1.39 anton 667: @cindex --appl-image, command-line option
668: @item --appl-image @i{file}
669: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 670: to the image (instead of processing them as engine options). This is
671: useful for building executable application images on Unix, built with
1.39 anton 672: @code{gforthmi --application ...}.
673:
1.29 crook 674: @cindex --path, command-line option
675: @cindex -p, command-line option
676: @item --path @i{path}
677: @itemx -p @i{path}
678: Uses @i{path} for searching the image file and Forth source code files
679: instead of the default in the environment variable @code{GFORTHPATH} or
680: the path specified at installation time (e.g.,
681: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
682: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 683:
1.29 crook 684: @cindex --dictionary-size, command-line option
685: @cindex -m, command-line option
686: @cindex @i{size} parameters for command-line options
687: @cindex size of the dictionary and the stacks
688: @item --dictionary-size @i{size}
689: @itemx -m @i{size}
690: Allocate @i{size} space for the Forth dictionary space instead of
691: using the default specified in the image (typically 256K). The
692: @i{size} specification for this and subsequent options consists of
693: an integer and a unit (e.g.,
694: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
695: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
696: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
697: @code{e} is used.
1.21 crook 698:
1.29 crook 699: @cindex --data-stack-size, command-line option
700: @cindex -d, command-line option
701: @item --data-stack-size @i{size}
702: @itemx -d @i{size}
703: Allocate @i{size} space for the data stack instead of using the
704: default specified in the image (typically 16K).
1.21 crook 705:
1.29 crook 706: @cindex --return-stack-size, command-line option
707: @cindex -r, command-line option
708: @item --return-stack-size @i{size}
709: @itemx -r @i{size}
710: Allocate @i{size} space for the return stack instead of using the
711: default specified in the image (typically 15K).
1.21 crook 712:
1.29 crook 713: @cindex --fp-stack-size, command-line option
714: @cindex -f, command-line option
715: @item --fp-stack-size @i{size}
716: @itemx -f @i{size}
717: Allocate @i{size} space for the floating point stack instead of
718: using the default specified in the image (typically 15.5K). In this case
719: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 720:
1.48 anton 721: @cindex --locals-stack-size, command-line option
722: @cindex -l, command-line option
723: @item --locals-stack-size @i{size}
724: @itemx -l @i{size}
725: Allocate @i{size} space for the locals stack instead of using the
726: default specified in the image (typically 14.5K).
727:
728: @cindex -h, command-line option
729: @cindex --help, command-line option
730: @item --help
731: @itemx -h
732: Print a message about the command-line options
733:
734: @cindex -v, command-line option
735: @cindex --version, command-line option
736: @item --version
737: @itemx -v
738: Print version and exit
739:
740: @cindex --debug, command-line option
741: @item --debug
742: Print some information useful for debugging on startup.
743:
744: @cindex --offset-image, command-line option
745: @item --offset-image
746: Start the dictionary at a slightly different position than would be used
747: otherwise (useful for creating data-relocatable images,
748: @pxref{Data-Relocatable Image Files}).
749:
750: @cindex --no-offset-im, command-line option
751: @item --no-offset-im
752: Start the dictionary at the normal position.
753:
754: @cindex --clear-dictionary, command-line option
755: @item --clear-dictionary
756: Initialize all bytes in the dictionary to 0 before loading the image
757: (@pxref{Data-Relocatable Image Files}).
758:
759: @cindex --die-on-signal, command-line-option
760: @item --die-on-signal
761: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
762: or the segmentation violation SIGSEGV) by translating it into a Forth
763: @code{THROW}. With this option, Gforth exits if it receives such a
764: signal. This option is useful when the engine and/or the image might be
765: severely broken (such that it causes another signal before recovering
766: from the first); this option avoids endless loops in such cases.
1.109 anton 767:
1.119 anton 768: @cindex --no-dynamic, command-line option
769: @cindex --dynamic, command-line option
1.109 anton 770: @item --no-dynamic
771: @item --dynamic
772: Disable or enable dynamic superinstructions with replication
773: (@pxref{Dynamic Superinstructions}).
774:
1.119 anton 775: @cindex --no-super, command-line option
1.109 anton 776: @item --no-super
1.110 anton 777: Disable dynamic superinstructions, use just dynamic replication; this is
778: useful if you want to patch threaded code (@pxref{Dynamic
779: Superinstructions}).
1.119 anton 780:
781: @cindex --ss-number, command-line option
782: @item --ss-number=@var{N}
783: Use only the first @var{N} static superinstructions compiled into the
784: engine (default: use them all; note that only @code{gforth-fast} has
785: any). This option is useful for measuring the performance impact of
786: static superinstructions.
787:
788: @cindex --ss-min-..., command-line options
789: @item --ss-min-codesize
790: @item --ss-min-ls
791: @item --ss-min-lsu
792: @item --ss-min-nexts
793: Use specified metric for determining the cost of a primitive or static
794: superinstruction for static superinstruction selection. @code{Codesize}
795: is the native code size of the primive or static superinstruction,
796: @code{ls} is the number of loads and stores, @code{lsu} is the number of
797: loads, stores, and updates, and @code{nexts} is the number of dispatches
798: (not taking dynamic superinstructions into account), i.e. every
799: primitive or static superinstruction has cost 1. Default:
800: @code{codesize} if you use dynamic code generation, otherwise
801: @code{nexts}.
802:
803: @cindex --ss-greedy, command-line option
804: @item --ss-greedy
805: This option is useful for measuring the performance impact of static
806: superinstructions. By default, an optimal shortest-path algorithm is
807: used for selecting static superinstructions. With @option{--ss-greedy}
808: this algorithm is modified to assume that anything after the static
809: superinstruction currently under consideration is not combined into
810: static superinstructions. With @option{--ss-min-nexts} this produces
811: the same result as a greedy algorithm that always selects the longest
812: superinstruction available at the moment. E.g., if there are
813: superinstructions AB and BCD, then for the sequence A B C D the optimal
814: algorithm will select A BCD and the greedy algorithm will select AB C D.
815:
816: @cindex --print-metrics, command-line option
817: @item --print-metrics
818: Prints some metrics used during static superinstruction selection:
819: @code{code size} is the actual size of the dynamically generated code.
820: @code{Metric codesize} is the sum of the codesize metrics as seen by
821: static superinstruction selection; there is a difference from @code{code
822: size}, because not all primitives and static superinstructions are
823: compiled into dynamically generated code, and because of markers. The
824: other metrics correspond to the @option{ss-min-...} options. This
825: option is useful for evaluating the effects of the @option{--ss-...}
826: options.
1.109 anton 827:
1.48 anton 828: @end table
829:
830: @cindex loading files at startup
831: @cindex executing code on startup
832: @cindex batch processing with Gforth
833: As explained above, the image-specific command-line arguments for the
834: default image @file{gforth.fi} consist of a sequence of filenames and
835: @code{-e @var{forth-code}} options that are interpreted in the sequence
836: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 837: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
838: option takes only one argument; if you want to evaluate more Forth
839: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 840: after processing the command line (instead of entering interactive mode)
1.121 anton 841: append @code{-e bye} to the command line. You can also process the
842: command-line arguments with a Forth program (@pxref{OS command line
843: arguments}).
1.48 anton 844:
845: @cindex versions, invoking other versions of Gforth
846: If you have several versions of Gforth installed, @code{gforth} will
847: invoke the version that was installed last. @code{gforth-@i{version}}
848: invokes a specific version. If your environment contains the variable
849: @code{GFORTHPATH}, you may want to override it by using the
850: @code{--path} option.
851:
852: Not yet implemented:
853: On startup the system first executes the system initialization file
854: (unless the option @code{--no-init-file} is given; note that the system
855: resulting from using this option may not be ANS Forth conformant). Then
856: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 857: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 858: then in @file{~}, then in the normal path (see above).
859:
860:
861:
862: @comment ----------------------------------------------
863: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
864: @section Leaving Gforth
865: @cindex Gforth - leaving
866: @cindex leaving Gforth
867:
868: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
869: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
870: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 871: data are discarded. For ways of saving the state of the system before
872: leaving Gforth see @ref{Image Files}.
1.48 anton 873:
874: doc-bye
875:
876:
877: @comment ----------------------------------------------
1.65 anton 878: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 879: @section Command-line editing
880: @cindex command-line editing
881:
882: Gforth maintains a history file that records every line that you type to
883: the text interpreter. This file is preserved between sessions, and is
884: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
885: repeatedly you can recall successively older commands from this (or
886: previous) session(s). The full list of command-line editing facilities is:
887:
888: @itemize @bullet
889: @item
890: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
891: commands from the history buffer.
892: @item
893: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
894: from the history buffer.
895: @item
896: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
897: @item
898: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
899: @item
900: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
901: closing up the line.
902: @item
903: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
904: @item
905: @kbd{Ctrl-a} to move the cursor to the start of the line.
906: @item
907: @kbd{Ctrl-e} to move the cursor to the end of the line.
908: @item
909: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
910: line.
911: @item
912: @key{TAB} to step through all possible full-word completions of the word
913: currently being typed.
914: @item
1.65 anton 915: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
916: using @code{bye}).
917: @item
918: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
919: character under the cursor.
1.48 anton 920: @end itemize
921:
922: When editing, displayable characters are inserted to the left of the
923: cursor position; the line is always in ``insert'' (as opposed to
924: ``overstrike'') mode.
925:
926: @cindex history file
927: @cindex @file{.gforth-history}
928: On Unix systems, the history file is @file{~/.gforth-history} by
929: default@footnote{i.e. it is stored in the user's home directory.}. You
930: can find out the name and location of your history file using:
931:
932: @example
933: history-file type \ Unix-class systems
934:
935: history-file type \ Other systems
936: history-dir type
937: @end example
938:
939: If you enter long definitions by hand, you can use a text editor to
940: paste them out of the history file into a Forth source file for reuse at
941: a later time.
942:
943: Gforth never trims the size of the history file, so you should do this
944: periodically, if necessary.
945:
946: @comment this is all defined in history.fs
947: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
948: @comment chosen?
949:
950:
951: @comment ----------------------------------------------
1.65 anton 952: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 953: @section Environment variables
954: @cindex environment variables
955:
956: Gforth uses these environment variables:
957:
958: @itemize @bullet
959: @item
960: @cindex @code{GFORTHHIST} -- environment variable
961: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
962: open/create the history file, @file{.gforth-history}. Default:
963: @code{$HOME}.
964:
965: @item
966: @cindex @code{GFORTHPATH} -- environment variable
967: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
968: for Forth source-code files.
969:
970: @item
1.129 anton 971: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
972:
973: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
974: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 975: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 976: and the command are directly concatenated, so if a space between them is
977: necessary, append it to the prefix.
978:
979: @item
1.48 anton 980: @cindex @code{GFORTH} -- environment variable
1.49 anton 981: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 982:
983: @item
984: @cindex @code{GFORTHD} -- environment variable
1.62 crook 985: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 986:
987: @item
988: @cindex @code{TMP}, @code{TEMP} - environment variable
989: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
990: location for the history file.
991: @end itemize
992:
993: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
994: @comment mentioning these.
995:
996: All the Gforth environment variables default to sensible values if they
997: are not set.
998:
999:
1000: @comment ----------------------------------------------
1.112 anton 1001: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1002: @section Gforth files
1003: @cindex Gforth files
1004:
1005: When you install Gforth on a Unix system, it installs files in these
1006: locations by default:
1007:
1008: @itemize @bullet
1009: @item
1010: @file{/usr/local/bin/gforth}
1011: @item
1012: @file{/usr/local/bin/gforthmi}
1013: @item
1014: @file{/usr/local/man/man1/gforth.1} - man page.
1015: @item
1016: @file{/usr/local/info} - the Info version of this manual.
1017: @item
1018: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1019: @item
1020: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1021: @item
1022: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1023: @item
1024: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1025: @end itemize
1026:
1027: You can select different places for installation by using
1028: @code{configure} options (listed with @code{configure --help}).
1029:
1030: @comment ----------------------------------------------
1.112 anton 1031: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1032: @section Gforth in pipes
1033: @cindex pipes, Gforth as part of
1034:
1035: Gforth can be used in pipes created elsewhere (described here). It can
1036: also create pipes on its own (@pxref{Pipes}).
1037:
1038: @cindex input from pipes
1039: If you pipe into Gforth, your program should read with @code{read-file}
1040: or @code{read-line} from @code{stdin} (@pxref{General files}).
1041: @code{Key} does not recognize the end of input. Words like
1042: @code{accept} echo the input and are therefore usually not useful for
1043: reading from a pipe. You have to invoke the Forth program with an OS
1044: command-line option, as you have no chance to use the Forth command line
1045: (the text interpreter would try to interpret the pipe input).
1046:
1047: @cindex output in pipes
1048: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1049:
1050: @cindex silent exiting from Gforth
1051: When you write to a pipe that has been closed at the other end, Gforth
1052: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1053: into the exception @code{broken-pipe-error}. If your application does
1054: not catch that exception, the system catches it and exits, usually
1055: silently (unless you were working on the Forth command line; then it
1056: prints an error message and exits). This is usually the desired
1057: behaviour.
1058:
1059: If you do not like this behaviour, you have to catch the exception
1060: yourself, and react to it.
1061:
1062: Here's an example of an invocation of Gforth that is usable in a pipe:
1063:
1064: @example
1065: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1066: type repeat ; foo bye"
1067: @end example
1068:
1069: This example just copies the input verbatim to the output. A very
1070: simple pipe containing this example looks like this:
1071:
1072: @example
1073: cat startup.fs |
1074: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1075: type repeat ; foo bye"|
1076: head
1077: @end example
1078:
1079: @cindex stderr and pipes
1080: Pipes involving Gforth's @code{stderr} output do not work.
1081:
1082: @comment ----------------------------------------------
1083: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1084: @section Startup speed
1085: @cindex Startup speed
1086: @cindex speed, startup
1087:
1088: If Gforth is used for CGI scripts or in shell scripts, its startup
1089: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1090: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1091: system time.
1092:
1093: If startup speed is a problem, you may consider the following ways to
1094: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1095: (for example, by using Fast-CGI).
1.48 anton 1096:
1.112 anton 1097: An easy step that influences Gforth startup speed is the use of the
1098: @option{--no-dynamic} option; this decreases image loading speed, but
1099: increases compile-time and run-time.
1100:
1101: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1102: building it with @code{XLDFLAGS=-static}. This requires more memory for
1103: the code and will therefore slow down the first invocation, but
1104: subsequent invocations avoid the dynamic linking overhead. Another
1105: disadvantage is that Gforth won't profit from library upgrades. As a
1106: result, @code{gforth-static -e bye} takes about 17.1ms user and
1107: 8.2ms system time.
1108:
1109: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1110: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1111: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1112: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1113: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1114: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1115: address for the dictionary, for whatever reason; so you better provide a
1116: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1117: bye} takes about 15.3ms user and 7.5ms system time.
1118:
1119: The final step is to disable dictionary hashing in Gforth. Gforth
1120: builds the hash table on startup, which takes much of the startup
1121: overhead. You can do this by commenting out the @code{include hash.fs}
1122: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1123: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1124: The disadvantages are that functionality like @code{table} and
1125: @code{ekey} is missing and that text interpretation (e.g., compiling)
1126: now takes much longer. So, you should only use this method if there is
1127: no significant text interpretation to perform (the script should be
1.62 crook 1128: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1129: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1130:
1131: @c ******************************************************************
1132: @node Tutorial, Introduction, Gforth Environment, Top
1133: @chapter Forth Tutorial
1134: @cindex Tutorial
1135: @cindex Forth Tutorial
1136:
1.67 anton 1137: @c Topics from nac's Introduction that could be mentioned:
1138: @c press <ret> after each line
1139: @c Prompt
1140: @c numbers vs. words in dictionary on text interpretation
1141: @c what happens on redefinition
1142: @c parsing words (in particular, defining words)
1143:
1.83 anton 1144: The difference of this chapter from the Introduction
1145: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1146: be used while sitting in front of a computer, and covers much more
1147: material, but does not explain how the Forth system works.
1148:
1.62 crook 1149: This tutorial can be used with any ANS-compliant Forth; any
1150: Gforth-specific features are marked as such and you can skip them if you
1151: work with another Forth. This tutorial does not explain all features of
1152: Forth, just enough to get you started and give you some ideas about the
1153: facilities available in Forth. Read the rest of the manual and the
1154: standard when you are through this.
1.48 anton 1155:
1156: The intended way to use this tutorial is that you work through it while
1157: sitting in front of the console, take a look at the examples and predict
1158: what they will do, then try them out; if the outcome is not as expected,
1159: find out why (e.g., by trying out variations of the example), so you
1160: understand what's going on. There are also some assignments that you
1161: should solve.
1162:
1163: This tutorial assumes that you have programmed before and know what,
1164: e.g., a loop is.
1165:
1166: @c !! explain compat library
1167:
1168: @menu
1169: * Starting Gforth Tutorial::
1170: * Syntax Tutorial::
1171: * Crash Course Tutorial::
1172: * Stack Tutorial::
1173: * Arithmetics Tutorial::
1174: * Stack Manipulation Tutorial::
1175: * Using files for Forth code Tutorial::
1176: * Comments Tutorial::
1177: * Colon Definitions Tutorial::
1178: * Decompilation Tutorial::
1179: * Stack-Effect Comments Tutorial::
1180: * Types Tutorial::
1181: * Factoring Tutorial::
1182: * Designing the stack effect Tutorial::
1183: * Local Variables Tutorial::
1184: * Conditional execution Tutorial::
1185: * Flags and Comparisons Tutorial::
1186: * General Loops Tutorial::
1187: * Counted loops Tutorial::
1188: * Recursion Tutorial::
1189: * Leaving definitions or loops Tutorial::
1190: * Return Stack Tutorial::
1191: * Memory Tutorial::
1192: * Characters and Strings Tutorial::
1193: * Alignment Tutorial::
1.87 anton 1194: * Files Tutorial::
1.48 anton 1195: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1196: * Execution Tokens Tutorial::
1197: * Exceptions Tutorial::
1198: * Defining Words Tutorial::
1199: * Arrays and Records Tutorial::
1200: * POSTPONE Tutorial::
1201: * Literal Tutorial::
1202: * Advanced macros Tutorial::
1203: * Compilation Tokens Tutorial::
1204: * Wordlists and Search Order Tutorial::
1205: @end menu
1206:
1207: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1208: @section Starting Gforth
1.66 anton 1209: @cindex starting Gforth tutorial
1.48 anton 1210: You can start Gforth by typing its name:
1211:
1212: @example
1213: gforth
1214: @end example
1215:
1216: That puts you into interactive mode; you can leave Gforth by typing
1217: @code{bye}. While in Gforth, you can edit the command line and access
1218: the command line history with cursor keys, similar to bash.
1219:
1220:
1221: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1222: @section Syntax
1.66 anton 1223: @cindex syntax tutorial
1.48 anton 1224:
1225: A @dfn{word} is a sequence of arbitrary characters (expcept white
1226: space). Words are separated by white space. E.g., each of the
1227: following lines contains exactly one word:
1228:
1229: @example
1230: word
1231: !@@#$%^&*()
1232: 1234567890
1233: 5!a
1234: @end example
1235:
1236: A frequent beginner's error is to leave away necessary white space,
1237: resulting in an error like @samp{Undefined word}; so if you see such an
1238: error, check if you have put spaces wherever necessary.
1239:
1240: @example
1241: ." hello, world" \ correct
1242: ."hello, world" \ gives an "Undefined word" error
1243: @end example
1244:
1.65 anton 1245: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1246: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1247: your system is case-sensitive, you may have to type all the examples
1248: given here in upper case.
1249:
1250:
1251: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1252: @section Crash Course
1253:
1254: Type
1255:
1256: @example
1257: 0 0 !
1258: here execute
1259: ' catch >body 20 erase abort
1260: ' (quit) >body 20 erase
1261: @end example
1262:
1263: The last two examples are guaranteed to destroy parts of Gforth (and
1264: most other systems), so you better leave Gforth afterwards (if it has
1265: not finished by itself). On some systems you may have to kill gforth
1266: from outside (e.g., in Unix with @code{kill}).
1267:
1268: Now that you know how to produce crashes (and that there's not much to
1269: them), let's learn how to produce meaningful programs.
1270:
1271:
1272: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1273: @section Stack
1.66 anton 1274: @cindex stack tutorial
1.48 anton 1275:
1276: The most obvious feature of Forth is the stack. When you type in a
1277: number, it is pushed on the stack. You can display the content of the
1278: stack with @code{.s}.
1279:
1280: @example
1281: 1 2 .s
1282: 3 .s
1283: @end example
1284:
1285: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1286: appear in @code{.s} output as they appeared in the input.
1287:
1288: You can print the top of stack element with @code{.}.
1289:
1290: @example
1291: 1 2 3 . . .
1292: @end example
1293:
1294: In general, words consume their stack arguments (@code{.s} is an
1295: exception).
1296:
1297: @assignment
1298: What does the stack contain after @code{5 6 7 .}?
1299: @endassignment
1300:
1301:
1302: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1303: @section Arithmetics
1.66 anton 1304: @cindex arithmetics tutorial
1.48 anton 1305:
1306: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1307: operate on the top two stack items:
1308:
1309: @example
1.67 anton 1310: 2 2 .s
1311: + .s
1312: .
1.48 anton 1313: 2 1 - .
1314: 7 3 mod .
1315: @end example
1316:
1317: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1318: as in the corresponding infix expression (this is generally the case in
1319: Forth).
1320:
1321: Parentheses are superfluous (and not available), because the order of
1322: the words unambiguously determines the order of evaluation and the
1323: operands:
1324:
1325: @example
1326: 3 4 + 5 * .
1327: 3 4 5 * + .
1328: @end example
1329:
1330: @assignment
1331: What are the infix expressions corresponding to the Forth code above?
1332: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1333: known as Postfix or RPN (Reverse Polish Notation).}.
1334: @endassignment
1335:
1336: To change the sign, use @code{negate}:
1337:
1338: @example
1339: 2 negate .
1340: @end example
1341:
1342: @assignment
1343: Convert -(-3)*4-5 to Forth.
1344: @endassignment
1345:
1346: @code{/mod} performs both @code{/} and @code{mod}.
1347:
1348: @example
1349: 7 3 /mod . .
1350: @end example
1351:
1.66 anton 1352: Reference: @ref{Arithmetic}.
1353:
1354:
1.48 anton 1355: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1356: @section Stack Manipulation
1.66 anton 1357: @cindex stack manipulation tutorial
1.48 anton 1358:
1359: Stack manipulation words rearrange the data on the stack.
1360:
1361: @example
1362: 1 .s drop .s
1363: 1 .s dup .s drop drop .s
1364: 1 2 .s over .s drop drop drop
1365: 1 2 .s swap .s drop drop
1366: 1 2 3 .s rot .s drop drop drop
1367: @end example
1368:
1369: These are the most important stack manipulation words. There are also
1370: variants that manipulate twice as many stack items:
1371:
1372: @example
1373: 1 2 3 4 .s 2swap .s 2drop 2drop
1374: @end example
1375:
1376: Two more stack manipulation words are:
1377:
1378: @example
1379: 1 2 .s nip .s drop
1380: 1 2 .s tuck .s 2drop drop
1381: @end example
1382:
1383: @assignment
1384: Replace @code{nip} and @code{tuck} with combinations of other stack
1385: manipulation words.
1386:
1387: @example
1388: Given: How do you get:
1389: 1 2 3 3 2 1
1390: 1 2 3 1 2 3 2
1391: 1 2 3 1 2 3 3
1392: 1 2 3 1 3 3
1393: 1 2 3 2 1 3
1394: 1 2 3 4 4 3 2 1
1395: 1 2 3 1 2 3 1 2 3
1396: 1 2 3 4 1 2 3 4 1 2
1397: 1 2 3
1398: 1 2 3 1 2 3 4
1399: 1 2 3 1 3
1400: @end example
1401: @endassignment
1402:
1403: @example
1404: 5 dup * .
1405: @end example
1406:
1407: @assignment
1408: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1409: Write a piece of Forth code that expects two numbers on the stack
1410: (@var{a} and @var{b}, with @var{b} on top) and computes
1411: @code{(a-b)(a+1)}.
1412: @endassignment
1413:
1.66 anton 1414: Reference: @ref{Stack Manipulation}.
1415:
1416:
1.48 anton 1417: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1418: @section Using files for Forth code
1.66 anton 1419: @cindex loading Forth code, tutorial
1420: @cindex files containing Forth code, tutorial
1.48 anton 1421:
1422: While working at the Forth command line is convenient for one-line
1423: examples and short one-off code, you probably want to store your source
1424: code in files for convenient editing and persistence. You can use your
1425: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1426: Gforth}) to create @var{file.fs} and use
1.48 anton 1427:
1428: @example
1.102 anton 1429: s" @var{file.fs}" included
1.48 anton 1430: @end example
1431:
1432: to load it into your Forth system. The file name extension I use for
1433: Forth files is @samp{.fs}.
1434:
1435: You can easily start Gforth with some files loaded like this:
1436:
1437: @example
1.102 anton 1438: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1439: @end example
1440:
1441: If an error occurs during loading these files, Gforth terminates,
1442: whereas an error during @code{INCLUDED} within Gforth usually gives you
1443: a Gforth command line. Starting the Forth system every time gives you a
1444: clean start every time, without interference from the results of earlier
1445: tries.
1446:
1447: I often put all the tests in a file, then load the code and run the
1448: tests with
1449:
1450: @example
1.102 anton 1451: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1452: @end example
1453:
1454: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1455: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1456: restart this command without ado.
1457:
1458: The advantage of this approach is that the tests can be repeated easily
1459: every time the program ist changed, making it easy to catch bugs
1460: introduced by the change.
1461:
1.66 anton 1462: Reference: @ref{Forth source files}.
1463:
1.48 anton 1464:
1465: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1466: @section Comments
1.66 anton 1467: @cindex comments tutorial
1.48 anton 1468:
1469: @example
1470: \ That's a comment; it ends at the end of the line
1471: ( Another comment; it ends here: ) .s
1472: @end example
1473:
1474: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1475: separated with white space from the following text.
1476:
1477: @example
1478: \This gives an "Undefined word" error
1479: @end example
1480:
1481: The first @code{)} ends a comment started with @code{(}, so you cannot
1482: nest @code{(}-comments; and you cannot comment out text containing a
1483: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1484: avoid @code{)} in word names.}.
1485:
1486: I use @code{\}-comments for descriptive text and for commenting out code
1487: of one or more line; I use @code{(}-comments for describing the stack
1488: effect, the stack contents, or for commenting out sub-line pieces of
1489: code.
1490:
1491: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1492: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1493: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1494: with @kbd{M-q}.
1495:
1.66 anton 1496: Reference: @ref{Comments}.
1497:
1.48 anton 1498:
1499: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1500: @section Colon Definitions
1.66 anton 1501: @cindex colon definitions, tutorial
1502: @cindex definitions, tutorial
1503: @cindex procedures, tutorial
1504: @cindex functions, tutorial
1.48 anton 1505:
1506: are similar to procedures and functions in other programming languages.
1507:
1508: @example
1509: : squared ( n -- n^2 )
1510: dup * ;
1511: 5 squared .
1512: 7 squared .
1513: @end example
1514:
1515: @code{:} starts the colon definition; its name is @code{squared}. The
1516: following comment describes its stack effect. The words @code{dup *}
1517: are not executed, but compiled into the definition. @code{;} ends the
1518: colon definition.
1519:
1520: The newly-defined word can be used like any other word, including using
1521: it in other definitions:
1522:
1523: @example
1524: : cubed ( n -- n^3 )
1525: dup squared * ;
1526: -5 cubed .
1527: : fourth-power ( n -- n^4 )
1528: squared squared ;
1529: 3 fourth-power .
1530: @end example
1531:
1532: @assignment
1533: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1534: @code{/mod} in terms of other Forth words, and check if they work (hint:
1535: test your tests on the originals first). Don't let the
1536: @samp{redefined}-Messages spook you, they are just warnings.
1537: @endassignment
1538:
1.66 anton 1539: Reference: @ref{Colon Definitions}.
1540:
1.48 anton 1541:
1542: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1543: @section Decompilation
1.66 anton 1544: @cindex decompilation tutorial
1545: @cindex see tutorial
1.48 anton 1546:
1547: You can decompile colon definitions with @code{see}:
1548:
1549: @example
1550: see squared
1551: see cubed
1552: @end example
1553:
1554: In Gforth @code{see} shows you a reconstruction of the source code from
1555: the executable code. Informations that were present in the source, but
1556: not in the executable code, are lost (e.g., comments).
1557:
1.65 anton 1558: You can also decompile the predefined words:
1559:
1560: @example
1561: see .
1562: see +
1563: @end example
1564:
1565:
1.48 anton 1566: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1567: @section Stack-Effect Comments
1.66 anton 1568: @cindex stack-effect comments, tutorial
1569: @cindex --, tutorial
1.48 anton 1570: By convention the comment after the name of a definition describes the
1571: stack effect: The part in from of the @samp{--} describes the state of
1572: the stack before the execution of the definition, i.e., the parameters
1573: that are passed into the colon definition; the part behind the @samp{--}
1574: is the state of the stack after the execution of the definition, i.e.,
1575: the results of the definition. The stack comment only shows the top
1576: stack items that the definition accesses and/or changes.
1577:
1578: You should put a correct stack effect on every definition, even if it is
1579: just @code{( -- )}. You should also add some descriptive comment to
1580: more complicated words (I usually do this in the lines following
1581: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1582: you have to work through every definition before you can understand
1.48 anton 1583: any).
1584:
1585: @assignment
1586: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1587: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1588: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1589: are done, you can compare your stack effects to those in this manual
1.48 anton 1590: (@pxref{Word Index}).
1591: @endassignment
1592:
1593: Sometimes programmers put comments at various places in colon
1594: definitions that describe the contents of the stack at that place (stack
1595: comments); i.e., they are like the first part of a stack-effect
1596: comment. E.g.,
1597:
1598: @example
1599: : cubed ( n -- n^3 )
1600: dup squared ( n n^2 ) * ;
1601: @end example
1602:
1603: In this case the stack comment is pretty superfluous, because the word
1604: is simple enough. If you think it would be a good idea to add such a
1605: comment to increase readability, you should also consider factoring the
1606: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1607: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1608: however, if you decide not to refactor it, then having such a comment is
1609: better than not having it.
1610:
1611: The names of the stack items in stack-effect and stack comments in the
1612: standard, in this manual, and in many programs specify the type through
1613: a type prefix, similar to Fortran and Hungarian notation. The most
1614: frequent prefixes are:
1615:
1616: @table @code
1617: @item n
1618: signed integer
1619: @item u
1620: unsigned integer
1621: @item c
1622: character
1623: @item f
1624: Boolean flags, i.e. @code{false} or @code{true}.
1625: @item a-addr,a-
1626: Cell-aligned address
1627: @item c-addr,c-
1628: Char-aligned address (note that a Char may have two bytes in Windows NT)
1629: @item xt
1630: Execution token, same size as Cell
1631: @item w,x
1632: Cell, can contain an integer or an address. It usually takes 32, 64 or
1633: 16 bits (depending on your platform and Forth system). A cell is more
1634: commonly known as machine word, but the term @emph{word} already means
1635: something different in Forth.
1636: @item d
1637: signed double-cell integer
1638: @item ud
1639: unsigned double-cell integer
1640: @item r
1641: Float (on the FP stack)
1642: @end table
1643:
1644: You can find a more complete list in @ref{Notation}.
1645:
1646: @assignment
1647: Write stack-effect comments for all definitions you have written up to
1648: now.
1649: @endassignment
1650:
1651:
1652: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1653: @section Types
1.66 anton 1654: @cindex types tutorial
1.48 anton 1655:
1656: In Forth the names of the operations are not overloaded; so similar
1657: operations on different types need different names; e.g., @code{+} adds
1658: integers, and you have to use @code{f+} to add floating-point numbers.
1659: The following prefixes are often used for related operations on
1660: different types:
1661:
1662: @table @code
1663: @item (none)
1664: signed integer
1665: @item u
1666: unsigned integer
1667: @item c
1668: character
1669: @item d
1670: signed double-cell integer
1671: @item ud, du
1672: unsigned double-cell integer
1673: @item 2
1674: two cells (not-necessarily double-cell numbers)
1675: @item m, um
1676: mixed single-cell and double-cell operations
1677: @item f
1678: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1679: and @samp{r} represents FP numbers).
1.48 anton 1680: @end table
1681:
1682: If there are no differences between the signed and the unsigned variant
1683: (e.g., for @code{+}), there is only the prefix-less variant.
1684:
1685: Forth does not perform type checking, neither at compile time, nor at
1686: run time. If you use the wrong oeration, the data are interpreted
1687: incorrectly:
1688:
1689: @example
1690: -1 u.
1691: @end example
1692:
1693: If you have only experience with type-checked languages until now, and
1694: have heard how important type-checking is, don't panic! In my
1695: experience (and that of other Forthers), type errors in Forth code are
1696: usually easy to find (once you get used to it), the increased vigilance
1697: of the programmer tends to catch some harder errors in addition to most
1698: type errors, and you never have to work around the type system, so in
1699: most situations the lack of type-checking seems to be a win (projects to
1700: add type checking to Forth have not caught on).
1701:
1702:
1703: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1704: @section Factoring
1.66 anton 1705: @cindex factoring tutorial
1.48 anton 1706:
1707: If you try to write longer definitions, you will soon find it hard to
1708: keep track of the stack contents. Therefore, good Forth programmers
1709: tend to write only short definitions (e.g., three lines). The art of
1710: finding meaningful short definitions is known as factoring (as in
1711: factoring polynomials).
1712:
1713: Well-factored programs offer additional advantages: smaller, more
1714: general words, are easier to test and debug and can be reused more and
1715: better than larger, specialized words.
1716:
1717: So, if you run into difficulties with stack management, when writing
1718: code, try to define meaningful factors for the word, and define the word
1719: in terms of those. Even if a factor contains only two words, it is
1720: often helpful.
1721:
1.65 anton 1722: Good factoring is not easy, and it takes some practice to get the knack
1723: for it; but even experienced Forth programmers often don't find the
1724: right solution right away, but only when rewriting the program. So, if
1725: you don't come up with a good solution immediately, keep trying, don't
1726: despair.
1.48 anton 1727:
1728: @c example !!
1729:
1730:
1731: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1732: @section Designing the stack effect
1.66 anton 1733: @cindex Stack effect design, tutorial
1734: @cindex design of stack effects, tutorial
1.48 anton 1735:
1736: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1737: function; and since there is only one result, you don't have to deal with
1.48 anton 1738: the order of results, either.
1739:
1.117 anton 1740: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1741: parameter and result order of a definition is important and should be
1742: designed well. The general guideline is to design the stack effect such
1743: that the word is simple to use in most cases, even if that complicates
1744: the implementation of the word. Some concrete rules are:
1745:
1746: @itemize @bullet
1747:
1748: @item
1749: Words consume all of their parameters (e.g., @code{.}).
1750:
1751: @item
1752: If there is a convention on the order of parameters (e.g., from
1753: mathematics or another programming language), stick with it (e.g.,
1754: @code{-}).
1755:
1756: @item
1757: If one parameter usually requires only a short computation (e.g., it is
1758: a constant), pass it on the top of the stack. Conversely, parameters
1759: that usually require a long sequence of code to compute should be passed
1760: as the bottom (i.e., first) parameter. This makes the code easier to
1761: read, because reader does not need to keep track of the bottom item
1762: through a long sequence of code (or, alternatively, through stack
1.49 anton 1763: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1764: address on top of the stack because it is usually simpler to compute
1765: than the stored value (often the address is just a variable).
1766:
1767: @item
1768: Similarly, results that are usually consumed quickly should be returned
1769: on the top of stack, whereas a result that is often used in long
1770: computations should be passed as bottom result. E.g., the file words
1771: like @code{open-file} return the error code on the top of stack, because
1772: it is usually consumed quickly by @code{throw}; moreover, the error code
1773: has to be checked before doing anything with the other results.
1774:
1775: @end itemize
1776:
1777: These rules are just general guidelines, don't lose sight of the overall
1778: goal to make the words easy to use. E.g., if the convention rule
1779: conflicts with the computation-length rule, you might decide in favour
1780: of the convention if the word will be used rarely, and in favour of the
1781: computation-length rule if the word will be used frequently (because
1782: with frequent use the cost of breaking the computation-length rule would
1783: be quite high, and frequent use makes it easier to remember an
1784: unconventional order).
1785:
1786: @c example !! structure package
1787:
1.65 anton 1788:
1.48 anton 1789: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1790: @section Local Variables
1.66 anton 1791: @cindex local variables, tutorial
1.48 anton 1792:
1793: You can define local variables (@emph{locals}) in a colon definition:
1794:
1795: @example
1796: : swap @{ a b -- b a @}
1797: b a ;
1798: 1 2 swap .s 2drop
1799: @end example
1800:
1801: (If your Forth system does not support this syntax, include
1802: @file{compat/anslocals.fs} first).
1803:
1804: In this example @code{@{ a b -- b a @}} is the locals definition; it
1805: takes two cells from the stack, puts the top of stack in @code{b} and
1806: the next stack element in @code{a}. @code{--} starts a comment ending
1807: with @code{@}}. After the locals definition, using the name of the
1808: local will push its value on the stack. You can leave the comment
1809: part (@code{-- b a}) away:
1810:
1811: @example
1812: : swap ( x1 x2 -- x2 x1 )
1813: @{ a b @} b a ;
1814: @end example
1815:
1816: In Gforth you can have several locals definitions, anywhere in a colon
1817: definition; in contrast, in a standard program you can have only one
1818: locals definition per colon definition, and that locals definition must
1819: be outside any controll structure.
1820:
1821: With locals you can write slightly longer definitions without running
1822: into stack trouble. However, I recommend trying to write colon
1823: definitions without locals for exercise purposes to help you gain the
1824: essential factoring skills.
1825:
1826: @assignment
1827: Rewrite your definitions until now with locals
1828: @endassignment
1829:
1.66 anton 1830: Reference: @ref{Locals}.
1831:
1.48 anton 1832:
1833: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1834: @section Conditional execution
1.66 anton 1835: @cindex conditionals, tutorial
1836: @cindex if, tutorial
1.48 anton 1837:
1838: In Forth you can use control structures only inside colon definitions.
1839: An @code{if}-structure looks like this:
1840:
1841: @example
1842: : abs ( n1 -- +n2 )
1843: dup 0 < if
1844: negate
1845: endif ;
1846: 5 abs .
1847: -5 abs .
1848: @end example
1849:
1850: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1851: the following code is performed, otherwise execution continues after the
1.51 pazsan 1852: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1853: elements and prioduces a flag:
1854:
1855: @example
1856: 1 2 < .
1857: 2 1 < .
1858: 1 1 < .
1859: @end example
1860:
1861: Actually the standard name for @code{endif} is @code{then}. This
1862: tutorial presents the examples using @code{endif}, because this is often
1863: less confusing for people familiar with other programming languages
1864: where @code{then} has a different meaning. If your system does not have
1865: @code{endif}, define it with
1866:
1867: @example
1868: : endif postpone then ; immediate
1869: @end example
1870:
1871: You can optionally use an @code{else}-part:
1872:
1873: @example
1874: : min ( n1 n2 -- n )
1875: 2dup < if
1876: drop
1877: else
1878: nip
1879: endif ;
1880: 2 3 min .
1881: 3 2 min .
1882: @end example
1883:
1884: @assignment
1885: Write @code{min} without @code{else}-part (hint: what's the definition
1886: of @code{nip}?).
1887: @endassignment
1888:
1.66 anton 1889: Reference: @ref{Selection}.
1890:
1.48 anton 1891:
1892: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1893: @section Flags and Comparisons
1.66 anton 1894: @cindex flags tutorial
1895: @cindex comparison tutorial
1.48 anton 1896:
1897: In a false-flag all bits are clear (0 when interpreted as integer). In
1898: a canonical true-flag all bits are set (-1 as a twos-complement signed
1899: integer); in many contexts (e.g., @code{if}) any non-zero value is
1900: treated as true flag.
1901:
1902: @example
1903: false .
1904: true .
1905: true hex u. decimal
1906: @end example
1907:
1908: Comparison words produce canonical flags:
1909:
1910: @example
1911: 1 1 = .
1912: 1 0= .
1913: 0 1 < .
1914: 0 0 < .
1915: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1916: -1 1 < .
1917: @end example
1918:
1.66 anton 1919: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1920: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1921: these combinations are standard (for details see the standard,
1922: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1923:
1924: You can use @code{and or xor invert} can be used as operations on
1925: canonical flags. Actually they are bitwise operations:
1926:
1927: @example
1928: 1 2 and .
1929: 1 2 or .
1930: 1 3 xor .
1931: 1 invert .
1932: @end example
1933:
1934: You can convert a zero/non-zero flag into a canonical flag with
1935: @code{0<>} (and complement it on the way with @code{0=}).
1936:
1937: @example
1938: 1 0= .
1939: 1 0<> .
1940: @end example
1941:
1.65 anton 1942: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1943: operation of the Boolean operations to avoid @code{if}s:
1944:
1945: @example
1946: : foo ( n1 -- n2 )
1947: 0= if
1948: 14
1949: else
1950: 0
1951: endif ;
1952: 0 foo .
1953: 1 foo .
1954:
1955: : foo ( n1 -- n2 )
1956: 0= 14 and ;
1957: 0 foo .
1958: 1 foo .
1959: @end example
1960:
1961: @assignment
1962: Write @code{min} without @code{if}.
1963: @endassignment
1964:
1.66 anton 1965: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1966: @ref{Bitwise operations}.
1967:
1.48 anton 1968:
1969: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1970: @section General Loops
1.66 anton 1971: @cindex loops, indefinite, tutorial
1.48 anton 1972:
1973: The endless loop is the most simple one:
1974:
1975: @example
1976: : endless ( -- )
1977: 0 begin
1978: dup . 1+
1979: again ;
1980: endless
1981: @end example
1982:
1983: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
1984: does nothing at run-time, @code{again} jumps back to @code{begin}.
1985:
1986: A loop with one exit at any place looks like this:
1987:
1988: @example
1989: : log2 ( +n1 -- n2 )
1990: \ logarithmus dualis of n1>0, rounded down to the next integer
1991: assert( dup 0> )
1992: 2/ 0 begin
1993: over 0> while
1994: 1+ swap 2/ swap
1995: repeat
1996: nip ;
1997: 7 log2 .
1998: 8 log2 .
1999: @end example
2000:
2001: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2002: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2003: continues behind the @code{while}. @code{Repeat} jumps back to
2004: @code{begin}, just like @code{again}.
2005:
2006: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2007: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2008: one bit (arithmetic shift right):
2009:
2010: @example
2011: -5 2 / .
2012: -5 2/ .
2013: @end example
2014:
2015: @code{assert(} is no standard word, but you can get it on systems other
2016: then Gforth by including @file{compat/assert.fs}. You can see what it
2017: does by trying
2018:
2019: @example
2020: 0 log2 .
2021: @end example
2022:
2023: Here's a loop with an exit at the end:
2024:
2025: @example
2026: : log2 ( +n1 -- n2 )
2027: \ logarithmus dualis of n1>0, rounded down to the next integer
2028: assert( dup 0 > )
2029: -1 begin
2030: 1+ swap 2/ swap
2031: over 0 <=
2032: until
2033: nip ;
2034: @end example
2035:
2036: @code{Until} consumes a flag; if it is non-zero, execution continues at
2037: the @code{begin}, otherwise after the @code{until}.
2038:
2039: @assignment
2040: Write a definition for computing the greatest common divisor.
2041: @endassignment
2042:
1.66 anton 2043: Reference: @ref{Simple Loops}.
2044:
1.48 anton 2045:
2046: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2047: @section Counted loops
1.66 anton 2048: @cindex loops, counted, tutorial
1.48 anton 2049:
2050: @example
2051: : ^ ( n1 u -- n )
2052: \ n = the uth power of u1
2053: 1 swap 0 u+do
2054: over *
2055: loop
2056: nip ;
2057: 3 2 ^ .
2058: 4 3 ^ .
2059: @end example
2060:
2061: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2062: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2063: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2064: times (or not at all, if @code{u3-u4<0}).
2065:
2066: You can see the stack effect design rules at work in the stack effect of
2067: the loop start words: Since the start value of the loop is more
2068: frequently constant than the end value, the start value is passed on
2069: the top-of-stack.
2070:
2071: You can access the counter of a counted loop with @code{i}:
2072:
2073: @example
2074: : fac ( u -- u! )
2075: 1 swap 1+ 1 u+do
2076: i *
2077: loop ;
2078: 5 fac .
2079: 7 fac .
2080: @end example
2081:
2082: There is also @code{+do}, which expects signed numbers (important for
2083: deciding whether to enter the loop).
2084:
2085: @assignment
2086: Write a definition for computing the nth Fibonacci number.
2087: @endassignment
2088:
1.65 anton 2089: You can also use increments other than 1:
2090:
2091: @example
2092: : up2 ( n1 n2 -- )
2093: +do
2094: i .
2095: 2 +loop ;
2096: 10 0 up2
2097:
2098: : down2 ( n1 n2 -- )
2099: -do
2100: i .
2101: 2 -loop ;
2102: 0 10 down2
2103: @end example
1.48 anton 2104:
1.66 anton 2105: Reference: @ref{Counted Loops}.
2106:
1.48 anton 2107:
2108: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2109: @section Recursion
1.66 anton 2110: @cindex recursion tutorial
1.48 anton 2111:
2112: Usually the name of a definition is not visible in the definition; but
2113: earlier definitions are usually visible:
2114:
2115: @example
2116: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2117: : / ( n1 n2 -- n )
2118: dup 0= if
2119: -10 throw \ report division by zero
2120: endif
2121: / \ old version
2122: ;
2123: 1 0 /
2124: @end example
2125:
2126: For recursive definitions you can use @code{recursive} (non-standard) or
2127: @code{recurse}:
2128:
2129: @example
2130: : fac1 ( n -- n! ) recursive
2131: dup 0> if
2132: dup 1- fac1 *
2133: else
2134: drop 1
2135: endif ;
2136: 7 fac1 .
2137:
2138: : fac2 ( n -- n! )
2139: dup 0> if
2140: dup 1- recurse *
2141: else
2142: drop 1
2143: endif ;
2144: 8 fac2 .
2145: @end example
2146:
2147: @assignment
2148: Write a recursive definition for computing the nth Fibonacci number.
2149: @endassignment
2150:
1.66 anton 2151: Reference (including indirect recursion): @xref{Calls and returns}.
2152:
1.48 anton 2153:
2154: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2155: @section Leaving definitions or loops
1.66 anton 2156: @cindex leaving definitions, tutorial
2157: @cindex leaving loops, tutorial
1.48 anton 2158:
2159: @code{EXIT} exits the current definition right away. For every counted
2160: loop that is left in this way, an @code{UNLOOP} has to be performed
2161: before the @code{EXIT}:
2162:
2163: @c !! real examples
2164: @example
2165: : ...
2166: ... u+do
2167: ... if
2168: ... unloop exit
2169: endif
2170: ...
2171: loop
2172: ... ;
2173: @end example
2174:
2175: @code{LEAVE} leaves the innermost counted loop right away:
2176:
2177: @example
2178: : ...
2179: ... u+do
2180: ... if
2181: ... leave
2182: endif
2183: ...
2184: loop
2185: ... ;
2186: @end example
2187:
1.65 anton 2188: @c !! example
1.48 anton 2189:
1.66 anton 2190: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2191:
2192:
1.48 anton 2193: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2194: @section Return Stack
1.66 anton 2195: @cindex return stack tutorial
1.48 anton 2196:
2197: In addition to the data stack Forth also has a second stack, the return
2198: stack; most Forth systems store the return addresses of procedure calls
2199: there (thus its name). Programmers can also use this stack:
2200:
2201: @example
2202: : foo ( n1 n2 -- )
2203: .s
2204: >r .s
1.50 anton 2205: r@@ .
1.48 anton 2206: >r .s
1.50 anton 2207: r@@ .
1.48 anton 2208: r> .
1.50 anton 2209: r@@ .
1.48 anton 2210: r> . ;
2211: 1 2 foo
2212: @end example
2213:
2214: @code{>r} takes an element from the data stack and pushes it onto the
2215: return stack; conversely, @code{r>} moves an elementm from the return to
2216: the data stack; @code{r@@} pushes a copy of the top of the return stack
2217: on the return stack.
2218:
2219: Forth programmers usually use the return stack for storing data
2220: temporarily, if using the data stack alone would be too complex, and
2221: factoring and locals are not an option:
2222:
2223: @example
2224: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2225: rot >r rot r> ;
2226: @end example
2227:
2228: The return address of the definition and the loop control parameters of
2229: counted loops usually reside on the return stack, so you have to take
2230: all items, that you have pushed on the return stack in a colon
2231: definition or counted loop, from the return stack before the definition
2232: or loop ends. You cannot access items that you pushed on the return
2233: stack outside some definition or loop within the definition of loop.
2234:
2235: If you miscount the return stack items, this usually ends in a crash:
2236:
2237: @example
2238: : crash ( n -- )
2239: >r ;
2240: 5 crash
2241: @end example
2242:
2243: You cannot mix using locals and using the return stack (according to the
2244: standard; Gforth has no problem). However, they solve the same
2245: problems, so this shouldn't be an issue.
2246:
2247: @assignment
2248: Can you rewrite any of the definitions you wrote until now in a better
2249: way using the return stack?
2250: @endassignment
2251:
1.66 anton 2252: Reference: @ref{Return stack}.
2253:
1.48 anton 2254:
2255: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2256: @section Memory
1.66 anton 2257: @cindex memory access/allocation tutorial
1.48 anton 2258:
2259: You can create a global variable @code{v} with
2260:
2261: @example
2262: variable v ( -- addr )
2263: @end example
2264:
2265: @code{v} pushes the address of a cell in memory on the stack. This cell
2266: was reserved by @code{variable}. You can use @code{!} (store) to store
2267: values into this cell and @code{@@} (fetch) to load the value from the
2268: stack into memory:
2269:
2270: @example
2271: v .
2272: 5 v ! .s
1.50 anton 2273: v @@ .
1.48 anton 2274: @end example
2275:
1.65 anton 2276: You can see a raw dump of memory with @code{dump}:
2277:
2278: @example
2279: v 1 cells .s dump
2280: @end example
2281:
2282: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2283: generally, address units (aus)) that @code{n1 cells} occupy. You can
2284: also reserve more memory:
1.48 anton 2285:
2286: @example
2287: create v2 20 cells allot
1.65 anton 2288: v2 20 cells dump
1.48 anton 2289: @end example
2290:
1.65 anton 2291: creates a word @code{v2} and reserves 20 uninitialized cells; the
2292: address pushed by @code{v2} points to the start of these 20 cells. You
2293: can use address arithmetic to access these cells:
1.48 anton 2294:
2295: @example
2296: 3 v2 5 cells + !
1.65 anton 2297: v2 20 cells dump
1.48 anton 2298: @end example
2299:
2300: You can reserve and initialize memory with @code{,}:
2301:
2302: @example
2303: create v3
2304: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2305: v3 @@ .
2306: v3 cell+ @@ .
2307: v3 2 cells + @@ .
1.65 anton 2308: v3 5 cells dump
1.48 anton 2309: @end example
2310:
2311: @assignment
2312: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2313: @code{u} cells, with the first of these cells at @code{addr}, the next
2314: one at @code{addr cell+} etc.
2315: @endassignment
2316:
2317: You can also reserve memory without creating a new word:
2318:
2319: @example
1.60 anton 2320: here 10 cells allot .
2321: here .
1.48 anton 2322: @end example
2323:
2324: @code{Here} pushes the start address of the memory area. You should
2325: store it somewhere, or you will have a hard time finding the memory area
2326: again.
2327:
2328: @code{Allot} manages dictionary memory. The dictionary memory contains
2329: the system's data structures for words etc. on Gforth and most other
2330: Forth systems. It is managed like a stack: You can free the memory that
2331: you have just @code{allot}ed with
2332:
2333: @example
2334: -10 cells allot
1.60 anton 2335: here .
1.48 anton 2336: @end example
2337:
2338: Note that you cannot do this if you have created a new word in the
2339: meantime (because then your @code{allot}ed memory is no longer on the
2340: top of the dictionary ``stack'').
2341:
2342: Alternatively, you can use @code{allocate} and @code{free} which allow
2343: freeing memory in any order:
2344:
2345: @example
2346: 10 cells allocate throw .s
2347: 20 cells allocate throw .s
2348: swap
2349: free throw
2350: free throw
2351: @end example
2352:
2353: The @code{throw}s deal with errors (e.g., out of memory).
2354:
1.65 anton 2355: And there is also a
2356: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2357: garbage collector}, which eliminates the need to @code{free} memory
2358: explicitly.
1.48 anton 2359:
1.66 anton 2360: Reference: @ref{Memory}.
2361:
1.48 anton 2362:
2363: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2364: @section Characters and Strings
1.66 anton 2365: @cindex strings tutorial
2366: @cindex characters tutorial
1.48 anton 2367:
2368: On the stack characters take up a cell, like numbers. In memory they
2369: have their own size (one 8-bit byte on most systems), and therefore
2370: require their own words for memory access:
2371:
2372: @example
2373: create v4
2374: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2375: v4 4 chars + c@@ .
1.65 anton 2376: v4 5 chars dump
1.48 anton 2377: @end example
2378:
2379: The preferred representation of strings on the stack is @code{addr
2380: u-count}, where @code{addr} is the address of the first character and
2381: @code{u-count} is the number of characters in the string.
2382:
2383: @example
2384: v4 5 type
2385: @end example
2386:
2387: You get a string constant with
2388:
2389: @example
2390: s" hello, world" .s
2391: type
2392: @end example
2393:
2394: Make sure you have a space between @code{s"} and the string; @code{s"}
2395: is a normal Forth word and must be delimited with white space (try what
2396: happens when you remove the space).
2397:
2398: However, this interpretive use of @code{s"} is quite restricted: the
2399: string exists only until the next call of @code{s"} (some Forth systems
2400: keep more than one of these strings, but usually they still have a
1.62 crook 2401: limited lifetime).
1.48 anton 2402:
2403: @example
2404: s" hello," s" world" .s
2405: type
2406: type
2407: @end example
2408:
1.62 crook 2409: You can also use @code{s"} in a definition, and the resulting
2410: strings then live forever (well, for as long as the definition):
1.48 anton 2411:
2412: @example
2413: : foo s" hello," s" world" ;
2414: foo .s
2415: type
2416: type
2417: @end example
2418:
2419: @assignment
2420: @code{Emit ( c -- )} types @code{c} as character (not a number).
2421: Implement @code{type ( addr u -- )}.
2422: @endassignment
2423:
1.66 anton 2424: Reference: @ref{Memory Blocks}.
2425:
2426:
1.84 pazsan 2427: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2428: @section Alignment
1.66 anton 2429: @cindex alignment tutorial
2430: @cindex memory alignment tutorial
1.48 anton 2431:
2432: On many processors cells have to be aligned in memory, if you want to
2433: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2434: not require alignment, access to aligned cells is faster).
1.48 anton 2435:
2436: @code{Create} aligns @code{here} (i.e., the place where the next
2437: allocation will occur, and that the @code{create}d word points to).
2438: Likewise, the memory produced by @code{allocate} starts at an aligned
2439: address. Adding a number of @code{cells} to an aligned address produces
2440: another aligned address.
2441:
2442: However, address arithmetic involving @code{char+} and @code{chars} can
2443: create an address that is not cell-aligned. @code{Aligned ( addr --
2444: a-addr )} produces the next aligned address:
2445:
2446: @example
1.50 anton 2447: v3 char+ aligned .s @@ .
2448: v3 char+ .s @@ .
1.48 anton 2449: @end example
2450:
2451: Similarly, @code{align} advances @code{here} to the next aligned
2452: address:
2453:
2454: @example
2455: create v5 97 c,
2456: here .
2457: align here .
2458: 1000 ,
2459: @end example
2460:
2461: Note that you should use aligned addresses even if your processor does
2462: not require them, if you want your program to be portable.
2463:
1.66 anton 2464: Reference: @ref{Address arithmetic}.
2465:
1.48 anton 2466:
1.84 pazsan 2467: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2468: @section Files
2469: @cindex files tutorial
2470:
2471: This section gives a short introduction into how to use files inside
2472: Forth. It's broken up into five easy steps:
2473:
2474: @enumerate 1
2475: @item Opened an ASCII text file for input
2476: @item Opened a file for output
2477: @item Read input file until string matched (or some other condition matched)
2478: @item Wrote some lines from input ( modified or not) to output
2479: @item Closed the files.
2480: @end enumerate
2481:
2482: @subsection Open file for input
2483:
2484: @example
2485: s" foo.in" r/o open-file throw Value fd-in
2486: @end example
2487:
2488: @subsection Create file for output
2489:
2490: @example
2491: s" foo.out" w/o create-file throw Value fd-out
2492: @end example
2493:
2494: The available file modes are r/o for read-only access, r/w for
2495: read-write access, and w/o for write-only access. You could open both
2496: files with r/w, too, if you like. All file words return error codes; for
2497: most applications, it's best to pass there error codes with @code{throw}
2498: to the outer error handler.
2499:
2500: If you want words for opening and assigning, define them as follows:
2501:
2502: @example
2503: 0 Value fd-in
2504: 0 Value fd-out
2505: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2506: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2507: @end example
2508:
2509: Usage example:
2510:
2511: @example
2512: s" foo.in" open-input
2513: s" foo.out" open-output
2514: @end example
2515:
2516: @subsection Scan file for a particular line
2517:
2518: @example
2519: 256 Constant max-line
2520: Create line-buffer max-line 2 + allot
2521:
2522: : scan-file ( addr u -- )
2523: begin
2524: line-buffer max-line fd-in read-line throw
2525: while
2526: >r 2dup line-buffer r> compare 0=
2527: until
2528: else
2529: drop
2530: then
2531: 2drop ;
2532: @end example
2533:
2534: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2535: the buffer at addr, and returns the number of bytes read, a flag that is
2536: false when the end of file is reached, and an error code.
1.84 pazsan 2537:
2538: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2539: returns zero if both strings are equal. It returns a positive number if
2540: the first string is lexically greater, a negative if the second string
2541: is lexically greater.
2542:
2543: We haven't seen this loop here; it has two exits. Since the @code{while}
2544: exits with the number of bytes read on the stack, we have to clean up
2545: that separately; that's after the @code{else}.
2546:
2547: Usage example:
2548:
2549: @example
2550: s" The text I search is here" scan-file
2551: @end example
2552:
2553: @subsection Copy input to output
2554:
2555: @example
2556: : copy-file ( -- )
2557: begin
2558: line-buffer max-line fd-in read-line throw
2559: while
2560: line-buffer swap fd-out write-file throw
2561: repeat ;
2562: @end example
2563:
2564: @subsection Close files
2565:
2566: @example
2567: fd-in close-file throw
2568: fd-out close-file throw
2569: @end example
2570:
2571: Likewise, you can put that into definitions, too:
2572:
2573: @example
2574: : close-input ( -- ) fd-in close-file throw ;
2575: : close-output ( -- ) fd-out close-file throw ;
2576: @end example
2577:
2578: @assignment
2579: How could you modify @code{copy-file} so that it copies until a second line is
2580: matched? Can you write a program that extracts a section of a text file,
2581: given the line that starts and the line that terminates that section?
2582: @endassignment
2583:
2584: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2585: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2586: @cindex semantics tutorial
2587: @cindex interpretation semantics tutorial
2588: @cindex compilation semantics tutorial
2589: @cindex immediate, tutorial
1.48 anton 2590:
2591: When a word is compiled, it behaves differently from being interpreted.
2592: E.g., consider @code{+}:
2593:
2594: @example
2595: 1 2 + .
2596: : foo + ;
2597: @end example
2598:
2599: These two behaviours are known as compilation and interpretation
2600: semantics. For normal words (e.g., @code{+}), the compilation semantics
2601: is to append the interpretation semantics to the currently defined word
2602: (@code{foo} in the example above). I.e., when @code{foo} is executed
2603: later, the interpretation semantics of @code{+} (i.e., adding two
2604: numbers) will be performed.
2605:
2606: However, there are words with non-default compilation semantics, e.g.,
2607: the control-flow words like @code{if}. You can use @code{immediate} to
2608: change the compilation semantics of the last defined word to be equal to
2609: the interpretation semantics:
2610:
2611: @example
2612: : [FOO] ( -- )
2613: 5 . ; immediate
2614:
2615: [FOO]
2616: : bar ( -- )
2617: [FOO] ;
2618: bar
2619: see bar
2620: @end example
2621:
2622: Two conventions to mark words with non-default compilation semnatics are
2623: names with brackets (more frequently used) and to write them all in
2624: upper case (less frequently used).
2625:
2626: In Gforth (and many other systems) you can also remove the
2627: interpretation semantics with @code{compile-only} (the compilation
2628: semantics is derived from the original interpretation semantics):
2629:
2630: @example
2631: : flip ( -- )
2632: 6 . ; compile-only \ but not immediate
2633: flip
2634:
2635: : flop ( -- )
2636: flip ;
2637: flop
2638: @end example
2639:
2640: In this example the interpretation semantics of @code{flop} is equal to
2641: the original interpretation semantics of @code{flip}.
2642:
2643: The text interpreter has two states: in interpret state, it performs the
2644: interpretation semantics of words it encounters; in compile state, it
2645: performs the compilation semantics of these words.
2646:
2647: Among other things, @code{:} switches into compile state, and @code{;}
2648: switches back to interpret state. They contain the factors @code{]}
2649: (switch to compile state) and @code{[} (switch to interpret state), that
2650: do nothing but switch the state.
2651:
2652: @example
2653: : xxx ( -- )
2654: [ 5 . ]
2655: ;
2656:
2657: xxx
2658: see xxx
2659: @end example
2660:
2661: These brackets are also the source of the naming convention mentioned
2662: above.
2663:
1.66 anton 2664: Reference: @ref{Interpretation and Compilation Semantics}.
2665:
1.48 anton 2666:
2667: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2668: @section Execution Tokens
1.66 anton 2669: @cindex execution tokens tutorial
2670: @cindex XT tutorial
1.48 anton 2671:
2672: @code{' word} gives you the execution token (XT) of a word. The XT is a
2673: cell representing the interpretation semantics of a word. You can
2674: execute this semantics with @code{execute}:
2675:
2676: @example
2677: ' + .s
2678: 1 2 rot execute .
2679: @end example
2680:
2681: The XT is similar to a function pointer in C. However, parameter
2682: passing through the stack makes it a little more flexible:
2683:
2684: @example
2685: : map-array ( ... addr u xt -- ... )
1.50 anton 2686: \ executes xt ( ... x -- ... ) for every element of the array starting
2687: \ at addr and containing u elements
1.48 anton 2688: @{ xt @}
2689: cells over + swap ?do
1.50 anton 2690: i @@ xt execute
1.48 anton 2691: 1 cells +loop ;
2692:
2693: create a 3 , 4 , 2 , -1 , 4 ,
2694: a 5 ' . map-array .s
2695: 0 a 5 ' + map-array .
2696: s" max-n" environment? drop .s
2697: a 5 ' min map-array .
2698: @end example
2699:
2700: You can use map-array with the XTs of words that consume one element
2701: more than they produce. In theory you can also use it with other XTs,
2702: but the stack effect then depends on the size of the array, which is
2703: hard to understand.
2704:
1.51 pazsan 2705: Since XTs are cell-sized, you can store them in memory and manipulate
2706: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2707: word with @code{compile,}:
2708:
2709: @example
2710: : foo1 ( n1 n2 -- n )
2711: [ ' + compile, ] ;
2712: see foo
2713: @end example
2714:
2715: This is non-standard, because @code{compile,} has no compilation
2716: semantics in the standard, but it works in good Forth systems. For the
2717: broken ones, use
2718:
2719: @example
2720: : [compile,] compile, ; immediate
2721:
2722: : foo1 ( n1 n2 -- n )
2723: [ ' + ] [compile,] ;
2724: see foo
2725: @end example
2726:
2727: @code{'} is a word with default compilation semantics; it parses the
2728: next word when its interpretation semantics are executed, not during
2729: compilation:
2730:
2731: @example
2732: : foo ( -- xt )
2733: ' ;
2734: see foo
2735: : bar ( ... "word" -- ... )
2736: ' execute ;
2737: see bar
1.60 anton 2738: 1 2 bar + .
1.48 anton 2739: @end example
2740:
2741: You often want to parse a word during compilation and compile its XT so
2742: it will be pushed on the stack at run-time. @code{[']} does this:
2743:
2744: @example
2745: : xt-+ ( -- xt )
2746: ['] + ;
2747: see xt-+
2748: 1 2 xt-+ execute .
2749: @end example
2750:
2751: Many programmers tend to see @code{'} and the word it parses as one
2752: unit, and expect it to behave like @code{[']} when compiled, and are
2753: confused by the actual behaviour. If you are, just remember that the
2754: Forth system just takes @code{'} as one unit and has no idea that it is
2755: a parsing word (attempts to convenience programmers in this issue have
2756: usually resulted in even worse pitfalls, see
1.66 anton 2757: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2758: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2759:
2760: Note that the state of the interpreter does not come into play when
1.51 pazsan 2761: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2762: compile state, it still gives you the interpretation semantics. And
2763: whatever that state is, @code{execute} performs the semantics
1.66 anton 2764: represented by the XT (i.e., for XTs produced with @code{'} the
2765: interpretation semantics).
2766:
2767: Reference: @ref{Tokens for Words}.
1.48 anton 2768:
2769:
2770: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2771: @section Exceptions
1.66 anton 2772: @cindex exceptions tutorial
1.48 anton 2773:
2774: @code{throw ( n -- )} causes an exception unless n is zero.
2775:
2776: @example
2777: 100 throw .s
2778: 0 throw .s
2779: @end example
2780:
2781: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2782: it catches exceptions and pushes the number of the exception on the
2783: stack (or 0, if the xt executed without exception). If there was an
2784: exception, the stacks have the same depth as when entering @code{catch}:
2785:
2786: @example
2787: .s
2788: 3 0 ' / catch .s
2789: 3 2 ' / catch .s
2790: @end example
2791:
2792: @assignment
2793: Try the same with @code{execute} instead of @code{catch}.
2794: @endassignment
2795:
2796: @code{Throw} always jumps to the dynamically next enclosing
2797: @code{catch}, even if it has to leave several call levels to achieve
2798: this:
2799:
2800: @example
2801: : foo 100 throw ;
2802: : foo1 foo ." after foo" ;
1.51 pazsan 2803: : bar ['] foo1 catch ;
1.60 anton 2804: bar .
1.48 anton 2805: @end example
2806:
2807: It is often important to restore a value upon leaving a definition, even
2808: if the definition is left through an exception. You can ensure this
2809: like this:
2810:
2811: @example
2812: : ...
2813: save-x
1.51 pazsan 2814: ['] word-changing-x catch ( ... n )
1.48 anton 2815: restore-x
2816: ( ... n ) throw ;
2817: @end example
2818:
1.55 anton 2819: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2820: @code{try ... recover ... endtry}. If the code between @code{try} and
2821: @code{recover} has an exception, the stack depths are restored, the
2822: exception number is pushed on the stack, and the code between
2823: @code{recover} and @code{endtry} is performed. E.g., the definition for
2824: @code{catch} is
2825:
2826: @example
2827: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2828: try
2829: execute 0
2830: recover
2831: nip
2832: endtry ;
2833: @end example
2834:
2835: The equivalent to the restoration code above is
2836:
2837: @example
2838: : ...
2839: save-x
2840: try
1.92 anton 2841: word-changing-x 0
2842: recover endtry
1.48 anton 2843: restore-x
2844: throw ;
2845: @end example
2846:
1.92 anton 2847: This works if @code{word-changing-x} does not change the stack depth,
2848: otherwise you should add some code between @code{recover} and
2849: @code{endtry} to balance the stack.
1.48 anton 2850:
1.66 anton 2851: Reference: @ref{Exception Handling}.
2852:
1.48 anton 2853:
2854: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2855: @section Defining Words
1.66 anton 2856: @cindex defining words tutorial
2857: @cindex does> tutorial
2858: @cindex create...does> tutorial
2859:
2860: @c before semantics?
1.48 anton 2861:
2862: @code{:}, @code{create}, and @code{variable} are definition words: They
2863: define other words. @code{Constant} is another definition word:
2864:
2865: @example
2866: 5 constant foo
2867: foo .
2868: @end example
2869:
2870: You can also use the prefixes @code{2} (double-cell) and @code{f}
2871: (floating point) with @code{variable} and @code{constant}.
2872:
2873: You can also define your own defining words. E.g.:
2874:
2875: @example
2876: : variable ( "name" -- )
2877: create 0 , ;
2878: @end example
2879:
2880: You can also define defining words that create words that do something
2881: other than just producing their address:
2882:
2883: @example
2884: : constant ( n "name" -- )
2885: create ,
2886: does> ( -- n )
1.50 anton 2887: ( addr ) @@ ;
1.48 anton 2888:
2889: 5 constant foo
2890: foo .
2891: @end example
2892:
2893: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2894: @code{does>} replaces @code{;}, but it also does something else: It
2895: changes the last defined word such that it pushes the address of the
2896: body of the word and then performs the code after the @code{does>}
2897: whenever it is called.
2898:
2899: In the example above, @code{constant} uses @code{,} to store 5 into the
2900: body of @code{foo}. When @code{foo} executes, it pushes the address of
2901: the body onto the stack, then (in the code after the @code{does>})
2902: fetches the 5 from there.
2903:
2904: The stack comment near the @code{does>} reflects the stack effect of the
2905: defined word, not the stack effect of the code after the @code{does>}
2906: (the difference is that the code expects the address of the body that
2907: the stack comment does not show).
2908:
2909: You can use these definition words to do factoring in cases that involve
2910: (other) definition words. E.g., a field offset is always added to an
2911: address. Instead of defining
2912:
2913: @example
2914: 2 cells constant offset-field1
2915: @end example
2916:
2917: and using this like
2918:
2919: @example
2920: ( addr ) offset-field1 +
2921: @end example
2922:
2923: you can define a definition word
2924:
2925: @example
2926: : simple-field ( n "name" -- )
2927: create ,
2928: does> ( n1 -- n1+n )
1.50 anton 2929: ( addr ) @@ + ;
1.48 anton 2930: @end example
1.21 crook 2931:
1.48 anton 2932: Definition and use of field offsets now look like this:
1.21 crook 2933:
1.48 anton 2934: @example
2935: 2 cells simple-field field1
1.60 anton 2936: create mystruct 4 cells allot
2937: mystruct .s field1 .s drop
1.48 anton 2938: @end example
1.21 crook 2939:
1.48 anton 2940: If you want to do something with the word without performing the code
2941: after the @code{does>}, you can access the body of a @code{create}d word
2942: with @code{>body ( xt -- addr )}:
1.21 crook 2943:
1.48 anton 2944: @example
2945: : value ( n "name" -- )
2946: create ,
2947: does> ( -- n1 )
1.50 anton 2948: @@ ;
1.48 anton 2949: : to ( n "name" -- )
2950: ' >body ! ;
1.21 crook 2951:
1.48 anton 2952: 5 value foo
2953: foo .
2954: 7 to foo
2955: foo .
2956: @end example
1.21 crook 2957:
1.48 anton 2958: @assignment
2959: Define @code{defer ( "name" -- )}, which creates a word that stores an
2960: XT (at the start the XT of @code{abort}), and upon execution
2961: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2962: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2963: recursion is one application of @code{defer}.
2964: @endassignment
1.29 crook 2965:
1.66 anton 2966: Reference: @ref{User-defined Defining Words}.
2967:
2968:
1.48 anton 2969: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2970: @section Arrays and Records
1.66 anton 2971: @cindex arrays tutorial
2972: @cindex records tutorial
2973: @cindex structs tutorial
1.29 crook 2974:
1.48 anton 2975: Forth has no standard words for defining data structures such as arrays
2976: and records (structs in C terminology), but you can build them yourself
2977: based on address arithmetic. You can also define words for defining
2978: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2979:
1.48 anton 2980: One of the first projects a Forth newcomer sets out upon when learning
2981: about defining words is an array defining word (possibly for
2982: n-dimensional arrays). Go ahead and do it, I did it, too; you will
2983: learn something from it. However, don't be disappointed when you later
2984: learn that you have little use for these words (inappropriate use would
2985: be even worse). I have not yet found a set of useful array words yet;
2986: the needs are just too diverse, and named, global arrays (the result of
2987: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 2988: consider how to pass them as parameters). Another such project is a set
2989: of words to help dealing with strings.
1.29 crook 2990:
1.48 anton 2991: On the other hand, there is a useful set of record words, and it has
2992: been defined in @file{compat/struct.fs}; these words are predefined in
2993: Gforth. They are explained in depth elsewhere in this manual (see
2994: @pxref{Structures}). The @code{simple-field} example above is
2995: simplified variant of fields in this package.
1.21 crook 2996:
2997:
1.48 anton 2998: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
2999: @section @code{POSTPONE}
1.66 anton 3000: @cindex postpone tutorial
1.21 crook 3001:
1.48 anton 3002: You can compile the compilation semantics (instead of compiling the
3003: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3004:
1.48 anton 3005: @example
3006: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3007: POSTPONE + ; immediate
1.48 anton 3008: : foo ( n1 n2 -- n )
3009: MY-+ ;
3010: 1 2 foo .
3011: see foo
3012: @end example
1.21 crook 3013:
1.48 anton 3014: During the definition of @code{foo} the text interpreter performs the
3015: compilation semantics of @code{MY-+}, which performs the compilation
3016: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3017:
3018: This example also displays separate stack comments for the compilation
3019: semantics and for the stack effect of the compiled code. For words with
3020: default compilation semantics these stack effects are usually not
3021: displayed; the stack effect of the compilation semantics is always
3022: @code{( -- )} for these words, the stack effect for the compiled code is
3023: the stack effect of the interpretation semantics.
3024:
3025: Note that the state of the interpreter does not come into play when
3026: performing the compilation semantics in this way. You can also perform
3027: it interpretively, e.g.:
3028:
3029: @example
3030: : foo2 ( n1 n2 -- n )
3031: [ MY-+ ] ;
3032: 1 2 foo .
3033: see foo
3034: @end example
1.21 crook 3035:
1.48 anton 3036: However, there are some broken Forth systems where this does not always
1.62 crook 3037: work, and therefore this practice was been declared non-standard in
1.48 anton 3038: 1999.
3039: @c !! repair.fs
3040:
3041: Here is another example for using @code{POSTPONE}:
1.44 crook 3042:
1.48 anton 3043: @example
3044: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3045: POSTPONE negate POSTPONE + ; immediate compile-only
3046: : bar ( n1 n2 -- n )
3047: MY-- ;
3048: 2 1 bar .
3049: see bar
3050: @end example
1.21 crook 3051:
1.48 anton 3052: You can define @code{ENDIF} in this way:
1.21 crook 3053:
1.48 anton 3054: @example
3055: : ENDIF ( Compilation: orig -- )
3056: POSTPONE then ; immediate
3057: @end example
1.21 crook 3058:
1.48 anton 3059: @assignment
3060: Write @code{MY-2DUP} that has compilation semantics equivalent to
3061: @code{2dup}, but compiles @code{over over}.
3062: @endassignment
1.29 crook 3063:
1.66 anton 3064: @c !! @xref{Macros} for reference
3065:
3066:
1.48 anton 3067: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3068: @section @code{Literal}
1.66 anton 3069: @cindex literal tutorial
1.29 crook 3070:
1.48 anton 3071: You cannot @code{POSTPONE} numbers:
1.21 crook 3072:
1.48 anton 3073: @example
3074: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3075: @end example
3076:
1.48 anton 3077: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3078:
1.48 anton 3079: @example
3080: : [FOO] ( compilation: --; run-time: -- n )
3081: 500 POSTPONE literal ; immediate
1.29 crook 3082:
1.60 anton 3083: : flip [FOO] ;
1.48 anton 3084: flip .
3085: see flip
3086: @end example
1.29 crook 3087:
1.48 anton 3088: @code{LITERAL} consumes a number at compile-time (when it's compilation
3089: semantics are executed) and pushes it at run-time (when the code it
3090: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3091: number computed at compile time into the current word:
1.29 crook 3092:
1.48 anton 3093: @example
3094: : bar ( -- n )
3095: [ 2 2 + ] literal ;
3096: see bar
3097: @end example
1.29 crook 3098:
1.48 anton 3099: @assignment
3100: Write @code{]L} which allows writing the example above as @code{: bar (
3101: -- n ) [ 2 2 + ]L ;}
3102: @endassignment
3103:
1.66 anton 3104: @c !! @xref{Macros} for reference
3105:
1.48 anton 3106:
3107: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3108: @section Advanced macros
1.66 anton 3109: @cindex macros, advanced tutorial
3110: @cindex run-time code generation, tutorial
1.48 anton 3111:
1.66 anton 3112: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3113: Execution Tokens}. It frequently performs @code{execute}, a relatively
3114: expensive operation in some Forth implementations. You can use
1.48 anton 3115: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3116: and produce a word that contains the word to be performed directly:
3117:
3118: @c use ]] ... [[
3119: @example
3120: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3121: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3122: \ array beginning at addr and containing u elements
3123: @{ xt @}
3124: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3125: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3126: 1 cells POSTPONE literal POSTPONE +loop ;
3127:
3128: : sum-array ( addr u -- n )
3129: 0 rot rot [ ' + compile-map-array ] ;
3130: see sum-array
3131: a 5 sum-array .
3132: @end example
3133:
3134: You can use the full power of Forth for generating the code; here's an
3135: example where the code is generated in a loop:
3136:
3137: @example
3138: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3139: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3140: POSTPONE tuck POSTPONE @@
1.48 anton 3141: POSTPONE literal POSTPONE * POSTPONE +
3142: POSTPONE swap POSTPONE cell+ ;
3143:
3144: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3145: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3146: 0 postpone literal postpone swap
3147: [ ' compile-vmul-step compile-map-array ]
3148: postpone drop ;
3149: see compile-vmul
3150:
3151: : a-vmul ( addr -- n )
1.51 pazsan 3152: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3153: [ a 5 compile-vmul ] ;
3154: see a-vmul
3155: a a-vmul .
3156: @end example
3157:
3158: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3159: also use @code{map-array} instead (try it now!).
1.48 anton 3160:
3161: You can use this technique for efficient multiplication of large
3162: matrices. In matrix multiplication, you multiply every line of one
3163: matrix with every column of the other matrix. You can generate the code
3164: for one line once, and use it for every column. The only downside of
3165: this technique is that it is cumbersome to recover the memory consumed
3166: by the generated code when you are done (and in more complicated cases
3167: it is not possible portably).
3168:
1.66 anton 3169: @c !! @xref{Macros} for reference
3170:
3171:
1.48 anton 3172: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3173: @section Compilation Tokens
1.66 anton 3174: @cindex compilation tokens, tutorial
3175: @cindex CT, tutorial
1.48 anton 3176:
3177: This section is Gforth-specific. You can skip it.
3178:
3179: @code{' word compile,} compiles the interpretation semantics. For words
3180: with default compilation semantics this is the same as performing the
3181: compilation semantics. To represent the compilation semantics of other
3182: words (e.g., words like @code{if} that have no interpretation
3183: semantics), Gforth has the concept of a compilation token (CT,
3184: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3185: You can perform the compilation semantics represented by a CT with
3186: @code{execute}:
1.29 crook 3187:
1.48 anton 3188: @example
3189: : foo2 ( n1 n2 -- n )
3190: [ comp' + execute ] ;
3191: see foo
3192: @end example
1.29 crook 3193:
1.48 anton 3194: You can compile the compilation semantics represented by a CT with
3195: @code{postpone,}:
1.30 anton 3196:
1.48 anton 3197: @example
3198: : foo3 ( -- )
3199: [ comp' + postpone, ] ;
3200: see foo3
3201: @end example
1.30 anton 3202:
1.51 pazsan 3203: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3204: @code{comp'} is particularly useful for words that have no
3205: interpretation semantics:
1.29 crook 3206:
1.30 anton 3207: @example
1.48 anton 3208: ' if
1.60 anton 3209: comp' if .s 2drop
1.30 anton 3210: @end example
3211:
1.66 anton 3212: Reference: @ref{Tokens for Words}.
3213:
1.29 crook 3214:
1.48 anton 3215: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3216: @section Wordlists and Search Order
1.66 anton 3217: @cindex wordlists tutorial
3218: @cindex search order, tutorial
1.48 anton 3219:
3220: The dictionary is not just a memory area that allows you to allocate
3221: memory with @code{allot}, it also contains the Forth words, arranged in
3222: several wordlists. When searching for a word in a wordlist,
3223: conceptually you start searching at the youngest and proceed towards
3224: older words (in reality most systems nowadays use hash-tables); i.e., if
3225: you define a word with the same name as an older word, the new word
3226: shadows the older word.
3227:
3228: Which wordlists are searched in which order is determined by the search
3229: order. You can display the search order with @code{order}. It displays
3230: first the search order, starting with the wordlist searched first, then
3231: it displays the wordlist that will contain newly defined words.
1.21 crook 3232:
1.48 anton 3233: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3234:
1.48 anton 3235: @example
3236: wordlist constant mywords
3237: @end example
1.21 crook 3238:
1.48 anton 3239: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3240: defined words (the @emph{current} wordlist):
1.21 crook 3241:
1.48 anton 3242: @example
3243: mywords set-current
3244: order
3245: @end example
1.26 crook 3246:
1.48 anton 3247: Gforth does not display a name for the wordlist in @code{mywords}
3248: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3249:
1.48 anton 3250: You can get the current wordlist with @code{get-current ( -- wid)}. If
3251: you want to put something into a specific wordlist without overall
3252: effect on the current wordlist, this typically looks like this:
1.21 crook 3253:
1.48 anton 3254: @example
3255: get-current mywords set-current ( wid )
3256: create someword
3257: ( wid ) set-current
3258: @end example
1.21 crook 3259:
1.48 anton 3260: You can write the search order with @code{set-order ( wid1 .. widn n --
3261: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3262: searched wordlist is topmost.
1.21 crook 3263:
1.48 anton 3264: @example
3265: get-order mywords swap 1+ set-order
3266: order
3267: @end example
1.21 crook 3268:
1.48 anton 3269: Yes, the order of wordlists in the output of @code{order} is reversed
3270: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3271:
1.48 anton 3272: @assignment
3273: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3274: wordlist to the search order. Define @code{previous ( -- )}, which
3275: removes the first searched wordlist from the search order. Experiment
3276: with boundary conditions (you will see some crashes or situations that
3277: are hard or impossible to leave).
3278: @endassignment
1.21 crook 3279:
1.48 anton 3280: The search order is a powerful foundation for providing features similar
3281: to Modula-2 modules and C++ namespaces. However, trying to modularize
3282: programs in this way has disadvantages for debugging and reuse/factoring
3283: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3284: though). These disadvantages are not so clear in other
1.82 anton 3285: languages/programming environments, because these languages are not so
1.48 anton 3286: strong in debugging and reuse.
1.21 crook 3287:
1.66 anton 3288: @c !! example
3289:
3290: Reference: @ref{Word Lists}.
1.21 crook 3291:
1.29 crook 3292: @c ******************************************************************
1.48 anton 3293: @node Introduction, Words, Tutorial, Top
1.29 crook 3294: @comment node-name, next, previous, up
3295: @chapter An Introduction to ANS Forth
3296: @cindex Forth - an introduction
1.21 crook 3297:
1.83 anton 3298: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3299: that it is slower-paced in its examples, but uses them to dive deep into
3300: explaining Forth internals (not covered by the Tutorial). Apart from
3301: that, this chapter covers far less material. It is suitable for reading
3302: without using a computer.
3303:
1.29 crook 3304: The primary purpose of this manual is to document Gforth. However, since
3305: Forth is not a widely-known language and there is a lack of up-to-date
3306: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3307: material. For other sources of Forth-related
3308: information, see @ref{Forth-related information}.
1.21 crook 3309:
1.29 crook 3310: The examples in this section should work on any ANS Forth; the
3311: output shown was produced using Gforth. Each example attempts to
3312: reproduce the exact output that Gforth produces. If you try out the
3313: examples (and you should), what you should type is shown @kbd{like this}
3314: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3315: that, where the example shows @key{RET} it means that you should
1.29 crook 3316: press the ``carriage return'' key. Unfortunately, some output formats for
3317: this manual cannot show the difference between @kbd{this} and
3318: @code{this} which will make trying out the examples harder (but not
3319: impossible).
1.21 crook 3320:
1.29 crook 3321: Forth is an unusual language. It provides an interactive development
3322: environment which includes both an interpreter and compiler. Forth
3323: programming style encourages you to break a problem down into many
3324: @cindex factoring
3325: small fragments (@dfn{factoring}), and then to develop and test each
3326: fragment interactively. Forth advocates assert that breaking the
3327: edit-compile-test cycle used by conventional programming languages can
3328: lead to great productivity improvements.
1.21 crook 3329:
1.29 crook 3330: @menu
1.67 anton 3331: * Introducing the Text Interpreter::
3332: * Stacks and Postfix notation::
3333: * Your first definition::
3334: * How does that work?::
3335: * Forth is written in Forth::
3336: * Review - elements of a Forth system::
3337: * Where to go next::
3338: * Exercises::
1.29 crook 3339: @end menu
1.21 crook 3340:
1.29 crook 3341: @comment ----------------------------------------------
3342: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3343: @section Introducing the Text Interpreter
3344: @cindex text interpreter
3345: @cindex outer interpreter
1.21 crook 3346:
1.30 anton 3347: @c IMO this is too detailed and the pace is too slow for
3348: @c an introduction. If you know German, take a look at
3349: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3350: @c to see how I do it - anton
3351:
1.44 crook 3352: @c nac-> Where I have accepted your comments 100% and modified the text
3353: @c accordingly, I have deleted your comments. Elsewhere I have added a
3354: @c response like this to attempt to rationalise what I have done. Of
3355: @c course, this is a very clumsy mechanism for something that would be
3356: @c done far more efficiently over a beer. Please delete any dialogue
3357: @c you consider closed.
3358:
1.29 crook 3359: When you invoke the Forth image, you will see a startup banner printed
3360: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3361: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3362: its command line interpreter, which is called the @dfn{Text Interpreter}
3363: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3364: about the text interpreter as you read through this chapter, for more
3365: detail @pxref{The Text Interpreter}).
1.21 crook 3366:
1.29 crook 3367: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3368: input. Type a number and press the @key{RET} key:
1.21 crook 3369:
1.26 crook 3370: @example
1.30 anton 3371: @kbd{45@key{RET}} ok
1.26 crook 3372: @end example
1.21 crook 3373:
1.29 crook 3374: Rather than give you a prompt to invite you to input something, the text
3375: interpreter prints a status message @i{after} it has processed a line
3376: of input. The status message in this case (``@code{ ok}'' followed by
3377: carriage-return) indicates that the text interpreter was able to process
3378: all of your input successfully. Now type something illegal:
3379:
3380: @example
1.30 anton 3381: @kbd{qwer341@key{RET}}
1.29 crook 3382: :1: Undefined word
3383: qwer341
3384: ^^^^^^^
3385: $400D2BA8 Bounce
3386: $400DBDA8 no.extensions
3387: @end example
1.23 crook 3388:
1.29 crook 3389: The exact text, other than the ``Undefined word'' may differ slightly on
3390: your system, but the effect is the same; when the text interpreter
3391: detects an error, it discards any remaining text on a line, resets
1.49 anton 3392: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3393: messages}.
1.23 crook 3394:
1.29 crook 3395: The text interpreter waits for you to press carriage-return, and then
3396: processes your input line. Starting at the beginning of the line, it
3397: breaks the line into groups of characters separated by spaces. For each
3398: group of characters in turn, it makes two attempts to do something:
1.23 crook 3399:
1.29 crook 3400: @itemize @bullet
3401: @item
1.44 crook 3402: @cindex name dictionary
1.29 crook 3403: It tries to treat it as a command. It does this by searching a @dfn{name
3404: dictionary}. If the group of characters matches an entry in the name
3405: dictionary, the name dictionary provides the text interpreter with
3406: information that allows the text interpreter perform some actions. In
3407: Forth jargon, we say that the group
3408: @cindex word
3409: @cindex definition
3410: @cindex execution token
3411: @cindex xt
3412: of characters names a @dfn{word}, that the dictionary search returns an
3413: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3414: word, and that the text interpreter executes the xt. Often, the terms
3415: @dfn{word} and @dfn{definition} are used interchangeably.
3416: @item
3417: If the text interpreter fails to find a match in the name dictionary, it
3418: tries to treat the group of characters as a number in the current number
3419: base (when you start up Forth, the current number base is base 10). If
3420: the group of characters legitimately represents a number, the text
3421: interpreter pushes the number onto a stack (we'll learn more about that
3422: in the next section).
3423: @end itemize
1.23 crook 3424:
1.29 crook 3425: If the text interpreter is unable to do either of these things with any
3426: group of characters, it discards the group of characters and the rest of
3427: the line, then prints an error message. If the text interpreter reaches
3428: the end of the line without error, it prints the status message ``@code{ ok}''
3429: followed by carriage-return.
1.21 crook 3430:
1.29 crook 3431: This is the simplest command we can give to the text interpreter:
1.23 crook 3432:
3433: @example
1.30 anton 3434: @key{RET} ok
1.23 crook 3435: @end example
1.21 crook 3436:
1.29 crook 3437: The text interpreter did everything we asked it to do (nothing) without
3438: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3439: command:
1.21 crook 3440:
1.23 crook 3441: @example
1.30 anton 3442: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3443: :1: Undefined word
3444: 12 dup fred dup
3445: ^^^^
3446: $400D2BA8 Bounce
3447: $400DBDA8 no.extensions
1.23 crook 3448: @end example
1.21 crook 3449:
1.29 crook 3450: When you press the carriage-return key, the text interpreter starts to
3451: work its way along the line:
1.21 crook 3452:
1.29 crook 3453: @itemize @bullet
3454: @item
3455: When it gets to the space after the @code{2}, it takes the group of
3456: characters @code{12} and looks them up in the name
3457: dictionary@footnote{We can't tell if it found them or not, but assume
3458: for now that it did not}. There is no match for this group of characters
3459: in the name dictionary, so it tries to treat them as a number. It is
3460: able to do this successfully, so it puts the number, 12, ``on the stack''
3461: (whatever that means).
3462: @item
3463: The text interpreter resumes scanning the line and gets the next group
3464: of characters, @code{dup}. It looks it up in the name dictionary and
3465: (you'll have to take my word for this) finds it, and executes the word
3466: @code{dup} (whatever that means).
3467: @item
3468: Once again, the text interpreter resumes scanning the line and gets the
3469: group of characters @code{fred}. It looks them up in the name
3470: dictionary, but can't find them. It tries to treat them as a number, but
3471: they don't represent any legal number.
3472: @end itemize
1.21 crook 3473:
1.29 crook 3474: At this point, the text interpreter gives up and prints an error
3475: message. The error message shows exactly how far the text interpreter
3476: got in processing the line. In particular, it shows that the text
3477: interpreter made no attempt to do anything with the final character
3478: group, @code{dup}, even though we have good reason to believe that the
3479: text interpreter would have no problem looking that word up and
3480: executing it a second time.
1.21 crook 3481:
3482:
1.29 crook 3483: @comment ----------------------------------------------
3484: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3485: @section Stacks, postfix notation and parameter passing
3486: @cindex text interpreter
3487: @cindex outer interpreter
1.21 crook 3488:
1.29 crook 3489: In procedural programming languages (like C and Pascal), the
3490: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3491: functions or procedures are called with @dfn{explicit parameters}. For
3492: example, in C we might write:
1.21 crook 3493:
1.23 crook 3494: @example
1.29 crook 3495: total = total + new_volume(length,height,depth);
1.23 crook 3496: @end example
1.21 crook 3497:
1.23 crook 3498: @noindent
1.29 crook 3499: where new_volume is a function-call to another piece of code, and total,
3500: length, height and depth are all variables. length, height and depth are
3501: parameters to the function-call.
1.21 crook 3502:
1.29 crook 3503: In Forth, the equivalent of the function or procedure is the
3504: @dfn{definition} and parameters are implicitly passed between
3505: definitions using a shared stack that is visible to the
3506: programmer. Although Forth does support variables, the existence of the
3507: stack means that they are used far less often than in most other
3508: programming languages. When the text interpreter encounters a number, it
3509: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3510: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3511: used for any operation is implied unambiguously by the operation being
3512: performed. The stack used for all integer operations is called the @dfn{data
3513: stack} and, since this is the stack used most commonly, references to
3514: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3515:
1.29 crook 3516: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3517:
1.23 crook 3518: @example
1.30 anton 3519: @kbd{1 2 3@key{RET}} ok
1.23 crook 3520: @end example
1.21 crook 3521:
1.29 crook 3522: Then this instructs the text interpreter to placed three numbers on the
3523: (data) stack. An analogy for the behaviour of the stack is to take a
3524: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3525: the table. The 3 was the last card onto the pile (``last-in'') and if
3526: you take a card off the pile then, unless you're prepared to fiddle a
3527: bit, the card that you take off will be the 3 (``first-out''). The
3528: number that will be first-out of the stack is called the @dfn{top of
3529: stack}, which
3530: @cindex TOS definition
3531: is often abbreviated to @dfn{TOS}.
1.21 crook 3532:
1.29 crook 3533: To understand how parameters are passed in Forth, consider the
3534: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3535: be surprised to learn that this definition performs addition. More
3536: precisely, it adds two number together and produces a result. Where does
3537: it get the two numbers from? It takes the top two numbers off the
3538: stack. Where does it place the result? On the stack. You can act-out the
3539: behaviour of @code{+} with your playing cards like this:
1.21 crook 3540:
3541: @itemize @bullet
3542: @item
1.29 crook 3543: Pick up two cards from the stack on the table
1.21 crook 3544: @item
1.29 crook 3545: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3546: numbers''
1.21 crook 3547: @item
1.29 crook 3548: Decide that the answer is 5
1.21 crook 3549: @item
1.29 crook 3550: Shuffle the two cards back into the pack and find a 5
1.21 crook 3551: @item
1.29 crook 3552: Put a 5 on the remaining ace that's on the table.
1.21 crook 3553: @end itemize
3554:
1.29 crook 3555: If you don't have a pack of cards handy but you do have Forth running,
3556: you can use the definition @code{.s} to show the current state of the stack,
3557: without affecting the stack. Type:
1.21 crook 3558:
3559: @example
1.124 anton 3560: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3561: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3562: @end example
3563:
1.124 anton 3564: The text interpreter looks up the word @code{clearstacks} and executes
3565: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3566: left on it by earlier examples. The text interpreter pushes each of the
3567: three numbers in turn onto the stack. Finally, the text interpreter
3568: looks up the word @code{.s} and executes it. The effect of executing
3569: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3570: followed by a list of all the items on the stack; the item on the far
3571: right-hand side is the TOS.
1.21 crook 3572:
1.29 crook 3573: You can now type:
1.21 crook 3574:
1.29 crook 3575: @example
1.30 anton 3576: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3577: @end example
1.21 crook 3578:
1.29 crook 3579: @noindent
3580: which is correct; there are now 2 items on the stack and the result of
3581: the addition is 5.
1.23 crook 3582:
1.29 crook 3583: If you're playing with cards, try doing a second addition: pick up the
3584: two cards, work out that their sum is 6, shuffle them into the pack,
3585: look for a 6 and place that on the table. You now have just one item on
3586: the stack. What happens if you try to do a third addition? Pick up the
3587: first card, pick up the second card -- ah! There is no second card. This
3588: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3589: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3590: Underflow or an Invalid Memory Address error).
1.23 crook 3591:
1.29 crook 3592: The opposite situation to a stack underflow is a @dfn{stack overflow},
3593: which simply accepts that there is a finite amount of storage space
3594: reserved for the stack. To stretch the playing card analogy, if you had
3595: enough packs of cards and you piled the cards up on the table, you would
3596: eventually be unable to add another card; you'd hit the ceiling. Gforth
3597: allows you to set the maximum size of the stacks. In general, the only
3598: time that you will get a stack overflow is because a definition has a
3599: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3600:
1.29 crook 3601: There's one final use for the playing card analogy. If you model your
3602: stack using a pack of playing cards, the maximum number of items on
3603: your stack will be 52 (I assume you didn't use the Joker). The maximum
3604: @i{value} of any item on the stack is 13 (the King). In fact, the only
3605: possible numbers are positive integer numbers 1 through 13; you can't
3606: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3607: think about some of the cards, you can accommodate different
3608: numbers. For example, you could think of the Jack as representing 0,
3609: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3610: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3611: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3612:
1.29 crook 3613: In that analogy, the limit was the amount of information that a single
3614: stack entry could hold, and Forth has a similar limit. In Forth, the
3615: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3616: implementation dependent and affects the maximum value that a stack
3617: entry can hold. A Standard Forth provides a cell size of at least
3618: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3619:
1.29 crook 3620: Forth does not do any type checking for you, so you are free to
3621: manipulate and combine stack items in any way you wish. A convenient way
3622: of treating stack items is as 2's complement signed integers, and that
3623: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3624:
1.29 crook 3625: @example
1.30 anton 3626: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3627: @end example
1.21 crook 3628:
1.29 crook 3629: If you use numbers and definitions like @code{+} in order to turn Forth
3630: into a great big pocket calculator, you will realise that it's rather
3631: different from a normal calculator. Rather than typing 2 + 3 = you had
3632: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3633: result). The terminology used to describe this difference is to say that
3634: your calculator uses @dfn{Infix Notation} (parameters and operators are
3635: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3636: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3637:
1.29 crook 3638: Whilst postfix notation might look confusing to begin with, it has
3639: several important advantages:
1.21 crook 3640:
1.23 crook 3641: @itemize @bullet
3642: @item
1.29 crook 3643: it is unambiguous
1.23 crook 3644: @item
1.29 crook 3645: it is more concise
1.23 crook 3646: @item
1.29 crook 3647: it fits naturally with a stack-based system
1.23 crook 3648: @end itemize
1.21 crook 3649:
1.29 crook 3650: To examine these claims in more detail, consider these sums:
1.21 crook 3651:
1.29 crook 3652: @example
3653: 6 + 5 * 4 =
3654: 4 * 5 + 6 =
3655: @end example
1.21 crook 3656:
1.29 crook 3657: If you're just learning maths or your maths is very rusty, you will
3658: probably come up with the answer 44 for the first and 26 for the
3659: second. If you are a bit of a whizz at maths you will remember the
3660: @i{convention} that multiplication takes precendence over addition, and
3661: you'd come up with the answer 26 both times. To explain the answer 26
3662: to someone who got the answer 44, you'd probably rewrite the first sum
3663: like this:
1.21 crook 3664:
1.29 crook 3665: @example
3666: 6 + (5 * 4) =
3667: @end example
1.21 crook 3668:
1.29 crook 3669: If what you really wanted was to perform the addition before the
3670: multiplication, you would have to use parentheses to force it.
1.21 crook 3671:
1.29 crook 3672: If you did the first two sums on a pocket calculator you would probably
3673: get the right answers, unless you were very cautious and entered them using
3674: these keystroke sequences:
1.21 crook 3675:
1.29 crook 3676: 6 + 5 = * 4 =
3677: 4 * 5 = + 6 =
1.21 crook 3678:
1.29 crook 3679: Postfix notation is unambiguous because the order that the operators
3680: are applied is always explicit; that also means that parentheses are
3681: never required. The operators are @i{active} (the act of quoting the
3682: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3683:
1.29 crook 3684: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3685: equivalent ways:
1.26 crook 3686:
3687: @example
1.29 crook 3688: 6 5 4 * + or:
3689: 5 4 * 6 +
1.26 crook 3690: @end example
1.23 crook 3691:
1.29 crook 3692: An important thing that you should notice about this notation is that
3693: the @i{order} of the numbers does not change; if you want to subtract
3694: 2 from 10 you type @code{10 2 -}.
1.1 anton 3695:
1.29 crook 3696: The reason that Forth uses postfix notation is very simple to explain: it
3697: makes the implementation extremely simple, and it follows naturally from
3698: using the stack as a mechanism for passing parameters. Another way of
3699: thinking about this is to realise that all Forth definitions are
3700: @i{active}; they execute as they are encountered by the text
3701: interpreter. The result of this is that the syntax of Forth is trivially
3702: simple.
1.1 anton 3703:
3704:
3705:
1.29 crook 3706: @comment ----------------------------------------------
3707: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3708: @section Your first Forth definition
3709: @cindex first definition
1.1 anton 3710:
1.29 crook 3711: Until now, the examples we've seen have been trivial; we've just been
3712: using Forth as a bigger-than-pocket calculator. Also, each calculation
3713: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3714: again@footnote{That's not quite true. If you press the up-arrow key on
3715: your keyboard you should be able to scroll back to any earlier command,
3716: edit it and re-enter it.} In this section we'll see how to add new
3717: words to Forth's vocabulary.
1.1 anton 3718:
1.29 crook 3719: The easiest way to create a new word is to use a @dfn{colon
3720: definition}. We'll define a few and try them out before worrying too
3721: much about how they work. Try typing in these examples; be careful to
3722: copy the spaces accurately:
1.1 anton 3723:
1.29 crook 3724: @example
3725: : add-two 2 + . ;
3726: : greet ." Hello and welcome" ;
3727: : demo 5 add-two ;
3728: @end example
1.1 anton 3729:
1.29 crook 3730: @noindent
3731: Now try them out:
1.1 anton 3732:
1.29 crook 3733: @example
1.30 anton 3734: @kbd{greet@key{RET}} Hello and welcome ok
3735: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3736: @kbd{4 add-two@key{RET}} 6 ok
3737: @kbd{demo@key{RET}} 7 ok
3738: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3739: @end example
1.1 anton 3740:
1.29 crook 3741: The first new thing that we've introduced here is the pair of words
3742: @code{:} and @code{;}. These are used to start and terminate a new
3743: definition, respectively. The first word after the @code{:} is the name
3744: for the new definition.
1.1 anton 3745:
1.29 crook 3746: As you can see from the examples, a definition is built up of words that
3747: have already been defined; Forth makes no distinction between
3748: definitions that existed when you started the system up, and those that
3749: you define yourself.
1.1 anton 3750:
1.29 crook 3751: The examples also introduce the words @code{.} (dot), @code{."}
3752: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3753: the stack and displays it. It's like @code{.s} except that it only
3754: displays the top item of the stack and it is destructive; after it has
3755: executed, the number is no longer on the stack. There is always one
3756: space printed after the number, and no spaces before it. Dot-quote
3757: defines a string (a sequence of characters) that will be printed when
3758: the word is executed. The string can contain any printable characters
3759: except @code{"}. A @code{"} has a special function; it is not a Forth
3760: word but it acts as a delimiter (the way that delimiters work is
3761: described in the next section). Finally, @code{dup} duplicates the value
3762: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3763:
1.29 crook 3764: We already know that the text interpreter searches through the
3765: dictionary to locate names. If you've followed the examples earlier, you
3766: will already have a definition called @code{add-two}. Lets try modifying
3767: it by typing in a new definition:
1.1 anton 3768:
1.29 crook 3769: @example
1.30 anton 3770: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3771: @end example
1.5 anton 3772:
1.29 crook 3773: Forth recognised that we were defining a word that already exists, and
3774: printed a message to warn us of that fact. Let's try out the new
3775: definition:
1.5 anton 3776:
1.29 crook 3777: @example
1.30 anton 3778: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3779: @end example
1.1 anton 3780:
1.29 crook 3781: @noindent
3782: All that we've actually done here, though, is to create a new
3783: definition, with a particular name. The fact that there was already a
3784: definition with the same name did not make any difference to the way
3785: that the new definition was created (except that Forth printed a warning
3786: message). The old definition of add-two still exists (try @code{demo}
3787: again to see that this is true). Any new definition will use the new
3788: definition of @code{add-two}, but old definitions continue to use the
3789: version that already existed at the time that they were @code{compiled}.
1.1 anton 3790:
1.29 crook 3791: Before you go on to the next section, try defining and redefining some
3792: words of your own.
1.1 anton 3793:
1.29 crook 3794: @comment ----------------------------------------------
3795: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3796: @section How does that work?
3797: @cindex parsing words
1.1 anton 3798:
1.30 anton 3799: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3800:
3801: @c Is it a good idea to talk about the interpretation semantics of a
3802: @c number? We don't have an xt to go along with it. - anton
3803:
3804: @c Now that I have eliminated execution semantics, I wonder if it would not
3805: @c be better to keep them (or add run-time semantics), to make it easier to
3806: @c explain what compilation semantics usually does. - anton
3807:
1.44 crook 3808: @c nac-> I removed the term ``default compilation sematics'' from the
3809: @c introductory chapter. Removing ``execution semantics'' was making
3810: @c everything simpler to explain, then I think the use of this term made
3811: @c everything more complex again. I replaced it with ``default
3812: @c semantics'' (which is used elsewhere in the manual) by which I mean
3813: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3814: @c flag set''.
3815:
3816: @c anton: I have eliminated default semantics (except in one place where it
3817: @c means "default interpretation and compilation semantics"), because it
3818: @c makes no sense in the presence of combined words. I reverted to
3819: @c "execution semantics" where necessary.
3820:
3821: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3822: @c section (and, unusually for me, I think I even made it shorter!). See
3823: @c what you think -- I know I have not addressed your primary concern
3824: @c that it is too heavy-going for an introduction. From what I understood
3825: @c of your course notes it looks as though they might be a good framework.
3826: @c Things that I've tried to capture here are some things that came as a
3827: @c great revelation here when I first understood them. Also, I like the
3828: @c fact that a very simple code example shows up almost all of the issues
3829: @c that you need to understand to see how Forth works. That's unique and
3830: @c worthwhile to emphasise.
3831:
1.83 anton 3832: @c anton: I think it's a good idea to present the details, especially those
3833: @c that you found to be a revelation, and probably the tutorial tries to be
3834: @c too superficial and does not get some of the things across that make
3835: @c Forth special. I do believe that most of the time these things should
3836: @c be discussed at the end of a section or in separate sections instead of
3837: @c in the middle of a section (e.g., the stuff you added in "User-defined
3838: @c defining words" leads in a completely different direction from the rest
3839: @c of the section).
3840:
1.29 crook 3841: Now we're going to take another look at the definition of @code{add-two}
3842: from the previous section. From our knowledge of the way that the text
3843: interpreter works, we would have expected this result when we tried to
3844: define @code{add-two}:
1.21 crook 3845:
1.29 crook 3846: @example
1.44 crook 3847: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3848: ^^^^^^^
3849: Error: Undefined word
3850: @end example
1.28 crook 3851:
1.29 crook 3852: The reason that this didn't happen is bound up in the way that @code{:}
3853: works. The word @code{:} does two special things. The first special
3854: thing that it does prevents the text interpreter from ever seeing the
3855: characters @code{add-two}. The text interpreter uses a variable called
3856: @cindex modifying >IN
1.44 crook 3857: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3858: input line. When it encounters the word @code{:} it behaves in exactly
3859: the same way as it does for any other word; it looks it up in the name
3860: dictionary, finds its xt and executes it. When @code{:} executes, it
3861: looks at the input buffer, finds the word @code{add-two} and advances the
3862: value of @code{>IN} to point past it. It then does some other stuff
3863: associated with creating the new definition (including creating an entry
3864: for @code{add-two} in the name dictionary). When the execution of @code{:}
3865: completes, control returns to the text interpreter, which is oblivious
3866: to the fact that it has been tricked into ignoring part of the input
3867: line.
1.21 crook 3868:
1.29 crook 3869: @cindex parsing words
3870: Words like @code{:} -- words that advance the value of @code{>IN} and so
3871: prevent the text interpreter from acting on the whole of the input line
3872: -- are called @dfn{parsing words}.
1.21 crook 3873:
1.29 crook 3874: @cindex @code{state} - effect on the text interpreter
3875: @cindex text interpreter - effect of state
3876: The second special thing that @code{:} does is change the value of a
3877: variable called @code{state}, which affects the way that the text
3878: interpreter behaves. When Gforth starts up, @code{state} has the value
3879: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3880: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3881: the text interpreter is said to be @dfn{compiling}.
3882:
3883: In this example, the text interpreter is compiling when it processes the
3884: string ``@code{2 + . ;}''. It still breaks the string down into
3885: character sequences in the same way. However, instead of pushing the
3886: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3887: into the definition of @code{add-two} that will make the number @code{2} get
3888: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3889: the behaviours of @code{+} and @code{.} are also compiled into the
3890: definition.
3891:
3892: One category of words don't get compiled. These so-called @dfn{immediate
3893: words} get executed (performed @i{now}) regardless of whether the text
3894: interpreter is interpreting or compiling. The word @code{;} is an
3895: immediate word. Rather than being compiled into the definition, it
3896: executes. Its effect is to terminate the current definition, which
3897: includes changing the value of @code{state} back to 0.
3898:
3899: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3900: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3901: definition.
1.28 crook 3902:
1.30 anton 3903: In Forth, every word or number can be described in terms of two
1.29 crook 3904: properties:
1.28 crook 3905:
3906: @itemize @bullet
3907: @item
1.29 crook 3908: @cindex interpretation semantics
1.44 crook 3909: Its @dfn{interpretation semantics} describe how it will behave when the
3910: text interpreter encounters it in @dfn{interpret} state. The
3911: interpretation semantics of a word are represented by an @dfn{execution
3912: token}.
1.28 crook 3913: @item
1.29 crook 3914: @cindex compilation semantics
1.44 crook 3915: Its @dfn{compilation semantics} describe how it will behave when the
3916: text interpreter encounters it in @dfn{compile} state. The compilation
3917: semantics of a word are represented in an implementation-dependent way;
3918: Gforth uses a @dfn{compilation token}.
1.29 crook 3919: @end itemize
3920:
3921: @noindent
3922: Numbers are always treated in a fixed way:
3923:
3924: @itemize @bullet
1.28 crook 3925: @item
1.44 crook 3926: When the number is @dfn{interpreted}, its behaviour is to push the
3927: number onto the stack.
1.28 crook 3928: @item
1.30 anton 3929: When the number is @dfn{compiled}, a piece of code is appended to the
3930: current definition that pushes the number when it runs. (In other words,
3931: the compilation semantics of a number are to postpone its interpretation
3932: semantics until the run-time of the definition that it is being compiled
3933: into.)
1.29 crook 3934: @end itemize
3935:
1.44 crook 3936: Words don't behave in such a regular way, but most have @i{default
3937: semantics} which means that they behave like this:
1.29 crook 3938:
3939: @itemize @bullet
1.28 crook 3940: @item
1.30 anton 3941: The @dfn{interpretation semantics} of the word are to do something useful.
3942: @item
1.29 crook 3943: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3944: @dfn{interpretation semantics} to the current definition (so that its
3945: run-time behaviour is to do something useful).
1.28 crook 3946: @end itemize
3947:
1.30 anton 3948: @cindex immediate words
1.44 crook 3949: The actual behaviour of any particular word can be controlled by using
3950: the words @code{immediate} and @code{compile-only} when the word is
3951: defined. These words set flags in the name dictionary entry of the most
3952: recently defined word, and these flags are retrieved by the text
3953: interpreter when it finds the word in the name dictionary.
3954:
3955: A word that is marked as @dfn{immediate} has compilation semantics that
3956: are identical to its interpretation semantics. In other words, it
3957: behaves like this:
1.29 crook 3958:
3959: @itemize @bullet
3960: @item
1.30 anton 3961: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3962: @item
1.30 anton 3963: The @dfn{compilation semantics} of the word are to do something useful
3964: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3965: @end itemize
1.28 crook 3966:
1.44 crook 3967: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3968: performing the interpretation semantics of the word directly; an attempt
3969: to do so will generate an error. It is never necessary to use
3970: @code{compile-only} (and it is not even part of ANS Forth, though it is
3971: provided by many implementations) but it is good etiquette to apply it
3972: to a word that will not behave correctly (and might have unexpected
3973: side-effects) in interpret state. For example, it is only legal to use
3974: the conditional word @code{IF} within a definition. If you forget this
3975: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3976: @code{compile-only} allows the text interpreter to generate a helpful
3977: error message rather than subjecting you to the consequences of your
3978: folly.
3979:
1.29 crook 3980: This example shows the difference between an immediate and a
3981: non-immediate word:
1.28 crook 3982:
1.29 crook 3983: @example
3984: : show-state state @@ . ;
3985: : show-state-now show-state ; immediate
3986: : word1 show-state ;
3987: : word2 show-state-now ;
1.28 crook 3988: @end example
1.23 crook 3989:
1.29 crook 3990: The word @code{immediate} after the definition of @code{show-state-now}
3991: makes that word an immediate word. These definitions introduce a new
3992: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
3993: variable, and leaves it on the stack. Therefore, the behaviour of
3994: @code{show-state} is to print a number that represents the current value
3995: of @code{state}.
1.28 crook 3996:
1.29 crook 3997: When you execute @code{word1}, it prints the number 0, indicating that
3998: the system is interpreting. When the text interpreter compiled the
3999: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4000: compilation semantics are to append its interpretation semantics to the
1.29 crook 4001: current definition. When you execute @code{word1}, it performs the
1.30 anton 4002: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4003: (and therefore @code{show-state}) are executed, the system is
4004: interpreting.
1.28 crook 4005:
1.30 anton 4006: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4007: you should have seen the number -1 printed, followed by ``@code{
4008: ok}''. When the text interpreter compiled the definition of
4009: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4010: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4011: semantics. It is executed straight away (even before the text
4012: interpreter has moved on to process another group of characters; the
4013: @code{;} in this example). The effect of executing it are to display the
4014: value of @code{state} @i{at the time that the definition of}
4015: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4016: system is compiling at this time. If you execute @code{word2} it does
4017: nothing at all.
1.28 crook 4018:
1.29 crook 4019: @cindex @code{."}, how it works
4020: Before leaving the subject of immediate words, consider the behaviour of
4021: @code{."} in the definition of @code{greet}, in the previous
4022: section. This word is both a parsing word and an immediate word. Notice
4023: that there is a space between @code{."} and the start of the text
4024: @code{Hello and welcome}, but that there is no space between the last
4025: letter of @code{welcome} and the @code{"} character. The reason for this
4026: is that @code{."} is a Forth word; it must have a space after it so that
4027: the text interpreter can identify it. The @code{"} is not a Forth word;
4028: it is a @dfn{delimiter}. The examples earlier show that, when the string
4029: is displayed, there is neither a space before the @code{H} nor after the
4030: @code{e}. Since @code{."} is an immediate word, it executes at the time
4031: that @code{greet} is defined. When it executes, its behaviour is to
4032: search forward in the input line looking for the delimiter. When it
4033: finds the delimiter, it updates @code{>IN} to point past the
4034: delimiter. It also compiles some magic code into the definition of
4035: @code{greet}; the xt of a run-time routine that prints a text string. It
4036: compiles the string @code{Hello and welcome} into memory so that it is
4037: available to be printed later. When the text interpreter gains control,
4038: the next word it finds in the input stream is @code{;} and so it
4039: terminates the definition of @code{greet}.
1.28 crook 4040:
4041:
4042: @comment ----------------------------------------------
1.29 crook 4043: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4044: @section Forth is written in Forth
4045: @cindex structure of Forth programs
4046:
4047: When you start up a Forth compiler, a large number of definitions
4048: already exist. In Forth, you develop a new application using bottom-up
4049: programming techniques to create new definitions that are defined in
4050: terms of existing definitions. As you create each definition you can
4051: test and debug it interactively.
4052:
4053: If you have tried out the examples in this section, you will probably
4054: have typed them in by hand; when you leave Gforth, your definitions will
4055: be lost. You can avoid this by using a text editor to enter Forth source
4056: code into a file, and then loading code from the file using
1.49 anton 4057: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4058: processed by the text interpreter, just as though you had typed it in by
4059: hand@footnote{Actually, there are some subtle differences -- see
4060: @ref{The Text Interpreter}.}.
4061:
4062: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4063: files for program entry (@pxref{Blocks}).
1.28 crook 4064:
1.29 crook 4065: In common with many, if not most, Forth compilers, most of Gforth is
4066: actually written in Forth. All of the @file{.fs} files in the
4067: installation directory@footnote{For example,
1.30 anton 4068: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4069: study to see examples of Forth programming.
1.28 crook 4070:
1.29 crook 4071: Gforth maintains a history file that records every line that you type to
4072: the text interpreter. This file is preserved between sessions, and is
4073: used to provide a command-line recall facility. If you enter long
4074: definitions by hand, you can use a text editor to paste them out of the
4075: history file into a Forth source file for reuse at a later time
1.49 anton 4076: (for more information @pxref{Command-line editing}).
1.28 crook 4077:
4078:
4079: @comment ----------------------------------------------
1.29 crook 4080: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4081: @section Review - elements of a Forth system
4082: @cindex elements of a Forth system
1.28 crook 4083:
1.29 crook 4084: To summarise this chapter:
1.28 crook 4085:
4086: @itemize @bullet
4087: @item
1.29 crook 4088: Forth programs use @dfn{factoring} to break a problem down into small
4089: fragments called @dfn{words} or @dfn{definitions}.
4090: @item
4091: Forth program development is an interactive process.
4092: @item
4093: The main command loop that accepts input, and controls both
4094: interpretation and compilation, is called the @dfn{text interpreter}
4095: (also known as the @dfn{outer interpreter}).
4096: @item
4097: Forth has a very simple syntax, consisting of words and numbers
4098: separated by spaces or carriage-return characters. Any additional syntax
4099: is imposed by @dfn{parsing words}.
4100: @item
4101: Forth uses a stack to pass parameters between words. As a result, it
4102: uses postfix notation.
4103: @item
4104: To use a word that has previously been defined, the text interpreter
4105: searches for the word in the @dfn{name dictionary}.
4106: @item
1.30 anton 4107: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4108: @item
1.29 crook 4109: The text interpreter uses the value of @code{state} to select between
4110: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4111: semantics} of a word that it encounters.
1.28 crook 4112: @item
1.30 anton 4113: The relationship between the @dfn{interpretation semantics} and
4114: @dfn{compilation semantics} for a word
1.29 crook 4115: depend upon the way in which the word was defined (for example, whether
4116: it is an @dfn{immediate} word).
1.28 crook 4117: @item
1.29 crook 4118: Forth definitions can be implemented in Forth (called @dfn{high-level
4119: definitions}) or in some other way (usually a lower-level language and
4120: as a result often called @dfn{low-level definitions}, @dfn{code
4121: definitions} or @dfn{primitives}).
1.28 crook 4122: @item
1.29 crook 4123: Many Forth systems are implemented mainly in Forth.
1.28 crook 4124: @end itemize
4125:
4126:
1.29 crook 4127: @comment ----------------------------------------------
1.48 anton 4128: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4129: @section Where To Go Next
4130: @cindex where to go next
1.28 crook 4131:
1.29 crook 4132: Amazing as it may seem, if you have read (and understood) this far, you
4133: know almost all the fundamentals about the inner workings of a Forth
4134: system. You certainly know enough to be able to read and understand the
4135: rest of this manual and the ANS Forth document, to learn more about the
4136: facilities that Forth in general and Gforth in particular provide. Even
4137: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4138: However, that's not a good idea just yet... better to try writing some
1.29 crook 4139: programs in Gforth.
1.28 crook 4140:
1.29 crook 4141: Forth has such a rich vocabulary that it can be hard to know where to
4142: start in learning it. This section suggests a few sets of words that are
4143: enough to write small but useful programs. Use the word index in this
4144: document to learn more about each word, then try it out and try to write
4145: small definitions using it. Start by experimenting with these words:
1.28 crook 4146:
4147: @itemize @bullet
4148: @item
1.29 crook 4149: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4150: @item
4151: Comparison: @code{MIN MAX =}
4152: @item
4153: Logic: @code{AND OR XOR NOT}
4154: @item
4155: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4156: @item
1.29 crook 4157: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4158: @item
1.29 crook 4159: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4160: @item
1.29 crook 4161: Defining words: @code{: ; CREATE}
1.28 crook 4162: @item
1.29 crook 4163: Memory allocation words: @code{ALLOT ,}
1.28 crook 4164: @item
1.29 crook 4165: Tools: @code{SEE WORDS .S MARKER}
4166: @end itemize
4167:
4168: When you have mastered those, go on to:
4169:
4170: @itemize @bullet
1.28 crook 4171: @item
1.29 crook 4172: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4173: @item
1.29 crook 4174: Memory access: @code{@@ !}
1.28 crook 4175: @end itemize
1.23 crook 4176:
1.29 crook 4177: When you have mastered these, there's nothing for it but to read through
4178: the whole of this manual and find out what you've missed.
4179:
4180: @comment ----------------------------------------------
1.48 anton 4181: @node Exercises, , Where to go next, Introduction
1.29 crook 4182: @section Exercises
4183: @cindex exercises
4184:
4185: TODO: provide a set of programming excercises linked into the stuff done
4186: already and into other sections of the manual. Provide solutions to all
4187: the exercises in a .fs file in the distribution.
4188:
4189: @c Get some inspiration from Starting Forth and Kelly&Spies.
4190:
4191: @c excercises:
4192: @c 1. take inches and convert to feet and inches.
4193: @c 2. take temperature and convert from fahrenheight to celcius;
4194: @c may need to care about symmetric vs floored??
4195: @c 3. take input line and do character substitution
4196: @c to encipher or decipher
4197: @c 4. as above but work on a file for in and out
4198: @c 5. take input line and convert to pig-latin
4199: @c
4200: @c thing of sets of things to exercise then come up with
4201: @c problems that need those things.
4202:
4203:
1.26 crook 4204: @c ******************************************************************
1.29 crook 4205: @node Words, Error messages, Introduction, Top
1.1 anton 4206: @chapter Forth Words
1.26 crook 4207: @cindex words
1.1 anton 4208:
4209: @menu
4210: * Notation::
1.65 anton 4211: * Case insensitivity::
4212: * Comments::
4213: * Boolean Flags::
1.1 anton 4214: * Arithmetic::
4215: * Stack Manipulation::
1.5 anton 4216: * Memory::
1.1 anton 4217: * Control Structures::
4218: * Defining Words::
1.65 anton 4219: * Interpretation and Compilation Semantics::
1.47 crook 4220: * Tokens for Words::
1.81 anton 4221: * Compiling words::
1.65 anton 4222: * The Text Interpreter::
1.111 anton 4223: * The Input Stream::
1.65 anton 4224: * Word Lists::
4225: * Environmental Queries::
1.12 anton 4226: * Files::
4227: * Blocks::
4228: * Other I/O::
1.121 anton 4229: * OS command line arguments::
1.78 anton 4230: * Locals::
4231: * Structures::
4232: * Object-oriented Forth::
1.12 anton 4233: * Programming Tools::
4234: * Assembler and Code Words::
4235: * Threading Words::
1.65 anton 4236: * Passing Commands to the OS::
4237: * Keeping track of Time::
4238: * Miscellaneous Words::
1.1 anton 4239: @end menu
4240:
1.65 anton 4241: @node Notation, Case insensitivity, Words, Words
1.1 anton 4242: @section Notation
4243: @cindex notation of glossary entries
4244: @cindex format of glossary entries
4245: @cindex glossary notation format
4246: @cindex word glossary entry format
4247:
4248: The Forth words are described in this section in the glossary notation
1.67 anton 4249: that has become a de-facto standard for Forth texts:
1.1 anton 4250:
4251: @format
1.29 crook 4252: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4253: @end format
1.29 crook 4254: @i{Description}
1.1 anton 4255:
4256: @table @var
4257: @item word
1.28 crook 4258: The name of the word.
1.1 anton 4259:
4260: @item Stack effect
4261: @cindex stack effect
1.29 crook 4262: The stack effect is written in the notation @code{@i{before} --
4263: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4264: stack entries before and after the execution of the word. The rest of
4265: the stack is not touched by the word. The top of stack is rightmost,
4266: i.e., a stack sequence is written as it is typed in. Note that Gforth
4267: uses a separate floating point stack, but a unified stack
1.29 crook 4268: notation. Also, return stack effects are not shown in @i{stack
4269: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4270: the type and/or the function of the item. See below for a discussion of
4271: the types.
4272:
4273: All words have two stack effects: A compile-time stack effect and a
4274: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4275: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4276: this standard behaviour, or the word does other unusual things at
4277: compile time, both stack effects are shown; otherwise only the run-time
4278: stack effect is shown.
4279:
4280: @cindex pronounciation of words
4281: @item pronunciation
4282: How the word is pronounced.
4283:
4284: @cindex wordset
1.67 anton 4285: @cindex environment wordset
1.1 anton 4286: @item wordset
1.21 crook 4287: The ANS Forth standard is divided into several word sets. A standard
4288: system need not support all of them. Therefore, in theory, the fewer
4289: word sets your program uses the more portable it will be. However, we
4290: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4291: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4292: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4293: describes words that will work in future releases of Gforth;
4294: @code{gforth-internal} words are more volatile. Environmental query
4295: strings are also displayed like words; you can recognize them by the
1.21 crook 4296: @code{environment} in the word set field.
1.1 anton 4297:
4298: @item Description
4299: A description of the behaviour of the word.
4300: @end table
4301:
4302: @cindex types of stack items
4303: @cindex stack item types
4304: The type of a stack item is specified by the character(s) the name
4305: starts with:
4306:
4307: @table @code
4308: @item f
4309: @cindex @code{f}, stack item type
4310: Boolean flags, i.e. @code{false} or @code{true}.
4311: @item c
4312: @cindex @code{c}, stack item type
4313: Char
4314: @item w
4315: @cindex @code{w}, stack item type
4316: Cell, can contain an integer or an address
4317: @item n
4318: @cindex @code{n}, stack item type
4319: signed integer
4320: @item u
4321: @cindex @code{u}, stack item type
4322: unsigned integer
4323: @item d
4324: @cindex @code{d}, stack item type
4325: double sized signed integer
4326: @item ud
4327: @cindex @code{ud}, stack item type
4328: double sized unsigned integer
4329: @item r
4330: @cindex @code{r}, stack item type
4331: Float (on the FP stack)
1.21 crook 4332: @item a-
1.1 anton 4333: @cindex @code{a_}, stack item type
4334: Cell-aligned address
1.21 crook 4335: @item c-
1.1 anton 4336: @cindex @code{c_}, stack item type
4337: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4338: @item f-
1.1 anton 4339: @cindex @code{f_}, stack item type
4340: Float-aligned address
1.21 crook 4341: @item df-
1.1 anton 4342: @cindex @code{df_}, stack item type
4343: Address aligned for IEEE double precision float
1.21 crook 4344: @item sf-
1.1 anton 4345: @cindex @code{sf_}, stack item type
4346: Address aligned for IEEE single precision float
4347: @item xt
4348: @cindex @code{xt}, stack item type
4349: Execution token, same size as Cell
4350: @item wid
4351: @cindex @code{wid}, stack item type
1.21 crook 4352: Word list ID, same size as Cell
1.68 anton 4353: @item ior, wior
4354: @cindex ior type description
4355: @cindex wior type description
4356: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4357: @item f83name
4358: @cindex @code{f83name}, stack item type
4359: Pointer to a name structure
4360: @item "
4361: @cindex @code{"}, stack item type
1.12 anton 4362: string in the input stream (not on the stack). The terminating character
4363: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4364: quotes.
4365: @end table
4366:
1.65 anton 4367: @comment ----------------------------------------------
4368: @node Case insensitivity, Comments, Notation, Words
4369: @section Case insensitivity
4370: @cindex case sensitivity
4371: @cindex upper and lower case
4372:
4373: Gforth is case-insensitive; you can enter definitions and invoke
4374: Standard words using upper, lower or mixed case (however,
4375: @pxref{core-idef, Implementation-defined options, Implementation-defined
4376: options}).
4377:
4378: ANS Forth only @i{requires} implementations to recognise Standard words
4379: when they are typed entirely in upper case. Therefore, a Standard
4380: program must use upper case for all Standard words. You can use whatever
4381: case you like for words that you define, but in a Standard program you
4382: have to use the words in the same case that you defined them.
4383:
4384: Gforth supports case sensitivity through @code{table}s (case-sensitive
4385: wordlists, @pxref{Word Lists}).
4386:
4387: Two people have asked how to convert Gforth to be case-sensitive; while
4388: we think this is a bad idea, you can change all wordlists into tables
4389: like this:
4390:
4391: @example
4392: ' table-find forth-wordlist wordlist-map @ !
4393: @end example
4394:
4395: Note that you now have to type the predefined words in the same case
4396: that we defined them, which are varying. You may want to convert them
4397: to your favourite case before doing this operation (I won't explain how,
4398: because if you are even contemplating doing this, you'd better have
4399: enough knowledge of Forth systems to know this already).
4400:
4401: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4402: @section Comments
1.26 crook 4403: @cindex comments
1.21 crook 4404:
1.29 crook 4405: Forth supports two styles of comment; the traditional @i{in-line} comment,
4406: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4407:
1.44 crook 4408:
1.23 crook 4409: doc-(
1.21 crook 4410: doc-\
1.23 crook 4411: doc-\G
1.21 crook 4412:
1.44 crook 4413:
1.21 crook 4414: @node Boolean Flags, Arithmetic, Comments, Words
4415: @section Boolean Flags
1.26 crook 4416: @cindex Boolean flags
1.21 crook 4417:
4418: A Boolean flag is cell-sized. A cell with all bits clear represents the
4419: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4420: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4421: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4422: @c on and off to Memory?
4423: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4424:
1.21 crook 4425: doc-true
4426: doc-false
1.29 crook 4427: doc-on
4428: doc-off
1.21 crook 4429:
1.44 crook 4430:
1.21 crook 4431: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4432: @section Arithmetic
4433: @cindex arithmetic words
4434:
4435: @cindex division with potentially negative operands
4436: Forth arithmetic is not checked, i.e., you will not hear about integer
4437: overflow on addition or multiplication, you may hear about division by
4438: zero if you are lucky. The operator is written after the operands, but
4439: the operands are still in the original order. I.e., the infix @code{2-1}
4440: corresponds to @code{2 1 -}. Forth offers a variety of division
4441: operators. If you perform division with potentially negative operands,
4442: you do not want to use @code{/} or @code{/mod} with its undefined
4443: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4444: former, @pxref{Mixed precision}).
1.26 crook 4445: @comment TODO discuss the different division forms and the std approach
1.1 anton 4446:
4447: @menu
4448: * Single precision::
1.67 anton 4449: * Double precision:: Double-cell integer arithmetic
1.1 anton 4450: * Bitwise operations::
1.67 anton 4451: * Numeric comparison::
1.29 crook 4452: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4453: * Floating Point::
4454: @end menu
4455:
1.67 anton 4456: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4457: @subsection Single precision
4458: @cindex single precision arithmetic words
4459:
1.67 anton 4460: @c !! cell undefined
4461:
4462: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4463: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4464: treat them. For the rules used by the text interpreter for recognising
4465: single-precision integers see @ref{Number Conversion}.
1.21 crook 4466:
1.67 anton 4467: These words are all defined for signed operands, but some of them also
4468: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4469: @code{*}.
1.44 crook 4470:
1.1 anton 4471: doc-+
1.21 crook 4472: doc-1+
1.128 anton 4473: doc-under+
1.1 anton 4474: doc--
1.21 crook 4475: doc-1-
1.1 anton 4476: doc-*
4477: doc-/
4478: doc-mod
4479: doc-/mod
4480: doc-negate
4481: doc-abs
4482: doc-min
4483: doc-max
1.27 crook 4484: doc-floored
1.1 anton 4485:
1.44 crook 4486:
1.67 anton 4487: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4488: @subsection Double precision
4489: @cindex double precision arithmetic words
4490:
1.49 anton 4491: For the rules used by the text interpreter for
4492: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4493:
4494: A double precision number is represented by a cell pair, with the most
1.67 anton 4495: significant cell at the TOS. It is trivial to convert an unsigned single
4496: to a double: simply push a @code{0} onto the TOS. Since numbers are
4497: represented by Gforth using 2's complement arithmetic, converting a
4498: signed single to a (signed) double requires sign-extension across the
4499: most significant cell. This can be achieved using @code{s>d}. The moral
4500: of the story is that you cannot convert a number without knowing whether
4501: it represents an unsigned or a signed number.
1.21 crook 4502:
1.67 anton 4503: These words are all defined for signed operands, but some of them also
4504: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4505:
1.21 crook 4506: doc-s>d
1.67 anton 4507: doc-d>s
1.21 crook 4508: doc-d+
4509: doc-d-
4510: doc-dnegate
4511: doc-dabs
4512: doc-dmin
4513: doc-dmax
4514:
1.44 crook 4515:
1.67 anton 4516: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4517: @subsection Bitwise operations
4518: @cindex bitwise operation words
4519:
4520:
4521: doc-and
4522: doc-or
4523: doc-xor
4524: doc-invert
4525: doc-lshift
4526: doc-rshift
4527: doc-2*
4528: doc-d2*
4529: doc-2/
4530: doc-d2/
4531:
4532:
4533: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4534: @subsection Numeric comparison
4535: @cindex numeric comparison words
4536:
1.67 anton 4537: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4538: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4539:
1.28 crook 4540: doc-<
4541: doc-<=
4542: doc-<>
4543: doc-=
4544: doc->
4545: doc->=
4546:
1.21 crook 4547: doc-0<
1.23 crook 4548: doc-0<=
1.21 crook 4549: doc-0<>
4550: doc-0=
1.23 crook 4551: doc-0>
4552: doc-0>=
1.28 crook 4553:
4554: doc-u<
4555: doc-u<=
1.44 crook 4556: @c u<> and u= exist but are the same as <> and =
1.31 anton 4557: @c doc-u<>
4558: @c doc-u=
1.28 crook 4559: doc-u>
4560: doc-u>=
4561:
4562: doc-within
4563:
4564: doc-d<
4565: doc-d<=
4566: doc-d<>
4567: doc-d=
4568: doc-d>
4569: doc-d>=
1.23 crook 4570:
1.21 crook 4571: doc-d0<
1.23 crook 4572: doc-d0<=
4573: doc-d0<>
1.21 crook 4574: doc-d0=
1.23 crook 4575: doc-d0>
4576: doc-d0>=
4577:
1.21 crook 4578: doc-du<
1.28 crook 4579: doc-du<=
1.44 crook 4580: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4581: @c doc-du<>
4582: @c doc-du=
1.28 crook 4583: doc-du>
4584: doc-du>=
1.1 anton 4585:
1.44 crook 4586:
1.21 crook 4587: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4588: @subsection Mixed precision
4589: @cindex mixed precision arithmetic words
4590:
1.44 crook 4591:
1.1 anton 4592: doc-m+
4593: doc-*/
4594: doc-*/mod
4595: doc-m*
4596: doc-um*
4597: doc-m*/
4598: doc-um/mod
4599: doc-fm/mod
4600: doc-sm/rem
4601:
1.44 crook 4602:
1.21 crook 4603: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4604: @subsection Floating Point
4605: @cindex floating point arithmetic words
4606:
1.49 anton 4607: For the rules used by the text interpreter for
4608: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4609:
1.67 anton 4610: Gforth has a separate floating point stack, but the documentation uses
4611: the unified notation.@footnote{It's easy to generate the separate
4612: notation from that by just separating the floating-point numbers out:
4613: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4614: r3 )}.}
1.1 anton 4615:
4616: @cindex floating-point arithmetic, pitfalls
4617: Floating point numbers have a number of unpleasant surprises for the
4618: unwary (e.g., floating point addition is not associative) and even a few
4619: for the wary. You should not use them unless you know what you are doing
4620: or you don't care that the results you get are totally bogus. If you
4621: want to learn about the problems of floating point numbers (and how to
1.66 anton 4622: avoid them), you might start with @cite{David Goldberg,
4623: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4624: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4625: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4626:
1.44 crook 4627:
1.21 crook 4628: doc-d>f
4629: doc-f>d
1.1 anton 4630: doc-f+
4631: doc-f-
4632: doc-f*
4633: doc-f/
4634: doc-fnegate
4635: doc-fabs
4636: doc-fmax
4637: doc-fmin
4638: doc-floor
4639: doc-fround
4640: doc-f**
4641: doc-fsqrt
4642: doc-fexp
4643: doc-fexpm1
4644: doc-fln
4645: doc-flnp1
4646: doc-flog
4647: doc-falog
1.32 anton 4648: doc-f2*
4649: doc-f2/
4650: doc-1/f
4651: doc-precision
4652: doc-set-precision
4653:
4654: @cindex angles in trigonometric operations
4655: @cindex trigonometric operations
4656: Angles in floating point operations are given in radians (a full circle
4657: has 2 pi radians).
4658:
1.1 anton 4659: doc-fsin
4660: doc-fcos
4661: doc-fsincos
4662: doc-ftan
4663: doc-fasin
4664: doc-facos
4665: doc-fatan
4666: doc-fatan2
4667: doc-fsinh
4668: doc-fcosh
4669: doc-ftanh
4670: doc-fasinh
4671: doc-facosh
4672: doc-fatanh
1.21 crook 4673: doc-pi
1.28 crook 4674:
1.32 anton 4675: @cindex equality of floats
4676: @cindex floating-point comparisons
1.31 anton 4677: One particular problem with floating-point arithmetic is that comparison
4678: for equality often fails when you would expect it to succeed. For this
4679: reason approximate equality is often preferred (but you still have to
1.67 anton 4680: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4681: differently from what you might expect. The comparison words are:
1.31 anton 4682:
4683: doc-f~rel
4684: doc-f~abs
1.68 anton 4685: doc-f~
1.31 anton 4686: doc-f=
4687: doc-f<>
4688:
4689: doc-f<
4690: doc-f<=
4691: doc-f>
4692: doc-f>=
4693:
1.21 crook 4694: doc-f0<
1.28 crook 4695: doc-f0<=
4696: doc-f0<>
1.21 crook 4697: doc-f0=
1.28 crook 4698: doc-f0>
4699: doc-f0>=
4700:
1.1 anton 4701:
4702: @node Stack Manipulation, Memory, Arithmetic, Words
4703: @section Stack Manipulation
4704: @cindex stack manipulation words
4705:
4706: @cindex floating-point stack in the standard
1.21 crook 4707: Gforth maintains a number of separate stacks:
4708:
1.29 crook 4709: @cindex data stack
4710: @cindex parameter stack
1.21 crook 4711: @itemize @bullet
4712: @item
1.29 crook 4713: A data stack (also known as the @dfn{parameter stack}) -- for
4714: characters, cells, addresses, and double cells.
1.21 crook 4715:
1.29 crook 4716: @cindex floating-point stack
1.21 crook 4717: @item
1.44 crook 4718: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4719:
1.29 crook 4720: @cindex return stack
1.21 crook 4721: @item
1.44 crook 4722: A return stack -- for holding the return addresses of colon
1.32 anton 4723: definitions and other (non-FP) data.
1.21 crook 4724:
1.29 crook 4725: @cindex locals stack
1.21 crook 4726: @item
1.44 crook 4727: A locals stack -- for holding local variables.
1.21 crook 4728: @end itemize
4729:
1.1 anton 4730: @menu
4731: * Data stack::
4732: * Floating point stack::
4733: * Return stack::
4734: * Locals stack::
4735: * Stack pointer manipulation::
4736: @end menu
4737:
4738: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4739: @subsection Data stack
4740: @cindex data stack manipulation words
4741: @cindex stack manipulations words, data stack
4742:
1.44 crook 4743:
1.1 anton 4744: doc-drop
4745: doc-nip
4746: doc-dup
4747: doc-over
4748: doc-tuck
4749: doc-swap
1.21 crook 4750: doc-pick
1.1 anton 4751: doc-rot
4752: doc--rot
4753: doc-?dup
4754: doc-roll
4755: doc-2drop
4756: doc-2nip
4757: doc-2dup
4758: doc-2over
4759: doc-2tuck
4760: doc-2swap
4761: doc-2rot
4762:
1.44 crook 4763:
1.1 anton 4764: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4765: @subsection Floating point stack
4766: @cindex floating-point stack manipulation words
4767: @cindex stack manipulation words, floating-point stack
4768:
1.32 anton 4769: Whilst every sane Forth has a separate floating-point stack, it is not
4770: strictly required; an ANS Forth system could theoretically keep
4771: floating-point numbers on the data stack. As an additional difficulty,
4772: you don't know how many cells a floating-point number takes. It is
4773: reportedly possible to write words in a way that they work also for a
4774: unified stack model, but we do not recommend trying it. Instead, just
4775: say that your program has an environmental dependency on a separate
4776: floating-point stack.
4777:
4778: doc-floating-stack
4779:
1.1 anton 4780: doc-fdrop
4781: doc-fnip
4782: doc-fdup
4783: doc-fover
4784: doc-ftuck
4785: doc-fswap
1.21 crook 4786: doc-fpick
1.1 anton 4787: doc-frot
4788:
1.44 crook 4789:
1.1 anton 4790: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4791: @subsection Return stack
4792: @cindex return stack manipulation words
4793: @cindex stack manipulation words, return stack
4794:
1.32 anton 4795: @cindex return stack and locals
4796: @cindex locals and return stack
4797: A Forth system is allowed to keep local variables on the
4798: return stack. This is reasonable, as local variables usually eliminate
4799: the need to use the return stack explicitly. So, if you want to produce
4800: a standard compliant program and you are using local variables in a
4801: word, forget about return stack manipulations in that word (refer to the
4802: standard document for the exact rules).
4803:
1.1 anton 4804: doc->r
4805: doc-r>
4806: doc-r@
4807: doc-rdrop
4808: doc-2>r
4809: doc-2r>
4810: doc-2r@
4811: doc-2rdrop
4812:
1.44 crook 4813:
1.1 anton 4814: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4815: @subsection Locals stack
4816:
1.78 anton 4817: Gforth uses an extra locals stack. It is described, along with the
4818: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4819:
1.1 anton 4820: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4821: @subsection Stack pointer manipulation
4822: @cindex stack pointer manipulation words
4823:
1.44 crook 4824: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4825: doc-sp0
1.1 anton 4826: doc-sp@
4827: doc-sp!
1.21 crook 4828: doc-fp0
1.1 anton 4829: doc-fp@
4830: doc-fp!
1.21 crook 4831: doc-rp0
1.1 anton 4832: doc-rp@
4833: doc-rp!
1.21 crook 4834: doc-lp0
1.1 anton 4835: doc-lp@
4836: doc-lp!
4837:
1.44 crook 4838:
1.1 anton 4839: @node Memory, Control Structures, Stack Manipulation, Words
4840: @section Memory
1.26 crook 4841: @cindex memory words
1.1 anton 4842:
1.32 anton 4843: @menu
4844: * Memory model::
4845: * Dictionary allocation::
4846: * Heap Allocation::
4847: * Memory Access::
4848: * Address arithmetic::
4849: * Memory Blocks::
4850: @end menu
4851:
1.67 anton 4852: In addition to the standard Forth memory allocation words, there is also
4853: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4854: garbage collector}.
4855:
1.32 anton 4856: @node Memory model, Dictionary allocation, Memory, Memory
4857: @subsection ANS Forth and Gforth memory models
4858:
4859: @c The ANS Forth description is a mess (e.g., is the heap part of
4860: @c the dictionary?), so let's not stick to closely with it.
4861:
1.67 anton 4862: ANS Forth considers a Forth system as consisting of several address
4863: spaces, of which only @dfn{data space} is managed and accessible with
4864: the memory words. Memory not necessarily in data space includes the
4865: stacks, the code (called code space) and the headers (called name
4866: space). In Gforth everything is in data space, but the code for the
4867: primitives is usually read-only.
1.32 anton 4868:
4869: Data space is divided into a number of areas: The (data space portion of
4870: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4871: refer to the search data structure embodied in word lists and headers,
4872: because it is used for looking up names, just as you would in a
4873: conventional dictionary.}, the heap, and a number of system-allocated
4874: buffers.
4875:
1.68 anton 4876: @cindex address arithmetic restrictions, ANS vs. Gforth
4877: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4878: In ANS Forth data space is also divided into contiguous regions. You
4879: can only use address arithmetic within a contiguous region, not between
4880: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4881: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4882: allocation}).
4883:
4884: Gforth provides one big address space, and address arithmetic can be
4885: performed between any addresses. However, in the dictionary headers or
4886: code are interleaved with data, so almost the only contiguous data space
4887: regions there are those described by ANS Forth as contiguous; but you
4888: can be sure that the dictionary is allocated towards increasing
4889: addresses even between contiguous regions. The memory order of
4890: allocations in the heap is platform-dependent (and possibly different
4891: from one run to the next).
4892:
1.27 crook 4893:
1.32 anton 4894: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4895: @subsection Dictionary allocation
1.27 crook 4896: @cindex reserving data space
4897: @cindex data space - reserving some
4898:
1.32 anton 4899: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4900: you want to deallocate X, you also deallocate everything
4901: allocated after X.
4902:
1.68 anton 4903: @cindex contiguous regions in dictionary allocation
1.32 anton 4904: The allocations using the words below are contiguous and grow the region
4905: towards increasing addresses. Other words that allocate dictionary
4906: memory of any kind (i.e., defining words including @code{:noname}) end
4907: the contiguous region and start a new one.
4908:
4909: In ANS Forth only @code{create}d words are guaranteed to produce an
4910: address that is the start of the following contiguous region. In
4911: particular, the cell allocated by @code{variable} is not guaranteed to
4912: be contiguous with following @code{allot}ed memory.
4913:
4914: You can deallocate memory by using @code{allot} with a negative argument
4915: (with some restrictions, see @code{allot}). For larger deallocations use
4916: @code{marker}.
1.27 crook 4917:
1.29 crook 4918:
1.27 crook 4919: doc-here
4920: doc-unused
4921: doc-allot
4922: doc-c,
1.29 crook 4923: doc-f,
1.27 crook 4924: doc-,
4925: doc-2,
4926:
1.32 anton 4927: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4928: course you should allocate memory in an aligned way, too. I.e., before
4929: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4930: The words below align @code{here} if it is not already. Basically it is
4931: only already aligned for a type, if the last allocation was a multiple
4932: of the size of this type and if @code{here} was aligned for this type
4933: before.
4934:
4935: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4936: ANS Forth (@code{maxalign}ed in Gforth).
4937:
4938: doc-align
4939: doc-falign
4940: doc-sfalign
4941: doc-dfalign
4942: doc-maxalign
4943: doc-cfalign
4944:
4945:
4946: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4947: @subsection Heap allocation
4948: @cindex heap allocation
4949: @cindex dynamic allocation of memory
4950: @cindex memory-allocation word set
4951:
1.68 anton 4952: @cindex contiguous regions and heap allocation
1.32 anton 4953: Heap allocation supports deallocation of allocated memory in any
4954: order. Dictionary allocation is not affected by it (i.e., it does not
4955: end a contiguous region). In Gforth, these words are implemented using
4956: the standard C library calls malloc(), free() and resize().
4957:
1.68 anton 4958: The memory region produced by one invocation of @code{allocate} or
4959: @code{resize} is internally contiguous. There is no contiguity between
4960: such a region and any other region (including others allocated from the
4961: heap).
4962:
1.32 anton 4963: doc-allocate
4964: doc-free
4965: doc-resize
4966:
1.27 crook 4967:
1.32 anton 4968: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4969: @subsection Memory Access
4970: @cindex memory access words
4971:
4972: doc-@
4973: doc-!
4974: doc-+!
4975: doc-c@
4976: doc-c!
4977: doc-2@
4978: doc-2!
4979: doc-f@
4980: doc-f!
4981: doc-sf@
4982: doc-sf!
4983: doc-df@
4984: doc-df!
4985:
1.68 anton 4986:
1.32 anton 4987: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4988: @subsection Address arithmetic
1.1 anton 4989: @cindex address arithmetic words
4990:
1.67 anton 4991: Address arithmetic is the foundation on which you can build data
4992: structures like arrays, records (@pxref{Structures}) and objects
4993: (@pxref{Object-oriented Forth}).
1.32 anton 4994:
1.68 anton 4995: @cindex address unit
4996: @cindex au (address unit)
1.1 anton 4997: ANS Forth does not specify the sizes of the data types. Instead, it
4998: offers a number of words for computing sizes and doing address
1.29 crook 4999: arithmetic. Address arithmetic is performed in terms of address units
5000: (aus); on most systems the address unit is one byte. Note that a
5001: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5002: platforms where it is a noop, it compiles to nothing).
1.1 anton 5003:
1.67 anton 5004: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5005: you have the address of a cell, perform @code{1 cells +}, and you will
5006: have the address of the next cell.
5007:
1.68 anton 5008: @cindex contiguous regions and address arithmetic
1.67 anton 5009: In ANS Forth you can perform address arithmetic only within a contiguous
5010: region, i.e., if you have an address into one region, you can only add
5011: and subtract such that the result is still within the region; you can
5012: only subtract or compare addresses from within the same contiguous
5013: region. Reasons: several contiguous regions can be arranged in memory
5014: in any way; on segmented systems addresses may have unusual
5015: representations, such that address arithmetic only works within a
5016: region. Gforth provides a few more guarantees (linear address space,
5017: dictionary grows upwards), but in general I have found it easy to stay
5018: within contiguous regions (exception: computing and comparing to the
5019: address just beyond the end of an array).
5020:
1.1 anton 5021: @cindex alignment of addresses for types
5022: ANS Forth also defines words for aligning addresses for specific
5023: types. Many computers require that accesses to specific data types
5024: must only occur at specific addresses; e.g., that cells may only be
5025: accessed at addresses divisible by 4. Even if a machine allows unaligned
5026: accesses, it can usually perform aligned accesses faster.
5027:
5028: For the performance-conscious: alignment operations are usually only
5029: necessary during the definition of a data structure, not during the
5030: (more frequent) accesses to it.
5031:
5032: ANS Forth defines no words for character-aligning addresses. This is not
5033: an oversight, but reflects the fact that addresses that are not
5034: char-aligned have no use in the standard and therefore will not be
5035: created.
5036:
5037: @cindex @code{CREATE} and alignment
1.29 crook 5038: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5039: are cell-aligned; in addition, Gforth guarantees that these addresses
5040: are aligned for all purposes.
5041:
1.26 crook 5042: Note that the ANS Forth word @code{char} has nothing to do with address
5043: arithmetic.
1.1 anton 5044:
1.44 crook 5045:
1.1 anton 5046: doc-chars
5047: doc-char+
5048: doc-cells
5049: doc-cell+
5050: doc-cell
5051: doc-aligned
5052: doc-floats
5053: doc-float+
5054: doc-float
5055: doc-faligned
5056: doc-sfloats
5057: doc-sfloat+
5058: doc-sfaligned
5059: doc-dfloats
5060: doc-dfloat+
5061: doc-dfaligned
5062: doc-maxaligned
5063: doc-cfaligned
5064: doc-address-unit-bits
5065:
1.44 crook 5066:
1.32 anton 5067: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5068: @subsection Memory Blocks
5069: @cindex memory block words
1.27 crook 5070: @cindex character strings - moving and copying
5071:
1.49 anton 5072: Memory blocks often represent character strings; For ways of storing
5073: character strings in memory see @ref{String Formats}. For other
5074: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5075:
1.67 anton 5076: A few of these words work on address unit blocks. In that case, you
5077: usually have to insert @code{CHARS} before the word when working on
5078: character strings. Most words work on character blocks, and expect a
5079: char-aligned address.
5080:
5081: When copying characters between overlapping memory regions, use
5082: @code{chars move} or choose carefully between @code{cmove} and
5083: @code{cmove>}.
1.44 crook 5084:
1.1 anton 5085: doc-move
5086: doc-erase
5087: doc-cmove
5088: doc-cmove>
5089: doc-fill
5090: doc-blank
1.21 crook 5091: doc-compare
1.111 anton 5092: doc-str=
5093: doc-str<
5094: doc-string-prefix?
1.21 crook 5095: doc-search
1.27 crook 5096: doc--trailing
5097: doc-/string
1.82 anton 5098: doc-bounds
1.44 crook 5099:
1.111 anton 5100:
1.27 crook 5101: @comment TODO examples
5102:
1.1 anton 5103:
1.26 crook 5104: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5105: @section Control Structures
5106: @cindex control structures
5107:
1.33 anton 5108: Control structures in Forth cannot be used interpretively, only in a
5109: colon definition@footnote{To be precise, they have no interpretation
5110: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5111: not like this limitation, but have not seen a satisfying way around it
5112: yet, although many schemes have been proposed.
1.1 anton 5113:
5114: @menu
1.33 anton 5115: * Selection:: IF ... ELSE ... ENDIF
5116: * Simple Loops:: BEGIN ...
1.29 crook 5117: * Counted Loops:: DO
1.67 anton 5118: * Arbitrary control structures::
5119: * Calls and returns::
1.1 anton 5120: * Exception Handling::
5121: @end menu
5122:
5123: @node Selection, Simple Loops, Control Structures, Control Structures
5124: @subsection Selection
5125: @cindex selection control structures
5126: @cindex control structures for selection
5127:
5128: @cindex @code{IF} control structure
5129: @example
1.29 crook 5130: @i{flag}
1.1 anton 5131: IF
1.29 crook 5132: @i{code}
1.1 anton 5133: ENDIF
5134: @end example
1.21 crook 5135: @noindent
1.33 anton 5136:
1.44 crook 5137: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5138: with any bit set represents truth) @i{code} is executed.
1.33 anton 5139:
1.1 anton 5140: @example
1.29 crook 5141: @i{flag}
1.1 anton 5142: IF
1.29 crook 5143: @i{code1}
1.1 anton 5144: ELSE
1.29 crook 5145: @i{code2}
1.1 anton 5146: ENDIF
5147: @end example
5148:
1.44 crook 5149: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5150: executed.
1.33 anton 5151:
1.1 anton 5152: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5153: standard, and @code{ENDIF} is not, although it is quite popular. We
5154: recommend using @code{ENDIF}, because it is less confusing for people
5155: who also know other languages (and is not prone to reinforcing negative
5156: prejudices against Forth in these people). Adding @code{ENDIF} to a
5157: system that only supplies @code{THEN} is simple:
5158: @example
1.82 anton 5159: : ENDIF POSTPONE then ; immediate
1.1 anton 5160: @end example
5161:
5162: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5163: (adv.)} has the following meanings:
5164: @quotation
5165: ... 2b: following next after in order ... 3d: as a necessary consequence
5166: (if you were there, then you saw them).
5167: @end quotation
5168: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5169: and many other programming languages has the meaning 3d.]
5170:
1.21 crook 5171: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5172: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5173: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5174: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5175: @file{compat/control.fs}.
5176:
5177: @cindex @code{CASE} control structure
5178: @example
1.29 crook 5179: @i{n}
1.1 anton 5180: CASE
1.29 crook 5181: @i{n1} OF @i{code1} ENDOF
5182: @i{n2} OF @i{code2} ENDOF
1.1 anton 5183: @dots{}
1.68 anton 5184: ( n ) @i{default-code} ( n )
1.131 anton 5185: ENDCASE ( )
1.1 anton 5186: @end example
5187:
1.131 anton 5188: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5189: no @i{ni} matches, the optional @i{default-code} is executed. The
5190: optional default case can be added by simply writing the code after
5191: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5192: but must not consume it. The value @i{n} is consumed by this
5193: construction (either by a OF that matches, or by the ENDCASE, if no OF
5194: matches).
1.1 anton 5195:
1.69 anton 5196: @progstyle
1.131 anton 5197: To keep the code understandable, you should ensure that you change the
5198: stack in the same way (wrt. number and types of stack items consumed
5199: and pushed) on all paths through a selection construct.
1.69 anton 5200:
1.1 anton 5201: @node Simple Loops, Counted Loops, Selection, Control Structures
5202: @subsection Simple Loops
5203: @cindex simple loops
5204: @cindex loops without count
5205:
5206: @cindex @code{WHILE} loop
5207: @example
5208: BEGIN
1.29 crook 5209: @i{code1}
5210: @i{flag}
1.1 anton 5211: WHILE
1.29 crook 5212: @i{code2}
1.1 anton 5213: REPEAT
5214: @end example
5215:
1.29 crook 5216: @i{code1} is executed and @i{flag} is computed. If it is true,
5217: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5218: false, execution continues after the @code{REPEAT}.
5219:
5220: @cindex @code{UNTIL} loop
5221: @example
5222: BEGIN
1.29 crook 5223: @i{code}
5224: @i{flag}
1.1 anton 5225: UNTIL
5226: @end example
5227:
1.29 crook 5228: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5229:
1.69 anton 5230: @progstyle
5231: To keep the code understandable, a complete iteration of the loop should
5232: not change the number and types of the items on the stacks.
5233:
1.1 anton 5234: @cindex endless loop
5235: @cindex loops, endless
5236: @example
5237: BEGIN
1.29 crook 5238: @i{code}
1.1 anton 5239: AGAIN
5240: @end example
5241:
5242: This is an endless loop.
5243:
5244: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5245: @subsection Counted Loops
5246: @cindex counted loops
5247: @cindex loops, counted
5248: @cindex @code{DO} loops
5249:
5250: The basic counted loop is:
5251: @example
1.29 crook 5252: @i{limit} @i{start}
1.1 anton 5253: ?DO
1.29 crook 5254: @i{body}
1.1 anton 5255: LOOP
5256: @end example
5257:
1.29 crook 5258: This performs one iteration for every integer, starting from @i{start}
5259: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5260: accessed with @code{i}. For example, the loop:
1.1 anton 5261: @example
5262: 10 0 ?DO
5263: i .
5264: LOOP
5265: @end example
1.21 crook 5266: @noindent
5267: prints @code{0 1 2 3 4 5 6 7 8 9}
5268:
1.1 anton 5269: The index of the innermost loop can be accessed with @code{i}, the index
5270: of the next loop with @code{j}, and the index of the third loop with
5271: @code{k}.
5272:
1.44 crook 5273:
1.1 anton 5274: doc-i
5275: doc-j
5276: doc-k
5277:
1.44 crook 5278:
1.1 anton 5279: The loop control data are kept on the return stack, so there are some
1.21 crook 5280: restrictions on mixing return stack accesses and counted loop words. In
5281: particuler, if you put values on the return stack outside the loop, you
5282: cannot read them inside the loop@footnote{well, not in a way that is
5283: portable.}. If you put values on the return stack within a loop, you
5284: have to remove them before the end of the loop and before accessing the
5285: index of the loop.
1.1 anton 5286:
5287: There are several variations on the counted loop:
5288:
1.21 crook 5289: @itemize @bullet
5290: @item
5291: @code{LEAVE} leaves the innermost counted loop immediately; execution
5292: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5293:
5294: @example
5295: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5296: @end example
5297: prints @code{0 1 2 3}
5298:
1.1 anton 5299:
1.21 crook 5300: @item
5301: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5302: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5303: return stack so @code{EXIT} can get to its return address. For example:
5304:
5305: @example
5306: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5307: @end example
5308: prints @code{0 1 2 3}
5309:
5310:
5311: @item
1.29 crook 5312: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5313: (and @code{LOOP} iterates until they become equal by wrap-around
5314: arithmetic). This behaviour is usually not what you want. Therefore,
5315: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5316: @code{?DO}), which do not enter the loop if @i{start} is greater than
5317: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5318: unsigned loop parameters.
5319:
1.21 crook 5320: @item
5321: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5322: the loop, independent of the loop parameters. Do not use @code{DO}, even
5323: if you know that the loop is entered in any case. Such knowledge tends
5324: to become invalid during maintenance of a program, and then the
5325: @code{DO} will make trouble.
5326:
5327: @item
1.29 crook 5328: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5329: index by @i{n} instead of by 1. The loop is terminated when the border
5330: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5331:
1.21 crook 5332: @example
5333: 4 0 +DO i . 2 +LOOP
5334: @end example
5335: @noindent
5336: prints @code{0 2}
5337:
5338: @example
5339: 4 1 +DO i . 2 +LOOP
5340: @end example
5341: @noindent
5342: prints @code{1 3}
1.1 anton 5343:
1.68 anton 5344: @item
1.1 anton 5345: @cindex negative increment for counted loops
5346: @cindex counted loops with negative increment
1.29 crook 5347: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5348:
1.21 crook 5349: @example
5350: -1 0 ?DO i . -1 +LOOP
5351: @end example
5352: @noindent
5353: prints @code{0 -1}
1.1 anton 5354:
1.21 crook 5355: @example
5356: 0 0 ?DO i . -1 +LOOP
5357: @end example
5358: prints nothing.
1.1 anton 5359:
1.29 crook 5360: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5361: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5362: index by @i{u} each iteration. The loop is terminated when the border
5363: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5364: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5365:
1.21 crook 5366: @example
5367: -2 0 -DO i . 1 -LOOP
5368: @end example
5369: @noindent
5370: prints @code{0 -1}
1.1 anton 5371:
1.21 crook 5372: @example
5373: -1 0 -DO i . 1 -LOOP
5374: @end example
5375: @noindent
5376: prints @code{0}
5377:
5378: @example
5379: 0 0 -DO i . 1 -LOOP
5380: @end example
5381: @noindent
5382: prints nothing.
1.1 anton 5383:
1.21 crook 5384: @end itemize
1.1 anton 5385:
5386: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5387: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5388: for these words that uses only standard words is provided in
5389: @file{compat/loops.fs}.
1.1 anton 5390:
5391:
5392: @cindex @code{FOR} loops
1.26 crook 5393: Another counted loop is:
1.1 anton 5394: @example
1.29 crook 5395: @i{n}
1.1 anton 5396: FOR
1.29 crook 5397: @i{body}
1.1 anton 5398: NEXT
5399: @end example
5400: This is the preferred loop of native code compiler writers who are too
1.26 crook 5401: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5402: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5403: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5404: Forth systems may behave differently, even if they support @code{FOR}
5405: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5406:
5407: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5408: @subsection Arbitrary control structures
5409: @cindex control structures, user-defined
5410:
5411: @cindex control-flow stack
5412: ANS Forth permits and supports using control structures in a non-nested
5413: way. Information about incomplete control structures is stored on the
5414: control-flow stack. This stack may be implemented on the Forth data
5415: stack, and this is what we have done in Gforth.
5416:
5417: @cindex @code{orig}, control-flow stack item
5418: @cindex @code{dest}, control-flow stack item
5419: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5420: entry represents a backward branch target. A few words are the basis for
5421: building any control structure possible (except control structures that
5422: need storage, like calls, coroutines, and backtracking).
5423:
1.44 crook 5424:
1.1 anton 5425: doc-if
5426: doc-ahead
5427: doc-then
5428: doc-begin
5429: doc-until
5430: doc-again
5431: doc-cs-pick
5432: doc-cs-roll
5433:
1.44 crook 5434:
1.21 crook 5435: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5436: manipulate the control-flow stack in a portable way. Without them, you
5437: would need to know how many stack items are occupied by a control-flow
5438: entry (many systems use one cell. In Gforth they currently take three,
5439: but this may change in the future).
5440:
1.1 anton 5441: Some standard control structure words are built from these words:
5442:
1.44 crook 5443:
1.1 anton 5444: doc-else
5445: doc-while
5446: doc-repeat
5447:
1.44 crook 5448:
5449: @noindent
1.1 anton 5450: Gforth adds some more control-structure words:
5451:
1.44 crook 5452:
1.1 anton 5453: doc-endif
5454: doc-?dup-if
5455: doc-?dup-0=-if
5456:
1.44 crook 5457:
5458: @noindent
1.1 anton 5459: Counted loop words constitute a separate group of words:
5460:
1.44 crook 5461:
1.1 anton 5462: doc-?do
5463: doc-+do
5464: doc-u+do
5465: doc--do
5466: doc-u-do
5467: doc-do
5468: doc-for
5469: doc-loop
5470: doc-+loop
5471: doc--loop
5472: doc-next
5473: doc-leave
5474: doc-?leave
5475: doc-unloop
5476: doc-done
5477:
1.44 crook 5478:
1.21 crook 5479: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5480: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5481: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5482: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5483: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5484: resolved (by using one of the loop-ending words or @code{DONE}).
5485:
1.44 crook 5486: @noindent
1.26 crook 5487: Another group of control structure words are:
1.1 anton 5488:
1.44 crook 5489:
1.1 anton 5490: doc-case
5491: doc-endcase
5492: doc-of
5493: doc-endof
5494:
1.44 crook 5495:
1.21 crook 5496: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5497: @code{CS-ROLL}.
1.1 anton 5498:
5499: @subsubsection Programming Style
1.47 crook 5500: @cindex control structures programming style
5501: @cindex programming style, arbitrary control structures
1.1 anton 5502:
5503: In order to ensure readability we recommend that you do not create
5504: arbitrary control structures directly, but define new control structure
5505: words for the control structure you want and use these words in your
1.26 crook 5506: program. For example, instead of writing:
1.1 anton 5507:
5508: @example
1.26 crook 5509: BEGIN
1.1 anton 5510: ...
1.26 crook 5511: IF [ 1 CS-ROLL ]
1.1 anton 5512: ...
1.26 crook 5513: AGAIN THEN
1.1 anton 5514: @end example
5515:
1.21 crook 5516: @noindent
1.1 anton 5517: we recommend defining control structure words, e.g.,
5518:
5519: @example
1.26 crook 5520: : WHILE ( DEST -- ORIG DEST )
5521: POSTPONE IF
5522: 1 CS-ROLL ; immediate
5523:
5524: : REPEAT ( orig dest -- )
5525: POSTPONE AGAIN
5526: POSTPONE THEN ; immediate
1.1 anton 5527: @end example
5528:
1.21 crook 5529: @noindent
1.1 anton 5530: and then using these to create the control structure:
5531:
5532: @example
1.26 crook 5533: BEGIN
1.1 anton 5534: ...
1.26 crook 5535: WHILE
1.1 anton 5536: ...
1.26 crook 5537: REPEAT
1.1 anton 5538: @end example
5539:
5540: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5541: @code{WHILE} are predefined, so in this example it would not be
5542: necessary to define them.
5543:
5544: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5545: @subsection Calls and returns
5546: @cindex calling a definition
5547: @cindex returning from a definition
5548:
1.3 anton 5549: @cindex recursive definitions
5550: A definition can be called simply be writing the name of the definition
1.26 crook 5551: to be called. Normally a definition is invisible during its own
1.3 anton 5552: definition. If you want to write a directly recursive definition, you
1.26 crook 5553: can use @code{recursive} to make the current definition visible, or
5554: @code{recurse} to call the current definition directly.
1.3 anton 5555:
1.44 crook 5556:
1.3 anton 5557: doc-recursive
5558: doc-recurse
5559:
1.44 crook 5560:
1.21 crook 5561: @comment TODO add example of the two recursion methods
1.12 anton 5562: @quotation
5563: @progstyle
5564: I prefer using @code{recursive} to @code{recurse}, because calling the
5565: definition by name is more descriptive (if the name is well-chosen) than
5566: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5567: implementation, it is much better to read (and think) ``now sort the
5568: partitions'' than to read ``now do a recursive call''.
5569: @end quotation
1.3 anton 5570:
1.29 crook 5571: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5572:
5573: @example
1.28 crook 5574: Defer foo
1.3 anton 5575:
5576: : bar ( ... -- ... )
5577: ... foo ... ;
5578:
5579: :noname ( ... -- ... )
5580: ... bar ... ;
5581: IS foo
5582: @end example
5583:
1.44 crook 5584: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5585:
1.26 crook 5586: The current definition returns control to the calling definition when
1.33 anton 5587: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5588:
5589: doc-exit
5590: doc-;s
5591:
1.44 crook 5592:
1.1 anton 5593: @node Exception Handling, , Calls and returns, Control Structures
5594: @subsection Exception Handling
1.26 crook 5595: @cindex exceptions
1.1 anton 5596:
1.68 anton 5597: @c quit is a very bad idea for error handling,
5598: @c because it does not translate into a THROW
5599: @c it also does not belong into this chapter
5600:
5601: If a word detects an error condition that it cannot handle, it can
5602: @code{throw} an exception. In the simplest case, this will terminate
5603: your program, and report an appropriate error.
1.21 crook 5604:
1.68 anton 5605: doc-throw
1.1 anton 5606:
1.69 anton 5607: @code{Throw} consumes a cell-sized error number on the stack. There are
5608: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5609: Gforth (and most other systems) you can use the iors produced by various
5610: words as error numbers (e.g., a typical use of @code{allocate} is
5611: @code{allocate throw}). Gforth also provides the word @code{exception}
5612: to define your own error numbers (with decent error reporting); an ANS
5613: Forth version of this word (but without the error messages) is available
5614: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5615: numbers (anything outside the range -4095..0), but won't get nice error
5616: messages, only numbers. For example, try:
5617:
5618: @example
1.69 anton 5619: -10 throw \ ANS defined
5620: -267 throw \ system defined
5621: s" my error" exception throw \ user defined
5622: 7 throw \ arbitrary number
1.68 anton 5623: @end example
5624:
5625: doc---exception-exception
1.1 anton 5626:
1.69 anton 5627: A common idiom to @code{THROW} a specific error if a flag is true is
5628: this:
5629:
5630: @example
5631: @code{( flag ) 0<> @i{errno} and throw}
5632: @end example
5633:
5634: Your program can provide exception handlers to catch exceptions. An
5635: exception handler can be used to correct the problem, or to clean up
5636: some data structures and just throw the exception to the next exception
5637: handler. Note that @code{throw} jumps to the dynamically innermost
5638: exception handler. The system's exception handler is outermost, and just
5639: prints an error and restarts command-line interpretation (or, in batch
5640: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5641:
1.68 anton 5642: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5643:
1.68 anton 5644: doc-catch
5645:
5646: The most common use of exception handlers is to clean up the state when
5647: an error happens. E.g.,
1.1 anton 5648:
1.26 crook 5649: @example
1.68 anton 5650: base @ >r hex \ actually the hex should be inside foo, or we h
5651: ['] foo catch ( nerror|0 )
5652: r> base !
1.69 anton 5653: ( nerror|0 ) throw \ pass it on
1.26 crook 5654: @end example
1.1 anton 5655:
1.69 anton 5656: A use of @code{catch} for handling the error @code{myerror} might look
5657: like this:
1.44 crook 5658:
1.68 anton 5659: @example
1.69 anton 5660: ['] foo catch
5661: CASE
5662: myerror OF ... ( do something about it ) ENDOF
5663: dup throw \ default: pass other errors on, do nothing on non-errors
5664: ENDCASE
1.68 anton 5665: @end example
1.44 crook 5666:
1.68 anton 5667: Having to wrap the code into a separate word is often cumbersome,
5668: therefore Gforth provides an alternative syntax:
1.1 anton 5669:
5670: @example
1.69 anton 5671: TRY
1.68 anton 5672: @i{code1}
1.69 anton 5673: RECOVER \ optional
1.68 anton 5674: @i{code2} \ optional
1.69 anton 5675: ENDTRY
1.1 anton 5676: @end example
5677:
1.68 anton 5678: This performs @i{Code1}. If @i{code1} completes normally, execution
5679: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5680: reset to the state during @code{try}, the throw value is pushed on the
5681: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5682: through the @code{endtry} into the following code.
1.26 crook 5683:
1.68 anton 5684: doc-try
5685: doc-recover
5686: doc-endtry
1.26 crook 5687:
1.69 anton 5688: The cleanup example from above in this syntax:
1.26 crook 5689:
1.68 anton 5690: @example
1.69 anton 5691: base @ >r TRY
1.68 anton 5692: hex foo \ now the hex is placed correctly
1.69 anton 5693: 0 \ value for throw
1.92 anton 5694: RECOVER ENDTRY
1.68 anton 5695: r> base ! throw
1.1 anton 5696: @end example
5697:
1.69 anton 5698: And here's the error handling example:
1.1 anton 5699:
1.68 anton 5700: @example
1.69 anton 5701: TRY
1.68 anton 5702: foo
1.69 anton 5703: RECOVER
5704: CASE
5705: myerror OF ... ( do something about it ) ENDOF
5706: throw \ pass other errors on
5707: ENDCASE
5708: ENDTRY
1.68 anton 5709: @end example
1.1 anton 5710:
1.69 anton 5711: @progstyle
5712: As usual, you should ensure that the stack depth is statically known at
5713: the end: either after the @code{throw} for passing on errors, or after
5714: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5715: selection construct for handling the error).
5716:
1.68 anton 5717: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5718: and you can provide an error message. @code{Abort} just produces an
5719: ``Aborted'' error.
1.1 anton 5720:
1.68 anton 5721: The problem with these words is that exception handlers cannot
5722: differentiate between different @code{abort"}s; they just look like
5723: @code{-2 throw} to them (the error message cannot be accessed by
5724: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5725: exception handlers.
1.44 crook 5726:
1.68 anton 5727: doc-abort"
1.26 crook 5728: doc-abort
1.29 crook 5729:
5730:
1.44 crook 5731:
1.29 crook 5732: @c -------------------------------------------------------------
1.47 crook 5733: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5734: @section Defining Words
5735: @cindex defining words
5736:
1.47 crook 5737: Defining words are used to extend Forth by creating new entries in the dictionary.
5738:
1.29 crook 5739: @menu
1.67 anton 5740: * CREATE::
1.44 crook 5741: * Variables:: Variables and user variables
1.67 anton 5742: * Constants::
1.44 crook 5743: * Values:: Initialised variables
1.67 anton 5744: * Colon Definitions::
1.44 crook 5745: * Anonymous Definitions:: Definitions without names
1.69 anton 5746: * Supplying names:: Passing definition names as strings
1.67 anton 5747: * User-defined Defining Words::
1.44 crook 5748: * Deferred words:: Allow forward references
1.67 anton 5749: * Aliases::
1.29 crook 5750: @end menu
5751:
1.44 crook 5752: @node CREATE, Variables, Defining Words, Defining Words
5753: @subsection @code{CREATE}
1.29 crook 5754: @cindex simple defining words
5755: @cindex defining words, simple
5756:
5757: Defining words are used to create new entries in the dictionary. The
5758: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5759: this:
5760:
5761: @example
5762: CREATE new-word1
5763: @end example
5764:
1.69 anton 5765: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5766: input stream (@code{new-word1} in our example). It generates a
5767: dictionary entry for @code{new-word1}. When @code{new-word1} is
5768: executed, all that it does is leave an address on the stack. The address
5769: represents the value of the data space pointer (@code{HERE}) at the time
5770: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5771: associating a name with the address of a region of memory.
1.29 crook 5772:
1.34 anton 5773: doc-create
5774:
1.69 anton 5775: Note that in ANS Forth guarantees only for @code{create} that its body
5776: is in dictionary data space (i.e., where @code{here}, @code{allot}
5777: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5778: @code{create}d words can be modified with @code{does>}
5779: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5780: can only be applied to @code{create}d words.
5781:
1.29 crook 5782: By extending this example to reserve some memory in data space, we end
1.69 anton 5783: up with something like a @i{variable}. Here are two different ways to do
5784: it:
1.29 crook 5785:
5786: @example
5787: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5788: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5789: @end example
5790:
5791: The variable can be examined and modified using @code{@@} (``fetch'') and
5792: @code{!} (``store'') like this:
5793:
5794: @example
5795: new-word2 @@ . \ get address, fetch from it and display
5796: 1234 new-word2 ! \ new value, get address, store to it
5797: @end example
5798:
1.44 crook 5799: @cindex arrays
5800: A similar mechanism can be used to create arrays. For example, an
5801: 80-character text input buffer:
1.29 crook 5802:
5803: @example
1.44 crook 5804: CREATE text-buf 80 chars allot
5805:
5806: text-buf 0 chars c@@ \ the 1st character (offset 0)
5807: text-buf 3 chars c@@ \ the 4th character (offset 3)
5808: @end example
1.29 crook 5809:
1.44 crook 5810: You can build arbitrarily complex data structures by allocating
1.49 anton 5811: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5812: learn about some Gforth tools that make it easier,
1.49 anton 5813: @xref{Structures}.
1.44 crook 5814:
5815:
5816: @node Variables, Constants, CREATE, Defining Words
5817: @subsection Variables
5818: @cindex variables
5819:
5820: The previous section showed how a sequence of commands could be used to
5821: generate a variable. As a final refinement, the whole code sequence can
5822: be wrapped up in a defining word (pre-empting the subject of the next
5823: section), making it easier to create new variables:
5824:
5825: @example
5826: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5827: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5828:
5829: myvariableX foo \ variable foo starts off with an unknown value
5830: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5831:
5832: 45 3 * foo ! \ set foo to 135
5833: 1234 joe ! \ set joe to 1234
5834: 3 joe +! \ increment joe by 3.. to 1237
5835: @end example
5836:
5837: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5838: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5839: guarantee that a @code{Variable} is initialised when it is created
5840: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5841: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5842: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5843: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5844: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5845: store a boolean, you can use @code{on} and @code{off} to toggle its
5846: state.
1.29 crook 5847:
1.34 anton 5848: doc-variable
5849: doc-2variable
5850: doc-fvariable
5851:
1.29 crook 5852: @cindex user variables
5853: @cindex user space
5854: The defining word @code{User} behaves in the same way as @code{Variable}.
5855: The difference is that it reserves space in @i{user (data) space} rather
5856: than normal data space. In a Forth system that has a multi-tasker, each
5857: task has its own set of user variables.
5858:
1.34 anton 5859: doc-user
1.67 anton 5860: @c doc-udp
5861: @c doc-uallot
1.34 anton 5862:
1.29 crook 5863: @comment TODO is that stuff about user variables strictly correct? Is it
5864: @comment just terminal tasks that have user variables?
5865: @comment should document tasker.fs (with some examples) elsewhere
5866: @comment in this manual, then expand on user space and user variables.
5867:
1.44 crook 5868: @node Constants, Values, Variables, Defining Words
5869: @subsection Constants
5870: @cindex constants
5871:
5872: @code{Constant} allows you to declare a fixed value and refer to it by
5873: name. For example:
1.29 crook 5874:
5875: @example
5876: 12 Constant INCHES-PER-FOOT
5877: 3E+08 fconstant SPEED-O-LIGHT
5878: @end example
5879:
5880: A @code{Variable} can be both read and written, so its run-time
5881: behaviour is to supply an address through which its current value can be
5882: manipulated. In contrast, the value of a @code{Constant} cannot be
5883: changed once it has been declared@footnote{Well, often it can be -- but
5884: not in a Standard, portable way. It's safer to use a @code{Value} (read
5885: on).} so it's not necessary to supply the address -- it is more
5886: efficient to return the value of the constant directly. That's exactly
5887: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5888: the top of the stack (You can find one
5889: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5890:
1.69 anton 5891: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5892: double and floating-point constants, respectively.
5893:
1.34 anton 5894: doc-constant
5895: doc-2constant
5896: doc-fconstant
5897:
5898: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5899: @c nac-> How could that not be true in an ANS Forth? You can't define a
5900: @c constant, use it and then delete the definition of the constant..
1.69 anton 5901:
5902: @c anton->An ANS Forth system can compile a constant to a literal; On
5903: @c decompilation you would see only the number, just as if it had been used
5904: @c in the first place. The word will stay, of course, but it will only be
5905: @c used by the text interpreter (no run-time duties, except when it is
5906: @c POSTPONEd or somesuch).
5907:
5908: @c nac:
1.44 crook 5909: @c I agree that it's rather deep, but IMO it is an important difference
5910: @c relative to other programming languages.. often it's annoying: it
5911: @c certainly changes my programming style relative to C.
5912:
1.69 anton 5913: @c anton: In what way?
5914:
1.29 crook 5915: Constants in Forth behave differently from their equivalents in other
5916: programming languages. In other languages, a constant (such as an EQU in
5917: assembler or a #define in C) only exists at compile-time; in the
5918: executable program the constant has been translated into an absolute
5919: number and, unless you are using a symbolic debugger, it's impossible to
5920: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5921: an entry in the header space and remains there after the code that uses
5922: it has been defined. In fact, it must remain in the dictionary since it
5923: has run-time duties to perform. For example:
1.29 crook 5924:
5925: @example
5926: 12 Constant INCHES-PER-FOOT
5927: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5928: @end example
5929:
5930: @cindex in-lining of constants
5931: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5932: associated with the constant @code{INCHES-PER-FOOT}. If you use
5933: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5934: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5935: attempt to optimise constants by in-lining them where they are used. You
5936: can force Gforth to in-line a constant like this:
5937:
5938: @example
5939: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5940: @end example
5941:
5942: If you use @code{see} to decompile @i{this} version of
5943: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5944: longer present. To understand how this works, read
5945: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5946:
5947: In-lining constants in this way might improve execution time
5948: fractionally, and can ensure that a constant is now only referenced at
5949: compile-time. However, the definition of the constant still remains in
5950: the dictionary. Some Forth compilers provide a mechanism for controlling
5951: a second dictionary for holding transient words such that this second
5952: dictionary can be deleted later in order to recover memory
5953: space. However, there is no standard way of doing this.
5954:
5955:
1.44 crook 5956: @node Values, Colon Definitions, Constants, Defining Words
5957: @subsection Values
5958: @cindex values
1.34 anton 5959:
1.69 anton 5960: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5961: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5962: (not in ANS Forth) you can access (and change) a @code{value} also with
5963: @code{>body}.
5964:
5965: Here are some
5966: examples:
1.29 crook 5967:
5968: @example
1.69 anton 5969: 12 Value APPLES \ Define APPLES with an initial value of 12
5970: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5971: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5972: APPLES \ puts 35 on the top of the stack.
1.29 crook 5973: @end example
5974:
1.44 crook 5975: doc-value
5976: doc-to
1.29 crook 5977:
1.35 anton 5978:
1.69 anton 5979:
1.44 crook 5980: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5981: @subsection Colon Definitions
5982: @cindex colon definitions
1.35 anton 5983:
5984: @example
1.44 crook 5985: : name ( ... -- ... )
5986: word1 word2 word3 ;
1.29 crook 5987: @end example
5988:
1.44 crook 5989: @noindent
5990: Creates a word called @code{name} that, upon execution, executes
5991: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 5992:
1.49 anton 5993: The explanation above is somewhat superficial. For simple examples of
5994: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 5995: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 5996: Compilation Semantics}.
1.29 crook 5997:
1.44 crook 5998: doc-:
5999: doc-;
1.1 anton 6000:
1.34 anton 6001:
1.69 anton 6002: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6003: @subsection Anonymous Definitions
6004: @cindex colon definitions
6005: @cindex defining words without name
1.34 anton 6006:
1.44 crook 6007: Sometimes you want to define an @dfn{anonymous word}; a word without a
6008: name. You can do this with:
1.1 anton 6009:
1.44 crook 6010: doc-:noname
1.1 anton 6011:
1.44 crook 6012: This leaves the execution token for the word on the stack after the
6013: closing @code{;}. Here's an example in which a deferred word is
6014: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6015:
1.29 crook 6016: @example
1.44 crook 6017: Defer deferred
6018: :noname ( ... -- ... )
6019: ... ;
6020: IS deferred
1.29 crook 6021: @end example
1.26 crook 6022:
1.44 crook 6023: @noindent
6024: Gforth provides an alternative way of doing this, using two separate
6025: words:
1.27 crook 6026:
1.44 crook 6027: doc-noname
6028: @cindex execution token of last defined word
1.116 anton 6029: doc-latestxt
1.1 anton 6030:
1.44 crook 6031: @noindent
6032: The previous example can be rewritten using @code{noname} and
1.116 anton 6033: @code{latestxt}:
1.1 anton 6034:
1.26 crook 6035: @example
1.44 crook 6036: Defer deferred
6037: noname : ( ... -- ... )
6038: ... ;
1.116 anton 6039: latestxt IS deferred
1.26 crook 6040: @end example
1.1 anton 6041:
1.29 crook 6042: @noindent
1.44 crook 6043: @code{noname} works with any defining word, not just @code{:}.
6044:
1.116 anton 6045: @code{latestxt} also works when the last word was not defined as
1.71 anton 6046: @code{noname}. It does not work for combined words, though. It also has
6047: the useful property that is is valid as soon as the header for a
6048: definition has been built. Thus:
1.44 crook 6049:
6050: @example
1.116 anton 6051: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6052: @end example
1.1 anton 6053:
1.44 crook 6054: @noindent
6055: prints 3 numbers; the last two are the same.
1.26 crook 6056:
1.69 anton 6057: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6058: @subsection Supplying the name of a defined word
6059: @cindex names for defined words
6060: @cindex defining words, name given in a string
6061:
6062: By default, a defining word takes the name for the defined word from the
6063: input stream. Sometimes you want to supply the name from a string. You
6064: can do this with:
6065:
6066: doc-nextname
6067:
6068: For example:
6069:
6070: @example
6071: s" foo" nextname create
6072: @end example
6073:
6074: @noindent
6075: is equivalent to:
6076:
6077: @example
6078: create foo
6079: @end example
6080:
6081: @noindent
6082: @code{nextname} works with any defining word.
6083:
1.1 anton 6084:
1.69 anton 6085: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6086: @subsection User-defined Defining Words
6087: @cindex user-defined defining words
6088: @cindex defining words, user-defined
1.1 anton 6089:
1.29 crook 6090: You can create a new defining word by wrapping defining-time code around
6091: an existing defining word and putting the sequence in a colon
1.69 anton 6092: definition.
6093:
6094: @c anton: This example is very complex and leads in a quite different
6095: @c direction from the CREATE-DOES> stuff that follows. It should probably
6096: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6097: @c subsection of Defining Words)
6098:
6099: For example, suppose that you have a word @code{stats} that
1.29 crook 6100: gathers statistics about colon definitions given the @i{xt} of the
6101: definition, and you want every colon definition in your application to
6102: make a call to @code{stats}. You can define and use a new version of
6103: @code{:} like this:
6104:
6105: @example
6106: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6107: ... ; \ other code
6108:
1.116 anton 6109: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6110:
6111: my: foo + - ;
6112: @end example
6113:
6114: When @code{foo} is defined using @code{my:} these steps occur:
6115:
6116: @itemize @bullet
6117: @item
6118: @code{my:} is executed.
6119: @item
6120: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6121: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6122: the input stream for a name, builds a dictionary header for the name
6123: @code{foo} and switches @code{state} from interpret to compile.
6124: @item
1.116 anton 6125: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6126: being defined -- @code{foo} -- onto the stack.
6127: @item
6128: The code that was produced by @code{postpone literal} is executed; this
6129: causes the value on the stack to be compiled as a literal in the code
6130: area of @code{foo}.
6131: @item
6132: The code @code{['] stats} compiles a literal into the definition of
6133: @code{my:}. When @code{compile,} is executed, that literal -- the
6134: execution token for @code{stats} -- is layed down in the code area of
6135: @code{foo} , following the literal@footnote{Strictly speaking, the
6136: mechanism that @code{compile,} uses to convert an @i{xt} into something
6137: in the code area is implementation-dependent. A threaded implementation
6138: might spit out the execution token directly whilst another
6139: implementation might spit out a native code sequence.}.
6140: @item
6141: At this point, the execution of @code{my:} is complete, and control
6142: returns to the text interpreter. The text interpreter is in compile
6143: state, so subsequent text @code{+ -} is compiled into the definition of
6144: @code{foo} and the @code{;} terminates the definition as always.
6145: @end itemize
6146:
6147: You can use @code{see} to decompile a word that was defined using
6148: @code{my:} and see how it is different from a normal @code{:}
6149: definition. For example:
6150:
6151: @example
6152: : bar + - ; \ like foo but using : rather than my:
6153: see bar
6154: : bar
6155: + - ;
6156: see foo
6157: : foo
6158: 107645672 stats + - ;
6159:
6160: \ use ' stats . to show that 107645672 is the xt for stats
6161: @end example
6162:
6163: You can use techniques like this to make new defining words in terms of
6164: @i{any} existing defining word.
1.1 anton 6165:
6166:
1.29 crook 6167: @cindex defining defining words
1.26 crook 6168: @cindex @code{CREATE} ... @code{DOES>}
6169: If you want the words defined with your defining words to behave
6170: differently from words defined with standard defining words, you can
6171: write your defining word like this:
1.1 anton 6172:
6173: @example
1.26 crook 6174: : def-word ( "name" -- )
1.29 crook 6175: CREATE @i{code1}
1.26 crook 6176: DOES> ( ... -- ... )
1.29 crook 6177: @i{code2} ;
1.26 crook 6178:
6179: def-word name
1.1 anton 6180: @end example
6181:
1.29 crook 6182: @cindex child words
6183: This fragment defines a @dfn{defining word} @code{def-word} and then
6184: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6185: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6186: is not executed at this time. The word @code{name} is sometimes called a
6187: @dfn{child} of @code{def-word}.
6188:
6189: When you execute @code{name}, the address of the body of @code{name} is
6190: put on the data stack and @i{code2} is executed (the address of the body
6191: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6192: @code{CREATE}, i.e., the address a @code{create}d word returns by
6193: default).
6194:
6195: @c anton:
6196: @c www.dictionary.com says:
6197: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6198: @c several generations of absence, usually caused by the chance
6199: @c recombination of genes. 2.An individual or a part that exhibits
6200: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6201: @c of previous behavior after a period of absence.
6202: @c
6203: @c Doesn't seem to fit.
1.29 crook 6204:
1.69 anton 6205: @c @cindex atavism in child words
1.33 anton 6206: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6207: similarly; they all have a common run-time behaviour determined by
6208: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6209: body of the child word. The structure of the data is common to all
6210: children of @code{def-word}, but the data values are specific -- and
6211: private -- to each child word. When a child word is executed, the
6212: address of its private data area is passed as a parameter on TOS to be
6213: used and manipulated@footnote{It is legitimate both to read and write to
6214: this data area.} by @i{code2}.
1.29 crook 6215:
6216: The two fragments of code that make up the defining words act (are
6217: executed) at two completely separate times:
1.1 anton 6218:
1.29 crook 6219: @itemize @bullet
6220: @item
6221: At @i{define time}, the defining word executes @i{code1} to generate a
6222: child word
6223: @item
6224: At @i{child execution time}, when a child word is invoked, @i{code2}
6225: is executed, using parameters (data) that are private and specific to
6226: the child word.
6227: @end itemize
6228:
1.44 crook 6229: Another way of understanding the behaviour of @code{def-word} and
6230: @code{name} is to say that, if you make the following definitions:
1.33 anton 6231: @example
6232: : def-word1 ( "name" -- )
6233: CREATE @i{code1} ;
6234:
6235: : action1 ( ... -- ... )
6236: @i{code2} ;
6237:
6238: def-word1 name1
6239: @end example
6240:
1.44 crook 6241: @noindent
6242: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6243:
1.29 crook 6244: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6245:
1.1 anton 6246: @example
1.29 crook 6247: : CONSTANT ( w "name" -- )
6248: CREATE ,
1.26 crook 6249: DOES> ( -- w )
6250: @@ ;
1.1 anton 6251: @end example
6252:
1.29 crook 6253: @comment There is a beautiful description of how this works and what
6254: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6255: @comment commentary on the Counting Fruits problem.
6256:
6257: When you create a constant with @code{5 CONSTANT five}, a set of
6258: define-time actions take place; first a new word @code{five} is created,
6259: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6260: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6261: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6262: no code of its own; it simply contains a data field and a pointer to the
6263: code that follows @code{DOES>} in its defining word. That makes words
6264: created in this way very compact.
6265:
6266: The final example in this section is intended to remind you that space
6267: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6268: both read and written by a Standard program@footnote{Exercise: use this
6269: example as a starting point for your own implementation of @code{Value}
6270: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6271: @code{[']}.}:
6272:
6273: @example
6274: : foo ( "name" -- )
6275: CREATE -1 ,
6276: DOES> ( -- )
1.33 anton 6277: @@ . ;
1.29 crook 6278:
6279: foo first-word
6280: foo second-word
6281:
6282: 123 ' first-word >BODY !
6283: @end example
6284:
6285: If @code{first-word} had been a @code{CREATE}d word, we could simply
6286: have executed it to get the address of its data field. However, since it
6287: was defined to have @code{DOES>} actions, its execution semantics are to
6288: perform those @code{DOES>} actions. To get the address of its data field
6289: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6290: translate the xt into the address of the data field. When you execute
6291: @code{first-word}, it will display @code{123}. When you execute
6292: @code{second-word} it will display @code{-1}.
1.26 crook 6293:
6294: @cindex stack effect of @code{DOES>}-parts
6295: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6296: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6297: the stack effect of the defined words, not the stack effect of the
6298: following code (the following code expects the address of the body on
6299: the top of stack, which is not reflected in the stack comment). This is
6300: the convention that I use and recommend (it clashes a bit with using
6301: locals declarations for stack effect specification, though).
1.1 anton 6302:
1.53 anton 6303: @menu
6304: * CREATE..DOES> applications::
6305: * CREATE..DOES> details::
1.63 anton 6306: * Advanced does> usage example::
1.91 anton 6307: * @code{Const-does>}::
1.53 anton 6308: @end menu
6309:
6310: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6311: @subsubsection Applications of @code{CREATE..DOES>}
6312: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6313:
1.26 crook 6314: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6315:
1.26 crook 6316: @cindex factoring similar colon definitions
6317: When you see a sequence of code occurring several times, and you can
6318: identify a meaning, you will factor it out as a colon definition. When
6319: you see similar colon definitions, you can factor them using
6320: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6321: that look very similar:
1.1 anton 6322: @example
1.26 crook 6323: : ori, ( reg-target reg-source n -- )
6324: 0 asm-reg-reg-imm ;
6325: : andi, ( reg-target reg-source n -- )
6326: 1 asm-reg-reg-imm ;
1.1 anton 6327: @end example
6328:
1.26 crook 6329: @noindent
6330: This could be factored with:
6331: @example
6332: : reg-reg-imm ( op-code -- )
6333: CREATE ,
6334: DOES> ( reg-target reg-source n -- )
6335: @@ asm-reg-reg-imm ;
6336:
6337: 0 reg-reg-imm ori,
6338: 1 reg-reg-imm andi,
6339: @end example
1.1 anton 6340:
1.26 crook 6341: @cindex currying
6342: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6343: supply a part of the parameters for a word (known as @dfn{currying} in
6344: the functional language community). E.g., @code{+} needs two
6345: parameters. Creating versions of @code{+} with one parameter fixed can
6346: be done like this:
1.82 anton 6347:
1.1 anton 6348: @example
1.82 anton 6349: : curry+ ( n1 "name" -- )
1.26 crook 6350: CREATE ,
6351: DOES> ( n2 -- n1+n2 )
6352: @@ + ;
6353:
6354: 3 curry+ 3+
6355: -2 curry+ 2-
1.1 anton 6356: @end example
6357:
1.91 anton 6358:
1.63 anton 6359: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6360: @subsubsection The gory details of @code{CREATE..DOES>}
6361: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6362:
1.26 crook 6363: doc-does>
1.1 anton 6364:
1.26 crook 6365: @cindex @code{DOES>} in a separate definition
6366: This means that you need not use @code{CREATE} and @code{DOES>} in the
6367: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6368: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6369: @example
6370: : does1
6371: DOES> ( ... -- ... )
1.44 crook 6372: ... ;
6373:
6374: : does2
6375: DOES> ( ... -- ... )
6376: ... ;
6377:
6378: : def-word ( ... -- ... )
6379: create ...
6380: IF
6381: does1
6382: ELSE
6383: does2
6384: ENDIF ;
6385: @end example
6386:
6387: In this example, the selection of whether to use @code{does1} or
1.69 anton 6388: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6389: @code{CREATE}d.
6390:
6391: @cindex @code{DOES>} in interpretation state
6392: In a standard program you can apply a @code{DOES>}-part only if the last
6393: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6394: will override the behaviour of the last word defined in any case. In a
6395: standard program, you can use @code{DOES>} only in a colon
6396: definition. In Gforth, you can also use it in interpretation state, in a
6397: kind of one-shot mode; for example:
6398: @example
6399: CREATE name ( ... -- ... )
6400: @i{initialization}
6401: DOES>
6402: @i{code} ;
6403: @end example
6404:
6405: @noindent
6406: is equivalent to the standard:
6407: @example
6408: :noname
6409: DOES>
6410: @i{code} ;
6411: CREATE name EXECUTE ( ... -- ... )
6412: @i{initialization}
6413: @end example
6414:
1.53 anton 6415: doc->body
6416:
1.91 anton 6417: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6418: @subsubsection Advanced does> usage example
6419:
6420: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6421: for disassembling instructions, that follow a very repetetive scheme:
6422:
6423: @example
6424: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6425: @var{entry-num} cells @var{table} + !
6426: @end example
6427:
6428: Of course, this inspires the idea to factor out the commonalities to
6429: allow a definition like
6430:
6431: @example
6432: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6433: @end example
6434:
6435: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6436: correlated. Moreover, before I wrote the disassembler, there already
6437: existed code that defines instructions like this:
1.63 anton 6438:
6439: @example
6440: @var{entry-num} @var{inst-format} @var{inst-name}
6441: @end example
6442:
6443: This code comes from the assembler and resides in
6444: @file{arch/mips/insts.fs}.
6445:
6446: So I had to define the @var{inst-format} words that performed the scheme
6447: above when executed. At first I chose to use run-time code-generation:
6448:
6449: @example
6450: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6451: :noname Postpone @var{disasm-operands}
6452: name Postpone sliteral Postpone type Postpone ;
6453: swap cells @var{table} + ! ;
6454: @end example
6455:
6456: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6457:
1.63 anton 6458: An alternative would have been to write this using
6459: @code{create}/@code{does>}:
6460:
6461: @example
6462: : @var{inst-format} ( entry-num "name" -- )
6463: here name string, ( entry-num c-addr ) \ parse and save "name"
6464: noname create , ( entry-num )
1.116 anton 6465: latestxt swap cells @var{table} + !
1.63 anton 6466: does> ( addr w -- )
6467: \ disassemble instruction w at addr
6468: @@ >r
6469: @var{disasm-operands}
6470: r> count type ;
6471: @end example
6472:
6473: Somehow the first solution is simpler, mainly because it's simpler to
6474: shift a string from definition-time to use-time with @code{sliteral}
6475: than with @code{string,} and friends.
6476:
6477: I wrote a lot of words following this scheme and soon thought about
6478: factoring out the commonalities among them. Note that this uses a
6479: two-level defining word, i.e., a word that defines ordinary defining
6480: words.
6481:
6482: This time a solution involving @code{postpone} and friends seemed more
6483: difficult (try it as an exercise), so I decided to use a
6484: @code{create}/@code{does>} word; since I was already at it, I also used
6485: @code{create}/@code{does>} for the lower level (try using
6486: @code{postpone} etc. as an exercise), resulting in the following
6487: definition:
6488:
6489: @example
6490: : define-format ( disasm-xt table-xt -- )
6491: \ define an instruction format that uses disasm-xt for
6492: \ disassembling and enters the defined instructions into table
6493: \ table-xt
6494: create 2,
6495: does> ( u "inst" -- )
6496: \ defines an anonymous word for disassembling instruction inst,
6497: \ and enters it as u-th entry into table-xt
6498: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6499: noname create 2, \ define anonymous word
1.116 anton 6500: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6501: does> ( addr w -- )
6502: \ disassemble instruction w at addr
6503: 2@@ >r ( addr w disasm-xt R: c-addr )
6504: execute ( R: c-addr ) \ disassemble operands
6505: r> count type ; \ print name
6506: @end example
6507:
6508: Note that the tables here (in contrast to above) do the @code{cells +}
6509: by themselves (that's why you have to pass an xt). This word is used in
6510: the following way:
6511:
6512: @example
6513: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6514: @end example
6515:
1.71 anton 6516: As shown above, the defined instruction format is then used like this:
6517:
6518: @example
6519: @var{entry-num} @var{inst-format} @var{inst-name}
6520: @end example
6521:
1.63 anton 6522: In terms of currying, this kind of two-level defining word provides the
6523: parameters in three stages: first @var{disasm-operands} and @var{table},
6524: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6525: the instruction to be disassembled.
6526:
6527: Of course this did not quite fit all the instruction format names used
6528: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6529: the parameters into the right form.
6530:
6531: If you have trouble following this section, don't worry. First, this is
6532: involved and takes time (and probably some playing around) to
6533: understand; second, this is the first two-level
6534: @code{create}/@code{does>} word I have written in seventeen years of
6535: Forth; and if I did not have @file{insts.fs} to start with, I may well
6536: have elected to use just a one-level defining word (with some repeating
6537: of parameters when using the defining word). So it is not necessary to
6538: understand this, but it may improve your understanding of Forth.
1.44 crook 6539:
6540:
1.91 anton 6541: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6542: @subsubsection @code{Const-does>}
6543:
6544: A frequent use of @code{create}...@code{does>} is for transferring some
6545: values from definition-time to run-time. Gforth supports this use with
6546:
6547: doc-const-does>
6548:
6549: A typical use of this word is:
6550:
6551: @example
6552: : curry+ ( n1 "name" -- )
6553: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6554: + ;
6555:
6556: 3 curry+ 3+
6557: @end example
6558:
6559: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6560: definition to run-time.
6561:
6562: The advantages of using @code{const-does>} are:
6563:
6564: @itemize
6565:
6566: @item
6567: You don't have to deal with storing and retrieving the values, i.e.,
6568: your program becomes more writable and readable.
6569:
6570: @item
6571: When using @code{does>}, you have to introduce a @code{@@} that cannot
6572: be optimized away (because you could change the data using
6573: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6574:
6575: @end itemize
6576:
6577: An ANS Forth implementation of @code{const-does>} is available in
6578: @file{compat/const-does.fs}.
6579:
6580:
1.44 crook 6581: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6582: @subsection Deferred words
6583: @cindex deferred words
6584:
6585: The defining word @code{Defer} allows you to define a word by name
6586: without defining its behaviour; the definition of its behaviour is
6587: deferred. Here are two situation where this can be useful:
6588:
6589: @itemize @bullet
6590: @item
6591: Where you want to allow the behaviour of a word to be altered later, and
6592: for all precompiled references to the word to change when its behaviour
6593: is changed.
6594: @item
6595: For mutual recursion; @xref{Calls and returns}.
6596: @end itemize
6597:
6598: In the following example, @code{foo} always invokes the version of
6599: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6600: always invokes the version that prints ``@code{Hello}''. There is no way
6601: of getting @code{foo} to use the later version without re-ordering the
6602: source code and recompiling it.
6603:
6604: @example
6605: : greet ." Good morning" ;
6606: : foo ... greet ... ;
6607: : greet ." Hello" ;
6608: : bar ... greet ... ;
6609: @end example
6610:
6611: This problem can be solved by defining @code{greet} as a @code{Defer}red
6612: word. The behaviour of a @code{Defer}red word can be defined and
6613: redefined at any time by using @code{IS} to associate the xt of a
6614: previously-defined word with it. The previous example becomes:
6615:
6616: @example
1.69 anton 6617: Defer greet ( -- )
1.44 crook 6618: : foo ... greet ... ;
6619: : bar ... greet ... ;
1.69 anton 6620: : greet1 ( -- ) ." Good morning" ;
6621: : greet2 ( -- ) ." Hello" ;
1.132 anton 6622: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6623: @end example
6624:
1.69 anton 6625: @progstyle
6626: You should write a stack comment for every deferred word, and put only
6627: XTs into deferred words that conform to this stack effect. Otherwise
6628: it's too difficult to use the deferred word.
6629:
1.44 crook 6630: A deferred word can be used to improve the statistics-gathering example
6631: from @ref{User-defined Defining Words}; rather than edit the
6632: application's source code to change every @code{:} to a @code{my:}, do
6633: this:
6634:
6635: @example
6636: : real: : ; \ retain access to the original
6637: defer : \ redefine as a deferred word
1.132 anton 6638: ' my: IS : \ use special version of :
1.44 crook 6639: \
6640: \ load application here
6641: \
1.132 anton 6642: ' real: IS : \ go back to the original
1.44 crook 6643: @end example
6644:
6645:
1.132 anton 6646: One thing to note is that @code{IS} has special compilation semantics,
6647: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6648:
6649: @example
6650: : set-greet ( xt -- )
1.132 anton 6651: IS greet ;
1.44 crook 6652:
6653: ' greet1 set-greet
6654: @end example
6655:
1.132 anton 6656: In situations where @code{IS} does not fit, use @code{defer!} instead.
6657:
1.69 anton 6658: A deferred word can only inherit execution semantics from the xt
6659: (because that is all that an xt can represent -- for more discussion of
6660: this @pxref{Tokens for Words}); by default it will have default
6661: interpretation and compilation semantics deriving from this execution
6662: semantics. However, you can change the interpretation and compilation
6663: semantics of the deferred word in the usual ways:
1.44 crook 6664:
6665: @example
1.132 anton 6666: : bar .... ; immediate
1.44 crook 6667: Defer fred immediate
6668: Defer jim
6669:
1.132 anton 6670: ' bar IS jim \ jim has default semantics
6671: ' bar IS fred \ fred is immediate
1.44 crook 6672: @end example
6673:
6674: doc-defer
1.132 anton 6675: doc-defer!
1.44 crook 6676: doc-is
1.132 anton 6677: doc-defer@
6678: doc-action-of
1.44 crook 6679: @comment TODO document these: what's defers [is]
6680: doc-defers
6681:
6682: @c Use @code{words-deferred} to see a list of deferred words.
6683:
1.132 anton 6684: Definitions of these words (except @code{defers}) in ANS Forth are
6685: provided in @file{compat/defer.fs}.
1.44 crook 6686:
6687:
1.69 anton 6688: @node Aliases, , Deferred words, Defining Words
1.44 crook 6689: @subsection Aliases
6690: @cindex aliases
1.1 anton 6691:
1.44 crook 6692: The defining word @code{Alias} allows you to define a word by name that
6693: has the same behaviour as some other word. Here are two situation where
6694: this can be useful:
1.1 anton 6695:
1.44 crook 6696: @itemize @bullet
6697: @item
6698: When you want access to a word's definition from a different word list
6699: (for an example of this, see the definition of the @code{Root} word list
6700: in the Gforth source).
6701: @item
6702: When you want to create a synonym; a definition that can be known by
6703: either of two names (for example, @code{THEN} and @code{ENDIF} are
6704: aliases).
6705: @end itemize
1.1 anton 6706:
1.69 anton 6707: Like deferred words, an alias has default compilation and interpretation
6708: semantics at the beginning (not the modifications of the other word),
6709: but you can change them in the usual ways (@code{immediate},
6710: @code{compile-only}). For example:
1.1 anton 6711:
6712: @example
1.44 crook 6713: : foo ... ; immediate
6714:
6715: ' foo Alias bar \ bar is not an immediate word
6716: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6717: @end example
6718:
1.44 crook 6719: Words that are aliases have the same xt, different headers in the
6720: dictionary, and consequently different name tokens (@pxref{Tokens for
6721: Words}) and possibly different immediate flags. An alias can only have
6722: default or immediate compilation semantics; you can define aliases for
6723: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6724:
1.44 crook 6725: doc-alias
1.1 anton 6726:
6727:
1.47 crook 6728: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6729: @section Interpretation and Compilation Semantics
1.26 crook 6730: @cindex semantics, interpretation and compilation
1.1 anton 6731:
1.71 anton 6732: @c !! state and ' are used without explanation
6733: @c example for immediate/compile-only? or is the tutorial enough
6734:
1.26 crook 6735: @cindex interpretation semantics
1.71 anton 6736: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6737: interpreter does when it encounters the word in interpret state. It also
6738: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6739: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6740: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6741: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6742:
1.26 crook 6743: @cindex compilation semantics
1.71 anton 6744: The @dfn{compilation semantics} of a (named) word are what the text
6745: interpreter does when it encounters the word in compile state. It also
6746: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6747: compiles@footnote{In standard terminology, ``appends to the current
6748: definition''.} the compilation semantics of @i{word}.
1.1 anton 6749:
1.26 crook 6750: @cindex execution semantics
6751: The standard also talks about @dfn{execution semantics}. They are used
6752: only for defining the interpretation and compilation semantics of many
6753: words. By default, the interpretation semantics of a word are to
6754: @code{execute} its execution semantics, and the compilation semantics of
6755: a word are to @code{compile,} its execution semantics.@footnote{In
6756: standard terminology: The default interpretation semantics are its
6757: execution semantics; the default compilation semantics are to append its
6758: execution semantics to the execution semantics of the current
6759: definition.}
6760:
1.71 anton 6761: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6762: the text interpreter, ticked, or @code{postpone}d, so they have no
6763: interpretation or compilation semantics. Their behaviour is represented
6764: by their XT (@pxref{Tokens for Words}), and we call it execution
6765: semantics, too.
6766:
1.26 crook 6767: @comment TODO expand, make it co-operate with new sections on text interpreter.
6768:
6769: @cindex immediate words
6770: @cindex compile-only words
6771: You can change the semantics of the most-recently defined word:
6772:
1.44 crook 6773:
1.26 crook 6774: doc-immediate
6775: doc-compile-only
6776: doc-restrict
6777:
1.82 anton 6778: By convention, words with non-default compilation semantics (e.g.,
6779: immediate words) often have names surrounded with brackets (e.g.,
6780: @code{[']}, @pxref{Execution token}).
1.44 crook 6781:
1.26 crook 6782: Note that ticking (@code{'}) a compile-only word gives an error
6783: (``Interpreting a compile-only word'').
1.1 anton 6784:
1.47 crook 6785: @menu
1.67 anton 6786: * Combined words::
1.47 crook 6787: @end menu
1.44 crook 6788:
1.71 anton 6789:
1.48 anton 6790: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6791: @subsection Combined Words
6792: @cindex combined words
6793:
6794: Gforth allows you to define @dfn{combined words} -- words that have an
6795: arbitrary combination of interpretation and compilation semantics.
6796:
1.26 crook 6797: doc-interpret/compile:
1.1 anton 6798:
1.26 crook 6799: This feature was introduced for implementing @code{TO} and @code{S"}. I
6800: recommend that you do not define such words, as cute as they may be:
6801: they make it hard to get at both parts of the word in some contexts.
6802: E.g., assume you want to get an execution token for the compilation
6803: part. Instead, define two words, one that embodies the interpretation
6804: part, and one that embodies the compilation part. Once you have done
6805: that, you can define a combined word with @code{interpret/compile:} for
6806: the convenience of your users.
1.1 anton 6807:
1.26 crook 6808: You might try to use this feature to provide an optimizing
6809: implementation of the default compilation semantics of a word. For
6810: example, by defining:
1.1 anton 6811: @example
1.26 crook 6812: :noname
6813: foo bar ;
6814: :noname
6815: POSTPONE foo POSTPONE bar ;
1.29 crook 6816: interpret/compile: opti-foobar
1.1 anton 6817: @end example
1.26 crook 6818:
1.23 crook 6819: @noindent
1.26 crook 6820: as an optimizing version of:
6821:
1.1 anton 6822: @example
1.26 crook 6823: : foobar
6824: foo bar ;
1.1 anton 6825: @end example
6826:
1.26 crook 6827: Unfortunately, this does not work correctly with @code{[compile]},
6828: because @code{[compile]} assumes that the compilation semantics of all
6829: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6830: opti-foobar} would compile compilation semantics, whereas
6831: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6832:
1.26 crook 6833: @cindex state-smart words (are a bad idea)
1.82 anton 6834: @anchor{state-smartness}
1.29 crook 6835: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6836: by @code{interpret/compile:} (words are state-smart if they check
6837: @code{STATE} during execution). E.g., they would try to code
6838: @code{foobar} like this:
1.1 anton 6839:
1.26 crook 6840: @example
6841: : foobar
6842: STATE @@
6843: IF ( compilation state )
6844: POSTPONE foo POSTPONE bar
6845: ELSE
6846: foo bar
6847: ENDIF ; immediate
6848: @end example
1.1 anton 6849:
1.26 crook 6850: Although this works if @code{foobar} is only processed by the text
6851: interpreter, it does not work in other contexts (like @code{'} or
6852: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6853: for a state-smart word, not for the interpretation semantics of the
6854: original @code{foobar}; when you execute this execution token (directly
6855: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6856: state, the result will not be what you expected (i.e., it will not
6857: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6858: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6859: M. Anton Ertl,
6860: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6861: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6862:
1.26 crook 6863: @cindex defining words with arbitrary semantics combinations
6864: It is also possible to write defining words that define words with
6865: arbitrary combinations of interpretation and compilation semantics. In
6866: general, they look like this:
1.1 anton 6867:
1.26 crook 6868: @example
6869: : def-word
6870: create-interpret/compile
1.29 crook 6871: @i{code1}
1.26 crook 6872: interpretation>
1.29 crook 6873: @i{code2}
1.26 crook 6874: <interpretation
6875: compilation>
1.29 crook 6876: @i{code3}
1.26 crook 6877: <compilation ;
6878: @end example
1.1 anton 6879:
1.29 crook 6880: For a @i{word} defined with @code{def-word}, the interpretation
6881: semantics are to push the address of the body of @i{word} and perform
6882: @i{code2}, and the compilation semantics are to push the address of
6883: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6884: can also be defined like this (except that the defined constants don't
6885: behave correctly when @code{[compile]}d):
1.1 anton 6886:
1.26 crook 6887: @example
6888: : constant ( n "name" -- )
6889: create-interpret/compile
6890: ,
6891: interpretation> ( -- n )
6892: @@
6893: <interpretation
6894: compilation> ( compilation. -- ; run-time. -- n )
6895: @@ postpone literal
6896: <compilation ;
6897: @end example
1.1 anton 6898:
1.44 crook 6899:
1.26 crook 6900: doc-create-interpret/compile
6901: doc-interpretation>
6902: doc-<interpretation
6903: doc-compilation>
6904: doc-<compilation
1.1 anton 6905:
1.44 crook 6906:
1.29 crook 6907: Words defined with @code{interpret/compile:} and
1.26 crook 6908: @code{create-interpret/compile} have an extended header structure that
6909: differs from other words; however, unless you try to access them with
6910: plain address arithmetic, you should not notice this. Words for
6911: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6912: @code{'} @i{word} @code{>body} also gives you the body of a word created
6913: with @code{create-interpret/compile}.
1.1 anton 6914:
1.44 crook 6915:
1.47 crook 6916: @c -------------------------------------------------------------
1.81 anton 6917: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6918: @section Tokens for Words
6919: @cindex tokens for words
6920:
6921: This section describes the creation and use of tokens that represent
6922: words.
6923:
1.71 anton 6924: @menu
6925: * Execution token:: represents execution/interpretation semantics
6926: * Compilation token:: represents compilation semantics
6927: * Name token:: represents named words
6928: @end menu
1.47 crook 6929:
1.71 anton 6930: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6931: @subsection Execution token
1.47 crook 6932:
6933: @cindex xt
6934: @cindex execution token
1.71 anton 6935: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6936: You can use @code{execute} to invoke this behaviour.
1.47 crook 6937:
1.71 anton 6938: @cindex tick (')
6939: You can use @code{'} to get an execution token that represents the
6940: interpretation semantics of a named word:
1.47 crook 6941:
6942: @example
1.97 anton 6943: 5 ' . ( n xt )
6944: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6945: @end example
1.47 crook 6946:
1.71 anton 6947: doc-'
6948:
6949: @code{'} parses at run-time; there is also a word @code{[']} that parses
6950: when it is compiled, and compiles the resulting XT:
6951:
6952: @example
6953: : foo ['] . execute ;
6954: 5 foo
6955: : bar ' execute ; \ by contrast,
6956: 5 bar . \ ' parses "." when bar executes
6957: @end example
6958:
6959: doc-[']
6960:
6961: If you want the execution token of @i{word}, write @code{['] @i{word}}
6962: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6963: @code{'} and @code{[']} behave somewhat unusually by complaining about
6964: compile-only words (because these words have no interpretation
6965: semantics). You might get what you want by using @code{COMP' @i{word}
6966: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6967: token}).
6968:
1.116 anton 6969: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6970: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6971: for the only behaviour the word has (the execution semantics). For
1.116 anton 6972: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6973: would produce if the word was defined anonymously.
6974:
6975: @example
6976: :noname ." hello" ;
6977: execute
1.47 crook 6978: @end example
6979:
1.71 anton 6980: An XT occupies one cell and can be manipulated like any other cell.
6981:
1.47 crook 6982: @cindex code field address
6983: @cindex CFA
1.71 anton 6984: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6985: operations that produce or consume it). For old hands: In Gforth, the
6986: XT is implemented as a code field address (CFA).
6987:
6988: doc-execute
6989: doc-perform
6990:
6991: @node Compilation token, Name token, Execution token, Tokens for Words
6992: @subsection Compilation token
1.47 crook 6993:
6994: @cindex compilation token
1.71 anton 6995: @cindex CT (compilation token)
6996: Gforth represents the compilation semantics of a named word by a
1.47 crook 6997: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6998: @i{xt} is an execution token. The compilation semantics represented by
6999: the compilation token can be performed with @code{execute}, which
7000: consumes the whole compilation token, with an additional stack effect
7001: determined by the represented compilation semantics.
7002:
7003: At present, the @i{w} part of a compilation token is an execution token,
7004: and the @i{xt} part represents either @code{execute} or
7005: @code{compile,}@footnote{Depending upon the compilation semantics of the
7006: word. If the word has default compilation semantics, the @i{xt} will
7007: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7008: @i{xt} will represent @code{execute}.}. However, don't rely on that
7009: knowledge, unless necessary; future versions of Gforth may introduce
7010: unusual compilation tokens (e.g., a compilation token that represents
7011: the compilation semantics of a literal).
7012:
1.71 anton 7013: You can perform the compilation semantics represented by the compilation
7014: token with @code{execute}. You can compile the compilation semantics
7015: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7016: equivalent to @code{postpone @i{word}}.
7017:
7018: doc-[comp']
7019: doc-comp'
7020: doc-postpone,
7021:
7022: @node Name token, , Compilation token, Tokens for Words
7023: @subsection Name token
1.47 crook 7024:
7025: @cindex name token
1.116 anton 7026: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7027: token is an abstract data type that occurs as argument or result of the
7028: words below.
7029:
7030: @c !! put this elswhere?
1.47 crook 7031: @cindex name field address
7032: @cindex NFA
1.116 anton 7033: The closest thing to the nt in older Forth systems is the name field
7034: address (NFA), but there are significant differences: in older Forth
7035: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7036: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7037: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7038: is a link field in the structure identified by the name token, but
7039: searching usually uses a hash table external to these structures; the
7040: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7041: implemented as the address of that count field.
1.47 crook 7042:
7043: doc-find-name
1.116 anton 7044: doc-latest
7045: doc->name
1.47 crook 7046: doc-name>int
7047: doc-name?int
7048: doc-name>comp
7049: doc-name>string
1.109 anton 7050: doc-id.
7051: doc-.name
7052: doc-.id
1.47 crook 7053:
1.81 anton 7054: @c ----------------------------------------------------------
7055: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7056: @section Compiling words
7057: @cindex compiling words
7058: @cindex macros
7059:
7060: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7061: between compilation and run-time. E.g., you can run arbitrary code
7062: between defining words (or for computing data used by defining words
7063: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7064: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7065: running arbitrary code while compiling a colon definition (exception:
7066: you must not allot dictionary space).
7067:
7068: @menu
7069: * Literals:: Compiling data values
7070: * Macros:: Compiling words
7071: @end menu
7072:
7073: @node Literals, Macros, Compiling words, Compiling words
7074: @subsection Literals
7075: @cindex Literals
7076:
7077: The simplest and most frequent example is to compute a literal during
7078: compilation. E.g., the following definition prints an array of strings,
7079: one string per line:
7080:
7081: @example
7082: : .strings ( addr u -- ) \ gforth
7083: 2* cells bounds U+DO
7084: cr i 2@@ type
7085: 2 cells +LOOP ;
7086: @end example
1.81 anton 7087:
1.82 anton 7088: With a simple-minded compiler like Gforth's, this computes @code{2
7089: cells} on every loop iteration. You can compute this value once and for
7090: all at compile time and compile it into the definition like this:
7091:
7092: @example
7093: : .strings ( addr u -- ) \ gforth
7094: 2* cells bounds U+DO
7095: cr i 2@@ type
7096: [ 2 cells ] literal +LOOP ;
7097: @end example
7098:
7099: @code{[} switches the text interpreter to interpret state (you will get
7100: an @code{ok} prompt if you type this example interactively and insert a
7101: newline between @code{[} and @code{]}), so it performs the
7102: interpretation semantics of @code{2 cells}; this computes a number.
7103: @code{]} switches the text interpreter back into compile state. It then
7104: performs @code{Literal}'s compilation semantics, which are to compile
7105: this number into the current word. You can decompile the word with
7106: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7107:
1.82 anton 7108: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7109: *} in this way.
1.81 anton 7110:
1.82 anton 7111: doc-[
7112: doc-]
1.81 anton 7113: doc-literal
7114: doc-]L
1.82 anton 7115:
7116: There are also words for compiling other data types than single cells as
7117: literals:
7118:
1.81 anton 7119: doc-2literal
7120: doc-fliteral
1.82 anton 7121: doc-sliteral
7122:
7123: @cindex colon-sys, passing data across @code{:}
7124: @cindex @code{:}, passing data across
7125: You might be tempted to pass data from outside a colon definition to the
7126: inside on the data stack. This does not work, because @code{:} puhes a
7127: colon-sys, making stuff below unaccessible. E.g., this does not work:
7128:
7129: @example
7130: 5 : foo literal ; \ error: "unstructured"
7131: @end example
7132:
7133: Instead, you have to pass the value in some other way, e.g., through a
7134: variable:
7135:
7136: @example
7137: variable temp
7138: 5 temp !
7139: : foo [ temp @@ ] literal ;
7140: @end example
7141:
7142:
7143: @node Macros, , Literals, Compiling words
7144: @subsection Macros
7145: @cindex Macros
7146: @cindex compiling compilation semantics
7147:
7148: @code{Literal} and friends compile data values into the current
7149: definition. You can also write words that compile other words into the
7150: current definition. E.g.,
7151:
7152: @example
7153: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7154: POSTPONE + ;
7155:
7156: : foo ( n1 n2 -- n )
7157: [ compile-+ ] ;
7158: 1 2 foo .
7159: @end example
7160:
7161: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7162: What happens in this example? @code{Postpone} compiles the compilation
7163: semantics of @code{+} into @code{compile-+}; later the text interpreter
7164: executes @code{compile-+} and thus the compilation semantics of +, which
7165: compile (the execution semantics of) @code{+} into
7166: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7167: should only be executed in compile state, so this example is not
7168: guaranteed to work on all standard systems, but on any decent system it
7169: will work.}
7170:
7171: doc-postpone
7172: doc-[compile]
7173:
7174: Compiling words like @code{compile-+} are usually immediate (or similar)
7175: so you do not have to switch to interpret state to execute them;
7176: mopifying the last example accordingly produces:
7177:
7178: @example
7179: : [compile-+] ( compilation: --; interpretation: -- )
7180: \ compiled code: ( n1 n2 -- n )
7181: POSTPONE + ; immediate
7182:
7183: : foo ( n1 n2 -- n )
7184: [compile-+] ;
7185: 1 2 foo .
7186: @end example
7187:
7188: Immediate compiling words are similar to macros in other languages (in
7189: particular, Lisp). The important differences to macros in, e.g., C are:
7190:
7191: @itemize @bullet
7192:
7193: @item
7194: You use the same language for defining and processing macros, not a
7195: separate preprocessing language and processor.
7196:
7197: @item
7198: Consequently, the full power of Forth is available in macro definitions.
7199: E.g., you can perform arbitrarily complex computations, or generate
7200: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7201: Tutorial}). This power is very useful when writing a parser generators
7202: or other code-generating software.
7203:
7204: @item
7205: Macros defined using @code{postpone} etc. deal with the language at a
7206: higher level than strings; name binding happens at macro definition
7207: time, so you can avoid the pitfalls of name collisions that can happen
7208: in C macros. Of course, Forth is a liberal language and also allows to
7209: shoot yourself in the foot with text-interpreted macros like
7210:
7211: @example
7212: : [compile-+] s" +" evaluate ; immediate
7213: @end example
7214:
7215: Apart from binding the name at macro use time, using @code{evaluate}
7216: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7217: @end itemize
7218:
7219: You may want the macro to compile a number into a word. The word to do
7220: it is @code{literal}, but you have to @code{postpone} it, so its
7221: compilation semantics take effect when the macro is executed, not when
7222: it is compiled:
7223:
7224: @example
7225: : [compile-5] ( -- ) \ compiled code: ( -- n )
7226: 5 POSTPONE literal ; immediate
7227:
7228: : foo [compile-5] ;
7229: foo .
7230: @end example
7231:
7232: You may want to pass parameters to a macro, that the macro should
7233: compile into the current definition. If the parameter is a number, then
7234: you can use @code{postpone literal} (similar for other values).
7235:
7236: If you want to pass a word that is to be compiled, the usual way is to
7237: pass an execution token and @code{compile,} it:
7238:
7239: @example
7240: : twice1 ( xt -- ) \ compiled code: ... -- ...
7241: dup compile, compile, ;
7242:
7243: : 2+ ( n1 -- n2 )
7244: [ ' 1+ twice1 ] ;
7245: @end example
7246:
7247: doc-compile,
7248:
7249: An alternative available in Gforth, that allows you to pass compile-only
7250: words as parameters is to use the compilation token (@pxref{Compilation
7251: token}). The same example in this technique:
7252:
7253: @example
7254: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7255: 2dup 2>r execute 2r> execute ;
7256:
7257: : 2+ ( n1 -- n2 )
7258: [ comp' 1+ twice ] ;
7259: @end example
7260:
7261: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7262: works even if the executed compilation semantics has an effect on the
7263: data stack.
7264:
7265: You can also define complete definitions with these words; this provides
7266: an alternative to using @code{does>} (@pxref{User-defined Defining
7267: Words}). E.g., instead of
7268:
7269: @example
7270: : curry+ ( n1 "name" -- )
7271: CREATE ,
7272: DOES> ( n2 -- n1+n2 )
7273: @@ + ;
7274: @end example
7275:
7276: you could define
7277:
7278: @example
7279: : curry+ ( n1 "name" -- )
7280: \ name execution: ( n2 -- n1+n2 )
7281: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7282:
1.82 anton 7283: -3 curry+ 3-
7284: see 3-
7285: @end example
1.81 anton 7286:
1.82 anton 7287: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7288: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7289:
1.82 anton 7290: This way of writing defining words is sometimes more, sometimes less
7291: convenient than using @code{does>} (@pxref{Advanced does> usage
7292: example}). One advantage of this method is that it can be optimized
7293: better, because the compiler knows that the value compiled with
7294: @code{literal} is fixed, whereas the data associated with a
7295: @code{create}d word can be changed.
1.47 crook 7296:
1.26 crook 7297: @c ----------------------------------------------------------
1.111 anton 7298: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7299: @section The Text Interpreter
7300: @cindex interpreter - outer
7301: @cindex text interpreter
7302: @cindex outer interpreter
1.1 anton 7303:
1.34 anton 7304: @c Should we really describe all these ugly details? IMO the text
7305: @c interpreter should be much cleaner, but that may not be possible within
7306: @c ANS Forth. - anton
1.44 crook 7307: @c nac-> I wanted to explain how it works to show how you can exploit
7308: @c it in your own programs. When I was writing a cross-compiler, figuring out
7309: @c some of these gory details was very helpful to me. None of the textbooks
7310: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7311: @c seems to positively avoid going into too much detail for some of
7312: @c the internals.
1.34 anton 7313:
1.71 anton 7314: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7315: @c it is; for the ugly details, I would prefer another place. I wonder
7316: @c whether we should have a chapter before "Words" that describes some
7317: @c basic concepts referred to in words, and a chapter after "Words" that
7318: @c describes implementation details.
7319:
1.29 crook 7320: The text interpreter@footnote{This is an expanded version of the
7321: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7322: that processes input from the current input device. It is also called
7323: the outer interpreter, in contrast to the inner interpreter
7324: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7325: implementations.
1.27 crook 7326:
1.29 crook 7327: @cindex interpret state
7328: @cindex compile state
7329: The text interpreter operates in one of two states: @dfn{interpret
7330: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7331: aptly-named variable @code{state}.
1.29 crook 7332:
7333: This section starts by describing how the text interpreter behaves when
7334: it is in interpret state, processing input from the user input device --
7335: the keyboard. This is the mode that a Forth system is in after it starts
7336: up.
7337:
7338: @cindex input buffer
7339: @cindex terminal input buffer
7340: The text interpreter works from an area of memory called the @dfn{input
7341: buffer}@footnote{When the text interpreter is processing input from the
7342: keyboard, this area of memory is called the @dfn{terminal input buffer}
7343: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7344: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7345: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7346: leading spaces (called @dfn{delimiters}) then parses a string (a
7347: sequence of non-space characters) until it reaches either a space
7348: character or the end of the buffer. Having parsed a string, it makes two
7349: attempts to process it:
1.27 crook 7350:
1.29 crook 7351: @cindex dictionary
1.27 crook 7352: @itemize @bullet
7353: @item
1.29 crook 7354: It looks for the string in a @dfn{dictionary} of definitions. If the
7355: string is found, the string names a @dfn{definition} (also known as a
7356: @dfn{word}) and the dictionary search returns information that allows
7357: the text interpreter to perform the word's @dfn{interpretation
7358: semantics}. In most cases, this simply means that the word will be
7359: executed.
1.27 crook 7360: @item
7361: If the string is not found in the dictionary, the text interpreter
1.29 crook 7362: attempts to treat it as a number, using the rules described in
7363: @ref{Number Conversion}. If the string represents a legal number in the
7364: current radix, the number is pushed onto a parameter stack (the data
7365: stack for integers, the floating-point stack for floating-point
7366: numbers).
7367: @end itemize
7368:
7369: If both attempts fail, or if the word is found in the dictionary but has
7370: no interpretation semantics@footnote{This happens if the word was
7371: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7372: remainder of the input buffer, issues an error message and waits for
7373: more input. If one of the attempts succeeds, the text interpreter
7374: repeats the parsing process until the whole of the input buffer has been
7375: processed, at which point it prints the status message ``@code{ ok}''
7376: and waits for more input.
7377:
1.71 anton 7378: @c anton: this should be in the input stream subsection (or below it)
7379:
1.29 crook 7380: @cindex parse area
7381: The text interpreter keeps track of its position in the input buffer by
7382: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7383: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7384: of the input buffer. The region from offset @code{>IN @@} to the end of
7385: the input buffer is called the @dfn{parse area}@footnote{In other words,
7386: the text interpreter processes the contents of the input buffer by
7387: parsing strings from the parse area until the parse area is empty.}.
7388: This example shows how @code{>IN} changes as the text interpreter parses
7389: the input buffer:
7390:
7391: @example
7392: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7393: CR ." ->" TYPE ." <-" ; IMMEDIATE
7394:
7395: 1 2 3 remaining + remaining .
7396:
7397: : foo 1 2 3 remaining SWAP remaining ;
7398: @end example
7399:
7400: @noindent
7401: The result is:
7402:
7403: @example
7404: ->+ remaining .<-
7405: ->.<-5 ok
7406:
7407: ->SWAP remaining ;-<
7408: ->;<- ok
7409: @end example
7410:
7411: @cindex parsing words
7412: The value of @code{>IN} can also be modified by a word in the input
7413: buffer that is executed by the text interpreter. This means that a word
7414: can ``trick'' the text interpreter into either skipping a section of the
7415: input buffer@footnote{This is how parsing words work.} or into parsing a
7416: section twice. For example:
1.27 crook 7417:
1.29 crook 7418: @example
1.71 anton 7419: : lat ." <<foo>>" ;
7420: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7421: @end example
7422:
7423: @noindent
7424: When @code{flat} is executed, this output is produced@footnote{Exercise
7425: for the reader: what would happen if the @code{3} were replaced with
7426: @code{4}?}:
7427:
7428: @example
1.71 anton 7429: <<bar>><<foo>>
1.29 crook 7430: @end example
7431:
1.71 anton 7432: This technique can be used to work around some of the interoperability
7433: problems of parsing words. Of course, it's better to avoid parsing
7434: words where possible.
7435:
1.29 crook 7436: @noindent
7437: Two important notes about the behaviour of the text interpreter:
1.27 crook 7438:
7439: @itemize @bullet
7440: @item
7441: It processes each input string to completion before parsing additional
1.29 crook 7442: characters from the input buffer.
7443: @item
7444: It treats the input buffer as a read-only region (and so must your code).
7445: @end itemize
7446:
7447: @noindent
7448: When the text interpreter is in compile state, its behaviour changes in
7449: these ways:
7450:
7451: @itemize @bullet
7452: @item
7453: If a parsed string is found in the dictionary, the text interpreter will
7454: perform the word's @dfn{compilation semantics}. In most cases, this
7455: simply means that the execution semantics of the word will be appended
7456: to the current definition.
1.27 crook 7457: @item
1.29 crook 7458: When a number is encountered, it is compiled into the current definition
7459: (as a literal) rather than being pushed onto a parameter stack.
7460: @item
7461: If an error occurs, @code{state} is modified to put the text interpreter
7462: back into interpret state.
7463: @item
7464: Each time a line is entered from the keyboard, Gforth prints
7465: ``@code{ compiled}'' rather than `` @code{ok}''.
7466: @end itemize
7467:
7468: @cindex text interpreter - input sources
7469: When the text interpreter is using an input device other than the
7470: keyboard, its behaviour changes in these ways:
7471:
7472: @itemize @bullet
7473: @item
7474: When the parse area is empty, the text interpreter attempts to refill
7475: the input buffer from the input source. When the input source is
1.71 anton 7476: exhausted, the input source is set back to the previous input source.
1.29 crook 7477: @item
7478: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7479: time the parse area is emptied.
7480: @item
7481: If an error occurs, the input source is set back to the user input
7482: device.
1.27 crook 7483: @end itemize
1.21 crook 7484:
1.49 anton 7485: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7486:
1.26 crook 7487: doc->in
1.27 crook 7488: doc-source
7489:
1.26 crook 7490: doc-tib
7491: doc-#tib
1.1 anton 7492:
1.44 crook 7493:
1.26 crook 7494: @menu
1.67 anton 7495: * Input Sources::
7496: * Number Conversion::
7497: * Interpret/Compile states::
7498: * Interpreter Directives::
1.26 crook 7499: @end menu
1.1 anton 7500:
1.29 crook 7501: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7502: @subsection Input Sources
7503: @cindex input sources
7504: @cindex text interpreter - input sources
7505:
1.44 crook 7506: By default, the text interpreter processes input from the user input
1.29 crook 7507: device (the keyboard) when Forth starts up. The text interpreter can
7508: process input from any of these sources:
7509:
7510: @itemize @bullet
7511: @item
7512: The user input device -- the keyboard.
7513: @item
7514: A file, using the words described in @ref{Forth source files}.
7515: @item
7516: A block, using the words described in @ref{Blocks}.
7517: @item
7518: A text string, using @code{evaluate}.
7519: @end itemize
7520:
7521: A program can identify the current input device from the values of
7522: @code{source-id} and @code{blk}.
7523:
1.44 crook 7524:
1.29 crook 7525: doc-source-id
7526: doc-blk
7527:
7528: doc-save-input
7529: doc-restore-input
7530:
7531: doc-evaluate
1.111 anton 7532: doc-query
1.1 anton 7533:
1.29 crook 7534:
1.44 crook 7535:
1.29 crook 7536: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7537: @subsection Number Conversion
7538: @cindex number conversion
7539: @cindex double-cell numbers, input format
7540: @cindex input format for double-cell numbers
7541: @cindex single-cell numbers, input format
7542: @cindex input format for single-cell numbers
7543: @cindex floating-point numbers, input format
7544: @cindex input format for floating-point numbers
1.1 anton 7545:
1.29 crook 7546: This section describes the rules that the text interpreter uses when it
7547: tries to convert a string into a number.
1.1 anton 7548:
1.26 crook 7549: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7550: number base@footnote{For example, 0-9 when the number base is decimal or
7551: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7552:
1.26 crook 7553: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7554:
1.29 crook 7555: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7556: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7557:
1.26 crook 7558: Let * represent any number of instances of the previous character
7559: (including none).
1.1 anton 7560:
1.26 crook 7561: Let any other character represent itself.
1.1 anton 7562:
1.29 crook 7563: @noindent
1.26 crook 7564: Now, the conversion rules are:
1.21 crook 7565:
1.26 crook 7566: @itemize @bullet
7567: @item
7568: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7569: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7570: @item
7571: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7572: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7573: arithmetic. Examples are -45 -5681 -0
7574: @item
7575: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7576: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7577: (all three of these represent the same number).
1.26 crook 7578: @item
7579: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7580: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7581: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7582: -34.65 (all three of these represent the same number).
1.26 crook 7583: @item
1.29 crook 7584: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7585: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7586: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7587: number) +12.E-4
1.26 crook 7588: @end itemize
1.1 anton 7589:
1.26 crook 7590: By default, the number base used for integer number conversion is given
1.35 anton 7591: by the contents of the variable @code{base}. Note that a lot of
7592: confusion can result from unexpected values of @code{base}. If you
7593: change @code{base} anywhere, make sure to save the old value and restore
7594: it afterwards. In general I recommend keeping @code{base} decimal, and
7595: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7596:
1.29 crook 7597: doc-dpl
1.26 crook 7598: doc-base
7599: doc-hex
7600: doc-decimal
1.1 anton 7601:
1.26 crook 7602: @cindex '-prefix for character strings
7603: @cindex &-prefix for decimal numbers
1.133 ! anton 7604: @cindex #-prefix for decimal numbers
1.26 crook 7605: @cindex %-prefix for binary numbers
7606: @cindex $-prefix for hexadecimal numbers
1.133 ! anton 7607: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7608: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7609: prefix@footnote{Some Forth implementations provide a similar scheme by
7610: implementing @code{$} etc. as parsing words that process the subsequent
7611: number in the input stream and push it onto the stack. For example, see
7612: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7613: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7614: is required between the prefix and the number.} before the first digit
1.133 ! anton 7615: of an (integer) number. The following prefixes are supported:
1.1 anton 7616:
1.26 crook 7617: @itemize @bullet
7618: @item
1.35 anton 7619: @code{&} -- decimal
1.26 crook 7620: @item
1.133 ! anton 7621: @code{#} -- decimal
! 7622: @item
1.35 anton 7623: @code{%} -- binary
1.26 crook 7624: @item
1.35 anton 7625: @code{$} -- hexadecimal
1.26 crook 7626: @item
1.133 ! anton 7627: @code{0x} -- hexadecimal, if base<33.
! 7628: @item
! 7629: @code{'} -- numeric value (e.g., ASCII code) of next character; an
! 7630: optional @code{'} may be present after the character.
1.26 crook 7631: @end itemize
1.1 anton 7632:
1.26 crook 7633: Here are some examples, with the equivalent decimal number shown after
7634: in braces:
1.1 anton 7635:
1.26 crook 7636: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 ! anton 7637: 'A (65),
! 7638: -'a' (-97),
1.26 crook 7639: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7640:
1.26 crook 7641: @cindex number conversion - traps for the unwary
1.29 crook 7642: @noindent
1.26 crook 7643: Number conversion has a number of traps for the unwary:
1.1 anton 7644:
1.26 crook 7645: @itemize @bullet
7646: @item
7647: You cannot determine the current number base using the code sequence
1.35 anton 7648: @code{base @@ .} -- the number base is always 10 in the current number
7649: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7650: @item
7651: If the number base is set to a value greater than 14 (for example,
7652: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7653: it to be intepreted as either a single-precision integer or a
7654: floating-point number (Gforth treats it as an integer). The ambiguity
7655: can be resolved by explicitly stating the sign of the mantissa and/or
7656: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7657: ambiguity arises; either representation will be treated as a
7658: floating-point number.
7659: @item
1.29 crook 7660: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7661: It is used to specify file types.
7662: @item
1.72 anton 7663: ANS Forth requires the @code{.} of a double-precision number to be the
7664: final character in the string. Gforth allows the @code{.} to be
7665: anywhere after the first digit.
1.26 crook 7666: @item
7667: The number conversion process does not check for overflow.
7668: @item
1.72 anton 7669: In an ANS Forth program @code{base} is required to be decimal when
7670: converting floating-point numbers. In Gforth, number conversion to
7671: floating-point numbers always uses base &10, irrespective of the value
7672: of @code{base}.
1.26 crook 7673: @end itemize
1.1 anton 7674:
1.49 anton 7675: You can read numbers into your programs with the words described in
7676: @ref{Input}.
1.1 anton 7677:
1.82 anton 7678: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7679: @subsection Interpret/Compile states
7680: @cindex Interpret/Compile states
1.1 anton 7681:
1.29 crook 7682: A standard program is not permitted to change @code{state}
7683: explicitly. However, it can change @code{state} implicitly, using the
7684: words @code{[} and @code{]}. When @code{[} is executed it switches
7685: @code{state} to interpret state, and therefore the text interpreter
7686: starts interpreting. When @code{]} is executed it switches @code{state}
7687: to compile state and therefore the text interpreter starts
1.44 crook 7688: compiling. The most common usage for these words is for switching into
7689: interpret state and back from within a colon definition; this technique
1.49 anton 7690: can be used to compile a literal (for an example, @pxref{Literals}) or
7691: for conditional compilation (for an example, @pxref{Interpreter
7692: Directives}).
1.44 crook 7693:
1.35 anton 7694:
7695: @c This is a bad example: It's non-standard, and it's not necessary.
7696: @c However, I can't think of a good example for switching into compile
7697: @c state when there is no current word (@code{state}-smart words are not a
7698: @c good reason). So maybe we should use an example for switching into
7699: @c interpret @code{state} in a colon def. - anton
1.44 crook 7700: @c nac-> I agree. I started out by putting in the example, then realised
7701: @c that it was non-ANS, so wrote more words around it. I hope this
7702: @c re-written version is acceptable to you. I do want to keep the example
7703: @c as it is helpful for showing what is and what is not portable, particularly
7704: @c where it outlaws a style in common use.
7705:
1.72 anton 7706: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7707: @c that, we can also show what's not. In any case, I have written a
7708: @c section Compiling Words which also deals with [ ].
1.35 anton 7709:
1.95 anton 7710: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7711:
1.95 anton 7712: @c @code{[} and @code{]} also give you the ability to switch into compile
7713: @c state and back, but we cannot think of any useful Standard application
7714: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7715:
7716: @c @example
7717: @c : AA ." this is A" ;
7718: @c : BB ." this is B" ;
7719: @c : CC ." this is C" ;
7720:
7721: @c create table ] aa bb cc [
7722:
7723: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7724: @c cells table + @@ execute ;
7725: @c @end example
7726:
7727: @c This example builds a jump table; @code{0 go} will display ``@code{this
7728: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7729: @c defining @code{table} like this:
7730:
7731: @c @example
7732: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7733: @c @end example
7734:
7735: @c The problem with this code is that the definition of @code{table} is not
7736: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7737: @c @i{may} work on systems where code space and data space co-incide, the
7738: @c Standard only allows data space to be assigned for a @code{CREATE}d
7739: @c word. In addition, the Standard only allows @code{@@} to access data
7740: @c space, whilst this example is using it to access code space. The only
7741: @c portable, Standard way to build this table is to build it in data space,
7742: @c like this:
7743:
7744: @c @example
7745: @c create table ' aa , ' bb , ' cc ,
7746: @c @end example
1.29 crook 7747:
1.95 anton 7748: @c doc-state
1.44 crook 7749:
1.29 crook 7750:
1.82 anton 7751: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7752: @subsection Interpreter Directives
7753: @cindex interpreter directives
1.72 anton 7754: @cindex conditional compilation
1.1 anton 7755:
1.29 crook 7756: These words are usually used in interpret state; typically to control
7757: which parts of a source file are processed by the text
1.26 crook 7758: interpreter. There are only a few ANS Forth Standard words, but Gforth
7759: supplements these with a rich set of immediate control structure words
7760: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7761: used in compile state (@pxref{Control Structures}). Typical usages:
7762:
7763: @example
1.72 anton 7764: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7765: .
7766: .
1.72 anton 7767: HAVE-ASSEMBLER [IF]
1.29 crook 7768: : ASSEMBLER-FEATURE
7769: ...
7770: ;
7771: [ENDIF]
7772: .
7773: .
7774: : SEE
7775: ... \ general-purpose SEE code
1.72 anton 7776: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7777: ... \ assembler-specific SEE code
7778: [ [ENDIF] ]
7779: ;
7780: @end example
1.1 anton 7781:
1.44 crook 7782:
1.26 crook 7783: doc-[IF]
7784: doc-[ELSE]
7785: doc-[THEN]
7786: doc-[ENDIF]
1.1 anton 7787:
1.26 crook 7788: doc-[IFDEF]
7789: doc-[IFUNDEF]
1.1 anton 7790:
1.26 crook 7791: doc-[?DO]
7792: doc-[DO]
7793: doc-[FOR]
7794: doc-[LOOP]
7795: doc-[+LOOP]
7796: doc-[NEXT]
1.1 anton 7797:
1.26 crook 7798: doc-[BEGIN]
7799: doc-[UNTIL]
7800: doc-[AGAIN]
7801: doc-[WHILE]
7802: doc-[REPEAT]
1.1 anton 7803:
1.27 crook 7804:
1.26 crook 7805: @c -------------------------------------------------------------
1.111 anton 7806: @node The Input Stream, Word Lists, The Text Interpreter, Words
7807: @section The Input Stream
7808: @cindex input stream
7809:
7810: @c !! integrate this better with the "Text Interpreter" section
7811: The text interpreter reads from the input stream, which can come from
7812: several sources (@pxref{Input Sources}). Some words, in particular
7813: defining words, but also words like @code{'}, read parameters from the
7814: input stream instead of from the stack.
7815:
7816: Such words are called parsing words, because they parse the input
7817: stream. Parsing words are hard to use in other words, because it is
7818: hard to pass program-generated parameters through the input stream.
7819: They also usually have an unintuitive combination of interpretation and
7820: compilation semantics when implemented naively, leading to various
7821: approaches that try to produce a more intuitive behaviour
7822: (@pxref{Combined words}).
7823:
7824: It should be obvious by now that parsing words are a bad idea. If you
7825: want to implement a parsing word for convenience, also provide a factor
7826: of the word that does not parse, but takes the parameters on the stack.
7827: To implement the parsing word on top if it, you can use the following
7828: words:
7829:
7830: @c anton: these belong in the input stream section
7831: doc-parse
7832: doc-parse-word
7833: doc-name
7834: doc-word
7835: doc-\"-parse
7836: doc-refill
7837:
7838: Conversely, if you have the bad luck (or lack of foresight) to have to
7839: deal with parsing words without having such factors, how do you pass a
7840: string that is not in the input stream to it?
7841:
7842: doc-execute-parsing
7843:
7844: If you want to run a parsing word on a file, the following word should
7845: help:
7846:
7847: doc-execute-parsing-file
7848:
7849: @c -------------------------------------------------------------
7850: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7851: @section Word Lists
7852: @cindex word lists
1.32 anton 7853: @cindex header space
1.1 anton 7854:
1.36 anton 7855: A wordlist is a list of named words; you can add new words and look up
7856: words by name (and you can remove words in a restricted way with
7857: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7858:
7859: @cindex search order stack
7860: The text interpreter searches the wordlists present in the search order
7861: (a stack of wordlists), from the top to the bottom. Within each
7862: wordlist, the search starts conceptually at the newest word; i.e., if
7863: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7864:
1.26 crook 7865: @cindex compilation word list
1.36 anton 7866: New words are added to the @dfn{compilation wordlist} (aka current
7867: wordlist).
1.1 anton 7868:
1.36 anton 7869: @cindex wid
7870: A word list is identified by a cell-sized word list identifier (@i{wid})
7871: in much the same way as a file is identified by a file handle. The
7872: numerical value of the wid has no (portable) meaning, and might change
7873: from session to session.
1.1 anton 7874:
1.29 crook 7875: The ANS Forth ``Search order'' word set is intended to provide a set of
7876: low-level tools that allow various different schemes to be
1.74 anton 7877: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7878: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7879: Forth.
1.1 anton 7880:
1.27 crook 7881: @comment TODO: locals section refers to here, saying that every word list (aka
7882: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7883: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7884:
1.45 crook 7885: @comment TODO: document markers, reveal, tables, mappedwordlist
7886:
7887: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7888: @comment word from the source files, rather than some alias.
1.44 crook 7889:
1.26 crook 7890: doc-forth-wordlist
7891: doc-definitions
7892: doc-get-current
7893: doc-set-current
7894: doc-get-order
1.45 crook 7895: doc---gforthman-set-order
1.26 crook 7896: doc-wordlist
1.30 anton 7897: doc-table
1.79 anton 7898: doc->order
1.36 anton 7899: doc-previous
1.26 crook 7900: doc-also
1.45 crook 7901: doc---gforthman-forth
1.26 crook 7902: doc-only
1.45 crook 7903: doc---gforthman-order
1.15 anton 7904:
1.26 crook 7905: doc-find
7906: doc-search-wordlist
1.15 anton 7907:
1.26 crook 7908: doc-words
7909: doc-vlist
1.44 crook 7910: @c doc-words-deferred
1.1 anton 7911:
1.74 anton 7912: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7913: doc-root
7914: doc-vocabulary
7915: doc-seal
7916: doc-vocs
7917: doc-current
7918: doc-context
1.1 anton 7919:
1.44 crook 7920:
1.26 crook 7921: @menu
1.75 anton 7922: * Vocabularies::
1.67 anton 7923: * Why use word lists?::
1.75 anton 7924: * Word list example::
1.26 crook 7925: @end menu
7926:
1.75 anton 7927: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7928: @subsection Vocabularies
7929: @cindex Vocabularies, detailed explanation
7930:
7931: Here is an example of creating and using a new wordlist using ANS
7932: Forth words:
7933:
7934: @example
7935: wordlist constant my-new-words-wordlist
7936: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7937:
7938: \ add it to the search order
7939: also my-new-words
7940:
7941: \ alternatively, add it to the search order and make it
7942: \ the compilation word list
7943: also my-new-words definitions
7944: \ type "order" to see the problem
7945: @end example
7946:
7947: The problem with this example is that @code{order} has no way to
7948: associate the name @code{my-new-words} with the wid of the word list (in
7949: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7950: that has no associated name). There is no Standard way of associating a
7951: name with a wid.
7952:
7953: In Gforth, this example can be re-coded using @code{vocabulary}, which
7954: associates a name with a wid:
7955:
7956: @example
7957: vocabulary my-new-words
7958:
7959: \ add it to the search order
7960: also my-new-words
7961:
7962: \ alternatively, add it to the search order and make it
7963: \ the compilation word list
7964: my-new-words definitions
7965: \ type "order" to see that the problem is solved
7966: @end example
7967:
7968:
7969: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7970: @subsection Why use word lists?
7971: @cindex word lists - why use them?
7972:
1.74 anton 7973: Here are some reasons why people use wordlists:
1.26 crook 7974:
7975: @itemize @bullet
1.74 anton 7976:
7977: @c anton: Gforth's hashing implementation makes the search speed
7978: @c independent from the number of words. But it is linear with the number
7979: @c of wordlists that have to be searched, so in effect using more wordlists
7980: @c actually slows down compilation.
7981:
7982: @c @item
7983: @c To improve compilation speed by reducing the number of header space
7984: @c entries that must be searched. This is achieved by creating a new
7985: @c word list that contains all of the definitions that are used in the
7986: @c definition of a Forth system but which would not usually be used by
7987: @c programs running on that system. That word list would be on the search
7988: @c list when the Forth system was compiled but would be removed from the
7989: @c search list for normal operation. This can be a useful technique for
7990: @c low-performance systems (for example, 8-bit processors in embedded
7991: @c systems) but is unlikely to be necessary in high-performance desktop
7992: @c systems.
7993:
1.26 crook 7994: @item
7995: To prevent a set of words from being used outside the context in which
7996: they are valid. Two classic examples of this are an integrated editor
7997: (all of the edit commands are defined in a separate word list; the
7998: search order is set to the editor word list when the editor is invoked;
7999: the old search order is restored when the editor is terminated) and an
8000: integrated assembler (the op-codes for the machine are defined in a
8001: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8002:
8003: @item
8004: To organize the words of an application or library into a user-visible
8005: set (in @code{forth-wordlist} or some other common wordlist) and a set
8006: of helper words used just for the implementation (hidden in a separate
1.75 anton 8007: wordlist). This keeps @code{words}' output smaller, separates
8008: implementation and interface, and reduces the chance of name conflicts
8009: within the common wordlist.
1.74 anton 8010:
1.26 crook 8011: @item
8012: To prevent a name-space clash between multiple definitions with the same
8013: name. For example, when building a cross-compiler you might have a word
8014: @code{IF} that generates conditional code for your target system. By
8015: placing this definition in a different word list you can control whether
8016: the host system's @code{IF} or the target system's @code{IF} get used in
8017: any particular context by controlling the order of the word lists on the
8018: search order stack.
1.74 anton 8019:
1.26 crook 8020: @end itemize
1.1 anton 8021:
1.74 anton 8022: The downsides of using wordlists are:
8023:
8024: @itemize
8025:
8026: @item
8027: Debugging becomes more cumbersome.
8028:
8029: @item
8030: Name conflicts worked around with wordlists are still there, and you
8031: have to arrange the search order carefully to get the desired results;
8032: if you forget to do that, you get hard-to-find errors (as in any case
8033: where you read the code differently from the compiler; @code{see} can
1.75 anton 8034: help seeing which of several possible words the name resolves to in such
8035: cases). @code{See} displays just the name of the words, not what
8036: wordlist they belong to, so it might be misleading. Using unique names
8037: is a better approach to avoid name conflicts.
1.74 anton 8038:
8039: @item
8040: You have to explicitly undo any changes to the search order. In many
8041: cases it would be more convenient if this happened implicitly. Gforth
8042: currently does not provide such a feature, but it may do so in the
8043: future.
8044: @end itemize
8045:
8046:
1.75 anton 8047: @node Word list example, , Why use word lists?, Word Lists
8048: @subsection Word list example
8049: @cindex word lists - example
1.1 anton 8050:
1.74 anton 8051: The following example is from the
8052: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8053: garbage collector} and uses wordlists to separate public words from
8054: helper words:
8055:
8056: @example
8057: get-current ( wid )
8058: vocabulary garbage-collector also garbage-collector definitions
8059: ... \ define helper words
8060: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8061: ... \ define the public (i.e., API) words
8062: \ they can refer to the helper words
8063: previous \ restore original search order (helper words become invisible)
8064: @end example
8065:
1.26 crook 8066: @c -------------------------------------------------------------
8067: @node Environmental Queries, Files, Word Lists, Words
8068: @section Environmental Queries
8069: @cindex environmental queries
1.21 crook 8070:
1.26 crook 8071: ANS Forth introduced the idea of ``environmental queries'' as a way
8072: for a program running on a system to determine certain characteristics of the system.
8073: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8074:
1.32 anton 8075: The Standard requires that the header space used for environmental queries
8076: be distinct from the header space used for definitions.
1.21 crook 8077:
1.26 crook 8078: Typically, environmental queries are supported by creating a set of
1.29 crook 8079: definitions in a word list that is @i{only} used during environmental
1.26 crook 8080: queries; that is what Gforth does. There is no Standard way of adding
8081: definitions to the set of recognised environmental queries, but any
8082: implementation that supports the loading of optional word sets must have
8083: some mechanism for doing this (after loading the word set, the
8084: associated environmental query string must return @code{true}). In
8085: Gforth, the word list used to honour environmental queries can be
8086: manipulated just like any other word list.
1.21 crook 8087:
1.44 crook 8088:
1.26 crook 8089: doc-environment?
8090: doc-environment-wordlist
1.21 crook 8091:
1.26 crook 8092: doc-gforth
8093: doc-os-class
1.21 crook 8094:
1.44 crook 8095:
1.26 crook 8096: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8097: returning two items on the stack, querying it using @code{environment?}
8098: will return an additional item; the @code{true} flag that shows that the
8099: string was recognised.
1.21 crook 8100:
1.26 crook 8101: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8102:
1.26 crook 8103: Here are some examples of using environmental queries:
1.21 crook 8104:
1.26 crook 8105: @example
8106: s" address-unit-bits" environment? 0=
8107: [IF]
8108: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8109: [ELSE]
8110: drop \ ensure balanced stack effect
1.26 crook 8111: [THEN]
1.21 crook 8112:
1.75 anton 8113: \ this might occur in the prelude of a standard program that uses THROW
8114: s" exception" environment? [IF]
8115: 0= [IF]
8116: : throw abort" exception thrown" ;
8117: [THEN]
8118: [ELSE] \ we don't know, so make sure
8119: : throw abort" exception thrown" ;
8120: [THEN]
1.21 crook 8121:
1.26 crook 8122: s" gforth" environment? [IF] .( Gforth version ) TYPE
8123: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8124:
8125: \ a program using v*
8126: s" gforth" environment? [IF]
8127: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8128: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8129: >r swap 2swap swap 0e r> 0 ?DO
8130: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8131: LOOP
8132: 2drop 2drop ;
8133: [THEN]
8134: [ELSE] \
8135: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8136: ...
8137: [THEN]
1.26 crook 8138: @end example
1.21 crook 8139:
1.26 crook 8140: Here is an example of adding a definition to the environment word list:
1.21 crook 8141:
1.26 crook 8142: @example
8143: get-current environment-wordlist set-current
8144: true constant block
8145: true constant block-ext
8146: set-current
8147: @end example
1.21 crook 8148:
1.26 crook 8149: You can see what definitions are in the environment word list like this:
1.21 crook 8150:
1.26 crook 8151: @example
1.79 anton 8152: environment-wordlist >order words previous
1.26 crook 8153: @end example
1.21 crook 8154:
8155:
1.26 crook 8156: @c -------------------------------------------------------------
8157: @node Files, Blocks, Environmental Queries, Words
8158: @section Files
1.28 crook 8159: @cindex files
8160: @cindex I/O - file-handling
1.21 crook 8161:
1.26 crook 8162: Gforth provides facilities for accessing files that are stored in the
8163: host operating system's file-system. Files that are processed by Gforth
8164: can be divided into two categories:
1.21 crook 8165:
1.23 crook 8166: @itemize @bullet
8167: @item
1.29 crook 8168: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8169: @item
1.29 crook 8170: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8171: @end itemize
8172:
8173: @menu
1.48 anton 8174: * Forth source files::
8175: * General files::
8176: * Search Paths::
1.26 crook 8177: @end menu
8178:
8179: @c -------------------------------------------------------------
8180: @node Forth source files, General files, Files, Files
8181: @subsection Forth source files
8182: @cindex including files
8183: @cindex Forth source files
1.21 crook 8184:
1.26 crook 8185: The simplest way to interpret the contents of a file is to use one of
8186: these two formats:
1.21 crook 8187:
1.26 crook 8188: @example
8189: include mysource.fs
8190: s" mysource.fs" included
8191: @end example
1.21 crook 8192:
1.75 anton 8193: You usually want to include a file only if it is not included already
1.26 crook 8194: (by, say, another source file). In that case, you can use one of these
1.45 crook 8195: three formats:
1.21 crook 8196:
1.26 crook 8197: @example
8198: require mysource.fs
8199: needs mysource.fs
8200: s" mysource.fs" required
8201: @end example
1.21 crook 8202:
1.26 crook 8203: @cindex stack effect of included files
8204: @cindex including files, stack effect
1.45 crook 8205: It is good practice to write your source files such that interpreting them
8206: does not change the stack. Source files designed in this way can be used with
1.26 crook 8207: @code{required} and friends without complications. For example:
1.21 crook 8208:
1.26 crook 8209: @example
1.75 anton 8210: 1024 require foo.fs drop
1.26 crook 8211: @end example
1.21 crook 8212:
1.75 anton 8213: Here you want to pass the argument 1024 (e.g., a buffer size) to
8214: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8215: ), which allows its use with @code{require}. Of course with such
8216: parameters to required files, you have to ensure that the first
8217: @code{require} fits for all uses (i.e., @code{require} it early in the
8218: master load file).
1.44 crook 8219:
1.26 crook 8220: doc-include-file
8221: doc-included
1.28 crook 8222: doc-included?
1.26 crook 8223: doc-include
8224: doc-required
8225: doc-require
8226: doc-needs
1.75 anton 8227: @c doc-init-included-files @c internal
8228: doc-sourcefilename
8229: doc-sourceline#
1.44 crook 8230:
1.26 crook 8231: A definition in ANS Forth for @code{required} is provided in
8232: @file{compat/required.fs}.
1.21 crook 8233:
1.26 crook 8234: @c -------------------------------------------------------------
8235: @node General files, Search Paths, Forth source files, Files
8236: @subsection General files
8237: @cindex general files
8238: @cindex file-handling
1.21 crook 8239:
1.75 anton 8240: Files are opened/created by name and type. The following file access
8241: methods (FAMs) are recognised:
1.44 crook 8242:
1.75 anton 8243: @cindex fam (file access method)
1.26 crook 8244: doc-r/o
8245: doc-r/w
8246: doc-w/o
8247: doc-bin
1.1 anton 8248:
1.44 crook 8249:
1.26 crook 8250: When a file is opened/created, it returns a file identifier,
1.29 crook 8251: @i{wfileid} that is used for all other file commands. All file
8252: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8253: successful operation and an implementation-defined non-zero value in the
8254: case of an error.
1.21 crook 8255:
1.44 crook 8256:
1.26 crook 8257: doc-open-file
8258: doc-create-file
1.21 crook 8259:
1.26 crook 8260: doc-close-file
8261: doc-delete-file
8262: doc-rename-file
8263: doc-read-file
8264: doc-read-line
8265: doc-write-file
8266: doc-write-line
8267: doc-emit-file
8268: doc-flush-file
1.21 crook 8269:
1.26 crook 8270: doc-file-status
8271: doc-file-position
8272: doc-reposition-file
8273: doc-file-size
8274: doc-resize-file
1.21 crook 8275:
1.93 anton 8276: doc-slurp-file
8277: doc-slurp-fid
1.112 anton 8278: doc-stdin
8279: doc-stdout
8280: doc-stderr
1.44 crook 8281:
1.26 crook 8282: @c ---------------------------------------------------------
1.48 anton 8283: @node Search Paths, , General files, Files
1.26 crook 8284: @subsection Search Paths
8285: @cindex path for @code{included}
8286: @cindex file search path
8287: @cindex @code{include} search path
8288: @cindex search path for files
1.21 crook 8289:
1.26 crook 8290: If you specify an absolute filename (i.e., a filename starting with
8291: @file{/} or @file{~}, or with @file{:} in the second position (as in
8292: @samp{C:...})) for @code{included} and friends, that file is included
8293: just as you would expect.
1.21 crook 8294:
1.75 anton 8295: If the filename starts with @file{./}, this refers to the directory that
8296: the present file was @code{included} from. This allows files to include
8297: other files relative to their own position (irrespective of the current
8298: working directory or the absolute position). This feature is essential
8299: for libraries consisting of several files, where a file may include
8300: other files from the library. It corresponds to @code{#include "..."}
8301: in C. If the current input source is not a file, @file{.} refers to the
8302: directory of the innermost file being included, or, if there is no file
8303: being included, to the current working directory.
8304:
8305: For relative filenames (not starting with @file{./}), Gforth uses a
8306: search path similar to Forth's search order (@pxref{Word Lists}). It
8307: tries to find the given filename in the directories present in the path,
8308: and includes the first one it finds. There are separate search paths for
8309: Forth source files and general files. If the search path contains the
8310: directory @file{.}, this refers to the directory of the current file, or
8311: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8312:
1.26 crook 8313: Use @file{~+} to refer to the current working directory (as in the
8314: @code{bash}).
1.1 anton 8315:
1.75 anton 8316: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8317:
1.48 anton 8318: @menu
1.75 anton 8319: * Source Search Paths::
1.48 anton 8320: * General Search Paths::
8321: @end menu
8322:
1.26 crook 8323: @c ---------------------------------------------------------
1.75 anton 8324: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8325: @subsubsection Source Search Paths
8326: @cindex search path control, source files
1.5 anton 8327:
1.26 crook 8328: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8329: Gforth}). You can display it and change it using @code{fpath} in
8330: combination with the general path handling words.
1.5 anton 8331:
1.75 anton 8332: doc-fpath
8333: @c the functionality of the following words is easily available through
8334: @c fpath and the general path words. The may go away.
8335: @c doc-.fpath
8336: @c doc-fpath+
8337: @c doc-fpath=
8338: @c doc-open-fpath-file
1.44 crook 8339:
8340: @noindent
1.26 crook 8341: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8342:
1.26 crook 8343: @example
1.75 anton 8344: fpath path= /usr/lib/forth/|./
1.26 crook 8345: require timer.fs
8346: @end example
1.5 anton 8347:
1.75 anton 8348:
1.26 crook 8349: @c ---------------------------------------------------------
1.75 anton 8350: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8351: @subsubsection General Search Paths
1.75 anton 8352: @cindex search path control, source files
1.5 anton 8353:
1.26 crook 8354: Your application may need to search files in several directories, like
8355: @code{included} does. To facilitate this, Gforth allows you to define
8356: and use your own search paths, by providing generic equivalents of the
8357: Forth search path words:
1.5 anton 8358:
1.75 anton 8359: doc-open-path-file
8360: doc-path-allot
8361: doc-clear-path
8362: doc-also-path
1.26 crook 8363: doc-.path
8364: doc-path+
8365: doc-path=
1.5 anton 8366:
1.75 anton 8367: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8368:
1.75 anton 8369: Here's an example of creating an empty search path:
8370: @c
1.26 crook 8371: @example
1.75 anton 8372: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8373: @end example
1.5 anton 8374:
1.26 crook 8375: @c -------------------------------------------------------------
8376: @node Blocks, Other I/O, Files, Words
8377: @section Blocks
1.28 crook 8378: @cindex I/O - blocks
8379: @cindex blocks
8380:
8381: When you run Gforth on a modern desk-top computer, it runs under the
8382: control of an operating system which provides certain services. One of
8383: these services is @var{file services}, which allows Forth source code
8384: and data to be stored in files and read into Gforth (@pxref{Files}).
8385:
8386: Traditionally, Forth has been an important programming language on
8387: systems where it has interfaced directly to the underlying hardware with
8388: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8389: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8390:
8391: A block is a 1024-byte data area, which can be used to hold data or
8392: Forth source code. No structure is imposed on the contents of the
8393: block. A block is identified by its number; blocks are numbered
8394: contiguously from 1 to an implementation-defined maximum.
8395:
8396: A typical system that used blocks but no operating system might use a
8397: single floppy-disk drive for mass storage, with the disks formatted to
8398: provide 256-byte sectors. Blocks would be implemented by assigning the
8399: first four sectors of the disk to block 1, the second four sectors to
8400: block 2 and so on, up to the limit of the capacity of the disk. The disk
8401: would not contain any file system information, just the set of blocks.
8402:
1.29 crook 8403: @cindex blocks file
1.28 crook 8404: On systems that do provide file services, blocks are typically
1.29 crook 8405: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8406: file}. The size of the blocks file will be an exact multiple of 1024
8407: bytes, corresponding to the number of blocks it contains. This is the
8408: mechanism that Gforth uses.
8409:
1.29 crook 8410: @cindex @file{blocks.fb}
1.75 anton 8411: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8412: having specified a blocks file, Gforth defaults to the blocks file
8413: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8414: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8415:
1.29 crook 8416: @cindex block buffers
1.28 crook 8417: When you read and write blocks under program control, Gforth uses a
1.29 crook 8418: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8419: not used when you use @code{load} to interpret the contents of a block.
8420:
1.75 anton 8421: The behaviour of the block buffers is analagous to that of a cache.
8422: Each block buffer has three states:
1.28 crook 8423:
8424: @itemize @bullet
8425: @item
8426: Unassigned
8427: @item
8428: Assigned-clean
8429: @item
8430: Assigned-dirty
8431: @end itemize
8432:
1.29 crook 8433: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8434: block, the block (specified by its block number) must be assigned to a
8435: block buffer.
8436:
8437: The assignment of a block to a block buffer is performed by @code{block}
8438: or @code{buffer}. Use @code{block} when you wish to modify the existing
8439: contents of a block. Use @code{buffer} when you don't care about the
8440: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8441: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8442: with the particular block is already stored in a block buffer due to an
8443: earlier @code{block} command, @code{buffer} will return that block
8444: buffer and the existing contents of the block will be
8445: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8446: block buffer for the block.}.
1.28 crook 8447:
1.47 crook 8448: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8449: @code{buffer}, that block buffer becomes the @i{current block
8450: buffer}. Data may only be manipulated (read or written) within the
8451: current block buffer.
1.47 crook 8452:
8453: When the contents of the current block buffer has been modified it is
1.48 anton 8454: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8455: either abandon the changes (by doing nothing) or mark the block as
8456: changed (assigned-dirty), using @code{update}. Using @code{update} does
8457: not change the blocks file; it simply changes a block buffer's state to
8458: @i{assigned-dirty}. The block will be written implicitly when it's
8459: buffer is needed for another block, or explicitly by @code{flush} or
8460: @code{save-buffers}.
8461:
8462: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8463: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8464: @code{flush}.
1.28 crook 8465:
1.29 crook 8466: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8467: algorithm to assign a block buffer to a block. That means that any
8468: particular block can only be assigned to one specific block buffer,
1.29 crook 8469: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8470: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8471: the new block immediately. If it is @i{assigned-dirty} its current
8472: contents are written back to the blocks file on disk before it is
1.28 crook 8473: allocated to the new block.
8474:
8475: Although no structure is imposed on the contents of a block, it is
8476: traditional to display the contents as 16 lines each of 64 characters. A
8477: block provides a single, continuous stream of input (for example, it
8478: acts as a single parse area) -- there are no end-of-line characters
8479: within a block, and no end-of-file character at the end of a
8480: block. There are two consequences of this:
1.26 crook 8481:
1.28 crook 8482: @itemize @bullet
8483: @item
8484: The last character of one line wraps straight into the first character
8485: of the following line
8486: @item
8487: The word @code{\} -- comment to end of line -- requires special
8488: treatment; in the context of a block it causes all characters until the
8489: end of the current 64-character ``line'' to be ignored.
8490: @end itemize
8491:
8492: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8493: the current blocks file will be extended to the appropriate size and the
1.28 crook 8494: block buffer will be initialised with spaces.
8495:
1.47 crook 8496: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8497: for details) but doesn't encourage the use of blocks; the mechanism is
8498: only provided for backward compatibility -- ANS Forth requires blocks to
8499: be available when files are.
1.28 crook 8500:
8501: Common techniques that are used when working with blocks include:
8502:
8503: @itemize @bullet
8504: @item
8505: A screen editor that allows you to edit blocks without leaving the Forth
8506: environment.
8507: @item
8508: Shadow screens; where every code block has an associated block
8509: containing comments (for example: code in odd block numbers, comments in
8510: even block numbers). Typically, the block editor provides a convenient
8511: mechanism to toggle between code and comments.
8512: @item
8513: Load blocks; a single block (typically block 1) contains a number of
8514: @code{thru} commands which @code{load} the whole of the application.
8515: @end itemize
1.26 crook 8516:
1.29 crook 8517: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8518: integrated into a Forth programming environment.
1.26 crook 8519:
8520: @comment TODO what about errors on open-blocks?
1.44 crook 8521:
1.26 crook 8522: doc-open-blocks
8523: doc-use
1.75 anton 8524: doc-block-offset
1.26 crook 8525: doc-get-block-fid
8526: doc-block-position
1.28 crook 8527:
1.75 anton 8528: doc-list
1.28 crook 8529: doc-scr
8530:
1.45 crook 8531: doc---gforthman-block
1.28 crook 8532: doc-buffer
8533:
1.75 anton 8534: doc-empty-buffers
8535: doc-empty-buffer
1.26 crook 8536: doc-update
1.28 crook 8537: doc-updated?
1.26 crook 8538: doc-save-buffers
1.75 anton 8539: doc-save-buffer
1.26 crook 8540: doc-flush
1.28 crook 8541:
1.26 crook 8542: doc-load
8543: doc-thru
8544: doc-+load
8545: doc-+thru
1.45 crook 8546: doc---gforthman--->
1.26 crook 8547: doc-block-included
8548:
1.44 crook 8549:
1.26 crook 8550: @c -------------------------------------------------------------
1.126 pazsan 8551: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8552: @section Other I/O
1.28 crook 8553: @cindex I/O - keyboard and display
1.26 crook 8554:
8555: @menu
8556: * Simple numeric output:: Predefined formats
8557: * Formatted numeric output:: Formatted (pictured) output
8558: * String Formats:: How Forth stores strings in memory
1.67 anton 8559: * Displaying characters and strings:: Other stuff
1.26 crook 8560: * Input:: Input
1.112 anton 8561: * Pipes:: How to create your own pipes
1.26 crook 8562: @end menu
8563:
8564: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8565: @subsection Simple numeric output
1.28 crook 8566: @cindex numeric output - simple/free-format
1.5 anton 8567:
1.26 crook 8568: The simplest output functions are those that display numbers from the
8569: data or floating-point stacks. Floating-point output is always displayed
8570: using base 10. Numbers displayed from the data stack use the value stored
8571: in @code{base}.
1.5 anton 8572:
1.44 crook 8573:
1.26 crook 8574: doc-.
8575: doc-dec.
8576: doc-hex.
8577: doc-u.
8578: doc-.r
8579: doc-u.r
8580: doc-d.
8581: doc-ud.
8582: doc-d.r
8583: doc-ud.r
8584: doc-f.
8585: doc-fe.
8586: doc-fs.
1.111 anton 8587: doc-f.rdp
1.44 crook 8588:
1.26 crook 8589: Examples of printing the number 1234.5678E23 in the different floating-point output
8590: formats are shown below:
1.5 anton 8591:
8592: @example
1.26 crook 8593: f. 123456779999999000000000000.
8594: fe. 123.456779999999E24
8595: fs. 1.23456779999999E26
1.5 anton 8596: @end example
8597:
8598:
1.26 crook 8599: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8600: @subsection Formatted numeric output
1.28 crook 8601: @cindex formatted numeric output
1.26 crook 8602: @cindex pictured numeric output
1.28 crook 8603: @cindex numeric output - formatted
1.26 crook 8604:
1.29 crook 8605: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8606: output} for formatted printing of integers. In this technique, digits
8607: are extracted from the number (using the current output radix defined by
8608: @code{base}), converted to ASCII codes and appended to a string that is
8609: built in a scratch-pad area of memory (@pxref{core-idef,
8610: Implementation-defined options, Implementation-defined
8611: options}). Arbitrary characters can be appended to the string during the
8612: extraction process. The completed string is specified by an address
8613: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8614: under program control.
1.5 anton 8615:
1.75 anton 8616: All of the integer output words described in the previous section
8617: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8618: numeric output.
1.5 anton 8619:
1.47 crook 8620: Three important things to remember about pictured numeric output:
1.5 anton 8621:
1.26 crook 8622: @itemize @bullet
8623: @item
1.28 crook 8624: It always operates on double-precision numbers; to display a
1.49 anton 8625: single-precision number, convert it first (for ways of doing this
8626: @pxref{Double precision}).
1.26 crook 8627: @item
1.28 crook 8628: It always treats the double-precision number as though it were
8629: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8630: @item
8631: The string is built up from right to left; least significant digit first.
8632: @end itemize
1.5 anton 8633:
1.44 crook 8634:
1.26 crook 8635: doc-<#
1.47 crook 8636: doc-<<#
1.26 crook 8637: doc-#
8638: doc-#s
8639: doc-hold
8640: doc-sign
8641: doc-#>
1.47 crook 8642: doc-#>>
1.5 anton 8643:
1.26 crook 8644: doc-represent
1.111 anton 8645: doc-f>str-rdp
8646: doc-f>buf-rdp
1.5 anton 8647:
1.44 crook 8648:
8649: @noindent
1.26 crook 8650: Here are some examples of using pictured numeric output:
1.5 anton 8651:
8652: @example
1.26 crook 8653: : my-u. ( u -- )
8654: \ Simplest use of pns.. behaves like Standard u.
8655: 0 \ convert to unsigned double
1.75 anton 8656: <<# \ start conversion
1.26 crook 8657: #s \ convert all digits
8658: #> \ complete conversion
1.75 anton 8659: TYPE SPACE \ display, with trailing space
8660: #>> ; \ release hold area
1.5 anton 8661:
1.26 crook 8662: : cents-only ( u -- )
8663: 0 \ convert to unsigned double
1.75 anton 8664: <<# \ start conversion
1.26 crook 8665: # # \ convert two least-significant digits
8666: #> \ complete conversion, discard other digits
1.75 anton 8667: TYPE SPACE \ display, with trailing space
8668: #>> ; \ release hold area
1.5 anton 8669:
1.26 crook 8670: : dollars-and-cents ( u -- )
8671: 0 \ convert to unsigned double
1.75 anton 8672: <<# \ start conversion
1.26 crook 8673: # # \ convert two least-significant digits
8674: [char] . hold \ insert decimal point
8675: #s \ convert remaining digits
8676: [char] $ hold \ append currency symbol
8677: #> \ complete conversion
1.75 anton 8678: TYPE SPACE \ display, with trailing space
8679: #>> ; \ release hold area
1.5 anton 8680:
1.26 crook 8681: : my-. ( n -- )
8682: \ handling negatives.. behaves like Standard .
8683: s>d \ convert to signed double
8684: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8685: <<# \ start conversion
1.26 crook 8686: #s \ convert all digits
8687: rot sign \ get at sign byte, append "-" if needed
8688: #> \ complete conversion
1.75 anton 8689: TYPE SPACE \ display, with trailing space
8690: #>> ; \ release hold area
1.5 anton 8691:
1.26 crook 8692: : account. ( n -- )
1.75 anton 8693: \ accountants don't like minus signs, they use parentheses
1.26 crook 8694: \ for negative numbers
8695: s>d \ convert to signed double
8696: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8697: <<# \ start conversion
1.26 crook 8698: 2 pick \ get copy of sign byte
8699: 0< IF [char] ) hold THEN \ right-most character of output
8700: #s \ convert all digits
8701: rot \ get at sign byte
8702: 0< IF [char] ( hold THEN
8703: #> \ complete conversion
1.75 anton 8704: TYPE SPACE \ display, with trailing space
8705: #>> ; \ release hold area
8706:
1.5 anton 8707: @end example
8708:
1.26 crook 8709: Here are some examples of using these words:
1.5 anton 8710:
8711: @example
1.26 crook 8712: 1 my-u. 1
8713: hex -1 my-u. decimal FFFFFFFF
8714: 1 cents-only 01
8715: 1234 cents-only 34
8716: 2 dollars-and-cents $0.02
8717: 1234 dollars-and-cents $12.34
8718: 123 my-. 123
8719: -123 my. -123
8720: 123 account. 123
8721: -456 account. (456)
1.5 anton 8722: @end example
8723:
8724:
1.26 crook 8725: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8726: @subsection String Formats
1.27 crook 8727: @cindex strings - see character strings
8728: @cindex character strings - formats
1.28 crook 8729: @cindex I/O - see character strings
1.75 anton 8730: @cindex counted strings
8731:
8732: @c anton: this does not really belong here; maybe the memory section,
8733: @c or the principles chapter
1.26 crook 8734:
1.27 crook 8735: Forth commonly uses two different methods for representing character
8736: strings:
1.26 crook 8737:
8738: @itemize @bullet
8739: @item
8740: @cindex address of counted string
1.45 crook 8741: @cindex counted string
1.29 crook 8742: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8743: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8744: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8745: memory.
8746: @item
1.29 crook 8747: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8748: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8749: first byte of the string.
8750: @end itemize
8751:
8752: ANS Forth encourages the use of the second format when representing
1.75 anton 8753: strings.
1.26 crook 8754:
1.44 crook 8755:
1.26 crook 8756: doc-count
8757:
1.44 crook 8758:
1.49 anton 8759: For words that move, copy and search for strings see @ref{Memory
8760: Blocks}. For words that display characters and strings see
8761: @ref{Displaying characters and strings}.
1.26 crook 8762:
8763: @node Displaying characters and strings, Input, String Formats, Other I/O
8764: @subsection Displaying characters and strings
1.27 crook 8765: @cindex characters - compiling and displaying
8766: @cindex character strings - compiling and displaying
1.26 crook 8767:
8768: This section starts with a glossary of Forth words and ends with a set
8769: of examples.
8770:
1.44 crook 8771:
1.26 crook 8772: doc-bl
8773: doc-space
8774: doc-spaces
8775: doc-emit
8776: doc-toupper
8777: doc-."
8778: doc-.(
1.98 anton 8779: doc-.\"
1.26 crook 8780: doc-type
1.44 crook 8781: doc-typewhite
1.26 crook 8782: doc-cr
1.27 crook 8783: @cindex cursor control
1.26 crook 8784: doc-at-xy
8785: doc-page
8786: doc-s"
1.98 anton 8787: doc-s\"
1.26 crook 8788: doc-c"
8789: doc-char
8790: doc-[char]
8791:
1.44 crook 8792:
8793: @noindent
1.26 crook 8794: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8795:
8796: @example
1.26 crook 8797: .( text-1)
8798: : my-word
8799: ." text-2" cr
8800: .( text-3)
8801: ;
8802:
8803: ." text-4"
8804:
8805: : my-char
8806: [char] ALPHABET emit
8807: char emit
8808: ;
1.5 anton 8809: @end example
8810:
1.26 crook 8811: When you load this code into Gforth, the following output is generated:
1.5 anton 8812:
1.26 crook 8813: @example
1.30 anton 8814: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8815: @end example
1.5 anton 8816:
1.26 crook 8817: @itemize @bullet
8818: @item
8819: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8820: is an immediate word; it behaves in the same way whether it is used inside
8821: or outside a colon definition.
8822: @item
8823: Message @code{text-4} is displayed because of Gforth's added interpretation
8824: semantics for @code{."}.
8825: @item
1.29 crook 8826: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8827: performs the compilation semantics for @code{."} within the definition of
8828: @code{my-word}.
8829: @end itemize
1.5 anton 8830:
1.26 crook 8831: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8832:
1.26 crook 8833: @example
1.30 anton 8834: @kbd{my-word @key{RET}} text-2
1.26 crook 8835: ok
1.30 anton 8836: @kbd{my-char fred @key{RET}} Af ok
8837: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8838: @end example
1.5 anton 8839:
8840: @itemize @bullet
8841: @item
1.26 crook 8842: Message @code{text-2} is displayed because of the run-time behaviour of
8843: @code{."}.
8844: @item
8845: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8846: on the stack at run-time. @code{emit} always displays the character
8847: when @code{my-char} is executed.
8848: @item
8849: @code{char} parses a string at run-time and the second @code{emit} displays
8850: the first character of the string.
1.5 anton 8851: @item
1.26 crook 8852: If you type @code{see my-char} you can see that @code{[char]} discarded
8853: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8854: definition of @code{my-char}.
1.5 anton 8855: @end itemize
8856:
8857:
8858:
1.112 anton 8859: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8860: @subsection Input
8861: @cindex input
1.28 crook 8862: @cindex I/O - see input
8863: @cindex parsing a string
1.5 anton 8864:
1.49 anton 8865: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8866:
1.27 crook 8867: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8868: @comment then index them
1.27 crook 8869:
1.44 crook 8870:
1.27 crook 8871: doc-key
8872: doc-key?
1.45 crook 8873: doc-ekey
8874: doc-ekey?
8875: doc-ekey>char
1.26 crook 8876: doc->number
8877: doc->float
8878: doc-accept
1.109 anton 8879: doc-edit-line
1.27 crook 8880: doc-pad
8881: @comment obsolescent words..
8882: doc-convert
1.26 crook 8883: doc-expect
1.27 crook 8884: doc-span
1.5 anton 8885:
8886:
1.112 anton 8887: @node Pipes, , Input, Other I/O
8888: @subsection Pipes
8889: @cindex pipes, creating your own
8890:
8891: In addition to using Gforth in pipes created by other processes
8892: (@pxref{Gforth in pipes}), you can create your own pipe with
8893: @code{open-pipe}, and read from or write to it.
8894:
8895: doc-open-pipe
8896: doc-close-pipe
8897:
8898: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8899: you don't catch this exception, Gforth will catch it and exit, usually
8900: silently (@pxref{Gforth in pipes}). Since you probably do not want
8901: this, you should wrap a @code{catch} or @code{try} block around the code
8902: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8903: problem yourself, and then return to regular processing.
8904:
8905: doc-broken-pipe-error
8906:
8907:
1.121 anton 8908: @node OS command line arguments, Locals, Other I/O, Words
8909: @section OS command line arguments
8910: @cindex OS command line arguments
8911: @cindex command line arguments, OS
8912: @cindex arguments, OS command line
8913:
8914: The usual way to pass arguments to Gforth programs on the command line
8915: is via the @option{-e} option, e.g.
8916:
8917: @example
8918: gforth -e "123 456" foo.fs -e bye
8919: @end example
8920:
8921: However, you may want to interpret the command-line arguments directly.
8922: In that case, you can access the (image-specific) command-line arguments
1.123 anton 8923: through @code{next-arg}:
1.121 anton 8924:
1.123 anton 8925: doc-next-arg
1.121 anton 8926:
1.123 anton 8927: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 8928:
8929: @example
8930: : echo ( -- )
1.122 anton 8931: begin
1.123 anton 8932: next-arg 2dup 0 0 d<> while
8933: type space
8934: repeat
8935: 2drop ;
1.121 anton 8936:
8937: echo cr bye
8938: @end example
8939:
8940: This can be invoked with
8941:
8942: @example
8943: gforth echo.fs hello world
8944: @end example
1.123 anton 8945:
8946: and it will print
8947:
8948: @example
8949: hello world
8950: @end example
8951:
8952: The next lower level of dealing with the OS command line are the
8953: following words:
8954:
8955: doc-arg
8956: doc-shift-args
8957:
8958: Finally, at the lowest level Gforth provides the following words:
8959:
8960: doc-argc
8961: doc-argv
1.121 anton 8962:
1.78 anton 8963: @c -------------------------------------------------------------
1.126 pazsan 8964: @node Locals, Structures, OS command line arguments, Words
1.78 anton 8965: @section Locals
8966: @cindex locals
8967:
8968: Local variables can make Forth programming more enjoyable and Forth
8969: programs easier to read. Unfortunately, the locals of ANS Forth are
8970: laden with restrictions. Therefore, we provide not only the ANS Forth
8971: locals wordset, but also our own, more powerful locals wordset (we
8972: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 8973:
1.78 anton 8974: The ideas in this section have also been published in M. Anton Ertl,
8975: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8976: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 8977:
8978: @menu
1.78 anton 8979: * Gforth locals::
8980: * ANS Forth locals::
1.5 anton 8981: @end menu
8982:
1.78 anton 8983: @node Gforth locals, ANS Forth locals, Locals, Locals
8984: @subsection Gforth locals
8985: @cindex Gforth locals
8986: @cindex locals, Gforth style
1.5 anton 8987:
1.78 anton 8988: Locals can be defined with
1.44 crook 8989:
1.78 anton 8990: @example
8991: @{ local1 local2 ... -- comment @}
8992: @end example
8993: or
8994: @example
8995: @{ local1 local2 ... @}
8996: @end example
1.5 anton 8997:
1.78 anton 8998: E.g.,
8999: @example
9000: : max @{ n1 n2 -- n3 @}
9001: n1 n2 > if
9002: n1
9003: else
9004: n2
9005: endif ;
9006: @end example
1.44 crook 9007:
1.78 anton 9008: The similarity of locals definitions with stack comments is intended. A
9009: locals definition often replaces the stack comment of a word. The order
9010: of the locals corresponds to the order in a stack comment and everything
9011: after the @code{--} is really a comment.
1.77 anton 9012:
1.78 anton 9013: This similarity has one disadvantage: It is too easy to confuse locals
9014: declarations with stack comments, causing bugs and making them hard to
9015: find. However, this problem can be avoided by appropriate coding
9016: conventions: Do not use both notations in the same program. If you do,
9017: they should be distinguished using additional means, e.g. by position.
1.77 anton 9018:
1.78 anton 9019: @cindex types of locals
9020: @cindex locals types
9021: The name of the local may be preceded by a type specifier, e.g.,
9022: @code{F:} for a floating point value:
1.5 anton 9023:
1.78 anton 9024: @example
9025: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9026: \ complex multiplication
9027: Ar Br f* Ai Bi f* f-
9028: Ar Bi f* Ai Br f* f+ ;
9029: @end example
1.44 crook 9030:
1.78 anton 9031: @cindex flavours of locals
9032: @cindex locals flavours
9033: @cindex value-flavoured locals
9034: @cindex variable-flavoured locals
9035: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9036: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9037: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9038: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9039: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9040: produces its address (which becomes invalid when the variable's scope is
9041: left). E.g., the standard word @code{emit} can be defined in terms of
9042: @code{type} like this:
1.5 anton 9043:
1.78 anton 9044: @example
9045: : emit @{ C^ char* -- @}
9046: char* 1 type ;
9047: @end example
1.5 anton 9048:
1.78 anton 9049: @cindex default type of locals
9050: @cindex locals, default type
9051: A local without type specifier is a @code{W:} local. Both flavours of
9052: locals are initialized with values from the data or FP stack.
1.44 crook 9053:
1.78 anton 9054: Currently there is no way to define locals with user-defined data
9055: structures, but we are working on it.
1.5 anton 9056:
1.78 anton 9057: Gforth allows defining locals everywhere in a colon definition. This
9058: poses the following questions:
1.5 anton 9059:
1.78 anton 9060: @menu
9061: * Where are locals visible by name?::
9062: * How long do locals live?::
9063: * Locals programming style::
9064: * Locals implementation::
9065: @end menu
1.44 crook 9066:
1.78 anton 9067: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9068: @subsubsection Where are locals visible by name?
9069: @cindex locals visibility
9070: @cindex visibility of locals
9071: @cindex scope of locals
1.5 anton 9072:
1.78 anton 9073: Basically, the answer is that locals are visible where you would expect
9074: it in block-structured languages, and sometimes a little longer. If you
9075: want to restrict the scope of a local, enclose its definition in
9076: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9077:
9078:
1.78 anton 9079: doc-scope
9080: doc-endscope
1.5 anton 9081:
9082:
1.78 anton 9083: These words behave like control structure words, so you can use them
9084: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9085: arbitrary ways.
1.77 anton 9086:
1.78 anton 9087: If you want a more exact answer to the visibility question, here's the
9088: basic principle: A local is visible in all places that can only be
9089: reached through the definition of the local@footnote{In compiler
9090: construction terminology, all places dominated by the definition of the
9091: local.}. In other words, it is not visible in places that can be reached
9092: without going through the definition of the local. E.g., locals defined
9093: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9094: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9095: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9096:
1.78 anton 9097: The reasoning behind this solution is: We want to have the locals
9098: visible as long as it is meaningful. The user can always make the
9099: visibility shorter by using explicit scoping. In a place that can
9100: only be reached through the definition of a local, the meaning of a
9101: local name is clear. In other places it is not: How is the local
9102: initialized at the control flow path that does not contain the
9103: definition? Which local is meant, if the same name is defined twice in
9104: two independent control flow paths?
1.77 anton 9105:
1.78 anton 9106: This should be enough detail for nearly all users, so you can skip the
9107: rest of this section. If you really must know all the gory details and
9108: options, read on.
1.77 anton 9109:
1.78 anton 9110: In order to implement this rule, the compiler has to know which places
9111: are unreachable. It knows this automatically after @code{AHEAD},
9112: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9113: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9114: compiler that the control flow never reaches that place. If
9115: @code{UNREACHABLE} is not used where it could, the only consequence is
9116: that the visibility of some locals is more limited than the rule above
9117: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9118: lie to the compiler), buggy code will be produced.
1.77 anton 9119:
1.5 anton 9120:
1.78 anton 9121: doc-unreachable
1.5 anton 9122:
1.23 crook 9123:
1.78 anton 9124: Another problem with this rule is that at @code{BEGIN}, the compiler
9125: does not know which locals will be visible on the incoming
9126: back-edge. All problems discussed in the following are due to this
9127: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9128: loops as examples; the discussion also applies to @code{?DO} and other
9129: loops). Perhaps the most insidious example is:
1.26 crook 9130: @example
1.78 anton 9131: AHEAD
9132: BEGIN
9133: x
9134: [ 1 CS-ROLL ] THEN
9135: @{ x @}
9136: ...
9137: UNTIL
1.26 crook 9138: @end example
1.23 crook 9139:
1.78 anton 9140: This should be legal according to the visibility rule. The use of
9141: @code{x} can only be reached through the definition; but that appears
9142: textually below the use.
9143:
9144: From this example it is clear that the visibility rules cannot be fully
9145: implemented without major headaches. Our implementation treats common
9146: cases as advertised and the exceptions are treated in a safe way: The
9147: compiler makes a reasonable guess about the locals visible after a
9148: @code{BEGIN}; if it is too pessimistic, the
9149: user will get a spurious error about the local not being defined; if the
9150: compiler is too optimistic, it will notice this later and issue a
9151: warning. In the case above the compiler would complain about @code{x}
9152: being undefined at its use. You can see from the obscure examples in
9153: this section that it takes quite unusual control structures to get the
9154: compiler into trouble, and even then it will often do fine.
1.23 crook 9155:
1.78 anton 9156: If the @code{BEGIN} is reachable from above, the most optimistic guess
9157: is that all locals visible before the @code{BEGIN} will also be
9158: visible after the @code{BEGIN}. This guess is valid for all loops that
9159: are entered only through the @code{BEGIN}, in particular, for normal
9160: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9161: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9162: compiler. When the branch to the @code{BEGIN} is finally generated by
9163: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9164: warns the user if it was too optimistic:
1.26 crook 9165: @example
1.78 anton 9166: IF
9167: @{ x @}
9168: BEGIN
9169: \ x ?
9170: [ 1 cs-roll ] THEN
9171: ...
9172: UNTIL
1.26 crook 9173: @end example
1.23 crook 9174:
1.78 anton 9175: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9176: optimistically assumes that it lives until the @code{THEN}. It notices
9177: this difference when it compiles the @code{UNTIL} and issues a
9178: warning. The user can avoid the warning, and make sure that @code{x}
9179: is not used in the wrong area by using explicit scoping:
9180: @example
9181: IF
9182: SCOPE
9183: @{ x @}
9184: ENDSCOPE
9185: BEGIN
9186: [ 1 cs-roll ] THEN
9187: ...
9188: UNTIL
9189: @end example
1.23 crook 9190:
1.78 anton 9191: Since the guess is optimistic, there will be no spurious error messages
9192: about undefined locals.
1.44 crook 9193:
1.78 anton 9194: If the @code{BEGIN} is not reachable from above (e.g., after
9195: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9196: optimistic guess, as the locals visible after the @code{BEGIN} may be
9197: defined later. Therefore, the compiler assumes that no locals are
9198: visible after the @code{BEGIN}. However, the user can use
9199: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9200: visible at the BEGIN as at the point where the top control-flow stack
9201: item was created.
1.23 crook 9202:
1.44 crook 9203:
1.78 anton 9204: doc-assume-live
1.26 crook 9205:
1.23 crook 9206:
1.78 anton 9207: @noindent
9208: E.g.,
9209: @example
9210: @{ x @}
9211: AHEAD
9212: ASSUME-LIVE
9213: BEGIN
9214: x
9215: [ 1 CS-ROLL ] THEN
9216: ...
9217: UNTIL
9218: @end example
1.44 crook 9219:
1.78 anton 9220: Other cases where the locals are defined before the @code{BEGIN} can be
9221: handled by inserting an appropriate @code{CS-ROLL} before the
9222: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9223: behind the @code{ASSUME-LIVE}).
1.23 crook 9224:
1.78 anton 9225: Cases where locals are defined after the @code{BEGIN} (but should be
9226: visible immediately after the @code{BEGIN}) can only be handled by
9227: rearranging the loop. E.g., the ``most insidious'' example above can be
9228: arranged into:
9229: @example
9230: BEGIN
9231: @{ x @}
9232: ... 0=
9233: WHILE
9234: x
9235: REPEAT
9236: @end example
1.44 crook 9237:
1.78 anton 9238: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9239: @subsubsection How long do locals live?
9240: @cindex locals lifetime
9241: @cindex lifetime of locals
1.23 crook 9242:
1.78 anton 9243: The right answer for the lifetime question would be: A local lives at
9244: least as long as it can be accessed. For a value-flavoured local this
9245: means: until the end of its visibility. However, a variable-flavoured
9246: local could be accessed through its address far beyond its visibility
9247: scope. Ultimately, this would mean that such locals would have to be
9248: garbage collected. Since this entails un-Forth-like implementation
9249: complexities, I adopted the same cowardly solution as some other
9250: languages (e.g., C): The local lives only as long as it is visible;
9251: afterwards its address is invalid (and programs that access it
9252: afterwards are erroneous).
1.23 crook 9253:
1.78 anton 9254: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9255: @subsubsection Locals programming style
9256: @cindex locals programming style
9257: @cindex programming style, locals
1.23 crook 9258:
1.78 anton 9259: The freedom to define locals anywhere has the potential to change
9260: programming styles dramatically. In particular, the need to use the
9261: return stack for intermediate storage vanishes. Moreover, all stack
9262: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9263: determined arguments) can be eliminated: If the stack items are in the
9264: wrong order, just write a locals definition for all of them; then
9265: write the items in the order you want.
1.23 crook 9266:
1.78 anton 9267: This seems a little far-fetched and eliminating stack manipulations is
9268: unlikely to become a conscious programming objective. Still, the number
9269: of stack manipulations will be reduced dramatically if local variables
9270: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9271: a traditional implementation of @code{max}).
1.23 crook 9272:
1.78 anton 9273: This shows one potential benefit of locals: making Forth programs more
9274: readable. Of course, this benefit will only be realized if the
9275: programmers continue to honour the principle of factoring instead of
9276: using the added latitude to make the words longer.
1.23 crook 9277:
1.78 anton 9278: @cindex single-assignment style for locals
9279: Using @code{TO} can and should be avoided. Without @code{TO},
9280: every value-flavoured local has only a single assignment and many
9281: advantages of functional languages apply to Forth. I.e., programs are
9282: easier to analyse, to optimize and to read: It is clear from the
9283: definition what the local stands for, it does not turn into something
9284: different later.
1.23 crook 9285:
1.78 anton 9286: E.g., a definition using @code{TO} might look like this:
9287: @example
9288: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9289: u1 u2 min 0
9290: ?do
9291: addr1 c@@ addr2 c@@ -
9292: ?dup-if
9293: unloop exit
9294: then
9295: addr1 char+ TO addr1
9296: addr2 char+ TO addr2
9297: loop
9298: u1 u2 - ;
1.26 crook 9299: @end example
1.78 anton 9300: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9301: every loop iteration. @code{strcmp} is a typical example of the
9302: readability problems of using @code{TO}. When you start reading
9303: @code{strcmp}, you think that @code{addr1} refers to the start of the
9304: string. Only near the end of the loop you realize that it is something
9305: else.
1.23 crook 9306:
1.78 anton 9307: This can be avoided by defining two locals at the start of the loop that
9308: are initialized with the right value for the current iteration.
9309: @example
9310: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9311: addr1 addr2
9312: u1 u2 min 0
9313: ?do @{ s1 s2 @}
9314: s1 c@@ s2 c@@ -
9315: ?dup-if
9316: unloop exit
9317: then
9318: s1 char+ s2 char+
9319: loop
9320: 2drop
9321: u1 u2 - ;
9322: @end example
9323: Here it is clear from the start that @code{s1} has a different value
9324: in every loop iteration.
1.23 crook 9325:
1.78 anton 9326: @node Locals implementation, , Locals programming style, Gforth locals
9327: @subsubsection Locals implementation
9328: @cindex locals implementation
9329: @cindex implementation of locals
1.23 crook 9330:
1.78 anton 9331: @cindex locals stack
9332: Gforth uses an extra locals stack. The most compelling reason for
9333: this is that the return stack is not float-aligned; using an extra stack
9334: also eliminates the problems and restrictions of using the return stack
9335: as locals stack. Like the other stacks, the locals stack grows toward
9336: lower addresses. A few primitives allow an efficient implementation:
9337:
9338:
9339: doc-@local#
9340: doc-f@local#
9341: doc-laddr#
9342: doc-lp+!#
9343: doc-lp!
9344: doc->l
9345: doc-f>l
9346:
9347:
9348: In addition to these primitives, some specializations of these
9349: primitives for commonly occurring inline arguments are provided for
9350: efficiency reasons, e.g., @code{@@local0} as specialization of
9351: @code{@@local#} for the inline argument 0. The following compiling words
9352: compile the right specialized version, or the general version, as
9353: appropriate:
1.23 crook 9354:
1.5 anton 9355:
1.107 dvdkhlng 9356: @c doc-compile-@local
9357: @c doc-compile-f@local
1.78 anton 9358: doc-compile-lp+!
1.5 anton 9359:
9360:
1.78 anton 9361: Combinations of conditional branches and @code{lp+!#} like
9362: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9363: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9364:
1.78 anton 9365: A special area in the dictionary space is reserved for keeping the
9366: local variable names. @code{@{} switches the dictionary pointer to this
9367: area and @code{@}} switches it back and generates the locals
9368: initializing code. @code{W:} etc.@ are normal defining words. This
9369: special area is cleared at the start of every colon definition.
1.5 anton 9370:
1.78 anton 9371: @cindex word list for defining locals
9372: A special feature of Gforth's dictionary is used to implement the
9373: definition of locals without type specifiers: every word list (aka
9374: vocabulary) has its own methods for searching
9375: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9376: with a special search method: When it is searched for a word, it
9377: actually creates that word using @code{W:}. @code{@{} changes the search
9378: order to first search the word list containing @code{@}}, @code{W:} etc.,
9379: and then the word list for defining locals without type specifiers.
1.5 anton 9380:
1.78 anton 9381: The lifetime rules support a stack discipline within a colon
9382: definition: The lifetime of a local is either nested with other locals
9383: lifetimes or it does not overlap them.
1.23 crook 9384:
1.78 anton 9385: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9386: pointer manipulation is generated. Between control structure words
9387: locals definitions can push locals onto the locals stack. @code{AGAIN}
9388: is the simplest of the other three control flow words. It has to
9389: restore the locals stack depth of the corresponding @code{BEGIN}
9390: before branching. The code looks like this:
9391: @format
9392: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9393: @code{branch} <begin>
9394: @end format
1.26 crook 9395:
1.78 anton 9396: @code{UNTIL} is a little more complicated: If it branches back, it
9397: must adjust the stack just like @code{AGAIN}. But if it falls through,
9398: the locals stack must not be changed. The compiler generates the
9399: following code:
9400: @format
9401: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9402: @end format
9403: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9404:
1.78 anton 9405: @code{THEN} can produce somewhat inefficient code:
9406: @format
9407: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9408: <orig target>:
9409: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9410: @end format
9411: The second @code{lp+!#} adjusts the locals stack pointer from the
9412: level at the @i{orig} point to the level after the @code{THEN}. The
9413: first @code{lp+!#} adjusts the locals stack pointer from the current
9414: level to the level at the orig point, so the complete effect is an
9415: adjustment from the current level to the right level after the
9416: @code{THEN}.
1.26 crook 9417:
1.78 anton 9418: @cindex locals information on the control-flow stack
9419: @cindex control-flow stack items, locals information
9420: In a conventional Forth implementation a dest control-flow stack entry
9421: is just the target address and an orig entry is just the address to be
9422: patched. Our locals implementation adds a word list to every orig or dest
9423: item. It is the list of locals visible (or assumed visible) at the point
9424: described by the entry. Our implementation also adds a tag to identify
9425: the kind of entry, in particular to differentiate between live and dead
9426: (reachable and unreachable) orig entries.
1.26 crook 9427:
1.78 anton 9428: A few unusual operations have to be performed on locals word lists:
1.44 crook 9429:
1.5 anton 9430:
1.78 anton 9431: doc-common-list
9432: doc-sub-list?
9433: doc-list-size
1.52 anton 9434:
9435:
1.78 anton 9436: Several features of our locals word list implementation make these
9437: operations easy to implement: The locals word lists are organised as
9438: linked lists; the tails of these lists are shared, if the lists
9439: contain some of the same locals; and the address of a name is greater
9440: than the address of the names behind it in the list.
1.5 anton 9441:
1.78 anton 9442: Another important implementation detail is the variable
9443: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9444: determine if they can be reached directly or only through the branch
9445: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9446: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9447: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9448:
1.78 anton 9449: Counted loops are similar to other loops in most respects, but
9450: @code{LEAVE} requires special attention: It performs basically the same
9451: service as @code{AHEAD}, but it does not create a control-flow stack
9452: entry. Therefore the information has to be stored elsewhere;
9453: traditionally, the information was stored in the target fields of the
9454: branches created by the @code{LEAVE}s, by organizing these fields into a
9455: linked list. Unfortunately, this clever trick does not provide enough
9456: space for storing our extended control flow information. Therefore, we
9457: introduce another stack, the leave stack. It contains the control-flow
9458: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9459:
1.78 anton 9460: Local names are kept until the end of the colon definition, even if
9461: they are no longer visible in any control-flow path. In a few cases
9462: this may lead to increased space needs for the locals name area, but
9463: usually less than reclaiming this space would cost in code size.
1.5 anton 9464:
1.44 crook 9465:
1.78 anton 9466: @node ANS Forth locals, , Gforth locals, Locals
9467: @subsection ANS Forth locals
9468: @cindex locals, ANS Forth style
1.5 anton 9469:
1.78 anton 9470: The ANS Forth locals wordset does not define a syntax for locals, but
9471: words that make it possible to define various syntaxes. One of the
9472: possible syntaxes is a subset of the syntax we used in the Gforth locals
9473: wordset, i.e.:
1.29 crook 9474:
9475: @example
1.78 anton 9476: @{ local1 local2 ... -- comment @}
9477: @end example
9478: @noindent
9479: or
9480: @example
9481: @{ local1 local2 ... @}
1.29 crook 9482: @end example
9483:
1.78 anton 9484: The order of the locals corresponds to the order in a stack comment. The
9485: restrictions are:
1.5 anton 9486:
1.78 anton 9487: @itemize @bullet
9488: @item
9489: Locals can only be cell-sized values (no type specifiers are allowed).
9490: @item
9491: Locals can be defined only outside control structures.
9492: @item
9493: Locals can interfere with explicit usage of the return stack. For the
9494: exact (and long) rules, see the standard. If you don't use return stack
9495: accessing words in a definition using locals, you will be all right. The
9496: purpose of this rule is to make locals implementation on the return
9497: stack easier.
9498: @item
9499: The whole definition must be in one line.
9500: @end itemize
1.5 anton 9501:
1.78 anton 9502: Locals defined in ANS Forth behave like @code{VALUE}s
9503: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9504: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9505:
1.78 anton 9506: Since the syntax above is supported by Gforth directly, you need not do
9507: anything to use it. If you want to port a program using this syntax to
9508: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9509: syntax on the other system.
1.5 anton 9510:
1.78 anton 9511: Note that a syntax shown in the standard, section A.13 looks
9512: similar, but is quite different in having the order of locals
9513: reversed. Beware!
1.5 anton 9514:
1.78 anton 9515: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9516:
1.78 anton 9517: doc-(local)
1.5 anton 9518:
1.78 anton 9519: The ANS Forth locals extension wordset defines a syntax using
9520: @code{locals|}, but it is so awful that we strongly recommend not to use
9521: it. We have implemented this syntax to make porting to Gforth easy, but
9522: do not document it here. The problem with this syntax is that the locals
9523: are defined in an order reversed with respect to the standard stack
9524: comment notation, making programs harder to read, and easier to misread
9525: and miswrite. The only merit of this syntax is that it is easy to
9526: implement using the ANS Forth locals wordset.
1.53 anton 9527:
9528:
1.78 anton 9529: @c ----------------------------------------------------------
9530: @node Structures, Object-oriented Forth, Locals, Words
9531: @section Structures
9532: @cindex structures
9533: @cindex records
1.53 anton 9534:
1.78 anton 9535: This section presents the structure package that comes with Gforth. A
9536: version of the package implemented in ANS Forth is available in
9537: @file{compat/struct.fs}. This package was inspired by a posting on
9538: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9539: possibly John Hayes). A version of this section has been published in
9540: M. Anton Ertl,
9541: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9542: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9543: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9544:
1.78 anton 9545: @menu
9546: * Why explicit structure support?::
9547: * Structure Usage::
9548: * Structure Naming Convention::
9549: * Structure Implementation::
9550: * Structure Glossary::
9551: @end menu
1.55 anton 9552:
1.78 anton 9553: @node Why explicit structure support?, Structure Usage, Structures, Structures
9554: @subsection Why explicit structure support?
1.53 anton 9555:
1.78 anton 9556: @cindex address arithmetic for structures
9557: @cindex structures using address arithmetic
9558: If we want to use a structure containing several fields, we could simply
9559: reserve memory for it, and access the fields using address arithmetic
9560: (@pxref{Address arithmetic}). As an example, consider a structure with
9561: the following fields
1.57 anton 9562:
1.78 anton 9563: @table @code
9564: @item a
9565: is a float
9566: @item b
9567: is a cell
9568: @item c
9569: is a float
9570: @end table
1.57 anton 9571:
1.78 anton 9572: Given the (float-aligned) base address of the structure we get the
9573: address of the field
1.52 anton 9574:
1.78 anton 9575: @table @code
9576: @item a
9577: without doing anything further.
9578: @item b
9579: with @code{float+}
9580: @item c
9581: with @code{float+ cell+ faligned}
9582: @end table
1.52 anton 9583:
1.78 anton 9584: It is easy to see that this can become quite tiring.
1.52 anton 9585:
1.78 anton 9586: Moreover, it is not very readable, because seeing a
9587: @code{cell+} tells us neither which kind of structure is
9588: accessed nor what field is accessed; we have to somehow infer the kind
9589: of structure, and then look up in the documentation, which field of
9590: that structure corresponds to that offset.
1.53 anton 9591:
1.78 anton 9592: Finally, this kind of address arithmetic also causes maintenance
9593: troubles: If you add or delete a field somewhere in the middle of the
9594: structure, you have to find and change all computations for the fields
9595: afterwards.
1.52 anton 9596:
1.78 anton 9597: So, instead of using @code{cell+} and friends directly, how
9598: about storing the offsets in constants:
1.52 anton 9599:
1.78 anton 9600: @example
9601: 0 constant a-offset
9602: 0 float+ constant b-offset
9603: 0 float+ cell+ faligned c-offset
9604: @end example
1.64 pazsan 9605:
1.78 anton 9606: Now we can get the address of field @code{x} with @code{x-offset
9607: +}. This is much better in all respects. Of course, you still
9608: have to change all later offset definitions if you add a field. You can
9609: fix this by declaring the offsets in the following way:
1.57 anton 9610:
1.78 anton 9611: @example
9612: 0 constant a-offset
9613: a-offset float+ constant b-offset
9614: b-offset cell+ faligned constant c-offset
9615: @end example
1.57 anton 9616:
1.78 anton 9617: Since we always use the offsets with @code{+}, we could use a defining
9618: word @code{cfield} that includes the @code{+} in the action of the
9619: defined word:
1.64 pazsan 9620:
1.78 anton 9621: @example
9622: : cfield ( n "name" -- )
9623: create ,
9624: does> ( name execution: addr1 -- addr2 )
9625: @@ + ;
1.64 pazsan 9626:
1.78 anton 9627: 0 cfield a
9628: 0 a float+ cfield b
9629: 0 b cell+ faligned cfield c
9630: @end example
1.64 pazsan 9631:
1.78 anton 9632: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9633:
1.78 anton 9634: The structure field words now can be used quite nicely. However,
9635: their definition is still a bit cumbersome: We have to repeat the
9636: name, the information about size and alignment is distributed before
9637: and after the field definitions etc. The structure package presented
9638: here addresses these problems.
1.64 pazsan 9639:
1.78 anton 9640: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9641: @subsection Structure Usage
9642: @cindex structure usage
1.57 anton 9643:
1.78 anton 9644: @cindex @code{field} usage
9645: @cindex @code{struct} usage
9646: @cindex @code{end-struct} usage
9647: You can define a structure for a (data-less) linked list with:
1.57 anton 9648: @example
1.78 anton 9649: struct
9650: cell% field list-next
9651: end-struct list%
1.57 anton 9652: @end example
9653:
1.78 anton 9654: With the address of the list node on the stack, you can compute the
9655: address of the field that contains the address of the next node with
9656: @code{list-next}. E.g., you can determine the length of a list
9657: with:
1.57 anton 9658:
9659: @example
1.78 anton 9660: : list-length ( list -- n )
9661: \ "list" is a pointer to the first element of a linked list
9662: \ "n" is the length of the list
9663: 0 BEGIN ( list1 n1 )
9664: over
9665: WHILE ( list1 n1 )
9666: 1+ swap list-next @@ swap
9667: REPEAT
9668: nip ;
1.57 anton 9669: @end example
9670:
1.78 anton 9671: You can reserve memory for a list node in the dictionary with
9672: @code{list% %allot}, which leaves the address of the list node on the
9673: stack. For the equivalent allocation on the heap you can use @code{list%
9674: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9675: use @code{list% %allocate}). You can get the the size of a list
9676: node with @code{list% %size} and its alignment with @code{list%
9677: %alignment}.
9678:
9679: Note that in ANS Forth the body of a @code{create}d word is
9680: @code{aligned} but not necessarily @code{faligned};
9681: therefore, if you do a:
1.57 anton 9682:
9683: @example
1.78 anton 9684: create @emph{name} foo% %allot drop
1.57 anton 9685: @end example
9686:
1.78 anton 9687: @noindent
9688: then the memory alloted for @code{foo%} is guaranteed to start at the
9689: body of @code{@emph{name}} only if @code{foo%} contains only character,
9690: cell and double fields. Therefore, if your structure contains floats,
9691: better use
1.57 anton 9692:
9693: @example
1.78 anton 9694: foo% %allot constant @emph{name}
1.57 anton 9695: @end example
9696:
1.78 anton 9697: @cindex structures containing structures
9698: You can include a structure @code{foo%} as a field of
9699: another structure, like this:
1.65 anton 9700: @example
1.78 anton 9701: struct
9702: ...
9703: foo% field ...
9704: ...
9705: end-struct ...
1.65 anton 9706: @end example
1.52 anton 9707:
1.78 anton 9708: @cindex structure extension
9709: @cindex extended records
9710: Instead of starting with an empty structure, you can extend an
9711: existing structure. E.g., a plain linked list without data, as defined
9712: above, is hardly useful; You can extend it to a linked list of integers,
9713: like this:@footnote{This feature is also known as @emph{extended
9714: records}. It is the main innovation in the Oberon language; in other
9715: words, adding this feature to Modula-2 led Wirth to create a new
9716: language, write a new compiler etc. Adding this feature to Forth just
9717: required a few lines of code.}
1.52 anton 9718:
1.78 anton 9719: @example
9720: list%
9721: cell% field intlist-int
9722: end-struct intlist%
9723: @end example
1.55 anton 9724:
1.78 anton 9725: @code{intlist%} is a structure with two fields:
9726: @code{list-next} and @code{intlist-int}.
1.55 anton 9727:
1.78 anton 9728: @cindex structures containing arrays
9729: You can specify an array type containing @emph{n} elements of
9730: type @code{foo%} like this:
1.55 anton 9731:
9732: @example
1.78 anton 9733: foo% @emph{n} *
1.56 anton 9734: @end example
1.55 anton 9735:
1.78 anton 9736: You can use this array type in any place where you can use a normal
9737: type, e.g., when defining a @code{field}, or with
9738: @code{%allot}.
9739:
9740: @cindex first field optimization
9741: The first field is at the base address of a structure and the word for
9742: this field (e.g., @code{list-next}) actually does not change the address
9743: on the stack. You may be tempted to leave it away in the interest of
9744: run-time and space efficiency. This is not necessary, because the
9745: structure package optimizes this case: If you compile a first-field
9746: words, no code is generated. So, in the interest of readability and
9747: maintainability you should include the word for the field when accessing
9748: the field.
1.52 anton 9749:
9750:
1.78 anton 9751: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9752: @subsection Structure Naming Convention
9753: @cindex structure naming convention
1.52 anton 9754:
1.78 anton 9755: The field names that come to (my) mind are often quite generic, and,
9756: if used, would cause frequent name clashes. E.g., many structures
9757: probably contain a @code{counter} field. The structure names
9758: that come to (my) mind are often also the logical choice for the names
9759: of words that create such a structure.
1.52 anton 9760:
1.78 anton 9761: Therefore, I have adopted the following naming conventions:
1.52 anton 9762:
1.78 anton 9763: @itemize @bullet
9764: @cindex field naming convention
9765: @item
9766: The names of fields are of the form
9767: @code{@emph{struct}-@emph{field}}, where
9768: @code{@emph{struct}} is the basic name of the structure, and
9769: @code{@emph{field}} is the basic name of the field. You can
9770: think of field words as converting the (address of the)
9771: structure into the (address of the) field.
1.52 anton 9772:
1.78 anton 9773: @cindex structure naming convention
9774: @item
9775: The names of structures are of the form
9776: @code{@emph{struct}%}, where
9777: @code{@emph{struct}} is the basic name of the structure.
9778: @end itemize
1.52 anton 9779:
1.78 anton 9780: This naming convention does not work that well for fields of extended
9781: structures; e.g., the integer list structure has a field
9782: @code{intlist-int}, but has @code{list-next}, not
9783: @code{intlist-next}.
1.53 anton 9784:
1.78 anton 9785: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9786: @subsection Structure Implementation
9787: @cindex structure implementation
9788: @cindex implementation of structures
1.52 anton 9789:
1.78 anton 9790: The central idea in the implementation is to pass the data about the
9791: structure being built on the stack, not in some global
9792: variable. Everything else falls into place naturally once this design
9793: decision is made.
1.53 anton 9794:
1.78 anton 9795: The type description on the stack is of the form @emph{align
9796: size}. Keeping the size on the top-of-stack makes dealing with arrays
9797: very simple.
1.53 anton 9798:
1.78 anton 9799: @code{field} is a defining word that uses @code{Create}
9800: and @code{DOES>}. The body of the field contains the offset
9801: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9802:
9803: @example
1.78 anton 9804: @@ +
1.53 anton 9805: @end example
9806:
1.78 anton 9807: @noindent
9808: i.e., add the offset to the address, giving the stack effect
9809: @i{addr1 -- addr2} for a field.
9810:
9811: @cindex first field optimization, implementation
9812: This simple structure is slightly complicated by the optimization
9813: for fields with offset 0, which requires a different
9814: @code{DOES>}-part (because we cannot rely on there being
9815: something on the stack if such a field is invoked during
9816: compilation). Therefore, we put the different @code{DOES>}-parts
9817: in separate words, and decide which one to invoke based on the
9818: offset. For a zero offset, the field is basically a noop; it is
9819: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9820:
1.78 anton 9821: @node Structure Glossary, , Structure Implementation, Structures
9822: @subsection Structure Glossary
9823: @cindex structure glossary
1.53 anton 9824:
1.5 anton 9825:
1.78 anton 9826: doc-%align
9827: doc-%alignment
9828: doc-%alloc
9829: doc-%allocate
9830: doc-%allot
9831: doc-cell%
9832: doc-char%
9833: doc-dfloat%
9834: doc-double%
9835: doc-end-struct
9836: doc-field
9837: doc-float%
9838: doc-naligned
9839: doc-sfloat%
9840: doc-%size
9841: doc-struct
1.54 anton 9842:
9843:
1.26 crook 9844: @c -------------------------------------------------------------
1.78 anton 9845: @node Object-oriented Forth, Programming Tools, Structures, Words
9846: @section Object-oriented Forth
9847:
9848: Gforth comes with three packages for object-oriented programming:
9849: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9850: is preloaded, so you have to @code{include} them before use. The most
9851: important differences between these packages (and others) are discussed
9852: in @ref{Comparison with other object models}. All packages are written
9853: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9854:
1.78 anton 9855: @menu
9856: * Why object-oriented programming?::
9857: * Object-Oriented Terminology::
9858: * Objects::
9859: * OOF::
9860: * Mini-OOF::
9861: * Comparison with other object models::
9862: @end menu
1.5 anton 9863:
1.78 anton 9864: @c ----------------------------------------------------------------
9865: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9866: @subsection Why object-oriented programming?
9867: @cindex object-oriented programming motivation
9868: @cindex motivation for object-oriented programming
1.44 crook 9869:
1.78 anton 9870: Often we have to deal with several data structures (@emph{objects}),
9871: that have to be treated similarly in some respects, but differently in
9872: others. Graphical objects are the textbook example: circles, triangles,
9873: dinosaurs, icons, and others, and we may want to add more during program
9874: development. We want to apply some operations to any graphical object,
9875: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9876: has to do something different for every kind of object.
9877: @comment TODO add some other operations eg perimeter, area
9878: @comment and tie in to concrete examples later..
1.5 anton 9879:
1.78 anton 9880: We could implement @code{draw} as a big @code{CASE}
9881: control structure that executes the appropriate code depending on the
9882: kind of object to be drawn. This would be not be very elegant, and,
9883: moreover, we would have to change @code{draw} every time we add
9884: a new kind of graphical object (say, a spaceship).
1.44 crook 9885:
1.78 anton 9886: What we would rather do is: When defining spaceships, we would tell
9887: the system: ``Here's how you @code{draw} a spaceship; you figure
9888: out the rest''.
1.5 anton 9889:
1.78 anton 9890: This is the problem that all systems solve that (rightfully) call
9891: themselves object-oriented; the object-oriented packages presented here
9892: solve this problem (and not much else).
9893: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9894:
1.78 anton 9895: @c ------------------------------------------------------------------------
9896: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9897: @subsection Object-Oriented Terminology
9898: @cindex object-oriented terminology
9899: @cindex terminology for object-oriented programming
1.5 anton 9900:
1.78 anton 9901: This section is mainly for reference, so you don't have to understand
9902: all of it right away. The terminology is mainly Smalltalk-inspired. In
9903: short:
1.44 crook 9904:
1.78 anton 9905: @table @emph
9906: @cindex class
9907: @item class
9908: a data structure definition with some extras.
1.5 anton 9909:
1.78 anton 9910: @cindex object
9911: @item object
9912: an instance of the data structure described by the class definition.
1.5 anton 9913:
1.78 anton 9914: @cindex instance variables
9915: @item instance variables
9916: fields of the data structure.
1.5 anton 9917:
1.78 anton 9918: @cindex selector
9919: @cindex method selector
9920: @cindex virtual function
9921: @item selector
9922: (or @emph{method selector}) a word (e.g.,
9923: @code{draw}) that performs an operation on a variety of data
9924: structures (classes). A selector describes @emph{what} operation to
9925: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9926:
1.78 anton 9927: @cindex method
9928: @item method
9929: the concrete definition that performs the operation
9930: described by the selector for a specific class. A method specifies
9931: @emph{how} the operation is performed for a specific class.
1.5 anton 9932:
1.78 anton 9933: @cindex selector invocation
9934: @cindex message send
9935: @cindex invoking a selector
9936: @item selector invocation
9937: a call of a selector. One argument of the call (the TOS (top-of-stack))
9938: is used for determining which method is used. In Smalltalk terminology:
9939: a message (consisting of the selector and the other arguments) is sent
9940: to the object.
1.5 anton 9941:
1.78 anton 9942: @cindex receiving object
9943: @item receiving object
9944: the object used for determining the method executed by a selector
9945: invocation. In the @file{objects.fs} model, it is the object that is on
9946: the TOS when the selector is invoked. (@emph{Receiving} comes from
9947: the Smalltalk @emph{message} terminology.)
1.5 anton 9948:
1.78 anton 9949: @cindex child class
9950: @cindex parent class
9951: @cindex inheritance
9952: @item child class
9953: a class that has (@emph{inherits}) all properties (instance variables,
9954: selectors, methods) from a @emph{parent class}. In Smalltalk
9955: terminology: The subclass inherits from the superclass. In C++
9956: terminology: The derived class inherits from the base class.
1.5 anton 9957:
1.78 anton 9958: @end table
1.5 anton 9959:
1.78 anton 9960: @c If you wonder about the message sending terminology, it comes from
9961: @c a time when each object had it's own task and objects communicated via
9962: @c message passing; eventually the Smalltalk developers realized that
9963: @c they can do most things through simple (indirect) calls. They kept the
9964: @c terminology.
1.5 anton 9965:
1.78 anton 9966: @c --------------------------------------------------------------
9967: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9968: @subsection The @file{objects.fs} model
9969: @cindex objects
9970: @cindex object-oriented programming
1.26 crook 9971:
1.78 anton 9972: @cindex @file{objects.fs}
9973: @cindex @file{oof.fs}
1.26 crook 9974:
1.78 anton 9975: This section describes the @file{objects.fs} package. This material also
9976: has been published in M. Anton Ertl,
9977: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9978: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9979: 37--43.
9980: @c McKewan's and Zsoter's packages
1.26 crook 9981:
1.78 anton 9982: This section assumes that you have read @ref{Structures}.
1.5 anton 9983:
1.78 anton 9984: The techniques on which this model is based have been used to implement
9985: the parser generator, Gray, and have also been used in Gforth for
9986: implementing the various flavours of word lists (hashed or not,
9987: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 9988:
9989:
1.26 crook 9990: @menu
1.78 anton 9991: * Properties of the Objects model::
9992: * Basic Objects Usage::
9993: * The Objects base class::
9994: * Creating objects::
9995: * Object-Oriented Programming Style::
9996: * Class Binding::
9997: * Method conveniences::
9998: * Classes and Scoping::
9999: * Dividing classes::
10000: * Object Interfaces::
10001: * Objects Implementation::
10002: * Objects Glossary::
1.26 crook 10003: @end menu
1.5 anton 10004:
1.78 anton 10005: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10006:
1.78 anton 10007: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10008: @subsubsection Properties of the @file{objects.fs} model
10009: @cindex @file{objects.fs} properties
1.5 anton 10010:
1.78 anton 10011: @itemize @bullet
10012: @item
10013: It is straightforward to pass objects on the stack. Passing
10014: selectors on the stack is a little less convenient, but possible.
1.44 crook 10015:
1.78 anton 10016: @item
10017: Objects are just data structures in memory, and are referenced by their
10018: address. You can create words for objects with normal defining words
10019: like @code{constant}. Likewise, there is no difference between instance
10020: variables that contain objects and those that contain other data.
1.5 anton 10021:
1.78 anton 10022: @item
10023: Late binding is efficient and easy to use.
1.44 crook 10024:
1.78 anton 10025: @item
10026: It avoids parsing, and thus avoids problems with state-smartness
10027: and reduced extensibility; for convenience there are a few parsing
10028: words, but they have non-parsing counterparts. There are also a few
10029: defining words that parse. This is hard to avoid, because all standard
10030: defining words parse (except @code{:noname}); however, such
10031: words are not as bad as many other parsing words, because they are not
10032: state-smart.
1.5 anton 10033:
1.78 anton 10034: @item
10035: It does not try to incorporate everything. It does a few things and does
10036: them well (IMO). In particular, this model was not designed to support
10037: information hiding (although it has features that may help); you can use
10038: a separate package for achieving this.
1.5 anton 10039:
1.78 anton 10040: @item
10041: It is layered; you don't have to learn and use all features to use this
10042: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10043: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10044: are optional and independent of each other.
1.5 anton 10045:
1.78 anton 10046: @item
10047: An implementation in ANS Forth is available.
1.5 anton 10048:
1.78 anton 10049: @end itemize
1.5 anton 10050:
1.44 crook 10051:
1.78 anton 10052: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10053: @subsubsection Basic @file{objects.fs} Usage
10054: @cindex basic objects usage
10055: @cindex objects, basic usage
1.5 anton 10056:
1.78 anton 10057: You can define a class for graphical objects like this:
1.44 crook 10058:
1.78 anton 10059: @cindex @code{class} usage
10060: @cindex @code{end-class} usage
10061: @cindex @code{selector} usage
1.5 anton 10062: @example
1.78 anton 10063: object class \ "object" is the parent class
10064: selector draw ( x y graphical -- )
10065: end-class graphical
10066: @end example
10067:
10068: This code defines a class @code{graphical} with an
10069: operation @code{draw}. We can perform the operation
10070: @code{draw} on any @code{graphical} object, e.g.:
10071:
10072: @example
10073: 100 100 t-rex draw
1.26 crook 10074: @end example
1.5 anton 10075:
1.78 anton 10076: @noindent
10077: where @code{t-rex} is a word (say, a constant) that produces a
10078: graphical object.
10079:
10080: @comment TODO add a 2nd operation eg perimeter.. and use for
10081: @comment a concrete example
1.5 anton 10082:
1.78 anton 10083: @cindex abstract class
10084: How do we create a graphical object? With the present definitions,
10085: we cannot create a useful graphical object. The class
10086: @code{graphical} describes graphical objects in general, but not
10087: any concrete graphical object type (C++ users would call it an
10088: @emph{abstract class}); e.g., there is no method for the selector
10089: @code{draw} in the class @code{graphical}.
1.5 anton 10090:
1.78 anton 10091: For concrete graphical objects, we define child classes of the
10092: class @code{graphical}, e.g.:
1.5 anton 10093:
1.78 anton 10094: @cindex @code{overrides} usage
10095: @cindex @code{field} usage in class definition
1.26 crook 10096: @example
1.78 anton 10097: graphical class \ "graphical" is the parent class
10098: cell% field circle-radius
1.5 anton 10099:
1.78 anton 10100: :noname ( x y circle -- )
10101: circle-radius @@ draw-circle ;
10102: overrides draw
1.5 anton 10103:
1.78 anton 10104: :noname ( n-radius circle -- )
10105: circle-radius ! ;
10106: overrides construct
1.5 anton 10107:
1.78 anton 10108: end-class circle
10109: @end example
1.44 crook 10110:
1.78 anton 10111: Here we define a class @code{circle} as a child of @code{graphical},
10112: with field @code{circle-radius} (which behaves just like a field
10113: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10114: for the selectors @code{draw} and @code{construct} (@code{construct} is
10115: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10116:
1.78 anton 10117: Now we can create a circle on the heap (i.e.,
10118: @code{allocate}d memory) with:
1.44 crook 10119:
1.78 anton 10120: @cindex @code{heap-new} usage
1.5 anton 10121: @example
1.78 anton 10122: 50 circle heap-new constant my-circle
1.5 anton 10123: @end example
10124:
1.78 anton 10125: @noindent
10126: @code{heap-new} invokes @code{construct}, thus
10127: initializing the field @code{circle-radius} with 50. We can draw
10128: this new circle at (100,100) with:
1.5 anton 10129:
10130: @example
1.78 anton 10131: 100 100 my-circle draw
1.5 anton 10132: @end example
10133:
1.78 anton 10134: @cindex selector invocation, restrictions
10135: @cindex class definition, restrictions
10136: Note: You can only invoke a selector if the object on the TOS
10137: (the receiving object) belongs to the class where the selector was
10138: defined or one of its descendents; e.g., you can invoke
10139: @code{draw} only for objects belonging to @code{graphical}
10140: or its descendents (e.g., @code{circle}). Immediately before
10141: @code{end-class}, the search order has to be the same as
10142: immediately after @code{class}.
10143:
10144: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10145: @subsubsection The @file{object.fs} base class
10146: @cindex @code{object} class
10147:
10148: When you define a class, you have to specify a parent class. So how do
10149: you start defining classes? There is one class available from the start:
10150: @code{object}. It is ancestor for all classes and so is the
10151: only class that has no parent. It has two selectors: @code{construct}
10152: and @code{print}.
10153:
10154: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10155: @subsubsection Creating objects
10156: @cindex creating objects
10157: @cindex object creation
10158: @cindex object allocation options
10159:
10160: @cindex @code{heap-new} discussion
10161: @cindex @code{dict-new} discussion
10162: @cindex @code{construct} discussion
10163: You can create and initialize an object of a class on the heap with
10164: @code{heap-new} ( ... class -- object ) and in the dictionary
10165: (allocation with @code{allot}) with @code{dict-new} (
10166: ... class -- object ). Both words invoke @code{construct}, which
10167: consumes the stack items indicated by "..." above.
10168:
10169: @cindex @code{init-object} discussion
10170: @cindex @code{class-inst-size} discussion
10171: If you want to allocate memory for an object yourself, you can get its
10172: alignment and size with @code{class-inst-size 2@@} ( class --
10173: align size ). Once you have memory for an object, you can initialize
10174: it with @code{init-object} ( ... class object -- );
10175: @code{construct} does only a part of the necessary work.
10176:
10177: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10178: @subsubsection Object-Oriented Programming Style
10179: @cindex object-oriented programming style
10180: @cindex programming style, object-oriented
1.5 anton 10181:
1.78 anton 10182: This section is not exhaustive.
1.5 anton 10183:
1.78 anton 10184: @cindex stack effects of selectors
10185: @cindex selectors and stack effects
10186: In general, it is a good idea to ensure that all methods for the
10187: same selector have the same stack effect: when you invoke a selector,
10188: you often have no idea which method will be invoked, so, unless all
10189: methods have the same stack effect, you will not know the stack effect
10190: of the selector invocation.
1.5 anton 10191:
1.78 anton 10192: One exception to this rule is methods for the selector
10193: @code{construct}. We know which method is invoked, because we
10194: specify the class to be constructed at the same place. Actually, I
10195: defined @code{construct} as a selector only to give the users a
10196: convenient way to specify initialization. The way it is used, a
10197: mechanism different from selector invocation would be more natural
10198: (but probably would take more code and more space to explain).
1.5 anton 10199:
1.78 anton 10200: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10201: @subsubsection Class Binding
10202: @cindex class binding
10203: @cindex early binding
1.5 anton 10204:
1.78 anton 10205: @cindex late binding
10206: Normal selector invocations determine the method at run-time depending
10207: on the class of the receiving object. This run-time selection is called
10208: @i{late binding}.
1.5 anton 10209:
1.78 anton 10210: Sometimes it's preferable to invoke a different method. For example,
10211: you might want to use the simple method for @code{print}ing
10212: @code{object}s instead of the possibly long-winded @code{print} method
10213: of the receiver class. You can achieve this by replacing the invocation
10214: of @code{print} with:
1.5 anton 10215:
1.78 anton 10216: @cindex @code{[bind]} usage
1.5 anton 10217: @example
1.78 anton 10218: [bind] object print
1.5 anton 10219: @end example
10220:
1.78 anton 10221: @noindent
10222: in compiled code or:
10223:
10224: @cindex @code{bind} usage
1.5 anton 10225: @example
1.78 anton 10226: bind object print
1.5 anton 10227: @end example
10228:
1.78 anton 10229: @cindex class binding, alternative to
10230: @noindent
10231: in interpreted code. Alternatively, you can define the method with a
10232: name (e.g., @code{print-object}), and then invoke it through the
10233: name. Class binding is just a (often more convenient) way to achieve
10234: the same effect; it avoids name clutter and allows you to invoke
10235: methods directly without naming them first.
1.5 anton 10236:
1.78 anton 10237: @cindex superclass binding
10238: @cindex parent class binding
10239: A frequent use of class binding is this: When we define a method
10240: for a selector, we often want the method to do what the selector does
10241: in the parent class, and a little more. There is a special word for
10242: this purpose: @code{[parent]}; @code{[parent]
10243: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10244: selector}}, where @code{@emph{parent}} is the parent
10245: class of the current class. E.g., a method definition might look like:
1.44 crook 10246:
1.78 anton 10247: @cindex @code{[parent]} usage
10248: @example
10249: :noname
10250: dup [parent] foo \ do parent's foo on the receiving object
10251: ... \ do some more
10252: ; overrides foo
10253: @end example
1.6 pazsan 10254:
1.78 anton 10255: @cindex class binding as optimization
10256: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10257: March 1997), Andrew McKewan presents class binding as an optimization
10258: technique. I recommend not using it for this purpose unless you are in
10259: an emergency. Late binding is pretty fast with this model anyway, so the
10260: benefit of using class binding is small; the cost of using class binding
10261: where it is not appropriate is reduced maintainability.
1.44 crook 10262:
1.78 anton 10263: While we are at programming style questions: You should bind
10264: selectors only to ancestor classes of the receiving object. E.g., say,
10265: you know that the receiving object is of class @code{foo} or its
10266: descendents; then you should bind only to @code{foo} and its
10267: ancestors.
1.12 anton 10268:
1.78 anton 10269: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10270: @subsubsection Method conveniences
10271: @cindex method conveniences
1.44 crook 10272:
1.78 anton 10273: In a method you usually access the receiving object pretty often. If
10274: you define the method as a plain colon definition (e.g., with
10275: @code{:noname}), you may have to do a lot of stack
10276: gymnastics. To avoid this, you can define the method with @code{m:
10277: ... ;m}. E.g., you could define the method for
10278: @code{draw}ing a @code{circle} with
1.6 pazsan 10279:
1.78 anton 10280: @cindex @code{this} usage
10281: @cindex @code{m:} usage
10282: @cindex @code{;m} usage
10283: @example
10284: m: ( x y circle -- )
10285: ( x y ) this circle-radius @@ draw-circle ;m
10286: @end example
1.6 pazsan 10287:
1.78 anton 10288: @cindex @code{exit} in @code{m: ... ;m}
10289: @cindex @code{exitm} discussion
10290: @cindex @code{catch} in @code{m: ... ;m}
10291: When this method is executed, the receiver object is removed from the
10292: stack; you can access it with @code{this} (admittedly, in this
10293: example the use of @code{m: ... ;m} offers no advantage). Note
10294: that I specify the stack effect for the whole method (i.e. including
10295: the receiver object), not just for the code between @code{m:}
10296: and @code{;m}. You cannot use @code{exit} in
10297: @code{m:...;m}; instead, use
10298: @code{exitm}.@footnote{Moreover, for any word that calls
10299: @code{catch} and was defined before loading
10300: @code{objects.fs}, you have to redefine it like I redefined
10301: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10302:
1.78 anton 10303: @cindex @code{inst-var} usage
10304: You will frequently use sequences of the form @code{this
10305: @emph{field}} (in the example above: @code{this
10306: circle-radius}). If you use the field only in this way, you can
10307: define it with @code{inst-var} and eliminate the
10308: @code{this} before the field name. E.g., the @code{circle}
10309: class above could also be defined with:
1.6 pazsan 10310:
1.78 anton 10311: @example
10312: graphical class
10313: cell% inst-var radius
1.6 pazsan 10314:
1.78 anton 10315: m: ( x y circle -- )
10316: radius @@ draw-circle ;m
10317: overrides draw
1.6 pazsan 10318:
1.78 anton 10319: m: ( n-radius circle -- )
10320: radius ! ;m
10321: overrides construct
1.6 pazsan 10322:
1.78 anton 10323: end-class circle
10324: @end example
1.6 pazsan 10325:
1.78 anton 10326: @code{radius} can only be used in @code{circle} and its
10327: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10328:
1.78 anton 10329: @cindex @code{inst-value} usage
10330: You can also define fields with @code{inst-value}, which is
10331: to @code{inst-var} what @code{value} is to
10332: @code{variable}. You can change the value of such a field with
10333: @code{[to-inst]}. E.g., we could also define the class
10334: @code{circle} like this:
1.44 crook 10335:
1.78 anton 10336: @example
10337: graphical class
10338: inst-value radius
1.6 pazsan 10339:
1.78 anton 10340: m: ( x y circle -- )
10341: radius draw-circle ;m
10342: overrides draw
1.44 crook 10343:
1.78 anton 10344: m: ( n-radius circle -- )
10345: [to-inst] radius ;m
10346: overrides construct
1.6 pazsan 10347:
1.78 anton 10348: end-class circle
10349: @end example
1.6 pazsan 10350:
1.78 anton 10351: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10352:
1.78 anton 10353: @c Finally, you can define named methods with @code{:m}. One use of this
10354: @c feature is the definition of words that occur only in one class and are
10355: @c not intended to be overridden, but which still need method context
10356: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10357: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10358:
10359:
1.78 anton 10360: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10361: @subsubsection Classes and Scoping
10362: @cindex classes and scoping
10363: @cindex scoping and classes
1.6 pazsan 10364:
1.78 anton 10365: Inheritance is frequent, unlike structure extension. This exacerbates
10366: the problem with the field name convention (@pxref{Structure Naming
10367: Convention}): One always has to remember in which class the field was
10368: originally defined; changing a part of the class structure would require
10369: changes for renaming in otherwise unaffected code.
1.6 pazsan 10370:
1.78 anton 10371: @cindex @code{inst-var} visibility
10372: @cindex @code{inst-value} visibility
10373: To solve this problem, I added a scoping mechanism (which was not in my
10374: original charter): A field defined with @code{inst-var} (or
10375: @code{inst-value}) is visible only in the class where it is defined and in
10376: the descendent classes of this class. Using such fields only makes
10377: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10378:
1.78 anton 10379: This scoping mechanism allows us to use the unadorned field name,
10380: because name clashes with unrelated words become much less likely.
1.6 pazsan 10381:
1.78 anton 10382: @cindex @code{protected} discussion
10383: @cindex @code{private} discussion
10384: Once we have this mechanism, we can also use it for controlling the
10385: visibility of other words: All words defined after
10386: @code{protected} are visible only in the current class and its
10387: descendents. @code{public} restores the compilation
10388: (i.e. @code{current}) word list that was in effect before. If you
10389: have several @code{protected}s without an intervening
10390: @code{public} or @code{set-current}, @code{public}
10391: will restore the compilation word list in effect before the first of
10392: these @code{protected}s.
1.6 pazsan 10393:
1.78 anton 10394: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10395: @subsubsection Dividing classes
10396: @cindex Dividing classes
10397: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10398:
1.78 anton 10399: You may want to do the definition of methods separate from the
10400: definition of the class, its selectors, fields, and instance variables,
10401: i.e., separate the implementation from the definition. You can do this
10402: in the following way:
1.6 pazsan 10403:
1.78 anton 10404: @example
10405: graphical class
10406: inst-value radius
10407: end-class circle
1.6 pazsan 10408:
1.78 anton 10409: ... \ do some other stuff
1.6 pazsan 10410:
1.78 anton 10411: circle methods \ now we are ready
1.44 crook 10412:
1.78 anton 10413: m: ( x y circle -- )
10414: radius draw-circle ;m
10415: overrides draw
1.6 pazsan 10416:
1.78 anton 10417: m: ( n-radius circle -- )
10418: [to-inst] radius ;m
10419: overrides construct
1.44 crook 10420:
1.78 anton 10421: end-methods
10422: @end example
1.7 pazsan 10423:
1.78 anton 10424: You can use several @code{methods}...@code{end-methods} sections. The
10425: only things you can do to the class in these sections are: defining
10426: methods, and overriding the class's selectors. You must not define new
10427: selectors or fields.
1.7 pazsan 10428:
1.78 anton 10429: Note that you often have to override a selector before using it. In
10430: particular, you usually have to override @code{construct} with a new
10431: method before you can invoke @code{heap-new} and friends. E.g., you
10432: must not create a circle before the @code{overrides construct} sequence
10433: in the example above.
1.7 pazsan 10434:
1.78 anton 10435: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10436: @subsubsection Object Interfaces
10437: @cindex object interfaces
10438: @cindex interfaces for objects
1.7 pazsan 10439:
1.78 anton 10440: In this model you can only call selectors defined in the class of the
10441: receiving objects or in one of its ancestors. If you call a selector
10442: with a receiving object that is not in one of these classes, the
10443: result is undefined; if you are lucky, the program crashes
10444: immediately.
1.7 pazsan 10445:
1.78 anton 10446: @cindex selectors common to hardly-related classes
10447: Now consider the case when you want to have a selector (or several)
10448: available in two classes: You would have to add the selector to a
10449: common ancestor class, in the worst case to @code{object}. You
10450: may not want to do this, e.g., because someone else is responsible for
10451: this ancestor class.
1.7 pazsan 10452:
1.78 anton 10453: The solution for this problem is interfaces. An interface is a
10454: collection of selectors. If a class implements an interface, the
10455: selectors become available to the class and its descendents. A class
10456: can implement an unlimited number of interfaces. For the problem
10457: discussed above, we would define an interface for the selector(s), and
10458: both classes would implement the interface.
1.7 pazsan 10459:
1.78 anton 10460: As an example, consider an interface @code{storage} for
10461: writing objects to disk and getting them back, and a class
10462: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10463:
1.78 anton 10464: @cindex @code{interface} usage
10465: @cindex @code{end-interface} usage
10466: @cindex @code{implementation} usage
10467: @example
10468: interface
10469: selector write ( file object -- )
10470: selector read1 ( file object -- )
10471: end-interface storage
1.13 pazsan 10472:
1.78 anton 10473: bar class
10474: storage implementation
1.13 pazsan 10475:
1.78 anton 10476: ... overrides write
10477: ... overrides read1
10478: ...
10479: end-class foo
10480: @end example
1.13 pazsan 10481:
1.78 anton 10482: @noindent
10483: (I would add a word @code{read} @i{( file -- object )} that uses
10484: @code{read1} internally, but that's beyond the point illustrated
10485: here.)
1.13 pazsan 10486:
1.78 anton 10487: Note that you cannot use @code{protected} in an interface; and
10488: of course you cannot define fields.
1.13 pazsan 10489:
1.78 anton 10490: In the Neon model, all selectors are available for all classes;
10491: therefore it does not need interfaces. The price you pay in this model
10492: is slower late binding, and therefore, added complexity to avoid late
10493: binding.
1.13 pazsan 10494:
1.78 anton 10495: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10496: @subsubsection @file{objects.fs} Implementation
10497: @cindex @file{objects.fs} implementation
1.13 pazsan 10498:
1.78 anton 10499: @cindex @code{object-map} discussion
10500: An object is a piece of memory, like one of the data structures
10501: described with @code{struct...end-struct}. It has a field
10502: @code{object-map} that points to the method map for the object's
10503: class.
1.13 pazsan 10504:
1.78 anton 10505: @cindex method map
10506: @cindex virtual function table
10507: The @emph{method map}@footnote{This is Self terminology; in C++
10508: terminology: virtual function table.} is an array that contains the
10509: execution tokens (@i{xt}s) of the methods for the object's class. Each
10510: selector contains an offset into a method map.
1.13 pazsan 10511:
1.78 anton 10512: @cindex @code{selector} implementation, class
10513: @code{selector} is a defining word that uses
10514: @code{CREATE} and @code{DOES>}. The body of the
10515: selector contains the offset; the @code{DOES>} action for a
10516: class selector is, basically:
1.8 pazsan 10517:
10518: @example
1.78 anton 10519: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10520: @end example
10521:
1.78 anton 10522: Since @code{object-map} is the first field of the object, it
10523: does not generate any code. As you can see, calling a selector has a
10524: small, constant cost.
1.26 crook 10525:
1.78 anton 10526: @cindex @code{current-interface} discussion
10527: @cindex class implementation and representation
10528: A class is basically a @code{struct} combined with a method
10529: map. During the class definition the alignment and size of the class
10530: are passed on the stack, just as with @code{struct}s, so
10531: @code{field} can also be used for defining class
10532: fields. However, passing more items on the stack would be
10533: inconvenient, so @code{class} builds a data structure in memory,
10534: which is accessed through the variable
10535: @code{current-interface}. After its definition is complete, the
10536: class is represented on the stack by a pointer (e.g., as parameter for
10537: a child class definition).
1.26 crook 10538:
1.78 anton 10539: A new class starts off with the alignment and size of its parent,
10540: and a copy of the parent's method map. Defining new fields extends the
10541: size and alignment; likewise, defining new selectors extends the
10542: method map. @code{overrides} just stores a new @i{xt} in the method
10543: map at the offset given by the selector.
1.13 pazsan 10544:
1.78 anton 10545: @cindex class binding, implementation
10546: Class binding just gets the @i{xt} at the offset given by the selector
10547: from the class's method map and @code{compile,}s (in the case of
10548: @code{[bind]}) it.
1.13 pazsan 10549:
1.78 anton 10550: @cindex @code{this} implementation
10551: @cindex @code{catch} and @code{this}
10552: @cindex @code{this} and @code{catch}
10553: I implemented @code{this} as a @code{value}. At the
10554: start of an @code{m:...;m} method the old @code{this} is
10555: stored to the return stack and restored at the end; and the object on
10556: the TOS is stored @code{TO this}. This technique has one
10557: disadvantage: If the user does not leave the method via
10558: @code{;m}, but via @code{throw} or @code{exit},
10559: @code{this} is not restored (and @code{exit} may
10560: crash). To deal with the @code{throw} problem, I have redefined
10561: @code{catch} to save and restore @code{this}; the same
10562: should be done with any word that can catch an exception. As for
10563: @code{exit}, I simply forbid it (as a replacement, there is
10564: @code{exitm}).
1.13 pazsan 10565:
1.78 anton 10566: @cindex @code{inst-var} implementation
10567: @code{inst-var} is just the same as @code{field}, with
10568: a different @code{DOES>} action:
1.13 pazsan 10569: @example
1.78 anton 10570: @@ this +
1.8 pazsan 10571: @end example
1.78 anton 10572: Similar for @code{inst-value}.
1.8 pazsan 10573:
1.78 anton 10574: @cindex class scoping implementation
10575: Each class also has a word list that contains the words defined with
10576: @code{inst-var} and @code{inst-value}, and its protected
10577: words. It also has a pointer to its parent. @code{class} pushes
10578: the word lists of the class and all its ancestors onto the search order stack,
10579: and @code{end-class} drops them.
1.20 pazsan 10580:
1.78 anton 10581: @cindex interface implementation
10582: An interface is like a class without fields, parent and protected
10583: words; i.e., it just has a method map. If a class implements an
10584: interface, its method map contains a pointer to the method map of the
10585: interface. The positive offsets in the map are reserved for class
10586: methods, therefore interface map pointers have negative
10587: offsets. Interfaces have offsets that are unique throughout the
10588: system, unlike class selectors, whose offsets are only unique for the
10589: classes where the selector is available (invokable).
1.20 pazsan 10590:
1.78 anton 10591: This structure means that interface selectors have to perform one
10592: indirection more than class selectors to find their method. Their body
10593: contains the interface map pointer offset in the class method map, and
10594: the method offset in the interface method map. The
10595: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10596:
10597: @example
1.78 anton 10598: ( object selector-body )
10599: 2dup selector-interface @@ ( object selector-body object interface-offset )
10600: swap object-map @@ + @@ ( object selector-body map )
10601: swap selector-offset @@ + @@ execute
1.20 pazsan 10602: @end example
10603:
1.78 anton 10604: where @code{object-map} and @code{selector-offset} are
10605: first fields and generate no code.
1.20 pazsan 10606:
1.78 anton 10607: As a concrete example, consider the following code:
1.20 pazsan 10608:
10609: @example
1.78 anton 10610: interface
10611: selector if1sel1
10612: selector if1sel2
10613: end-interface if1
1.20 pazsan 10614:
1.78 anton 10615: object class
10616: if1 implementation
10617: selector cl1sel1
10618: cell% inst-var cl1iv1
1.20 pazsan 10619:
1.78 anton 10620: ' m1 overrides construct
10621: ' m2 overrides if1sel1
10622: ' m3 overrides if1sel2
10623: ' m4 overrides cl1sel2
10624: end-class cl1
1.20 pazsan 10625:
1.78 anton 10626: create obj1 object dict-new drop
10627: create obj2 cl1 dict-new drop
10628: @end example
1.20 pazsan 10629:
1.78 anton 10630: The data structure created by this code (including the data structure
10631: for @code{object}) is shown in the
10632: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10633: @comment TODO add this diagram..
1.20 pazsan 10634:
1.78 anton 10635: @node Objects Glossary, , Objects Implementation, Objects
10636: @subsubsection @file{objects.fs} Glossary
10637: @cindex @file{objects.fs} Glossary
1.20 pazsan 10638:
10639:
1.78 anton 10640: doc---objects-bind
10641: doc---objects-<bind>
10642: doc---objects-bind'
10643: doc---objects-[bind]
10644: doc---objects-class
10645: doc---objects-class->map
10646: doc---objects-class-inst-size
10647: doc---objects-class-override!
1.79 anton 10648: doc---objects-class-previous
10649: doc---objects-class>order
1.78 anton 10650: doc---objects-construct
10651: doc---objects-current'
10652: doc---objects-[current]
10653: doc---objects-current-interface
10654: doc---objects-dict-new
10655: doc---objects-end-class
10656: doc---objects-end-class-noname
10657: doc---objects-end-interface
10658: doc---objects-end-interface-noname
10659: doc---objects-end-methods
10660: doc---objects-exitm
10661: doc---objects-heap-new
10662: doc---objects-implementation
10663: doc---objects-init-object
10664: doc---objects-inst-value
10665: doc---objects-inst-var
10666: doc---objects-interface
10667: doc---objects-m:
10668: doc---objects-:m
10669: doc---objects-;m
10670: doc---objects-method
10671: doc---objects-methods
10672: doc---objects-object
10673: doc---objects-overrides
10674: doc---objects-[parent]
10675: doc---objects-print
10676: doc---objects-protected
10677: doc---objects-public
10678: doc---objects-selector
10679: doc---objects-this
10680: doc---objects-<to-inst>
10681: doc---objects-[to-inst]
10682: doc---objects-to-this
10683: doc---objects-xt-new
1.20 pazsan 10684:
10685:
1.78 anton 10686: @c -------------------------------------------------------------
10687: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10688: @subsection The @file{oof.fs} model
10689: @cindex oof
10690: @cindex object-oriented programming
1.20 pazsan 10691:
1.78 anton 10692: @cindex @file{objects.fs}
10693: @cindex @file{oof.fs}
1.20 pazsan 10694:
1.78 anton 10695: This section describes the @file{oof.fs} package.
1.20 pazsan 10696:
1.78 anton 10697: The package described in this section has been used in bigFORTH since 1991, and
10698: used for two large applications: a chromatographic system used to
10699: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10700:
1.78 anton 10701: You can find a description (in German) of @file{oof.fs} in @cite{Object
10702: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10703: 10(2), 1994.
1.20 pazsan 10704:
1.78 anton 10705: @menu
10706: * Properties of the OOF model::
10707: * Basic OOF Usage::
10708: * The OOF base class::
10709: * Class Declaration::
10710: * Class Implementation::
10711: @end menu
1.20 pazsan 10712:
1.78 anton 10713: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10714: @subsubsection Properties of the @file{oof.fs} model
10715: @cindex @file{oof.fs} properties
1.20 pazsan 10716:
1.78 anton 10717: @itemize @bullet
10718: @item
10719: This model combines object oriented programming with information
10720: hiding. It helps you writing large application, where scoping is
10721: necessary, because it provides class-oriented scoping.
1.20 pazsan 10722:
1.78 anton 10723: @item
10724: Named objects, object pointers, and object arrays can be created,
10725: selector invocation uses the ``object selector'' syntax. Selector invocation
10726: to objects and/or selectors on the stack is a bit less convenient, but
10727: possible.
1.44 crook 10728:
1.78 anton 10729: @item
10730: Selector invocation and instance variable usage of the active object is
10731: straightforward, since both make use of the active object.
1.44 crook 10732:
1.78 anton 10733: @item
10734: Late binding is efficient and easy to use.
1.20 pazsan 10735:
1.78 anton 10736: @item
10737: State-smart objects parse selectors. However, extensibility is provided
10738: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10739:
1.78 anton 10740: @item
10741: An implementation in ANS Forth is available.
1.20 pazsan 10742:
1.78 anton 10743: @end itemize
1.23 crook 10744:
10745:
1.78 anton 10746: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10747: @subsubsection Basic @file{oof.fs} Usage
10748: @cindex @file{oof.fs} usage
1.23 crook 10749:
1.78 anton 10750: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10751:
1.78 anton 10752: You can define a class for graphical objects like this:
1.23 crook 10753:
1.78 anton 10754: @cindex @code{class} usage
10755: @cindex @code{class;} usage
10756: @cindex @code{method} usage
10757: @example
10758: object class graphical \ "object" is the parent class
10759: method draw ( x y graphical -- )
10760: class;
10761: @end example
1.23 crook 10762:
1.78 anton 10763: This code defines a class @code{graphical} with an
10764: operation @code{draw}. We can perform the operation
10765: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10766:
1.78 anton 10767: @example
10768: 100 100 t-rex draw
10769: @end example
1.23 crook 10770:
1.78 anton 10771: @noindent
10772: where @code{t-rex} is an object or object pointer, created with e.g.
10773: @code{graphical : t-rex}.
1.23 crook 10774:
1.78 anton 10775: @cindex abstract class
10776: How do we create a graphical object? With the present definitions,
10777: we cannot create a useful graphical object. The class
10778: @code{graphical} describes graphical objects in general, but not
10779: any concrete graphical object type (C++ users would call it an
10780: @emph{abstract class}); e.g., there is no method for the selector
10781: @code{draw} in the class @code{graphical}.
1.23 crook 10782:
1.78 anton 10783: For concrete graphical objects, we define child classes of the
10784: class @code{graphical}, e.g.:
1.23 crook 10785:
1.78 anton 10786: @example
10787: graphical class circle \ "graphical" is the parent class
10788: cell var circle-radius
10789: how:
10790: : draw ( x y -- )
10791: circle-radius @@ draw-circle ;
1.23 crook 10792:
1.78 anton 10793: : init ( n-radius -- (
10794: circle-radius ! ;
10795: class;
10796: @end example
1.1 anton 10797:
1.78 anton 10798: Here we define a class @code{circle} as a child of @code{graphical},
10799: with a field @code{circle-radius}; it defines new methods for the
10800: selectors @code{draw} and @code{init} (@code{init} is defined in
10801: @code{object}, the parent class of @code{graphical}).
1.1 anton 10802:
1.78 anton 10803: Now we can create a circle in the dictionary with:
1.1 anton 10804:
1.78 anton 10805: @example
10806: 50 circle : my-circle
10807: @end example
1.21 crook 10808:
1.78 anton 10809: @noindent
10810: @code{:} invokes @code{init}, thus initializing the field
10811: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10812: with:
1.1 anton 10813:
1.78 anton 10814: @example
10815: 100 100 my-circle draw
10816: @end example
1.1 anton 10817:
1.78 anton 10818: @cindex selector invocation, restrictions
10819: @cindex class definition, restrictions
10820: Note: You can only invoke a selector if the receiving object belongs to
10821: the class where the selector was defined or one of its descendents;
10822: e.g., you can invoke @code{draw} only for objects belonging to
10823: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10824: mechanism will check if you try to invoke a selector that is not
10825: defined in this class hierarchy, so you'll get an error at compilation
10826: time.
1.1 anton 10827:
10828:
1.78 anton 10829: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10830: @subsubsection The @file{oof.fs} base class
10831: @cindex @file{oof.fs} base class
1.1 anton 10832:
1.78 anton 10833: When you define a class, you have to specify a parent class. So how do
10834: you start defining classes? There is one class available from the start:
10835: @code{object}. You have to use it as ancestor for all classes. It is the
10836: only class that has no parent. Classes are also objects, except that
10837: they don't have instance variables; class manipulation such as
10838: inheritance or changing definitions of a class is handled through
10839: selectors of the class @code{object}.
1.1 anton 10840:
1.78 anton 10841: @code{object} provides a number of selectors:
1.1 anton 10842:
1.78 anton 10843: @itemize @bullet
10844: @item
10845: @code{class} for subclassing, @code{definitions} to add definitions
10846: later on, and @code{class?} to get type informations (is the class a
10847: subclass of the class passed on the stack?).
1.1 anton 10848:
1.78 anton 10849: doc---object-class
10850: doc---object-definitions
10851: doc---object-class?
1.1 anton 10852:
10853:
1.26 crook 10854: @item
1.78 anton 10855: @code{init} and @code{dispose} as constructor and destructor of the
10856: object. @code{init} is invocated after the object's memory is allocated,
10857: while @code{dispose} also handles deallocation. Thus if you redefine
10858: @code{dispose}, you have to call the parent's dispose with @code{super
10859: dispose}, too.
10860:
10861: doc---object-init
10862: doc---object-dispose
10863:
1.1 anton 10864:
1.26 crook 10865: @item
1.78 anton 10866: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10867: @code{[]} to create named and unnamed objects and object arrays or
10868: object pointers.
10869:
10870: doc---object-new
10871: doc---object-new[]
10872: doc---object-:
10873: doc---object-ptr
10874: doc---object-asptr
10875: doc---object-[]
10876:
1.1 anton 10877:
1.26 crook 10878: @item
1.78 anton 10879: @code{::} and @code{super} for explicit scoping. You should use explicit
10880: scoping only for super classes or classes with the same set of instance
10881: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10882:
1.78 anton 10883: doc---object-::
10884: doc---object-super
1.21 crook 10885:
10886:
1.26 crook 10887: @item
1.78 anton 10888: @code{self} to get the address of the object
1.21 crook 10889:
1.78 anton 10890: doc---object-self
1.21 crook 10891:
10892:
1.78 anton 10893: @item
10894: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10895: pointers and instance defers.
1.21 crook 10896:
1.78 anton 10897: doc---object-bind
10898: doc---object-bound
10899: doc---object-link
10900: doc---object-is
1.21 crook 10901:
10902:
1.78 anton 10903: @item
10904: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10905: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10906:
1.78 anton 10907: doc---object-'
10908: doc---object-postpone
1.21 crook 10909:
10910:
1.78 anton 10911: @item
10912: @code{with} and @code{endwith} to select the active object from the
10913: stack, and enable its scope. Using @code{with} and @code{endwith}
10914: also allows you to create code using selector @code{postpone} without being
10915: trapped by the state-smart objects.
1.21 crook 10916:
1.78 anton 10917: doc---object-with
10918: doc---object-endwith
1.21 crook 10919:
10920:
1.78 anton 10921: @end itemize
1.21 crook 10922:
1.78 anton 10923: @node Class Declaration, Class Implementation, The OOF base class, OOF
10924: @subsubsection Class Declaration
10925: @cindex class declaration
1.21 crook 10926:
1.78 anton 10927: @itemize @bullet
10928: @item
10929: Instance variables
1.21 crook 10930:
1.78 anton 10931: doc---oof-var
1.21 crook 10932:
10933:
1.78 anton 10934: @item
10935: Object pointers
1.21 crook 10936:
1.78 anton 10937: doc---oof-ptr
10938: doc---oof-asptr
1.21 crook 10939:
10940:
1.78 anton 10941: @item
10942: Instance defers
1.21 crook 10943:
1.78 anton 10944: doc---oof-defer
1.21 crook 10945:
10946:
1.78 anton 10947: @item
10948: Method selectors
1.21 crook 10949:
1.78 anton 10950: doc---oof-early
10951: doc---oof-method
1.21 crook 10952:
10953:
1.78 anton 10954: @item
10955: Class-wide variables
1.21 crook 10956:
1.78 anton 10957: doc---oof-static
1.21 crook 10958:
10959:
1.78 anton 10960: @item
10961: End declaration
1.1 anton 10962:
1.78 anton 10963: doc---oof-how:
10964: doc---oof-class;
1.21 crook 10965:
10966:
1.78 anton 10967: @end itemize
1.21 crook 10968:
1.78 anton 10969: @c -------------------------------------------------------------
10970: @node Class Implementation, , Class Declaration, OOF
10971: @subsubsection Class Implementation
10972: @cindex class implementation
1.21 crook 10973:
1.78 anton 10974: @c -------------------------------------------------------------
10975: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10976: @subsection The @file{mini-oof.fs} model
10977: @cindex mini-oof
1.21 crook 10978:
1.78 anton 10979: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 10980: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 10981: and reduces to the bare minimum of features. This is based on a posting
10982: of Bernd Paysan in comp.lang.forth.
1.21 crook 10983:
1.78 anton 10984: @menu
10985: * Basic Mini-OOF Usage::
10986: * Mini-OOF Example::
10987: * Mini-OOF Implementation::
10988: @end menu
1.21 crook 10989:
1.78 anton 10990: @c -------------------------------------------------------------
10991: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10992: @subsubsection Basic @file{mini-oof.fs} Usage
10993: @cindex mini-oof usage
1.21 crook 10994:
1.78 anton 10995: There is a base class (@code{class}, which allocates one cell for the
10996: object pointer) plus seven other words: to define a method, a variable,
10997: a class; to end a class, to resolve binding, to allocate an object and
10998: to compile a class method.
10999: @comment TODO better description of the last one
1.26 crook 11000:
1.21 crook 11001:
1.78 anton 11002: doc-object
11003: doc-method
11004: doc-var
11005: doc-class
11006: doc-end-class
11007: doc-defines
11008: doc-new
11009: doc-::
1.21 crook 11010:
11011:
11012:
1.78 anton 11013: @c -------------------------------------------------------------
11014: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11015: @subsubsection Mini-OOF Example
11016: @cindex mini-oof example
1.1 anton 11017:
1.78 anton 11018: A short example shows how to use this package. This example, in slightly
11019: extended form, is supplied as @file{moof-exm.fs}
11020: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11021:
1.26 crook 11022: @example
1.78 anton 11023: object class
11024: method init
11025: method draw
11026: end-class graphical
1.26 crook 11027: @end example
1.20 pazsan 11028:
1.78 anton 11029: This code defines a class @code{graphical} with an
11030: operation @code{draw}. We can perform the operation
11031: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11032:
1.26 crook 11033: @example
1.78 anton 11034: 100 100 t-rex draw
1.26 crook 11035: @end example
1.12 anton 11036:
1.78 anton 11037: where @code{t-rex} is an object or object pointer, created with e.g.
11038: @code{graphical new Constant t-rex}.
1.12 anton 11039:
1.78 anton 11040: For concrete graphical objects, we define child classes of the
11041: class @code{graphical}, e.g.:
1.12 anton 11042:
1.26 crook 11043: @example
11044: graphical class
1.78 anton 11045: cell var circle-radius
11046: end-class circle \ "graphical" is the parent class
1.12 anton 11047:
1.78 anton 11048: :noname ( x y -- )
11049: circle-radius @@ draw-circle ; circle defines draw
11050: :noname ( r -- )
11051: circle-radius ! ; circle defines init
11052: @end example
1.12 anton 11053:
1.78 anton 11054: There is no implicit init method, so we have to define one. The creation
11055: code of the object now has to call init explicitely.
1.21 crook 11056:
1.78 anton 11057: @example
11058: circle new Constant my-circle
11059: 50 my-circle init
1.12 anton 11060: @end example
11061:
1.78 anton 11062: It is also possible to add a function to create named objects with
11063: automatic call of @code{init}, given that all objects have @code{init}
11064: on the same place:
1.38 anton 11065:
1.78 anton 11066: @example
11067: : new: ( .. o "name" -- )
11068: new dup Constant init ;
11069: 80 circle new: large-circle
11070: @end example
1.12 anton 11071:
1.78 anton 11072: We can draw this new circle at (100,100) with:
1.12 anton 11073:
1.78 anton 11074: @example
11075: 100 100 my-circle draw
11076: @end example
1.12 anton 11077:
1.78 anton 11078: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11079: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11080:
1.78 anton 11081: Object-oriented systems with late binding typically use a
11082: ``vtable''-approach: the first variable in each object is a pointer to a
11083: table, which contains the methods as function pointers. The vtable
11084: may also contain other information.
1.12 anton 11085:
1.79 anton 11086: So first, let's declare selectors:
1.37 anton 11087:
11088: @example
1.79 anton 11089: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11090: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11091: @end example
1.37 anton 11092:
1.79 anton 11093: During selector declaration, the number of selectors and instance
11094: variables is on the stack (in address units). @code{method} creates one
11095: selector and increments the selector number. To execute a selector, it
1.78 anton 11096: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11097: executes the method @i{xt} stored there. Each selector takes the object
11098: it is invoked with as top of stack parameter; it passes the parameters
11099: (including the object) unchanged to the appropriate method which should
1.78 anton 11100: consume that object.
1.37 anton 11101:
1.78 anton 11102: Now, we also have to declare instance variables
1.37 anton 11103:
1.78 anton 11104: @example
1.79 anton 11105: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11106: DOES> ( o -- addr ) @@ + ;
1.37 anton 11107: @end example
11108:
1.78 anton 11109: As before, a word is created with the current offset. Instance
11110: variables can have different sizes (cells, floats, doubles, chars), so
11111: all we do is take the size and add it to the offset. If your machine
11112: has alignment restrictions, put the proper @code{aligned} or
11113: @code{faligned} before the variable, to adjust the variable
11114: offset. That's why it is on the top of stack.
1.37 anton 11115:
1.78 anton 11116: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11117:
1.78 anton 11118: @example
11119: Create object 1 cells , 2 cells ,
1.79 anton 11120: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11121: @end example
1.12 anton 11122:
1.78 anton 11123: For inheritance, the vtable of the parent object has to be
11124: copied when a new, derived class is declared. This gives all the
11125: methods of the parent class, which can be overridden, though.
1.12 anton 11126:
1.78 anton 11127: @example
1.79 anton 11128: : end-class ( class selectors vars "name" -- )
1.78 anton 11129: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11130: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11131: @end example
1.12 anton 11132:
1.78 anton 11133: The first line creates the vtable, initialized with
11134: @code{noop}s. The second line is the inheritance mechanism, it
11135: copies the xts from the parent vtable.
1.12 anton 11136:
1.78 anton 11137: We still have no way to define new methods, let's do that now:
1.12 anton 11138:
1.26 crook 11139: @example
1.79 anton 11140: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11141: @end example
1.12 anton 11142:
1.78 anton 11143: To allocate a new object, we need a word, too:
1.12 anton 11144:
1.78 anton 11145: @example
11146: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11147: @end example
11148:
1.78 anton 11149: Sometimes derived classes want to access the method of the
11150: parent object. There are two ways to achieve this with Mini-OOF:
11151: first, you could use named words, and second, you could look up the
11152: vtable of the parent object.
1.12 anton 11153:
1.78 anton 11154: @example
11155: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11156: @end example
1.12 anton 11157:
11158:
1.78 anton 11159: Nothing can be more confusing than a good example, so here is
11160: one. First let's declare a text object (called
11161: @code{button}), that stores text and position:
1.12 anton 11162:
1.78 anton 11163: @example
11164: object class
11165: cell var text
11166: cell var len
11167: cell var x
11168: cell var y
11169: method init
11170: method draw
11171: end-class button
11172: @end example
1.12 anton 11173:
1.78 anton 11174: @noindent
11175: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11176:
1.26 crook 11177: @example
1.78 anton 11178: :noname ( o -- )
11179: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11180: button defines draw
11181: :noname ( addr u o -- )
11182: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11183: button defines init
1.26 crook 11184: @end example
1.12 anton 11185:
1.78 anton 11186: @noindent
11187: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11188: new data and no new selectors:
1.78 anton 11189:
11190: @example
11191: button class
11192: end-class bold-button
1.12 anton 11193:
1.78 anton 11194: : bold 27 emit ." [1m" ;
11195: : normal 27 emit ." [0m" ;
11196: @end example
1.1 anton 11197:
1.78 anton 11198: @noindent
11199: The class @code{bold-button} has a different draw method to
11200: @code{button}, but the new method is defined in terms of the draw method
11201: for @code{button}:
1.20 pazsan 11202:
1.78 anton 11203: @example
11204: :noname bold [ button :: draw ] normal ; bold-button defines draw
11205: @end example
1.21 crook 11206:
1.78 anton 11207: @noindent
1.79 anton 11208: Finally, create two objects and apply selectors:
1.21 crook 11209:
1.26 crook 11210: @example
1.78 anton 11211: button new Constant foo
11212: s" thin foo" foo init
11213: page
11214: foo draw
11215: bold-button new Constant bar
11216: s" fat bar" bar init
11217: 1 bar y !
11218: bar draw
1.26 crook 11219: @end example
1.21 crook 11220:
11221:
1.78 anton 11222: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11223: @subsection Comparison with other object models
11224: @cindex comparison of object models
11225: @cindex object models, comparison
11226:
11227: Many object-oriented Forth extensions have been proposed (@cite{A survey
11228: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11229: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11230: relation of the object models described here to two well-known and two
11231: closely-related (by the use of method maps) models. Andras Zsoter
11232: helped us with this section.
11233:
11234: @cindex Neon model
11235: The most popular model currently seems to be the Neon model (see
11236: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11237: 1997) by Andrew McKewan) but this model has a number of limitations
11238: @footnote{A longer version of this critique can be
11239: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11240: Dimensions, May 1997) by Anton Ertl.}:
11241:
11242: @itemize @bullet
11243: @item
11244: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11245: to pass objects on the stack.
1.21 crook 11246:
1.78 anton 11247: @item
11248: It requires that the selector parses the input stream (at
1.79 anton 11249: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11250: hard to find.
1.21 crook 11251:
1.78 anton 11252: @item
1.79 anton 11253: It allows using every selector on every object; this eliminates the
11254: need for interfaces, but makes it harder to create efficient
11255: implementations.
1.78 anton 11256: @end itemize
1.21 crook 11257:
1.78 anton 11258: @cindex Pountain's object-oriented model
11259: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11260: Press, London, 1987) by Dick Pountain. However, it is not really about
11261: object-oriented programming, because it hardly deals with late
11262: binding. Instead, it focuses on features like information hiding and
11263: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11264:
1.78 anton 11265: @cindex Zsoter's object-oriented model
1.79 anton 11266: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11267: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11268: describes a model that makes heavy use of an active object (like
11269: @code{this} in @file{objects.fs}): The active object is not only used
11270: for accessing all fields, but also specifies the receiving object of
11271: every selector invocation; you have to change the active object
11272: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11273: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11274: the method entry point is unnecessary with Zsoter's model, because the
11275: receiving object is the active object already. On the other hand, the
11276: explicit change is absolutely necessary in that model, because otherwise
11277: no one could ever change the active object. An ANS Forth implementation
11278: of this model is available through
11279: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11280:
1.78 anton 11281: @cindex @file{oof.fs}, differences to other models
11282: The @file{oof.fs} model combines information hiding and overloading
11283: resolution (by keeping names in various word lists) with object-oriented
11284: programming. It sets the active object implicitly on method entry, but
11285: also allows explicit changing (with @code{>o...o>} or with
11286: @code{with...endwith}). It uses parsing and state-smart objects and
11287: classes for resolving overloading and for early binding: the object or
11288: class parses the selector and determines the method from this. If the
11289: selector is not parsed by an object or class, it performs a call to the
11290: selector for the active object (late binding), like Zsoter's model.
11291: Fields are always accessed through the active object. The big
11292: disadvantage of this model is the parsing and the state-smartness, which
11293: reduces extensibility and increases the opportunities for subtle bugs;
11294: essentially, you are only safe if you never tick or @code{postpone} an
11295: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11296:
1.78 anton 11297: @cindex @file{mini-oof.fs}, differences to other models
11298: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11299: version of the @file{objects.fs} model, but syntactically it is a
11300: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11301:
11302:
1.78 anton 11303: @c -------------------------------------------------------------
11304: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11305: @section Programming Tools
11306: @cindex programming tools
1.21 crook 11307:
1.78 anton 11308: @c !! move this and assembler down below OO stuff.
1.21 crook 11309:
1.78 anton 11310: @menu
11311: * Examining::
11312: * Forgetting words::
11313: * Debugging:: Simple and quick.
11314: * Assertions:: Making your programs self-checking.
11315: * Singlestep Debugger:: Executing your program word by word.
11316: @end menu
1.21 crook 11317:
1.78 anton 11318: @node Examining, Forgetting words, Programming Tools, Programming Tools
11319: @subsection Examining data and code
11320: @cindex examining data and code
11321: @cindex data examination
11322: @cindex code examination
1.44 crook 11323:
1.78 anton 11324: The following words inspect the stack non-destructively:
1.21 crook 11325:
1.78 anton 11326: doc-.s
11327: doc-f.s
1.44 crook 11328:
1.78 anton 11329: There is a word @code{.r} but it does @i{not} display the return stack!
11330: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11331:
1.78 anton 11332: doc-depth
11333: doc-fdepth
11334: doc-clearstack
1.124 anton 11335: doc-clearstacks
1.21 crook 11336:
1.78 anton 11337: The following words inspect memory.
1.21 crook 11338:
1.78 anton 11339: doc-?
11340: doc-dump
1.21 crook 11341:
1.78 anton 11342: And finally, @code{see} allows to inspect code:
1.21 crook 11343:
1.78 anton 11344: doc-see
11345: doc-xt-see
1.111 anton 11346: doc-simple-see
11347: doc-simple-see-range
1.21 crook 11348:
1.78 anton 11349: @node Forgetting words, Debugging, Examining, Programming Tools
11350: @subsection Forgetting words
11351: @cindex words, forgetting
11352: @cindex forgeting words
1.21 crook 11353:
1.78 anton 11354: @c anton: other, maybe better places for this subsection: Defining Words;
11355: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11356:
1.78 anton 11357: Forth allows you to forget words (and everything that was alloted in the
11358: dictonary after them) in a LIFO manner.
1.21 crook 11359:
1.78 anton 11360: doc-marker
1.21 crook 11361:
1.78 anton 11362: The most common use of this feature is during progam development: when
11363: you change a source file, forget all the words it defined and load it
11364: again (since you also forget everything defined after the source file
11365: was loaded, you have to reload that, too). Note that effects like
11366: storing to variables and destroyed system words are not undone when you
11367: forget words. With a system like Gforth, that is fast enough at
11368: starting up and compiling, I find it more convenient to exit and restart
11369: Gforth, as this gives me a clean slate.
1.21 crook 11370:
1.78 anton 11371: Here's an example of using @code{marker} at the start of a source file
11372: that you are debugging; it ensures that you only ever have one copy of
11373: the file's definitions compiled at any time:
1.21 crook 11374:
1.78 anton 11375: @example
11376: [IFDEF] my-code
11377: my-code
11378: [ENDIF]
1.26 crook 11379:
1.78 anton 11380: marker my-code
11381: init-included-files
1.21 crook 11382:
1.78 anton 11383: \ .. definitions start here
11384: \ .
11385: \ .
11386: \ end
11387: @end example
1.21 crook 11388:
1.26 crook 11389:
1.78 anton 11390: @node Debugging, Assertions, Forgetting words, Programming Tools
11391: @subsection Debugging
11392: @cindex debugging
1.21 crook 11393:
1.78 anton 11394: Languages with a slow edit/compile/link/test development loop tend to
11395: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11396:
1.78 anton 11397: A much better (faster) way in fast-compiling languages is to add
11398: printing code at well-selected places, let the program run, look at
11399: the output, see where things went wrong, add more printing code, etc.,
11400: until the bug is found.
1.21 crook 11401:
1.78 anton 11402: The simple debugging aids provided in @file{debugs.fs}
11403: are meant to support this style of debugging.
1.21 crook 11404:
1.78 anton 11405: The word @code{~~} prints debugging information (by default the source
11406: location and the stack contents). It is easy to insert. If you use Emacs
11407: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11408: query-replace them with nothing). The deferred words
1.101 anton 11409: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11410: @code{~~}. The default source location output format works well with
11411: Emacs' compilation mode, so you can step through the program at the
11412: source level using @kbd{C-x `} (the advantage over a stepping debugger
11413: is that you can step in any direction and you know where the crash has
11414: happened or where the strange data has occurred).
1.21 crook 11415:
1.78 anton 11416: doc-~~
11417: doc-printdebugdata
1.101 anton 11418: doc-.debugline
1.21 crook 11419:
1.106 anton 11420: @cindex filenames in @code{~~} output
11421: @code{~~} (and assertions) will usually print the wrong file name if a
11422: marker is executed in the same file after their occurance. They will
11423: print @samp{*somewhere*} as file name if a marker is executed in the
11424: same file before their occurance.
11425:
11426:
1.78 anton 11427: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11428: @subsection Assertions
11429: @cindex assertions
1.21 crook 11430:
1.78 anton 11431: It is a good idea to make your programs self-checking, especially if you
11432: make an assumption that may become invalid during maintenance (for
11433: example, that a certain field of a data structure is never zero). Gforth
11434: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11435:
11436: @example
1.78 anton 11437: assert( @i{flag} )
1.26 crook 11438: @end example
11439:
1.78 anton 11440: The code between @code{assert(} and @code{)} should compute a flag, that
11441: should be true if everything is alright and false otherwise. It should
11442: not change anything else on the stack. The overall stack effect of the
11443: assertion is @code{( -- )}. E.g.
1.21 crook 11444:
1.26 crook 11445: @example
1.78 anton 11446: assert( 1 1 + 2 = ) \ what we learn in school
11447: assert( dup 0<> ) \ assert that the top of stack is not zero
11448: assert( false ) \ this code should not be reached
1.21 crook 11449: @end example
11450:
1.78 anton 11451: The need for assertions is different at different times. During
11452: debugging, we want more checking, in production we sometimes care more
11453: for speed. Therefore, assertions can be turned off, i.e., the assertion
11454: becomes a comment. Depending on the importance of an assertion and the
11455: time it takes to check it, you may want to turn off some assertions and
11456: keep others turned on. Gforth provides several levels of assertions for
11457: this purpose:
11458:
11459:
11460: doc-assert0(
11461: doc-assert1(
11462: doc-assert2(
11463: doc-assert3(
11464: doc-assert(
11465: doc-)
1.21 crook 11466:
11467:
1.78 anton 11468: The variable @code{assert-level} specifies the highest assertions that
11469: are turned on. I.e., at the default @code{assert-level} of one,
11470: @code{assert0(} and @code{assert1(} assertions perform checking, while
11471: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11472:
1.78 anton 11473: The value of @code{assert-level} is evaluated at compile-time, not at
11474: run-time. Therefore you cannot turn assertions on or off at run-time;
11475: you have to set the @code{assert-level} appropriately before compiling a
11476: piece of code. You can compile different pieces of code at different
11477: @code{assert-level}s (e.g., a trusted library at level 1 and
11478: newly-written code at level 3).
1.26 crook 11479:
11480:
1.78 anton 11481: doc-assert-level
1.26 crook 11482:
11483:
1.78 anton 11484: If an assertion fails, a message compatible with Emacs' compilation mode
11485: is produced and the execution is aborted (currently with @code{ABORT"}.
11486: If there is interest, we will introduce a special throw code. But if you
11487: intend to @code{catch} a specific condition, using @code{throw} is
11488: probably more appropriate than an assertion).
1.106 anton 11489:
11490: @cindex filenames in assertion output
11491: Assertions (and @code{~~}) will usually print the wrong file name if a
11492: marker is executed in the same file after their occurance. They will
11493: print @samp{*somewhere*} as file name if a marker is executed in the
11494: same file before their occurance.
1.44 crook 11495:
1.78 anton 11496: Definitions in ANS Forth for these assertion words are provided
11497: in @file{compat/assert.fs}.
1.26 crook 11498:
1.44 crook 11499:
1.78 anton 11500: @node Singlestep Debugger, , Assertions, Programming Tools
11501: @subsection Singlestep Debugger
11502: @cindex singlestep Debugger
11503: @cindex debugging Singlestep
1.44 crook 11504:
1.112 anton 11505: The singlestep debugger does not work in this release.
11506:
1.78 anton 11507: When you create a new word there's often the need to check whether it
11508: behaves correctly or not. You can do this by typing @code{dbg
11509: badword}. A debug session might look like this:
1.26 crook 11510:
1.78 anton 11511: @example
11512: : badword 0 DO i . LOOP ; ok
11513: 2 dbg badword
11514: : badword
11515: Scanning code...
1.44 crook 11516:
1.78 anton 11517: Nesting debugger ready!
1.44 crook 11518:
1.78 anton 11519: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11520: 400D4740 8049F68 DO -> [ 0 ]
11521: 400D4744 804A0C8 i -> [ 1 ] 00000
11522: 400D4748 400C5E60 . -> 0 [ 0 ]
11523: 400D474C 8049D0C LOOP -> [ 0 ]
11524: 400D4744 804A0C8 i -> [ 1 ] 00001
11525: 400D4748 400C5E60 . -> 1 [ 0 ]
11526: 400D474C 8049D0C LOOP -> [ 0 ]
11527: 400D4758 804B384 ; -> ok
11528: @end example
1.21 crook 11529:
1.78 anton 11530: Each line displayed is one step. You always have to hit return to
11531: execute the next word that is displayed. If you don't want to execute
11532: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11533: an overview what keys are available:
1.44 crook 11534:
1.78 anton 11535: @table @i
1.44 crook 11536:
1.78 anton 11537: @item @key{RET}
11538: Next; Execute the next word.
1.21 crook 11539:
1.78 anton 11540: @item n
11541: Nest; Single step through next word.
1.44 crook 11542:
1.78 anton 11543: @item u
11544: Unnest; Stop debugging and execute rest of word. If we got to this word
11545: with nest, continue debugging with the calling word.
1.44 crook 11546:
1.78 anton 11547: @item d
11548: Done; Stop debugging and execute rest.
1.21 crook 11549:
1.78 anton 11550: @item s
11551: Stop; Abort immediately.
1.44 crook 11552:
1.78 anton 11553: @end table
1.44 crook 11554:
1.78 anton 11555: Debugging large application with this mechanism is very difficult, because
11556: you have to nest very deeply into the program before the interesting part
11557: begins. This takes a lot of time.
1.26 crook 11558:
1.78 anton 11559: To do it more directly put a @code{BREAK:} command into your source code.
11560: When program execution reaches @code{BREAK:} the single step debugger is
11561: invoked and you have all the features described above.
1.44 crook 11562:
1.78 anton 11563: If you have more than one part to debug it is useful to know where the
11564: program has stopped at the moment. You can do this by the
11565: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11566: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11567:
1.26 crook 11568:
1.78 anton 11569: doc-dbg
11570: doc-break:
11571: doc-break"
1.44 crook 11572:
11573:
1.26 crook 11574:
1.78 anton 11575: @c -------------------------------------------------------------
11576: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11577: @section Assembler and Code Words
11578: @cindex assembler
11579: @cindex code words
1.44 crook 11580:
1.78 anton 11581: @menu
11582: * Code and ;code::
11583: * Common Assembler:: Assembler Syntax
11584: * Common Disassembler::
11585: * 386 Assembler:: Deviations and special cases
11586: * Alpha Assembler:: Deviations and special cases
11587: * MIPS assembler:: Deviations and special cases
11588: * Other assemblers:: How to write them
11589: @end menu
1.21 crook 11590:
1.78 anton 11591: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11592: @subsection @code{Code} and @code{;code}
1.26 crook 11593:
1.78 anton 11594: Gforth provides some words for defining primitives (words written in
11595: machine code), and for defining the machine-code equivalent of
11596: @code{DOES>}-based defining words. However, the machine-independent
11597: nature of Gforth poses a few problems: First of all, Gforth runs on
11598: several architectures, so it can provide no standard assembler. What's
11599: worse is that the register allocation not only depends on the processor,
11600: but also on the @code{gcc} version and options used.
1.44 crook 11601:
1.78 anton 11602: The words that Gforth offers encapsulate some system dependences (e.g.,
11603: the header structure), so a system-independent assembler may be used in
11604: Gforth. If you do not have an assembler, you can compile machine code
11605: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11606: because these words emit stuff in @i{data} space; it works because
11607: Gforth has unified code/data spaces. Assembler isn't likely to be
11608: portable anyway.}.
1.21 crook 11609:
1.44 crook 11610:
1.78 anton 11611: doc-assembler
11612: doc-init-asm
11613: doc-code
11614: doc-end-code
11615: doc-;code
11616: doc-flush-icache
1.44 crook 11617:
1.21 crook 11618:
1.78 anton 11619: If @code{flush-icache} does not work correctly, @code{code} words
11620: etc. will not work (reliably), either.
1.44 crook 11621:
1.78 anton 11622: The typical usage of these @code{code} words can be shown most easily by
11623: analogy to the equivalent high-level defining words:
1.44 crook 11624:
1.78 anton 11625: @example
11626: : foo code foo
11627: <high-level Forth words> <assembler>
11628: ; end-code
11629:
11630: : bar : bar
11631: <high-level Forth words> <high-level Forth words>
11632: CREATE CREATE
11633: <high-level Forth words> <high-level Forth words>
11634: DOES> ;code
11635: <high-level Forth words> <assembler>
11636: ; end-code
11637: @end example
1.21 crook 11638:
1.78 anton 11639: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11640:
1.78 anton 11641: @cindex registers of the inner interpreter
11642: In the assembly code you will want to refer to the inner interpreter's
11643: registers (e.g., the data stack pointer) and you may want to use other
11644: registers for temporary storage. Unfortunately, the register allocation
11645: is installation-dependent.
1.44 crook 11646:
1.78 anton 11647: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11648: (return stack pointer) may be in different places in @code{gforth} and
11649: @code{gforth-fast}, or different installations. This means that you
11650: cannot write a @code{NEXT} routine that works reliably on both versions
11651: or different installations; so for doing @code{NEXT}, I recommend
11652: jumping to @code{' noop >code-address}, which contains nothing but a
11653: @code{NEXT}.
1.21 crook 11654:
1.78 anton 11655: For general accesses to the inner interpreter's registers, the easiest
11656: solution is to use explicit register declarations (@pxref{Explicit Reg
11657: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11658: all of the inner interpreter's registers: You have to compile Gforth
11659: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11660: the appropriate declarations must be present in the @code{machine.h}
11661: file (see @code{mips.h} for an example; you can find a full list of all
11662: declarable register symbols with @code{grep register engine.c}). If you
11663: give explicit registers to all variables that are declared at the
11664: beginning of @code{engine()}, you should be able to use the other
11665: caller-saved registers for temporary storage. Alternatively, you can use
11666: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11667: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11668: reserve a register (however, this restriction on register allocation may
11669: slow Gforth significantly).
1.44 crook 11670:
1.78 anton 11671: If this solution is not viable (e.g., because @code{gcc} does not allow
11672: you to explicitly declare all the registers you need), you have to find
11673: out by looking at the code where the inner interpreter's registers
11674: reside and which registers can be used for temporary storage. You can
11675: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11676:
1.78 anton 11677: In any case, it is good practice to abstract your assembly code from the
11678: actual register allocation. E.g., if the data stack pointer resides in
11679: register @code{$17}, create an alias for this register called @code{sp},
11680: and use that in your assembly code.
1.21 crook 11681:
1.78 anton 11682: @cindex code words, portable
11683: Another option for implementing normal and defining words efficiently
11684: is to add the desired functionality to the source of Gforth. For normal
11685: words you just have to edit @file{primitives} (@pxref{Automatic
11686: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11687: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11688: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11689:
1.78 anton 11690: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11691: @subsection Common Assembler
1.44 crook 11692:
1.78 anton 11693: The assemblers in Gforth generally use a postfix syntax, i.e., the
11694: instruction name follows the operands.
1.21 crook 11695:
1.78 anton 11696: The operands are passed in the usual order (the same that is used in the
11697: manual of the architecture). Since they all are Forth words, they have
11698: to be separated by spaces; you can also use Forth words to compute the
11699: operands.
1.44 crook 11700:
1.78 anton 11701: The instruction names usually end with a @code{,}. This makes it easier
11702: to visually separate instructions if you put several of them on one
11703: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11704:
1.78 anton 11705: Registers are usually specified by number; e.g., (decimal) @code{11}
11706: specifies registers R11 and F11 on the Alpha architecture (which one,
11707: depends on the instruction). The usual names are also available, e.g.,
11708: @code{s2} for R11 on Alpha.
1.21 crook 11709:
1.78 anton 11710: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11711: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11712: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11713: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11714: conditions are specified in a way specific to each assembler.
1.1 anton 11715:
1.78 anton 11716: Note that the register assignments of the Gforth engine can change
11717: between Gforth versions, or even between different compilations of the
11718: same Gforth version (e.g., if you use a different GCC version). So if
11719: you want to refer to Gforth's registers (e.g., the stack pointer or
11720: TOS), I recommend defining your own words for refering to these
11721: registers, and using them later on; then you can easily adapt to a
11722: changed register assignment. The stability of the register assignment
11723: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11724:
1.100 anton 11725: The most common use of these registers is to dispatch to the next word
11726: (the @code{next} routine). A portable way to do this is to jump to
11727: @code{' noop >code-address} (of course, this is less efficient than
11728: integrating the @code{next} code and scheduling it well).
1.1 anton 11729:
1.96 anton 11730: Another difference between Gforth version is that the top of stack is
11731: kept in memory in @code{gforth} and, on most platforms, in a register in
11732: @code{gforth-fast}.
11733:
1.78 anton 11734: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11735: @subsection Common Disassembler
1.127 anton 11736: @cindex disassembler, general
11737: @cindex gdb disassembler
1.1 anton 11738:
1.78 anton 11739: You can disassemble a @code{code} word with @code{see}
11740: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11741:
1.127 anton 11742: doc-discode
1.44 crook 11743:
1.127 anton 11744: There are two kinds of disassembler for Gforth: The Forth disassembler
11745: (available on some CPUs) and the gdb disassembler (available on
11746: platforms with @command{gdb} and @command{mktemp}). If both are
11747: available, the Forth disassembler is used by default. If you prefer
11748: the gdb disassembler, say
11749:
11750: @example
11751: ' disasm-gdb is discode
11752: @end example
11753:
11754: If neither is available, @code{discode} performs @code{dump}.
11755:
11756: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11757: assembler (i.e., same syntax, etc.). It also includes additional
11758: information in comments. In particular, the address of the instruction
11759: is given in a comment before the instruction.
1.1 anton 11760:
1.127 anton 11761: The gdb disassembler produces output in the same format as the gdb
11762: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11763: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11764: the 386 and AMD64 architectures).
11765:
1.78 anton 11766: @code{See} may display more or less than the actual code of the word,
11767: because the recognition of the end of the code is unreliable. You can
1.127 anton 11768: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11769: the code word is not immediately followed by a named word. If you have
1.116 anton 11770: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11771: to ensure that the end is recognized.
1.21 crook 11772:
1.78 anton 11773: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11774: @subsection 386 Assembler
1.44 crook 11775:
1.78 anton 11776: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11777: available under GPL, and originally part of bigFORTH.
1.21 crook 11778:
1.78 anton 11779: The 386 disassembler included in Gforth was written by Andrew McKewan
11780: and is in the public domain.
1.21 crook 11781:
1.91 anton 11782: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11783:
1.78 anton 11784: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11785:
1.78 anton 11786: The assembler includes all instruction of the Athlon, i.e. 486 core
11787: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11788: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11789: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11790:
1.78 anton 11791: There are several prefixes to switch between different operation sizes,
11792: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11793: double-word accesses. Addressing modes can be switched with @code{.wa}
11794: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11795: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11796:
1.78 anton 11797: For floating point operations, the prefixes are @code{.fs} (IEEE
11798: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11799: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11800:
1.78 anton 11801: The MMX opcodes don't have size prefixes, they are spelled out like in
11802: the Intel assembler. Instead of move from and to memory, there are
11803: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11804:
1.78 anton 11805: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11806: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11807: e.g., @code{3 #}. Here are some examples of addressing modes in various
11808: syntaxes:
1.21 crook 11809:
1.26 crook 11810: @example
1.91 anton 11811: Gforth Intel (NASM) AT&T (gas) Name
11812: .w ax ax %ax register (16 bit)
11813: ax eax %eax register (32 bit)
11814: 3 # offset 3 $3 immediate
11815: 1000 #) byte ptr 1000 1000 displacement
11816: bx ) [ebx] (%ebx) base
11817: 100 di d) 100[edi] 100(%edi) base+displacement
11818: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11819: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11820: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11821: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11822: @end example
11823:
11824: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11825: @code{DI)} to enforce 32-bit displacement fields (useful for
11826: later patching).
1.21 crook 11827:
1.78 anton 11828: Some example of instructions are:
1.1 anton 11829:
11830: @example
1.78 anton 11831: ax bx mov \ move ebx,eax
11832: 3 # ax mov \ mov eax,3
11833: 100 di ) ax mov \ mov eax,100[edi]
11834: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11835: .w ax bx mov \ mov bx,ax
1.1 anton 11836: @end example
11837:
1.78 anton 11838: The following forms are supported for binary instructions:
1.1 anton 11839:
11840: @example
1.78 anton 11841: <reg> <reg> <inst>
11842: <n> # <reg> <inst>
11843: <mem> <reg> <inst>
11844: <reg> <mem> <inst>
1.1 anton 11845: @end example
11846:
1.78 anton 11847: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11848:
1.26 crook 11849: @example
1.78 anton 11850: <reg/mem> 1 # shl \ shortens to shift without immediate
11851: <reg/mem> 4 # shl
11852: <reg/mem> cl shl
1.26 crook 11853: @end example
1.1 anton 11854:
1.78 anton 11855: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11856: the byte version.
1.1 anton 11857:
1.78 anton 11858: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11859: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11860: pc < >= <= >}. (Note that most of these words shadow some Forth words
11861: when @code{assembler} is in front of @code{forth} in the search path,
11862: e.g., in @code{code} words). Currently the control structure words use
11863: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11864: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11865:
1.78 anton 11866: Here is an example of a @code{code} word (assumes that the stack pointer
11867: is in esi and the TOS is in ebx):
1.21 crook 11868:
1.26 crook 11869: @example
1.78 anton 11870: code my+ ( n1 n2 -- n )
11871: 4 si D) bx add
11872: 4 # si add
11873: Next
11874: end-code
1.26 crook 11875: @end example
1.21 crook 11876:
1.78 anton 11877: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11878: @subsection Alpha Assembler
1.21 crook 11879:
1.78 anton 11880: The Alpha assembler and disassembler were originally written by Bernd
11881: Thallner.
1.26 crook 11882:
1.78 anton 11883: The register names @code{a0}--@code{a5} are not available to avoid
11884: shadowing hex numbers.
1.2 jwilke 11885:
1.78 anton 11886: Immediate forms of arithmetic instructions are distinguished by a
11887: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11888: does not count as arithmetic instruction).
1.2 jwilke 11889:
1.78 anton 11890: You have to specify all operands to an instruction, even those that
11891: other assemblers consider optional, e.g., the destination register for
11892: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11893:
1.78 anton 11894: You can specify conditions for @code{if,} by removing the first @code{b}
11895: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11896:
1.26 crook 11897: @example
1.78 anton 11898: 11 fgt if, \ if F11>0e
11899: ...
11900: endif,
1.26 crook 11901: @end example
1.2 jwilke 11902:
1.78 anton 11903: @code{fbgt,} gives @code{fgt}.
11904:
11905: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11906: @subsection MIPS assembler
1.2 jwilke 11907:
1.78 anton 11908: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11909:
1.78 anton 11910: Currently the assembler and disassembler only cover the MIPS-I
11911: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11912:
1.78 anton 11913: The register names @code{$a0}--@code{$a3} are not available to avoid
11914: shadowing hex numbers.
1.2 jwilke 11915:
1.78 anton 11916: Because there is no way to distinguish registers from immediate values,
11917: you have to explicitly use the immediate forms of instructions, i.e.,
11918: @code{addiu,}, not just @code{addu,} (@command{as} does this
11919: implicitly).
1.2 jwilke 11920:
1.78 anton 11921: If the architecture manual specifies several formats for the instruction
11922: (e.g., for @code{jalr,}), you usually have to use the one with more
11923: arguments (i.e., two for @code{jalr,}). When in doubt, see
11924: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11925:
1.78 anton 11926: Branches and jumps in the MIPS architecture have a delay slot. You have
11927: to fill it yourself (the simplest way is to use @code{nop,}), the
11928: assembler does not do it for you (unlike @command{as}). Even
11929: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11930: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11931: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11932:
1.78 anton 11933: Note that you must not put branches, jumps, or @code{li,} into the delay
11934: slot: @code{li,} may expand to several instructions, and control flow
11935: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11936:
1.78 anton 11937: For branches the argument specifying the target is a relative address;
11938: You have to add the address of the delay slot to get the absolute
11939: address.
1.1 anton 11940:
1.78 anton 11941: The MIPS architecture also has load delay slots and restrictions on
11942: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11943: yourself to satisfy these restrictions, the assembler does not do it for
11944: you.
1.1 anton 11945:
1.78 anton 11946: You can specify the conditions for @code{if,} etc. by taking a
11947: conditional branch and leaving away the @code{b} at the start and the
11948: @code{,} at the end. E.g.,
1.1 anton 11949:
1.26 crook 11950: @example
1.78 anton 11951: 4 5 eq if,
11952: ... \ do something if $4 equals $5
11953: then,
1.26 crook 11954: @end example
1.1 anton 11955:
1.78 anton 11956: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11957: @subsection Other assemblers
11958:
11959: If you want to contribute another assembler/disassembler, please contact
1.103 anton 11960: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11961: an assembler already. If you are writing them from scratch, please use
11962: a similar syntax style as the one we use (i.e., postfix, commas at the
11963: end of the instruction names, @pxref{Common Assembler}); make the output
11964: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 11965: similar to the style we used.
11966:
11967: Hints on implementation: The most important part is to have a good test
11968: suite that contains all instructions. Once you have that, the rest is
11969: easy. For actual coding you can take a look at
11970: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11971: the assembler and disassembler, avoiding redundancy and some potential
11972: bugs. You can also look at that file (and @pxref{Advanced does> usage
11973: example}) to get ideas how to factor a disassembler.
11974:
11975: Start with the disassembler, because it's easier to reuse data from the
11976: disassembler for the assembler than the other way round.
1.1 anton 11977:
1.78 anton 11978: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11979: how simple it can be.
1.1 anton 11980:
1.78 anton 11981: @c -------------------------------------------------------------
11982: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11983: @section Threading Words
11984: @cindex threading words
1.1 anton 11985:
1.78 anton 11986: @cindex code address
11987: These words provide access to code addresses and other threading stuff
11988: in Gforth (and, possibly, other interpretive Forths). It more or less
11989: abstracts away the differences between direct and indirect threading
11990: (and, for direct threading, the machine dependences). However, at
11991: present this wordset is still incomplete. It is also pretty low-level;
11992: some day it will hopefully be made unnecessary by an internals wordset
11993: that abstracts implementation details away completely.
1.1 anton 11994:
1.78 anton 11995: The terminology used here stems from indirect threaded Forth systems; in
11996: such a system, the XT of a word is represented by the CFA (code field
11997: address) of a word; the CFA points to a cell that contains the code
11998: address. The code address is the address of some machine code that
11999: performs the run-time action of invoking the word (e.g., the
12000: @code{dovar:} routine pushes the address of the body of the word (a
12001: variable) on the stack
12002: ).
1.1 anton 12003:
1.78 anton 12004: @cindex code address
12005: @cindex code field address
12006: In an indirect threaded Forth, you can get the code address of @i{name}
12007: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12008: >code-address}, independent of the threading method.
1.1 anton 12009:
1.78 anton 12010: doc-threading-method
12011: doc->code-address
12012: doc-code-address!
1.1 anton 12013:
1.78 anton 12014: @cindex @code{does>}-handler
12015: @cindex @code{does>}-code
12016: For a word defined with @code{DOES>}, the code address usually points to
12017: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12018: routine (in Gforth on some platforms, it can also point to the dodoes
12019: routine itself). What you are typically interested in, though, is
12020: whether a word is a @code{DOES>}-defined word, and what Forth code it
12021: executes; @code{>does-code} tells you that.
1.1 anton 12022:
1.78 anton 12023: doc->does-code
1.1 anton 12024:
1.78 anton 12025: To create a @code{DOES>}-defined word with the following basic words,
12026: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12027: @code{/does-handler} aus behind you have to place your executable Forth
12028: code. Finally you have to create a word and modify its behaviour with
12029: @code{does-handler!}.
1.1 anton 12030:
1.78 anton 12031: doc-does-code!
12032: doc-does-handler!
12033: doc-/does-handler
1.1 anton 12034:
1.78 anton 12035: The code addresses produced by various defining words are produced by
12036: the following words:
1.1 anton 12037:
1.78 anton 12038: doc-docol:
12039: doc-docon:
12040: doc-dovar:
12041: doc-douser:
12042: doc-dodefer:
12043: doc-dofield:
1.1 anton 12044:
1.99 anton 12045: @cindex definer
12046: The following two words generalize @code{>code-address},
12047: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12048:
12049: doc->definer
12050: doc-definer!
12051:
1.26 crook 12052: @c -------------------------------------------------------------
1.78 anton 12053: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12054: @section Passing Commands to the Operating System
12055: @cindex operating system - passing commands
12056: @cindex shell commands
12057:
12058: Gforth allows you to pass an arbitrary string to the host operating
12059: system shell (if such a thing exists) for execution.
12060:
12061: doc-sh
12062: doc-system
12063: doc-$?
1.23 crook 12064: doc-getenv
1.44 crook 12065:
1.26 crook 12066: @c -------------------------------------------------------------
1.47 crook 12067: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12068: @section Keeping track of Time
12069: @cindex time-related words
12070:
12071: doc-ms
12072: doc-time&date
1.79 anton 12073: doc-utime
12074: doc-cputime
1.47 crook 12075:
12076:
12077: @c -------------------------------------------------------------
12078: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12079: @section Miscellaneous Words
12080: @cindex miscellaneous words
12081:
1.29 crook 12082: @comment TODO find homes for these
12083:
1.26 crook 12084: These section lists the ANS Forth words that are not documented
1.21 crook 12085: elsewhere in this manual. Ultimately, they all need proper homes.
12086:
1.68 anton 12087: doc-quit
1.44 crook 12088:
1.26 crook 12089: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12090: (@pxref{ANS conformance}):
1.21 crook 12091:
12092: @code{EDITOR}
12093: @code{EMIT?}
12094: @code{FORGET}
12095:
1.24 anton 12096: @c ******************************************************************
12097: @node Error messages, Tools, Words, Top
12098: @chapter Error messages
12099: @cindex error messages
12100: @cindex backtrace
12101:
12102: A typical Gforth error message looks like this:
12103:
12104: @example
1.86 anton 12105: in file included from \evaluated string/:-1
1.24 anton 12106: in file included from ./yyy.fs:1
12107: ./xxx.fs:4: Invalid memory address
12108: bar
12109: ^^^
1.79 anton 12110: Backtrace:
1.25 anton 12111: $400E664C @@
12112: $400E6664 foo
1.24 anton 12113: @end example
12114:
12115: The message identifying the error is @code{Invalid memory address}. The
12116: error happened when text-interpreting line 4 of the file
12117: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12118: word on the line where the error happened, is pointed out (with
12119: @code{^^^}).
12120:
12121: The file containing the error was included in line 1 of @file{./yyy.fs},
12122: and @file{yyy.fs} was included from a non-file (in this case, by giving
12123: @file{yyy.fs} as command-line parameter to Gforth).
12124:
12125: At the end of the error message you find a return stack dump that can be
12126: interpreted as a backtrace (possibly empty). On top you find the top of
12127: the return stack when the @code{throw} happened, and at the bottom you
12128: find the return stack entry just above the return stack of the topmost
12129: text interpreter.
12130:
12131: To the right of most return stack entries you see a guess for the word
12132: that pushed that return stack entry as its return address. This gives a
12133: backtrace. In our case we see that @code{bar} called @code{foo}, and
12134: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12135: address} exception).
12136:
12137: Note that the backtrace is not perfect: We don't know which return stack
12138: entries are return addresses (so we may get false positives); and in
12139: some cases (e.g., for @code{abort"}) we cannot determine from the return
12140: address the word that pushed the return address, so for some return
12141: addresses you see no names in the return stack dump.
1.25 anton 12142:
12143: @cindex @code{catch} and backtraces
12144: The return stack dump represents the return stack at the time when a
12145: specific @code{throw} was executed. In programs that make use of
12146: @code{catch}, it is not necessarily clear which @code{throw} should be
12147: used for the return stack dump (e.g., consider one @code{throw} that
12148: indicates an error, which is caught, and during recovery another error
1.42 anton 12149: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12150: presents the return stack dump for the first @code{throw} after the last
12151: executed (not returned-to) @code{catch}; this works well in the usual
12152: case.
12153:
12154: @cindex @code{gforth-fast} and backtraces
12155: @cindex @code{gforth-fast}, difference from @code{gforth}
12156: @cindex backtraces with @code{gforth-fast}
12157: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12158: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12159: from primitives (e.g., invalid memory address, stack empty etc.);
12160: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12161: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12162: exception caused by a primitive in @code{gforth-fast}, you will
12163: typically see no return stack dump at all; however, if the exception is
12164: caught by @code{catch} (e.g., for restoring some state), and then
12165: @code{throw}n again, the return stack dump will be for the first such
12166: @code{throw}.
1.2 jwilke 12167:
1.5 anton 12168: @c ******************************************************************
1.24 anton 12169: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12170: @chapter Tools
12171:
12172: @menu
12173: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12174: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12175: @end menu
12176:
12177: See also @ref{Emacs and Gforth}.
12178:
1.126 pazsan 12179: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12180: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12181: @cindex @file{ans-report.fs}
12182: @cindex report the words used in your program
12183: @cindex words used in your program
12184:
12185: If you want to label a Forth program as ANS Forth Program, you must
12186: document which wordsets the program uses; for extension wordsets, it is
12187: helpful to list the words the program requires from these wordsets
12188: (because Forth systems are allowed to provide only some words of them).
12189:
12190: The @file{ans-report.fs} tool makes it easy for you to determine which
12191: words from which wordset and which non-ANS words your application
12192: uses. You simply have to include @file{ans-report.fs} before loading the
12193: program you want to check. After loading your program, you can get the
12194: report with @code{print-ans-report}. A typical use is to run this as
12195: batch job like this:
12196: @example
12197: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12198: @end example
12199:
12200: The output looks like this (for @file{compat/control.fs}):
12201: @example
12202: The program uses the following words
12203: from CORE :
12204: : POSTPONE THEN ; immediate ?dup IF 0=
12205: from BLOCK-EXT :
12206: \
12207: from FILE :
12208: (
12209: @end example
12210:
12211: @subsection Caveats
12212:
12213: Note that @file{ans-report.fs} just checks which words are used, not whether
12214: they are used in an ANS Forth conforming way!
12215:
12216: Some words are defined in several wordsets in the
12217: standard. @file{ans-report.fs} reports them for only one of the
12218: wordsets, and not necessarily the one you expect. It depends on usage
12219: which wordset is the right one to specify. E.g., if you only use the
12220: compilation semantics of @code{S"}, it is a Core word; if you also use
12221: its interpretation semantics, it is a File word.
1.124 anton 12222:
12223:
1.127 anton 12224: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12225: @section Stack depth changes during interpretation
12226: @cindex @file{depth-changes.fs}
12227: @cindex depth changes during interpretation
12228: @cindex stack depth changes during interpretation
12229: @cindex items on the stack after interpretation
12230:
12231: Sometimes you notice that, after loading a file, there are items left
12232: on the stack. The tool @file{depth-changes.fs} helps you find out
12233: quickly where in the file these stack items are coming from.
12234:
12235: The simplest way of using @file{depth-changes.fs} is to include it
12236: before the file(s) you want to check, e.g.:
12237:
12238: @example
12239: gforth depth-changes.fs my-file.fs
12240: @end example
12241:
12242: This will compare the stack depths of the data and FP stack at every
12243: empty line (in interpretation state) against these depths at the last
12244: empty line (in interpretation state). If the depths are not equal,
12245: the position in the file and the stack contents are printed with
12246: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12247: change has occured in the paragraph of non-empty lines before the
12248: indicated line. It is a good idea to leave an empty line at the end
12249: of the file, so the last paragraph is checked, too.
12250:
12251: Checking only at empty lines usually works well, but sometimes you
12252: have big blocks of non-empty lines (e.g., when building a big table),
12253: and you want to know where in this block the stack depth changed. You
12254: can check all interpreted lines with
12255:
12256: @example
12257: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12258: @end example
12259:
12260: This checks the stack depth at every end-of-line. So the depth change
12261: occured in the line reported by the @code{~~} (not in the line
12262: before).
12263:
12264: Note that, while this offers better accuracy in indicating where the
12265: stack depth changes, it will often report many intentional stack depth
12266: changes (e.g., when an interpreted computation stretches across
12267: several lines). You can suppress the checking of some lines by
12268: putting backslashes at the end of these lines (not followed by white
12269: space), and using
12270:
12271: @example
12272: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12273: @end example
1.1 anton 12274:
12275: @c ******************************************************************
1.65 anton 12276: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12277: @chapter ANS conformance
12278: @cindex ANS conformance of Gforth
12279:
12280: To the best of our knowledge, Gforth is an
12281:
12282: ANS Forth System
12283: @itemize @bullet
12284: @item providing the Core Extensions word set
12285: @item providing the Block word set
12286: @item providing the Block Extensions word set
12287: @item providing the Double-Number word set
12288: @item providing the Double-Number Extensions word set
12289: @item providing the Exception word set
12290: @item providing the Exception Extensions word set
12291: @item providing the Facility word set
1.40 anton 12292: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12293: @item providing the File Access word set
12294: @item providing the File Access Extensions word set
12295: @item providing the Floating-Point word set
12296: @item providing the Floating-Point Extensions word set
12297: @item providing the Locals word set
12298: @item providing the Locals Extensions word set
12299: @item providing the Memory-Allocation word set
12300: @item providing the Memory-Allocation Extensions word set (that one's easy)
12301: @item providing the Programming-Tools word set
12302: @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
12303: @item providing the Search-Order word set
12304: @item providing the Search-Order Extensions word set
12305: @item providing the String word set
12306: @item providing the String Extensions word set (another easy one)
12307: @end itemize
12308:
1.118 anton 12309: Gforth has the following environmental restrictions:
12310:
12311: @cindex environmental restrictions
12312: @itemize @bullet
12313: @item
12314: While processing the OS command line, if an exception is not caught,
12315: Gforth exits with a non-zero exit code instyead of performing QUIT.
12316:
12317: @item
12318: When an @code{throw} is performed after a @code{query}, Gforth does not
12319: allways restore the input source specification in effect at the
12320: corresponding catch.
12321:
12322: @end itemize
12323:
12324:
1.1 anton 12325: @cindex system documentation
12326: In addition, ANS Forth systems are required to document certain
12327: implementation choices. This chapter tries to meet these
12328: requirements. In many cases it gives a way to ask the system for the
12329: information instead of providing the information directly, in
12330: particular, if the information depends on the processor, the operating
12331: system or the installation options chosen, or if they are likely to
12332: change during the maintenance of Gforth.
12333:
12334: @comment The framework for the rest has been taken from pfe.
12335:
12336: @menu
12337: * The Core Words::
12338: * The optional Block word set::
12339: * The optional Double Number word set::
12340: * The optional Exception word set::
12341: * The optional Facility word set::
12342: * The optional File-Access word set::
12343: * The optional Floating-Point word set::
12344: * The optional Locals word set::
12345: * The optional Memory-Allocation word set::
12346: * The optional Programming-Tools word set::
12347: * The optional Search-Order word set::
12348: @end menu
12349:
12350:
12351: @c =====================================================================
12352: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12353: @comment node-name, next, previous, up
12354: @section The Core Words
12355: @c =====================================================================
12356: @cindex core words, system documentation
12357: @cindex system documentation, core words
12358:
12359: @menu
12360: * core-idef:: Implementation Defined Options
12361: * core-ambcond:: Ambiguous Conditions
12362: * core-other:: Other System Documentation
12363: @end menu
12364:
12365: @c ---------------------------------------------------------------------
12366: @node core-idef, core-ambcond, The Core Words, The Core Words
12367: @subsection Implementation Defined Options
12368: @c ---------------------------------------------------------------------
12369: @cindex core words, implementation-defined options
12370: @cindex implementation-defined options, core words
12371:
12372:
12373: @table @i
12374: @item (Cell) aligned addresses:
12375: @cindex cell-aligned addresses
12376: @cindex aligned addresses
12377: processor-dependent. Gforth's alignment words perform natural alignment
12378: (e.g., an address aligned for a datum of size 8 is divisible by
12379: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12380:
12381: @item @code{EMIT} and non-graphic characters:
12382: @cindex @code{EMIT} and non-graphic characters
12383: @cindex non-graphic characters and @code{EMIT}
12384: The character is output using the C library function (actually, macro)
12385: @code{putc}.
12386:
12387: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12388: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12389: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12390: @cindex @code{ACCEPT}, editing
12391: @cindex @code{EXPECT}, editing
12392: This is modeled on the GNU readline library (@pxref{Readline
12393: Interaction, , Command Line Editing, readline, The GNU Readline
12394: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12395: producing a full word completion every time you type it (instead of
1.28 crook 12396: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12397:
12398: @item character set:
12399: @cindex character set
12400: The character set of your computer and display device. Gforth is
12401: 8-bit-clean (but some other component in your system may make trouble).
12402:
12403: @item Character-aligned address requirements:
12404: @cindex character-aligned address requirements
12405: installation-dependent. Currently a character is represented by a C
12406: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12407: (Comments on that requested).
12408:
12409: @item character-set extensions and matching of names:
12410: @cindex character-set extensions and matching of names
1.26 crook 12411: @cindex case-sensitivity for name lookup
12412: @cindex name lookup, case-sensitivity
12413: @cindex locale and case-sensitivity
1.21 crook 12414: Any character except the ASCII NUL character can be used in a
1.1 anton 12415: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12416: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12417: function is probably influenced by the locale. E.g., the @code{C} locale
12418: does not know about accents and umlauts, so they are matched
12419: case-sensitively in that locale. For portability reasons it is best to
12420: write programs such that they work in the @code{C} locale. Then one can
12421: use libraries written by a Polish programmer (who might use words
12422: containing ISO Latin-2 encoded characters) and by a French programmer
12423: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12424: funny results for some of the words (which ones, depends on the font you
12425: are using)). Also, the locale you prefer may not be available in other
12426: operating systems. Hopefully, Unicode will solve these problems one day.
12427:
12428: @item conditions under which control characters match a space delimiter:
12429: @cindex space delimiters
12430: @cindex control characters as delimiters
1.117 anton 12431: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12432: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12433: are delimiters. @code{Parse}, on the other hand, treats space like other
12434: delimiters. @code{Parse-word}, which is used by the outer
1.1 anton 12435: interpreter (aka text interpreter) by default, treats all white-space
12436: characters as delimiters.
12437:
1.26 crook 12438: @item format of the control-flow stack:
12439: @cindex control-flow stack, format
12440: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12441: stack item in cells is given by the constant @code{cs-item-size}. At the
12442: time of this writing, an item consists of a (pointer to a) locals list
12443: (third), an address in the code (second), and a tag for identifying the
12444: item (TOS). The following tags are used: @code{defstart},
12445: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12446: @code{scopestart}.
12447:
12448: @item conversion of digits > 35
12449: @cindex digits > 35
12450: The characters @code{[\]^_'} are the digits with the decimal value
12451: 36@minus{}41. There is no way to input many of the larger digits.
12452:
12453: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12454: @cindex @code{EXPECT}, display after end of input
12455: @cindex @code{ACCEPT}, display after end of input
12456: The cursor is moved to the end of the entered string. If the input is
12457: terminated using the @kbd{Return} key, a space is typed.
12458:
12459: @item exception abort sequence of @code{ABORT"}:
12460: @cindex exception abort sequence of @code{ABORT"}
12461: @cindex @code{ABORT"}, exception abort sequence
12462: The error string is stored into the variable @code{"error} and a
12463: @code{-2 throw} is performed.
12464:
12465: @item input line terminator:
12466: @cindex input line terminator
12467: @cindex line terminator on input
1.26 crook 12468: @cindex newline character on input
1.1 anton 12469: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12470: lines. One of these characters is typically produced when you type the
12471: @kbd{Enter} or @kbd{Return} key.
12472:
12473: @item maximum size of a counted string:
12474: @cindex maximum size of a counted string
12475: @cindex counted string, maximum size
12476: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12477: on all platforms, but this may change.
1.1 anton 12478:
12479: @item maximum size of a parsed string:
12480: @cindex maximum size of a parsed string
12481: @cindex parsed string, maximum size
12482: Given by the constant @code{/line}. Currently 255 characters.
12483:
12484: @item maximum size of a definition name, in characters:
12485: @cindex maximum size of a definition name, in characters
12486: @cindex name, maximum length
1.113 anton 12487: MAXU/8
1.1 anton 12488:
12489: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12490: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12491: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12492: MAXU/8
1.1 anton 12493:
12494: @item method of selecting the user input device:
12495: @cindex user input device, method of selecting
12496: The user input device is the standard input. There is currently no way to
12497: change it from within Gforth. However, the input can typically be
12498: redirected in the command line that starts Gforth.
12499:
12500: @item method of selecting the user output device:
12501: @cindex user output device, method of selecting
12502: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12503: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12504: output when the user output device is a terminal, otherwise the output
12505: is buffered.
1.1 anton 12506:
12507: @item methods of dictionary compilation:
12508: What are we expected to document here?
12509:
12510: @item number of bits in one address unit:
12511: @cindex number of bits in one address unit
12512: @cindex address unit, size in bits
12513: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12514: platforms.
1.1 anton 12515:
12516: @item number representation and arithmetic:
12517: @cindex number representation and arithmetic
1.79 anton 12518: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12519:
12520: @item ranges for integer types:
12521: @cindex ranges for integer types
12522: @cindex integer types, ranges
12523: Installation-dependent. Make environmental queries for @code{MAX-N},
12524: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12525: unsigned (and positive) types is 0. The lower bound for signed types on
12526: two's complement and one's complement machines machines can be computed
12527: by adding 1 to the upper bound.
12528:
12529: @item read-only data space regions:
12530: @cindex read-only data space regions
12531: @cindex data-space, read-only regions
12532: The whole Forth data space is writable.
12533:
12534: @item size of buffer at @code{WORD}:
12535: @cindex size of buffer at @code{WORD}
12536: @cindex @code{WORD} buffer size
12537: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12538: shared with the pictured numeric output string. If overwriting
12539: @code{PAD} is acceptable, it is as large as the remaining dictionary
12540: space, although only as much can be sensibly used as fits in a counted
12541: string.
12542:
12543: @item size of one cell in address units:
12544: @cindex cell size
12545: @code{1 cells .}.
12546:
12547: @item size of one character in address units:
12548: @cindex char size
1.79 anton 12549: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12550:
12551: @item size of the keyboard terminal buffer:
12552: @cindex size of the keyboard terminal buffer
12553: @cindex terminal buffer, size
12554: Varies. You can determine the size at a specific time using @code{lp@@
12555: tib - .}. It is shared with the locals stack and TIBs of files that
12556: include the current file. You can change the amount of space for TIBs
12557: and locals stack at Gforth startup with the command line option
12558: @code{-l}.
12559:
12560: @item size of the pictured numeric output buffer:
12561: @cindex size of the pictured numeric output buffer
12562: @cindex pictured numeric output buffer, size
12563: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12564: shared with @code{WORD}.
12565:
12566: @item size of the scratch area returned by @code{PAD}:
12567: @cindex size of the scratch area returned by @code{PAD}
12568: @cindex @code{PAD} size
12569: The remainder of dictionary space. @code{unused pad here - - .}.
12570:
12571: @item system case-sensitivity characteristics:
12572: @cindex case-sensitivity characteristics
1.26 crook 12573: Dictionary searches are case-insensitive (except in
1.1 anton 12574: @code{TABLE}s). However, as explained above under @i{character-set
12575: extensions}, the matching for non-ASCII characters is determined by the
12576: locale you are using. In the default @code{C} locale all non-ASCII
12577: characters are matched case-sensitively.
12578:
12579: @item system prompt:
12580: @cindex system prompt
12581: @cindex prompt
12582: @code{ ok} in interpret state, @code{ compiled} in compile state.
12583:
12584: @item division rounding:
12585: @cindex division rounding
12586: installation dependent. @code{s" floored" environment? drop .}. We leave
12587: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12588: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12589:
12590: @item values of @code{STATE} when true:
12591: @cindex @code{STATE} values
12592: -1.
12593:
12594: @item values returned after arithmetic overflow:
12595: On two's complement machines, arithmetic is performed modulo
12596: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12597: arithmetic (with appropriate mapping for signed types). Division by zero
12598: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12599: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12600:
12601: @item whether the current definition can be found after @t{DOES>}:
12602: @cindex @t{DOES>}, visibility of current definition
12603: No.
12604:
12605: @end table
12606:
12607: @c ---------------------------------------------------------------------
12608: @node core-ambcond, core-other, core-idef, The Core Words
12609: @subsection Ambiguous conditions
12610: @c ---------------------------------------------------------------------
12611: @cindex core words, ambiguous conditions
12612: @cindex ambiguous conditions, core words
12613:
12614: @table @i
12615:
12616: @item a name is neither a word nor a number:
12617: @cindex name not found
1.26 crook 12618: @cindex undefined word
1.80 anton 12619: @code{-13 throw} (Undefined word).
1.1 anton 12620:
12621: @item a definition name exceeds the maximum length allowed:
1.26 crook 12622: @cindex word name too long
1.1 anton 12623: @code{-19 throw} (Word name too long)
12624:
12625: @item addressing a region not inside the various data spaces of the forth system:
12626: @cindex Invalid memory address
1.32 anton 12627: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12628: typically readable. Accessing other addresses gives results dependent on
12629: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12630: address).
12631:
12632: @item argument type incompatible with parameter:
1.26 crook 12633: @cindex argument type mismatch
1.1 anton 12634: This is usually not caught. Some words perform checks, e.g., the control
12635: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12636: mismatch).
12637:
12638: @item attempting to obtain the execution token of a word with undefined execution semantics:
12639: @cindex Interpreting a compile-only word, for @code{'} etc.
12640: @cindex execution token of words with undefined execution semantics
12641: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12642: get an execution token for @code{compile-only-error} (which performs a
12643: @code{-14 throw} when executed).
12644:
12645: @item dividing by zero:
12646: @cindex dividing by zero
12647: @cindex floating point unidentified fault, integer division
1.80 anton 12648: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12649: zero); on other systems, this typically results in a @code{-55 throw}
12650: (Floating-point unidentified fault).
1.1 anton 12651:
12652: @item insufficient data stack or return stack space:
12653: @cindex insufficient data stack or return stack space
12654: @cindex stack overflow
1.26 crook 12655: @cindex address alignment exception, stack overflow
1.1 anton 12656: @cindex Invalid memory address, stack overflow
12657: Depending on the operating system, the installation, and the invocation
12658: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12659: it is not checked. If it is checked, you typically get a @code{-3 throw}
12660: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12661: throw} (Invalid memory address) (depending on the platform and how you
12662: achieved the overflow) as soon as the overflow happens. If it is not
12663: checked, overflows typically result in mysterious illegal memory
12664: accesses, producing @code{-9 throw} (Invalid memory address) or
12665: @code{-23 throw} (Address alignment exception); they might also destroy
12666: the internal data structure of @code{ALLOCATE} and friends, resulting in
12667: various errors in these words.
1.1 anton 12668:
12669: @item insufficient space for loop control parameters:
12670: @cindex insufficient space for loop control parameters
1.80 anton 12671: Like other return stack overflows.
1.1 anton 12672:
12673: @item insufficient space in the dictionary:
12674: @cindex insufficient space in the dictionary
12675: @cindex dictionary overflow
1.12 anton 12676: If you try to allot (either directly with @code{allot}, or indirectly
12677: with @code{,}, @code{create} etc.) more memory than available in the
12678: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12679: to access memory beyond the end of the dictionary, the results are
12680: similar to stack overflows.
1.1 anton 12681:
12682: @item interpreting a word with undefined interpretation semantics:
12683: @cindex interpreting a word with undefined interpretation semantics
12684: @cindex Interpreting a compile-only word
12685: For some words, we have defined interpretation semantics. For the
12686: others: @code{-14 throw} (Interpreting a compile-only word).
12687:
12688: @item modifying the contents of the input buffer or a string literal:
12689: @cindex modifying the contents of the input buffer or a string literal
12690: These are located in writable memory and can be modified.
12691:
12692: @item overflow of the pictured numeric output string:
12693: @cindex overflow of the pictured numeric output string
12694: @cindex pictured numeric output string, overflow
1.24 anton 12695: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12696:
12697: @item parsed string overflow:
12698: @cindex parsed string overflow
12699: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12700:
12701: @item producing a result out of range:
12702: @cindex result out of range
12703: On two's complement machines, arithmetic is performed modulo
12704: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12705: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12706: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12707: throw} (floating point unidentified fault). @code{convert} and
12708: @code{>number} currently overflow silently.
1.1 anton 12709:
12710: @item reading from an empty data or return stack:
12711: @cindex stack empty
12712: @cindex stack underflow
1.24 anton 12713: @cindex return stack underflow
1.1 anton 12714: The data stack is checked by the outer (aka text) interpreter after
12715: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12716: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12717: depending on operating system, installation, and invocation. If they are
12718: caught by a check, they typically result in @code{-4 throw} (Stack
12719: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12720: (Invalid memory address), depending on the platform and which stack
12721: underflows and by how much. Note that even if the system uses checking
12722: (through the MMU), your program may have to underflow by a significant
12723: number of stack items to trigger the reaction (the reason for this is
12724: that the MMU, and therefore the checking, works with a page-size
12725: granularity). If there is no checking, the symptoms resulting from an
12726: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12727: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12728: (Invalid memory address) and Illegal Instruction (typically @code{-260
12729: throw}).
1.1 anton 12730:
12731: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12732: @cindex unexpected end of the input buffer
12733: @cindex zero-length string as a name
12734: @cindex Attempt to use zero-length string as a name
12735: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12736: use zero-length string as a name). Words like @code{'} probably will not
12737: find what they search. Note that it is possible to create zero-length
12738: names with @code{nextname} (should it not?).
12739:
12740: @item @code{>IN} greater than input buffer:
12741: @cindex @code{>IN} greater than input buffer
12742: The next invocation of a parsing word returns a string with length 0.
12743:
12744: @item @code{RECURSE} appears after @code{DOES>}:
12745: @cindex @code{RECURSE} appears after @code{DOES>}
12746: Compiles a recursive call to the defining word, not to the defined word.
12747:
12748: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12749: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12750: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12751: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12752: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12753: the end of the file was reached), its source-id may be
12754: reused. Therefore, restoring an input source specification referencing a
12755: closed file may lead to unpredictable results instead of a @code{-12
12756: THROW}.
12757:
12758: In the future, Gforth may be able to restore input source specifications
12759: from other than the current input source.
12760:
12761: @item data space containing definitions gets de-allocated:
12762: @cindex data space containing definitions gets de-allocated
12763: Deallocation with @code{allot} is not checked. This typically results in
12764: memory access faults or execution of illegal instructions.
12765:
12766: @item data space read/write with incorrect alignment:
12767: @cindex data space read/write with incorrect alignment
12768: @cindex alignment faults
1.26 crook 12769: @cindex address alignment exception
1.1 anton 12770: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12771: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12772: alignment turned on, incorrect alignment results in a @code{-9 throw}
12773: (Invalid memory address). There are reportedly some processors with
1.12 anton 12774: alignment restrictions that do not report violations.
1.1 anton 12775:
12776: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12777: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12778: Like other alignment errors.
12779:
12780: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12781: Like other stack underflows.
12782:
12783: @item loop control parameters not available:
12784: @cindex loop control parameters not available
12785: Not checked. The counted loop words simply assume that the top of return
12786: stack items are loop control parameters and behave accordingly.
12787:
12788: @item most recent definition does not have a name (@code{IMMEDIATE}):
12789: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12790: @cindex last word was headerless
12791: @code{abort" last word was headerless"}.
12792:
12793: @item name not defined by @code{VALUE} used by @code{TO}:
12794: @cindex name not defined by @code{VALUE} used by @code{TO}
12795: @cindex @code{TO} on non-@code{VALUE}s
12796: @cindex Invalid name argument, @code{TO}
12797: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12798: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12799:
12800: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12801: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12802: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12803: @code{-13 throw} (Undefined word)
12804:
12805: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12806: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12807: Gforth behaves as if they were of the same type. I.e., you can predict
12808: the behaviour by interpreting all parameters as, e.g., signed.
12809:
12810: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12811: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12812: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12813: compilation semantics of @code{TO}.
12814:
12815: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12816: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12817: @cindex @code{WORD}, string overflow
12818: Not checked. The string will be ok, but the count will, of course,
12819: contain only the least significant bits of the length.
12820:
12821: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12822: @cindex @code{LSHIFT}, large shift counts
12823: @cindex @code{RSHIFT}, large shift counts
12824: Processor-dependent. Typical behaviours are returning 0 and using only
12825: the low bits of the shift count.
12826:
12827: @item word not defined via @code{CREATE}:
12828: @cindex @code{>BODY} of non-@code{CREATE}d words
12829: @code{>BODY} produces the PFA of the word no matter how it was defined.
12830:
12831: @cindex @code{DOES>} of non-@code{CREATE}d words
12832: @code{DOES>} changes the execution semantics of the last defined word no
12833: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12834: @code{CREATE , DOES>}.
12835:
12836: @item words improperly used outside @code{<#} and @code{#>}:
12837: Not checked. As usual, you can expect memory faults.
12838:
12839: @end table
12840:
12841:
12842: @c ---------------------------------------------------------------------
12843: @node core-other, , core-ambcond, The Core Words
12844: @subsection Other system documentation
12845: @c ---------------------------------------------------------------------
12846: @cindex other system documentation, core words
12847: @cindex core words, other system documentation
12848:
12849: @table @i
12850: @item nonstandard words using @code{PAD}:
12851: @cindex @code{PAD} use by nonstandard words
12852: None.
12853:
12854: @item operator's terminal facilities available:
12855: @cindex operator's terminal facilities available
1.80 anton 12856: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12857: and you can give commands to Gforth interactively. The actual facilities
12858: available depend on how you invoke Gforth.
12859:
12860: @item program data space available:
12861: @cindex program data space available
12862: @cindex data space available
12863: @code{UNUSED .} gives the remaining dictionary space. The total
12864: dictionary space can be specified with the @code{-m} switch
12865: (@pxref{Invoking Gforth}) when Gforth starts up.
12866:
12867: @item return stack space available:
12868: @cindex return stack space available
12869: You can compute the total return stack space in cells with
12870: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12871: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12872:
12873: @item stack space available:
12874: @cindex stack space available
12875: You can compute the total data stack space in cells with
12876: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12877: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12878:
12879: @item system dictionary space required, in address units:
12880: @cindex system dictionary space required, in address units
12881: Type @code{here forthstart - .} after startup. At the time of this
12882: writing, this gives 80080 (bytes) on a 32-bit system.
12883: @end table
12884:
12885:
12886: @c =====================================================================
12887: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12888: @section The optional Block word set
12889: @c =====================================================================
12890: @cindex system documentation, block words
12891: @cindex block words, system documentation
12892:
12893: @menu
12894: * block-idef:: Implementation Defined Options
12895: * block-ambcond:: Ambiguous Conditions
12896: * block-other:: Other System Documentation
12897: @end menu
12898:
12899:
12900: @c ---------------------------------------------------------------------
12901: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12902: @subsection Implementation Defined Options
12903: @c ---------------------------------------------------------------------
12904: @cindex implementation-defined options, block words
12905: @cindex block words, implementation-defined options
12906:
12907: @table @i
12908: @item the format for display by @code{LIST}:
12909: @cindex @code{LIST} display format
12910: First the screen number is displayed, then 16 lines of 64 characters,
12911: each line preceded by the line number.
12912:
12913: @item the length of a line affected by @code{\}:
12914: @cindex length of a line affected by @code{\}
12915: @cindex @code{\}, line length in blocks
12916: 64 characters.
12917: @end table
12918:
12919:
12920: @c ---------------------------------------------------------------------
12921: @node block-ambcond, block-other, block-idef, The optional Block word set
12922: @subsection Ambiguous conditions
12923: @c ---------------------------------------------------------------------
12924: @cindex block words, ambiguous conditions
12925: @cindex ambiguous conditions, block words
12926:
12927: @table @i
12928: @item correct block read was not possible:
12929: @cindex block read not possible
12930: Typically results in a @code{throw} of some OS-derived value (between
12931: -512 and -2048). If the blocks file was just not long enough, blanks are
12932: supplied for the missing portion.
12933:
12934: @item I/O exception in block transfer:
12935: @cindex I/O exception in block transfer
12936: @cindex block transfer, I/O exception
12937: Typically results in a @code{throw} of some OS-derived value (between
12938: -512 and -2048).
12939:
12940: @item invalid block number:
12941: @cindex invalid block number
12942: @cindex block number invalid
12943: @code{-35 throw} (Invalid block number)
12944:
12945: @item a program directly alters the contents of @code{BLK}:
12946: @cindex @code{BLK}, altering @code{BLK}
12947: The input stream is switched to that other block, at the same
12948: position. If the storing to @code{BLK} happens when interpreting
12949: non-block input, the system will get quite confused when the block ends.
12950:
12951: @item no current block buffer for @code{UPDATE}:
12952: @cindex @code{UPDATE}, no current block buffer
12953: @code{UPDATE} has no effect.
12954:
12955: @end table
12956:
12957: @c ---------------------------------------------------------------------
12958: @node block-other, , block-ambcond, The optional Block word set
12959: @subsection Other system documentation
12960: @c ---------------------------------------------------------------------
12961: @cindex other system documentation, block words
12962: @cindex block words, other system documentation
12963:
12964: @table @i
12965: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12966: No restrictions (yet).
12967:
12968: @item the number of blocks available for source and data:
12969: depends on your disk space.
12970:
12971: @end table
12972:
12973:
12974: @c =====================================================================
12975: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12976: @section The optional Double Number word set
12977: @c =====================================================================
12978: @cindex system documentation, double words
12979: @cindex double words, system documentation
12980:
12981: @menu
12982: * double-ambcond:: Ambiguous Conditions
12983: @end menu
12984:
12985:
12986: @c ---------------------------------------------------------------------
12987: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12988: @subsection Ambiguous conditions
12989: @c ---------------------------------------------------------------------
12990: @cindex double words, ambiguous conditions
12991: @cindex ambiguous conditions, double words
12992:
12993: @table @i
1.29 crook 12994: @item @i{d} outside of range of @i{n} in @code{D>S}:
12995: @cindex @code{D>S}, @i{d} out of range of @i{n}
12996: The least significant cell of @i{d} is produced.
1.1 anton 12997:
12998: @end table
12999:
13000:
13001: @c =====================================================================
13002: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13003: @section The optional Exception word set
13004: @c =====================================================================
13005: @cindex system documentation, exception words
13006: @cindex exception words, system documentation
13007:
13008: @menu
13009: * exception-idef:: Implementation Defined Options
13010: @end menu
13011:
13012:
13013: @c ---------------------------------------------------------------------
13014: @node exception-idef, , The optional Exception word set, The optional Exception word set
13015: @subsection Implementation Defined Options
13016: @c ---------------------------------------------------------------------
13017: @cindex implementation-defined options, exception words
13018: @cindex exception words, implementation-defined options
13019:
13020: @table @i
13021: @item @code{THROW}-codes used in the system:
13022: @cindex @code{THROW}-codes used in the system
13023: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13024: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13025: codes -512@minus{}-2047 are used for OS errors (for file and memory
13026: allocation operations). The mapping from OS error numbers to throw codes
13027: is -512@minus{}@code{errno}. One side effect of this mapping is that
13028: undefined OS errors produce a message with a strange number; e.g.,
13029: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13030: @end table
13031:
13032: @c =====================================================================
13033: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13034: @section The optional Facility word set
13035: @c =====================================================================
13036: @cindex system documentation, facility words
13037: @cindex facility words, system documentation
13038:
13039: @menu
13040: * facility-idef:: Implementation Defined Options
13041: * facility-ambcond:: Ambiguous Conditions
13042: @end menu
13043:
13044:
13045: @c ---------------------------------------------------------------------
13046: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13047: @subsection Implementation Defined Options
13048: @c ---------------------------------------------------------------------
13049: @cindex implementation-defined options, facility words
13050: @cindex facility words, implementation-defined options
13051:
13052: @table @i
13053: @item encoding of keyboard events (@code{EKEY}):
13054: @cindex keyboard events, encoding in @code{EKEY}
13055: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13056: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13057: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13058: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13059: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13060: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13061:
1.1 anton 13062:
13063: @item duration of a system clock tick:
13064: @cindex duration of a system clock tick
13065: @cindex clock tick duration
13066: System dependent. With respect to @code{MS}, the time is specified in
13067: microseconds. How well the OS and the hardware implement this, is
13068: another question.
13069:
13070: @item repeatability to be expected from the execution of @code{MS}:
13071: @cindex repeatability to be expected from the execution of @code{MS}
13072: @cindex @code{MS}, repeatability to be expected
13073: System dependent. On Unix, a lot depends on load. If the system is
13074: lightly loaded, and the delay is short enough that Gforth does not get
13075: swapped out, the performance should be acceptable. Under MS-DOS and
13076: other single-tasking systems, it should be good.
13077:
13078: @end table
13079:
13080:
13081: @c ---------------------------------------------------------------------
13082: @node facility-ambcond, , facility-idef, The optional Facility word set
13083: @subsection Ambiguous conditions
13084: @c ---------------------------------------------------------------------
13085: @cindex facility words, ambiguous conditions
13086: @cindex ambiguous conditions, facility words
13087:
13088: @table @i
13089: @item @code{AT-XY} can't be performed on user output device:
13090: @cindex @code{AT-XY} can't be performed on user output device
13091: Largely terminal dependent. No range checks are done on the arguments.
13092: No errors are reported. You may see some garbage appearing, you may see
13093: simply nothing happen.
13094:
13095: @end table
13096:
13097:
13098: @c =====================================================================
13099: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13100: @section The optional File-Access word set
13101: @c =====================================================================
13102: @cindex system documentation, file words
13103: @cindex file words, system documentation
13104:
13105: @menu
13106: * file-idef:: Implementation Defined Options
13107: * file-ambcond:: Ambiguous Conditions
13108: @end menu
13109:
13110: @c ---------------------------------------------------------------------
13111: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13112: @subsection Implementation Defined Options
13113: @c ---------------------------------------------------------------------
13114: @cindex implementation-defined options, file words
13115: @cindex file words, implementation-defined options
13116:
13117: @table @i
13118: @item file access methods used:
13119: @cindex file access methods used
13120: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13121: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13122: @code{wb}): The file is cleared, if it exists, and created, if it does
13123: not (with both @code{open-file} and @code{create-file}). Under Unix
13124: @code{create-file} creates a file with 666 permissions modified by your
13125: umask.
13126:
13127: @item file exceptions:
13128: @cindex file exceptions
13129: The file words do not raise exceptions (except, perhaps, memory access
13130: faults when you pass illegal addresses or file-ids).
13131:
13132: @item file line terminator:
13133: @cindex file line terminator
13134: System-dependent. Gforth uses C's newline character as line
13135: terminator. What the actual character code(s) of this are is
13136: system-dependent.
13137:
13138: @item file name format:
13139: @cindex file name format
13140: System dependent. Gforth just uses the file name format of your OS.
13141:
13142: @item information returned by @code{FILE-STATUS}:
13143: @cindex @code{FILE-STATUS}, returned information
13144: @code{FILE-STATUS} returns the most powerful file access mode allowed
13145: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13146: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13147: along with the returned mode.
13148:
13149: @item input file state after an exception when including source:
13150: @cindex exception when including source
13151: All files that are left via the exception are closed.
13152:
1.29 crook 13153: @item @i{ior} values and meaning:
13154: @cindex @i{ior} values and meaning
1.68 anton 13155: @cindex @i{wior} values and meaning
1.29 crook 13156: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13157: intended as throw codes. They typically are in the range
13158: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13159: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13160:
13161: @item maximum depth of file input nesting:
13162: @cindex maximum depth of file input nesting
13163: @cindex file input nesting, maximum depth
13164: limited by the amount of return stack, locals/TIB stack, and the number
13165: of open files available. This should not give you troubles.
13166:
13167: @item maximum size of input line:
13168: @cindex maximum size of input line
13169: @cindex input line size, maximum
13170: @code{/line}. Currently 255.
13171:
13172: @item methods of mapping block ranges to files:
13173: @cindex mapping block ranges to files
13174: @cindex files containing blocks
13175: @cindex blocks in files
13176: By default, blocks are accessed in the file @file{blocks.fb} in the
13177: current working directory. The file can be switched with @code{USE}.
13178:
13179: @item number of string buffers provided by @code{S"}:
13180: @cindex @code{S"}, number of string buffers
13181: 1
13182:
13183: @item size of string buffer used by @code{S"}:
13184: @cindex @code{S"}, size of string buffer
13185: @code{/line}. currently 255.
13186:
13187: @end table
13188:
13189: @c ---------------------------------------------------------------------
13190: @node file-ambcond, , file-idef, The optional File-Access word set
13191: @subsection Ambiguous conditions
13192: @c ---------------------------------------------------------------------
13193: @cindex file words, ambiguous conditions
13194: @cindex ambiguous conditions, file words
13195:
13196: @table @i
13197: @item attempting to position a file outside its boundaries:
13198: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13199: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13200: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13201:
13202: @item attempting to read from file positions not yet written:
13203: @cindex reading from file positions not yet written
13204: End-of-file, i.e., zero characters are read and no error is reported.
13205:
1.29 crook 13206: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13207: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13208: An appropriate exception may be thrown, but a memory fault or other
13209: problem is more probable.
13210:
1.29 crook 13211: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13212: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13213: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13214: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13215: thrown.
13216:
13217: @item named file cannot be opened (@code{INCLUDED}):
13218: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13219: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13220:
13221: @item requesting an unmapped block number:
13222: @cindex unmapped block numbers
13223: There are no unmapped legal block numbers. On some operating systems,
13224: writing a block with a large number may overflow the file system and
13225: have an error message as consequence.
13226:
13227: @item using @code{source-id} when @code{blk} is non-zero:
13228: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13229: @code{source-id} performs its function. Typically it will give the id of
13230: the source which loaded the block. (Better ideas?)
13231:
13232: @end table
13233:
13234:
13235: @c =====================================================================
13236: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13237: @section The optional Floating-Point word set
13238: @c =====================================================================
13239: @cindex system documentation, floating-point words
13240: @cindex floating-point words, system documentation
13241:
13242: @menu
13243: * floating-idef:: Implementation Defined Options
13244: * floating-ambcond:: Ambiguous Conditions
13245: @end menu
13246:
13247:
13248: @c ---------------------------------------------------------------------
13249: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13250: @subsection Implementation Defined Options
13251: @c ---------------------------------------------------------------------
13252: @cindex implementation-defined options, floating-point words
13253: @cindex floating-point words, implementation-defined options
13254:
13255: @table @i
13256: @item format and range of floating point numbers:
13257: @cindex format and range of floating point numbers
13258: @cindex floating point numbers, format and range
13259: System-dependent; the @code{double} type of C.
13260:
1.29 crook 13261: @item results of @code{REPRESENT} when @i{float} is out of range:
13262: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13263: System dependent; @code{REPRESENT} is implemented using the C library
13264: function @code{ecvt()} and inherits its behaviour in this respect.
13265:
13266: @item rounding or truncation of floating-point numbers:
13267: @cindex rounding of floating-point numbers
13268: @cindex truncation of floating-point numbers
13269: @cindex floating-point numbers, rounding or truncation
13270: System dependent; the rounding behaviour is inherited from the hosting C
13271: compiler. IEEE-FP-based (i.e., most) systems by default round to
13272: nearest, and break ties by rounding to even (i.e., such that the last
13273: bit of the mantissa is 0).
13274:
13275: @item size of floating-point stack:
13276: @cindex floating-point stack size
13277: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13278: the floating-point stack (in floats). You can specify this on startup
13279: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13280:
13281: @item width of floating-point stack:
13282: @cindex floating-point stack width
13283: @code{1 floats}.
13284:
13285: @end table
13286:
13287:
13288: @c ---------------------------------------------------------------------
13289: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13290: @subsection Ambiguous conditions
13291: @c ---------------------------------------------------------------------
13292: @cindex floating-point words, ambiguous conditions
13293: @cindex ambiguous conditions, floating-point words
13294:
13295: @table @i
13296: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13297: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13298: System-dependent. Typically results in a @code{-23 THROW} like other
13299: alignment violations.
13300:
13301: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13302: @cindex @code{f@@} used with an address that is not float aligned
13303: @cindex @code{f!} used with an address that is not float aligned
13304: System-dependent. Typically results in a @code{-23 THROW} like other
13305: alignment violations.
13306:
13307: @item floating-point result out of range:
13308: @cindex floating-point result out of range
1.80 anton 13309: System-dependent. Can result in a @code{-43 throw} (floating point
13310: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13311: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13312: unidentified fault), or can produce a special value representing, e.g.,
13313: Infinity.
13314:
13315: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13316: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13317: System-dependent. Typically results in an alignment fault like other
13318: alignment violations.
13319:
1.35 anton 13320: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13321: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13322: The floating-point number is converted into decimal nonetheless.
13323:
13324: @item Both arguments are equal to zero (@code{FATAN2}):
13325: @cindex @code{FATAN2}, both arguments are equal to zero
13326: System-dependent. @code{FATAN2} is implemented using the C library
13327: function @code{atan2()}.
13328:
1.29 crook 13329: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13330: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13331: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13332: because of small errors and the tan will be a very large (or very small)
13333: but finite number.
13334:
1.29 crook 13335: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13336: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13337: The result is rounded to the nearest float.
13338:
13339: @item dividing by zero:
13340: @cindex dividing by zero, floating-point
13341: @cindex floating-point dividing by zero
13342: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13343: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13344: (floating point divide by zero) or @code{-55 throw} (Floating-point
13345: unidentified fault).
1.1 anton 13346:
13347: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13348: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13349: System dependent. On IEEE-FP based systems the number is converted into
13350: an infinity.
13351:
1.29 crook 13352: @item @i{float}<1 (@code{FACOSH}):
13353: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13354: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13355: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13356:
1.29 crook 13357: @item @i{float}=<-1 (@code{FLNP1}):
13358: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13359: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13360: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13361: negative infinity for @i{float}=-1).
1.1 anton 13362:
1.29 crook 13363: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13364: @cindex @code{FLN}, @i{float}=<0
13365: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13366: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13367: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13368: negative infinity for @i{float}=0).
1.1 anton 13369:
1.29 crook 13370: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13371: @cindex @code{FASINH}, @i{float}<0
13372: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13373: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13374: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13375: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13376: C library?).
1.1 anton 13377:
1.29 crook 13378: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13379: @cindex @code{FACOS}, |@i{float}|>1
13380: @cindex @code{FASIN}, |@i{float}|>1
13381: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13382: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13383: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13384:
1.29 crook 13385: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13386: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13387: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13388: Platform-dependent; typically, some double number is produced and no
13389: error is reported.
1.1 anton 13390:
13391: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13392: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13393: @code{Precision} characters of the numeric output area are used. If
13394: @code{precision} is too high, these words will smash the data or code
13395: close to @code{here}.
1.1 anton 13396: @end table
13397:
13398: @c =====================================================================
13399: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13400: @section The optional Locals word set
13401: @c =====================================================================
13402: @cindex system documentation, locals words
13403: @cindex locals words, system documentation
13404:
13405: @menu
13406: * locals-idef:: Implementation Defined Options
13407: * locals-ambcond:: Ambiguous Conditions
13408: @end menu
13409:
13410:
13411: @c ---------------------------------------------------------------------
13412: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13413: @subsection Implementation Defined Options
13414: @c ---------------------------------------------------------------------
13415: @cindex implementation-defined options, locals words
13416: @cindex locals words, implementation-defined options
13417:
13418: @table @i
13419: @item maximum number of locals in a definition:
13420: @cindex maximum number of locals in a definition
13421: @cindex locals, maximum number in a definition
13422: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13423: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13424: characters. The number of locals in a definition is bounded by the size
13425: of locals-buffer, which contains the names of the locals.
13426:
13427: @end table
13428:
13429:
13430: @c ---------------------------------------------------------------------
13431: @node locals-ambcond, , locals-idef, The optional Locals word set
13432: @subsection Ambiguous conditions
13433: @c ---------------------------------------------------------------------
13434: @cindex locals words, ambiguous conditions
13435: @cindex ambiguous conditions, locals words
13436:
13437: @table @i
13438: @item executing a named local in interpretation state:
13439: @cindex local in interpretation state
13440: @cindex Interpreting a compile-only word, for a local
13441: Locals have no interpretation semantics. If you try to perform the
13442: interpretation semantics, you will get a @code{-14 throw} somewhere
13443: (Interpreting a compile-only word). If you perform the compilation
13444: semantics, the locals access will be compiled (irrespective of state).
13445:
1.29 crook 13446: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13447: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13448: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13449: @cindex Invalid name argument, @code{TO}
13450: @code{-32 throw} (Invalid name argument)
13451:
13452: @end table
13453:
13454:
13455: @c =====================================================================
13456: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13457: @section The optional Memory-Allocation word set
13458: @c =====================================================================
13459: @cindex system documentation, memory-allocation words
13460: @cindex memory-allocation words, system documentation
13461:
13462: @menu
13463: * memory-idef:: Implementation Defined Options
13464: @end menu
13465:
13466:
13467: @c ---------------------------------------------------------------------
13468: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13469: @subsection Implementation Defined Options
13470: @c ---------------------------------------------------------------------
13471: @cindex implementation-defined options, memory-allocation words
13472: @cindex memory-allocation words, implementation-defined options
13473:
13474: @table @i
1.29 crook 13475: @item values and meaning of @i{ior}:
13476: @cindex @i{ior} values and meaning
13477: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13478: intended as throw codes. They typically are in the range
13479: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13480: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13481:
13482: @end table
13483:
13484: @c =====================================================================
13485: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13486: @section The optional Programming-Tools word set
13487: @c =====================================================================
13488: @cindex system documentation, programming-tools words
13489: @cindex programming-tools words, system documentation
13490:
13491: @menu
13492: * programming-idef:: Implementation Defined Options
13493: * programming-ambcond:: Ambiguous Conditions
13494: @end menu
13495:
13496:
13497: @c ---------------------------------------------------------------------
13498: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13499: @subsection Implementation Defined Options
13500: @c ---------------------------------------------------------------------
13501: @cindex implementation-defined options, programming-tools words
13502: @cindex programming-tools words, implementation-defined options
13503:
13504: @table @i
13505: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13506: @cindex @code{;CODE} ending sequence
13507: @cindex @code{CODE} ending sequence
13508: @code{END-CODE}
13509:
13510: @item manner of processing input following @code{;CODE} and @code{CODE}:
13511: @cindex @code{;CODE}, processing input
13512: @cindex @code{CODE}, processing input
13513: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13514: the input is processed by the text interpreter, (starting) in interpret
13515: state.
13516:
13517: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13518: @cindex @code{ASSEMBLER}, search order capability
13519: The ANS Forth search order word set.
13520:
13521: @item source and format of display by @code{SEE}:
13522: @cindex @code{SEE}, source and format of output
1.80 anton 13523: The source for @code{see} is the executable code used by the inner
1.1 anton 13524: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13525: (and on some platforms, assembly code for primitives) as well as
13526: possible.
1.1 anton 13527:
13528: @end table
13529:
13530: @c ---------------------------------------------------------------------
13531: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13532: @subsection Ambiguous conditions
13533: @c ---------------------------------------------------------------------
13534: @cindex programming-tools words, ambiguous conditions
13535: @cindex ambiguous conditions, programming-tools words
13536:
13537: @table @i
13538:
1.21 crook 13539: @item deleting the compilation word list (@code{FORGET}):
13540: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13541: Not implemented (yet).
13542:
1.29 crook 13543: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13544: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13545: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13546: @cindex control-flow stack underflow
13547: This typically results in an @code{abort"} with a descriptive error
13548: message (may change into a @code{-22 throw} (Control structure mismatch)
13549: in the future). You may also get a memory access error. If you are
13550: unlucky, this ambiguous condition is not caught.
13551:
1.29 crook 13552: @item @i{name} can't be found (@code{FORGET}):
13553: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13554: Not implemented (yet).
13555:
1.29 crook 13556: @item @i{name} not defined via @code{CREATE}:
13557: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13558: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13559: the execution semantics of the last defined word no matter how it was
13560: defined.
13561:
13562: @item @code{POSTPONE} applied to @code{[IF]}:
13563: @cindex @code{POSTPONE} applied to @code{[IF]}
13564: @cindex @code{[IF]} and @code{POSTPONE}
13565: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13566: equivalent to @code{[IF]}.
13567:
13568: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13569: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13570: Continue in the same state of conditional compilation in the next outer
13571: input source. Currently there is no warning to the user about this.
13572:
13573: @item removing a needed definition (@code{FORGET}):
13574: @cindex @code{FORGET}, removing a needed definition
13575: Not implemented (yet).
13576:
13577: @end table
13578:
13579:
13580: @c =====================================================================
13581: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13582: @section The optional Search-Order word set
13583: @c =====================================================================
13584: @cindex system documentation, search-order words
13585: @cindex search-order words, system documentation
13586:
13587: @menu
13588: * search-idef:: Implementation Defined Options
13589: * search-ambcond:: Ambiguous Conditions
13590: @end menu
13591:
13592:
13593: @c ---------------------------------------------------------------------
13594: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13595: @subsection Implementation Defined Options
13596: @c ---------------------------------------------------------------------
13597: @cindex implementation-defined options, search-order words
13598: @cindex search-order words, implementation-defined options
13599:
13600: @table @i
13601: @item maximum number of word lists in search order:
13602: @cindex maximum number of word lists in search order
13603: @cindex search order, maximum depth
13604: @code{s" wordlists" environment? drop .}. Currently 16.
13605:
13606: @item minimum search order:
13607: @cindex minimum search order
13608: @cindex search order, minimum
13609: @code{root root}.
13610:
13611: @end table
13612:
13613: @c ---------------------------------------------------------------------
13614: @node search-ambcond, , search-idef, The optional Search-Order word set
13615: @subsection Ambiguous conditions
13616: @c ---------------------------------------------------------------------
13617: @cindex search-order words, ambiguous conditions
13618: @cindex ambiguous conditions, search-order words
13619:
13620: @table @i
1.21 crook 13621: @item changing the compilation word list (during compilation):
13622: @cindex changing the compilation word list (during compilation)
13623: @cindex compilation word list, change before definition ends
13624: The word is entered into the word list that was the compilation word list
1.1 anton 13625: at the start of the definition. Any changes to the name field (e.g.,
13626: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13627: are applied to the latest defined word (as reported by @code{latest} or
13628: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13629:
13630: @item search order empty (@code{previous}):
13631: @cindex @code{previous}, search order empty
1.26 crook 13632: @cindex vocstack empty, @code{previous}
1.1 anton 13633: @code{abort" Vocstack empty"}.
13634:
13635: @item too many word lists in search order (@code{also}):
13636: @cindex @code{also}, too many word lists in search order
1.26 crook 13637: @cindex vocstack full, @code{also}
1.1 anton 13638: @code{abort" Vocstack full"}.
13639:
13640: @end table
13641:
13642: @c ***************************************************************
1.65 anton 13643: @node Standard vs Extensions, Model, ANS conformance, Top
13644: @chapter Should I use Gforth extensions?
13645: @cindex Gforth extensions
13646:
13647: As you read through the rest of this manual, you will see documentation
13648: for @i{Standard} words, and documentation for some appealing Gforth
13649: @i{extensions}. You might ask yourself the question: @i{``Should I
13650: restrict myself to the standard, or should I use the extensions?''}
13651:
13652: The answer depends on the goals you have for the program you are working
13653: on:
13654:
13655: @itemize @bullet
13656:
13657: @item Is it just for yourself or do you want to share it with others?
13658:
13659: @item
13660: If you want to share it, do the others all use Gforth?
13661:
13662: @item
13663: If it is just for yourself, do you want to restrict yourself to Gforth?
13664:
13665: @end itemize
13666:
13667: If restricting the program to Gforth is ok, then there is no reason not
13668: to use extensions. It is still a good idea to keep to the standard
13669: where it is easy, in case you want to reuse these parts in another
13670: program that you want to be portable.
13671:
13672: If you want to be able to port the program to other Forth systems, there
13673: are the following points to consider:
13674:
13675: @itemize @bullet
13676:
13677: @item
13678: Most Forth systems that are being maintained support the ANS Forth
13679: standard. So if your program complies with the standard, it will be
13680: portable among many systems.
13681:
13682: @item
13683: A number of the Gforth extensions can be implemented in ANS Forth using
13684: public-domain files provided in the @file{compat/} directory. These are
13685: mentioned in the text in passing. There is no reason not to use these
13686: extensions, your program will still be ANS Forth compliant; just include
13687: the appropriate compat files with your program.
13688:
13689: @item
13690: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13691: analyse your program and determine what non-Standard words it relies
13692: upon. However, it does not check whether you use standard words in a
13693: non-standard way.
13694:
13695: @item
13696: Some techniques are not standardized by ANS Forth, and are hard or
13697: impossible to implement in a standard way, but can be implemented in
13698: most Forth systems easily, and usually in similar ways (e.g., accessing
13699: word headers). Forth has a rich historical precedent for programmers
13700: taking advantage of implementation-dependent features of their tools
13701: (for example, relying on a knowledge of the dictionary
13702: structure). Sometimes these techniques are necessary to extract every
13703: last bit of performance from the hardware, sometimes they are just a
13704: programming shorthand.
13705:
13706: @item
13707: Does using a Gforth extension save more work than the porting this part
13708: to other Forth systems (if any) will cost?
13709:
13710: @item
13711: Is the additional functionality worth the reduction in portability and
13712: the additional porting problems?
13713:
13714: @end itemize
13715:
13716: In order to perform these consideratios, you need to know what's
13717: standard and what's not. This manual generally states if something is
1.81 anton 13718: non-standard, but the authoritative source is the
13719: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13720: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13721: into the thought processes of the technical committee.
13722:
13723: Note also that portability between Forth systems is not the only
13724: portability issue; there is also the issue of portability between
13725: different platforms (processor/OS combinations).
13726:
13727: @c ***************************************************************
13728: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13729: @chapter Model
13730:
13731: This chapter has yet to be written. It will contain information, on
13732: which internal structures you can rely.
13733:
13734: @c ***************************************************************
13735: @node Integrating Gforth, Emacs and Gforth, Model, Top
13736: @chapter Integrating Gforth into C programs
13737:
13738: This is not yet implemented.
13739:
13740: Several people like to use Forth as scripting language for applications
13741: that are otherwise written in C, C++, or some other language.
13742:
13743: The Forth system ATLAST provides facilities for embedding it into
13744: applications; unfortunately it has several disadvantages: most
13745: importantly, it is not based on ANS Forth, and it is apparently dead
13746: (i.e., not developed further and not supported). The facilities
1.21 crook 13747: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13748: making the switch should not be hard.
13749:
13750: We also tried to design the interface such that it can easily be
13751: implemented by other Forth systems, so that we may one day arrive at a
13752: standardized interface. Such a standard interface would allow you to
13753: replace the Forth system without having to rewrite C code.
13754:
13755: You embed the Gforth interpreter by linking with the library
13756: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13757: global symbols in this library that belong to the interface, have the
13758: prefix @code{forth_}. (Global symbols that are used internally have the
13759: prefix @code{gforth_}).
13760:
13761: You can include the declarations of Forth types and the functions and
13762: variables of the interface with @code{#include <forth.h>}.
13763:
13764: Types.
13765:
13766: Variables.
13767:
13768: Data and FP Stack pointer. Area sizes.
13769:
13770: functions.
13771:
13772: forth_init(imagefile)
13773: forth_evaluate(string) exceptions?
13774: forth_goto(address) (or forth_execute(xt)?)
13775: forth_continue() (a corountining mechanism)
13776:
13777: Adding primitives.
13778:
13779: No checking.
13780:
13781: Signals?
13782:
13783: Accessing the Stacks
13784:
1.26 crook 13785: @c ******************************************************************
1.1 anton 13786: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13787: @chapter Emacs and Gforth
13788: @cindex Emacs and Gforth
13789:
13790: @cindex @file{gforth.el}
13791: @cindex @file{forth.el}
13792: @cindex Rydqvist, Goran
1.107 dvdkhlng 13793: @cindex Kuehling, David
1.1 anton 13794: @cindex comment editing commands
13795: @cindex @code{\}, editing with Emacs
13796: @cindex debug tracer editing commands
13797: @cindex @code{~~}, removal with Emacs
13798: @cindex Forth mode in Emacs
1.107 dvdkhlng 13799:
1.1 anton 13800: Gforth comes with @file{gforth.el}, an improved version of
13801: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13802: improvements are:
13803:
13804: @itemize @bullet
13805: @item
1.107 dvdkhlng 13806: A better handling of indentation.
13807: @item
13808: A custom hilighting engine for Forth-code.
1.26 crook 13809: @item
13810: Comment paragraph filling (@kbd{M-q})
13811: @item
13812: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13813: @item
13814: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13815: @item
13816: Support of the @code{info-lookup} feature for looking up the
13817: documentation of a word.
1.107 dvdkhlng 13818: @item
13819: Support for reading and writing blocks files.
1.26 crook 13820: @end itemize
13821:
1.107 dvdkhlng 13822: To get a basic description of these features, enter Forth mode and
13823: type @kbd{C-h m}.
1.1 anton 13824:
13825: @cindex source location of error or debugging output in Emacs
13826: @cindex error output, finding the source location in Emacs
13827: @cindex debugging output, finding the source location in Emacs
13828: In addition, Gforth supports Emacs quite well: The source code locations
13829: given in error messages, debugging output (from @code{~~}) and failed
13830: assertion messages are in the right format for Emacs' compilation mode
13831: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13832: Manual}) so the source location corresponding to an error or other
13833: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13834: @kbd{C-c C-c} for the error under the cursor).
13835:
1.107 dvdkhlng 13836: @cindex viewing the documentation of a word in Emacs
13837: @cindex context-sensitive help
13838: Moreover, for words documented in this manual, you can look up the
13839: glossary entry quickly by using @kbd{C-h TAB}
13840: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13841: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13842: later and does not work for words containing @code{:}.
13843:
13844: @menu
13845: * Installing gforth.el:: Making Emacs aware of Forth.
13846: * Emacs Tags:: Viewing the source of a word in Emacs.
13847: * Hilighting:: Making Forth code look prettier.
13848: * Auto-Indentation:: Customizing auto-indentation.
13849: * Blocks Files:: Reading and writing blocks files.
13850: @end menu
13851:
13852: @c ----------------------------------
1.109 anton 13853: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13854: @section Installing gforth.el
13855: @cindex @file{.emacs}
13856: @cindex @file{gforth.el}, installation
13857: To make the features from @file{gforth.el} available in Emacs, add
13858: the following lines to your @file{.emacs} file:
13859:
13860: @example
13861: (autoload 'forth-mode "gforth.el")
13862: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13863: auto-mode-alist))
13864: (autoload 'forth-block-mode "gforth.el")
13865: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13866: auto-mode-alist))
13867: (add-hook 'forth-mode-hook (function (lambda ()
13868: ;; customize variables here:
13869: (setq forth-indent-level 4)
13870: (setq forth-minor-indent-level 2)
13871: (setq forth-hilight-level 3)
13872: ;;; ...
13873: )))
13874: @end example
13875:
13876: @c ----------------------------------
13877: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13878: @section Emacs Tags
1.1 anton 13879: @cindex @file{TAGS} file
13880: @cindex @file{etags.fs}
13881: @cindex viewing the source of a word in Emacs
1.43 anton 13882: @cindex @code{require}, placement in files
13883: @cindex @code{include}, placement in files
1.107 dvdkhlng 13884: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13885: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13886: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13887: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13888: several tags files at the same time (e.g., one for the Gforth sources
13889: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13890: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13891: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13892: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13893: with @file{etags.fs}, you should avoid putting definitions both before
13894: and after @code{require} etc., otherwise you will see the same file
13895: visited several times by commands like @code{tags-search}.
1.1 anton 13896:
1.107 dvdkhlng 13897: @c ----------------------------------
13898: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13899: @section Hilighting
13900: @cindex hilighting Forth code in Emacs
13901: @cindex highlighting Forth code in Emacs
13902: @file{gforth.el} comes with a custom source hilighting engine. When
13903: you open a file in @code{forth-mode}, it will be completely parsed,
13904: assigning faces to keywords, comments, strings etc. While you edit
13905: the file, modified regions get parsed and updated on-the-fly.
13906:
13907: Use the variable `forth-hilight-level' to change the level of
13908: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13909: you set the hilighting level to 0, the parser will still work in the
13910: background, collecting information about whether regions of text are
13911: ``compiled'' or ``interpreted''. Those information are required for
13912: auto-indentation to work properly. Set `forth-disable-parser' to
13913: non-nil if your computer is too slow to handle parsing. This will
13914: have an impact on the smartness of the auto-indentation engine,
13915: though.
13916:
13917: Sometimes Forth sources define new features that should be hilighted,
13918: new control structures, defining-words etc. You can use the variable
13919: `forth-custom-words' to make @code{forth-mode} hilight additional
13920: words and constructs. See the docstring of `forth-words' for details
13921: (in Emacs, type @kbd{C-h v forth-words}).
13922:
13923: `forth-custom-words' is meant to be customized in your
13924: @file{.emacs} file. To customize hilighing in a file-specific manner,
13925: set `forth-local-words' in a local-variables section at the end of
13926: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13927:
13928: Example:
13929: @example
13930: 0 [IF]
13931: Local Variables:
13932: forth-local-words:
13933: ((("t:") definition-starter (font-lock-keyword-face . 1)
13934: "[ \t\n]" t name (font-lock-function-name-face . 3))
13935: ((";t") definition-ender (font-lock-keyword-face . 1)))
13936: End:
13937: [THEN]
13938: @end example
13939:
13940: @c ----------------------------------
13941: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13942: @section Auto-Indentation
13943: @cindex auto-indentation of Forth code in Emacs
13944: @cindex indentation of Forth code in Emacs
13945: @code{forth-mode} automatically tries to indent lines in a smart way,
13946: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13947:
13948: Simple customization can be achieved by setting
13949: `forth-indent-level' and `forth-minor-indent-level' in your
13950: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13951: per default by multiples of 4 columns. To use the more traditional
13952: 3-column indentation, add the following lines to your @file{.emacs}:
13953:
13954: @example
13955: (add-hook 'forth-mode-hook (function (lambda ()
13956: ;; customize variables here:
13957: (setq forth-indent-level 3)
13958: (setq forth-minor-indent-level 1)
13959: )))
13960: @end example
13961:
13962: If you want indentation to recognize non-default words, customize it
13963: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
13964: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13965: v forth-indent-words}).
13966:
13967: To customize indentation in a file-specific manner, set
13968: `forth-local-indent-words' in a local-variables section at the end of
13969: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13970: Emacs Manual}).
13971:
13972: Example:
13973: @example
13974: 0 [IF]
13975: Local Variables:
13976: forth-local-indent-words:
13977: ((("t:") (0 . 2) (0 . 2))
13978: ((";t") (-2 . 0) (0 . -2)))
13979: End:
13980: [THEN]
13981: @end example
13982:
13983: @c ----------------------------------
1.109 anton 13984: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 13985: @section Blocks Files
13986: @cindex blocks files, use with Emacs
13987: @code{forth-mode} Autodetects blocks files by checking whether the
13988: length of the first line exceeds 1023 characters. It then tries to
13989: convert the file into normal text format. When you save the file, it
13990: will be written to disk as normal stream-source file.
13991:
13992: If you want to write blocks files, use @code{forth-blocks-mode}. It
13993: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 13994:
1.107 dvdkhlng 13995: @itemize @bullet
13996: @item
13997: Files are written to disk in blocks file format.
13998: @item
13999: Screen numbers are displayed in the mode line (enumerated beginning
14000: with the value of `forth-block-base')
14001: @item
14002: Warnings are displayed when lines exceed 64 characters.
14003: @item
14004: The beginning of the currently edited block is marked with an
14005: overlay-arrow.
14006: @end itemize
1.41 anton 14007:
1.107 dvdkhlng 14008: There are some restrictions you should be aware of. When you open a
14009: blocks file that contains tabulator or newline characters, these
14010: characters will be translated into spaces when the file is written
14011: back to disk. If tabs or newlines are encountered during blocks file
14012: reading, an error is output to the echo area. So have a look at the
14013: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14014:
1.107 dvdkhlng 14015: Please consult the docstring of @code{forth-blocks-mode} for more
14016: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14017:
1.26 crook 14018: @c ******************************************************************
1.1 anton 14019: @node Image Files, Engine, Emacs and Gforth, Top
14020: @chapter Image Files
1.26 crook 14021: @cindex image file
14022: @cindex @file{.fi} files
1.1 anton 14023: @cindex precompiled Forth code
14024: @cindex dictionary in persistent form
14025: @cindex persistent form of dictionary
14026:
14027: An image file is a file containing an image of the Forth dictionary,
14028: i.e., compiled Forth code and data residing in the dictionary. By
14029: convention, we use the extension @code{.fi} for image files.
14030:
14031: @menu
1.18 anton 14032: * Image Licensing Issues:: Distribution terms for images.
14033: * Image File Background:: Why have image files?
1.67 anton 14034: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14035: * Data-Relocatable Image Files:: are better.
1.67 anton 14036: * Fully Relocatable Image Files:: better yet.
1.18 anton 14037: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14038: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14039: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14040: @end menu
14041:
1.18 anton 14042: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14043: @section Image Licensing Issues
14044: @cindex license for images
14045: @cindex image license
14046:
14047: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14048: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14049: original image; i.e., according to copyright law it is a derived work of
14050: the original image.
14051:
14052: Since Gforth is distributed under the GNU GPL, the newly created image
14053: falls under the GNU GPL, too. In particular, this means that if you
14054: distribute the image, you have to make all of the sources for the image
1.113 anton 14055: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14056: GNU General Public License (Section 3)}.
14057:
14058: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14059: contains only code compiled from the sources you gave it; if none of
14060: these sources is under the GPL, the terms discussed above do not apply
14061: to the image. However, if your image needs an engine (a gforth binary)
14062: that is under the GPL, you should make sure that you distribute both in
14063: a way that is at most a @emph{mere aggregation}, if you don't want the
14064: terms of the GPL to apply to the image.
14065:
14066: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14067: @section Image File Background
14068: @cindex image file background
14069:
1.80 anton 14070: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14071: definitions written in Forth. Since the Forth compiler itself belongs to
14072: those definitions, it is not possible to start the system with the
1.80 anton 14073: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14074: code as an image file in nearly executable form. When Gforth starts up,
14075: a C routine loads the image file into memory, optionally relocates the
14076: addresses, then sets up the memory (stacks etc.) according to
14077: information in the image file, and (finally) starts executing Forth
14078: code.
1.1 anton 14079:
14080: The image file variants represent different compromises between the
14081: goals of making it easy to generate image files and making them
14082: portable.
14083:
14084: @cindex relocation at run-time
1.26 crook 14085: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14086: run-time. This avoids many of the complications discussed below (image
14087: files are data relocatable without further ado), but costs performance
14088: (one addition per memory access).
14089:
14090: @cindex relocation at load-time
1.26 crook 14091: By contrast, the Gforth loader performs relocation at image load time. The
14092: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14093: appropriate code-field addresses (or code addresses in the case of
14094: direct threading).
14095:
14096: There are three kinds of image files, with different degrees of
14097: relocatability: non-relocatable, data-relocatable, and fully relocatable
14098: image files.
14099:
14100: @cindex image file loader
14101: @cindex relocating loader
14102: @cindex loader for image files
14103: These image file variants have several restrictions in common; they are
14104: caused by the design of the image file loader:
14105:
14106: @itemize @bullet
14107: @item
14108: There is only one segment; in particular, this means, that an image file
14109: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14110: them). The contents of the stacks are not represented, either.
1.1 anton 14111:
14112: @item
14113: The only kinds of relocation supported are: adding the same offset to
14114: all cells that represent data addresses; and replacing special tokens
14115: with code addresses or with pieces of machine code.
14116:
14117: If any complex computations involving addresses are performed, the
14118: results cannot be represented in the image file. Several applications that
14119: use such computations come to mind:
14120: @itemize @minus
14121: @item
14122: Hashing addresses (or data structures which contain addresses) for table
14123: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14124: purpose, you will have no problem, because the hash tables are
14125: recomputed automatically when the system is started. If you use your own
14126: hash tables, you will have to do something similar.
14127:
14128: @item
14129: There's a cute implementation of doubly-linked lists that uses
14130: @code{XOR}ed addresses. You could represent such lists as singly-linked
14131: in the image file, and restore the doubly-linked representation on
14132: startup.@footnote{In my opinion, though, you should think thrice before
14133: using a doubly-linked list (whatever implementation).}
14134:
14135: @item
14136: The code addresses of run-time routines like @code{docol:} cannot be
14137: represented in the image file (because their tokens would be replaced by
14138: machine code in direct threaded implementations). As a workaround,
14139: compute these addresses at run-time with @code{>code-address} from the
14140: executions tokens of appropriate words (see the definitions of
1.80 anton 14141: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14142:
14143: @item
14144: On many architectures addresses are represented in machine code in some
14145: shifted or mangled form. You cannot put @code{CODE} words that contain
14146: absolute addresses in this form in a relocatable image file. Workarounds
14147: are representing the address in some relative form (e.g., relative to
14148: the CFA, which is present in some register), or loading the address from
14149: a place where it is stored in a non-mangled form.
14150: @end itemize
14151: @end itemize
14152:
14153: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14154: @section Non-Relocatable Image Files
14155: @cindex non-relocatable image files
1.26 crook 14156: @cindex image file, non-relocatable
1.1 anton 14157:
14158: These files are simple memory dumps of the dictionary. They are specific
14159: to the executable (i.e., @file{gforth} file) they were created
14160: with. What's worse, they are specific to the place on which the
14161: dictionary resided when the image was created. Now, there is no
14162: guarantee that the dictionary will reside at the same place the next
14163: time you start Gforth, so there's no guarantee that a non-relocatable
14164: image will work the next time (Gforth will complain instead of crashing,
14165: though).
14166:
14167: You can create a non-relocatable image file with
14168:
1.44 crook 14169:
1.1 anton 14170: doc-savesystem
14171:
1.44 crook 14172:
1.1 anton 14173: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14174: @section Data-Relocatable Image Files
14175: @cindex data-relocatable image files
1.26 crook 14176: @cindex image file, data-relocatable
1.1 anton 14177:
14178: These files contain relocatable data addresses, but fixed code addresses
14179: (instead of tokens). They are specific to the executable (i.e.,
14180: @file{gforth} file) they were created with. For direct threading on some
14181: architectures (e.g., the i386), data-relocatable images do not work. You
14182: get a data-relocatable image, if you use @file{gforthmi} with a
14183: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14184: Relocatable Image Files}).
14185:
14186: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14187: @section Fully Relocatable Image Files
14188: @cindex fully relocatable image files
1.26 crook 14189: @cindex image file, fully relocatable
1.1 anton 14190:
14191: @cindex @file{kern*.fi}, relocatability
14192: @cindex @file{gforth.fi}, relocatability
14193: These image files have relocatable data addresses, and tokens for code
14194: addresses. They can be used with different binaries (e.g., with and
14195: without debugging) on the same machine, and even across machines with
14196: the same data formats (byte order, cell size, floating point
14197: format). However, they are usually specific to the version of Gforth
14198: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14199: are fully relocatable.
14200:
14201: There are two ways to create a fully relocatable image file:
14202:
14203: @menu
1.29 crook 14204: * gforthmi:: The normal way
1.1 anton 14205: * cross.fs:: The hard way
14206: @end menu
14207:
14208: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14209: @subsection @file{gforthmi}
14210: @cindex @file{comp-i.fs}
14211: @cindex @file{gforthmi}
14212:
14213: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14214: image @i{file} that contains everything you would load by invoking
14215: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14216: @example
1.29 crook 14217: gforthmi @i{file} @i{options}
1.1 anton 14218: @end example
14219:
14220: E.g., if you want to create an image @file{asm.fi} that has the file
14221: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14222: like this:
14223:
14224: @example
14225: gforthmi asm.fi asm.fs
14226: @end example
14227:
1.27 crook 14228: @file{gforthmi} is implemented as a sh script and works like this: It
14229: produces two non-relocatable images for different addresses and then
14230: compares them. Its output reflects this: first you see the output (if
1.62 crook 14231: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14232: files, then you see the output of the comparing program: It displays the
14233: offset used for data addresses and the offset used for code addresses;
1.1 anton 14234: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14235: image files, it displays a line like this:
1.1 anton 14236:
14237: @example
14238: 78DC BFFFFA50 BFFFFA40
14239: @end example
14240:
14241: This means that at offset $78dc from @code{forthstart}, one input image
14242: contains $bffffa50, and the other contains $bffffa40. Since these cells
14243: cannot be represented correctly in the output image, you should examine
14244: these places in the dictionary and verify that these cells are dead
14245: (i.e., not read before they are written).
1.39 anton 14246:
14247: @cindex --application, @code{gforthmi} option
14248: If you insert the option @code{--application} in front of the image file
14249: name, you will get an image that uses the @code{--appl-image} option
14250: instead of the @code{--image-file} option (@pxref{Invoking
14251: Gforth}). When you execute such an image on Unix (by typing the image
14252: name as command), the Gforth engine will pass all options to the image
14253: instead of trying to interpret them as engine options.
1.1 anton 14254:
1.27 crook 14255: If you type @file{gforthmi} with no arguments, it prints some usage
14256: instructions.
14257:
1.1 anton 14258: @cindex @code{savesystem} during @file{gforthmi}
14259: @cindex @code{bye} during @file{gforthmi}
14260: @cindex doubly indirect threaded code
1.44 crook 14261: @cindex environment variables
14262: @cindex @code{GFORTHD} -- environment variable
14263: @cindex @code{GFORTH} -- environment variable
1.1 anton 14264: @cindex @code{gforth-ditc}
1.29 crook 14265: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14266: words @code{savesystem} and @code{bye} must be visible. A special doubly
14267: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14268: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14269: this executable through the environment variable @code{GFORTHD}
14270: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14271: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14272: data-relocatable image (because there is no code address offset). The
14273: normal @file{gforth} executable is used for creating the relocatable
14274: image; you can pass the exact filename of this executable through the
14275: environment variable @code{GFORTH}.
1.1 anton 14276:
14277: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14278: @subsection @file{cross.fs}
14279: @cindex @file{cross.fs}
14280: @cindex cross-compiler
14281: @cindex metacompiler
1.47 crook 14282: @cindex target compiler
1.1 anton 14283:
14284: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14285: programming language (@pxref{Cross Compiler}).
1.1 anton 14286:
1.47 crook 14287: @code{cross} allows you to create image files for machines with
1.1 anton 14288: different data sizes and data formats than the one used for generating
14289: the image file. You can also use it to create an application image that
14290: does not contain a Forth compiler. These features are bought with
14291: restrictions and inconveniences in programming. E.g., addresses have to
14292: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14293: order to make the code relocatable.
14294:
14295:
14296: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14297: @section Stack and Dictionary Sizes
14298: @cindex image file, stack and dictionary sizes
14299: @cindex dictionary size default
14300: @cindex stack size default
14301:
14302: If you invoke Gforth with a command line flag for the size
14303: (@pxref{Invoking Gforth}), the size you specify is stored in the
14304: dictionary. If you save the dictionary with @code{savesystem} or create
14305: an image with @file{gforthmi}, this size will become the default
14306: for the resulting image file. E.g., the following will create a
1.21 crook 14307: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14308:
14309: @example
14310: gforthmi gforth.fi -m 1M
14311: @end example
14312:
14313: In other words, if you want to set the default size for the dictionary
14314: and the stacks of an image, just invoke @file{gforthmi} with the
14315: appropriate options when creating the image.
14316:
14317: @cindex stack size, cache-friendly
14318: Note: For cache-friendly behaviour (i.e., good performance), you should
14319: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14320: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14321: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14322:
14323: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14324: @section Running Image Files
14325: @cindex running image files
14326: @cindex invoking image files
14327: @cindex image file invocation
14328:
14329: @cindex -i, invoke image file
14330: @cindex --image file, invoke image file
1.29 crook 14331: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14332: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14333: @example
1.29 crook 14334: gforth -i @i{image}
1.1 anton 14335: @end example
14336:
14337: @cindex executable image file
1.26 crook 14338: @cindex image file, executable
1.1 anton 14339: If your operating system supports starting scripts with a line of the
14340: form @code{#! ...}, you just have to type the image file name to start
14341: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14342: just a convention). I.e., to run Gforth with the image file @i{image},
14343: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14344: This works because every @code{.fi} file starts with a line of this
14345: format:
14346:
14347: @example
14348: #! /usr/local/bin/gforth-0.4.0 -i
14349: @end example
14350:
14351: The file and pathname for the Gforth engine specified on this line is
14352: the specific Gforth executable that it was built against; i.e. the value
14353: of the environment variable @code{GFORTH} at the time that
14354: @file{gforthmi} was executed.
1.1 anton 14355:
1.27 crook 14356: You can make use of the same shell capability to make a Forth source
14357: file into an executable. For example, if you place this text in a file:
1.26 crook 14358:
14359: @example
14360: #! /usr/local/bin/gforth
14361:
14362: ." Hello, world" CR
14363: bye
14364: @end example
14365:
14366: @noindent
1.27 crook 14367: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14368: directly from the command line. The sequence @code{#!} is used in two
14369: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14370: system@footnote{The Unix kernel actually recognises two types of files:
14371: executable files and files of data, where the data is processed by an
14372: interpreter that is specified on the ``interpreter line'' -- the first
14373: line of the file, starting with the sequence #!. There may be a small
14374: limit (e.g., 32) on the number of characters that may be specified on
14375: the interpreter line.} secondly it is treated as a comment character by
14376: Gforth. Because of the second usage, a space is required between
1.80 anton 14377: @code{#!} and the path to the executable (moreover, some Unixes
14378: require the sequence @code{#! /}).
1.27 crook 14379:
14380: The disadvantage of this latter technique, compared with using
1.80 anton 14381: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14382: compiled on-the-fly, each time the program is invoked.
1.26 crook 14383:
1.1 anton 14384: doc-#!
14385:
1.44 crook 14386:
1.1 anton 14387: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14388: @section Modifying the Startup Sequence
14389: @cindex startup sequence for image file
14390: @cindex image file initialization sequence
14391: @cindex initialization sequence of image file
14392:
1.120 anton 14393: You can add your own initialization to the startup sequence of an image
14394: through the deferred word @code{'cold}. @code{'cold} is invoked just
14395: before the image-specific command line processing (i.e., loading files
14396: and evaluating (@code{-e}) strings) starts.
1.1 anton 14397:
14398: A sequence for adding your initialization usually looks like this:
14399:
14400: @example
14401: :noname
14402: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14403: ... \ your stuff
14404: ; IS 'cold
14405: @end example
14406:
14407: @cindex turnkey image files
1.26 crook 14408: @cindex image file, turnkey applications
1.1 anton 14409: You can make a turnkey image by letting @code{'cold} execute a word
14410: (your turnkey application) that never returns; instead, it exits Gforth
14411: via @code{bye} or @code{throw}.
14412:
1.121 anton 14413: You can access the (image-specific) command-line arguments through
14414: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14415: arguments}).
1.1 anton 14416:
1.26 crook 14417: If @code{'cold} exits normally, Gforth processes the command-line
14418: arguments as files to be loaded and strings to be evaluated. Therefore,
14419: @code{'cold} should remove the arguments it has used in this case.
14420:
14421: doc-'cold
1.44 crook 14422:
1.1 anton 14423: @c ******************************************************************
1.113 anton 14424: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14425: @chapter Engine
14426: @cindex engine
14427: @cindex virtual machine
14428:
1.26 crook 14429: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14430: may be helpful for finding your way in the Gforth sources.
14431:
1.109 anton 14432: The ideas in this section have also been published in the following
14433: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14434: Forth-Tagung '93; M. Anton Ertl,
14435: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14436: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14437: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14438: Threaded code variations and optimizations (extended version)}},
14439: Forth-Tagung '02.
1.1 anton 14440:
14441: @menu
14442: * Portability::
14443: * Threading::
14444: * Primitives::
14445: * Performance::
14446: @end menu
14447:
14448: @node Portability, Threading, Engine, Engine
14449: @section Portability
14450: @cindex engine portability
14451:
1.26 crook 14452: An important goal of the Gforth Project is availability across a wide
14453: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14454: achieved this goal by manually coding the engine in assembly language
14455: for several then-popular processors. This approach is very
14456: labor-intensive and the results are short-lived due to progress in
14457: computer architecture.
1.1 anton 14458:
14459: @cindex C, using C for the engine
14460: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14461: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14462: particularly popular for UNIX-based Forths due to the large variety of
14463: architectures of UNIX machines. Unfortunately an implementation in C
14464: does not mix well with the goals of efficiency and with using
14465: traditional techniques: Indirect or direct threading cannot be expressed
14466: in C, and switch threading, the fastest technique available in C, is
14467: significantly slower. Another problem with C is that it is very
14468: cumbersome to express double integer arithmetic.
14469:
14470: @cindex GNU C for the engine
14471: @cindex long long
14472: Fortunately, there is a portable language that does not have these
14473: limitations: GNU C, the version of C processed by the GNU C compiler
14474: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14475: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14476: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14477: threading possible, its @code{long long} type (@pxref{Long Long, ,
14478: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14479: double numbers on many systems. GNU C is freely available on all
1.1 anton 14480: important (and many unimportant) UNIX machines, VMS, 80386s running
14481: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14482: on all these machines.
14483:
14484: Writing in a portable language has the reputation of producing code that
14485: is slower than assembly. For our Forth engine we repeatedly looked at
14486: the code produced by the compiler and eliminated most compiler-induced
14487: inefficiencies by appropriate changes in the source code.
14488:
14489: @cindex explicit register declarations
14490: @cindex --enable-force-reg, configuration flag
14491: @cindex -DFORCE_REG
14492: However, register allocation cannot be portably influenced by the
14493: programmer, leading to some inefficiencies on register-starved
14494: machines. We use explicit register declarations (@pxref{Explicit Reg
14495: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14496: improve the speed on some machines. They are turned on by using the
14497: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14498: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14499: machine, but also on the compiler version: On some machines some
14500: compiler versions produce incorrect code when certain explicit register
14501: declarations are used. So by default @code{-DFORCE_REG} is not used.
14502:
14503: @node Threading, Primitives, Portability, Engine
14504: @section Threading
14505: @cindex inner interpreter implementation
14506: @cindex threaded code implementation
14507:
14508: @cindex labels as values
14509: GNU C's labels as values extension (available since @code{gcc-2.0},
14510: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14511: makes it possible to take the address of @i{label} by writing
14512: @code{&&@i{label}}. This address can then be used in a statement like
14513: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14514: @code{goto x}.
14515:
1.26 crook 14516: @cindex @code{NEXT}, indirect threaded
1.1 anton 14517: @cindex indirect threaded inner interpreter
14518: @cindex inner interpreter, indirect threaded
1.26 crook 14519: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14520: @example
14521: cfa = *ip++;
14522: ca = *cfa;
14523: goto *ca;
14524: @end example
14525: @cindex instruction pointer
14526: For those unfamiliar with the names: @code{ip} is the Forth instruction
14527: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14528: execution token and points to the code field of the next word to be
14529: executed; The @code{ca} (code address) fetched from there points to some
14530: executable code, e.g., a primitive or the colon definition handler
14531: @code{docol}.
14532:
1.26 crook 14533: @cindex @code{NEXT}, direct threaded
1.1 anton 14534: @cindex direct threaded inner interpreter
14535: @cindex inner interpreter, direct threaded
14536: Direct threading is even simpler:
14537: @example
14538: ca = *ip++;
14539: goto *ca;
14540: @end example
14541:
14542: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14543: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14544:
14545: @menu
14546: * Scheduling::
14547: * Direct or Indirect Threaded?::
1.109 anton 14548: * Dynamic Superinstructions::
1.1 anton 14549: * DOES>::
14550: @end menu
14551:
14552: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14553: @subsection Scheduling
14554: @cindex inner interpreter optimization
14555:
14556: There is a little complication: Pipelined and superscalar processors,
14557: i.e., RISC and some modern CISC machines can process independent
14558: instructions while waiting for the results of an instruction. The
14559: compiler usually reorders (schedules) the instructions in a way that
14560: achieves good usage of these delay slots. However, on our first tries
14561: the compiler did not do well on scheduling primitives. E.g., for
14562: @code{+} implemented as
14563: @example
14564: n=sp[0]+sp[1];
14565: sp++;
14566: sp[0]=n;
14567: NEXT;
14568: @end example
1.81 anton 14569: the @code{NEXT} comes strictly after the other code, i.e., there is
14570: nearly no scheduling. After a little thought the problem becomes clear:
14571: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14572: addresses (and the version of @code{gcc} we used would not know it even
14573: if it was possible), so it could not move the load of the cfa above the
14574: store to the TOS. Indeed the pointers could be the same, if code on or
14575: very near the top of stack were executed. In the interest of speed we
14576: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14577: in scheduling: @code{NEXT} is divided into several parts:
14578: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14579: like:
1.1 anton 14580: @example
1.81 anton 14581: NEXT_P0;
1.1 anton 14582: n=sp[0]+sp[1];
14583: sp++;
14584: NEXT_P1;
14585: sp[0]=n;
14586: NEXT_P2;
14587: @end example
14588:
1.81 anton 14589: There are various schemes that distribute the different operations of
14590: NEXT between these parts in several ways; in general, different schemes
14591: perform best on different processors. We use a scheme for most
14592: architectures that performs well for most processors of this
1.109 anton 14593: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14594: the scheme on installation time.
14595:
1.1 anton 14596:
1.109 anton 14597: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14598: @subsection Direct or Indirect Threaded?
14599: @cindex threading, direct or indirect?
14600:
1.109 anton 14601: Threaded forth code consists of references to primitives (simple machine
14602: code routines like @code{+}) and to non-primitives (e.g., colon
14603: definitions, variables, constants); for a specific class of
14604: non-primitives (e.g., variables) there is one code routine (e.g.,
14605: @code{dovar}), but each variable needs a separate reference to its data.
14606:
14607: Traditionally Forth has been implemented as indirect threaded code,
14608: because this allows to use only one cell to reference a non-primitive
14609: (basically you point to the data, and find the code address there).
14610:
14611: @cindex primitive-centric threaded code
14612: However, threaded code in Gforth (since 0.6.0) uses two cells for
14613: non-primitives, one for the code address, and one for the data address;
14614: the data pointer is an immediate argument for the virtual machine
14615: instruction represented by the code address. We call this
14616: @emph{primitive-centric} threaded code, because all code addresses point
14617: to simple primitives. E.g., for a variable, the code address is for
14618: @code{lit} (also used for integer literals like @code{99}).
14619:
14620: Primitive-centric threaded code allows us to use (faster) direct
14621: threading as dispatch method, completely portably (direct threaded code
14622: in Gforth before 0.6.0 required architecture-specific code). It also
14623: eliminates the performance problems related to I-cache consistency that
14624: 386 implementations have with direct threaded code, and allows
14625: additional optimizations.
14626:
14627: @cindex hybrid direct/indirect threaded code
14628: There is a catch, however: the @var{xt} parameter of @code{execute} can
14629: occupy only one cell, so how do we pass non-primitives with their code
14630: @emph{and} data addresses to them? Our answer is to use indirect
14631: threaded dispatch for @code{execute} and other words that use a
14632: single-cell xt. So, normal threaded code in colon definitions uses
14633: direct threading, and @code{execute} and similar words, which dispatch
14634: to xts on the data stack, use indirect threaded code. We call this
14635: @emph{hybrid direct/indirect} threaded code.
14636:
14637: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14638: @cindex gforth engine
14639: @cindex gforth-fast engine
14640: The engines @command{gforth} and @command{gforth-fast} use hybrid
14641: direct/indirect threaded code. This means that with these engines you
14642: cannot use @code{,} to compile an xt. Instead, you have to use
14643: @code{compile,}.
14644:
14645: @cindex gforth-itc engine
1.115 anton 14646: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14647: This engine uses plain old indirect threaded code. It still compiles in
14648: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14649: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14650: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14651: and execute @code{' , is compile,}. Your program can check if it is
14652: running on a hybrid direct/indirect threaded engine or a pure indirect
14653: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14654:
14655:
14656: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14657: @subsection Dynamic Superinstructions
14658: @cindex Dynamic superinstructions with replication
14659: @cindex Superinstructions
14660: @cindex Replication
14661:
14662: The engines @command{gforth} and @command{gforth-fast} use another
14663: optimization: Dynamic superinstructions with replication. As an
14664: example, consider the following colon definition:
14665:
14666: @example
14667: : squared ( n1 -- n2 )
14668: dup * ;
14669: @end example
14670:
14671: Gforth compiles this into the threaded code sequence
14672:
14673: @example
14674: dup
14675: *
14676: ;s
14677: @end example
14678:
14679: In normal direct threaded code there is a code address occupying one
14680: cell for each of these primitives. Each code address points to a
14681: machine code routine, and the interpreter jumps to this machine code in
14682: order to execute the primitive. The routines for these three
14683: primitives are (in @command{gforth-fast} on the 386):
14684:
14685: @example
14686: Code dup
14687: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14688: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14689: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14690: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14691: end-code
14692: Code *
14693: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14694: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14695: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14696: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14697: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14698: end-code
14699: Code ;s
14700: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14701: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14702: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14703: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14704: end-code
14705: @end example
14706:
14707: With dynamic superinstructions and replication the compiler does not
14708: just lay down the threaded code, but also copies the machine code
14709: fragments, usually without the jump at the end.
14710:
14711: @example
14712: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14713: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14714: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14715: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14716: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14717: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14718: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14719: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14720: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14721: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14722: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14723: @end example
14724:
14725: Only when a threaded-code control-flow change happens (e.g., in
14726: @code{;s}), the jump is appended. This optimization eliminates many of
14727: these jumps and makes the rest much more predictable. The speedup
14728: depends on the processor and the application; on the Athlon and Pentium
14729: III this optimization typically produces a speedup by a factor of 2.
14730:
14731: The code addresses in the direct-threaded code are set to point to the
14732: appropriate points in the copied machine code, in this example like
14733: this:
1.1 anton 14734:
1.109 anton 14735: @example
14736: primitive code address
14737: dup $4057D27D
14738: * $4057D286
14739: ;s $4057D292
14740: @end example
14741:
14742: Thus there can be threaded-code jumps to any place in this piece of
14743: code. This also simplifies decompilation quite a bit.
14744:
14745: @cindex --no-dynamic command-line option
14746: @cindex --no-super command-line option
14747: You can disable this optimization with @option{--no-dynamic}. You can
14748: use the copying without eliminating the jumps (i.e., dynamic
14749: replication, but without superinstructions) with @option{--no-super};
14750: this gives the branch prediction benefit alone; the effect on
1.110 anton 14751: performance depends on the CPU; on the Athlon and Pentium III the
14752: speedup is a little less than for dynamic superinstructions with
14753: replication.
14754:
14755: @cindex patching threaded code
14756: One use of these options is if you want to patch the threaded code.
14757: With superinstructions, many of the dispatch jumps are eliminated, so
14758: patching often has no effect. These options preserve all the dispatch
14759: jumps.
1.109 anton 14760:
14761: @cindex --dynamic command-line option
1.110 anton 14762: On some machines dynamic superinstructions are disabled by default,
14763: because it is unsafe on these machines. However, if you feel
14764: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14765:
14766: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14767: @subsection DOES>
14768: @cindex @code{DOES>} implementation
14769:
1.26 crook 14770: @cindex @code{dodoes} routine
14771: @cindex @code{DOES>}-code
1.1 anton 14772: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14773: the chunk of code executed by every word defined by a
1.109 anton 14774: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14775: this is only needed if the xt of the word is @code{execute}d. The main
14776: problem here is: How to find the Forth code to be executed, i.e. the
14777: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14778: solutions:
1.1 anton 14779:
1.21 crook 14780: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14781: @code{DOES>}-code address is stored in the cell after the code address
14782: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14783: illegal in the Forth-79 and all later standards, because in fig-Forth
14784: this address lies in the body (which is illegal in these
14785: standards). However, by making the code field larger for all words this
14786: solution becomes legal again. We use this approach. Leaving a cell
14787: unused in most words is a bit wasteful, but on the machines we are
14788: targeting this is hardly a problem.
14789:
1.1 anton 14790:
14791: @node Primitives, Performance, Threading, Engine
14792: @section Primitives
14793: @cindex primitives, implementation
14794: @cindex virtual machine instructions, implementation
14795:
14796: @menu
14797: * Automatic Generation::
14798: * TOS Optimization::
14799: * Produced code::
14800: @end menu
14801:
14802: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14803: @subsection Automatic Generation
14804: @cindex primitives, automatic generation
14805:
14806: @cindex @file{prims2x.fs}
1.109 anton 14807:
1.1 anton 14808: Since the primitives are implemented in a portable language, there is no
14809: longer any need to minimize the number of primitives. On the contrary,
14810: having many primitives has an advantage: speed. In order to reduce the
14811: number of errors in primitives and to make programming them easier, we
1.109 anton 14812: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14813: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14814: generates most (and sometimes all) of the C code for a primitive from
14815: the stack effect notation. The source for a primitive has the following
14816: form:
1.1 anton 14817:
14818: @cindex primitive source format
14819: @format
1.58 anton 14820: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14821: [@code{""}@i{glossary entry}@code{""}]
14822: @i{C code}
1.1 anton 14823: [@code{:}
1.29 crook 14824: @i{Forth code}]
1.1 anton 14825: @end format
14826:
14827: The items in brackets are optional. The category and glossary fields
14828: are there for generating the documentation, the Forth code is there
14829: for manual implementations on machines without GNU C. E.g., the source
14830: for the primitive @code{+} is:
14831: @example
1.58 anton 14832: + ( n1 n2 -- n ) core plus
1.1 anton 14833: n = n1+n2;
14834: @end example
14835:
14836: This looks like a specification, but in fact @code{n = n1+n2} is C
14837: code. Our primitive generation tool extracts a lot of information from
14838: the stack effect notations@footnote{We use a one-stack notation, even
14839: though we have separate data and floating-point stacks; The separate
14840: notation can be generated easily from the unified notation.}: The number
14841: of items popped from and pushed on the stack, their type, and by what
14842: name they are referred to in the C code. It then generates a C code
14843: prelude and postlude for each primitive. The final C code for @code{+}
14844: looks like this:
14845:
14846: @example
1.46 pazsan 14847: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14848: /* */ /* documentation */
1.81 anton 14849: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14850: @{
14851: DEF_CA /* definition of variable ca (indirect threading) */
14852: Cell n1; /* definitions of variables */
14853: Cell n2;
14854: Cell n;
1.81 anton 14855: NEXT_P0; /* NEXT part 0 */
1.1 anton 14856: n1 = (Cell) sp[1]; /* input */
14857: n2 = (Cell) TOS;
14858: sp += 1; /* stack adjustment */
14859: @{
14860: n = n1+n2; /* C code taken from the source */
14861: @}
14862: NEXT_P1; /* NEXT part 1 */
14863: TOS = (Cell)n; /* output */
14864: NEXT_P2; /* NEXT part 2 */
14865: @}
14866: @end example
14867:
14868: This looks long and inefficient, but the GNU C compiler optimizes quite
14869: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14870: HP RISC machines: Defining the @code{n}s does not produce any code, and
14871: using them as intermediate storage also adds no cost.
14872:
1.26 crook 14873: There are also other optimizations that are not illustrated by this
14874: example: assignments between simple variables are usually for free (copy
1.1 anton 14875: propagation). If one of the stack items is not used by the primitive
14876: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14877: (dead code elimination). On the other hand, there are some things that
14878: the compiler does not do, therefore they are performed by
14879: @file{prims2x.fs}: The compiler does not optimize code away that stores
14880: a stack item to the place where it just came from (e.g., @code{over}).
14881:
14882: While programming a primitive is usually easy, there are a few cases
14883: where the programmer has to take the actions of the generator into
14884: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14885: fall through to @code{NEXT}.
1.109 anton 14886:
14887: For more information
1.1 anton 14888:
14889: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14890: @subsection TOS Optimization
14891: @cindex TOS optimization for primitives
14892: @cindex primitives, keeping the TOS in a register
14893:
14894: An important optimization for stack machine emulators, e.g., Forth
14895: engines, is keeping one or more of the top stack items in
1.29 crook 14896: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14897: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14898: @itemize @bullet
14899: @item
1.29 crook 14900: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14901: due to fewer loads from and stores to the stack.
1.29 crook 14902: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14903: @i{y<n}, due to additional moves between registers.
1.1 anton 14904: @end itemize
14905:
14906: @cindex -DUSE_TOS
14907: @cindex -DUSE_NO_TOS
14908: In particular, keeping one item in a register is never a disadvantage,
14909: if there are enough registers. Keeping two items in registers is a
14910: disadvantage for frequent words like @code{?branch}, constants,
14911: variables, literals and @code{i}. Therefore our generator only produces
14912: code that keeps zero or one items in registers. The generated C code
14913: covers both cases; the selection between these alternatives is made at
14914: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14915: code for @code{+} is just a simple variable name in the one-item case,
14916: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14917: GNU C compiler tries to keep simple variables like @code{TOS} in
14918: registers, and it usually succeeds, if there are enough registers.
14919:
14920: @cindex -DUSE_FTOS
14921: @cindex -DUSE_NO_FTOS
14922: The primitive generator performs the TOS optimization for the
14923: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14924: operations the benefit of this optimization is even larger:
14925: floating-point operations take quite long on most processors, but can be
14926: performed in parallel with other operations as long as their results are
14927: not used. If the FP-TOS is kept in a register, this works. If
14928: it is kept on the stack, i.e., in memory, the store into memory has to
14929: wait for the result of the floating-point operation, lengthening the
14930: execution time of the primitive considerably.
14931:
14932: The TOS optimization makes the automatic generation of primitives a
14933: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14934: @code{TOS} is not sufficient. There are some special cases to
14935: consider:
14936: @itemize @bullet
14937: @item In the case of @code{dup ( w -- w w )} the generator must not
14938: eliminate the store to the original location of the item on the stack,
14939: if the TOS optimization is turned on.
14940: @item Primitives with stack effects of the form @code{--}
1.29 crook 14941: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14942: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14943: must load the TOS from the stack at the end. But for the null stack
14944: effect @code{--} no stores or loads should be generated.
14945: @end itemize
14946:
14947: @node Produced code, , TOS Optimization, Primitives
14948: @subsection Produced code
14949: @cindex primitives, assembly code listing
14950:
14951: @cindex @file{engine.s}
14952: To see what assembly code is produced for the primitives on your machine
14953: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 14954: look at the resulting file @file{engine.s}. Alternatively, you can also
14955: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 14956:
14957: @node Performance, , Primitives, Engine
14958: @section Performance
14959: @cindex performance of some Forth interpreters
14960: @cindex engine performance
14961: @cindex benchmarking Forth systems
14962: @cindex Gforth performance
14963:
14964: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 14965: impossible to write a significantly faster threaded-code engine.
1.1 anton 14966:
14967: On register-starved machines like the 386 architecture processors
14968: improvements are possible, because @code{gcc} does not utilize the
14969: registers as well as a human, even with explicit register declarations;
14970: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14971: and hand-tuned it for the 486; this system is 1.19 times faster on the
14972: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14973: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14974: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14975: registers fit in real registers (and we can even afford to use the TOS
14976: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 14977: earlier results. And dynamic superinstructions provide another speedup
14978: (but only around a factor 1.2 on the 486).
1.1 anton 14979:
14980: @cindex Win32Forth performance
14981: @cindex NT Forth performance
14982: @cindex eforth performance
14983: @cindex ThisForth performance
14984: @cindex PFE performance
14985: @cindex TILE performance
1.81 anton 14986: The potential advantage of assembly language implementations is not
1.112 anton 14987: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 14988: (direct threaded, compiled with @code{gcc-2.95.1} and
14989: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14990: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14991: (with and without peephole (aka pinhole) optimization of the threaded
14992: code); all these systems were written in assembly language. We also
14993: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14994: with @code{gcc-2.6.3} with the default configuration for Linux:
14995: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14996: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14997: employs peephole optimization of the threaded code) and TILE (compiled
14998: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14999: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15000: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15001: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15002: then extended it to run the benchmarks, added the peephole optimizer,
15003: ran the benchmarks and reported the results.
1.40 anton 15004:
1.1 anton 15005: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15006: matrix multiplication come from the Stanford integer benchmarks and have
15007: been translated into Forth by Martin Fraeman; we used the versions
15008: included in the TILE Forth package, but with bigger data set sizes; and
15009: a recursive Fibonacci number computation for benchmarking calling
15010: performance. The following table shows the time taken for the benchmarks
15011: scaled by the time taken by Gforth (in other words, it shows the speedup
15012: factor that Gforth achieved over the other systems).
15013:
15014: @example
1.112 anton 15015: relative Win32- NT eforth This-
15016: time Gforth Forth Forth eforth +opt PFE Forth TILE
15017: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15018: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15019: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15020: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15021: @end example
15022:
1.26 crook 15023: You may be quite surprised by the good performance of Gforth when
15024: compared with systems written in assembly language. One important reason
15025: for the disappointing performance of these other systems is probably
15026: that they are not written optimally for the 486 (e.g., they use the
15027: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15028: but costly method for relocating the Forth image: like @code{cforth}, it
15029: computes the actual addresses at run time, resulting in two address
15030: computations per @code{NEXT} (@pxref{Image File Background}).
15031:
1.1 anton 15032: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15033: explained with the self-imposed restriction of the latter systems to
15034: standard C, which makes efficient threading impossible (however, the
1.4 anton 15035: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15036: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15037: Moreover, current C compilers have a hard time optimizing other aspects
15038: of the ThisForth and the TILE source.
15039:
1.26 crook 15040: The performance of Gforth on 386 architecture processors varies widely
15041: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15042: allocate any of the virtual machine registers into real machine
15043: registers by itself and would not work correctly with explicit register
1.112 anton 15044: declarations, giving a significantly slower engine (on a 486DX2/66
15045: running the Sieve) than the one measured above.
1.1 anton 15046:
1.26 crook 15047: Note that there have been several releases of Win32Forth since the
15048: release presented here, so the results presented above may have little
1.40 anton 15049: predictive value for the performance of Win32Forth today (results for
15050: the current release on an i486DX2/66 are welcome).
1.1 anton 15051:
15052: @cindex @file{Benchres}
1.66 anton 15053: In
15054: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15055: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15056: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15057: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15058: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15059: than the version used here. You can find a newer version of these
15060: measurements at
1.47 crook 15061: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15062: find numbers for Gforth on various machines in @file{Benchres}.
15063:
1.26 crook 15064: @c ******************************************************************
1.113 anton 15065: @c @node Binding to System Library, Cross Compiler, Engine, Top
15066: @c @chapter Binding to System Library
1.13 pazsan 15067:
1.113 anton 15068: @c ****************************************************************
15069: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15070: @chapter Cross Compiler
1.47 crook 15071: @cindex @file{cross.fs}
15072: @cindex cross-compiler
15073: @cindex metacompiler
15074: @cindex target compiler
1.13 pazsan 15075:
1.46 pazsan 15076: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15077: mostly written in Forth, including crucial parts like the outer
15078: interpreter and compiler, it needs compiled Forth code to get
15079: started. The cross compiler allows to create new images for other
15080: architectures, even running under another Forth system.
1.13 pazsan 15081:
15082: @menu
1.67 anton 15083: * Using the Cross Compiler::
15084: * How the Cross Compiler Works::
1.13 pazsan 15085: @end menu
15086:
1.21 crook 15087: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15088: @section Using the Cross Compiler
1.46 pazsan 15089:
15090: The cross compiler uses a language that resembles Forth, but isn't. The
15091: main difference is that you can execute Forth code after definition,
15092: while you usually can't execute the code compiled by cross, because the
15093: code you are compiling is typically for a different computer than the
15094: one you are compiling on.
15095:
1.81 anton 15096: @c anton: This chapter is somewhat different from waht I would expect: I
15097: @c would expect an explanation of the cross language and how to create an
15098: @c application image with it. The section explains some aspects of
15099: @c creating a Gforth kernel.
15100:
1.46 pazsan 15101: The Makefile is already set up to allow you to create kernels for new
15102: architectures with a simple make command. The generic kernels using the
15103: GCC compiled virtual machine are created in the normal build process
15104: with @code{make}. To create a embedded Gforth executable for e.g. the
15105: 8086 processor (running on a DOS machine), type
15106:
15107: @example
15108: make kernl-8086.fi
15109: @end example
15110:
15111: This will use the machine description from the @file{arch/8086}
15112: directory to create a new kernel. A machine file may look like that:
15113:
15114: @example
15115: \ Parameter for target systems 06oct92py
15116:
15117: 4 Constant cell \ cell size in bytes
15118: 2 Constant cell<< \ cell shift to bytes
15119: 5 Constant cell>bit \ cell shift to bits
15120: 8 Constant bits/char \ bits per character
15121: 8 Constant bits/byte \ bits per byte [default: 8]
15122: 8 Constant float \ bytes per float
15123: 8 Constant /maxalign \ maximum alignment in bytes
15124: false Constant bigendian \ byte order
15125: ( true=big, false=little )
15126:
15127: include machpc.fs \ feature list
15128: @end example
15129:
15130: This part is obligatory for the cross compiler itself, the feature list
15131: is used by the kernel to conditionally compile some features in and out,
15132: depending on whether the target supports these features.
15133:
15134: There are some optional features, if you define your own primitives,
15135: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15136: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15137: @code{prims-include} includes primitives, and @code{>boot} prepares for
15138: booting.
15139:
15140: @example
15141: : asm-include ." Include assembler" cr
15142: s" arch/8086/asm.fs" included ;
15143:
15144: : prims-include ." Include primitives" cr
15145: s" arch/8086/prim.fs" included ;
15146:
15147: : >boot ." Prepare booting" cr
15148: s" ' boot >body into-forth 1+ !" evaluate ;
15149: @end example
15150:
15151: These words are used as sort of macro during the cross compilation in
1.81 anton 15152: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15153: be possible --- but more complicated --- to write a new kernel project
15154: file, too.
15155:
15156: @file{kernel/main.fs} expects the machine description file name on the
15157: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15158: @code{mach-file} leaves a counted string on the stack, or
15159: @code{machine-file} leaves an address, count pair of the filename on the
15160: stack.
15161:
15162: The feature list is typically controlled using @code{SetValue}, generic
15163: files that are used by several projects can use @code{DefaultValue}
15164: instead. Both functions work like @code{Value}, when the value isn't
15165: defined, but @code{SetValue} works like @code{to} if the value is
15166: defined, and @code{DefaultValue} doesn't set anything, if the value is
15167: defined.
15168:
15169: @example
15170: \ generic mach file for pc gforth 03sep97jaw
15171:
15172: true DefaultValue NIL \ relocating
15173:
15174: >ENVIRON
15175:
15176: true DefaultValue file \ controls the presence of the
15177: \ file access wordset
15178: true DefaultValue OS \ flag to indicate a operating system
15179:
15180: true DefaultValue prims \ true: primitives are c-code
15181:
15182: true DefaultValue floating \ floating point wordset is present
15183:
15184: true DefaultValue glocals \ gforth locals are present
15185: \ will be loaded
15186: true DefaultValue dcomps \ double number comparisons
15187:
15188: true DefaultValue hash \ hashing primitives are loaded/present
15189:
15190: true DefaultValue xconds \ used together with glocals,
15191: \ special conditionals supporting gforths'
15192: \ local variables
15193: true DefaultValue header \ save a header information
15194:
15195: true DefaultValue backtrace \ enables backtrace code
15196:
15197: false DefaultValue ec
15198: false DefaultValue crlf
15199:
15200: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15201:
15202: &16 KB DefaultValue stack-size
15203: &15 KB &512 + DefaultValue fstack-size
15204: &15 KB DefaultValue rstack-size
15205: &14 KB &512 + DefaultValue lstack-size
15206: @end example
1.13 pazsan 15207:
1.48 anton 15208: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15209: @section How the Cross Compiler Works
1.13 pazsan 15210:
15211: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15212: @appendix Bugs
1.1 anton 15213: @cindex bug reporting
15214:
1.21 crook 15215: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15216:
1.103 anton 15217: If you find a bug, please submit a bug report through
15218: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15219:
15220: @itemize @bullet
15221: @item
1.81 anton 15222: A program (or a sequence of keyboard commands) that reproduces the bug.
15223: @item
15224: A description of what you think constitutes the buggy behaviour.
15225: @item
1.21 crook 15226: The Gforth version used (it is announced at the start of an
15227: interactive Gforth session).
15228: @item
15229: The machine and operating system (on Unix
15230: systems @code{uname -a} will report this information).
15231: @item
1.81 anton 15232: The installation options (you can find the configure options at the
15233: start of @file{config.status}) and configuration (@code{configure}
15234: output or @file{config.cache}).
1.21 crook 15235: @item
15236: A complete list of changes (if any) you (or your installer) have made to the
15237: Gforth sources.
15238: @end itemize
1.1 anton 15239:
15240: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15241: to Report Bugs, gcc.info, GNU C Manual}.
15242:
15243:
1.21 crook 15244: @node Origin, Forth-related information, Bugs, Top
15245: @appendix Authors and Ancestors of Gforth
1.1 anton 15246:
15247: @section Authors and Contributors
15248: @cindex authors of Gforth
15249: @cindex contributors to Gforth
15250:
15251: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15252: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15253: lot to the manual. Assemblers and disassemblers were contributed by
15254: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15255: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15256: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15257: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15258: support for calling C libraries. Helpful comments also came from Paul
15259: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15260: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15261: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15262: Gforth-0.2.1 there were also helpful comments from many others; thank
15263: you all, sorry for not listing you here (but digging through my mailbox
15264: to extract your names is on my to-do list).
1.1 anton 15265:
15266: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15267: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15268: was developed across the Internet, and its authors did not meet
1.20 pazsan 15269: physically for the first 4 years of development.
1.1 anton 15270:
15271: @section Pedigree
1.26 crook 15272: @cindex pedigree of Gforth
1.1 anton 15273:
1.81 anton 15274: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15275: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15276:
1.20 pazsan 15277: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15278: 32 bit native code version of VolksForth for the Atari ST, written
15279: mostly by Dietrich Weineck.
15280:
1.81 anton 15281: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15282: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15283: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15284:
15285: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15286: Forth-83 standard. !! Pedigree? When?
15287:
15288: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15289: 1979. Robert Selzer and Bill Ragsdale developed the original
15290: implementation of fig-Forth for the 6502 based on microForth.
15291:
15292: The principal architect of microForth was Dean Sanderson. microForth was
15293: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15294: the 1802, and subsequently implemented on the 8080, the 6800 and the
15295: Z80.
15296:
15297: All earlier Forth systems were custom-made, usually by Charles Moore,
15298: who discovered (as he puts it) Forth during the late 60s. The first full
15299: Forth existed in 1971.
15300:
1.81 anton 15301: A part of the information in this section comes from
15302: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15303: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15304: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15305: SIGPLAN Notices 28(3), 1993. You can find more historical and
15306: genealogical information about Forth there.
1.1 anton 15307:
1.81 anton 15308: @c ------------------------------------------------------------------
1.113 anton 15309: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15310: @appendix Other Forth-related information
15311: @cindex Forth-related information
15312:
1.81 anton 15313: @c anton: I threw most of this stuff out, because it can be found through
15314: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15315:
15316: @cindex comp.lang.forth
15317: @cindex frequently asked questions
1.81 anton 15318: There is an active news group (comp.lang.forth) discussing Forth
15319: (including Gforth) and Forth-related issues. Its
15320: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15321: (frequently asked questions and their answers) contains a lot of
15322: information on Forth. You should read it before posting to
15323: comp.lang.forth.
1.21 crook 15324:
1.81 anton 15325: The ANS Forth standard is most usable in its
15326: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15327:
1.113 anton 15328: @c ---------------------------------------------------
15329: @node Licenses, Word Index, Forth-related information, Top
15330: @appendix Licenses
15331:
15332: @menu
15333: * GNU Free Documentation License:: License for copying this manual.
15334: * Copying:: GPL (for copying this software).
15335: @end menu
15336:
15337: @include fdl.texi
15338:
15339: @include gpl.texi
15340:
15341:
15342:
1.81 anton 15343: @c ------------------------------------------------------------------
1.113 anton 15344: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15345: @unnumbered Word Index
15346:
1.26 crook 15347: This index is a list of Forth words that have ``glossary'' entries
15348: within this manual. Each word is listed with its stack effect and
15349: wordset.
1.1 anton 15350:
15351: @printindex fn
15352:
1.81 anton 15353: @c anton: the name index seems superfluous given the word and concept indices.
15354:
15355: @c @node Name Index, Concept Index, Word Index, Top
15356: @c @unnumbered Name Index
1.41 anton 15357:
1.81 anton 15358: @c This index is a list of Forth words that have ``glossary'' entries
15359: @c within this manual.
1.41 anton 15360:
1.81 anton 15361: @c @printindex ky
1.41 anton 15362:
1.113 anton 15363: @c -------------------------------------------------------
1.81 anton 15364: @node Concept Index, , Word Index, Top
1.1 anton 15365: @unnumbered Concept and Word Index
15366:
1.26 crook 15367: Not all entries listed in this index are present verbatim in the
15368: text. This index also duplicates, in abbreviated form, all of the words
15369: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15370:
15371: @printindex cp
15372:
15373: @bye
1.81 anton 15374:
15375:
1.1 anton 15376:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>