Annotation of gforth/doc/gforth.ds, revision 1.148
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.142 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
226: * Assembler and Code Words::
227: * Threading Words::
1.65 anton 228: * Passing Commands to the OS::
229: * Keeping track of Time::
230: * Miscellaneous Words::
1.12 anton 231:
232: Arithmetic
233:
234: * Single precision::
1.67 anton 235: * Double precision:: Double-cell integer arithmetic
1.12 anton 236: * Bitwise operations::
1.67 anton 237: * Numeric comparison::
1.32 anton 238: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 239: * Floating Point::
240:
241: Stack Manipulation
242:
243: * Data stack::
244: * Floating point stack::
245: * Return stack::
246: * Locals stack::
247: * Stack pointer manipulation::
248:
249: Memory
250:
1.32 anton 251: * Memory model::
252: * Dictionary allocation::
253: * Heap Allocation::
254: * Memory Access::
255: * Address arithmetic::
256: * Memory Blocks::
1.12 anton 257:
258: Control Structures
259:
1.41 anton 260: * Selection:: IF ... ELSE ... ENDIF
261: * Simple Loops:: BEGIN ...
1.32 anton 262: * Counted Loops:: DO
1.67 anton 263: * Arbitrary control structures::
264: * Calls and returns::
1.12 anton 265: * Exception Handling::
266:
267: Defining Words
268:
1.67 anton 269: * CREATE::
1.44 crook 270: * Variables:: Variables and user variables
1.67 anton 271: * Constants::
1.44 crook 272: * Values:: Initialised variables
1.67 anton 273: * Colon Definitions::
1.44 crook 274: * Anonymous Definitions:: Definitions without names
1.71 anton 275: * Supplying names:: Passing definition names as strings
1.67 anton 276: * User-defined Defining Words::
1.44 crook 277: * Deferred words:: Allow forward references
1.67 anton 278: * Aliases::
1.47 crook 279:
1.63 anton 280: User-defined Defining Words
281:
282: * CREATE..DOES> applications::
283: * CREATE..DOES> details::
284: * Advanced does> usage example::
1.91 anton 285: * @code{Const-does>}::
1.63 anton 286:
1.47 crook 287: Interpretation and Compilation Semantics
288:
1.67 anton 289: * Combined words::
1.12 anton 290:
1.71 anton 291: Tokens for Words
292:
293: * Execution token:: represents execution/interpretation semantics
294: * Compilation token:: represents compilation semantics
295: * Name token:: represents named words
296:
1.82 anton 297: Compiling words
298:
299: * Literals:: Compiling data values
300: * Macros:: Compiling words
301:
1.21 crook 302: The Text Interpreter
303:
1.67 anton 304: * Input Sources::
305: * Number Conversion::
306: * Interpret/Compile states::
307: * Interpreter Directives::
1.21 crook 308:
1.26 crook 309: Word Lists
310:
1.75 anton 311: * Vocabularies::
1.67 anton 312: * Why use word lists?::
1.75 anton 313: * Word list example::
1.26 crook 314:
315: Files
316:
1.48 anton 317: * Forth source files::
318: * General files::
319: * Search Paths::
320:
321: Search Paths
322:
1.75 anton 323: * Source Search Paths::
1.26 crook 324: * General Search Paths::
325:
326: Other I/O
327:
1.32 anton 328: * Simple numeric output:: Predefined formats
329: * Formatted numeric output:: Formatted (pictured) output
330: * String Formats:: How Forth stores strings in memory
1.67 anton 331: * Displaying characters and strings:: Other stuff
1.32 anton 332: * Input:: Input
1.112 anton 333: * Pipes:: How to create your own pipes
1.26 crook 334:
335: Locals
336:
337: * Gforth locals::
338: * ANS Forth locals::
339:
340: Gforth locals
341:
342: * Where are locals visible by name?::
343: * How long do locals live?::
1.78 anton 344: * Locals programming style::
345: * Locals implementation::
1.26 crook 346:
1.12 anton 347: Structures
348:
349: * Why explicit structure support?::
350: * Structure Usage::
351: * Structure Naming Convention::
352: * Structure Implementation::
353: * Structure Glossary::
354:
355: Object-oriented Forth
356:
1.48 anton 357: * Why object-oriented programming?::
358: * Object-Oriented Terminology::
359: * Objects::
360: * OOF::
361: * Mini-OOF::
1.23 crook 362: * Comparison with other object models::
1.12 anton 363:
1.24 anton 364: The @file{objects.fs} model
1.12 anton 365:
366: * Properties of the Objects model::
367: * Basic Objects Usage::
1.41 anton 368: * The Objects base class::
1.12 anton 369: * Creating objects::
370: * Object-Oriented Programming Style::
371: * Class Binding::
372: * Method conveniences::
373: * Classes and Scoping::
1.41 anton 374: * Dividing classes::
1.12 anton 375: * Object Interfaces::
376: * Objects Implementation::
377: * Objects Glossary::
378:
1.24 anton 379: The @file{oof.fs} model
1.12 anton 380:
1.67 anton 381: * Properties of the OOF model::
382: * Basic OOF Usage::
383: * The OOF base class::
384: * Class Declaration::
385: * Class Implementation::
1.12 anton 386:
1.24 anton 387: The @file{mini-oof.fs} model
1.23 crook 388:
1.48 anton 389: * Basic Mini-OOF Usage::
390: * Mini-OOF Example::
391: * Mini-OOF Implementation::
1.23 crook 392:
1.78 anton 393: Programming Tools
394:
395: * Examining::
396: * Forgetting words::
397: * Debugging:: Simple and quick.
398: * Assertions:: Making your programs self-checking.
399: * Singlestep Debugger:: Executing your program word by word.
400:
401: Assembler and Code Words
402:
403: * Code and ;code::
404: * Common Assembler:: Assembler Syntax
405: * Common Disassembler::
406: * 386 Assembler:: Deviations and special cases
407: * Alpha Assembler:: Deviations and special cases
408: * MIPS assembler:: Deviations and special cases
409: * Other assemblers:: How to write them
410:
1.12 anton 411: Tools
412:
413: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 414: * Stack depth changes:: Where does this stack item come from?
1.12 anton 415:
416: ANS conformance
417:
418: * The Core Words::
419: * The optional Block word set::
420: * The optional Double Number word set::
421: * The optional Exception word set::
422: * The optional Facility word set::
423: * The optional File-Access word set::
424: * The optional Floating-Point word set::
425: * The optional Locals word set::
426: * The optional Memory-Allocation word set::
427: * The optional Programming-Tools word set::
428: * The optional Search-Order word set::
429:
430: The Core Words
431:
432: * core-idef:: Implementation Defined Options
433: * core-ambcond:: Ambiguous Conditions
434: * core-other:: Other System Documentation
435:
436: The optional Block word set
437:
438: * block-idef:: Implementation Defined Options
439: * block-ambcond:: Ambiguous Conditions
440: * block-other:: Other System Documentation
441:
442: The optional Double Number word set
443:
444: * double-ambcond:: Ambiguous Conditions
445:
446: The optional Exception word set
447:
448: * exception-idef:: Implementation Defined Options
449:
450: The optional Facility word set
451:
452: * facility-idef:: Implementation Defined Options
453: * facility-ambcond:: Ambiguous Conditions
454:
455: The optional File-Access word set
456:
457: * file-idef:: Implementation Defined Options
458: * file-ambcond:: Ambiguous Conditions
459:
460: The optional Floating-Point word set
461:
462: * floating-idef:: Implementation Defined Options
463: * floating-ambcond:: Ambiguous Conditions
464:
465: The optional Locals word set
466:
467: * locals-idef:: Implementation Defined Options
468: * locals-ambcond:: Ambiguous Conditions
469:
470: The optional Memory-Allocation word set
471:
472: * memory-idef:: Implementation Defined Options
473:
474: The optional Programming-Tools word set
475:
476: * programming-idef:: Implementation Defined Options
477: * programming-ambcond:: Ambiguous Conditions
478:
479: The optional Search-Order word set
480:
481: * search-idef:: Implementation Defined Options
482: * search-ambcond:: Ambiguous Conditions
483:
1.109 anton 484: Emacs and Gforth
485:
486: * Installing gforth.el:: Making Emacs aware of Forth.
487: * Emacs Tags:: Viewing the source of a word in Emacs.
488: * Hilighting:: Making Forth code look prettier.
489: * Auto-Indentation:: Customizing auto-indentation.
490: * Blocks Files:: Reading and writing blocks files.
491:
1.12 anton 492: Image Files
493:
1.24 anton 494: * Image Licensing Issues:: Distribution terms for images.
495: * Image File Background:: Why have image files?
1.67 anton 496: * Non-Relocatable Image Files:: don't always work.
1.24 anton 497: * Data-Relocatable Image Files:: are better.
1.67 anton 498: * Fully Relocatable Image Files:: better yet.
1.24 anton 499: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 500: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 501: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 502:
503: Fully Relocatable Image Files
504:
1.27 crook 505: * gforthmi:: The normal way
1.12 anton 506: * cross.fs:: The hard way
507:
508: Engine
509:
510: * Portability::
511: * Threading::
512: * Primitives::
513: * Performance::
514:
515: Threading
516:
517: * Scheduling::
518: * Direct or Indirect Threaded?::
1.109 anton 519: * Dynamic Superinstructions::
1.12 anton 520: * DOES>::
521:
522: Primitives
523:
524: * Automatic Generation::
525: * TOS Optimization::
526: * Produced code::
1.13 pazsan 527:
528: Cross Compiler
529:
1.67 anton 530: * Using the Cross Compiler::
531: * How the Cross Compiler Works::
1.13 pazsan 532:
1.113 anton 533: Licenses
534:
535: * GNU Free Documentation License:: License for copying this manual.
536: * Copying:: GPL (for copying this software).
537:
1.24 anton 538: @end detailmenu
1.1 anton 539: @end menu
540:
1.113 anton 541: @c ----------------------------------------------------------
1.1 anton 542: @iftex
543: @unnumbered Preface
544: @cindex Preface
1.21 crook 545: This manual documents Gforth. Some introductory material is provided for
546: readers who are unfamiliar with Forth or who are migrating to Gforth
547: from other Forth compilers. However, this manual is primarily a
548: reference manual.
1.1 anton 549: @end iftex
550:
1.28 crook 551: @comment TODO much more blurb here.
1.26 crook 552:
553: @c ******************************************************************
1.113 anton 554: @node Goals, Gforth Environment, Top, Top
1.26 crook 555: @comment node-name, next, previous, up
556: @chapter Goals of Gforth
557: @cindex goals of the Gforth project
558: The goal of the Gforth Project is to develop a standard model for
559: ANS Forth. This can be split into several subgoals:
560:
561: @itemize @bullet
562: @item
563: Gforth should conform to the ANS Forth Standard.
564: @item
565: It should be a model, i.e. it should define all the
566: implementation-dependent things.
567: @item
568: It should become standard, i.e. widely accepted and used. This goal
569: is the most difficult one.
570: @end itemize
571:
572: To achieve these goals Gforth should be
573: @itemize @bullet
574: @item
575: Similar to previous models (fig-Forth, F83)
576: @item
577: Powerful. It should provide for all the things that are considered
578: necessary today and even some that are not yet considered necessary.
579: @item
580: Efficient. It should not get the reputation of being exceptionally
581: slow.
582: @item
583: Free.
584: @item
585: Available on many machines/easy to port.
586: @end itemize
587:
588: Have we achieved these goals? Gforth conforms to the ANS Forth
589: standard. It may be considered a model, but we have not yet documented
590: which parts of the model are stable and which parts we are likely to
591: change. It certainly has not yet become a de facto standard, but it
592: appears to be quite popular. It has some similarities to and some
593: differences from previous models. It has some powerful features, but not
594: yet everything that we envisioned. We certainly have achieved our
1.65 anton 595: execution speed goals (@pxref{Performance})@footnote{However, in 1998
596: the bar was raised when the major commercial Forth vendors switched to
597: native code compilers.}. It is free and available on many machines.
1.29 crook 598:
1.26 crook 599: @c ******************************************************************
1.48 anton 600: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 601: @chapter Gforth Environment
602: @cindex Gforth environment
1.21 crook 603:
1.45 crook 604: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 605: material in this chapter.
1.21 crook 606:
607: @menu
1.29 crook 608: * Invoking Gforth:: Getting in
609: * Leaving Gforth:: Getting out
610: * Command-line editing::
1.48 anton 611: * Environment variables:: that affect how Gforth starts up
1.29 crook 612: * Gforth Files:: What gets installed and where
1.112 anton 613: * Gforth in pipes::
1.48 anton 614: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 615: @end menu
616:
1.49 anton 617: For related information about the creation of images see @ref{Image Files}.
1.29 crook 618:
1.21 crook 619: @comment ----------------------------------------------
1.48 anton 620: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 621: @section Invoking Gforth
622: @cindex invoking Gforth
623: @cindex running Gforth
624: @cindex command-line options
625: @cindex options on the command line
626: @cindex flags on the command line
1.21 crook 627:
1.30 anton 628: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 629: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 630: will usually just say @code{gforth} -- this automatically loads the
631: default image file @file{gforth.fi}. In many other cases the default
632: Gforth image will be invoked like this:
1.21 crook 633: @example
1.30 anton 634: gforth [file | -e forth-code] ...
1.21 crook 635: @end example
1.29 crook 636: @noindent
637: This interprets the contents of the files and the Forth code in the order they
638: are given.
1.21 crook 639:
1.109 anton 640: In addition to the @command{gforth} engine, there is also an engine
641: called @command{gforth-fast}, which is faster, but gives less
642: informative error messages (@pxref{Error messages}) and may catch some
643: stack underflows later or not at all. You should use it for debugged,
644: performance-critical programs.
645:
646: Moreover, there is an engine called @command{gforth-itc}, which is
647: useful in some backwards-compatibility situations (@pxref{Direct or
648: Indirect Threaded?}).
1.30 anton 649:
1.29 crook 650: In general, the command line looks like this:
1.21 crook 651:
652: @example
1.30 anton 653: gforth[-fast] [engine options] [image options]
1.21 crook 654: @end example
655:
1.30 anton 656: The engine options must come before the rest of the command
1.29 crook 657: line. They are:
1.26 crook 658:
1.29 crook 659: @table @code
660: @cindex -i, command-line option
661: @cindex --image-file, command-line option
662: @item --image-file @i{file}
663: @itemx -i @i{file}
664: Loads the Forth image @i{file} instead of the default
665: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 666:
1.39 anton 667: @cindex --appl-image, command-line option
668: @item --appl-image @i{file}
669: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 670: to the image (instead of processing them as engine options). This is
671: useful for building executable application images on Unix, built with
1.39 anton 672: @code{gforthmi --application ...}.
673:
1.29 crook 674: @cindex --path, command-line option
675: @cindex -p, command-line option
676: @item --path @i{path}
677: @itemx -p @i{path}
678: Uses @i{path} for searching the image file and Forth source code files
679: instead of the default in the environment variable @code{GFORTHPATH} or
680: the path specified at installation time (e.g.,
681: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
682: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 683:
1.29 crook 684: @cindex --dictionary-size, command-line option
685: @cindex -m, command-line option
686: @cindex @i{size} parameters for command-line options
687: @cindex size of the dictionary and the stacks
688: @item --dictionary-size @i{size}
689: @itemx -m @i{size}
690: Allocate @i{size} space for the Forth dictionary space instead of
691: using the default specified in the image (typically 256K). The
692: @i{size} specification for this and subsequent options consists of
693: an integer and a unit (e.g.,
694: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
695: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
696: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
697: @code{e} is used.
1.21 crook 698:
1.29 crook 699: @cindex --data-stack-size, command-line option
700: @cindex -d, command-line option
701: @item --data-stack-size @i{size}
702: @itemx -d @i{size}
703: Allocate @i{size} space for the data stack instead of using the
704: default specified in the image (typically 16K).
1.21 crook 705:
1.29 crook 706: @cindex --return-stack-size, command-line option
707: @cindex -r, command-line option
708: @item --return-stack-size @i{size}
709: @itemx -r @i{size}
710: Allocate @i{size} space for the return stack instead of using the
711: default specified in the image (typically 15K).
1.21 crook 712:
1.29 crook 713: @cindex --fp-stack-size, command-line option
714: @cindex -f, command-line option
715: @item --fp-stack-size @i{size}
716: @itemx -f @i{size}
717: Allocate @i{size} space for the floating point stack instead of
718: using the default specified in the image (typically 15.5K). In this case
719: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 720:
1.48 anton 721: @cindex --locals-stack-size, command-line option
722: @cindex -l, command-line option
723: @item --locals-stack-size @i{size}
724: @itemx -l @i{size}
725: Allocate @i{size} space for the locals stack instead of using the
726: default specified in the image (typically 14.5K).
727:
728: @cindex -h, command-line option
729: @cindex --help, command-line option
730: @item --help
731: @itemx -h
732: Print a message about the command-line options
733:
734: @cindex -v, command-line option
735: @cindex --version, command-line option
736: @item --version
737: @itemx -v
738: Print version and exit
739:
740: @cindex --debug, command-line option
741: @item --debug
742: Print some information useful for debugging on startup.
743:
744: @cindex --offset-image, command-line option
745: @item --offset-image
746: Start the dictionary at a slightly different position than would be used
747: otherwise (useful for creating data-relocatable images,
748: @pxref{Data-Relocatable Image Files}).
749:
750: @cindex --no-offset-im, command-line option
751: @item --no-offset-im
752: Start the dictionary at the normal position.
753:
754: @cindex --clear-dictionary, command-line option
755: @item --clear-dictionary
756: Initialize all bytes in the dictionary to 0 before loading the image
757: (@pxref{Data-Relocatable Image Files}).
758:
759: @cindex --die-on-signal, command-line-option
760: @item --die-on-signal
761: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
762: or the segmentation violation SIGSEGV) by translating it into a Forth
763: @code{THROW}. With this option, Gforth exits if it receives such a
764: signal. This option is useful when the engine and/or the image might be
765: severely broken (such that it causes another signal before recovering
766: from the first); this option avoids endless loops in such cases.
1.109 anton 767:
1.119 anton 768: @cindex --no-dynamic, command-line option
769: @cindex --dynamic, command-line option
1.109 anton 770: @item --no-dynamic
771: @item --dynamic
772: Disable or enable dynamic superinstructions with replication
773: (@pxref{Dynamic Superinstructions}).
774:
1.119 anton 775: @cindex --no-super, command-line option
1.109 anton 776: @item --no-super
1.110 anton 777: Disable dynamic superinstructions, use just dynamic replication; this is
778: useful if you want to patch threaded code (@pxref{Dynamic
779: Superinstructions}).
1.119 anton 780:
781: @cindex --ss-number, command-line option
782: @item --ss-number=@var{N}
783: Use only the first @var{N} static superinstructions compiled into the
784: engine (default: use them all; note that only @code{gforth-fast} has
785: any). This option is useful for measuring the performance impact of
786: static superinstructions.
787:
788: @cindex --ss-min-..., command-line options
789: @item --ss-min-codesize
790: @item --ss-min-ls
791: @item --ss-min-lsu
792: @item --ss-min-nexts
793: Use specified metric for determining the cost of a primitive or static
794: superinstruction for static superinstruction selection. @code{Codesize}
795: is the native code size of the primive or static superinstruction,
796: @code{ls} is the number of loads and stores, @code{lsu} is the number of
797: loads, stores, and updates, and @code{nexts} is the number of dispatches
798: (not taking dynamic superinstructions into account), i.e. every
799: primitive or static superinstruction has cost 1. Default:
800: @code{codesize} if you use dynamic code generation, otherwise
801: @code{nexts}.
802:
803: @cindex --ss-greedy, command-line option
804: @item --ss-greedy
805: This option is useful for measuring the performance impact of static
806: superinstructions. By default, an optimal shortest-path algorithm is
807: used for selecting static superinstructions. With @option{--ss-greedy}
808: this algorithm is modified to assume that anything after the static
809: superinstruction currently under consideration is not combined into
810: static superinstructions. With @option{--ss-min-nexts} this produces
811: the same result as a greedy algorithm that always selects the longest
812: superinstruction available at the moment. E.g., if there are
813: superinstructions AB and BCD, then for the sequence A B C D the optimal
814: algorithm will select A BCD and the greedy algorithm will select AB C D.
815:
816: @cindex --print-metrics, command-line option
817: @item --print-metrics
818: Prints some metrics used during static superinstruction selection:
819: @code{code size} is the actual size of the dynamically generated code.
820: @code{Metric codesize} is the sum of the codesize metrics as seen by
821: static superinstruction selection; there is a difference from @code{code
822: size}, because not all primitives and static superinstructions are
823: compiled into dynamically generated code, and because of markers. The
824: other metrics correspond to the @option{ss-min-...} options. This
825: option is useful for evaluating the effects of the @option{--ss-...}
826: options.
1.109 anton 827:
1.48 anton 828: @end table
829:
830: @cindex loading files at startup
831: @cindex executing code on startup
832: @cindex batch processing with Gforth
833: As explained above, the image-specific command-line arguments for the
834: default image @file{gforth.fi} consist of a sequence of filenames and
835: @code{-e @var{forth-code}} options that are interpreted in the sequence
836: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 837: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
838: option takes only one argument; if you want to evaluate more Forth
839: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 840: after processing the command line (instead of entering interactive mode)
1.121 anton 841: append @code{-e bye} to the command line. You can also process the
842: command-line arguments with a Forth program (@pxref{OS command line
843: arguments}).
1.48 anton 844:
845: @cindex versions, invoking other versions of Gforth
846: If you have several versions of Gforth installed, @code{gforth} will
847: invoke the version that was installed last. @code{gforth-@i{version}}
848: invokes a specific version. If your environment contains the variable
849: @code{GFORTHPATH}, you may want to override it by using the
850: @code{--path} option.
851:
852: Not yet implemented:
853: On startup the system first executes the system initialization file
854: (unless the option @code{--no-init-file} is given; note that the system
855: resulting from using this option may not be ANS Forth conformant). Then
856: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 857: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 858: then in @file{~}, then in the normal path (see above).
859:
860:
861:
862: @comment ----------------------------------------------
863: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
864: @section Leaving Gforth
865: @cindex Gforth - leaving
866: @cindex leaving Gforth
867:
868: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
869: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
870: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 871: data are discarded. For ways of saving the state of the system before
872: leaving Gforth see @ref{Image Files}.
1.48 anton 873:
874: doc-bye
875:
876:
877: @comment ----------------------------------------------
1.65 anton 878: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 879: @section Command-line editing
880: @cindex command-line editing
881:
882: Gforth maintains a history file that records every line that you type to
883: the text interpreter. This file is preserved between sessions, and is
884: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
885: repeatedly you can recall successively older commands from this (or
886: previous) session(s). The full list of command-line editing facilities is:
887:
888: @itemize @bullet
889: @item
890: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
891: commands from the history buffer.
892: @item
893: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
894: from the history buffer.
895: @item
896: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
897: @item
898: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
899: @item
900: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
901: closing up the line.
902: @item
903: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
904: @item
905: @kbd{Ctrl-a} to move the cursor to the start of the line.
906: @item
907: @kbd{Ctrl-e} to move the cursor to the end of the line.
908: @item
909: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
910: line.
911: @item
912: @key{TAB} to step through all possible full-word completions of the word
913: currently being typed.
914: @item
1.65 anton 915: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
916: using @code{bye}).
917: @item
918: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
919: character under the cursor.
1.48 anton 920: @end itemize
921:
922: When editing, displayable characters are inserted to the left of the
923: cursor position; the line is always in ``insert'' (as opposed to
924: ``overstrike'') mode.
925:
926: @cindex history file
927: @cindex @file{.gforth-history}
928: On Unix systems, the history file is @file{~/.gforth-history} by
929: default@footnote{i.e. it is stored in the user's home directory.}. You
930: can find out the name and location of your history file using:
931:
932: @example
933: history-file type \ Unix-class systems
934:
935: history-file type \ Other systems
936: history-dir type
937: @end example
938:
939: If you enter long definitions by hand, you can use a text editor to
940: paste them out of the history file into a Forth source file for reuse at
941: a later time.
942:
943: Gforth never trims the size of the history file, so you should do this
944: periodically, if necessary.
945:
946: @comment this is all defined in history.fs
947: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
948: @comment chosen?
949:
950:
951: @comment ----------------------------------------------
1.65 anton 952: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 953: @section Environment variables
954: @cindex environment variables
955:
956: Gforth uses these environment variables:
957:
958: @itemize @bullet
959: @item
960: @cindex @code{GFORTHHIST} -- environment variable
961: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
962: open/create the history file, @file{.gforth-history}. Default:
963: @code{$HOME}.
964:
965: @item
966: @cindex @code{GFORTHPATH} -- environment variable
967: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
968: for Forth source-code files.
969:
970: @item
1.147 anton 971: @cindex @code{LANG} -- environment variable
972: @code{LANG} -- see @code{LC_CTYPE}
973:
974: @item
975: @cindex @code{LC_ALL} -- environment variable
976: @code{LC_ALL} -- see @code{LC_CTYPE}
977:
978: @item
979: @cindex @code{LC_CTYPE} -- environment variable
980: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
981: startup, Gforth uses the UTF-8 encoding for strings internally and
982: expects its input and produces its output in UTF-8 encoding, otherwise
983: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
984: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
985: that is unset, in @code{LANG}.
986:
987: @item
1.129 anton 988: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
989:
990: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
991: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 992: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 993: and the command are directly concatenated, so if a space between them is
994: necessary, append it to the prefix.
995:
996: @item
1.48 anton 997: @cindex @code{GFORTH} -- environment variable
1.49 anton 998: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 999:
1000: @item
1001: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1002: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1003:
1004: @item
1005: @cindex @code{TMP}, @code{TEMP} - environment variable
1006: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1007: location for the history file.
1008: @end itemize
1009:
1010: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1011: @comment mentioning these.
1012:
1013: All the Gforth environment variables default to sensible values if they
1014: are not set.
1015:
1016:
1017: @comment ----------------------------------------------
1.112 anton 1018: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1019: @section Gforth files
1020: @cindex Gforth files
1021:
1022: When you install Gforth on a Unix system, it installs files in these
1023: locations by default:
1024:
1025: @itemize @bullet
1026: @item
1027: @file{/usr/local/bin/gforth}
1028: @item
1029: @file{/usr/local/bin/gforthmi}
1030: @item
1031: @file{/usr/local/man/man1/gforth.1} - man page.
1032: @item
1033: @file{/usr/local/info} - the Info version of this manual.
1034: @item
1035: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1036: @item
1037: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1038: @item
1039: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1040: @item
1041: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1042: @end itemize
1043:
1044: You can select different places for installation by using
1045: @code{configure} options (listed with @code{configure --help}).
1046:
1047: @comment ----------------------------------------------
1.112 anton 1048: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1049: @section Gforth in pipes
1050: @cindex pipes, Gforth as part of
1051:
1052: Gforth can be used in pipes created elsewhere (described here). It can
1053: also create pipes on its own (@pxref{Pipes}).
1054:
1055: @cindex input from pipes
1056: If you pipe into Gforth, your program should read with @code{read-file}
1057: or @code{read-line} from @code{stdin} (@pxref{General files}).
1058: @code{Key} does not recognize the end of input. Words like
1059: @code{accept} echo the input and are therefore usually not useful for
1060: reading from a pipe. You have to invoke the Forth program with an OS
1061: command-line option, as you have no chance to use the Forth command line
1062: (the text interpreter would try to interpret the pipe input).
1063:
1064: @cindex output in pipes
1065: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1066:
1067: @cindex silent exiting from Gforth
1068: When you write to a pipe that has been closed at the other end, Gforth
1069: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1070: into the exception @code{broken-pipe-error}. If your application does
1071: not catch that exception, the system catches it and exits, usually
1072: silently (unless you were working on the Forth command line; then it
1073: prints an error message and exits). This is usually the desired
1074: behaviour.
1075:
1076: If you do not like this behaviour, you have to catch the exception
1077: yourself, and react to it.
1078:
1079: Here's an example of an invocation of Gforth that is usable in a pipe:
1080:
1081: @example
1082: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1083: type repeat ; foo bye"
1084: @end example
1085:
1086: This example just copies the input verbatim to the output. A very
1087: simple pipe containing this example looks like this:
1088:
1089: @example
1090: cat startup.fs |
1091: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1092: type repeat ; foo bye"|
1093: head
1094: @end example
1095:
1096: @cindex stderr and pipes
1097: Pipes involving Gforth's @code{stderr} output do not work.
1098:
1099: @comment ----------------------------------------------
1100: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1101: @section Startup speed
1102: @cindex Startup speed
1103: @cindex speed, startup
1104:
1105: If Gforth is used for CGI scripts or in shell scripts, its startup
1106: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1107: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1108: system time.
1109:
1110: If startup speed is a problem, you may consider the following ways to
1111: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1112: (for example, by using Fast-CGI).
1.48 anton 1113:
1.112 anton 1114: An easy step that influences Gforth startup speed is the use of the
1115: @option{--no-dynamic} option; this decreases image loading speed, but
1116: increases compile-time and run-time.
1117:
1118: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1119: building it with @code{XLDFLAGS=-static}. This requires more memory for
1120: the code and will therefore slow down the first invocation, but
1121: subsequent invocations avoid the dynamic linking overhead. Another
1122: disadvantage is that Gforth won't profit from library upgrades. As a
1123: result, @code{gforth-static -e bye} takes about 17.1ms user and
1124: 8.2ms system time.
1125:
1126: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1127: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1128: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1129: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1130: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1131: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1132: address for the dictionary, for whatever reason; so you better provide a
1133: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1134: bye} takes about 15.3ms user and 7.5ms system time.
1135:
1136: The final step is to disable dictionary hashing in Gforth. Gforth
1137: builds the hash table on startup, which takes much of the startup
1138: overhead. You can do this by commenting out the @code{include hash.fs}
1139: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1140: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1141: The disadvantages are that functionality like @code{table} and
1142: @code{ekey} is missing and that text interpretation (e.g., compiling)
1143: now takes much longer. So, you should only use this method if there is
1144: no significant text interpretation to perform (the script should be
1.62 crook 1145: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1146: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1147:
1148: @c ******************************************************************
1149: @node Tutorial, Introduction, Gforth Environment, Top
1150: @chapter Forth Tutorial
1151: @cindex Tutorial
1152: @cindex Forth Tutorial
1153:
1.67 anton 1154: @c Topics from nac's Introduction that could be mentioned:
1155: @c press <ret> after each line
1156: @c Prompt
1157: @c numbers vs. words in dictionary on text interpretation
1158: @c what happens on redefinition
1159: @c parsing words (in particular, defining words)
1160:
1.83 anton 1161: The difference of this chapter from the Introduction
1162: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1163: be used while sitting in front of a computer, and covers much more
1164: material, but does not explain how the Forth system works.
1165:
1.62 crook 1166: This tutorial can be used with any ANS-compliant Forth; any
1167: Gforth-specific features are marked as such and you can skip them if you
1168: work with another Forth. This tutorial does not explain all features of
1169: Forth, just enough to get you started and give you some ideas about the
1170: facilities available in Forth. Read the rest of the manual and the
1171: standard when you are through this.
1.48 anton 1172:
1173: The intended way to use this tutorial is that you work through it while
1174: sitting in front of the console, take a look at the examples and predict
1175: what they will do, then try them out; if the outcome is not as expected,
1176: find out why (e.g., by trying out variations of the example), so you
1177: understand what's going on. There are also some assignments that you
1178: should solve.
1179:
1180: This tutorial assumes that you have programmed before and know what,
1181: e.g., a loop is.
1182:
1183: @c !! explain compat library
1184:
1185: @menu
1186: * Starting Gforth Tutorial::
1187: * Syntax Tutorial::
1188: * Crash Course Tutorial::
1189: * Stack Tutorial::
1190: * Arithmetics Tutorial::
1191: * Stack Manipulation Tutorial::
1192: * Using files for Forth code Tutorial::
1193: * Comments Tutorial::
1194: * Colon Definitions Tutorial::
1195: * Decompilation Tutorial::
1196: * Stack-Effect Comments Tutorial::
1197: * Types Tutorial::
1198: * Factoring Tutorial::
1199: * Designing the stack effect Tutorial::
1200: * Local Variables Tutorial::
1201: * Conditional execution Tutorial::
1202: * Flags and Comparisons Tutorial::
1203: * General Loops Tutorial::
1204: * Counted loops Tutorial::
1205: * Recursion Tutorial::
1206: * Leaving definitions or loops Tutorial::
1207: * Return Stack Tutorial::
1208: * Memory Tutorial::
1209: * Characters and Strings Tutorial::
1210: * Alignment Tutorial::
1.87 anton 1211: * Files Tutorial::
1.48 anton 1212: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1213: * Execution Tokens Tutorial::
1214: * Exceptions Tutorial::
1215: * Defining Words Tutorial::
1216: * Arrays and Records Tutorial::
1217: * POSTPONE Tutorial::
1218: * Literal Tutorial::
1219: * Advanced macros Tutorial::
1220: * Compilation Tokens Tutorial::
1221: * Wordlists and Search Order Tutorial::
1222: @end menu
1223:
1224: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1225: @section Starting Gforth
1.66 anton 1226: @cindex starting Gforth tutorial
1.48 anton 1227: You can start Gforth by typing its name:
1228:
1229: @example
1230: gforth
1231: @end example
1232:
1233: That puts you into interactive mode; you can leave Gforth by typing
1234: @code{bye}. While in Gforth, you can edit the command line and access
1235: the command line history with cursor keys, similar to bash.
1236:
1237:
1238: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1239: @section Syntax
1.66 anton 1240: @cindex syntax tutorial
1.48 anton 1241:
1242: A @dfn{word} is a sequence of arbitrary characters (expcept white
1243: space). Words are separated by white space. E.g., each of the
1244: following lines contains exactly one word:
1245:
1246: @example
1247: word
1248: !@@#$%^&*()
1249: 1234567890
1250: 5!a
1251: @end example
1252:
1253: A frequent beginner's error is to leave away necessary white space,
1254: resulting in an error like @samp{Undefined word}; so if you see such an
1255: error, check if you have put spaces wherever necessary.
1256:
1257: @example
1258: ." hello, world" \ correct
1259: ."hello, world" \ gives an "Undefined word" error
1260: @end example
1261:
1.65 anton 1262: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1263: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1264: your system is case-sensitive, you may have to type all the examples
1265: given here in upper case.
1266:
1267:
1268: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1269: @section Crash Course
1270:
1271: Type
1272:
1273: @example
1274: 0 0 !
1275: here execute
1276: ' catch >body 20 erase abort
1277: ' (quit) >body 20 erase
1278: @end example
1279:
1280: The last two examples are guaranteed to destroy parts of Gforth (and
1281: most other systems), so you better leave Gforth afterwards (if it has
1282: not finished by itself). On some systems you may have to kill gforth
1283: from outside (e.g., in Unix with @code{kill}).
1284:
1285: Now that you know how to produce crashes (and that there's not much to
1286: them), let's learn how to produce meaningful programs.
1287:
1288:
1289: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1290: @section Stack
1.66 anton 1291: @cindex stack tutorial
1.48 anton 1292:
1293: The most obvious feature of Forth is the stack. When you type in a
1294: number, it is pushed on the stack. You can display the content of the
1295: stack with @code{.s}.
1296:
1297: @example
1298: 1 2 .s
1299: 3 .s
1300: @end example
1301:
1302: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1303: appear in @code{.s} output as they appeared in the input.
1304:
1305: You can print the top of stack element with @code{.}.
1306:
1307: @example
1308: 1 2 3 . . .
1309: @end example
1310:
1311: In general, words consume their stack arguments (@code{.s} is an
1312: exception).
1313:
1.141 anton 1314: @quotation Assignment
1.48 anton 1315: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1316: @end quotation
1.48 anton 1317:
1318:
1319: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1320: @section Arithmetics
1.66 anton 1321: @cindex arithmetics tutorial
1.48 anton 1322:
1323: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1324: operate on the top two stack items:
1325:
1326: @example
1.67 anton 1327: 2 2 .s
1328: + .s
1329: .
1.48 anton 1330: 2 1 - .
1331: 7 3 mod .
1332: @end example
1333:
1334: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1335: as in the corresponding infix expression (this is generally the case in
1336: Forth).
1337:
1338: Parentheses are superfluous (and not available), because the order of
1339: the words unambiguously determines the order of evaluation and the
1340: operands:
1341:
1342: @example
1343: 3 4 + 5 * .
1344: 3 4 5 * + .
1345: @end example
1346:
1.141 anton 1347: @quotation Assignment
1.48 anton 1348: What are the infix expressions corresponding to the Forth code above?
1349: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1350: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1351: @end quotation
1.48 anton 1352:
1353: To change the sign, use @code{negate}:
1354:
1355: @example
1356: 2 negate .
1357: @end example
1358:
1.141 anton 1359: @quotation Assignment
1.48 anton 1360: Convert -(-3)*4-5 to Forth.
1.141 anton 1361: @end quotation
1.48 anton 1362:
1363: @code{/mod} performs both @code{/} and @code{mod}.
1364:
1365: @example
1366: 7 3 /mod . .
1367: @end example
1368:
1.66 anton 1369: Reference: @ref{Arithmetic}.
1370:
1371:
1.48 anton 1372: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1373: @section Stack Manipulation
1.66 anton 1374: @cindex stack manipulation tutorial
1.48 anton 1375:
1376: Stack manipulation words rearrange the data on the stack.
1377:
1378: @example
1379: 1 .s drop .s
1380: 1 .s dup .s drop drop .s
1381: 1 2 .s over .s drop drop drop
1382: 1 2 .s swap .s drop drop
1383: 1 2 3 .s rot .s drop drop drop
1384: @end example
1385:
1386: These are the most important stack manipulation words. There are also
1387: variants that manipulate twice as many stack items:
1388:
1389: @example
1390: 1 2 3 4 .s 2swap .s 2drop 2drop
1391: @end example
1392:
1393: Two more stack manipulation words are:
1394:
1395: @example
1396: 1 2 .s nip .s drop
1397: 1 2 .s tuck .s 2drop drop
1398: @end example
1399:
1.141 anton 1400: @quotation Assignment
1.48 anton 1401: Replace @code{nip} and @code{tuck} with combinations of other stack
1402: manipulation words.
1403:
1404: @example
1405: Given: How do you get:
1406: 1 2 3 3 2 1
1407: 1 2 3 1 2 3 2
1408: 1 2 3 1 2 3 3
1409: 1 2 3 1 3 3
1410: 1 2 3 2 1 3
1411: 1 2 3 4 4 3 2 1
1412: 1 2 3 1 2 3 1 2 3
1413: 1 2 3 4 1 2 3 4 1 2
1414: 1 2 3
1415: 1 2 3 1 2 3 4
1416: 1 2 3 1 3
1417: @end example
1.141 anton 1418: @end quotation
1.48 anton 1419:
1420: @example
1421: 5 dup * .
1422: @end example
1423:
1.141 anton 1424: @quotation Assignment
1.48 anton 1425: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1426: Write a piece of Forth code that expects two numbers on the stack
1427: (@var{a} and @var{b}, with @var{b} on top) and computes
1428: @code{(a-b)(a+1)}.
1.141 anton 1429: @end quotation
1.48 anton 1430:
1.66 anton 1431: Reference: @ref{Stack Manipulation}.
1432:
1433:
1.48 anton 1434: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1435: @section Using files for Forth code
1.66 anton 1436: @cindex loading Forth code, tutorial
1437: @cindex files containing Forth code, tutorial
1.48 anton 1438:
1439: While working at the Forth command line is convenient for one-line
1440: examples and short one-off code, you probably want to store your source
1441: code in files for convenient editing and persistence. You can use your
1442: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1443: Gforth}) to create @var{file.fs} and use
1.48 anton 1444:
1445: @example
1.102 anton 1446: s" @var{file.fs}" included
1.48 anton 1447: @end example
1448:
1449: to load it into your Forth system. The file name extension I use for
1450: Forth files is @samp{.fs}.
1451:
1452: You can easily start Gforth with some files loaded like this:
1453:
1454: @example
1.102 anton 1455: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1456: @end example
1457:
1458: If an error occurs during loading these files, Gforth terminates,
1459: whereas an error during @code{INCLUDED} within Gforth usually gives you
1460: a Gforth command line. Starting the Forth system every time gives you a
1461: clean start every time, without interference from the results of earlier
1462: tries.
1463:
1464: I often put all the tests in a file, then load the code and run the
1465: tests with
1466:
1467: @example
1.102 anton 1468: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1469: @end example
1470:
1471: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1472: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1473: restart this command without ado.
1474:
1475: The advantage of this approach is that the tests can be repeated easily
1476: every time the program ist changed, making it easy to catch bugs
1477: introduced by the change.
1478:
1.66 anton 1479: Reference: @ref{Forth source files}.
1480:
1.48 anton 1481:
1482: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1483: @section Comments
1.66 anton 1484: @cindex comments tutorial
1.48 anton 1485:
1486: @example
1487: \ That's a comment; it ends at the end of the line
1488: ( Another comment; it ends here: ) .s
1489: @end example
1490:
1491: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1492: separated with white space from the following text.
1493:
1494: @example
1495: \This gives an "Undefined word" error
1496: @end example
1497:
1498: The first @code{)} ends a comment started with @code{(}, so you cannot
1499: nest @code{(}-comments; and you cannot comment out text containing a
1500: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1501: avoid @code{)} in word names.}.
1502:
1503: I use @code{\}-comments for descriptive text and for commenting out code
1504: of one or more line; I use @code{(}-comments for describing the stack
1505: effect, the stack contents, or for commenting out sub-line pieces of
1506: code.
1507:
1508: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1509: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1510: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1511: with @kbd{M-q}.
1512:
1.66 anton 1513: Reference: @ref{Comments}.
1514:
1.48 anton 1515:
1516: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1517: @section Colon Definitions
1.66 anton 1518: @cindex colon definitions, tutorial
1519: @cindex definitions, tutorial
1520: @cindex procedures, tutorial
1521: @cindex functions, tutorial
1.48 anton 1522:
1523: are similar to procedures and functions in other programming languages.
1524:
1525: @example
1526: : squared ( n -- n^2 )
1527: dup * ;
1528: 5 squared .
1529: 7 squared .
1530: @end example
1531:
1532: @code{:} starts the colon definition; its name is @code{squared}. The
1533: following comment describes its stack effect. The words @code{dup *}
1534: are not executed, but compiled into the definition. @code{;} ends the
1535: colon definition.
1536:
1537: The newly-defined word can be used like any other word, including using
1538: it in other definitions:
1539:
1540: @example
1541: : cubed ( n -- n^3 )
1542: dup squared * ;
1543: -5 cubed .
1544: : fourth-power ( n -- n^4 )
1545: squared squared ;
1546: 3 fourth-power .
1547: @end example
1548:
1.141 anton 1549: @quotation Assignment
1.48 anton 1550: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1551: @code{/mod} in terms of other Forth words, and check if they work (hint:
1552: test your tests on the originals first). Don't let the
1553: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1554: @end quotation
1.48 anton 1555:
1.66 anton 1556: Reference: @ref{Colon Definitions}.
1557:
1.48 anton 1558:
1559: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1560: @section Decompilation
1.66 anton 1561: @cindex decompilation tutorial
1562: @cindex see tutorial
1.48 anton 1563:
1564: You can decompile colon definitions with @code{see}:
1565:
1566: @example
1567: see squared
1568: see cubed
1569: @end example
1570:
1571: In Gforth @code{see} shows you a reconstruction of the source code from
1572: the executable code. Informations that were present in the source, but
1573: not in the executable code, are lost (e.g., comments).
1574:
1.65 anton 1575: You can also decompile the predefined words:
1576:
1577: @example
1578: see .
1579: see +
1580: @end example
1581:
1582:
1.48 anton 1583: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1584: @section Stack-Effect Comments
1.66 anton 1585: @cindex stack-effect comments, tutorial
1586: @cindex --, tutorial
1.48 anton 1587: By convention the comment after the name of a definition describes the
1588: stack effect: The part in from of the @samp{--} describes the state of
1589: the stack before the execution of the definition, i.e., the parameters
1590: that are passed into the colon definition; the part behind the @samp{--}
1591: is the state of the stack after the execution of the definition, i.e.,
1592: the results of the definition. The stack comment only shows the top
1593: stack items that the definition accesses and/or changes.
1594:
1595: You should put a correct stack effect on every definition, even if it is
1596: just @code{( -- )}. You should also add some descriptive comment to
1597: more complicated words (I usually do this in the lines following
1598: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1599: you have to work through every definition before you can understand
1.48 anton 1600: any).
1601:
1.141 anton 1602: @quotation Assignment
1.48 anton 1603: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1604: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1605: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1606: are done, you can compare your stack effects to those in this manual
1.48 anton 1607: (@pxref{Word Index}).
1.141 anton 1608: @end quotation
1.48 anton 1609:
1610: Sometimes programmers put comments at various places in colon
1611: definitions that describe the contents of the stack at that place (stack
1612: comments); i.e., they are like the first part of a stack-effect
1613: comment. E.g.,
1614:
1615: @example
1616: : cubed ( n -- n^3 )
1617: dup squared ( n n^2 ) * ;
1618: @end example
1619:
1620: In this case the stack comment is pretty superfluous, because the word
1621: is simple enough. If you think it would be a good idea to add such a
1622: comment to increase readability, you should also consider factoring the
1623: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1624: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1625: however, if you decide not to refactor it, then having such a comment is
1626: better than not having it.
1627:
1628: The names of the stack items in stack-effect and stack comments in the
1629: standard, in this manual, and in many programs specify the type through
1630: a type prefix, similar to Fortran and Hungarian notation. The most
1631: frequent prefixes are:
1632:
1633: @table @code
1634: @item n
1635: signed integer
1636: @item u
1637: unsigned integer
1638: @item c
1639: character
1640: @item f
1641: Boolean flags, i.e. @code{false} or @code{true}.
1642: @item a-addr,a-
1643: Cell-aligned address
1644: @item c-addr,c-
1645: Char-aligned address (note that a Char may have two bytes in Windows NT)
1646: @item xt
1647: Execution token, same size as Cell
1648: @item w,x
1649: Cell, can contain an integer or an address. It usually takes 32, 64 or
1650: 16 bits (depending on your platform and Forth system). A cell is more
1651: commonly known as machine word, but the term @emph{word} already means
1652: something different in Forth.
1653: @item d
1654: signed double-cell integer
1655: @item ud
1656: unsigned double-cell integer
1657: @item r
1658: Float (on the FP stack)
1659: @end table
1660:
1661: You can find a more complete list in @ref{Notation}.
1662:
1.141 anton 1663: @quotation Assignment
1.48 anton 1664: Write stack-effect comments for all definitions you have written up to
1665: now.
1.141 anton 1666: @end quotation
1.48 anton 1667:
1668:
1669: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1670: @section Types
1.66 anton 1671: @cindex types tutorial
1.48 anton 1672:
1673: In Forth the names of the operations are not overloaded; so similar
1674: operations on different types need different names; e.g., @code{+} adds
1675: integers, and you have to use @code{f+} to add floating-point numbers.
1676: The following prefixes are often used for related operations on
1677: different types:
1678:
1679: @table @code
1680: @item (none)
1681: signed integer
1682: @item u
1683: unsigned integer
1684: @item c
1685: character
1686: @item d
1687: signed double-cell integer
1688: @item ud, du
1689: unsigned double-cell integer
1690: @item 2
1691: two cells (not-necessarily double-cell numbers)
1692: @item m, um
1693: mixed single-cell and double-cell operations
1694: @item f
1695: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1696: and @samp{r} represents FP numbers).
1.48 anton 1697: @end table
1698:
1699: If there are no differences between the signed and the unsigned variant
1700: (e.g., for @code{+}), there is only the prefix-less variant.
1701:
1702: Forth does not perform type checking, neither at compile time, nor at
1703: run time. If you use the wrong oeration, the data are interpreted
1704: incorrectly:
1705:
1706: @example
1707: -1 u.
1708: @end example
1709:
1710: If you have only experience with type-checked languages until now, and
1711: have heard how important type-checking is, don't panic! In my
1712: experience (and that of other Forthers), type errors in Forth code are
1713: usually easy to find (once you get used to it), the increased vigilance
1714: of the programmer tends to catch some harder errors in addition to most
1715: type errors, and you never have to work around the type system, so in
1716: most situations the lack of type-checking seems to be a win (projects to
1717: add type checking to Forth have not caught on).
1718:
1719:
1720: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1721: @section Factoring
1.66 anton 1722: @cindex factoring tutorial
1.48 anton 1723:
1724: If you try to write longer definitions, you will soon find it hard to
1725: keep track of the stack contents. Therefore, good Forth programmers
1726: tend to write only short definitions (e.g., three lines). The art of
1727: finding meaningful short definitions is known as factoring (as in
1728: factoring polynomials).
1729:
1730: Well-factored programs offer additional advantages: smaller, more
1731: general words, are easier to test and debug and can be reused more and
1732: better than larger, specialized words.
1733:
1734: So, if you run into difficulties with stack management, when writing
1735: code, try to define meaningful factors for the word, and define the word
1736: in terms of those. Even if a factor contains only two words, it is
1737: often helpful.
1738:
1.65 anton 1739: Good factoring is not easy, and it takes some practice to get the knack
1740: for it; but even experienced Forth programmers often don't find the
1741: right solution right away, but only when rewriting the program. So, if
1742: you don't come up with a good solution immediately, keep trying, don't
1743: despair.
1.48 anton 1744:
1745: @c example !!
1746:
1747:
1748: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1749: @section Designing the stack effect
1.66 anton 1750: @cindex Stack effect design, tutorial
1751: @cindex design of stack effects, tutorial
1.48 anton 1752:
1753: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1754: function; and since there is only one result, you don't have to deal with
1.48 anton 1755: the order of results, either.
1756:
1.117 anton 1757: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1758: parameter and result order of a definition is important and should be
1759: designed well. The general guideline is to design the stack effect such
1760: that the word is simple to use in most cases, even if that complicates
1761: the implementation of the word. Some concrete rules are:
1762:
1763: @itemize @bullet
1764:
1765: @item
1766: Words consume all of their parameters (e.g., @code{.}).
1767:
1768: @item
1769: If there is a convention on the order of parameters (e.g., from
1770: mathematics or another programming language), stick with it (e.g.,
1771: @code{-}).
1772:
1773: @item
1774: If one parameter usually requires only a short computation (e.g., it is
1775: a constant), pass it on the top of the stack. Conversely, parameters
1776: that usually require a long sequence of code to compute should be passed
1777: as the bottom (i.e., first) parameter. This makes the code easier to
1778: read, because reader does not need to keep track of the bottom item
1779: through a long sequence of code (or, alternatively, through stack
1.49 anton 1780: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1781: address on top of the stack because it is usually simpler to compute
1782: than the stored value (often the address is just a variable).
1783:
1784: @item
1785: Similarly, results that are usually consumed quickly should be returned
1786: on the top of stack, whereas a result that is often used in long
1787: computations should be passed as bottom result. E.g., the file words
1788: like @code{open-file} return the error code on the top of stack, because
1789: it is usually consumed quickly by @code{throw}; moreover, the error code
1790: has to be checked before doing anything with the other results.
1791:
1792: @end itemize
1793:
1794: These rules are just general guidelines, don't lose sight of the overall
1795: goal to make the words easy to use. E.g., if the convention rule
1796: conflicts with the computation-length rule, you might decide in favour
1797: of the convention if the word will be used rarely, and in favour of the
1798: computation-length rule if the word will be used frequently (because
1799: with frequent use the cost of breaking the computation-length rule would
1800: be quite high, and frequent use makes it easier to remember an
1801: unconventional order).
1802:
1803: @c example !! structure package
1804:
1.65 anton 1805:
1.48 anton 1806: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1807: @section Local Variables
1.66 anton 1808: @cindex local variables, tutorial
1.48 anton 1809:
1810: You can define local variables (@emph{locals}) in a colon definition:
1811:
1812: @example
1813: : swap @{ a b -- b a @}
1814: b a ;
1815: 1 2 swap .s 2drop
1816: @end example
1817:
1818: (If your Forth system does not support this syntax, include
1819: @file{compat/anslocals.fs} first).
1820:
1821: In this example @code{@{ a b -- b a @}} is the locals definition; it
1822: takes two cells from the stack, puts the top of stack in @code{b} and
1823: the next stack element in @code{a}. @code{--} starts a comment ending
1824: with @code{@}}. After the locals definition, using the name of the
1825: local will push its value on the stack. You can leave the comment
1826: part (@code{-- b a}) away:
1827:
1828: @example
1829: : swap ( x1 x2 -- x2 x1 )
1830: @{ a b @} b a ;
1831: @end example
1832:
1833: In Gforth you can have several locals definitions, anywhere in a colon
1834: definition; in contrast, in a standard program you can have only one
1835: locals definition per colon definition, and that locals definition must
1836: be outside any controll structure.
1837:
1838: With locals you can write slightly longer definitions without running
1839: into stack trouble. However, I recommend trying to write colon
1840: definitions without locals for exercise purposes to help you gain the
1841: essential factoring skills.
1842:
1.141 anton 1843: @quotation Assignment
1.48 anton 1844: Rewrite your definitions until now with locals
1.141 anton 1845: @end quotation
1.48 anton 1846:
1.66 anton 1847: Reference: @ref{Locals}.
1848:
1.48 anton 1849:
1850: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1851: @section Conditional execution
1.66 anton 1852: @cindex conditionals, tutorial
1853: @cindex if, tutorial
1.48 anton 1854:
1855: In Forth you can use control structures only inside colon definitions.
1856: An @code{if}-structure looks like this:
1857:
1858: @example
1859: : abs ( n1 -- +n2 )
1860: dup 0 < if
1861: negate
1862: endif ;
1863: 5 abs .
1864: -5 abs .
1865: @end example
1866:
1867: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1868: the following code is performed, otherwise execution continues after the
1.51 pazsan 1869: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1870: elements and prioduces a flag:
1871:
1872: @example
1873: 1 2 < .
1874: 2 1 < .
1875: 1 1 < .
1876: @end example
1877:
1878: Actually the standard name for @code{endif} is @code{then}. This
1879: tutorial presents the examples using @code{endif}, because this is often
1880: less confusing for people familiar with other programming languages
1881: where @code{then} has a different meaning. If your system does not have
1882: @code{endif}, define it with
1883:
1884: @example
1885: : endif postpone then ; immediate
1886: @end example
1887:
1888: You can optionally use an @code{else}-part:
1889:
1890: @example
1891: : min ( n1 n2 -- n )
1892: 2dup < if
1893: drop
1894: else
1895: nip
1896: endif ;
1897: 2 3 min .
1898: 3 2 min .
1899: @end example
1900:
1.141 anton 1901: @quotation Assignment
1.48 anton 1902: Write @code{min} without @code{else}-part (hint: what's the definition
1903: of @code{nip}?).
1.141 anton 1904: @end quotation
1.48 anton 1905:
1.66 anton 1906: Reference: @ref{Selection}.
1907:
1.48 anton 1908:
1909: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1910: @section Flags and Comparisons
1.66 anton 1911: @cindex flags tutorial
1912: @cindex comparison tutorial
1.48 anton 1913:
1914: In a false-flag all bits are clear (0 when interpreted as integer). In
1915: a canonical true-flag all bits are set (-1 as a twos-complement signed
1916: integer); in many contexts (e.g., @code{if}) any non-zero value is
1917: treated as true flag.
1918:
1919: @example
1920: false .
1921: true .
1922: true hex u. decimal
1923: @end example
1924:
1925: Comparison words produce canonical flags:
1926:
1927: @example
1928: 1 1 = .
1929: 1 0= .
1930: 0 1 < .
1931: 0 0 < .
1932: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1933: -1 1 < .
1934: @end example
1935:
1.66 anton 1936: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1937: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1938: these combinations are standard (for details see the standard,
1939: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1940:
1941: You can use @code{and or xor invert} can be used as operations on
1942: canonical flags. Actually they are bitwise operations:
1943:
1944: @example
1945: 1 2 and .
1946: 1 2 or .
1947: 1 3 xor .
1948: 1 invert .
1949: @end example
1950:
1951: You can convert a zero/non-zero flag into a canonical flag with
1952: @code{0<>} (and complement it on the way with @code{0=}).
1953:
1954: @example
1955: 1 0= .
1956: 1 0<> .
1957: @end example
1958:
1.65 anton 1959: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1960: operation of the Boolean operations to avoid @code{if}s:
1961:
1962: @example
1963: : foo ( n1 -- n2 )
1964: 0= if
1965: 14
1966: else
1967: 0
1968: endif ;
1969: 0 foo .
1970: 1 foo .
1971:
1972: : foo ( n1 -- n2 )
1973: 0= 14 and ;
1974: 0 foo .
1975: 1 foo .
1976: @end example
1977:
1.141 anton 1978: @quotation Assignment
1.48 anton 1979: Write @code{min} without @code{if}.
1.141 anton 1980: @end quotation
1.48 anton 1981:
1.66 anton 1982: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1983: @ref{Bitwise operations}.
1984:
1.48 anton 1985:
1986: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1987: @section General Loops
1.66 anton 1988: @cindex loops, indefinite, tutorial
1.48 anton 1989:
1990: The endless loop is the most simple one:
1991:
1992: @example
1993: : endless ( -- )
1994: 0 begin
1995: dup . 1+
1996: again ;
1997: endless
1998: @end example
1999:
2000: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2001: does nothing at run-time, @code{again} jumps back to @code{begin}.
2002:
2003: A loop with one exit at any place looks like this:
2004:
2005: @example
2006: : log2 ( +n1 -- n2 )
2007: \ logarithmus dualis of n1>0, rounded down to the next integer
2008: assert( dup 0> )
2009: 2/ 0 begin
2010: over 0> while
2011: 1+ swap 2/ swap
2012: repeat
2013: nip ;
2014: 7 log2 .
2015: 8 log2 .
2016: @end example
2017:
2018: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2019: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2020: continues behind the @code{while}. @code{Repeat} jumps back to
2021: @code{begin}, just like @code{again}.
2022:
2023: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2024: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2025: one bit (arithmetic shift right):
2026:
2027: @example
2028: -5 2 / .
2029: -5 2/ .
2030: @end example
2031:
2032: @code{assert(} is no standard word, but you can get it on systems other
2033: then Gforth by including @file{compat/assert.fs}. You can see what it
2034: does by trying
2035:
2036: @example
2037: 0 log2 .
2038: @end example
2039:
2040: Here's a loop with an exit at the end:
2041:
2042: @example
2043: : log2 ( +n1 -- n2 )
2044: \ logarithmus dualis of n1>0, rounded down to the next integer
2045: assert( dup 0 > )
2046: -1 begin
2047: 1+ swap 2/ swap
2048: over 0 <=
2049: until
2050: nip ;
2051: @end example
2052:
2053: @code{Until} consumes a flag; if it is non-zero, execution continues at
2054: the @code{begin}, otherwise after the @code{until}.
2055:
1.141 anton 2056: @quotation Assignment
1.48 anton 2057: Write a definition for computing the greatest common divisor.
1.141 anton 2058: @end quotation
1.48 anton 2059:
1.66 anton 2060: Reference: @ref{Simple Loops}.
2061:
1.48 anton 2062:
2063: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2064: @section Counted loops
1.66 anton 2065: @cindex loops, counted, tutorial
1.48 anton 2066:
2067: @example
2068: : ^ ( n1 u -- n )
2069: \ n = the uth power of u1
2070: 1 swap 0 u+do
2071: over *
2072: loop
2073: nip ;
2074: 3 2 ^ .
2075: 4 3 ^ .
2076: @end example
2077:
2078: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2079: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2080: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2081: times (or not at all, if @code{u3-u4<0}).
2082:
2083: You can see the stack effect design rules at work in the stack effect of
2084: the loop start words: Since the start value of the loop is more
2085: frequently constant than the end value, the start value is passed on
2086: the top-of-stack.
2087:
2088: You can access the counter of a counted loop with @code{i}:
2089:
2090: @example
2091: : fac ( u -- u! )
2092: 1 swap 1+ 1 u+do
2093: i *
2094: loop ;
2095: 5 fac .
2096: 7 fac .
2097: @end example
2098:
2099: There is also @code{+do}, which expects signed numbers (important for
2100: deciding whether to enter the loop).
2101:
1.141 anton 2102: @quotation Assignment
1.48 anton 2103: Write a definition for computing the nth Fibonacci number.
1.141 anton 2104: @end quotation
1.48 anton 2105:
1.65 anton 2106: You can also use increments other than 1:
2107:
2108: @example
2109: : up2 ( n1 n2 -- )
2110: +do
2111: i .
2112: 2 +loop ;
2113: 10 0 up2
2114:
2115: : down2 ( n1 n2 -- )
2116: -do
2117: i .
2118: 2 -loop ;
2119: 0 10 down2
2120: @end example
1.48 anton 2121:
1.66 anton 2122: Reference: @ref{Counted Loops}.
2123:
1.48 anton 2124:
2125: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2126: @section Recursion
1.66 anton 2127: @cindex recursion tutorial
1.48 anton 2128:
2129: Usually the name of a definition is not visible in the definition; but
2130: earlier definitions are usually visible:
2131:
2132: @example
2133: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2134: : / ( n1 n2 -- n )
2135: dup 0= if
2136: -10 throw \ report division by zero
2137: endif
2138: / \ old version
2139: ;
2140: 1 0 /
2141: @end example
2142:
2143: For recursive definitions you can use @code{recursive} (non-standard) or
2144: @code{recurse}:
2145:
2146: @example
2147: : fac1 ( n -- n! ) recursive
2148: dup 0> if
2149: dup 1- fac1 *
2150: else
2151: drop 1
2152: endif ;
2153: 7 fac1 .
2154:
2155: : fac2 ( n -- n! )
2156: dup 0> if
2157: dup 1- recurse *
2158: else
2159: drop 1
2160: endif ;
2161: 8 fac2 .
2162: @end example
2163:
1.141 anton 2164: @quotation Assignment
1.48 anton 2165: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2166: @end quotation
1.48 anton 2167:
1.66 anton 2168: Reference (including indirect recursion): @xref{Calls and returns}.
2169:
1.48 anton 2170:
2171: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2172: @section Leaving definitions or loops
1.66 anton 2173: @cindex leaving definitions, tutorial
2174: @cindex leaving loops, tutorial
1.48 anton 2175:
2176: @code{EXIT} exits the current definition right away. For every counted
2177: loop that is left in this way, an @code{UNLOOP} has to be performed
2178: before the @code{EXIT}:
2179:
2180: @c !! real examples
2181: @example
2182: : ...
2183: ... u+do
2184: ... if
2185: ... unloop exit
2186: endif
2187: ...
2188: loop
2189: ... ;
2190: @end example
2191:
2192: @code{LEAVE} leaves the innermost counted loop right away:
2193:
2194: @example
2195: : ...
2196: ... u+do
2197: ... if
2198: ... leave
2199: endif
2200: ...
2201: loop
2202: ... ;
2203: @end example
2204:
1.65 anton 2205: @c !! example
1.48 anton 2206:
1.66 anton 2207: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2208:
2209:
1.48 anton 2210: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2211: @section Return Stack
1.66 anton 2212: @cindex return stack tutorial
1.48 anton 2213:
2214: In addition to the data stack Forth also has a second stack, the return
2215: stack; most Forth systems store the return addresses of procedure calls
2216: there (thus its name). Programmers can also use this stack:
2217:
2218: @example
2219: : foo ( n1 n2 -- )
2220: .s
2221: >r .s
1.50 anton 2222: r@@ .
1.48 anton 2223: >r .s
1.50 anton 2224: r@@ .
1.48 anton 2225: r> .
1.50 anton 2226: r@@ .
1.48 anton 2227: r> . ;
2228: 1 2 foo
2229: @end example
2230:
2231: @code{>r} takes an element from the data stack and pushes it onto the
2232: return stack; conversely, @code{r>} moves an elementm from the return to
2233: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 ! anton 2234: on the data stack.
1.48 anton 2235:
2236: Forth programmers usually use the return stack for storing data
2237: temporarily, if using the data stack alone would be too complex, and
2238: factoring and locals are not an option:
2239:
2240: @example
2241: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2242: rot >r rot r> ;
2243: @end example
2244:
2245: The return address of the definition and the loop control parameters of
2246: counted loops usually reside on the return stack, so you have to take
2247: all items, that you have pushed on the return stack in a colon
2248: definition or counted loop, from the return stack before the definition
2249: or loop ends. You cannot access items that you pushed on the return
2250: stack outside some definition or loop within the definition of loop.
2251:
2252: If you miscount the return stack items, this usually ends in a crash:
2253:
2254: @example
2255: : crash ( n -- )
2256: >r ;
2257: 5 crash
2258: @end example
2259:
2260: You cannot mix using locals and using the return stack (according to the
2261: standard; Gforth has no problem). However, they solve the same
2262: problems, so this shouldn't be an issue.
2263:
1.141 anton 2264: @quotation Assignment
1.48 anton 2265: Can you rewrite any of the definitions you wrote until now in a better
2266: way using the return stack?
1.141 anton 2267: @end quotation
1.48 anton 2268:
1.66 anton 2269: Reference: @ref{Return stack}.
2270:
1.48 anton 2271:
2272: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2273: @section Memory
1.66 anton 2274: @cindex memory access/allocation tutorial
1.48 anton 2275:
2276: You can create a global variable @code{v} with
2277:
2278: @example
2279: variable v ( -- addr )
2280: @end example
2281:
2282: @code{v} pushes the address of a cell in memory on the stack. This cell
2283: was reserved by @code{variable}. You can use @code{!} (store) to store
2284: values into this cell and @code{@@} (fetch) to load the value from the
2285: stack into memory:
2286:
2287: @example
2288: v .
2289: 5 v ! .s
1.50 anton 2290: v @@ .
1.48 anton 2291: @end example
2292:
1.65 anton 2293: You can see a raw dump of memory with @code{dump}:
2294:
2295: @example
2296: v 1 cells .s dump
2297: @end example
2298:
2299: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2300: generally, address units (aus)) that @code{n1 cells} occupy. You can
2301: also reserve more memory:
1.48 anton 2302:
2303: @example
2304: create v2 20 cells allot
1.65 anton 2305: v2 20 cells dump
1.48 anton 2306: @end example
2307:
1.65 anton 2308: creates a word @code{v2} and reserves 20 uninitialized cells; the
2309: address pushed by @code{v2} points to the start of these 20 cells. You
2310: can use address arithmetic to access these cells:
1.48 anton 2311:
2312: @example
2313: 3 v2 5 cells + !
1.65 anton 2314: v2 20 cells dump
1.48 anton 2315: @end example
2316:
2317: You can reserve and initialize memory with @code{,}:
2318:
2319: @example
2320: create v3
2321: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2322: v3 @@ .
2323: v3 cell+ @@ .
2324: v3 2 cells + @@ .
1.65 anton 2325: v3 5 cells dump
1.48 anton 2326: @end example
2327:
1.141 anton 2328: @quotation Assignment
1.48 anton 2329: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2330: @code{u} cells, with the first of these cells at @code{addr}, the next
2331: one at @code{addr cell+} etc.
1.141 anton 2332: @end quotation
1.48 anton 2333:
2334: You can also reserve memory without creating a new word:
2335:
2336: @example
1.60 anton 2337: here 10 cells allot .
2338: here .
1.48 anton 2339: @end example
2340:
2341: @code{Here} pushes the start address of the memory area. You should
2342: store it somewhere, or you will have a hard time finding the memory area
2343: again.
2344:
2345: @code{Allot} manages dictionary memory. The dictionary memory contains
2346: the system's data structures for words etc. on Gforth and most other
2347: Forth systems. It is managed like a stack: You can free the memory that
2348: you have just @code{allot}ed with
2349:
2350: @example
2351: -10 cells allot
1.60 anton 2352: here .
1.48 anton 2353: @end example
2354:
2355: Note that you cannot do this if you have created a new word in the
2356: meantime (because then your @code{allot}ed memory is no longer on the
2357: top of the dictionary ``stack'').
2358:
2359: Alternatively, you can use @code{allocate} and @code{free} which allow
2360: freeing memory in any order:
2361:
2362: @example
2363: 10 cells allocate throw .s
2364: 20 cells allocate throw .s
2365: swap
2366: free throw
2367: free throw
2368: @end example
2369:
2370: The @code{throw}s deal with errors (e.g., out of memory).
2371:
1.65 anton 2372: And there is also a
2373: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2374: garbage collector}, which eliminates the need to @code{free} memory
2375: explicitly.
1.48 anton 2376:
1.66 anton 2377: Reference: @ref{Memory}.
2378:
1.48 anton 2379:
2380: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2381: @section Characters and Strings
1.66 anton 2382: @cindex strings tutorial
2383: @cindex characters tutorial
1.48 anton 2384:
2385: On the stack characters take up a cell, like numbers. In memory they
2386: have their own size (one 8-bit byte on most systems), and therefore
2387: require their own words for memory access:
2388:
2389: @example
2390: create v4
2391: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2392: v4 4 chars + c@@ .
1.65 anton 2393: v4 5 chars dump
1.48 anton 2394: @end example
2395:
2396: The preferred representation of strings on the stack is @code{addr
2397: u-count}, where @code{addr} is the address of the first character and
2398: @code{u-count} is the number of characters in the string.
2399:
2400: @example
2401: v4 5 type
2402: @end example
2403:
2404: You get a string constant with
2405:
2406: @example
2407: s" hello, world" .s
2408: type
2409: @end example
2410:
2411: Make sure you have a space between @code{s"} and the string; @code{s"}
2412: is a normal Forth word and must be delimited with white space (try what
2413: happens when you remove the space).
2414:
2415: However, this interpretive use of @code{s"} is quite restricted: the
2416: string exists only until the next call of @code{s"} (some Forth systems
2417: keep more than one of these strings, but usually they still have a
1.62 crook 2418: limited lifetime).
1.48 anton 2419:
2420: @example
2421: s" hello," s" world" .s
2422: type
2423: type
2424: @end example
2425:
1.62 crook 2426: You can also use @code{s"} in a definition, and the resulting
2427: strings then live forever (well, for as long as the definition):
1.48 anton 2428:
2429: @example
2430: : foo s" hello," s" world" ;
2431: foo .s
2432: type
2433: type
2434: @end example
2435:
1.141 anton 2436: @quotation Assignment
1.48 anton 2437: @code{Emit ( c -- )} types @code{c} as character (not a number).
2438: Implement @code{type ( addr u -- )}.
1.141 anton 2439: @end quotation
1.48 anton 2440:
1.66 anton 2441: Reference: @ref{Memory Blocks}.
2442:
2443:
1.84 pazsan 2444: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2445: @section Alignment
1.66 anton 2446: @cindex alignment tutorial
2447: @cindex memory alignment tutorial
1.48 anton 2448:
2449: On many processors cells have to be aligned in memory, if you want to
2450: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2451: not require alignment, access to aligned cells is faster).
1.48 anton 2452:
2453: @code{Create} aligns @code{here} (i.e., the place where the next
2454: allocation will occur, and that the @code{create}d word points to).
2455: Likewise, the memory produced by @code{allocate} starts at an aligned
2456: address. Adding a number of @code{cells} to an aligned address produces
2457: another aligned address.
2458:
2459: However, address arithmetic involving @code{char+} and @code{chars} can
2460: create an address that is not cell-aligned. @code{Aligned ( addr --
2461: a-addr )} produces the next aligned address:
2462:
2463: @example
1.50 anton 2464: v3 char+ aligned .s @@ .
2465: v3 char+ .s @@ .
1.48 anton 2466: @end example
2467:
2468: Similarly, @code{align} advances @code{here} to the next aligned
2469: address:
2470:
2471: @example
2472: create v5 97 c,
2473: here .
2474: align here .
2475: 1000 ,
2476: @end example
2477:
2478: Note that you should use aligned addresses even if your processor does
2479: not require them, if you want your program to be portable.
2480:
1.66 anton 2481: Reference: @ref{Address arithmetic}.
2482:
1.48 anton 2483:
1.84 pazsan 2484: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2485: @section Files
2486: @cindex files tutorial
2487:
2488: This section gives a short introduction into how to use files inside
2489: Forth. It's broken up into five easy steps:
2490:
2491: @enumerate 1
2492: @item Opened an ASCII text file for input
2493: @item Opened a file for output
2494: @item Read input file until string matched (or some other condition matched)
2495: @item Wrote some lines from input ( modified or not) to output
2496: @item Closed the files.
2497: @end enumerate
2498:
2499: @subsection Open file for input
2500:
2501: @example
2502: s" foo.in" r/o open-file throw Value fd-in
2503: @end example
2504:
2505: @subsection Create file for output
2506:
2507: @example
2508: s" foo.out" w/o create-file throw Value fd-out
2509: @end example
2510:
2511: The available file modes are r/o for read-only access, r/w for
2512: read-write access, and w/o for write-only access. You could open both
2513: files with r/w, too, if you like. All file words return error codes; for
2514: most applications, it's best to pass there error codes with @code{throw}
2515: to the outer error handler.
2516:
2517: If you want words for opening and assigning, define them as follows:
2518:
2519: @example
2520: 0 Value fd-in
2521: 0 Value fd-out
2522: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2523: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2524: @end example
2525:
2526: Usage example:
2527:
2528: @example
2529: s" foo.in" open-input
2530: s" foo.out" open-output
2531: @end example
2532:
2533: @subsection Scan file for a particular line
2534:
2535: @example
2536: 256 Constant max-line
2537: Create line-buffer max-line 2 + allot
2538:
2539: : scan-file ( addr u -- )
2540: begin
2541: line-buffer max-line fd-in read-line throw
2542: while
2543: >r 2dup line-buffer r> compare 0=
2544: until
2545: else
2546: drop
2547: then
2548: 2drop ;
2549: @end example
2550:
2551: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2552: the buffer at addr, and returns the number of bytes read, a flag that is
2553: false when the end of file is reached, and an error code.
1.84 pazsan 2554:
2555: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2556: returns zero if both strings are equal. It returns a positive number if
2557: the first string is lexically greater, a negative if the second string
2558: is lexically greater.
2559:
2560: We haven't seen this loop here; it has two exits. Since the @code{while}
2561: exits with the number of bytes read on the stack, we have to clean up
2562: that separately; that's after the @code{else}.
2563:
2564: Usage example:
2565:
2566: @example
2567: s" The text I search is here" scan-file
2568: @end example
2569:
2570: @subsection Copy input to output
2571:
2572: @example
2573: : copy-file ( -- )
2574: begin
2575: line-buffer max-line fd-in read-line throw
2576: while
2577: line-buffer swap fd-out write-file throw
2578: repeat ;
2579: @end example
2580:
2581: @subsection Close files
2582:
2583: @example
2584: fd-in close-file throw
2585: fd-out close-file throw
2586: @end example
2587:
2588: Likewise, you can put that into definitions, too:
2589:
2590: @example
2591: : close-input ( -- ) fd-in close-file throw ;
2592: : close-output ( -- ) fd-out close-file throw ;
2593: @end example
2594:
1.141 anton 2595: @quotation Assignment
1.84 pazsan 2596: How could you modify @code{copy-file} so that it copies until a second line is
2597: matched? Can you write a program that extracts a section of a text file,
2598: given the line that starts and the line that terminates that section?
1.141 anton 2599: @end quotation
1.84 pazsan 2600:
2601: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2602: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2603: @cindex semantics tutorial
2604: @cindex interpretation semantics tutorial
2605: @cindex compilation semantics tutorial
2606: @cindex immediate, tutorial
1.48 anton 2607:
2608: When a word is compiled, it behaves differently from being interpreted.
2609: E.g., consider @code{+}:
2610:
2611: @example
2612: 1 2 + .
2613: : foo + ;
2614: @end example
2615:
2616: These two behaviours are known as compilation and interpretation
2617: semantics. For normal words (e.g., @code{+}), the compilation semantics
2618: is to append the interpretation semantics to the currently defined word
2619: (@code{foo} in the example above). I.e., when @code{foo} is executed
2620: later, the interpretation semantics of @code{+} (i.e., adding two
2621: numbers) will be performed.
2622:
2623: However, there are words with non-default compilation semantics, e.g.,
2624: the control-flow words like @code{if}. You can use @code{immediate} to
2625: change the compilation semantics of the last defined word to be equal to
2626: the interpretation semantics:
2627:
2628: @example
2629: : [FOO] ( -- )
2630: 5 . ; immediate
2631:
2632: [FOO]
2633: : bar ( -- )
2634: [FOO] ;
2635: bar
2636: see bar
2637: @end example
2638:
2639: Two conventions to mark words with non-default compilation semnatics are
2640: names with brackets (more frequently used) and to write them all in
2641: upper case (less frequently used).
2642:
2643: In Gforth (and many other systems) you can also remove the
2644: interpretation semantics with @code{compile-only} (the compilation
2645: semantics is derived from the original interpretation semantics):
2646:
2647: @example
2648: : flip ( -- )
2649: 6 . ; compile-only \ but not immediate
2650: flip
2651:
2652: : flop ( -- )
2653: flip ;
2654: flop
2655: @end example
2656:
2657: In this example the interpretation semantics of @code{flop} is equal to
2658: the original interpretation semantics of @code{flip}.
2659:
2660: The text interpreter has two states: in interpret state, it performs the
2661: interpretation semantics of words it encounters; in compile state, it
2662: performs the compilation semantics of these words.
2663:
2664: Among other things, @code{:} switches into compile state, and @code{;}
2665: switches back to interpret state. They contain the factors @code{]}
2666: (switch to compile state) and @code{[} (switch to interpret state), that
2667: do nothing but switch the state.
2668:
2669: @example
2670: : xxx ( -- )
2671: [ 5 . ]
2672: ;
2673:
2674: xxx
2675: see xxx
2676: @end example
2677:
2678: These brackets are also the source of the naming convention mentioned
2679: above.
2680:
1.66 anton 2681: Reference: @ref{Interpretation and Compilation Semantics}.
2682:
1.48 anton 2683:
2684: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2685: @section Execution Tokens
1.66 anton 2686: @cindex execution tokens tutorial
2687: @cindex XT tutorial
1.48 anton 2688:
2689: @code{' word} gives you the execution token (XT) of a word. The XT is a
2690: cell representing the interpretation semantics of a word. You can
2691: execute this semantics with @code{execute}:
2692:
2693: @example
2694: ' + .s
2695: 1 2 rot execute .
2696: @end example
2697:
2698: The XT is similar to a function pointer in C. However, parameter
2699: passing through the stack makes it a little more flexible:
2700:
2701: @example
2702: : map-array ( ... addr u xt -- ... )
1.50 anton 2703: \ executes xt ( ... x -- ... ) for every element of the array starting
2704: \ at addr and containing u elements
1.48 anton 2705: @{ xt @}
2706: cells over + swap ?do
1.50 anton 2707: i @@ xt execute
1.48 anton 2708: 1 cells +loop ;
2709:
2710: create a 3 , 4 , 2 , -1 , 4 ,
2711: a 5 ' . map-array .s
2712: 0 a 5 ' + map-array .
2713: s" max-n" environment? drop .s
2714: a 5 ' min map-array .
2715: @end example
2716:
2717: You can use map-array with the XTs of words that consume one element
2718: more than they produce. In theory you can also use it with other XTs,
2719: but the stack effect then depends on the size of the array, which is
2720: hard to understand.
2721:
1.51 pazsan 2722: Since XTs are cell-sized, you can store them in memory and manipulate
2723: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2724: word with @code{compile,}:
2725:
2726: @example
2727: : foo1 ( n1 n2 -- n )
2728: [ ' + compile, ] ;
2729: see foo
2730: @end example
2731:
2732: This is non-standard, because @code{compile,} has no compilation
2733: semantics in the standard, but it works in good Forth systems. For the
2734: broken ones, use
2735:
2736: @example
2737: : [compile,] compile, ; immediate
2738:
2739: : foo1 ( n1 n2 -- n )
2740: [ ' + ] [compile,] ;
2741: see foo
2742: @end example
2743:
2744: @code{'} is a word with default compilation semantics; it parses the
2745: next word when its interpretation semantics are executed, not during
2746: compilation:
2747:
2748: @example
2749: : foo ( -- xt )
2750: ' ;
2751: see foo
2752: : bar ( ... "word" -- ... )
2753: ' execute ;
2754: see bar
1.60 anton 2755: 1 2 bar + .
1.48 anton 2756: @end example
2757:
2758: You often want to parse a word during compilation and compile its XT so
2759: it will be pushed on the stack at run-time. @code{[']} does this:
2760:
2761: @example
2762: : xt-+ ( -- xt )
2763: ['] + ;
2764: see xt-+
2765: 1 2 xt-+ execute .
2766: @end example
2767:
2768: Many programmers tend to see @code{'} and the word it parses as one
2769: unit, and expect it to behave like @code{[']} when compiled, and are
2770: confused by the actual behaviour. If you are, just remember that the
2771: Forth system just takes @code{'} as one unit and has no idea that it is
2772: a parsing word (attempts to convenience programmers in this issue have
2773: usually resulted in even worse pitfalls, see
1.66 anton 2774: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2775: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2776:
2777: Note that the state of the interpreter does not come into play when
1.51 pazsan 2778: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2779: compile state, it still gives you the interpretation semantics. And
2780: whatever that state is, @code{execute} performs the semantics
1.66 anton 2781: represented by the XT (i.e., for XTs produced with @code{'} the
2782: interpretation semantics).
2783:
2784: Reference: @ref{Tokens for Words}.
1.48 anton 2785:
2786:
2787: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2788: @section Exceptions
1.66 anton 2789: @cindex exceptions tutorial
1.48 anton 2790:
2791: @code{throw ( n -- )} causes an exception unless n is zero.
2792:
2793: @example
2794: 100 throw .s
2795: 0 throw .s
2796: @end example
2797:
2798: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2799: it catches exceptions and pushes the number of the exception on the
2800: stack (or 0, if the xt executed without exception). If there was an
2801: exception, the stacks have the same depth as when entering @code{catch}:
2802:
2803: @example
2804: .s
2805: 3 0 ' / catch .s
2806: 3 2 ' / catch .s
2807: @end example
2808:
1.141 anton 2809: @quotation Assignment
1.48 anton 2810: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2811: @end quotation
1.48 anton 2812:
2813: @code{Throw} always jumps to the dynamically next enclosing
2814: @code{catch}, even if it has to leave several call levels to achieve
2815: this:
2816:
2817: @example
2818: : foo 100 throw ;
2819: : foo1 foo ." after foo" ;
1.51 pazsan 2820: : bar ['] foo1 catch ;
1.60 anton 2821: bar .
1.48 anton 2822: @end example
2823:
2824: It is often important to restore a value upon leaving a definition, even
2825: if the definition is left through an exception. You can ensure this
2826: like this:
2827:
2828: @example
2829: : ...
2830: save-x
1.51 pazsan 2831: ['] word-changing-x catch ( ... n )
1.48 anton 2832: restore-x
2833: ( ... n ) throw ;
2834: @end example
2835:
1.55 anton 2836: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2837: @code{try ... recover ... endtry}. If the code between @code{try} and
2838: @code{recover} has an exception, the stack depths are restored, the
2839: exception number is pushed on the stack, and the code between
2840: @code{recover} and @code{endtry} is performed. E.g., the definition for
2841: @code{catch} is
2842:
2843: @example
2844: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2845: try
2846: execute 0
2847: recover
2848: nip
2849: endtry ;
2850: @end example
2851:
2852: The equivalent to the restoration code above is
2853:
2854: @example
2855: : ...
2856: save-x
2857: try
1.92 anton 2858: word-changing-x 0
2859: recover endtry
1.48 anton 2860: restore-x
2861: throw ;
2862: @end example
2863:
1.92 anton 2864: This works if @code{word-changing-x} does not change the stack depth,
2865: otherwise you should add some code between @code{recover} and
2866: @code{endtry} to balance the stack.
1.48 anton 2867:
1.66 anton 2868: Reference: @ref{Exception Handling}.
2869:
1.48 anton 2870:
2871: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2872: @section Defining Words
1.66 anton 2873: @cindex defining words tutorial
2874: @cindex does> tutorial
2875: @cindex create...does> tutorial
2876:
2877: @c before semantics?
1.48 anton 2878:
2879: @code{:}, @code{create}, and @code{variable} are definition words: They
2880: define other words. @code{Constant} is another definition word:
2881:
2882: @example
2883: 5 constant foo
2884: foo .
2885: @end example
2886:
2887: You can also use the prefixes @code{2} (double-cell) and @code{f}
2888: (floating point) with @code{variable} and @code{constant}.
2889:
2890: You can also define your own defining words. E.g.:
2891:
2892: @example
2893: : variable ( "name" -- )
2894: create 0 , ;
2895: @end example
2896:
2897: You can also define defining words that create words that do something
2898: other than just producing their address:
2899:
2900: @example
2901: : constant ( n "name" -- )
2902: create ,
2903: does> ( -- n )
1.50 anton 2904: ( addr ) @@ ;
1.48 anton 2905:
2906: 5 constant foo
2907: foo .
2908: @end example
2909:
2910: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2911: @code{does>} replaces @code{;}, but it also does something else: It
2912: changes the last defined word such that it pushes the address of the
2913: body of the word and then performs the code after the @code{does>}
2914: whenever it is called.
2915:
2916: In the example above, @code{constant} uses @code{,} to store 5 into the
2917: body of @code{foo}. When @code{foo} executes, it pushes the address of
2918: the body onto the stack, then (in the code after the @code{does>})
2919: fetches the 5 from there.
2920:
2921: The stack comment near the @code{does>} reflects the stack effect of the
2922: defined word, not the stack effect of the code after the @code{does>}
2923: (the difference is that the code expects the address of the body that
2924: the stack comment does not show).
2925:
2926: You can use these definition words to do factoring in cases that involve
2927: (other) definition words. E.g., a field offset is always added to an
2928: address. Instead of defining
2929:
2930: @example
2931: 2 cells constant offset-field1
2932: @end example
2933:
2934: and using this like
2935:
2936: @example
2937: ( addr ) offset-field1 +
2938: @end example
2939:
2940: you can define a definition word
2941:
2942: @example
2943: : simple-field ( n "name" -- )
2944: create ,
2945: does> ( n1 -- n1+n )
1.50 anton 2946: ( addr ) @@ + ;
1.48 anton 2947: @end example
1.21 crook 2948:
1.48 anton 2949: Definition and use of field offsets now look like this:
1.21 crook 2950:
1.48 anton 2951: @example
2952: 2 cells simple-field field1
1.60 anton 2953: create mystruct 4 cells allot
2954: mystruct .s field1 .s drop
1.48 anton 2955: @end example
1.21 crook 2956:
1.48 anton 2957: If you want to do something with the word without performing the code
2958: after the @code{does>}, you can access the body of a @code{create}d word
2959: with @code{>body ( xt -- addr )}:
1.21 crook 2960:
1.48 anton 2961: @example
2962: : value ( n "name" -- )
2963: create ,
2964: does> ( -- n1 )
1.50 anton 2965: @@ ;
1.48 anton 2966: : to ( n "name" -- )
2967: ' >body ! ;
1.21 crook 2968:
1.48 anton 2969: 5 value foo
2970: foo .
2971: 7 to foo
2972: foo .
2973: @end example
1.21 crook 2974:
1.141 anton 2975: @quotation Assignment
1.48 anton 2976: Define @code{defer ( "name" -- )}, which creates a word that stores an
2977: XT (at the start the XT of @code{abort}), and upon execution
2978: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2979: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2980: recursion is one application of @code{defer}.
1.141 anton 2981: @end quotation
1.29 crook 2982:
1.66 anton 2983: Reference: @ref{User-defined Defining Words}.
2984:
2985:
1.48 anton 2986: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2987: @section Arrays and Records
1.66 anton 2988: @cindex arrays tutorial
2989: @cindex records tutorial
2990: @cindex structs tutorial
1.29 crook 2991:
1.48 anton 2992: Forth has no standard words for defining data structures such as arrays
2993: and records (structs in C terminology), but you can build them yourself
2994: based on address arithmetic. You can also define words for defining
2995: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2996:
1.48 anton 2997: One of the first projects a Forth newcomer sets out upon when learning
2998: about defining words is an array defining word (possibly for
2999: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3000: learn something from it. However, don't be disappointed when you later
3001: learn that you have little use for these words (inappropriate use would
3002: be even worse). I have not yet found a set of useful array words yet;
3003: the needs are just too diverse, and named, global arrays (the result of
3004: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3005: consider how to pass them as parameters). Another such project is a set
3006: of words to help dealing with strings.
1.29 crook 3007:
1.48 anton 3008: On the other hand, there is a useful set of record words, and it has
3009: been defined in @file{compat/struct.fs}; these words are predefined in
3010: Gforth. They are explained in depth elsewhere in this manual (see
3011: @pxref{Structures}). The @code{simple-field} example above is
3012: simplified variant of fields in this package.
1.21 crook 3013:
3014:
1.48 anton 3015: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3016: @section @code{POSTPONE}
1.66 anton 3017: @cindex postpone tutorial
1.21 crook 3018:
1.48 anton 3019: You can compile the compilation semantics (instead of compiling the
3020: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3021:
1.48 anton 3022: @example
3023: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3024: POSTPONE + ; immediate
1.48 anton 3025: : foo ( n1 n2 -- n )
3026: MY-+ ;
3027: 1 2 foo .
3028: see foo
3029: @end example
1.21 crook 3030:
1.48 anton 3031: During the definition of @code{foo} the text interpreter performs the
3032: compilation semantics of @code{MY-+}, which performs the compilation
3033: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3034:
3035: This example also displays separate stack comments for the compilation
3036: semantics and for the stack effect of the compiled code. For words with
3037: default compilation semantics these stack effects are usually not
3038: displayed; the stack effect of the compilation semantics is always
3039: @code{( -- )} for these words, the stack effect for the compiled code is
3040: the stack effect of the interpretation semantics.
3041:
3042: Note that the state of the interpreter does not come into play when
3043: performing the compilation semantics in this way. You can also perform
3044: it interpretively, e.g.:
3045:
3046: @example
3047: : foo2 ( n1 n2 -- n )
3048: [ MY-+ ] ;
3049: 1 2 foo .
3050: see foo
3051: @end example
1.21 crook 3052:
1.48 anton 3053: However, there are some broken Forth systems where this does not always
1.62 crook 3054: work, and therefore this practice was been declared non-standard in
1.48 anton 3055: 1999.
3056: @c !! repair.fs
3057:
3058: Here is another example for using @code{POSTPONE}:
1.44 crook 3059:
1.48 anton 3060: @example
3061: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3062: POSTPONE negate POSTPONE + ; immediate compile-only
3063: : bar ( n1 n2 -- n )
3064: MY-- ;
3065: 2 1 bar .
3066: see bar
3067: @end example
1.21 crook 3068:
1.48 anton 3069: You can define @code{ENDIF} in this way:
1.21 crook 3070:
1.48 anton 3071: @example
3072: : ENDIF ( Compilation: orig -- )
3073: POSTPONE then ; immediate
3074: @end example
1.21 crook 3075:
1.141 anton 3076: @quotation Assignment
1.48 anton 3077: Write @code{MY-2DUP} that has compilation semantics equivalent to
3078: @code{2dup}, but compiles @code{over over}.
1.141 anton 3079: @end quotation
1.29 crook 3080:
1.66 anton 3081: @c !! @xref{Macros} for reference
3082:
3083:
1.48 anton 3084: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3085: @section @code{Literal}
1.66 anton 3086: @cindex literal tutorial
1.29 crook 3087:
1.48 anton 3088: You cannot @code{POSTPONE} numbers:
1.21 crook 3089:
1.48 anton 3090: @example
3091: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3092: @end example
3093:
1.48 anton 3094: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3095:
1.48 anton 3096: @example
3097: : [FOO] ( compilation: --; run-time: -- n )
3098: 500 POSTPONE literal ; immediate
1.29 crook 3099:
1.60 anton 3100: : flip [FOO] ;
1.48 anton 3101: flip .
3102: see flip
3103: @end example
1.29 crook 3104:
1.48 anton 3105: @code{LITERAL} consumes a number at compile-time (when it's compilation
3106: semantics are executed) and pushes it at run-time (when the code it
3107: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3108: number computed at compile time into the current word:
1.29 crook 3109:
1.48 anton 3110: @example
3111: : bar ( -- n )
3112: [ 2 2 + ] literal ;
3113: see bar
3114: @end example
1.29 crook 3115:
1.141 anton 3116: @quotation Assignment
1.48 anton 3117: Write @code{]L} which allows writing the example above as @code{: bar (
3118: -- n ) [ 2 2 + ]L ;}
1.141 anton 3119: @end quotation
1.48 anton 3120:
1.66 anton 3121: @c !! @xref{Macros} for reference
3122:
1.48 anton 3123:
3124: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3125: @section Advanced macros
1.66 anton 3126: @cindex macros, advanced tutorial
3127: @cindex run-time code generation, tutorial
1.48 anton 3128:
1.66 anton 3129: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3130: Execution Tokens}. It frequently performs @code{execute}, a relatively
3131: expensive operation in some Forth implementations. You can use
1.48 anton 3132: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3133: and produce a word that contains the word to be performed directly:
3134:
3135: @c use ]] ... [[
3136: @example
3137: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3138: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3139: \ array beginning at addr and containing u elements
3140: @{ xt @}
3141: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3142: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3143: 1 cells POSTPONE literal POSTPONE +loop ;
3144:
3145: : sum-array ( addr u -- n )
3146: 0 rot rot [ ' + compile-map-array ] ;
3147: see sum-array
3148: a 5 sum-array .
3149: @end example
3150:
3151: You can use the full power of Forth for generating the code; here's an
3152: example where the code is generated in a loop:
3153:
3154: @example
3155: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3156: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3157: POSTPONE tuck POSTPONE @@
1.48 anton 3158: POSTPONE literal POSTPONE * POSTPONE +
3159: POSTPONE swap POSTPONE cell+ ;
3160:
3161: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3162: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3163: 0 postpone literal postpone swap
3164: [ ' compile-vmul-step compile-map-array ]
3165: postpone drop ;
3166: see compile-vmul
3167:
3168: : a-vmul ( addr -- n )
1.51 pazsan 3169: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3170: [ a 5 compile-vmul ] ;
3171: see a-vmul
3172: a a-vmul .
3173: @end example
3174:
3175: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3176: also use @code{map-array} instead (try it now!).
1.48 anton 3177:
3178: You can use this technique for efficient multiplication of large
3179: matrices. In matrix multiplication, you multiply every line of one
3180: matrix with every column of the other matrix. You can generate the code
3181: for one line once, and use it for every column. The only downside of
3182: this technique is that it is cumbersome to recover the memory consumed
3183: by the generated code when you are done (and in more complicated cases
3184: it is not possible portably).
3185:
1.66 anton 3186: @c !! @xref{Macros} for reference
3187:
3188:
1.48 anton 3189: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3190: @section Compilation Tokens
1.66 anton 3191: @cindex compilation tokens, tutorial
3192: @cindex CT, tutorial
1.48 anton 3193:
3194: This section is Gforth-specific. You can skip it.
3195:
3196: @code{' word compile,} compiles the interpretation semantics. For words
3197: with default compilation semantics this is the same as performing the
3198: compilation semantics. To represent the compilation semantics of other
3199: words (e.g., words like @code{if} that have no interpretation
3200: semantics), Gforth has the concept of a compilation token (CT,
3201: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3202: You can perform the compilation semantics represented by a CT with
3203: @code{execute}:
1.29 crook 3204:
1.48 anton 3205: @example
3206: : foo2 ( n1 n2 -- n )
3207: [ comp' + execute ] ;
3208: see foo
3209: @end example
1.29 crook 3210:
1.48 anton 3211: You can compile the compilation semantics represented by a CT with
3212: @code{postpone,}:
1.30 anton 3213:
1.48 anton 3214: @example
3215: : foo3 ( -- )
3216: [ comp' + postpone, ] ;
3217: see foo3
3218: @end example
1.30 anton 3219:
1.51 pazsan 3220: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3221: @code{comp'} is particularly useful for words that have no
3222: interpretation semantics:
1.29 crook 3223:
1.30 anton 3224: @example
1.48 anton 3225: ' if
1.60 anton 3226: comp' if .s 2drop
1.30 anton 3227: @end example
3228:
1.66 anton 3229: Reference: @ref{Tokens for Words}.
3230:
1.29 crook 3231:
1.48 anton 3232: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3233: @section Wordlists and Search Order
1.66 anton 3234: @cindex wordlists tutorial
3235: @cindex search order, tutorial
1.48 anton 3236:
3237: The dictionary is not just a memory area that allows you to allocate
3238: memory with @code{allot}, it also contains the Forth words, arranged in
3239: several wordlists. When searching for a word in a wordlist,
3240: conceptually you start searching at the youngest and proceed towards
3241: older words (in reality most systems nowadays use hash-tables); i.e., if
3242: you define a word with the same name as an older word, the new word
3243: shadows the older word.
3244:
3245: Which wordlists are searched in which order is determined by the search
3246: order. You can display the search order with @code{order}. It displays
3247: first the search order, starting with the wordlist searched first, then
3248: it displays the wordlist that will contain newly defined words.
1.21 crook 3249:
1.48 anton 3250: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3251:
1.48 anton 3252: @example
3253: wordlist constant mywords
3254: @end example
1.21 crook 3255:
1.48 anton 3256: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3257: defined words (the @emph{current} wordlist):
1.21 crook 3258:
1.48 anton 3259: @example
3260: mywords set-current
3261: order
3262: @end example
1.26 crook 3263:
1.48 anton 3264: Gforth does not display a name for the wordlist in @code{mywords}
3265: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3266:
1.48 anton 3267: You can get the current wordlist with @code{get-current ( -- wid)}. If
3268: you want to put something into a specific wordlist without overall
3269: effect on the current wordlist, this typically looks like this:
1.21 crook 3270:
1.48 anton 3271: @example
3272: get-current mywords set-current ( wid )
3273: create someword
3274: ( wid ) set-current
3275: @end example
1.21 crook 3276:
1.48 anton 3277: You can write the search order with @code{set-order ( wid1 .. widn n --
3278: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3279: searched wordlist is topmost.
1.21 crook 3280:
1.48 anton 3281: @example
3282: get-order mywords swap 1+ set-order
3283: order
3284: @end example
1.21 crook 3285:
1.48 anton 3286: Yes, the order of wordlists in the output of @code{order} is reversed
3287: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3288:
1.141 anton 3289: @quotation Assignment
1.48 anton 3290: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3291: wordlist to the search order. Define @code{previous ( -- )}, which
3292: removes the first searched wordlist from the search order. Experiment
3293: with boundary conditions (you will see some crashes or situations that
3294: are hard or impossible to leave).
1.141 anton 3295: @end quotation
1.21 crook 3296:
1.48 anton 3297: The search order is a powerful foundation for providing features similar
3298: to Modula-2 modules and C++ namespaces. However, trying to modularize
3299: programs in this way has disadvantages for debugging and reuse/factoring
3300: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3301: though). These disadvantages are not so clear in other
1.82 anton 3302: languages/programming environments, because these languages are not so
1.48 anton 3303: strong in debugging and reuse.
1.21 crook 3304:
1.66 anton 3305: @c !! example
3306:
3307: Reference: @ref{Word Lists}.
1.21 crook 3308:
1.29 crook 3309: @c ******************************************************************
1.48 anton 3310: @node Introduction, Words, Tutorial, Top
1.29 crook 3311: @comment node-name, next, previous, up
3312: @chapter An Introduction to ANS Forth
3313: @cindex Forth - an introduction
1.21 crook 3314:
1.83 anton 3315: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3316: that it is slower-paced in its examples, but uses them to dive deep into
3317: explaining Forth internals (not covered by the Tutorial). Apart from
3318: that, this chapter covers far less material. It is suitable for reading
3319: without using a computer.
3320:
1.29 crook 3321: The primary purpose of this manual is to document Gforth. However, since
3322: Forth is not a widely-known language and there is a lack of up-to-date
3323: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3324: material. For other sources of Forth-related
3325: information, see @ref{Forth-related information}.
1.21 crook 3326:
1.29 crook 3327: The examples in this section should work on any ANS Forth; the
3328: output shown was produced using Gforth. Each example attempts to
3329: reproduce the exact output that Gforth produces. If you try out the
3330: examples (and you should), what you should type is shown @kbd{like this}
3331: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3332: that, where the example shows @key{RET} it means that you should
1.29 crook 3333: press the ``carriage return'' key. Unfortunately, some output formats for
3334: this manual cannot show the difference between @kbd{this} and
3335: @code{this} which will make trying out the examples harder (but not
3336: impossible).
1.21 crook 3337:
1.29 crook 3338: Forth is an unusual language. It provides an interactive development
3339: environment which includes both an interpreter and compiler. Forth
3340: programming style encourages you to break a problem down into many
3341: @cindex factoring
3342: small fragments (@dfn{factoring}), and then to develop and test each
3343: fragment interactively. Forth advocates assert that breaking the
3344: edit-compile-test cycle used by conventional programming languages can
3345: lead to great productivity improvements.
1.21 crook 3346:
1.29 crook 3347: @menu
1.67 anton 3348: * Introducing the Text Interpreter::
3349: * Stacks and Postfix notation::
3350: * Your first definition::
3351: * How does that work?::
3352: * Forth is written in Forth::
3353: * Review - elements of a Forth system::
3354: * Where to go next::
3355: * Exercises::
1.29 crook 3356: @end menu
1.21 crook 3357:
1.29 crook 3358: @comment ----------------------------------------------
3359: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3360: @section Introducing the Text Interpreter
3361: @cindex text interpreter
3362: @cindex outer interpreter
1.21 crook 3363:
1.30 anton 3364: @c IMO this is too detailed and the pace is too slow for
3365: @c an introduction. If you know German, take a look at
3366: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3367: @c to see how I do it - anton
3368:
1.44 crook 3369: @c nac-> Where I have accepted your comments 100% and modified the text
3370: @c accordingly, I have deleted your comments. Elsewhere I have added a
3371: @c response like this to attempt to rationalise what I have done. Of
3372: @c course, this is a very clumsy mechanism for something that would be
3373: @c done far more efficiently over a beer. Please delete any dialogue
3374: @c you consider closed.
3375:
1.29 crook 3376: When you invoke the Forth image, you will see a startup banner printed
3377: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3378: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3379: its command line interpreter, which is called the @dfn{Text Interpreter}
3380: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3381: about the text interpreter as you read through this chapter, for more
3382: detail @pxref{The Text Interpreter}).
1.21 crook 3383:
1.29 crook 3384: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3385: input. Type a number and press the @key{RET} key:
1.21 crook 3386:
1.26 crook 3387: @example
1.30 anton 3388: @kbd{45@key{RET}} ok
1.26 crook 3389: @end example
1.21 crook 3390:
1.29 crook 3391: Rather than give you a prompt to invite you to input something, the text
3392: interpreter prints a status message @i{after} it has processed a line
3393: of input. The status message in this case (``@code{ ok}'' followed by
3394: carriage-return) indicates that the text interpreter was able to process
3395: all of your input successfully. Now type something illegal:
3396:
3397: @example
1.30 anton 3398: @kbd{qwer341@key{RET}}
1.134 anton 3399: *the terminal*:2: Undefined word
3400: >>>qwer341<<<
3401: Backtrace:
3402: $2A95B42A20 throw
3403: $2A95B57FB8 no.extensions
1.29 crook 3404: @end example
1.23 crook 3405:
1.134 anton 3406: The exact text, other than the ``Undefined word'' may differ slightly
3407: on your system, but the effect is the same; when the text interpreter
1.29 crook 3408: detects an error, it discards any remaining text on a line, resets
1.134 anton 3409: certain internal state and prints an error message. For a detailed
3410: description of error messages see @ref{Error messages}.
1.23 crook 3411:
1.29 crook 3412: The text interpreter waits for you to press carriage-return, and then
3413: processes your input line. Starting at the beginning of the line, it
3414: breaks the line into groups of characters separated by spaces. For each
3415: group of characters in turn, it makes two attempts to do something:
1.23 crook 3416:
1.29 crook 3417: @itemize @bullet
3418: @item
1.44 crook 3419: @cindex name dictionary
1.29 crook 3420: It tries to treat it as a command. It does this by searching a @dfn{name
3421: dictionary}. If the group of characters matches an entry in the name
3422: dictionary, the name dictionary provides the text interpreter with
3423: information that allows the text interpreter perform some actions. In
3424: Forth jargon, we say that the group
3425: @cindex word
3426: @cindex definition
3427: @cindex execution token
3428: @cindex xt
3429: of characters names a @dfn{word}, that the dictionary search returns an
3430: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3431: word, and that the text interpreter executes the xt. Often, the terms
3432: @dfn{word} and @dfn{definition} are used interchangeably.
3433: @item
3434: If the text interpreter fails to find a match in the name dictionary, it
3435: tries to treat the group of characters as a number in the current number
3436: base (when you start up Forth, the current number base is base 10). If
3437: the group of characters legitimately represents a number, the text
3438: interpreter pushes the number onto a stack (we'll learn more about that
3439: in the next section).
3440: @end itemize
1.23 crook 3441:
1.29 crook 3442: If the text interpreter is unable to do either of these things with any
3443: group of characters, it discards the group of characters and the rest of
3444: the line, then prints an error message. If the text interpreter reaches
3445: the end of the line without error, it prints the status message ``@code{ ok}''
3446: followed by carriage-return.
1.21 crook 3447:
1.29 crook 3448: This is the simplest command we can give to the text interpreter:
1.23 crook 3449:
3450: @example
1.30 anton 3451: @key{RET} ok
1.23 crook 3452: @end example
1.21 crook 3453:
1.29 crook 3454: The text interpreter did everything we asked it to do (nothing) without
3455: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3456: command:
1.21 crook 3457:
1.23 crook 3458: @example
1.30 anton 3459: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3460: *the terminal*:3: Undefined word
3461: 12 dup >>>fred<<< dup
3462: Backtrace:
3463: $2A95B42A20 throw
3464: $2A95B57FB8 no.extensions
1.23 crook 3465: @end example
1.21 crook 3466:
1.29 crook 3467: When you press the carriage-return key, the text interpreter starts to
3468: work its way along the line:
1.21 crook 3469:
1.29 crook 3470: @itemize @bullet
3471: @item
3472: When it gets to the space after the @code{2}, it takes the group of
3473: characters @code{12} and looks them up in the name
3474: dictionary@footnote{We can't tell if it found them or not, but assume
3475: for now that it did not}. There is no match for this group of characters
3476: in the name dictionary, so it tries to treat them as a number. It is
3477: able to do this successfully, so it puts the number, 12, ``on the stack''
3478: (whatever that means).
3479: @item
3480: The text interpreter resumes scanning the line and gets the next group
3481: of characters, @code{dup}. It looks it up in the name dictionary and
3482: (you'll have to take my word for this) finds it, and executes the word
3483: @code{dup} (whatever that means).
3484: @item
3485: Once again, the text interpreter resumes scanning the line and gets the
3486: group of characters @code{fred}. It looks them up in the name
3487: dictionary, but can't find them. It tries to treat them as a number, but
3488: they don't represent any legal number.
3489: @end itemize
1.21 crook 3490:
1.29 crook 3491: At this point, the text interpreter gives up and prints an error
3492: message. The error message shows exactly how far the text interpreter
3493: got in processing the line. In particular, it shows that the text
3494: interpreter made no attempt to do anything with the final character
3495: group, @code{dup}, even though we have good reason to believe that the
3496: text interpreter would have no problem looking that word up and
3497: executing it a second time.
1.21 crook 3498:
3499:
1.29 crook 3500: @comment ----------------------------------------------
3501: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3502: @section Stacks, postfix notation and parameter passing
3503: @cindex text interpreter
3504: @cindex outer interpreter
1.21 crook 3505:
1.29 crook 3506: In procedural programming languages (like C and Pascal), the
3507: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3508: functions or procedures are called with @dfn{explicit parameters}. For
3509: example, in C we might write:
1.21 crook 3510:
1.23 crook 3511: @example
1.29 crook 3512: total = total + new_volume(length,height,depth);
1.23 crook 3513: @end example
1.21 crook 3514:
1.23 crook 3515: @noindent
1.29 crook 3516: where new_volume is a function-call to another piece of code, and total,
3517: length, height and depth are all variables. length, height and depth are
3518: parameters to the function-call.
1.21 crook 3519:
1.29 crook 3520: In Forth, the equivalent of the function or procedure is the
3521: @dfn{definition} and parameters are implicitly passed between
3522: definitions using a shared stack that is visible to the
3523: programmer. Although Forth does support variables, the existence of the
3524: stack means that they are used far less often than in most other
3525: programming languages. When the text interpreter encounters a number, it
3526: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3527: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3528: used for any operation is implied unambiguously by the operation being
3529: performed. The stack used for all integer operations is called the @dfn{data
3530: stack} and, since this is the stack used most commonly, references to
3531: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3532:
1.29 crook 3533: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3534:
1.23 crook 3535: @example
1.30 anton 3536: @kbd{1 2 3@key{RET}} ok
1.23 crook 3537: @end example
1.21 crook 3538:
1.29 crook 3539: Then this instructs the text interpreter to placed three numbers on the
3540: (data) stack. An analogy for the behaviour of the stack is to take a
3541: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3542: the table. The 3 was the last card onto the pile (``last-in'') and if
3543: you take a card off the pile then, unless you're prepared to fiddle a
3544: bit, the card that you take off will be the 3 (``first-out''). The
3545: number that will be first-out of the stack is called the @dfn{top of
3546: stack}, which
3547: @cindex TOS definition
3548: is often abbreviated to @dfn{TOS}.
1.21 crook 3549:
1.29 crook 3550: To understand how parameters are passed in Forth, consider the
3551: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3552: be surprised to learn that this definition performs addition. More
3553: precisely, it adds two number together and produces a result. Where does
3554: it get the two numbers from? It takes the top two numbers off the
3555: stack. Where does it place the result? On the stack. You can act-out the
3556: behaviour of @code{+} with your playing cards like this:
1.21 crook 3557:
3558: @itemize @bullet
3559: @item
1.29 crook 3560: Pick up two cards from the stack on the table
1.21 crook 3561: @item
1.29 crook 3562: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3563: numbers''
1.21 crook 3564: @item
1.29 crook 3565: Decide that the answer is 5
1.21 crook 3566: @item
1.29 crook 3567: Shuffle the two cards back into the pack and find a 5
1.21 crook 3568: @item
1.29 crook 3569: Put a 5 on the remaining ace that's on the table.
1.21 crook 3570: @end itemize
3571:
1.29 crook 3572: If you don't have a pack of cards handy but you do have Forth running,
3573: you can use the definition @code{.s} to show the current state of the stack,
3574: without affecting the stack. Type:
1.21 crook 3575:
3576: @example
1.124 anton 3577: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3578: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3579: @end example
3580:
1.124 anton 3581: The text interpreter looks up the word @code{clearstacks} and executes
3582: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3583: left on it by earlier examples. The text interpreter pushes each of the
3584: three numbers in turn onto the stack. Finally, the text interpreter
3585: looks up the word @code{.s} and executes it. The effect of executing
3586: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3587: followed by a list of all the items on the stack; the item on the far
3588: right-hand side is the TOS.
1.21 crook 3589:
1.29 crook 3590: You can now type:
1.21 crook 3591:
1.29 crook 3592: @example
1.30 anton 3593: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3594: @end example
1.21 crook 3595:
1.29 crook 3596: @noindent
3597: which is correct; there are now 2 items on the stack and the result of
3598: the addition is 5.
1.23 crook 3599:
1.29 crook 3600: If you're playing with cards, try doing a second addition: pick up the
3601: two cards, work out that their sum is 6, shuffle them into the pack,
3602: look for a 6 and place that on the table. You now have just one item on
3603: the stack. What happens if you try to do a third addition? Pick up the
3604: first card, pick up the second card -- ah! There is no second card. This
3605: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3606: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3607: Underflow or an Invalid Memory Address error).
1.23 crook 3608:
1.29 crook 3609: The opposite situation to a stack underflow is a @dfn{stack overflow},
3610: which simply accepts that there is a finite amount of storage space
3611: reserved for the stack. To stretch the playing card analogy, if you had
3612: enough packs of cards and you piled the cards up on the table, you would
3613: eventually be unable to add another card; you'd hit the ceiling. Gforth
3614: allows you to set the maximum size of the stacks. In general, the only
3615: time that you will get a stack overflow is because a definition has a
3616: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3617:
1.29 crook 3618: There's one final use for the playing card analogy. If you model your
3619: stack using a pack of playing cards, the maximum number of items on
3620: your stack will be 52 (I assume you didn't use the Joker). The maximum
3621: @i{value} of any item on the stack is 13 (the King). In fact, the only
3622: possible numbers are positive integer numbers 1 through 13; you can't
3623: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3624: think about some of the cards, you can accommodate different
3625: numbers. For example, you could think of the Jack as representing 0,
3626: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3627: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3628: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3629:
1.29 crook 3630: In that analogy, the limit was the amount of information that a single
3631: stack entry could hold, and Forth has a similar limit. In Forth, the
3632: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3633: implementation dependent and affects the maximum value that a stack
3634: entry can hold. A Standard Forth provides a cell size of at least
3635: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3636:
1.29 crook 3637: Forth does not do any type checking for you, so you are free to
3638: manipulate and combine stack items in any way you wish. A convenient way
3639: of treating stack items is as 2's complement signed integers, and that
3640: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3641:
1.29 crook 3642: @example
1.30 anton 3643: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3644: @end example
1.21 crook 3645:
1.29 crook 3646: If you use numbers and definitions like @code{+} in order to turn Forth
3647: into a great big pocket calculator, you will realise that it's rather
3648: different from a normal calculator. Rather than typing 2 + 3 = you had
3649: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3650: result). The terminology used to describe this difference is to say that
3651: your calculator uses @dfn{Infix Notation} (parameters and operators are
3652: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3653: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3654:
1.29 crook 3655: Whilst postfix notation might look confusing to begin with, it has
3656: several important advantages:
1.21 crook 3657:
1.23 crook 3658: @itemize @bullet
3659: @item
1.29 crook 3660: it is unambiguous
1.23 crook 3661: @item
1.29 crook 3662: it is more concise
1.23 crook 3663: @item
1.29 crook 3664: it fits naturally with a stack-based system
1.23 crook 3665: @end itemize
1.21 crook 3666:
1.29 crook 3667: To examine these claims in more detail, consider these sums:
1.21 crook 3668:
1.29 crook 3669: @example
3670: 6 + 5 * 4 =
3671: 4 * 5 + 6 =
3672: @end example
1.21 crook 3673:
1.29 crook 3674: If you're just learning maths or your maths is very rusty, you will
3675: probably come up with the answer 44 for the first and 26 for the
3676: second. If you are a bit of a whizz at maths you will remember the
3677: @i{convention} that multiplication takes precendence over addition, and
3678: you'd come up with the answer 26 both times. To explain the answer 26
3679: to someone who got the answer 44, you'd probably rewrite the first sum
3680: like this:
1.21 crook 3681:
1.29 crook 3682: @example
3683: 6 + (5 * 4) =
3684: @end example
1.21 crook 3685:
1.29 crook 3686: If what you really wanted was to perform the addition before the
3687: multiplication, you would have to use parentheses to force it.
1.21 crook 3688:
1.29 crook 3689: If you did the first two sums on a pocket calculator you would probably
3690: get the right answers, unless you were very cautious and entered them using
3691: these keystroke sequences:
1.21 crook 3692:
1.29 crook 3693: 6 + 5 = * 4 =
3694: 4 * 5 = + 6 =
1.21 crook 3695:
1.29 crook 3696: Postfix notation is unambiguous because the order that the operators
3697: are applied is always explicit; that also means that parentheses are
3698: never required. The operators are @i{active} (the act of quoting the
3699: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3700:
1.29 crook 3701: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3702: equivalent ways:
1.26 crook 3703:
3704: @example
1.29 crook 3705: 6 5 4 * + or:
3706: 5 4 * 6 +
1.26 crook 3707: @end example
1.23 crook 3708:
1.29 crook 3709: An important thing that you should notice about this notation is that
3710: the @i{order} of the numbers does not change; if you want to subtract
3711: 2 from 10 you type @code{10 2 -}.
1.1 anton 3712:
1.29 crook 3713: The reason that Forth uses postfix notation is very simple to explain: it
3714: makes the implementation extremely simple, and it follows naturally from
3715: using the stack as a mechanism for passing parameters. Another way of
3716: thinking about this is to realise that all Forth definitions are
3717: @i{active}; they execute as they are encountered by the text
3718: interpreter. The result of this is that the syntax of Forth is trivially
3719: simple.
1.1 anton 3720:
3721:
3722:
1.29 crook 3723: @comment ----------------------------------------------
3724: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3725: @section Your first Forth definition
3726: @cindex first definition
1.1 anton 3727:
1.29 crook 3728: Until now, the examples we've seen have been trivial; we've just been
3729: using Forth as a bigger-than-pocket calculator. Also, each calculation
3730: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3731: again@footnote{That's not quite true. If you press the up-arrow key on
3732: your keyboard you should be able to scroll back to any earlier command,
3733: edit it and re-enter it.} In this section we'll see how to add new
3734: words to Forth's vocabulary.
1.1 anton 3735:
1.29 crook 3736: The easiest way to create a new word is to use a @dfn{colon
3737: definition}. We'll define a few and try them out before worrying too
3738: much about how they work. Try typing in these examples; be careful to
3739: copy the spaces accurately:
1.1 anton 3740:
1.29 crook 3741: @example
3742: : add-two 2 + . ;
3743: : greet ." Hello and welcome" ;
3744: : demo 5 add-two ;
3745: @end example
1.1 anton 3746:
1.29 crook 3747: @noindent
3748: Now try them out:
1.1 anton 3749:
1.29 crook 3750: @example
1.30 anton 3751: @kbd{greet@key{RET}} Hello and welcome ok
3752: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3753: @kbd{4 add-two@key{RET}} 6 ok
3754: @kbd{demo@key{RET}} 7 ok
3755: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3756: @end example
1.1 anton 3757:
1.29 crook 3758: The first new thing that we've introduced here is the pair of words
3759: @code{:} and @code{;}. These are used to start and terminate a new
3760: definition, respectively. The first word after the @code{:} is the name
3761: for the new definition.
1.1 anton 3762:
1.29 crook 3763: As you can see from the examples, a definition is built up of words that
3764: have already been defined; Forth makes no distinction between
3765: definitions that existed when you started the system up, and those that
3766: you define yourself.
1.1 anton 3767:
1.29 crook 3768: The examples also introduce the words @code{.} (dot), @code{."}
3769: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3770: the stack and displays it. It's like @code{.s} except that it only
3771: displays the top item of the stack and it is destructive; after it has
3772: executed, the number is no longer on the stack. There is always one
3773: space printed after the number, and no spaces before it. Dot-quote
3774: defines a string (a sequence of characters) that will be printed when
3775: the word is executed. The string can contain any printable characters
3776: except @code{"}. A @code{"} has a special function; it is not a Forth
3777: word but it acts as a delimiter (the way that delimiters work is
3778: described in the next section). Finally, @code{dup} duplicates the value
3779: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3780:
1.29 crook 3781: We already know that the text interpreter searches through the
3782: dictionary to locate names. If you've followed the examples earlier, you
3783: will already have a definition called @code{add-two}. Lets try modifying
3784: it by typing in a new definition:
1.1 anton 3785:
1.29 crook 3786: @example
1.30 anton 3787: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3788: @end example
1.5 anton 3789:
1.29 crook 3790: Forth recognised that we were defining a word that already exists, and
3791: printed a message to warn us of that fact. Let's try out the new
3792: definition:
1.5 anton 3793:
1.29 crook 3794: @example
1.30 anton 3795: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3796: @end example
1.1 anton 3797:
1.29 crook 3798: @noindent
3799: All that we've actually done here, though, is to create a new
3800: definition, with a particular name. The fact that there was already a
3801: definition with the same name did not make any difference to the way
3802: that the new definition was created (except that Forth printed a warning
3803: message). The old definition of add-two still exists (try @code{demo}
3804: again to see that this is true). Any new definition will use the new
3805: definition of @code{add-two}, but old definitions continue to use the
3806: version that already existed at the time that they were @code{compiled}.
1.1 anton 3807:
1.29 crook 3808: Before you go on to the next section, try defining and redefining some
3809: words of your own.
1.1 anton 3810:
1.29 crook 3811: @comment ----------------------------------------------
3812: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3813: @section How does that work?
3814: @cindex parsing words
1.1 anton 3815:
1.30 anton 3816: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3817:
3818: @c Is it a good idea to talk about the interpretation semantics of a
3819: @c number? We don't have an xt to go along with it. - anton
3820:
3821: @c Now that I have eliminated execution semantics, I wonder if it would not
3822: @c be better to keep them (or add run-time semantics), to make it easier to
3823: @c explain what compilation semantics usually does. - anton
3824:
1.44 crook 3825: @c nac-> I removed the term ``default compilation sematics'' from the
3826: @c introductory chapter. Removing ``execution semantics'' was making
3827: @c everything simpler to explain, then I think the use of this term made
3828: @c everything more complex again. I replaced it with ``default
3829: @c semantics'' (which is used elsewhere in the manual) by which I mean
3830: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3831: @c flag set''.
3832:
3833: @c anton: I have eliminated default semantics (except in one place where it
3834: @c means "default interpretation and compilation semantics"), because it
3835: @c makes no sense in the presence of combined words. I reverted to
3836: @c "execution semantics" where necessary.
3837:
3838: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3839: @c section (and, unusually for me, I think I even made it shorter!). See
3840: @c what you think -- I know I have not addressed your primary concern
3841: @c that it is too heavy-going for an introduction. From what I understood
3842: @c of your course notes it looks as though they might be a good framework.
3843: @c Things that I've tried to capture here are some things that came as a
3844: @c great revelation here when I first understood them. Also, I like the
3845: @c fact that a very simple code example shows up almost all of the issues
3846: @c that you need to understand to see how Forth works. That's unique and
3847: @c worthwhile to emphasise.
3848:
1.83 anton 3849: @c anton: I think it's a good idea to present the details, especially those
3850: @c that you found to be a revelation, and probably the tutorial tries to be
3851: @c too superficial and does not get some of the things across that make
3852: @c Forth special. I do believe that most of the time these things should
3853: @c be discussed at the end of a section or in separate sections instead of
3854: @c in the middle of a section (e.g., the stuff you added in "User-defined
3855: @c defining words" leads in a completely different direction from the rest
3856: @c of the section).
3857:
1.29 crook 3858: Now we're going to take another look at the definition of @code{add-two}
3859: from the previous section. From our knowledge of the way that the text
3860: interpreter works, we would have expected this result when we tried to
3861: define @code{add-two}:
1.21 crook 3862:
1.29 crook 3863: @example
1.44 crook 3864: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3865: *the terminal*:4: Undefined word
3866: : >>>add-two<<< 2 + . ;
1.29 crook 3867: @end example
1.28 crook 3868:
1.29 crook 3869: The reason that this didn't happen is bound up in the way that @code{:}
3870: works. The word @code{:} does two special things. The first special
3871: thing that it does prevents the text interpreter from ever seeing the
3872: characters @code{add-two}. The text interpreter uses a variable called
3873: @cindex modifying >IN
1.44 crook 3874: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3875: input line. When it encounters the word @code{:} it behaves in exactly
3876: the same way as it does for any other word; it looks it up in the name
3877: dictionary, finds its xt and executes it. When @code{:} executes, it
3878: looks at the input buffer, finds the word @code{add-two} and advances the
3879: value of @code{>IN} to point past it. It then does some other stuff
3880: associated with creating the new definition (including creating an entry
3881: for @code{add-two} in the name dictionary). When the execution of @code{:}
3882: completes, control returns to the text interpreter, which is oblivious
3883: to the fact that it has been tricked into ignoring part of the input
3884: line.
1.21 crook 3885:
1.29 crook 3886: @cindex parsing words
3887: Words like @code{:} -- words that advance the value of @code{>IN} and so
3888: prevent the text interpreter from acting on the whole of the input line
3889: -- are called @dfn{parsing words}.
1.21 crook 3890:
1.29 crook 3891: @cindex @code{state} - effect on the text interpreter
3892: @cindex text interpreter - effect of state
3893: The second special thing that @code{:} does is change the value of a
3894: variable called @code{state}, which affects the way that the text
3895: interpreter behaves. When Gforth starts up, @code{state} has the value
3896: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3897: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3898: the text interpreter is said to be @dfn{compiling}.
3899:
3900: In this example, the text interpreter is compiling when it processes the
3901: string ``@code{2 + . ;}''. It still breaks the string down into
3902: character sequences in the same way. However, instead of pushing the
3903: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3904: into the definition of @code{add-two} that will make the number @code{2} get
3905: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3906: the behaviours of @code{+} and @code{.} are also compiled into the
3907: definition.
3908:
3909: One category of words don't get compiled. These so-called @dfn{immediate
3910: words} get executed (performed @i{now}) regardless of whether the text
3911: interpreter is interpreting or compiling. The word @code{;} is an
3912: immediate word. Rather than being compiled into the definition, it
3913: executes. Its effect is to terminate the current definition, which
3914: includes changing the value of @code{state} back to 0.
3915:
3916: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3917: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3918: definition.
1.28 crook 3919:
1.30 anton 3920: In Forth, every word or number can be described in terms of two
1.29 crook 3921: properties:
1.28 crook 3922:
3923: @itemize @bullet
3924: @item
1.29 crook 3925: @cindex interpretation semantics
1.44 crook 3926: Its @dfn{interpretation semantics} describe how it will behave when the
3927: text interpreter encounters it in @dfn{interpret} state. The
3928: interpretation semantics of a word are represented by an @dfn{execution
3929: token}.
1.28 crook 3930: @item
1.29 crook 3931: @cindex compilation semantics
1.44 crook 3932: Its @dfn{compilation semantics} describe how it will behave when the
3933: text interpreter encounters it in @dfn{compile} state. The compilation
3934: semantics of a word are represented in an implementation-dependent way;
3935: Gforth uses a @dfn{compilation token}.
1.29 crook 3936: @end itemize
3937:
3938: @noindent
3939: Numbers are always treated in a fixed way:
3940:
3941: @itemize @bullet
1.28 crook 3942: @item
1.44 crook 3943: When the number is @dfn{interpreted}, its behaviour is to push the
3944: number onto the stack.
1.28 crook 3945: @item
1.30 anton 3946: When the number is @dfn{compiled}, a piece of code is appended to the
3947: current definition that pushes the number when it runs. (In other words,
3948: the compilation semantics of a number are to postpone its interpretation
3949: semantics until the run-time of the definition that it is being compiled
3950: into.)
1.29 crook 3951: @end itemize
3952:
1.44 crook 3953: Words don't behave in such a regular way, but most have @i{default
3954: semantics} which means that they behave like this:
1.29 crook 3955:
3956: @itemize @bullet
1.28 crook 3957: @item
1.30 anton 3958: The @dfn{interpretation semantics} of the word are to do something useful.
3959: @item
1.29 crook 3960: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3961: @dfn{interpretation semantics} to the current definition (so that its
3962: run-time behaviour is to do something useful).
1.28 crook 3963: @end itemize
3964:
1.30 anton 3965: @cindex immediate words
1.44 crook 3966: The actual behaviour of any particular word can be controlled by using
3967: the words @code{immediate} and @code{compile-only} when the word is
3968: defined. These words set flags in the name dictionary entry of the most
3969: recently defined word, and these flags are retrieved by the text
3970: interpreter when it finds the word in the name dictionary.
3971:
3972: A word that is marked as @dfn{immediate} has compilation semantics that
3973: are identical to its interpretation semantics. In other words, it
3974: behaves like this:
1.29 crook 3975:
3976: @itemize @bullet
3977: @item
1.30 anton 3978: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3979: @item
1.30 anton 3980: The @dfn{compilation semantics} of the word are to do something useful
3981: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3982: @end itemize
1.28 crook 3983:
1.44 crook 3984: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3985: performing the interpretation semantics of the word directly; an attempt
3986: to do so will generate an error. It is never necessary to use
3987: @code{compile-only} (and it is not even part of ANS Forth, though it is
3988: provided by many implementations) but it is good etiquette to apply it
3989: to a word that will not behave correctly (and might have unexpected
3990: side-effects) in interpret state. For example, it is only legal to use
3991: the conditional word @code{IF} within a definition. If you forget this
3992: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3993: @code{compile-only} allows the text interpreter to generate a helpful
3994: error message rather than subjecting you to the consequences of your
3995: folly.
3996:
1.29 crook 3997: This example shows the difference between an immediate and a
3998: non-immediate word:
1.28 crook 3999:
1.29 crook 4000: @example
4001: : show-state state @@ . ;
4002: : show-state-now show-state ; immediate
4003: : word1 show-state ;
4004: : word2 show-state-now ;
1.28 crook 4005: @end example
1.23 crook 4006:
1.29 crook 4007: The word @code{immediate} after the definition of @code{show-state-now}
4008: makes that word an immediate word. These definitions introduce a new
4009: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4010: variable, and leaves it on the stack. Therefore, the behaviour of
4011: @code{show-state} is to print a number that represents the current value
4012: of @code{state}.
1.28 crook 4013:
1.29 crook 4014: When you execute @code{word1}, it prints the number 0, indicating that
4015: the system is interpreting. When the text interpreter compiled the
4016: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4017: compilation semantics are to append its interpretation semantics to the
1.29 crook 4018: current definition. When you execute @code{word1}, it performs the
1.30 anton 4019: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4020: (and therefore @code{show-state}) are executed, the system is
4021: interpreting.
1.28 crook 4022:
1.30 anton 4023: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4024: you should have seen the number -1 printed, followed by ``@code{
4025: ok}''. When the text interpreter compiled the definition of
4026: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4027: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4028: semantics. It is executed straight away (even before the text
4029: interpreter has moved on to process another group of characters; the
4030: @code{;} in this example). The effect of executing it are to display the
4031: value of @code{state} @i{at the time that the definition of}
4032: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4033: system is compiling at this time. If you execute @code{word2} it does
4034: nothing at all.
1.28 crook 4035:
1.29 crook 4036: @cindex @code{."}, how it works
4037: Before leaving the subject of immediate words, consider the behaviour of
4038: @code{."} in the definition of @code{greet}, in the previous
4039: section. This word is both a parsing word and an immediate word. Notice
4040: that there is a space between @code{."} and the start of the text
4041: @code{Hello and welcome}, but that there is no space between the last
4042: letter of @code{welcome} and the @code{"} character. The reason for this
4043: is that @code{."} is a Forth word; it must have a space after it so that
4044: the text interpreter can identify it. The @code{"} is not a Forth word;
4045: it is a @dfn{delimiter}. The examples earlier show that, when the string
4046: is displayed, there is neither a space before the @code{H} nor after the
4047: @code{e}. Since @code{."} is an immediate word, it executes at the time
4048: that @code{greet} is defined. When it executes, its behaviour is to
4049: search forward in the input line looking for the delimiter. When it
4050: finds the delimiter, it updates @code{>IN} to point past the
4051: delimiter. It also compiles some magic code into the definition of
4052: @code{greet}; the xt of a run-time routine that prints a text string. It
4053: compiles the string @code{Hello and welcome} into memory so that it is
4054: available to be printed later. When the text interpreter gains control,
4055: the next word it finds in the input stream is @code{;} and so it
4056: terminates the definition of @code{greet}.
1.28 crook 4057:
4058:
4059: @comment ----------------------------------------------
1.29 crook 4060: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4061: @section Forth is written in Forth
4062: @cindex structure of Forth programs
4063:
4064: When you start up a Forth compiler, a large number of definitions
4065: already exist. In Forth, you develop a new application using bottom-up
4066: programming techniques to create new definitions that are defined in
4067: terms of existing definitions. As you create each definition you can
4068: test and debug it interactively.
4069:
4070: If you have tried out the examples in this section, you will probably
4071: have typed them in by hand; when you leave Gforth, your definitions will
4072: be lost. You can avoid this by using a text editor to enter Forth source
4073: code into a file, and then loading code from the file using
1.49 anton 4074: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4075: processed by the text interpreter, just as though you had typed it in by
4076: hand@footnote{Actually, there are some subtle differences -- see
4077: @ref{The Text Interpreter}.}.
4078:
4079: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4080: files for program entry (@pxref{Blocks}).
1.28 crook 4081:
1.29 crook 4082: In common with many, if not most, Forth compilers, most of Gforth is
4083: actually written in Forth. All of the @file{.fs} files in the
4084: installation directory@footnote{For example,
1.30 anton 4085: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4086: study to see examples of Forth programming.
1.28 crook 4087:
1.29 crook 4088: Gforth maintains a history file that records every line that you type to
4089: the text interpreter. This file is preserved between sessions, and is
4090: used to provide a command-line recall facility. If you enter long
4091: definitions by hand, you can use a text editor to paste them out of the
4092: history file into a Forth source file for reuse at a later time
1.49 anton 4093: (for more information @pxref{Command-line editing}).
1.28 crook 4094:
4095:
4096: @comment ----------------------------------------------
1.29 crook 4097: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4098: @section Review - elements of a Forth system
4099: @cindex elements of a Forth system
1.28 crook 4100:
1.29 crook 4101: To summarise this chapter:
1.28 crook 4102:
4103: @itemize @bullet
4104: @item
1.29 crook 4105: Forth programs use @dfn{factoring} to break a problem down into small
4106: fragments called @dfn{words} or @dfn{definitions}.
4107: @item
4108: Forth program development is an interactive process.
4109: @item
4110: The main command loop that accepts input, and controls both
4111: interpretation and compilation, is called the @dfn{text interpreter}
4112: (also known as the @dfn{outer interpreter}).
4113: @item
4114: Forth has a very simple syntax, consisting of words and numbers
4115: separated by spaces or carriage-return characters. Any additional syntax
4116: is imposed by @dfn{parsing words}.
4117: @item
4118: Forth uses a stack to pass parameters between words. As a result, it
4119: uses postfix notation.
4120: @item
4121: To use a word that has previously been defined, the text interpreter
4122: searches for the word in the @dfn{name dictionary}.
4123: @item
1.30 anton 4124: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4125: @item
1.29 crook 4126: The text interpreter uses the value of @code{state} to select between
4127: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4128: semantics} of a word that it encounters.
1.28 crook 4129: @item
1.30 anton 4130: The relationship between the @dfn{interpretation semantics} and
4131: @dfn{compilation semantics} for a word
1.29 crook 4132: depend upon the way in which the word was defined (for example, whether
4133: it is an @dfn{immediate} word).
1.28 crook 4134: @item
1.29 crook 4135: Forth definitions can be implemented in Forth (called @dfn{high-level
4136: definitions}) or in some other way (usually a lower-level language and
4137: as a result often called @dfn{low-level definitions}, @dfn{code
4138: definitions} or @dfn{primitives}).
1.28 crook 4139: @item
1.29 crook 4140: Many Forth systems are implemented mainly in Forth.
1.28 crook 4141: @end itemize
4142:
4143:
1.29 crook 4144: @comment ----------------------------------------------
1.48 anton 4145: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4146: @section Where To Go Next
4147: @cindex where to go next
1.28 crook 4148:
1.29 crook 4149: Amazing as it may seem, if you have read (and understood) this far, you
4150: know almost all the fundamentals about the inner workings of a Forth
4151: system. You certainly know enough to be able to read and understand the
4152: rest of this manual and the ANS Forth document, to learn more about the
4153: facilities that Forth in general and Gforth in particular provide. Even
4154: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4155: However, that's not a good idea just yet... better to try writing some
1.29 crook 4156: programs in Gforth.
1.28 crook 4157:
1.29 crook 4158: Forth has such a rich vocabulary that it can be hard to know where to
4159: start in learning it. This section suggests a few sets of words that are
4160: enough to write small but useful programs. Use the word index in this
4161: document to learn more about each word, then try it out and try to write
4162: small definitions using it. Start by experimenting with these words:
1.28 crook 4163:
4164: @itemize @bullet
4165: @item
1.29 crook 4166: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4167: @item
4168: Comparison: @code{MIN MAX =}
4169: @item
4170: Logic: @code{AND OR XOR NOT}
4171: @item
4172: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4173: @item
1.29 crook 4174: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4175: @item
1.29 crook 4176: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4177: @item
1.29 crook 4178: Defining words: @code{: ; CREATE}
1.28 crook 4179: @item
1.29 crook 4180: Memory allocation words: @code{ALLOT ,}
1.28 crook 4181: @item
1.29 crook 4182: Tools: @code{SEE WORDS .S MARKER}
4183: @end itemize
4184:
4185: When you have mastered those, go on to:
4186:
4187: @itemize @bullet
1.28 crook 4188: @item
1.29 crook 4189: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4190: @item
1.29 crook 4191: Memory access: @code{@@ !}
1.28 crook 4192: @end itemize
1.23 crook 4193:
1.29 crook 4194: When you have mastered these, there's nothing for it but to read through
4195: the whole of this manual and find out what you've missed.
4196:
4197: @comment ----------------------------------------------
1.48 anton 4198: @node Exercises, , Where to go next, Introduction
1.29 crook 4199: @section Exercises
4200: @cindex exercises
4201:
4202: TODO: provide a set of programming excercises linked into the stuff done
4203: already and into other sections of the manual. Provide solutions to all
4204: the exercises in a .fs file in the distribution.
4205:
4206: @c Get some inspiration from Starting Forth and Kelly&Spies.
4207:
4208: @c excercises:
4209: @c 1. take inches and convert to feet and inches.
4210: @c 2. take temperature and convert from fahrenheight to celcius;
4211: @c may need to care about symmetric vs floored??
4212: @c 3. take input line and do character substitution
4213: @c to encipher or decipher
4214: @c 4. as above but work on a file for in and out
4215: @c 5. take input line and convert to pig-latin
4216: @c
4217: @c thing of sets of things to exercise then come up with
4218: @c problems that need those things.
4219:
4220:
1.26 crook 4221: @c ******************************************************************
1.29 crook 4222: @node Words, Error messages, Introduction, Top
1.1 anton 4223: @chapter Forth Words
1.26 crook 4224: @cindex words
1.1 anton 4225:
4226: @menu
4227: * Notation::
1.65 anton 4228: * Case insensitivity::
4229: * Comments::
4230: * Boolean Flags::
1.1 anton 4231: * Arithmetic::
4232: * Stack Manipulation::
1.5 anton 4233: * Memory::
1.1 anton 4234: * Control Structures::
4235: * Defining Words::
1.65 anton 4236: * Interpretation and Compilation Semantics::
1.47 crook 4237: * Tokens for Words::
1.81 anton 4238: * Compiling words::
1.65 anton 4239: * The Text Interpreter::
1.111 anton 4240: * The Input Stream::
1.65 anton 4241: * Word Lists::
4242: * Environmental Queries::
1.12 anton 4243: * Files::
4244: * Blocks::
4245: * Other I/O::
1.121 anton 4246: * OS command line arguments::
1.78 anton 4247: * Locals::
4248: * Structures::
4249: * Object-oriented Forth::
1.12 anton 4250: * Programming Tools::
4251: * Assembler and Code Words::
4252: * Threading Words::
1.65 anton 4253: * Passing Commands to the OS::
4254: * Keeping track of Time::
4255: * Miscellaneous Words::
1.1 anton 4256: @end menu
4257:
1.65 anton 4258: @node Notation, Case insensitivity, Words, Words
1.1 anton 4259: @section Notation
4260: @cindex notation of glossary entries
4261: @cindex format of glossary entries
4262: @cindex glossary notation format
4263: @cindex word glossary entry format
4264:
4265: The Forth words are described in this section in the glossary notation
1.67 anton 4266: that has become a de-facto standard for Forth texts:
1.1 anton 4267:
4268: @format
1.29 crook 4269: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4270: @end format
1.29 crook 4271: @i{Description}
1.1 anton 4272:
4273: @table @var
4274: @item word
1.28 crook 4275: The name of the word.
1.1 anton 4276:
4277: @item Stack effect
4278: @cindex stack effect
1.29 crook 4279: The stack effect is written in the notation @code{@i{before} --
4280: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4281: stack entries before and after the execution of the word. The rest of
4282: the stack is not touched by the word. The top of stack is rightmost,
4283: i.e., a stack sequence is written as it is typed in. Note that Gforth
4284: uses a separate floating point stack, but a unified stack
1.29 crook 4285: notation. Also, return stack effects are not shown in @i{stack
4286: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4287: the type and/or the function of the item. See below for a discussion of
4288: the types.
4289:
4290: All words have two stack effects: A compile-time stack effect and a
4291: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4292: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4293: this standard behaviour, or the word does other unusual things at
4294: compile time, both stack effects are shown; otherwise only the run-time
4295: stack effect is shown.
4296:
4297: @cindex pronounciation of words
4298: @item pronunciation
4299: How the word is pronounced.
4300:
4301: @cindex wordset
1.67 anton 4302: @cindex environment wordset
1.1 anton 4303: @item wordset
1.21 crook 4304: The ANS Forth standard is divided into several word sets. A standard
4305: system need not support all of them. Therefore, in theory, the fewer
4306: word sets your program uses the more portable it will be. However, we
4307: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4308: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4309: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4310: describes words that will work in future releases of Gforth;
4311: @code{gforth-internal} words are more volatile. Environmental query
4312: strings are also displayed like words; you can recognize them by the
1.21 crook 4313: @code{environment} in the word set field.
1.1 anton 4314:
4315: @item Description
4316: A description of the behaviour of the word.
4317: @end table
4318:
4319: @cindex types of stack items
4320: @cindex stack item types
4321: The type of a stack item is specified by the character(s) the name
4322: starts with:
4323:
4324: @table @code
4325: @item f
4326: @cindex @code{f}, stack item type
4327: Boolean flags, i.e. @code{false} or @code{true}.
4328: @item c
4329: @cindex @code{c}, stack item type
4330: Char
4331: @item w
4332: @cindex @code{w}, stack item type
4333: Cell, can contain an integer or an address
4334: @item n
4335: @cindex @code{n}, stack item type
4336: signed integer
4337: @item u
4338: @cindex @code{u}, stack item type
4339: unsigned integer
4340: @item d
4341: @cindex @code{d}, stack item type
4342: double sized signed integer
4343: @item ud
4344: @cindex @code{ud}, stack item type
4345: double sized unsigned integer
4346: @item r
4347: @cindex @code{r}, stack item type
4348: Float (on the FP stack)
1.21 crook 4349: @item a-
1.1 anton 4350: @cindex @code{a_}, stack item type
4351: Cell-aligned address
1.21 crook 4352: @item c-
1.1 anton 4353: @cindex @code{c_}, stack item type
4354: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4355: @item f-
1.1 anton 4356: @cindex @code{f_}, stack item type
4357: Float-aligned address
1.21 crook 4358: @item df-
1.1 anton 4359: @cindex @code{df_}, stack item type
4360: Address aligned for IEEE double precision float
1.21 crook 4361: @item sf-
1.1 anton 4362: @cindex @code{sf_}, stack item type
4363: Address aligned for IEEE single precision float
4364: @item xt
4365: @cindex @code{xt}, stack item type
4366: Execution token, same size as Cell
4367: @item wid
4368: @cindex @code{wid}, stack item type
1.21 crook 4369: Word list ID, same size as Cell
1.68 anton 4370: @item ior, wior
4371: @cindex ior type description
4372: @cindex wior type description
4373: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4374: @item f83name
4375: @cindex @code{f83name}, stack item type
4376: Pointer to a name structure
4377: @item "
4378: @cindex @code{"}, stack item type
1.12 anton 4379: string in the input stream (not on the stack). The terminating character
4380: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4381: quotes.
4382: @end table
4383:
1.65 anton 4384: @comment ----------------------------------------------
4385: @node Case insensitivity, Comments, Notation, Words
4386: @section Case insensitivity
4387: @cindex case sensitivity
4388: @cindex upper and lower case
4389:
4390: Gforth is case-insensitive; you can enter definitions and invoke
4391: Standard words using upper, lower or mixed case (however,
4392: @pxref{core-idef, Implementation-defined options, Implementation-defined
4393: options}).
4394:
4395: ANS Forth only @i{requires} implementations to recognise Standard words
4396: when they are typed entirely in upper case. Therefore, a Standard
4397: program must use upper case for all Standard words. You can use whatever
4398: case you like for words that you define, but in a Standard program you
4399: have to use the words in the same case that you defined them.
4400:
4401: Gforth supports case sensitivity through @code{table}s (case-sensitive
4402: wordlists, @pxref{Word Lists}).
4403:
4404: Two people have asked how to convert Gforth to be case-sensitive; while
4405: we think this is a bad idea, you can change all wordlists into tables
4406: like this:
4407:
4408: @example
4409: ' table-find forth-wordlist wordlist-map @ !
4410: @end example
4411:
4412: Note that you now have to type the predefined words in the same case
4413: that we defined them, which are varying. You may want to convert them
4414: to your favourite case before doing this operation (I won't explain how,
4415: because if you are even contemplating doing this, you'd better have
4416: enough knowledge of Forth systems to know this already).
4417:
4418: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4419: @section Comments
1.26 crook 4420: @cindex comments
1.21 crook 4421:
1.29 crook 4422: Forth supports two styles of comment; the traditional @i{in-line} comment,
4423: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4424:
1.44 crook 4425:
1.23 crook 4426: doc-(
1.21 crook 4427: doc-\
1.23 crook 4428: doc-\G
1.21 crook 4429:
1.44 crook 4430:
1.21 crook 4431: @node Boolean Flags, Arithmetic, Comments, Words
4432: @section Boolean Flags
1.26 crook 4433: @cindex Boolean flags
1.21 crook 4434:
4435: A Boolean flag is cell-sized. A cell with all bits clear represents the
4436: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4437: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4438: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4439: @c on and off to Memory?
4440: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4441:
1.21 crook 4442: doc-true
4443: doc-false
1.29 crook 4444: doc-on
4445: doc-off
1.21 crook 4446:
1.44 crook 4447:
1.21 crook 4448: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4449: @section Arithmetic
4450: @cindex arithmetic words
4451:
4452: @cindex division with potentially negative operands
4453: Forth arithmetic is not checked, i.e., you will not hear about integer
4454: overflow on addition or multiplication, you may hear about division by
4455: zero if you are lucky. The operator is written after the operands, but
4456: the operands are still in the original order. I.e., the infix @code{2-1}
4457: corresponds to @code{2 1 -}. Forth offers a variety of division
4458: operators. If you perform division with potentially negative operands,
4459: you do not want to use @code{/} or @code{/mod} with its undefined
4460: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4461: former, @pxref{Mixed precision}).
1.26 crook 4462: @comment TODO discuss the different division forms and the std approach
1.1 anton 4463:
4464: @menu
4465: * Single precision::
1.67 anton 4466: * Double precision:: Double-cell integer arithmetic
1.1 anton 4467: * Bitwise operations::
1.67 anton 4468: * Numeric comparison::
1.29 crook 4469: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4470: * Floating Point::
4471: @end menu
4472:
1.67 anton 4473: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4474: @subsection Single precision
4475: @cindex single precision arithmetic words
4476:
1.67 anton 4477: @c !! cell undefined
4478:
4479: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4480: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4481: treat them. For the rules used by the text interpreter for recognising
4482: single-precision integers see @ref{Number Conversion}.
1.21 crook 4483:
1.67 anton 4484: These words are all defined for signed operands, but some of them also
4485: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4486: @code{*}.
1.44 crook 4487:
1.1 anton 4488: doc-+
1.21 crook 4489: doc-1+
1.128 anton 4490: doc-under+
1.1 anton 4491: doc--
1.21 crook 4492: doc-1-
1.1 anton 4493: doc-*
4494: doc-/
4495: doc-mod
4496: doc-/mod
4497: doc-negate
4498: doc-abs
4499: doc-min
4500: doc-max
1.27 crook 4501: doc-floored
1.1 anton 4502:
1.44 crook 4503:
1.67 anton 4504: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4505: @subsection Double precision
4506: @cindex double precision arithmetic words
4507:
1.49 anton 4508: For the rules used by the text interpreter for
4509: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4510:
4511: A double precision number is represented by a cell pair, with the most
1.67 anton 4512: significant cell at the TOS. It is trivial to convert an unsigned single
4513: to a double: simply push a @code{0} onto the TOS. Since numbers are
4514: represented by Gforth using 2's complement arithmetic, converting a
4515: signed single to a (signed) double requires sign-extension across the
4516: most significant cell. This can be achieved using @code{s>d}. The moral
4517: of the story is that you cannot convert a number without knowing whether
4518: it represents an unsigned or a signed number.
1.21 crook 4519:
1.67 anton 4520: These words are all defined for signed operands, but some of them also
4521: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4522:
1.21 crook 4523: doc-s>d
1.67 anton 4524: doc-d>s
1.21 crook 4525: doc-d+
4526: doc-d-
4527: doc-dnegate
4528: doc-dabs
4529: doc-dmin
4530: doc-dmax
4531:
1.44 crook 4532:
1.67 anton 4533: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4534: @subsection Bitwise operations
4535: @cindex bitwise operation words
4536:
4537:
4538: doc-and
4539: doc-or
4540: doc-xor
4541: doc-invert
4542: doc-lshift
4543: doc-rshift
4544: doc-2*
4545: doc-d2*
4546: doc-2/
4547: doc-d2/
4548:
4549:
4550: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4551: @subsection Numeric comparison
4552: @cindex numeric comparison words
4553:
1.67 anton 4554: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4555: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4556:
1.28 crook 4557: doc-<
4558: doc-<=
4559: doc-<>
4560: doc-=
4561: doc->
4562: doc->=
4563:
1.21 crook 4564: doc-0<
1.23 crook 4565: doc-0<=
1.21 crook 4566: doc-0<>
4567: doc-0=
1.23 crook 4568: doc-0>
4569: doc-0>=
1.28 crook 4570:
4571: doc-u<
4572: doc-u<=
1.44 crook 4573: @c u<> and u= exist but are the same as <> and =
1.31 anton 4574: @c doc-u<>
4575: @c doc-u=
1.28 crook 4576: doc-u>
4577: doc-u>=
4578:
4579: doc-within
4580:
4581: doc-d<
4582: doc-d<=
4583: doc-d<>
4584: doc-d=
4585: doc-d>
4586: doc-d>=
1.23 crook 4587:
1.21 crook 4588: doc-d0<
1.23 crook 4589: doc-d0<=
4590: doc-d0<>
1.21 crook 4591: doc-d0=
1.23 crook 4592: doc-d0>
4593: doc-d0>=
4594:
1.21 crook 4595: doc-du<
1.28 crook 4596: doc-du<=
1.44 crook 4597: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4598: @c doc-du<>
4599: @c doc-du=
1.28 crook 4600: doc-du>
4601: doc-du>=
1.1 anton 4602:
1.44 crook 4603:
1.21 crook 4604: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4605: @subsection Mixed precision
4606: @cindex mixed precision arithmetic words
4607:
1.44 crook 4608:
1.1 anton 4609: doc-m+
4610: doc-*/
4611: doc-*/mod
4612: doc-m*
4613: doc-um*
4614: doc-m*/
4615: doc-um/mod
4616: doc-fm/mod
4617: doc-sm/rem
4618:
1.44 crook 4619:
1.21 crook 4620: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4621: @subsection Floating Point
4622: @cindex floating point arithmetic words
4623:
1.49 anton 4624: For the rules used by the text interpreter for
4625: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4626:
1.67 anton 4627: Gforth has a separate floating point stack, but the documentation uses
4628: the unified notation.@footnote{It's easy to generate the separate
4629: notation from that by just separating the floating-point numbers out:
4630: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4631: r3 )}.}
1.1 anton 4632:
4633: @cindex floating-point arithmetic, pitfalls
4634: Floating point numbers have a number of unpleasant surprises for the
4635: unwary (e.g., floating point addition is not associative) and even a few
4636: for the wary. You should not use them unless you know what you are doing
4637: or you don't care that the results you get are totally bogus. If you
4638: want to learn about the problems of floating point numbers (and how to
1.66 anton 4639: avoid them), you might start with @cite{David Goldberg,
4640: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4641: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4642: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4643:
1.44 crook 4644:
1.21 crook 4645: doc-d>f
4646: doc-f>d
1.1 anton 4647: doc-f+
4648: doc-f-
4649: doc-f*
4650: doc-f/
4651: doc-fnegate
4652: doc-fabs
4653: doc-fmax
4654: doc-fmin
4655: doc-floor
4656: doc-fround
4657: doc-f**
4658: doc-fsqrt
4659: doc-fexp
4660: doc-fexpm1
4661: doc-fln
4662: doc-flnp1
4663: doc-flog
4664: doc-falog
1.32 anton 4665: doc-f2*
4666: doc-f2/
4667: doc-1/f
4668: doc-precision
4669: doc-set-precision
4670:
4671: @cindex angles in trigonometric operations
4672: @cindex trigonometric operations
4673: Angles in floating point operations are given in radians (a full circle
4674: has 2 pi radians).
4675:
1.1 anton 4676: doc-fsin
4677: doc-fcos
4678: doc-fsincos
4679: doc-ftan
4680: doc-fasin
4681: doc-facos
4682: doc-fatan
4683: doc-fatan2
4684: doc-fsinh
4685: doc-fcosh
4686: doc-ftanh
4687: doc-fasinh
4688: doc-facosh
4689: doc-fatanh
1.21 crook 4690: doc-pi
1.28 crook 4691:
1.32 anton 4692: @cindex equality of floats
4693: @cindex floating-point comparisons
1.31 anton 4694: One particular problem with floating-point arithmetic is that comparison
4695: for equality often fails when you would expect it to succeed. For this
4696: reason approximate equality is often preferred (but you still have to
1.67 anton 4697: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4698: differently from what you might expect. The comparison words are:
1.31 anton 4699:
4700: doc-f~rel
4701: doc-f~abs
1.68 anton 4702: doc-f~
1.31 anton 4703: doc-f=
4704: doc-f<>
4705:
4706: doc-f<
4707: doc-f<=
4708: doc-f>
4709: doc-f>=
4710:
1.21 crook 4711: doc-f0<
1.28 crook 4712: doc-f0<=
4713: doc-f0<>
1.21 crook 4714: doc-f0=
1.28 crook 4715: doc-f0>
4716: doc-f0>=
4717:
1.1 anton 4718:
4719: @node Stack Manipulation, Memory, Arithmetic, Words
4720: @section Stack Manipulation
4721: @cindex stack manipulation words
4722:
4723: @cindex floating-point stack in the standard
1.21 crook 4724: Gforth maintains a number of separate stacks:
4725:
1.29 crook 4726: @cindex data stack
4727: @cindex parameter stack
1.21 crook 4728: @itemize @bullet
4729: @item
1.29 crook 4730: A data stack (also known as the @dfn{parameter stack}) -- for
4731: characters, cells, addresses, and double cells.
1.21 crook 4732:
1.29 crook 4733: @cindex floating-point stack
1.21 crook 4734: @item
1.44 crook 4735: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4736:
1.29 crook 4737: @cindex return stack
1.21 crook 4738: @item
1.44 crook 4739: A return stack -- for holding the return addresses of colon
1.32 anton 4740: definitions and other (non-FP) data.
1.21 crook 4741:
1.29 crook 4742: @cindex locals stack
1.21 crook 4743: @item
1.44 crook 4744: A locals stack -- for holding local variables.
1.21 crook 4745: @end itemize
4746:
1.1 anton 4747: @menu
4748: * Data stack::
4749: * Floating point stack::
4750: * Return stack::
4751: * Locals stack::
4752: * Stack pointer manipulation::
4753: @end menu
4754:
4755: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4756: @subsection Data stack
4757: @cindex data stack manipulation words
4758: @cindex stack manipulations words, data stack
4759:
1.44 crook 4760:
1.1 anton 4761: doc-drop
4762: doc-nip
4763: doc-dup
4764: doc-over
4765: doc-tuck
4766: doc-swap
1.21 crook 4767: doc-pick
1.1 anton 4768: doc-rot
4769: doc--rot
4770: doc-?dup
4771: doc-roll
4772: doc-2drop
4773: doc-2nip
4774: doc-2dup
4775: doc-2over
4776: doc-2tuck
4777: doc-2swap
4778: doc-2rot
4779:
1.44 crook 4780:
1.1 anton 4781: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4782: @subsection Floating point stack
4783: @cindex floating-point stack manipulation words
4784: @cindex stack manipulation words, floating-point stack
4785:
1.32 anton 4786: Whilst every sane Forth has a separate floating-point stack, it is not
4787: strictly required; an ANS Forth system could theoretically keep
4788: floating-point numbers on the data stack. As an additional difficulty,
4789: you don't know how many cells a floating-point number takes. It is
4790: reportedly possible to write words in a way that they work also for a
4791: unified stack model, but we do not recommend trying it. Instead, just
4792: say that your program has an environmental dependency on a separate
4793: floating-point stack.
4794:
4795: doc-floating-stack
4796:
1.1 anton 4797: doc-fdrop
4798: doc-fnip
4799: doc-fdup
4800: doc-fover
4801: doc-ftuck
4802: doc-fswap
1.21 crook 4803: doc-fpick
1.1 anton 4804: doc-frot
4805:
1.44 crook 4806:
1.1 anton 4807: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4808: @subsection Return stack
4809: @cindex return stack manipulation words
4810: @cindex stack manipulation words, return stack
4811:
1.32 anton 4812: @cindex return stack and locals
4813: @cindex locals and return stack
4814: A Forth system is allowed to keep local variables on the
4815: return stack. This is reasonable, as local variables usually eliminate
4816: the need to use the return stack explicitly. So, if you want to produce
4817: a standard compliant program and you are using local variables in a
4818: word, forget about return stack manipulations in that word (refer to the
4819: standard document for the exact rules).
4820:
1.1 anton 4821: doc->r
4822: doc-r>
4823: doc-r@
4824: doc-rdrop
4825: doc-2>r
4826: doc-2r>
4827: doc-2r@
4828: doc-2rdrop
4829:
1.44 crook 4830:
1.1 anton 4831: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4832: @subsection Locals stack
4833:
1.78 anton 4834: Gforth uses an extra locals stack. It is described, along with the
4835: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4836:
1.1 anton 4837: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4838: @subsection Stack pointer manipulation
4839: @cindex stack pointer manipulation words
4840:
1.44 crook 4841: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4842: doc-sp0
1.1 anton 4843: doc-sp@
4844: doc-sp!
1.21 crook 4845: doc-fp0
1.1 anton 4846: doc-fp@
4847: doc-fp!
1.21 crook 4848: doc-rp0
1.1 anton 4849: doc-rp@
4850: doc-rp!
1.21 crook 4851: doc-lp0
1.1 anton 4852: doc-lp@
4853: doc-lp!
4854:
1.44 crook 4855:
1.1 anton 4856: @node Memory, Control Structures, Stack Manipulation, Words
4857: @section Memory
1.26 crook 4858: @cindex memory words
1.1 anton 4859:
1.32 anton 4860: @menu
4861: * Memory model::
4862: * Dictionary allocation::
4863: * Heap Allocation::
4864: * Memory Access::
4865: * Address arithmetic::
4866: * Memory Blocks::
4867: @end menu
4868:
1.67 anton 4869: In addition to the standard Forth memory allocation words, there is also
4870: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4871: garbage collector}.
4872:
1.32 anton 4873: @node Memory model, Dictionary allocation, Memory, Memory
4874: @subsection ANS Forth and Gforth memory models
4875:
4876: @c The ANS Forth description is a mess (e.g., is the heap part of
4877: @c the dictionary?), so let's not stick to closely with it.
4878:
1.67 anton 4879: ANS Forth considers a Forth system as consisting of several address
4880: spaces, of which only @dfn{data space} is managed and accessible with
4881: the memory words. Memory not necessarily in data space includes the
4882: stacks, the code (called code space) and the headers (called name
4883: space). In Gforth everything is in data space, but the code for the
4884: primitives is usually read-only.
1.32 anton 4885:
4886: Data space is divided into a number of areas: The (data space portion of
4887: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4888: refer to the search data structure embodied in word lists and headers,
4889: because it is used for looking up names, just as you would in a
4890: conventional dictionary.}, the heap, and a number of system-allocated
4891: buffers.
4892:
1.68 anton 4893: @cindex address arithmetic restrictions, ANS vs. Gforth
4894: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4895: In ANS Forth data space is also divided into contiguous regions. You
4896: can only use address arithmetic within a contiguous region, not between
4897: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4898: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4899: allocation}).
4900:
4901: Gforth provides one big address space, and address arithmetic can be
4902: performed between any addresses. However, in the dictionary headers or
4903: code are interleaved with data, so almost the only contiguous data space
4904: regions there are those described by ANS Forth as contiguous; but you
4905: can be sure that the dictionary is allocated towards increasing
4906: addresses even between contiguous regions. The memory order of
4907: allocations in the heap is platform-dependent (and possibly different
4908: from one run to the next).
4909:
1.27 crook 4910:
1.32 anton 4911: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4912: @subsection Dictionary allocation
1.27 crook 4913: @cindex reserving data space
4914: @cindex data space - reserving some
4915:
1.32 anton 4916: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4917: you want to deallocate X, you also deallocate everything
4918: allocated after X.
4919:
1.68 anton 4920: @cindex contiguous regions in dictionary allocation
1.32 anton 4921: The allocations using the words below are contiguous and grow the region
4922: towards increasing addresses. Other words that allocate dictionary
4923: memory of any kind (i.e., defining words including @code{:noname}) end
4924: the contiguous region and start a new one.
4925:
4926: In ANS Forth only @code{create}d words are guaranteed to produce an
4927: address that is the start of the following contiguous region. In
4928: particular, the cell allocated by @code{variable} is not guaranteed to
4929: be contiguous with following @code{allot}ed memory.
4930:
4931: You can deallocate memory by using @code{allot} with a negative argument
4932: (with some restrictions, see @code{allot}). For larger deallocations use
4933: @code{marker}.
1.27 crook 4934:
1.29 crook 4935:
1.27 crook 4936: doc-here
4937: doc-unused
4938: doc-allot
4939: doc-c,
1.29 crook 4940: doc-f,
1.27 crook 4941: doc-,
4942: doc-2,
4943:
1.32 anton 4944: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4945: course you should allocate memory in an aligned way, too. I.e., before
4946: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4947: The words below align @code{here} if it is not already. Basically it is
4948: only already aligned for a type, if the last allocation was a multiple
4949: of the size of this type and if @code{here} was aligned for this type
4950: before.
4951:
4952: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4953: ANS Forth (@code{maxalign}ed in Gforth).
4954:
4955: doc-align
4956: doc-falign
4957: doc-sfalign
4958: doc-dfalign
4959: doc-maxalign
4960: doc-cfalign
4961:
4962:
4963: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4964: @subsection Heap allocation
4965: @cindex heap allocation
4966: @cindex dynamic allocation of memory
4967: @cindex memory-allocation word set
4968:
1.68 anton 4969: @cindex contiguous regions and heap allocation
1.32 anton 4970: Heap allocation supports deallocation of allocated memory in any
4971: order. Dictionary allocation is not affected by it (i.e., it does not
4972: end a contiguous region). In Gforth, these words are implemented using
4973: the standard C library calls malloc(), free() and resize().
4974:
1.68 anton 4975: The memory region produced by one invocation of @code{allocate} or
4976: @code{resize} is internally contiguous. There is no contiguity between
4977: such a region and any other region (including others allocated from the
4978: heap).
4979:
1.32 anton 4980: doc-allocate
4981: doc-free
4982: doc-resize
4983:
1.27 crook 4984:
1.32 anton 4985: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4986: @subsection Memory Access
4987: @cindex memory access words
4988:
4989: doc-@
4990: doc-!
4991: doc-+!
4992: doc-c@
4993: doc-c!
4994: doc-2@
4995: doc-2!
4996: doc-f@
4997: doc-f!
4998: doc-sf@
4999: doc-sf!
5000: doc-df@
5001: doc-df!
1.144 anton 5002: doc-sw@
5003: doc-uw@
5004: doc-w!
5005: doc-sl@
5006: doc-ul@
5007: doc-l!
1.68 anton 5008:
1.32 anton 5009: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5010: @subsection Address arithmetic
1.1 anton 5011: @cindex address arithmetic words
5012:
1.67 anton 5013: Address arithmetic is the foundation on which you can build data
5014: structures like arrays, records (@pxref{Structures}) and objects
5015: (@pxref{Object-oriented Forth}).
1.32 anton 5016:
1.68 anton 5017: @cindex address unit
5018: @cindex au (address unit)
1.1 anton 5019: ANS Forth does not specify the sizes of the data types. Instead, it
5020: offers a number of words for computing sizes and doing address
1.29 crook 5021: arithmetic. Address arithmetic is performed in terms of address units
5022: (aus); on most systems the address unit is one byte. Note that a
5023: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5024: platforms where it is a noop, it compiles to nothing).
1.1 anton 5025:
1.67 anton 5026: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5027: you have the address of a cell, perform @code{1 cells +}, and you will
5028: have the address of the next cell.
5029:
1.68 anton 5030: @cindex contiguous regions and address arithmetic
1.67 anton 5031: In ANS Forth you can perform address arithmetic only within a contiguous
5032: region, i.e., if you have an address into one region, you can only add
5033: and subtract such that the result is still within the region; you can
5034: only subtract or compare addresses from within the same contiguous
5035: region. Reasons: several contiguous regions can be arranged in memory
5036: in any way; on segmented systems addresses may have unusual
5037: representations, such that address arithmetic only works within a
5038: region. Gforth provides a few more guarantees (linear address space,
5039: dictionary grows upwards), but in general I have found it easy to stay
5040: within contiguous regions (exception: computing and comparing to the
5041: address just beyond the end of an array).
5042:
1.1 anton 5043: @cindex alignment of addresses for types
5044: ANS Forth also defines words for aligning addresses for specific
5045: types. Many computers require that accesses to specific data types
5046: must only occur at specific addresses; e.g., that cells may only be
5047: accessed at addresses divisible by 4. Even if a machine allows unaligned
5048: accesses, it can usually perform aligned accesses faster.
5049:
5050: For the performance-conscious: alignment operations are usually only
5051: necessary during the definition of a data structure, not during the
5052: (more frequent) accesses to it.
5053:
5054: ANS Forth defines no words for character-aligning addresses. This is not
5055: an oversight, but reflects the fact that addresses that are not
5056: char-aligned have no use in the standard and therefore will not be
5057: created.
5058:
5059: @cindex @code{CREATE} and alignment
1.29 crook 5060: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5061: are cell-aligned; in addition, Gforth guarantees that these addresses
5062: are aligned for all purposes.
5063:
1.26 crook 5064: Note that the ANS Forth word @code{char} has nothing to do with address
5065: arithmetic.
1.1 anton 5066:
1.44 crook 5067:
1.1 anton 5068: doc-chars
5069: doc-char+
5070: doc-cells
5071: doc-cell+
5072: doc-cell
5073: doc-aligned
5074: doc-floats
5075: doc-float+
5076: doc-float
5077: doc-faligned
5078: doc-sfloats
5079: doc-sfloat+
5080: doc-sfaligned
5081: doc-dfloats
5082: doc-dfloat+
5083: doc-dfaligned
5084: doc-maxaligned
5085: doc-cfaligned
5086: doc-address-unit-bits
1.145 anton 5087: doc-/w
5088: doc-/l
1.44 crook 5089:
1.32 anton 5090: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5091: @subsection Memory Blocks
5092: @cindex memory block words
1.27 crook 5093: @cindex character strings - moving and copying
5094:
1.49 anton 5095: Memory blocks often represent character strings; For ways of storing
5096: character strings in memory see @ref{String Formats}. For other
5097: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5098:
1.67 anton 5099: A few of these words work on address unit blocks. In that case, you
5100: usually have to insert @code{CHARS} before the word when working on
5101: character strings. Most words work on character blocks, and expect a
5102: char-aligned address.
5103:
5104: When copying characters between overlapping memory regions, use
5105: @code{chars move} or choose carefully between @code{cmove} and
5106: @code{cmove>}.
1.44 crook 5107:
1.1 anton 5108: doc-move
5109: doc-erase
5110: doc-cmove
5111: doc-cmove>
5112: doc-fill
5113: doc-blank
1.21 crook 5114: doc-compare
1.111 anton 5115: doc-str=
5116: doc-str<
5117: doc-string-prefix?
1.21 crook 5118: doc-search
1.27 crook 5119: doc--trailing
5120: doc-/string
1.82 anton 5121: doc-bounds
1.141 anton 5122: doc-pad
1.111 anton 5123:
1.27 crook 5124: @comment TODO examples
5125:
1.1 anton 5126:
1.26 crook 5127: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5128: @section Control Structures
5129: @cindex control structures
5130:
1.33 anton 5131: Control structures in Forth cannot be used interpretively, only in a
5132: colon definition@footnote{To be precise, they have no interpretation
5133: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5134: not like this limitation, but have not seen a satisfying way around it
5135: yet, although many schemes have been proposed.
1.1 anton 5136:
5137: @menu
1.33 anton 5138: * Selection:: IF ... ELSE ... ENDIF
5139: * Simple Loops:: BEGIN ...
1.29 crook 5140: * Counted Loops:: DO
1.67 anton 5141: * Arbitrary control structures::
5142: * Calls and returns::
1.1 anton 5143: * Exception Handling::
5144: @end menu
5145:
5146: @node Selection, Simple Loops, Control Structures, Control Structures
5147: @subsection Selection
5148: @cindex selection control structures
5149: @cindex control structures for selection
5150:
5151: @cindex @code{IF} control structure
5152: @example
1.29 crook 5153: @i{flag}
1.1 anton 5154: IF
1.29 crook 5155: @i{code}
1.1 anton 5156: ENDIF
5157: @end example
1.21 crook 5158: @noindent
1.33 anton 5159:
1.44 crook 5160: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5161: with any bit set represents truth) @i{code} is executed.
1.33 anton 5162:
1.1 anton 5163: @example
1.29 crook 5164: @i{flag}
1.1 anton 5165: IF
1.29 crook 5166: @i{code1}
1.1 anton 5167: ELSE
1.29 crook 5168: @i{code2}
1.1 anton 5169: ENDIF
5170: @end example
5171:
1.44 crook 5172: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5173: executed.
1.33 anton 5174:
1.1 anton 5175: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5176: standard, and @code{ENDIF} is not, although it is quite popular. We
5177: recommend using @code{ENDIF}, because it is less confusing for people
5178: who also know other languages (and is not prone to reinforcing negative
5179: prejudices against Forth in these people). Adding @code{ENDIF} to a
5180: system that only supplies @code{THEN} is simple:
5181: @example
1.82 anton 5182: : ENDIF POSTPONE then ; immediate
1.1 anton 5183: @end example
5184:
5185: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5186: (adv.)} has the following meanings:
5187: @quotation
5188: ... 2b: following next after in order ... 3d: as a necessary consequence
5189: (if you were there, then you saw them).
5190: @end quotation
5191: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5192: and many other programming languages has the meaning 3d.]
5193:
1.21 crook 5194: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5195: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5196: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5197: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5198: @file{compat/control.fs}.
5199:
5200: @cindex @code{CASE} control structure
5201: @example
1.29 crook 5202: @i{n}
1.1 anton 5203: CASE
1.29 crook 5204: @i{n1} OF @i{code1} ENDOF
5205: @i{n2} OF @i{code2} ENDOF
1.1 anton 5206: @dots{}
1.68 anton 5207: ( n ) @i{default-code} ( n )
1.131 anton 5208: ENDCASE ( )
1.1 anton 5209: @end example
5210:
1.131 anton 5211: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5212: no @i{ni} matches, the optional @i{default-code} is executed. The
5213: optional default case can be added by simply writing the code after
5214: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5215: but must not consume it. The value @i{n} is consumed by this
5216: construction (either by a OF that matches, or by the ENDCASE, if no OF
5217: matches).
1.1 anton 5218:
1.69 anton 5219: @progstyle
1.131 anton 5220: To keep the code understandable, you should ensure that you change the
5221: stack in the same way (wrt. number and types of stack items consumed
5222: and pushed) on all paths through a selection construct.
1.69 anton 5223:
1.1 anton 5224: @node Simple Loops, Counted Loops, Selection, Control Structures
5225: @subsection Simple Loops
5226: @cindex simple loops
5227: @cindex loops without count
5228:
5229: @cindex @code{WHILE} loop
5230: @example
5231: BEGIN
1.29 crook 5232: @i{code1}
5233: @i{flag}
1.1 anton 5234: WHILE
1.29 crook 5235: @i{code2}
1.1 anton 5236: REPEAT
5237: @end example
5238:
1.29 crook 5239: @i{code1} is executed and @i{flag} is computed. If it is true,
5240: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5241: false, execution continues after the @code{REPEAT}.
5242:
5243: @cindex @code{UNTIL} loop
5244: @example
5245: BEGIN
1.29 crook 5246: @i{code}
5247: @i{flag}
1.1 anton 5248: UNTIL
5249: @end example
5250:
1.29 crook 5251: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5252:
1.69 anton 5253: @progstyle
5254: To keep the code understandable, a complete iteration of the loop should
5255: not change the number and types of the items on the stacks.
5256:
1.1 anton 5257: @cindex endless loop
5258: @cindex loops, endless
5259: @example
5260: BEGIN
1.29 crook 5261: @i{code}
1.1 anton 5262: AGAIN
5263: @end example
5264:
5265: This is an endless loop.
5266:
5267: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5268: @subsection Counted Loops
5269: @cindex counted loops
5270: @cindex loops, counted
5271: @cindex @code{DO} loops
5272:
5273: The basic counted loop is:
5274: @example
1.29 crook 5275: @i{limit} @i{start}
1.1 anton 5276: ?DO
1.29 crook 5277: @i{body}
1.1 anton 5278: LOOP
5279: @end example
5280:
1.29 crook 5281: This performs one iteration for every integer, starting from @i{start}
5282: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5283: accessed with @code{i}. For example, the loop:
1.1 anton 5284: @example
5285: 10 0 ?DO
5286: i .
5287: LOOP
5288: @end example
1.21 crook 5289: @noindent
5290: prints @code{0 1 2 3 4 5 6 7 8 9}
5291:
1.1 anton 5292: The index of the innermost loop can be accessed with @code{i}, the index
5293: of the next loop with @code{j}, and the index of the third loop with
5294: @code{k}.
5295:
1.44 crook 5296:
1.1 anton 5297: doc-i
5298: doc-j
5299: doc-k
5300:
1.44 crook 5301:
1.1 anton 5302: The loop control data are kept on the return stack, so there are some
1.21 crook 5303: restrictions on mixing return stack accesses and counted loop words. In
5304: particuler, if you put values on the return stack outside the loop, you
5305: cannot read them inside the loop@footnote{well, not in a way that is
5306: portable.}. If you put values on the return stack within a loop, you
5307: have to remove them before the end of the loop and before accessing the
5308: index of the loop.
1.1 anton 5309:
5310: There are several variations on the counted loop:
5311:
1.21 crook 5312: @itemize @bullet
5313: @item
5314: @code{LEAVE} leaves the innermost counted loop immediately; execution
5315: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5316:
5317: @example
5318: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5319: @end example
5320: prints @code{0 1 2 3}
5321:
1.1 anton 5322:
1.21 crook 5323: @item
5324: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5325: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5326: return stack so @code{EXIT} can get to its return address. For example:
5327:
5328: @example
5329: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5330: @end example
5331: prints @code{0 1 2 3}
5332:
5333:
5334: @item
1.29 crook 5335: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5336: (and @code{LOOP} iterates until they become equal by wrap-around
5337: arithmetic). This behaviour is usually not what you want. Therefore,
5338: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5339: @code{?DO}), which do not enter the loop if @i{start} is greater than
5340: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5341: unsigned loop parameters.
5342:
1.21 crook 5343: @item
5344: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5345: the loop, independent of the loop parameters. Do not use @code{DO}, even
5346: if you know that the loop is entered in any case. Such knowledge tends
5347: to become invalid during maintenance of a program, and then the
5348: @code{DO} will make trouble.
5349:
5350: @item
1.29 crook 5351: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5352: index by @i{n} instead of by 1. The loop is terminated when the border
5353: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5354:
1.21 crook 5355: @example
5356: 4 0 +DO i . 2 +LOOP
5357: @end example
5358: @noindent
5359: prints @code{0 2}
5360:
5361: @example
5362: 4 1 +DO i . 2 +LOOP
5363: @end example
5364: @noindent
5365: prints @code{1 3}
1.1 anton 5366:
1.68 anton 5367: @item
1.1 anton 5368: @cindex negative increment for counted loops
5369: @cindex counted loops with negative increment
1.29 crook 5370: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
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 -1}
1.1 anton 5377:
1.21 crook 5378: @example
5379: 0 0 ?DO i . -1 +LOOP
5380: @end example
5381: prints nothing.
1.1 anton 5382:
1.29 crook 5383: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5384: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5385: index by @i{u} each iteration. The loop is terminated when the border
5386: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5387: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5388:
1.21 crook 5389: @example
5390: -2 0 -DO i . 1 -LOOP
5391: @end example
5392: @noindent
5393: prints @code{0 -1}
1.1 anton 5394:
1.21 crook 5395: @example
5396: -1 0 -DO i . 1 -LOOP
5397: @end example
5398: @noindent
5399: prints @code{0}
5400:
5401: @example
5402: 0 0 -DO i . 1 -LOOP
5403: @end example
5404: @noindent
5405: prints nothing.
1.1 anton 5406:
1.21 crook 5407: @end itemize
1.1 anton 5408:
5409: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5410: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5411: for these words that uses only standard words is provided in
5412: @file{compat/loops.fs}.
1.1 anton 5413:
5414:
5415: @cindex @code{FOR} loops
1.26 crook 5416: Another counted loop is:
1.1 anton 5417: @example
1.29 crook 5418: @i{n}
1.1 anton 5419: FOR
1.29 crook 5420: @i{body}
1.1 anton 5421: NEXT
5422: @end example
5423: This is the preferred loop of native code compiler writers who are too
1.26 crook 5424: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5425: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5426: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5427: Forth systems may behave differently, even if they support @code{FOR}
5428: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5429:
5430: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5431: @subsection Arbitrary control structures
5432: @cindex control structures, user-defined
5433:
5434: @cindex control-flow stack
5435: ANS Forth permits and supports using control structures in a non-nested
5436: way. Information about incomplete control structures is stored on the
5437: control-flow stack. This stack may be implemented on the Forth data
5438: stack, and this is what we have done in Gforth.
5439:
5440: @cindex @code{orig}, control-flow stack item
5441: @cindex @code{dest}, control-flow stack item
5442: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5443: entry represents a backward branch target. A few words are the basis for
5444: building any control structure possible (except control structures that
5445: need storage, like calls, coroutines, and backtracking).
5446:
1.44 crook 5447:
1.1 anton 5448: doc-if
5449: doc-ahead
5450: doc-then
5451: doc-begin
5452: doc-until
5453: doc-again
5454: doc-cs-pick
5455: doc-cs-roll
5456:
1.44 crook 5457:
1.21 crook 5458: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5459: manipulate the control-flow stack in a portable way. Without them, you
5460: would need to know how many stack items are occupied by a control-flow
5461: entry (many systems use one cell. In Gforth they currently take three,
5462: but this may change in the future).
5463:
1.1 anton 5464: Some standard control structure words are built from these words:
5465:
1.44 crook 5466:
1.1 anton 5467: doc-else
5468: doc-while
5469: doc-repeat
5470:
1.44 crook 5471:
5472: @noindent
1.1 anton 5473: Gforth adds some more control-structure words:
5474:
1.44 crook 5475:
1.1 anton 5476: doc-endif
5477: doc-?dup-if
5478: doc-?dup-0=-if
5479:
1.44 crook 5480:
5481: @noindent
1.1 anton 5482: Counted loop words constitute a separate group of words:
5483:
1.44 crook 5484:
1.1 anton 5485: doc-?do
5486: doc-+do
5487: doc-u+do
5488: doc--do
5489: doc-u-do
5490: doc-do
5491: doc-for
5492: doc-loop
5493: doc-+loop
5494: doc--loop
5495: doc-next
5496: doc-leave
5497: doc-?leave
5498: doc-unloop
5499: doc-done
5500:
1.44 crook 5501:
1.21 crook 5502: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5503: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5504: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5505: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5506: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5507: resolved (by using one of the loop-ending words or @code{DONE}).
5508:
1.44 crook 5509: @noindent
1.26 crook 5510: Another group of control structure words are:
1.1 anton 5511:
1.44 crook 5512:
1.1 anton 5513: doc-case
5514: doc-endcase
5515: doc-of
5516: doc-endof
5517:
1.44 crook 5518:
1.21 crook 5519: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5520: @code{CS-ROLL}.
1.1 anton 5521:
5522: @subsubsection Programming Style
1.47 crook 5523: @cindex control structures programming style
5524: @cindex programming style, arbitrary control structures
1.1 anton 5525:
5526: In order to ensure readability we recommend that you do not create
5527: arbitrary control structures directly, but define new control structure
5528: words for the control structure you want and use these words in your
1.26 crook 5529: program. For example, instead of writing:
1.1 anton 5530:
5531: @example
1.26 crook 5532: BEGIN
1.1 anton 5533: ...
1.26 crook 5534: IF [ 1 CS-ROLL ]
1.1 anton 5535: ...
1.26 crook 5536: AGAIN THEN
1.1 anton 5537: @end example
5538:
1.21 crook 5539: @noindent
1.1 anton 5540: we recommend defining control structure words, e.g.,
5541:
5542: @example
1.26 crook 5543: : WHILE ( DEST -- ORIG DEST )
5544: POSTPONE IF
5545: 1 CS-ROLL ; immediate
5546:
5547: : REPEAT ( orig dest -- )
5548: POSTPONE AGAIN
5549: POSTPONE THEN ; immediate
1.1 anton 5550: @end example
5551:
1.21 crook 5552: @noindent
1.1 anton 5553: and then using these to create the control structure:
5554:
5555: @example
1.26 crook 5556: BEGIN
1.1 anton 5557: ...
1.26 crook 5558: WHILE
1.1 anton 5559: ...
1.26 crook 5560: REPEAT
1.1 anton 5561: @end example
5562:
5563: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5564: @code{WHILE} are predefined, so in this example it would not be
5565: necessary to define them.
5566:
5567: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5568: @subsection Calls and returns
5569: @cindex calling a definition
5570: @cindex returning from a definition
5571:
1.3 anton 5572: @cindex recursive definitions
5573: A definition can be called simply be writing the name of the definition
1.26 crook 5574: to be called. Normally a definition is invisible during its own
1.3 anton 5575: definition. If you want to write a directly recursive definition, you
1.26 crook 5576: can use @code{recursive} to make the current definition visible, or
5577: @code{recurse} to call the current definition directly.
1.3 anton 5578:
1.44 crook 5579:
1.3 anton 5580: doc-recursive
5581: doc-recurse
5582:
1.44 crook 5583:
1.21 crook 5584: @comment TODO add example of the two recursion methods
1.12 anton 5585: @quotation
5586: @progstyle
5587: I prefer using @code{recursive} to @code{recurse}, because calling the
5588: definition by name is more descriptive (if the name is well-chosen) than
5589: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5590: implementation, it is much better to read (and think) ``now sort the
5591: partitions'' than to read ``now do a recursive call''.
5592: @end quotation
1.3 anton 5593:
1.29 crook 5594: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5595:
5596: @example
1.28 crook 5597: Defer foo
1.3 anton 5598:
5599: : bar ( ... -- ... )
5600: ... foo ... ;
5601:
5602: :noname ( ... -- ... )
5603: ... bar ... ;
5604: IS foo
5605: @end example
5606:
1.44 crook 5607: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5608:
1.26 crook 5609: The current definition returns control to the calling definition when
1.33 anton 5610: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5611:
5612: doc-exit
5613: doc-;s
5614:
1.44 crook 5615:
1.1 anton 5616: @node Exception Handling, , Calls and returns, Control Structures
5617: @subsection Exception Handling
1.26 crook 5618: @cindex exceptions
1.1 anton 5619:
1.68 anton 5620: @c quit is a very bad idea for error handling,
5621: @c because it does not translate into a THROW
5622: @c it also does not belong into this chapter
5623:
5624: If a word detects an error condition that it cannot handle, it can
5625: @code{throw} an exception. In the simplest case, this will terminate
5626: your program, and report an appropriate error.
1.21 crook 5627:
1.68 anton 5628: doc-throw
1.1 anton 5629:
1.69 anton 5630: @code{Throw} consumes a cell-sized error number on the stack. There are
5631: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5632: Gforth (and most other systems) you can use the iors produced by various
5633: words as error numbers (e.g., a typical use of @code{allocate} is
5634: @code{allocate throw}). Gforth also provides the word @code{exception}
5635: to define your own error numbers (with decent error reporting); an ANS
5636: Forth version of this word (but without the error messages) is available
5637: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5638: numbers (anything outside the range -4095..0), but won't get nice error
5639: messages, only numbers. For example, try:
5640:
5641: @example
1.69 anton 5642: -10 throw \ ANS defined
5643: -267 throw \ system defined
5644: s" my error" exception throw \ user defined
5645: 7 throw \ arbitrary number
1.68 anton 5646: @end example
5647:
5648: doc---exception-exception
1.1 anton 5649:
1.69 anton 5650: A common idiom to @code{THROW} a specific error if a flag is true is
5651: this:
5652:
5653: @example
5654: @code{( flag ) 0<> @i{errno} and throw}
5655: @end example
5656:
5657: Your program can provide exception handlers to catch exceptions. An
5658: exception handler can be used to correct the problem, or to clean up
5659: some data structures and just throw the exception to the next exception
5660: handler. Note that @code{throw} jumps to the dynamically innermost
5661: exception handler. The system's exception handler is outermost, and just
5662: prints an error and restarts command-line interpretation (or, in batch
5663: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5664:
1.68 anton 5665: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5666:
1.68 anton 5667: doc-catch
5668:
5669: The most common use of exception handlers is to clean up the state when
5670: an error happens. E.g.,
1.1 anton 5671:
1.26 crook 5672: @example
1.68 anton 5673: base @ >r hex \ actually the hex should be inside foo, or we h
5674: ['] foo catch ( nerror|0 )
5675: r> base !
1.69 anton 5676: ( nerror|0 ) throw \ pass it on
1.26 crook 5677: @end example
1.1 anton 5678:
1.69 anton 5679: A use of @code{catch} for handling the error @code{myerror} might look
5680: like this:
1.44 crook 5681:
1.68 anton 5682: @example
1.69 anton 5683: ['] foo catch
5684: CASE
5685: myerror OF ... ( do something about it ) ENDOF
5686: dup throw \ default: pass other errors on, do nothing on non-errors
5687: ENDCASE
1.68 anton 5688: @end example
1.44 crook 5689:
1.68 anton 5690: Having to wrap the code into a separate word is often cumbersome,
5691: therefore Gforth provides an alternative syntax:
1.1 anton 5692:
5693: @example
1.69 anton 5694: TRY
1.68 anton 5695: @i{code1}
1.69 anton 5696: RECOVER \ optional
1.68 anton 5697: @i{code2} \ optional
1.69 anton 5698: ENDTRY
1.1 anton 5699: @end example
5700:
1.68 anton 5701: This performs @i{Code1}. If @i{code1} completes normally, execution
5702: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5703: reset to the state during @code{try}, the throw value is pushed on the
5704: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5705: through the @code{endtry} into the following code.
1.26 crook 5706:
1.68 anton 5707: doc-try
5708: doc-recover
5709: doc-endtry
1.26 crook 5710:
1.69 anton 5711: The cleanup example from above in this syntax:
1.26 crook 5712:
1.68 anton 5713: @example
1.69 anton 5714: base @ >r TRY
1.68 anton 5715: hex foo \ now the hex is placed correctly
1.69 anton 5716: 0 \ value for throw
1.92 anton 5717: RECOVER ENDTRY
1.68 anton 5718: r> base ! throw
1.1 anton 5719: @end example
5720:
1.69 anton 5721: And here's the error handling example:
1.1 anton 5722:
1.68 anton 5723: @example
1.69 anton 5724: TRY
1.68 anton 5725: foo
1.69 anton 5726: RECOVER
5727: CASE
5728: myerror OF ... ( do something about it ) ENDOF
5729: throw \ pass other errors on
5730: ENDCASE
5731: ENDTRY
1.68 anton 5732: @end example
1.1 anton 5733:
1.69 anton 5734: @progstyle
5735: As usual, you should ensure that the stack depth is statically known at
5736: the end: either after the @code{throw} for passing on errors, or after
5737: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5738: selection construct for handling the error).
5739:
1.68 anton 5740: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5741: and you can provide an error message. @code{Abort} just produces an
5742: ``Aborted'' error.
1.1 anton 5743:
1.68 anton 5744: The problem with these words is that exception handlers cannot
5745: differentiate between different @code{abort"}s; they just look like
5746: @code{-2 throw} to them (the error message cannot be accessed by
5747: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5748: exception handlers.
1.44 crook 5749:
1.68 anton 5750: doc-abort"
1.26 crook 5751: doc-abort
1.29 crook 5752:
5753:
1.44 crook 5754:
1.29 crook 5755: @c -------------------------------------------------------------
1.47 crook 5756: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5757: @section Defining Words
5758: @cindex defining words
5759:
1.47 crook 5760: Defining words are used to extend Forth by creating new entries in the dictionary.
5761:
1.29 crook 5762: @menu
1.67 anton 5763: * CREATE::
1.44 crook 5764: * Variables:: Variables and user variables
1.67 anton 5765: * Constants::
1.44 crook 5766: * Values:: Initialised variables
1.67 anton 5767: * Colon Definitions::
1.44 crook 5768: * Anonymous Definitions:: Definitions without names
1.69 anton 5769: * Supplying names:: Passing definition names as strings
1.67 anton 5770: * User-defined Defining Words::
1.44 crook 5771: * Deferred words:: Allow forward references
1.67 anton 5772: * Aliases::
1.29 crook 5773: @end menu
5774:
1.44 crook 5775: @node CREATE, Variables, Defining Words, Defining Words
5776: @subsection @code{CREATE}
1.29 crook 5777: @cindex simple defining words
5778: @cindex defining words, simple
5779:
5780: Defining words are used to create new entries in the dictionary. The
5781: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5782: this:
5783:
5784: @example
5785: CREATE new-word1
5786: @end example
5787:
1.69 anton 5788: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5789: input stream (@code{new-word1} in our example). It generates a
5790: dictionary entry for @code{new-word1}. When @code{new-word1} is
5791: executed, all that it does is leave an address on the stack. The address
5792: represents the value of the data space pointer (@code{HERE}) at the time
5793: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5794: associating a name with the address of a region of memory.
1.29 crook 5795:
1.34 anton 5796: doc-create
5797:
1.69 anton 5798: Note that in ANS Forth guarantees only for @code{create} that its body
5799: is in dictionary data space (i.e., where @code{here}, @code{allot}
5800: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5801: @code{create}d words can be modified with @code{does>}
5802: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5803: can only be applied to @code{create}d words.
5804:
1.29 crook 5805: By extending this example to reserve some memory in data space, we end
1.69 anton 5806: up with something like a @i{variable}. Here are two different ways to do
5807: it:
1.29 crook 5808:
5809: @example
5810: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5811: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5812: @end example
5813:
5814: The variable can be examined and modified using @code{@@} (``fetch'') and
5815: @code{!} (``store'') like this:
5816:
5817: @example
5818: new-word2 @@ . \ get address, fetch from it and display
5819: 1234 new-word2 ! \ new value, get address, store to it
5820: @end example
5821:
1.44 crook 5822: @cindex arrays
5823: A similar mechanism can be used to create arrays. For example, an
5824: 80-character text input buffer:
1.29 crook 5825:
5826: @example
1.44 crook 5827: CREATE text-buf 80 chars allot
5828:
5829: text-buf 0 chars c@@ \ the 1st character (offset 0)
5830: text-buf 3 chars c@@ \ the 4th character (offset 3)
5831: @end example
1.29 crook 5832:
1.44 crook 5833: You can build arbitrarily complex data structures by allocating
1.49 anton 5834: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5835: learn about some Gforth tools that make it easier,
1.49 anton 5836: @xref{Structures}.
1.44 crook 5837:
5838:
5839: @node Variables, Constants, CREATE, Defining Words
5840: @subsection Variables
5841: @cindex variables
5842:
5843: The previous section showed how a sequence of commands could be used to
5844: generate a variable. As a final refinement, the whole code sequence can
5845: be wrapped up in a defining word (pre-empting the subject of the next
5846: section), making it easier to create new variables:
5847:
5848: @example
5849: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5850: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5851:
5852: myvariableX foo \ variable foo starts off with an unknown value
5853: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5854:
5855: 45 3 * foo ! \ set foo to 135
5856: 1234 joe ! \ set joe to 1234
5857: 3 joe +! \ increment joe by 3.. to 1237
5858: @end example
5859:
5860: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5861: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5862: guarantee that a @code{Variable} is initialised when it is created
5863: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5864: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5865: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5866: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5867: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5868: store a boolean, you can use @code{on} and @code{off} to toggle its
5869: state.
1.29 crook 5870:
1.34 anton 5871: doc-variable
5872: doc-2variable
5873: doc-fvariable
5874:
1.29 crook 5875: @cindex user variables
5876: @cindex user space
5877: The defining word @code{User} behaves in the same way as @code{Variable}.
5878: The difference is that it reserves space in @i{user (data) space} rather
5879: than normal data space. In a Forth system that has a multi-tasker, each
5880: task has its own set of user variables.
5881:
1.34 anton 5882: doc-user
1.67 anton 5883: @c doc-udp
5884: @c doc-uallot
1.34 anton 5885:
1.29 crook 5886: @comment TODO is that stuff about user variables strictly correct? Is it
5887: @comment just terminal tasks that have user variables?
5888: @comment should document tasker.fs (with some examples) elsewhere
5889: @comment in this manual, then expand on user space and user variables.
5890:
1.44 crook 5891: @node Constants, Values, Variables, Defining Words
5892: @subsection Constants
5893: @cindex constants
5894:
5895: @code{Constant} allows you to declare a fixed value and refer to it by
5896: name. For example:
1.29 crook 5897:
5898: @example
5899: 12 Constant INCHES-PER-FOOT
5900: 3E+08 fconstant SPEED-O-LIGHT
5901: @end example
5902:
5903: A @code{Variable} can be both read and written, so its run-time
5904: behaviour is to supply an address through which its current value can be
5905: manipulated. In contrast, the value of a @code{Constant} cannot be
5906: changed once it has been declared@footnote{Well, often it can be -- but
5907: not in a Standard, portable way. It's safer to use a @code{Value} (read
5908: on).} so it's not necessary to supply the address -- it is more
5909: efficient to return the value of the constant directly. That's exactly
5910: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5911: the top of the stack (You can find one
5912: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5913:
1.69 anton 5914: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5915: double and floating-point constants, respectively.
5916:
1.34 anton 5917: doc-constant
5918: doc-2constant
5919: doc-fconstant
5920:
5921: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5922: @c nac-> How could that not be true in an ANS Forth? You can't define a
5923: @c constant, use it and then delete the definition of the constant..
1.69 anton 5924:
5925: @c anton->An ANS Forth system can compile a constant to a literal; On
5926: @c decompilation you would see only the number, just as if it had been used
5927: @c in the first place. The word will stay, of course, but it will only be
5928: @c used by the text interpreter (no run-time duties, except when it is
5929: @c POSTPONEd or somesuch).
5930:
5931: @c nac:
1.44 crook 5932: @c I agree that it's rather deep, but IMO it is an important difference
5933: @c relative to other programming languages.. often it's annoying: it
5934: @c certainly changes my programming style relative to C.
5935:
1.69 anton 5936: @c anton: In what way?
5937:
1.29 crook 5938: Constants in Forth behave differently from their equivalents in other
5939: programming languages. In other languages, a constant (such as an EQU in
5940: assembler or a #define in C) only exists at compile-time; in the
5941: executable program the constant has been translated into an absolute
5942: number and, unless you are using a symbolic debugger, it's impossible to
5943: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5944: an entry in the header space and remains there after the code that uses
5945: it has been defined. In fact, it must remain in the dictionary since it
5946: has run-time duties to perform. For example:
1.29 crook 5947:
5948: @example
5949: 12 Constant INCHES-PER-FOOT
5950: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5951: @end example
5952:
5953: @cindex in-lining of constants
5954: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5955: associated with the constant @code{INCHES-PER-FOOT}. If you use
5956: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5957: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5958: attempt to optimise constants by in-lining them where they are used. You
5959: can force Gforth to in-line a constant like this:
5960:
5961: @example
5962: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5963: @end example
5964:
5965: If you use @code{see} to decompile @i{this} version of
5966: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5967: longer present. To understand how this works, read
5968: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5969:
5970: In-lining constants in this way might improve execution time
5971: fractionally, and can ensure that a constant is now only referenced at
5972: compile-time. However, the definition of the constant still remains in
5973: the dictionary. Some Forth compilers provide a mechanism for controlling
5974: a second dictionary for holding transient words such that this second
5975: dictionary can be deleted later in order to recover memory
5976: space. However, there is no standard way of doing this.
5977:
5978:
1.44 crook 5979: @node Values, Colon Definitions, Constants, Defining Words
5980: @subsection Values
5981: @cindex values
1.34 anton 5982:
1.69 anton 5983: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5984: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5985: (not in ANS Forth) you can access (and change) a @code{value} also with
5986: @code{>body}.
5987:
5988: Here are some
5989: examples:
1.29 crook 5990:
5991: @example
1.69 anton 5992: 12 Value APPLES \ Define APPLES with an initial value of 12
5993: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5994: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5995: APPLES \ puts 35 on the top of the stack.
1.29 crook 5996: @end example
5997:
1.44 crook 5998: doc-value
5999: doc-to
1.29 crook 6000:
1.35 anton 6001:
1.69 anton 6002:
1.44 crook 6003: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6004: @subsection Colon Definitions
6005: @cindex colon definitions
1.35 anton 6006:
6007: @example
1.44 crook 6008: : name ( ... -- ... )
6009: word1 word2 word3 ;
1.29 crook 6010: @end example
6011:
1.44 crook 6012: @noindent
6013: Creates a word called @code{name} that, upon execution, executes
6014: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6015:
1.49 anton 6016: The explanation above is somewhat superficial. For simple examples of
6017: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6018: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6019: Compilation Semantics}.
1.29 crook 6020:
1.44 crook 6021: doc-:
6022: doc-;
1.1 anton 6023:
1.34 anton 6024:
1.69 anton 6025: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6026: @subsection Anonymous Definitions
6027: @cindex colon definitions
6028: @cindex defining words without name
1.34 anton 6029:
1.44 crook 6030: Sometimes you want to define an @dfn{anonymous word}; a word without a
6031: name. You can do this with:
1.1 anton 6032:
1.44 crook 6033: doc-:noname
1.1 anton 6034:
1.44 crook 6035: This leaves the execution token for the word on the stack after the
6036: closing @code{;}. Here's an example in which a deferred word is
6037: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6038:
1.29 crook 6039: @example
1.44 crook 6040: Defer deferred
6041: :noname ( ... -- ... )
6042: ... ;
6043: IS deferred
1.29 crook 6044: @end example
1.26 crook 6045:
1.44 crook 6046: @noindent
6047: Gforth provides an alternative way of doing this, using two separate
6048: words:
1.27 crook 6049:
1.44 crook 6050: doc-noname
6051: @cindex execution token of last defined word
1.116 anton 6052: doc-latestxt
1.1 anton 6053:
1.44 crook 6054: @noindent
6055: The previous example can be rewritten using @code{noname} and
1.116 anton 6056: @code{latestxt}:
1.1 anton 6057:
1.26 crook 6058: @example
1.44 crook 6059: Defer deferred
6060: noname : ( ... -- ... )
6061: ... ;
1.116 anton 6062: latestxt IS deferred
1.26 crook 6063: @end example
1.1 anton 6064:
1.29 crook 6065: @noindent
1.44 crook 6066: @code{noname} works with any defining word, not just @code{:}.
6067:
1.116 anton 6068: @code{latestxt} also works when the last word was not defined as
1.71 anton 6069: @code{noname}. It does not work for combined words, though. It also has
6070: the useful property that is is valid as soon as the header for a
6071: definition has been built. Thus:
1.44 crook 6072:
6073: @example
1.116 anton 6074: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6075: @end example
1.1 anton 6076:
1.44 crook 6077: @noindent
6078: prints 3 numbers; the last two are the same.
1.26 crook 6079:
1.69 anton 6080: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6081: @subsection Supplying the name of a defined word
6082: @cindex names for defined words
6083: @cindex defining words, name given in a string
6084:
6085: By default, a defining word takes the name for the defined word from the
6086: input stream. Sometimes you want to supply the name from a string. You
6087: can do this with:
6088:
6089: doc-nextname
6090:
6091: For example:
6092:
6093: @example
6094: s" foo" nextname create
6095: @end example
6096:
6097: @noindent
6098: is equivalent to:
6099:
6100: @example
6101: create foo
6102: @end example
6103:
6104: @noindent
6105: @code{nextname} works with any defining word.
6106:
1.1 anton 6107:
1.69 anton 6108: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6109: @subsection User-defined Defining Words
6110: @cindex user-defined defining words
6111: @cindex defining words, user-defined
1.1 anton 6112:
1.29 crook 6113: You can create a new defining word by wrapping defining-time code around
6114: an existing defining word and putting the sequence in a colon
1.69 anton 6115: definition.
6116:
6117: @c anton: This example is very complex and leads in a quite different
6118: @c direction from the CREATE-DOES> stuff that follows. It should probably
6119: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6120: @c subsection of Defining Words)
6121:
6122: For example, suppose that you have a word @code{stats} that
1.29 crook 6123: gathers statistics about colon definitions given the @i{xt} of the
6124: definition, and you want every colon definition in your application to
6125: make a call to @code{stats}. You can define and use a new version of
6126: @code{:} like this:
6127:
6128: @example
6129: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6130: ... ; \ other code
6131:
1.116 anton 6132: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6133:
6134: my: foo + - ;
6135: @end example
6136:
6137: When @code{foo} is defined using @code{my:} these steps occur:
6138:
6139: @itemize @bullet
6140: @item
6141: @code{my:} is executed.
6142: @item
6143: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6144: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6145: the input stream for a name, builds a dictionary header for the name
6146: @code{foo} and switches @code{state} from interpret to compile.
6147: @item
1.116 anton 6148: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6149: being defined -- @code{foo} -- onto the stack.
6150: @item
6151: The code that was produced by @code{postpone literal} is executed; this
6152: causes the value on the stack to be compiled as a literal in the code
6153: area of @code{foo}.
6154: @item
6155: The code @code{['] stats} compiles a literal into the definition of
6156: @code{my:}. When @code{compile,} is executed, that literal -- the
6157: execution token for @code{stats} -- is layed down in the code area of
6158: @code{foo} , following the literal@footnote{Strictly speaking, the
6159: mechanism that @code{compile,} uses to convert an @i{xt} into something
6160: in the code area is implementation-dependent. A threaded implementation
6161: might spit out the execution token directly whilst another
6162: implementation might spit out a native code sequence.}.
6163: @item
6164: At this point, the execution of @code{my:} is complete, and control
6165: returns to the text interpreter. The text interpreter is in compile
6166: state, so subsequent text @code{+ -} is compiled into the definition of
6167: @code{foo} and the @code{;} terminates the definition as always.
6168: @end itemize
6169:
6170: You can use @code{see} to decompile a word that was defined using
6171: @code{my:} and see how it is different from a normal @code{:}
6172: definition. For example:
6173:
6174: @example
6175: : bar + - ; \ like foo but using : rather than my:
6176: see bar
6177: : bar
6178: + - ;
6179: see foo
6180: : foo
6181: 107645672 stats + - ;
6182:
1.140 anton 6183: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6184: @end example
6185:
6186: You can use techniques like this to make new defining words in terms of
6187: @i{any} existing defining word.
1.1 anton 6188:
6189:
1.29 crook 6190: @cindex defining defining words
1.26 crook 6191: @cindex @code{CREATE} ... @code{DOES>}
6192: If you want the words defined with your defining words to behave
6193: differently from words defined with standard defining words, you can
6194: write your defining word like this:
1.1 anton 6195:
6196: @example
1.26 crook 6197: : def-word ( "name" -- )
1.29 crook 6198: CREATE @i{code1}
1.26 crook 6199: DOES> ( ... -- ... )
1.29 crook 6200: @i{code2} ;
1.26 crook 6201:
6202: def-word name
1.1 anton 6203: @end example
6204:
1.29 crook 6205: @cindex child words
6206: This fragment defines a @dfn{defining word} @code{def-word} and then
6207: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6208: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6209: is not executed at this time. The word @code{name} is sometimes called a
6210: @dfn{child} of @code{def-word}.
6211:
6212: When you execute @code{name}, the address of the body of @code{name} is
6213: put on the data stack and @i{code2} is executed (the address of the body
6214: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6215: @code{CREATE}, i.e., the address a @code{create}d word returns by
6216: default).
6217:
6218: @c anton:
6219: @c www.dictionary.com says:
6220: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6221: @c several generations of absence, usually caused by the chance
6222: @c recombination of genes. 2.An individual or a part that exhibits
6223: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6224: @c of previous behavior after a period of absence.
6225: @c
6226: @c Doesn't seem to fit.
1.29 crook 6227:
1.69 anton 6228: @c @cindex atavism in child words
1.33 anton 6229: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6230: similarly; they all have a common run-time behaviour determined by
6231: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6232: body of the child word. The structure of the data is common to all
6233: children of @code{def-word}, but the data values are specific -- and
6234: private -- to each child word. When a child word is executed, the
6235: address of its private data area is passed as a parameter on TOS to be
6236: used and manipulated@footnote{It is legitimate both to read and write to
6237: this data area.} by @i{code2}.
1.29 crook 6238:
6239: The two fragments of code that make up the defining words act (are
6240: executed) at two completely separate times:
1.1 anton 6241:
1.29 crook 6242: @itemize @bullet
6243: @item
6244: At @i{define time}, the defining word executes @i{code1} to generate a
6245: child word
6246: @item
6247: At @i{child execution time}, when a child word is invoked, @i{code2}
6248: is executed, using parameters (data) that are private and specific to
6249: the child word.
6250: @end itemize
6251:
1.44 crook 6252: Another way of understanding the behaviour of @code{def-word} and
6253: @code{name} is to say that, if you make the following definitions:
1.33 anton 6254: @example
6255: : def-word1 ( "name" -- )
6256: CREATE @i{code1} ;
6257:
6258: : action1 ( ... -- ... )
6259: @i{code2} ;
6260:
6261: def-word1 name1
6262: @end example
6263:
1.44 crook 6264: @noindent
6265: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6266:
1.29 crook 6267: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6268:
1.1 anton 6269: @example
1.29 crook 6270: : CONSTANT ( w "name" -- )
6271: CREATE ,
1.26 crook 6272: DOES> ( -- w )
6273: @@ ;
1.1 anton 6274: @end example
6275:
1.29 crook 6276: @comment There is a beautiful description of how this works and what
6277: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6278: @comment commentary on the Counting Fruits problem.
6279:
6280: When you create a constant with @code{5 CONSTANT five}, a set of
6281: define-time actions take place; first a new word @code{five} is created,
6282: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6283: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6284: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6285: no code of its own; it simply contains a data field and a pointer to the
6286: code that follows @code{DOES>} in its defining word. That makes words
6287: created in this way very compact.
6288:
6289: The final example in this section is intended to remind you that space
6290: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6291: both read and written by a Standard program@footnote{Exercise: use this
6292: example as a starting point for your own implementation of @code{Value}
6293: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6294: @code{[']}.}:
6295:
6296: @example
6297: : foo ( "name" -- )
6298: CREATE -1 ,
6299: DOES> ( -- )
1.33 anton 6300: @@ . ;
1.29 crook 6301:
6302: foo first-word
6303: foo second-word
6304:
6305: 123 ' first-word >BODY !
6306: @end example
6307:
6308: If @code{first-word} had been a @code{CREATE}d word, we could simply
6309: have executed it to get the address of its data field. However, since it
6310: was defined to have @code{DOES>} actions, its execution semantics are to
6311: perform those @code{DOES>} actions. To get the address of its data field
6312: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6313: translate the xt into the address of the data field. When you execute
6314: @code{first-word}, it will display @code{123}. When you execute
6315: @code{second-word} it will display @code{-1}.
1.26 crook 6316:
6317: @cindex stack effect of @code{DOES>}-parts
6318: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6319: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6320: the stack effect of the defined words, not the stack effect of the
6321: following code (the following code expects the address of the body on
6322: the top of stack, which is not reflected in the stack comment). This is
6323: the convention that I use and recommend (it clashes a bit with using
6324: locals declarations for stack effect specification, though).
1.1 anton 6325:
1.53 anton 6326: @menu
6327: * CREATE..DOES> applications::
6328: * CREATE..DOES> details::
1.63 anton 6329: * Advanced does> usage example::
1.91 anton 6330: * @code{Const-does>}::
1.53 anton 6331: @end menu
6332:
6333: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6334: @subsubsection Applications of @code{CREATE..DOES>}
6335: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6336:
1.26 crook 6337: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6338:
1.26 crook 6339: @cindex factoring similar colon definitions
6340: When you see a sequence of code occurring several times, and you can
6341: identify a meaning, you will factor it out as a colon definition. When
6342: you see similar colon definitions, you can factor them using
6343: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6344: that look very similar:
1.1 anton 6345: @example
1.26 crook 6346: : ori, ( reg-target reg-source n -- )
6347: 0 asm-reg-reg-imm ;
6348: : andi, ( reg-target reg-source n -- )
6349: 1 asm-reg-reg-imm ;
1.1 anton 6350: @end example
6351:
1.26 crook 6352: @noindent
6353: This could be factored with:
6354: @example
6355: : reg-reg-imm ( op-code -- )
6356: CREATE ,
6357: DOES> ( reg-target reg-source n -- )
6358: @@ asm-reg-reg-imm ;
6359:
6360: 0 reg-reg-imm ori,
6361: 1 reg-reg-imm andi,
6362: @end example
1.1 anton 6363:
1.26 crook 6364: @cindex currying
6365: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6366: supply a part of the parameters for a word (known as @dfn{currying} in
6367: the functional language community). E.g., @code{+} needs two
6368: parameters. Creating versions of @code{+} with one parameter fixed can
6369: be done like this:
1.82 anton 6370:
1.1 anton 6371: @example
1.82 anton 6372: : curry+ ( n1 "name" -- )
1.26 crook 6373: CREATE ,
6374: DOES> ( n2 -- n1+n2 )
6375: @@ + ;
6376:
6377: 3 curry+ 3+
6378: -2 curry+ 2-
1.1 anton 6379: @end example
6380:
1.91 anton 6381:
1.63 anton 6382: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6383: @subsubsection The gory details of @code{CREATE..DOES>}
6384: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6385:
1.26 crook 6386: doc-does>
1.1 anton 6387:
1.26 crook 6388: @cindex @code{DOES>} in a separate definition
6389: This means that you need not use @code{CREATE} and @code{DOES>} in the
6390: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6391: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6392: @example
6393: : does1
6394: DOES> ( ... -- ... )
1.44 crook 6395: ... ;
6396:
6397: : does2
6398: DOES> ( ... -- ... )
6399: ... ;
6400:
6401: : def-word ( ... -- ... )
6402: create ...
6403: IF
6404: does1
6405: ELSE
6406: does2
6407: ENDIF ;
6408: @end example
6409:
6410: In this example, the selection of whether to use @code{does1} or
1.69 anton 6411: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6412: @code{CREATE}d.
6413:
6414: @cindex @code{DOES>} in interpretation state
6415: In a standard program you can apply a @code{DOES>}-part only if the last
6416: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6417: will override the behaviour of the last word defined in any case. In a
6418: standard program, you can use @code{DOES>} only in a colon
6419: definition. In Gforth, you can also use it in interpretation state, in a
6420: kind of one-shot mode; for example:
6421: @example
6422: CREATE name ( ... -- ... )
6423: @i{initialization}
6424: DOES>
6425: @i{code} ;
6426: @end example
6427:
6428: @noindent
6429: is equivalent to the standard:
6430: @example
6431: :noname
6432: DOES>
6433: @i{code} ;
6434: CREATE name EXECUTE ( ... -- ... )
6435: @i{initialization}
6436: @end example
6437:
1.53 anton 6438: doc->body
6439:
1.91 anton 6440: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6441: @subsubsection Advanced does> usage example
6442:
6443: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6444: for disassembling instructions, that follow a very repetetive scheme:
6445:
6446: @example
6447: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6448: @var{entry-num} cells @var{table} + !
6449: @end example
6450:
6451: Of course, this inspires the idea to factor out the commonalities to
6452: allow a definition like
6453:
6454: @example
6455: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6456: @end example
6457:
6458: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6459: correlated. Moreover, before I wrote the disassembler, there already
6460: existed code that defines instructions like this:
1.63 anton 6461:
6462: @example
6463: @var{entry-num} @var{inst-format} @var{inst-name}
6464: @end example
6465:
6466: This code comes from the assembler and resides in
6467: @file{arch/mips/insts.fs}.
6468:
6469: So I had to define the @var{inst-format} words that performed the scheme
6470: above when executed. At first I chose to use run-time code-generation:
6471:
6472: @example
6473: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6474: :noname Postpone @var{disasm-operands}
6475: name Postpone sliteral Postpone type Postpone ;
6476: swap cells @var{table} + ! ;
6477: @end example
6478:
6479: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6480:
1.63 anton 6481: An alternative would have been to write this using
6482: @code{create}/@code{does>}:
6483:
6484: @example
6485: : @var{inst-format} ( entry-num "name" -- )
6486: here name string, ( entry-num c-addr ) \ parse and save "name"
6487: noname create , ( entry-num )
1.116 anton 6488: latestxt swap cells @var{table} + !
1.63 anton 6489: does> ( addr w -- )
6490: \ disassemble instruction w at addr
6491: @@ >r
6492: @var{disasm-operands}
6493: r> count type ;
6494: @end example
6495:
6496: Somehow the first solution is simpler, mainly because it's simpler to
6497: shift a string from definition-time to use-time with @code{sliteral}
6498: than with @code{string,} and friends.
6499:
6500: I wrote a lot of words following this scheme and soon thought about
6501: factoring out the commonalities among them. Note that this uses a
6502: two-level defining word, i.e., a word that defines ordinary defining
6503: words.
6504:
6505: This time a solution involving @code{postpone} and friends seemed more
6506: difficult (try it as an exercise), so I decided to use a
6507: @code{create}/@code{does>} word; since I was already at it, I also used
6508: @code{create}/@code{does>} for the lower level (try using
6509: @code{postpone} etc. as an exercise), resulting in the following
6510: definition:
6511:
6512: @example
6513: : define-format ( disasm-xt table-xt -- )
6514: \ define an instruction format that uses disasm-xt for
6515: \ disassembling and enters the defined instructions into table
6516: \ table-xt
6517: create 2,
6518: does> ( u "inst" -- )
6519: \ defines an anonymous word for disassembling instruction inst,
6520: \ and enters it as u-th entry into table-xt
6521: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6522: noname create 2, \ define anonymous word
1.116 anton 6523: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6524: does> ( addr w -- )
6525: \ disassemble instruction w at addr
6526: 2@@ >r ( addr w disasm-xt R: c-addr )
6527: execute ( R: c-addr ) \ disassemble operands
6528: r> count type ; \ print name
6529: @end example
6530:
6531: Note that the tables here (in contrast to above) do the @code{cells +}
6532: by themselves (that's why you have to pass an xt). This word is used in
6533: the following way:
6534:
6535: @example
6536: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6537: @end example
6538:
1.71 anton 6539: As shown above, the defined instruction format is then used like this:
6540:
6541: @example
6542: @var{entry-num} @var{inst-format} @var{inst-name}
6543: @end example
6544:
1.63 anton 6545: In terms of currying, this kind of two-level defining word provides the
6546: parameters in three stages: first @var{disasm-operands} and @var{table},
6547: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6548: the instruction to be disassembled.
6549:
6550: Of course this did not quite fit all the instruction format names used
6551: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6552: the parameters into the right form.
6553:
6554: If you have trouble following this section, don't worry. First, this is
6555: involved and takes time (and probably some playing around) to
6556: understand; second, this is the first two-level
6557: @code{create}/@code{does>} word I have written in seventeen years of
6558: Forth; and if I did not have @file{insts.fs} to start with, I may well
6559: have elected to use just a one-level defining word (with some repeating
6560: of parameters when using the defining word). So it is not necessary to
6561: understand this, but it may improve your understanding of Forth.
1.44 crook 6562:
6563:
1.91 anton 6564: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6565: @subsubsection @code{Const-does>}
6566:
6567: A frequent use of @code{create}...@code{does>} is for transferring some
6568: values from definition-time to run-time. Gforth supports this use with
6569:
6570: doc-const-does>
6571:
6572: A typical use of this word is:
6573:
6574: @example
6575: : curry+ ( n1 "name" -- )
6576: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6577: + ;
6578:
6579: 3 curry+ 3+
6580: @end example
6581:
6582: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6583: definition to run-time.
6584:
6585: The advantages of using @code{const-does>} are:
6586:
6587: @itemize
6588:
6589: @item
6590: You don't have to deal with storing and retrieving the values, i.e.,
6591: your program becomes more writable and readable.
6592:
6593: @item
6594: When using @code{does>}, you have to introduce a @code{@@} that cannot
6595: be optimized away (because you could change the data using
6596: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6597:
6598: @end itemize
6599:
6600: An ANS Forth implementation of @code{const-does>} is available in
6601: @file{compat/const-does.fs}.
6602:
6603:
1.44 crook 6604: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6605: @subsection Deferred words
6606: @cindex deferred words
6607:
6608: The defining word @code{Defer} allows you to define a word by name
6609: without defining its behaviour; the definition of its behaviour is
6610: deferred. Here are two situation where this can be useful:
6611:
6612: @itemize @bullet
6613: @item
6614: Where you want to allow the behaviour of a word to be altered later, and
6615: for all precompiled references to the word to change when its behaviour
6616: is changed.
6617: @item
6618: For mutual recursion; @xref{Calls and returns}.
6619: @end itemize
6620:
6621: In the following example, @code{foo} always invokes the version of
6622: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6623: always invokes the version that prints ``@code{Hello}''. There is no way
6624: of getting @code{foo} to use the later version without re-ordering the
6625: source code and recompiling it.
6626:
6627: @example
6628: : greet ." Good morning" ;
6629: : foo ... greet ... ;
6630: : greet ." Hello" ;
6631: : bar ... greet ... ;
6632: @end example
6633:
6634: This problem can be solved by defining @code{greet} as a @code{Defer}red
6635: word. The behaviour of a @code{Defer}red word can be defined and
6636: redefined at any time by using @code{IS} to associate the xt of a
6637: previously-defined word with it. The previous example becomes:
6638:
6639: @example
1.69 anton 6640: Defer greet ( -- )
1.44 crook 6641: : foo ... greet ... ;
6642: : bar ... greet ... ;
1.69 anton 6643: : greet1 ( -- ) ." Good morning" ;
6644: : greet2 ( -- ) ." Hello" ;
1.132 anton 6645: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6646: @end example
6647:
1.69 anton 6648: @progstyle
6649: You should write a stack comment for every deferred word, and put only
6650: XTs into deferred words that conform to this stack effect. Otherwise
6651: it's too difficult to use the deferred word.
6652:
1.44 crook 6653: A deferred word can be used to improve the statistics-gathering example
6654: from @ref{User-defined Defining Words}; rather than edit the
6655: application's source code to change every @code{:} to a @code{my:}, do
6656: this:
6657:
6658: @example
6659: : real: : ; \ retain access to the original
6660: defer : \ redefine as a deferred word
1.132 anton 6661: ' my: IS : \ use special version of :
1.44 crook 6662: \
6663: \ load application here
6664: \
1.132 anton 6665: ' real: IS : \ go back to the original
1.44 crook 6666: @end example
6667:
6668:
1.132 anton 6669: One thing to note is that @code{IS} has special compilation semantics,
6670: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6671:
6672: @example
6673: : set-greet ( xt -- )
1.132 anton 6674: IS greet ;
1.44 crook 6675:
6676: ' greet1 set-greet
6677: @end example
6678:
1.132 anton 6679: In situations where @code{IS} does not fit, use @code{defer!} instead.
6680:
1.69 anton 6681: A deferred word can only inherit execution semantics from the xt
6682: (because that is all that an xt can represent -- for more discussion of
6683: this @pxref{Tokens for Words}); by default it will have default
6684: interpretation and compilation semantics deriving from this execution
6685: semantics. However, you can change the interpretation and compilation
6686: semantics of the deferred word in the usual ways:
1.44 crook 6687:
6688: @example
1.132 anton 6689: : bar .... ; immediate
1.44 crook 6690: Defer fred immediate
6691: Defer jim
6692:
1.132 anton 6693: ' bar IS jim \ jim has default semantics
6694: ' bar IS fred \ fred is immediate
1.44 crook 6695: @end example
6696:
6697: doc-defer
1.132 anton 6698: doc-defer!
1.44 crook 6699: doc-is
1.132 anton 6700: doc-defer@
6701: doc-action-of
1.44 crook 6702: @comment TODO document these: what's defers [is]
6703: doc-defers
6704:
6705: @c Use @code{words-deferred} to see a list of deferred words.
6706:
1.132 anton 6707: Definitions of these words (except @code{defers}) in ANS Forth are
6708: provided in @file{compat/defer.fs}.
1.44 crook 6709:
6710:
1.69 anton 6711: @node Aliases, , Deferred words, Defining Words
1.44 crook 6712: @subsection Aliases
6713: @cindex aliases
1.1 anton 6714:
1.44 crook 6715: The defining word @code{Alias} allows you to define a word by name that
6716: has the same behaviour as some other word. Here are two situation where
6717: this can be useful:
1.1 anton 6718:
1.44 crook 6719: @itemize @bullet
6720: @item
6721: When you want access to a word's definition from a different word list
6722: (for an example of this, see the definition of the @code{Root} word list
6723: in the Gforth source).
6724: @item
6725: When you want to create a synonym; a definition that can be known by
6726: either of two names (for example, @code{THEN} and @code{ENDIF} are
6727: aliases).
6728: @end itemize
1.1 anton 6729:
1.69 anton 6730: Like deferred words, an alias has default compilation and interpretation
6731: semantics at the beginning (not the modifications of the other word),
6732: but you can change them in the usual ways (@code{immediate},
6733: @code{compile-only}). For example:
1.1 anton 6734:
6735: @example
1.44 crook 6736: : foo ... ; immediate
6737:
6738: ' foo Alias bar \ bar is not an immediate word
6739: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6740: @end example
6741:
1.44 crook 6742: Words that are aliases have the same xt, different headers in the
6743: dictionary, and consequently different name tokens (@pxref{Tokens for
6744: Words}) and possibly different immediate flags. An alias can only have
6745: default or immediate compilation semantics; you can define aliases for
6746: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6747:
1.44 crook 6748: doc-alias
1.1 anton 6749:
6750:
1.47 crook 6751: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6752: @section Interpretation and Compilation Semantics
1.26 crook 6753: @cindex semantics, interpretation and compilation
1.1 anton 6754:
1.71 anton 6755: @c !! state and ' are used without explanation
6756: @c example for immediate/compile-only? or is the tutorial enough
6757:
1.26 crook 6758: @cindex interpretation semantics
1.71 anton 6759: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6760: interpreter does when it encounters the word in interpret state. It also
6761: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6762: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6763: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6764: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6765:
1.26 crook 6766: @cindex compilation semantics
1.71 anton 6767: The @dfn{compilation semantics} of a (named) word are what the text
6768: interpreter does when it encounters the word in compile state. It also
6769: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6770: compiles@footnote{In standard terminology, ``appends to the current
6771: definition''.} the compilation semantics of @i{word}.
1.1 anton 6772:
1.26 crook 6773: @cindex execution semantics
6774: The standard also talks about @dfn{execution semantics}. They are used
6775: only for defining the interpretation and compilation semantics of many
6776: words. By default, the interpretation semantics of a word are to
6777: @code{execute} its execution semantics, and the compilation semantics of
6778: a word are to @code{compile,} its execution semantics.@footnote{In
6779: standard terminology: The default interpretation semantics are its
6780: execution semantics; the default compilation semantics are to append its
6781: execution semantics to the execution semantics of the current
6782: definition.}
6783:
1.71 anton 6784: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6785: the text interpreter, ticked, or @code{postpone}d, so they have no
6786: interpretation or compilation semantics. Their behaviour is represented
6787: by their XT (@pxref{Tokens for Words}), and we call it execution
6788: semantics, too.
6789:
1.26 crook 6790: @comment TODO expand, make it co-operate with new sections on text interpreter.
6791:
6792: @cindex immediate words
6793: @cindex compile-only words
6794: You can change the semantics of the most-recently defined word:
6795:
1.44 crook 6796:
1.26 crook 6797: doc-immediate
6798: doc-compile-only
6799: doc-restrict
6800:
1.82 anton 6801: By convention, words with non-default compilation semantics (e.g.,
6802: immediate words) often have names surrounded with brackets (e.g.,
6803: @code{[']}, @pxref{Execution token}).
1.44 crook 6804:
1.26 crook 6805: Note that ticking (@code{'}) a compile-only word gives an error
6806: (``Interpreting a compile-only word'').
1.1 anton 6807:
1.47 crook 6808: @menu
1.67 anton 6809: * Combined words::
1.47 crook 6810: @end menu
1.44 crook 6811:
1.71 anton 6812:
1.48 anton 6813: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6814: @subsection Combined Words
6815: @cindex combined words
6816:
6817: Gforth allows you to define @dfn{combined words} -- words that have an
6818: arbitrary combination of interpretation and compilation semantics.
6819:
1.26 crook 6820: doc-interpret/compile:
1.1 anton 6821:
1.26 crook 6822: This feature was introduced for implementing @code{TO} and @code{S"}. I
6823: recommend that you do not define such words, as cute as they may be:
6824: they make it hard to get at both parts of the word in some contexts.
6825: E.g., assume you want to get an execution token for the compilation
6826: part. Instead, define two words, one that embodies the interpretation
6827: part, and one that embodies the compilation part. Once you have done
6828: that, you can define a combined word with @code{interpret/compile:} for
6829: the convenience of your users.
1.1 anton 6830:
1.26 crook 6831: You might try to use this feature to provide an optimizing
6832: implementation of the default compilation semantics of a word. For
6833: example, by defining:
1.1 anton 6834: @example
1.26 crook 6835: :noname
6836: foo bar ;
6837: :noname
6838: POSTPONE foo POSTPONE bar ;
1.29 crook 6839: interpret/compile: opti-foobar
1.1 anton 6840: @end example
1.26 crook 6841:
1.23 crook 6842: @noindent
1.26 crook 6843: as an optimizing version of:
6844:
1.1 anton 6845: @example
1.26 crook 6846: : foobar
6847: foo bar ;
1.1 anton 6848: @end example
6849:
1.26 crook 6850: Unfortunately, this does not work correctly with @code{[compile]},
6851: because @code{[compile]} assumes that the compilation semantics of all
6852: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6853: opti-foobar} would compile compilation semantics, whereas
6854: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6855:
1.26 crook 6856: @cindex state-smart words (are a bad idea)
1.82 anton 6857: @anchor{state-smartness}
1.29 crook 6858: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6859: by @code{interpret/compile:} (words are state-smart if they check
6860: @code{STATE} during execution). E.g., they would try to code
6861: @code{foobar} like this:
1.1 anton 6862:
1.26 crook 6863: @example
6864: : foobar
6865: STATE @@
6866: IF ( compilation state )
6867: POSTPONE foo POSTPONE bar
6868: ELSE
6869: foo bar
6870: ENDIF ; immediate
6871: @end example
1.1 anton 6872:
1.26 crook 6873: Although this works if @code{foobar} is only processed by the text
6874: interpreter, it does not work in other contexts (like @code{'} or
6875: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6876: for a state-smart word, not for the interpretation semantics of the
6877: original @code{foobar}; when you execute this execution token (directly
6878: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6879: state, the result will not be what you expected (i.e., it will not
6880: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6881: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6882: M. Anton Ertl,
6883: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6884: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6885:
1.26 crook 6886: @cindex defining words with arbitrary semantics combinations
6887: It is also possible to write defining words that define words with
6888: arbitrary combinations of interpretation and compilation semantics. In
6889: general, they look like this:
1.1 anton 6890:
1.26 crook 6891: @example
6892: : def-word
6893: create-interpret/compile
1.29 crook 6894: @i{code1}
1.26 crook 6895: interpretation>
1.29 crook 6896: @i{code2}
1.26 crook 6897: <interpretation
6898: compilation>
1.29 crook 6899: @i{code3}
1.26 crook 6900: <compilation ;
6901: @end example
1.1 anton 6902:
1.29 crook 6903: For a @i{word} defined with @code{def-word}, the interpretation
6904: semantics are to push the address of the body of @i{word} and perform
6905: @i{code2}, and the compilation semantics are to push the address of
6906: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6907: can also be defined like this (except that the defined constants don't
6908: behave correctly when @code{[compile]}d):
1.1 anton 6909:
1.26 crook 6910: @example
6911: : constant ( n "name" -- )
6912: create-interpret/compile
6913: ,
6914: interpretation> ( -- n )
6915: @@
6916: <interpretation
6917: compilation> ( compilation. -- ; run-time. -- n )
6918: @@ postpone literal
6919: <compilation ;
6920: @end example
1.1 anton 6921:
1.44 crook 6922:
1.26 crook 6923: doc-create-interpret/compile
6924: doc-interpretation>
6925: doc-<interpretation
6926: doc-compilation>
6927: doc-<compilation
1.1 anton 6928:
1.44 crook 6929:
1.29 crook 6930: Words defined with @code{interpret/compile:} and
1.26 crook 6931: @code{create-interpret/compile} have an extended header structure that
6932: differs from other words; however, unless you try to access them with
6933: plain address arithmetic, you should not notice this. Words for
6934: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6935: @code{'} @i{word} @code{>body} also gives you the body of a word created
6936: with @code{create-interpret/compile}.
1.1 anton 6937:
1.44 crook 6938:
1.47 crook 6939: @c -------------------------------------------------------------
1.81 anton 6940: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6941: @section Tokens for Words
6942: @cindex tokens for words
6943:
6944: This section describes the creation and use of tokens that represent
6945: words.
6946:
1.71 anton 6947: @menu
6948: * Execution token:: represents execution/interpretation semantics
6949: * Compilation token:: represents compilation semantics
6950: * Name token:: represents named words
6951: @end menu
1.47 crook 6952:
1.71 anton 6953: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6954: @subsection Execution token
1.47 crook 6955:
6956: @cindex xt
6957: @cindex execution token
1.71 anton 6958: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6959: You can use @code{execute} to invoke this behaviour.
1.47 crook 6960:
1.71 anton 6961: @cindex tick (')
6962: You can use @code{'} to get an execution token that represents the
6963: interpretation semantics of a named word:
1.47 crook 6964:
6965: @example
1.97 anton 6966: 5 ' . ( n xt )
6967: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6968: @end example
1.47 crook 6969:
1.71 anton 6970: doc-'
6971:
6972: @code{'} parses at run-time; there is also a word @code{[']} that parses
6973: when it is compiled, and compiles the resulting XT:
6974:
6975: @example
6976: : foo ['] . execute ;
6977: 5 foo
6978: : bar ' execute ; \ by contrast,
6979: 5 bar . \ ' parses "." when bar executes
6980: @end example
6981:
6982: doc-[']
6983:
6984: If you want the execution token of @i{word}, write @code{['] @i{word}}
6985: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6986: @code{'} and @code{[']} behave somewhat unusually by complaining about
6987: compile-only words (because these words have no interpretation
6988: semantics). You might get what you want by using @code{COMP' @i{word}
6989: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6990: token}).
6991:
1.116 anton 6992: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6993: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6994: for the only behaviour the word has (the execution semantics). For
1.116 anton 6995: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6996: would produce if the word was defined anonymously.
6997:
6998: @example
6999: :noname ." hello" ;
7000: execute
1.47 crook 7001: @end example
7002:
1.71 anton 7003: An XT occupies one cell and can be manipulated like any other cell.
7004:
1.47 crook 7005: @cindex code field address
7006: @cindex CFA
1.71 anton 7007: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7008: operations that produce or consume it). For old hands: In Gforth, the
7009: XT is implemented as a code field address (CFA).
7010:
7011: doc-execute
7012: doc-perform
7013:
7014: @node Compilation token, Name token, Execution token, Tokens for Words
7015: @subsection Compilation token
1.47 crook 7016:
7017: @cindex compilation token
1.71 anton 7018: @cindex CT (compilation token)
7019: Gforth represents the compilation semantics of a named word by a
1.47 crook 7020: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7021: @i{xt} is an execution token. The compilation semantics represented by
7022: the compilation token can be performed with @code{execute}, which
7023: consumes the whole compilation token, with an additional stack effect
7024: determined by the represented compilation semantics.
7025:
7026: At present, the @i{w} part of a compilation token is an execution token,
7027: and the @i{xt} part represents either @code{execute} or
7028: @code{compile,}@footnote{Depending upon the compilation semantics of the
7029: word. If the word has default compilation semantics, the @i{xt} will
7030: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7031: @i{xt} will represent @code{execute}.}. However, don't rely on that
7032: knowledge, unless necessary; future versions of Gforth may introduce
7033: unusual compilation tokens (e.g., a compilation token that represents
7034: the compilation semantics of a literal).
7035:
1.71 anton 7036: You can perform the compilation semantics represented by the compilation
7037: token with @code{execute}. You can compile the compilation semantics
7038: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7039: equivalent to @code{postpone @i{word}}.
7040:
7041: doc-[comp']
7042: doc-comp'
7043: doc-postpone,
7044:
7045: @node Name token, , Compilation token, Tokens for Words
7046: @subsection Name token
1.47 crook 7047:
7048: @cindex name token
1.116 anton 7049: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7050: token is an abstract data type that occurs as argument or result of the
7051: words below.
7052:
7053: @c !! put this elswhere?
1.47 crook 7054: @cindex name field address
7055: @cindex NFA
1.116 anton 7056: The closest thing to the nt in older Forth systems is the name field
7057: address (NFA), but there are significant differences: in older Forth
7058: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7059: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7060: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7061: is a link field in the structure identified by the name token, but
7062: searching usually uses a hash table external to these structures; the
7063: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7064: implemented as the address of that count field.
1.47 crook 7065:
7066: doc-find-name
1.116 anton 7067: doc-latest
7068: doc->name
1.47 crook 7069: doc-name>int
7070: doc-name?int
7071: doc-name>comp
7072: doc-name>string
1.109 anton 7073: doc-id.
7074: doc-.name
7075: doc-.id
1.47 crook 7076:
1.81 anton 7077: @c ----------------------------------------------------------
7078: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7079: @section Compiling words
7080: @cindex compiling words
7081: @cindex macros
7082:
7083: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7084: between compilation and run-time. E.g., you can run arbitrary code
7085: between defining words (or for computing data used by defining words
7086: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7087: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7088: running arbitrary code while compiling a colon definition (exception:
7089: you must not allot dictionary space).
7090:
7091: @menu
7092: * Literals:: Compiling data values
7093: * Macros:: Compiling words
7094: @end menu
7095:
7096: @node Literals, Macros, Compiling words, Compiling words
7097: @subsection Literals
7098: @cindex Literals
7099:
7100: The simplest and most frequent example is to compute a literal during
7101: compilation. E.g., the following definition prints an array of strings,
7102: one string per line:
7103:
7104: @example
7105: : .strings ( addr u -- ) \ gforth
7106: 2* cells bounds U+DO
7107: cr i 2@@ type
7108: 2 cells +LOOP ;
7109: @end example
1.81 anton 7110:
1.82 anton 7111: With a simple-minded compiler like Gforth's, this computes @code{2
7112: cells} on every loop iteration. You can compute this value once and for
7113: all at compile time and compile it into the definition like this:
7114:
7115: @example
7116: : .strings ( addr u -- ) \ gforth
7117: 2* cells bounds U+DO
7118: cr i 2@@ type
7119: [ 2 cells ] literal +LOOP ;
7120: @end example
7121:
7122: @code{[} switches the text interpreter to interpret state (you will get
7123: an @code{ok} prompt if you type this example interactively and insert a
7124: newline between @code{[} and @code{]}), so it performs the
7125: interpretation semantics of @code{2 cells}; this computes a number.
7126: @code{]} switches the text interpreter back into compile state. It then
7127: performs @code{Literal}'s compilation semantics, which are to compile
7128: this number into the current word. You can decompile the word with
7129: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7130:
1.82 anton 7131: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7132: *} in this way.
1.81 anton 7133:
1.82 anton 7134: doc-[
7135: doc-]
1.81 anton 7136: doc-literal
7137: doc-]L
1.82 anton 7138:
7139: There are also words for compiling other data types than single cells as
7140: literals:
7141:
1.81 anton 7142: doc-2literal
7143: doc-fliteral
1.82 anton 7144: doc-sliteral
7145:
7146: @cindex colon-sys, passing data across @code{:}
7147: @cindex @code{:}, passing data across
7148: You might be tempted to pass data from outside a colon definition to the
7149: inside on the data stack. This does not work, because @code{:} puhes a
7150: colon-sys, making stuff below unaccessible. E.g., this does not work:
7151:
7152: @example
7153: 5 : foo literal ; \ error: "unstructured"
7154: @end example
7155:
7156: Instead, you have to pass the value in some other way, e.g., through a
7157: variable:
7158:
7159: @example
7160: variable temp
7161: 5 temp !
7162: : foo [ temp @@ ] literal ;
7163: @end example
7164:
7165:
7166: @node Macros, , Literals, Compiling words
7167: @subsection Macros
7168: @cindex Macros
7169: @cindex compiling compilation semantics
7170:
7171: @code{Literal} and friends compile data values into the current
7172: definition. You can also write words that compile other words into the
7173: current definition. E.g.,
7174:
7175: @example
7176: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7177: POSTPONE + ;
7178:
7179: : foo ( n1 n2 -- n )
7180: [ compile-+ ] ;
7181: 1 2 foo .
7182: @end example
7183:
7184: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7185: What happens in this example? @code{Postpone} compiles the compilation
7186: semantics of @code{+} into @code{compile-+}; later the text interpreter
7187: executes @code{compile-+} and thus the compilation semantics of +, which
7188: compile (the execution semantics of) @code{+} into
7189: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7190: should only be executed in compile state, so this example is not
7191: guaranteed to work on all standard systems, but on any decent system it
7192: will work.}
7193:
7194: doc-postpone
7195: doc-[compile]
7196:
7197: Compiling words like @code{compile-+} are usually immediate (or similar)
7198: so you do not have to switch to interpret state to execute them;
7199: mopifying the last example accordingly produces:
7200:
7201: @example
7202: : [compile-+] ( compilation: --; interpretation: -- )
7203: \ compiled code: ( n1 n2 -- n )
7204: POSTPONE + ; immediate
7205:
7206: : foo ( n1 n2 -- n )
7207: [compile-+] ;
7208: 1 2 foo .
7209: @end example
7210:
7211: Immediate compiling words are similar to macros in other languages (in
7212: particular, Lisp). The important differences to macros in, e.g., C are:
7213:
7214: @itemize @bullet
7215:
7216: @item
7217: You use the same language for defining and processing macros, not a
7218: separate preprocessing language and processor.
7219:
7220: @item
7221: Consequently, the full power of Forth is available in macro definitions.
7222: E.g., you can perform arbitrarily complex computations, or generate
7223: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7224: Tutorial}). This power is very useful when writing a parser generators
7225: or other code-generating software.
7226:
7227: @item
7228: Macros defined using @code{postpone} etc. deal with the language at a
7229: higher level than strings; name binding happens at macro definition
7230: time, so you can avoid the pitfalls of name collisions that can happen
7231: in C macros. Of course, Forth is a liberal language and also allows to
7232: shoot yourself in the foot with text-interpreted macros like
7233:
7234: @example
7235: : [compile-+] s" +" evaluate ; immediate
7236: @end example
7237:
7238: Apart from binding the name at macro use time, using @code{evaluate}
7239: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7240: @end itemize
7241:
7242: You may want the macro to compile a number into a word. The word to do
7243: it is @code{literal}, but you have to @code{postpone} it, so its
7244: compilation semantics take effect when the macro is executed, not when
7245: it is compiled:
7246:
7247: @example
7248: : [compile-5] ( -- ) \ compiled code: ( -- n )
7249: 5 POSTPONE literal ; immediate
7250:
7251: : foo [compile-5] ;
7252: foo .
7253: @end example
7254:
7255: You may want to pass parameters to a macro, that the macro should
7256: compile into the current definition. If the parameter is a number, then
7257: you can use @code{postpone literal} (similar for other values).
7258:
7259: If you want to pass a word that is to be compiled, the usual way is to
7260: pass an execution token and @code{compile,} it:
7261:
7262: @example
7263: : twice1 ( xt -- ) \ compiled code: ... -- ...
7264: dup compile, compile, ;
7265:
7266: : 2+ ( n1 -- n2 )
7267: [ ' 1+ twice1 ] ;
7268: @end example
7269:
7270: doc-compile,
7271:
7272: An alternative available in Gforth, that allows you to pass compile-only
7273: words as parameters is to use the compilation token (@pxref{Compilation
7274: token}). The same example in this technique:
7275:
7276: @example
7277: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7278: 2dup 2>r execute 2r> execute ;
7279:
7280: : 2+ ( n1 -- n2 )
7281: [ comp' 1+ twice ] ;
7282: @end example
7283:
7284: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7285: works even if the executed compilation semantics has an effect on the
7286: data stack.
7287:
7288: You can also define complete definitions with these words; this provides
7289: an alternative to using @code{does>} (@pxref{User-defined Defining
7290: Words}). E.g., instead of
7291:
7292: @example
7293: : curry+ ( n1 "name" -- )
7294: CREATE ,
7295: DOES> ( n2 -- n1+n2 )
7296: @@ + ;
7297: @end example
7298:
7299: you could define
7300:
7301: @example
7302: : curry+ ( n1 "name" -- )
7303: \ name execution: ( n2 -- n1+n2 )
7304: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7305:
1.82 anton 7306: -3 curry+ 3-
7307: see 3-
7308: @end example
1.81 anton 7309:
1.82 anton 7310: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7311: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7312:
1.82 anton 7313: This way of writing defining words is sometimes more, sometimes less
7314: convenient than using @code{does>} (@pxref{Advanced does> usage
7315: example}). One advantage of this method is that it can be optimized
7316: better, because the compiler knows that the value compiled with
7317: @code{literal} is fixed, whereas the data associated with a
7318: @code{create}d word can be changed.
1.47 crook 7319:
1.26 crook 7320: @c ----------------------------------------------------------
1.111 anton 7321: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7322: @section The Text Interpreter
7323: @cindex interpreter - outer
7324: @cindex text interpreter
7325: @cindex outer interpreter
1.1 anton 7326:
1.34 anton 7327: @c Should we really describe all these ugly details? IMO the text
7328: @c interpreter should be much cleaner, but that may not be possible within
7329: @c ANS Forth. - anton
1.44 crook 7330: @c nac-> I wanted to explain how it works to show how you can exploit
7331: @c it in your own programs. When I was writing a cross-compiler, figuring out
7332: @c some of these gory details was very helpful to me. None of the textbooks
7333: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7334: @c seems to positively avoid going into too much detail for some of
7335: @c the internals.
1.34 anton 7336:
1.71 anton 7337: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7338: @c it is; for the ugly details, I would prefer another place. I wonder
7339: @c whether we should have a chapter before "Words" that describes some
7340: @c basic concepts referred to in words, and a chapter after "Words" that
7341: @c describes implementation details.
7342:
1.29 crook 7343: The text interpreter@footnote{This is an expanded version of the
7344: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7345: that processes input from the current input device. It is also called
7346: the outer interpreter, in contrast to the inner interpreter
7347: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7348: implementations.
1.27 crook 7349:
1.29 crook 7350: @cindex interpret state
7351: @cindex compile state
7352: The text interpreter operates in one of two states: @dfn{interpret
7353: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7354: aptly-named variable @code{state}.
1.29 crook 7355:
7356: This section starts by describing how the text interpreter behaves when
7357: it is in interpret state, processing input from the user input device --
7358: the keyboard. This is the mode that a Forth system is in after it starts
7359: up.
7360:
7361: @cindex input buffer
7362: @cindex terminal input buffer
7363: The text interpreter works from an area of memory called the @dfn{input
7364: buffer}@footnote{When the text interpreter is processing input from the
7365: keyboard, this area of memory is called the @dfn{terminal input buffer}
7366: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7367: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7368: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7369: leading spaces (called @dfn{delimiters}) then parses a string (a
7370: sequence of non-space characters) until it reaches either a space
7371: character or the end of the buffer. Having parsed a string, it makes two
7372: attempts to process it:
1.27 crook 7373:
1.29 crook 7374: @cindex dictionary
1.27 crook 7375: @itemize @bullet
7376: @item
1.29 crook 7377: It looks for the string in a @dfn{dictionary} of definitions. If the
7378: string is found, the string names a @dfn{definition} (also known as a
7379: @dfn{word}) and the dictionary search returns information that allows
7380: the text interpreter to perform the word's @dfn{interpretation
7381: semantics}. In most cases, this simply means that the word will be
7382: executed.
1.27 crook 7383: @item
7384: If the string is not found in the dictionary, the text interpreter
1.29 crook 7385: attempts to treat it as a number, using the rules described in
7386: @ref{Number Conversion}. If the string represents a legal number in the
7387: current radix, the number is pushed onto a parameter stack (the data
7388: stack for integers, the floating-point stack for floating-point
7389: numbers).
7390: @end itemize
7391:
7392: If both attempts fail, or if the word is found in the dictionary but has
7393: no interpretation semantics@footnote{This happens if the word was
7394: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7395: remainder of the input buffer, issues an error message and waits for
7396: more input. If one of the attempts succeeds, the text interpreter
7397: repeats the parsing process until the whole of the input buffer has been
7398: processed, at which point it prints the status message ``@code{ ok}''
7399: and waits for more input.
7400:
1.71 anton 7401: @c anton: this should be in the input stream subsection (or below it)
7402:
1.29 crook 7403: @cindex parse area
7404: The text interpreter keeps track of its position in the input buffer by
7405: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7406: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7407: of the input buffer. The region from offset @code{>IN @@} to the end of
7408: the input buffer is called the @dfn{parse area}@footnote{In other words,
7409: the text interpreter processes the contents of the input buffer by
7410: parsing strings from the parse area until the parse area is empty.}.
7411: This example shows how @code{>IN} changes as the text interpreter parses
7412: the input buffer:
7413:
7414: @example
7415: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7416: CR ." ->" TYPE ." <-" ; IMMEDIATE
7417:
7418: 1 2 3 remaining + remaining .
7419:
7420: : foo 1 2 3 remaining SWAP remaining ;
7421: @end example
7422:
7423: @noindent
7424: The result is:
7425:
7426: @example
7427: ->+ remaining .<-
7428: ->.<-5 ok
7429:
7430: ->SWAP remaining ;-<
7431: ->;<- ok
7432: @end example
7433:
7434: @cindex parsing words
7435: The value of @code{>IN} can also be modified by a word in the input
7436: buffer that is executed by the text interpreter. This means that a word
7437: can ``trick'' the text interpreter into either skipping a section of the
7438: input buffer@footnote{This is how parsing words work.} or into parsing a
7439: section twice. For example:
1.27 crook 7440:
1.29 crook 7441: @example
1.71 anton 7442: : lat ." <<foo>>" ;
7443: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7444: @end example
7445:
7446: @noindent
7447: When @code{flat} is executed, this output is produced@footnote{Exercise
7448: for the reader: what would happen if the @code{3} were replaced with
7449: @code{4}?}:
7450:
7451: @example
1.71 anton 7452: <<bar>><<foo>>
1.29 crook 7453: @end example
7454:
1.71 anton 7455: This technique can be used to work around some of the interoperability
7456: problems of parsing words. Of course, it's better to avoid parsing
7457: words where possible.
7458:
1.29 crook 7459: @noindent
7460: Two important notes about the behaviour of the text interpreter:
1.27 crook 7461:
7462: @itemize @bullet
7463: @item
7464: It processes each input string to completion before parsing additional
1.29 crook 7465: characters from the input buffer.
7466: @item
7467: It treats the input buffer as a read-only region (and so must your code).
7468: @end itemize
7469:
7470: @noindent
7471: When the text interpreter is in compile state, its behaviour changes in
7472: these ways:
7473:
7474: @itemize @bullet
7475: @item
7476: If a parsed string is found in the dictionary, the text interpreter will
7477: perform the word's @dfn{compilation semantics}. In most cases, this
7478: simply means that the execution semantics of the word will be appended
7479: to the current definition.
1.27 crook 7480: @item
1.29 crook 7481: When a number is encountered, it is compiled into the current definition
7482: (as a literal) rather than being pushed onto a parameter stack.
7483: @item
7484: If an error occurs, @code{state} is modified to put the text interpreter
7485: back into interpret state.
7486: @item
7487: Each time a line is entered from the keyboard, Gforth prints
7488: ``@code{ compiled}'' rather than `` @code{ok}''.
7489: @end itemize
7490:
7491: @cindex text interpreter - input sources
7492: When the text interpreter is using an input device other than the
7493: keyboard, its behaviour changes in these ways:
7494:
7495: @itemize @bullet
7496: @item
7497: When the parse area is empty, the text interpreter attempts to refill
7498: the input buffer from the input source. When the input source is
1.71 anton 7499: exhausted, the input source is set back to the previous input source.
1.29 crook 7500: @item
7501: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7502: time the parse area is emptied.
7503: @item
7504: If an error occurs, the input source is set back to the user input
7505: device.
1.27 crook 7506: @end itemize
1.21 crook 7507:
1.49 anton 7508: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7509:
1.26 crook 7510: doc->in
1.27 crook 7511: doc-source
7512:
1.26 crook 7513: doc-tib
7514: doc-#tib
1.1 anton 7515:
1.44 crook 7516:
1.26 crook 7517: @menu
1.67 anton 7518: * Input Sources::
7519: * Number Conversion::
7520: * Interpret/Compile states::
7521: * Interpreter Directives::
1.26 crook 7522: @end menu
1.1 anton 7523:
1.29 crook 7524: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7525: @subsection Input Sources
7526: @cindex input sources
7527: @cindex text interpreter - input sources
7528:
1.44 crook 7529: By default, the text interpreter processes input from the user input
1.29 crook 7530: device (the keyboard) when Forth starts up. The text interpreter can
7531: process input from any of these sources:
7532:
7533: @itemize @bullet
7534: @item
7535: The user input device -- the keyboard.
7536: @item
7537: A file, using the words described in @ref{Forth source files}.
7538: @item
7539: A block, using the words described in @ref{Blocks}.
7540: @item
7541: A text string, using @code{evaluate}.
7542: @end itemize
7543:
7544: A program can identify the current input device from the values of
7545: @code{source-id} and @code{blk}.
7546:
1.44 crook 7547:
1.29 crook 7548: doc-source-id
7549: doc-blk
7550:
7551: doc-save-input
7552: doc-restore-input
7553:
7554: doc-evaluate
1.111 anton 7555: doc-query
1.1 anton 7556:
1.29 crook 7557:
1.44 crook 7558:
1.29 crook 7559: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7560: @subsection Number Conversion
7561: @cindex number conversion
7562: @cindex double-cell numbers, input format
7563: @cindex input format for double-cell numbers
7564: @cindex single-cell numbers, input format
7565: @cindex input format for single-cell numbers
7566: @cindex floating-point numbers, input format
7567: @cindex input format for floating-point numbers
1.1 anton 7568:
1.29 crook 7569: This section describes the rules that the text interpreter uses when it
7570: tries to convert a string into a number.
1.1 anton 7571:
1.26 crook 7572: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7573: number base@footnote{For example, 0-9 when the number base is decimal or
7574: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7575:
1.26 crook 7576: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7577:
1.29 crook 7578: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7579: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7580:
1.26 crook 7581: Let * represent any number of instances of the previous character
7582: (including none).
1.1 anton 7583:
1.26 crook 7584: Let any other character represent itself.
1.1 anton 7585:
1.29 crook 7586: @noindent
1.26 crook 7587: Now, the conversion rules are:
1.21 crook 7588:
1.26 crook 7589: @itemize @bullet
7590: @item
7591: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7592: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7593: @item
7594: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7595: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7596: arithmetic. Examples are -45 -5681 -0
7597: @item
7598: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7599: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7600: (all three of these represent the same number).
1.26 crook 7601: @item
7602: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7603: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7604: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7605: -34.65 (all three of these represent the same number).
1.26 crook 7606: @item
1.29 crook 7607: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7608: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7609: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7610: number) +12.E-4
1.26 crook 7611: @end itemize
1.1 anton 7612:
1.26 crook 7613: By default, the number base used for integer number conversion is given
1.35 anton 7614: by the contents of the variable @code{base}. Note that a lot of
7615: confusion can result from unexpected values of @code{base}. If you
7616: change @code{base} anywhere, make sure to save the old value and restore
7617: it afterwards. In general I recommend keeping @code{base} decimal, and
7618: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7619:
1.29 crook 7620: doc-dpl
1.26 crook 7621: doc-base
7622: doc-hex
7623: doc-decimal
1.1 anton 7624:
1.26 crook 7625: @cindex '-prefix for character strings
7626: @cindex &-prefix for decimal numbers
1.133 anton 7627: @cindex #-prefix for decimal numbers
1.26 crook 7628: @cindex %-prefix for binary numbers
7629: @cindex $-prefix for hexadecimal numbers
1.133 anton 7630: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7631: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7632: prefix@footnote{Some Forth implementations provide a similar scheme by
7633: implementing @code{$} etc. as parsing words that process the subsequent
7634: number in the input stream and push it onto the stack. For example, see
7635: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7636: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7637: is required between the prefix and the number.} before the first digit
1.133 anton 7638: of an (integer) number. The following prefixes are supported:
1.1 anton 7639:
1.26 crook 7640: @itemize @bullet
7641: @item
1.35 anton 7642: @code{&} -- decimal
1.26 crook 7643: @item
1.133 anton 7644: @code{#} -- decimal
7645: @item
1.35 anton 7646: @code{%} -- binary
1.26 crook 7647: @item
1.35 anton 7648: @code{$} -- hexadecimal
1.26 crook 7649: @item
1.133 anton 7650: @code{0x} -- hexadecimal, if base<33.
7651: @item
7652: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7653: optional @code{'} may be present after the character.
1.26 crook 7654: @end itemize
1.1 anton 7655:
1.26 crook 7656: Here are some examples, with the equivalent decimal number shown after
7657: in braces:
1.1 anton 7658:
1.26 crook 7659: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7660: 'A (65),
7661: -'a' (-97),
1.26 crook 7662: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7663:
1.26 crook 7664: @cindex number conversion - traps for the unwary
1.29 crook 7665: @noindent
1.26 crook 7666: Number conversion has a number of traps for the unwary:
1.1 anton 7667:
1.26 crook 7668: @itemize @bullet
7669: @item
7670: You cannot determine the current number base using the code sequence
1.35 anton 7671: @code{base @@ .} -- the number base is always 10 in the current number
7672: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7673: @item
7674: If the number base is set to a value greater than 14 (for example,
7675: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7676: it to be intepreted as either a single-precision integer or a
7677: floating-point number (Gforth treats it as an integer). The ambiguity
7678: can be resolved by explicitly stating the sign of the mantissa and/or
7679: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7680: ambiguity arises; either representation will be treated as a
7681: floating-point number.
7682: @item
1.29 crook 7683: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7684: It is used to specify file types.
7685: @item
1.72 anton 7686: ANS Forth requires the @code{.} of a double-precision number to be the
7687: final character in the string. Gforth allows the @code{.} to be
7688: anywhere after the first digit.
1.26 crook 7689: @item
7690: The number conversion process does not check for overflow.
7691: @item
1.72 anton 7692: In an ANS Forth program @code{base} is required to be decimal when
7693: converting floating-point numbers. In Gforth, number conversion to
7694: floating-point numbers always uses base &10, irrespective of the value
7695: of @code{base}.
1.26 crook 7696: @end itemize
1.1 anton 7697:
1.49 anton 7698: You can read numbers into your programs with the words described in
7699: @ref{Input}.
1.1 anton 7700:
1.82 anton 7701: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7702: @subsection Interpret/Compile states
7703: @cindex Interpret/Compile states
1.1 anton 7704:
1.29 crook 7705: A standard program is not permitted to change @code{state}
7706: explicitly. However, it can change @code{state} implicitly, using the
7707: words @code{[} and @code{]}. When @code{[} is executed it switches
7708: @code{state} to interpret state, and therefore the text interpreter
7709: starts interpreting. When @code{]} is executed it switches @code{state}
7710: to compile state and therefore the text interpreter starts
1.44 crook 7711: compiling. The most common usage for these words is for switching into
7712: interpret state and back from within a colon definition; this technique
1.49 anton 7713: can be used to compile a literal (for an example, @pxref{Literals}) or
7714: for conditional compilation (for an example, @pxref{Interpreter
7715: Directives}).
1.44 crook 7716:
1.35 anton 7717:
7718: @c This is a bad example: It's non-standard, and it's not necessary.
7719: @c However, I can't think of a good example for switching into compile
7720: @c state when there is no current word (@code{state}-smart words are not a
7721: @c good reason). So maybe we should use an example for switching into
7722: @c interpret @code{state} in a colon def. - anton
1.44 crook 7723: @c nac-> I agree. I started out by putting in the example, then realised
7724: @c that it was non-ANS, so wrote more words around it. I hope this
7725: @c re-written version is acceptable to you. I do want to keep the example
7726: @c as it is helpful for showing what is and what is not portable, particularly
7727: @c where it outlaws a style in common use.
7728:
1.72 anton 7729: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7730: @c that, we can also show what's not. In any case, I have written a
7731: @c section Compiling Words which also deals with [ ].
1.35 anton 7732:
1.95 anton 7733: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7734:
1.95 anton 7735: @c @code{[} and @code{]} also give you the ability to switch into compile
7736: @c state and back, but we cannot think of any useful Standard application
7737: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7738:
7739: @c @example
7740: @c : AA ." this is A" ;
7741: @c : BB ." this is B" ;
7742: @c : CC ." this is C" ;
7743:
7744: @c create table ] aa bb cc [
7745:
7746: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7747: @c cells table + @@ execute ;
7748: @c @end example
7749:
7750: @c This example builds a jump table; @code{0 go} will display ``@code{this
7751: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7752: @c defining @code{table} like this:
7753:
7754: @c @example
7755: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7756: @c @end example
7757:
7758: @c The problem with this code is that the definition of @code{table} is not
7759: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7760: @c @i{may} work on systems where code space and data space co-incide, the
7761: @c Standard only allows data space to be assigned for a @code{CREATE}d
7762: @c word. In addition, the Standard only allows @code{@@} to access data
7763: @c space, whilst this example is using it to access code space. The only
7764: @c portable, Standard way to build this table is to build it in data space,
7765: @c like this:
7766:
7767: @c @example
7768: @c create table ' aa , ' bb , ' cc ,
7769: @c @end example
1.29 crook 7770:
1.95 anton 7771: @c doc-state
1.44 crook 7772:
1.29 crook 7773:
1.82 anton 7774: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7775: @subsection Interpreter Directives
7776: @cindex interpreter directives
1.72 anton 7777: @cindex conditional compilation
1.1 anton 7778:
1.29 crook 7779: These words are usually used in interpret state; typically to control
7780: which parts of a source file are processed by the text
1.26 crook 7781: interpreter. There are only a few ANS Forth Standard words, but Gforth
7782: supplements these with a rich set of immediate control structure words
7783: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7784: used in compile state (@pxref{Control Structures}). Typical usages:
7785:
7786: @example
1.72 anton 7787: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7788: .
7789: .
1.72 anton 7790: HAVE-ASSEMBLER [IF]
1.29 crook 7791: : ASSEMBLER-FEATURE
7792: ...
7793: ;
7794: [ENDIF]
7795: .
7796: .
7797: : SEE
7798: ... \ general-purpose SEE code
1.72 anton 7799: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7800: ... \ assembler-specific SEE code
7801: [ [ENDIF] ]
7802: ;
7803: @end example
1.1 anton 7804:
1.44 crook 7805:
1.26 crook 7806: doc-[IF]
7807: doc-[ELSE]
7808: doc-[THEN]
7809: doc-[ENDIF]
1.1 anton 7810:
1.26 crook 7811: doc-[IFDEF]
7812: doc-[IFUNDEF]
1.1 anton 7813:
1.26 crook 7814: doc-[?DO]
7815: doc-[DO]
7816: doc-[FOR]
7817: doc-[LOOP]
7818: doc-[+LOOP]
7819: doc-[NEXT]
1.1 anton 7820:
1.26 crook 7821: doc-[BEGIN]
7822: doc-[UNTIL]
7823: doc-[AGAIN]
7824: doc-[WHILE]
7825: doc-[REPEAT]
1.1 anton 7826:
1.27 crook 7827:
1.26 crook 7828: @c -------------------------------------------------------------
1.111 anton 7829: @node The Input Stream, Word Lists, The Text Interpreter, Words
7830: @section The Input Stream
7831: @cindex input stream
7832:
7833: @c !! integrate this better with the "Text Interpreter" section
7834: The text interpreter reads from the input stream, which can come from
7835: several sources (@pxref{Input Sources}). Some words, in particular
7836: defining words, but also words like @code{'}, read parameters from the
7837: input stream instead of from the stack.
7838:
7839: Such words are called parsing words, because they parse the input
7840: stream. Parsing words are hard to use in other words, because it is
7841: hard to pass program-generated parameters through the input stream.
7842: They also usually have an unintuitive combination of interpretation and
7843: compilation semantics when implemented naively, leading to various
7844: approaches that try to produce a more intuitive behaviour
7845: (@pxref{Combined words}).
7846:
7847: It should be obvious by now that parsing words are a bad idea. If you
7848: want to implement a parsing word for convenience, also provide a factor
7849: of the word that does not parse, but takes the parameters on the stack.
7850: To implement the parsing word on top if it, you can use the following
7851: words:
7852:
7853: @c anton: these belong in the input stream section
7854: doc-parse
1.138 anton 7855: doc-parse-name
1.111 anton 7856: doc-parse-word
7857: doc-name
7858: doc-word
7859: doc-\"-parse
7860: doc-refill
7861:
7862: Conversely, if you have the bad luck (or lack of foresight) to have to
7863: deal with parsing words without having such factors, how do you pass a
7864: string that is not in the input stream to it?
7865:
7866: doc-execute-parsing
7867:
1.146 anton 7868: A definition of this word in ANS Forth is provided in
7869: @file{compat/execute-parsing.fs}.
7870:
1.111 anton 7871: If you want to run a parsing word on a file, the following word should
7872: help:
7873:
7874: doc-execute-parsing-file
7875:
7876: @c -------------------------------------------------------------
7877: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7878: @section Word Lists
7879: @cindex word lists
1.32 anton 7880: @cindex header space
1.1 anton 7881:
1.36 anton 7882: A wordlist is a list of named words; you can add new words and look up
7883: words by name (and you can remove words in a restricted way with
7884: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7885:
7886: @cindex search order stack
7887: The text interpreter searches the wordlists present in the search order
7888: (a stack of wordlists), from the top to the bottom. Within each
7889: wordlist, the search starts conceptually at the newest word; i.e., if
7890: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7891:
1.26 crook 7892: @cindex compilation word list
1.36 anton 7893: New words are added to the @dfn{compilation wordlist} (aka current
7894: wordlist).
1.1 anton 7895:
1.36 anton 7896: @cindex wid
7897: A word list is identified by a cell-sized word list identifier (@i{wid})
7898: in much the same way as a file is identified by a file handle. The
7899: numerical value of the wid has no (portable) meaning, and might change
7900: from session to session.
1.1 anton 7901:
1.29 crook 7902: The ANS Forth ``Search order'' word set is intended to provide a set of
7903: low-level tools that allow various different schemes to be
1.74 anton 7904: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7905: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7906: Forth.
1.1 anton 7907:
1.27 crook 7908: @comment TODO: locals section refers to here, saying that every word list (aka
7909: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7910: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7911:
1.45 crook 7912: @comment TODO: document markers, reveal, tables, mappedwordlist
7913:
7914: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7915: @comment word from the source files, rather than some alias.
1.44 crook 7916:
1.26 crook 7917: doc-forth-wordlist
7918: doc-definitions
7919: doc-get-current
7920: doc-set-current
7921: doc-get-order
1.45 crook 7922: doc---gforthman-set-order
1.26 crook 7923: doc-wordlist
1.30 anton 7924: doc-table
1.79 anton 7925: doc->order
1.36 anton 7926: doc-previous
1.26 crook 7927: doc-also
1.45 crook 7928: doc---gforthman-forth
1.26 crook 7929: doc-only
1.45 crook 7930: doc---gforthman-order
1.15 anton 7931:
1.26 crook 7932: doc-find
7933: doc-search-wordlist
1.15 anton 7934:
1.26 crook 7935: doc-words
7936: doc-vlist
1.44 crook 7937: @c doc-words-deferred
1.1 anton 7938:
1.74 anton 7939: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7940: doc-root
7941: doc-vocabulary
7942: doc-seal
7943: doc-vocs
7944: doc-current
7945: doc-context
1.1 anton 7946:
1.44 crook 7947:
1.26 crook 7948: @menu
1.75 anton 7949: * Vocabularies::
1.67 anton 7950: * Why use word lists?::
1.75 anton 7951: * Word list example::
1.26 crook 7952: @end menu
7953:
1.75 anton 7954: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7955: @subsection Vocabularies
7956: @cindex Vocabularies, detailed explanation
7957:
7958: Here is an example of creating and using a new wordlist using ANS
7959: Forth words:
7960:
7961: @example
7962: wordlist constant my-new-words-wordlist
7963: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7964:
7965: \ add it to the search order
7966: also my-new-words
7967:
7968: \ alternatively, add it to the search order and make it
7969: \ the compilation word list
7970: also my-new-words definitions
7971: \ type "order" to see the problem
7972: @end example
7973:
7974: The problem with this example is that @code{order} has no way to
7975: associate the name @code{my-new-words} with the wid of the word list (in
7976: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7977: that has no associated name). There is no Standard way of associating a
7978: name with a wid.
7979:
7980: In Gforth, this example can be re-coded using @code{vocabulary}, which
7981: associates a name with a wid:
7982:
7983: @example
7984: vocabulary my-new-words
7985:
7986: \ add it to the search order
7987: also my-new-words
7988:
7989: \ alternatively, add it to the search order and make it
7990: \ the compilation word list
7991: my-new-words definitions
7992: \ type "order" to see that the problem is solved
7993: @end example
7994:
7995:
7996: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7997: @subsection Why use word lists?
7998: @cindex word lists - why use them?
7999:
1.74 anton 8000: Here are some reasons why people use wordlists:
1.26 crook 8001:
8002: @itemize @bullet
1.74 anton 8003:
8004: @c anton: Gforth's hashing implementation makes the search speed
8005: @c independent from the number of words. But it is linear with the number
8006: @c of wordlists that have to be searched, so in effect using more wordlists
8007: @c actually slows down compilation.
8008:
8009: @c @item
8010: @c To improve compilation speed by reducing the number of header space
8011: @c entries that must be searched. This is achieved by creating a new
8012: @c word list that contains all of the definitions that are used in the
8013: @c definition of a Forth system but which would not usually be used by
8014: @c programs running on that system. That word list would be on the search
8015: @c list when the Forth system was compiled but would be removed from the
8016: @c search list for normal operation. This can be a useful technique for
8017: @c low-performance systems (for example, 8-bit processors in embedded
8018: @c systems) but is unlikely to be necessary in high-performance desktop
8019: @c systems.
8020:
1.26 crook 8021: @item
8022: To prevent a set of words from being used outside the context in which
8023: they are valid. Two classic examples of this are an integrated editor
8024: (all of the edit commands are defined in a separate word list; the
8025: search order is set to the editor word list when the editor is invoked;
8026: the old search order is restored when the editor is terminated) and an
8027: integrated assembler (the op-codes for the machine are defined in a
8028: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8029:
8030: @item
8031: To organize the words of an application or library into a user-visible
8032: set (in @code{forth-wordlist} or some other common wordlist) and a set
8033: of helper words used just for the implementation (hidden in a separate
1.75 anton 8034: wordlist). This keeps @code{words}' output smaller, separates
8035: implementation and interface, and reduces the chance of name conflicts
8036: within the common wordlist.
1.74 anton 8037:
1.26 crook 8038: @item
8039: To prevent a name-space clash between multiple definitions with the same
8040: name. For example, when building a cross-compiler you might have a word
8041: @code{IF} that generates conditional code for your target system. By
8042: placing this definition in a different word list you can control whether
8043: the host system's @code{IF} or the target system's @code{IF} get used in
8044: any particular context by controlling the order of the word lists on the
8045: search order stack.
1.74 anton 8046:
1.26 crook 8047: @end itemize
1.1 anton 8048:
1.74 anton 8049: The downsides of using wordlists are:
8050:
8051: @itemize
8052:
8053: @item
8054: Debugging becomes more cumbersome.
8055:
8056: @item
8057: Name conflicts worked around with wordlists are still there, and you
8058: have to arrange the search order carefully to get the desired results;
8059: if you forget to do that, you get hard-to-find errors (as in any case
8060: where you read the code differently from the compiler; @code{see} can
1.75 anton 8061: help seeing which of several possible words the name resolves to in such
8062: cases). @code{See} displays just the name of the words, not what
8063: wordlist they belong to, so it might be misleading. Using unique names
8064: is a better approach to avoid name conflicts.
1.74 anton 8065:
8066: @item
8067: You have to explicitly undo any changes to the search order. In many
8068: cases it would be more convenient if this happened implicitly. Gforth
8069: currently does not provide such a feature, but it may do so in the
8070: future.
8071: @end itemize
8072:
8073:
1.75 anton 8074: @node Word list example, , Why use word lists?, Word Lists
8075: @subsection Word list example
8076: @cindex word lists - example
1.1 anton 8077:
1.74 anton 8078: The following example is from the
8079: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8080: garbage collector} and uses wordlists to separate public words from
8081: helper words:
8082:
8083: @example
8084: get-current ( wid )
8085: vocabulary garbage-collector also garbage-collector definitions
8086: ... \ define helper words
8087: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8088: ... \ define the public (i.e., API) words
8089: \ they can refer to the helper words
8090: previous \ restore original search order (helper words become invisible)
8091: @end example
8092:
1.26 crook 8093: @c -------------------------------------------------------------
8094: @node Environmental Queries, Files, Word Lists, Words
8095: @section Environmental Queries
8096: @cindex environmental queries
1.21 crook 8097:
1.26 crook 8098: ANS Forth introduced the idea of ``environmental queries'' as a way
8099: for a program running on a system to determine certain characteristics of the system.
8100: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8101:
1.32 anton 8102: The Standard requires that the header space used for environmental queries
8103: be distinct from the header space used for definitions.
1.21 crook 8104:
1.26 crook 8105: Typically, environmental queries are supported by creating a set of
1.29 crook 8106: definitions in a word list that is @i{only} used during environmental
1.26 crook 8107: queries; that is what Gforth does. There is no Standard way of adding
8108: definitions to the set of recognised environmental queries, but any
8109: implementation that supports the loading of optional word sets must have
8110: some mechanism for doing this (after loading the word set, the
8111: associated environmental query string must return @code{true}). In
8112: Gforth, the word list used to honour environmental queries can be
8113: manipulated just like any other word list.
1.21 crook 8114:
1.44 crook 8115:
1.26 crook 8116: doc-environment?
8117: doc-environment-wordlist
1.21 crook 8118:
1.26 crook 8119: doc-gforth
8120: doc-os-class
1.21 crook 8121:
1.44 crook 8122:
1.26 crook 8123: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8124: returning two items on the stack, querying it using @code{environment?}
8125: will return an additional item; the @code{true} flag that shows that the
8126: string was recognised.
1.21 crook 8127:
1.26 crook 8128: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8129:
1.26 crook 8130: Here are some examples of using environmental queries:
1.21 crook 8131:
1.26 crook 8132: @example
8133: s" address-unit-bits" environment? 0=
8134: [IF]
8135: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8136: [ELSE]
8137: drop \ ensure balanced stack effect
1.26 crook 8138: [THEN]
1.21 crook 8139:
1.75 anton 8140: \ this might occur in the prelude of a standard program that uses THROW
8141: s" exception" environment? [IF]
8142: 0= [IF]
8143: : throw abort" exception thrown" ;
8144: [THEN]
8145: [ELSE] \ we don't know, so make sure
8146: : throw abort" exception thrown" ;
8147: [THEN]
1.21 crook 8148:
1.26 crook 8149: s" gforth" environment? [IF] .( Gforth version ) TYPE
8150: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8151:
8152: \ a program using v*
8153: s" gforth" environment? [IF]
8154: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8155: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8156: >r swap 2swap swap 0e r> 0 ?DO
8157: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8158: LOOP
8159: 2drop 2drop ;
8160: [THEN]
8161: [ELSE] \
8162: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8163: ...
8164: [THEN]
1.26 crook 8165: @end example
1.21 crook 8166:
1.26 crook 8167: Here is an example of adding a definition to the environment word list:
1.21 crook 8168:
1.26 crook 8169: @example
8170: get-current environment-wordlist set-current
8171: true constant block
8172: true constant block-ext
8173: set-current
8174: @end example
1.21 crook 8175:
1.26 crook 8176: You can see what definitions are in the environment word list like this:
1.21 crook 8177:
1.26 crook 8178: @example
1.79 anton 8179: environment-wordlist >order words previous
1.26 crook 8180: @end example
1.21 crook 8181:
8182:
1.26 crook 8183: @c -------------------------------------------------------------
8184: @node Files, Blocks, Environmental Queries, Words
8185: @section Files
1.28 crook 8186: @cindex files
8187: @cindex I/O - file-handling
1.21 crook 8188:
1.26 crook 8189: Gforth provides facilities for accessing files that are stored in the
8190: host operating system's file-system. Files that are processed by Gforth
8191: can be divided into two categories:
1.21 crook 8192:
1.23 crook 8193: @itemize @bullet
8194: @item
1.29 crook 8195: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8196: @item
1.29 crook 8197: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8198: @end itemize
8199:
8200: @menu
1.48 anton 8201: * Forth source files::
8202: * General files::
8203: * Search Paths::
1.26 crook 8204: @end menu
8205:
8206: @c -------------------------------------------------------------
8207: @node Forth source files, General files, Files, Files
8208: @subsection Forth source files
8209: @cindex including files
8210: @cindex Forth source files
1.21 crook 8211:
1.26 crook 8212: The simplest way to interpret the contents of a file is to use one of
8213: these two formats:
1.21 crook 8214:
1.26 crook 8215: @example
8216: include mysource.fs
8217: s" mysource.fs" included
8218: @end example
1.21 crook 8219:
1.75 anton 8220: You usually want to include a file only if it is not included already
1.26 crook 8221: (by, say, another source file). In that case, you can use one of these
1.45 crook 8222: three formats:
1.21 crook 8223:
1.26 crook 8224: @example
8225: require mysource.fs
8226: needs mysource.fs
8227: s" mysource.fs" required
8228: @end example
1.21 crook 8229:
1.26 crook 8230: @cindex stack effect of included files
8231: @cindex including files, stack effect
1.45 crook 8232: It is good practice to write your source files such that interpreting them
8233: does not change the stack. Source files designed in this way can be used with
1.26 crook 8234: @code{required} and friends without complications. For example:
1.21 crook 8235:
1.26 crook 8236: @example
1.75 anton 8237: 1024 require foo.fs drop
1.26 crook 8238: @end example
1.21 crook 8239:
1.75 anton 8240: Here you want to pass the argument 1024 (e.g., a buffer size) to
8241: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8242: ), which allows its use with @code{require}. Of course with such
8243: parameters to required files, you have to ensure that the first
8244: @code{require} fits for all uses (i.e., @code{require} it early in the
8245: master load file).
1.44 crook 8246:
1.26 crook 8247: doc-include-file
8248: doc-included
1.28 crook 8249: doc-included?
1.26 crook 8250: doc-include
8251: doc-required
8252: doc-require
8253: doc-needs
1.75 anton 8254: @c doc-init-included-files @c internal
8255: doc-sourcefilename
8256: doc-sourceline#
1.44 crook 8257:
1.26 crook 8258: A definition in ANS Forth for @code{required} is provided in
8259: @file{compat/required.fs}.
1.21 crook 8260:
1.26 crook 8261: @c -------------------------------------------------------------
8262: @node General files, Search Paths, Forth source files, Files
8263: @subsection General files
8264: @cindex general files
8265: @cindex file-handling
1.21 crook 8266:
1.75 anton 8267: Files are opened/created by name and type. The following file access
8268: methods (FAMs) are recognised:
1.44 crook 8269:
1.75 anton 8270: @cindex fam (file access method)
1.26 crook 8271: doc-r/o
8272: doc-r/w
8273: doc-w/o
8274: doc-bin
1.1 anton 8275:
1.44 crook 8276:
1.26 crook 8277: When a file is opened/created, it returns a file identifier,
1.29 crook 8278: @i{wfileid} that is used for all other file commands. All file
8279: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8280: successful operation and an implementation-defined non-zero value in the
8281: case of an error.
1.21 crook 8282:
1.44 crook 8283:
1.26 crook 8284: doc-open-file
8285: doc-create-file
1.21 crook 8286:
1.26 crook 8287: doc-close-file
8288: doc-delete-file
8289: doc-rename-file
8290: doc-read-file
8291: doc-read-line
8292: doc-write-file
8293: doc-write-line
8294: doc-emit-file
8295: doc-flush-file
1.21 crook 8296:
1.26 crook 8297: doc-file-status
8298: doc-file-position
8299: doc-reposition-file
8300: doc-file-size
8301: doc-resize-file
1.21 crook 8302:
1.93 anton 8303: doc-slurp-file
8304: doc-slurp-fid
1.112 anton 8305: doc-stdin
8306: doc-stdout
8307: doc-stderr
1.44 crook 8308:
1.26 crook 8309: @c ---------------------------------------------------------
1.48 anton 8310: @node Search Paths, , General files, Files
1.26 crook 8311: @subsection Search Paths
8312: @cindex path for @code{included}
8313: @cindex file search path
8314: @cindex @code{include} search path
8315: @cindex search path for files
1.21 crook 8316:
1.26 crook 8317: If you specify an absolute filename (i.e., a filename starting with
8318: @file{/} or @file{~}, or with @file{:} in the second position (as in
8319: @samp{C:...})) for @code{included} and friends, that file is included
8320: just as you would expect.
1.21 crook 8321:
1.75 anton 8322: If the filename starts with @file{./}, this refers to the directory that
8323: the present file was @code{included} from. This allows files to include
8324: other files relative to their own position (irrespective of the current
8325: working directory or the absolute position). This feature is essential
8326: for libraries consisting of several files, where a file may include
8327: other files from the library. It corresponds to @code{#include "..."}
8328: in C. If the current input source is not a file, @file{.} refers to the
8329: directory of the innermost file being included, or, if there is no file
8330: being included, to the current working directory.
8331:
8332: For relative filenames (not starting with @file{./}), Gforth uses a
8333: search path similar to Forth's search order (@pxref{Word Lists}). It
8334: tries to find the given filename in the directories present in the path,
8335: and includes the first one it finds. There are separate search paths for
8336: Forth source files and general files. If the search path contains the
8337: directory @file{.}, this refers to the directory of the current file, or
8338: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8339:
1.26 crook 8340: Use @file{~+} to refer to the current working directory (as in the
8341: @code{bash}).
1.1 anton 8342:
1.75 anton 8343: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8344:
1.48 anton 8345: @menu
1.75 anton 8346: * Source Search Paths::
1.48 anton 8347: * General Search Paths::
8348: @end menu
8349:
1.26 crook 8350: @c ---------------------------------------------------------
1.75 anton 8351: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8352: @subsubsection Source Search Paths
8353: @cindex search path control, source files
1.5 anton 8354:
1.26 crook 8355: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8356: Gforth}). You can display it and change it using @code{fpath} in
8357: combination with the general path handling words.
1.5 anton 8358:
1.75 anton 8359: doc-fpath
8360: @c the functionality of the following words is easily available through
8361: @c fpath and the general path words. The may go away.
8362: @c doc-.fpath
8363: @c doc-fpath+
8364: @c doc-fpath=
8365: @c doc-open-fpath-file
1.44 crook 8366:
8367: @noindent
1.26 crook 8368: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8369:
1.26 crook 8370: @example
1.75 anton 8371: fpath path= /usr/lib/forth/|./
1.26 crook 8372: require timer.fs
8373: @end example
1.5 anton 8374:
1.75 anton 8375:
1.26 crook 8376: @c ---------------------------------------------------------
1.75 anton 8377: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8378: @subsubsection General Search Paths
1.75 anton 8379: @cindex search path control, source files
1.5 anton 8380:
1.26 crook 8381: Your application may need to search files in several directories, like
8382: @code{included} does. To facilitate this, Gforth allows you to define
8383: and use your own search paths, by providing generic equivalents of the
8384: Forth search path words:
1.5 anton 8385:
1.75 anton 8386: doc-open-path-file
8387: doc-path-allot
8388: doc-clear-path
8389: doc-also-path
1.26 crook 8390: doc-.path
8391: doc-path+
8392: doc-path=
1.5 anton 8393:
1.75 anton 8394: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8395:
1.75 anton 8396: Here's an example of creating an empty search path:
8397: @c
1.26 crook 8398: @example
1.75 anton 8399: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8400: @end example
1.5 anton 8401:
1.26 crook 8402: @c -------------------------------------------------------------
8403: @node Blocks, Other I/O, Files, Words
8404: @section Blocks
1.28 crook 8405: @cindex I/O - blocks
8406: @cindex blocks
8407:
8408: When you run Gforth on a modern desk-top computer, it runs under the
8409: control of an operating system which provides certain services. One of
8410: these services is @var{file services}, which allows Forth source code
8411: and data to be stored in files and read into Gforth (@pxref{Files}).
8412:
8413: Traditionally, Forth has been an important programming language on
8414: systems where it has interfaced directly to the underlying hardware with
8415: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8416: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8417:
8418: A block is a 1024-byte data area, which can be used to hold data or
8419: Forth source code. No structure is imposed on the contents of the
8420: block. A block is identified by its number; blocks are numbered
8421: contiguously from 1 to an implementation-defined maximum.
8422:
8423: A typical system that used blocks but no operating system might use a
8424: single floppy-disk drive for mass storage, with the disks formatted to
8425: provide 256-byte sectors. Blocks would be implemented by assigning the
8426: first four sectors of the disk to block 1, the second four sectors to
8427: block 2 and so on, up to the limit of the capacity of the disk. The disk
8428: would not contain any file system information, just the set of blocks.
8429:
1.29 crook 8430: @cindex blocks file
1.28 crook 8431: On systems that do provide file services, blocks are typically
1.29 crook 8432: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8433: file}. The size of the blocks file will be an exact multiple of 1024
8434: bytes, corresponding to the number of blocks it contains. This is the
8435: mechanism that Gforth uses.
8436:
1.29 crook 8437: @cindex @file{blocks.fb}
1.75 anton 8438: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8439: having specified a blocks file, Gforth defaults to the blocks file
8440: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8441: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8442:
1.29 crook 8443: @cindex block buffers
1.28 crook 8444: When you read and write blocks under program control, Gforth uses a
1.29 crook 8445: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8446: not used when you use @code{load} to interpret the contents of a block.
8447:
1.75 anton 8448: The behaviour of the block buffers is analagous to that of a cache.
8449: Each block buffer has three states:
1.28 crook 8450:
8451: @itemize @bullet
8452: @item
8453: Unassigned
8454: @item
8455: Assigned-clean
8456: @item
8457: Assigned-dirty
8458: @end itemize
8459:
1.29 crook 8460: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8461: block, the block (specified by its block number) must be assigned to a
8462: block buffer.
8463:
8464: The assignment of a block to a block buffer is performed by @code{block}
8465: or @code{buffer}. Use @code{block} when you wish to modify the existing
8466: contents of a block. Use @code{buffer} when you don't care about the
8467: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8468: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8469: with the particular block is already stored in a block buffer due to an
8470: earlier @code{block} command, @code{buffer} will return that block
8471: buffer and the existing contents of the block will be
8472: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8473: block buffer for the block.}.
1.28 crook 8474:
1.47 crook 8475: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8476: @code{buffer}, that block buffer becomes the @i{current block
8477: buffer}. Data may only be manipulated (read or written) within the
8478: current block buffer.
1.47 crook 8479:
8480: When the contents of the current block buffer has been modified it is
1.48 anton 8481: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8482: either abandon the changes (by doing nothing) or mark the block as
8483: changed (assigned-dirty), using @code{update}. Using @code{update} does
8484: not change the blocks file; it simply changes a block buffer's state to
8485: @i{assigned-dirty}. The block will be written implicitly when it's
8486: buffer is needed for another block, or explicitly by @code{flush} or
8487: @code{save-buffers}.
8488:
8489: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8490: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8491: @code{flush}.
1.28 crook 8492:
1.29 crook 8493: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8494: algorithm to assign a block buffer to a block. That means that any
8495: particular block can only be assigned to one specific block buffer,
1.29 crook 8496: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8497: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8498: the new block immediately. If it is @i{assigned-dirty} its current
8499: contents are written back to the blocks file on disk before it is
1.28 crook 8500: allocated to the new block.
8501:
8502: Although no structure is imposed on the contents of a block, it is
8503: traditional to display the contents as 16 lines each of 64 characters. A
8504: block provides a single, continuous stream of input (for example, it
8505: acts as a single parse area) -- there are no end-of-line characters
8506: within a block, and no end-of-file character at the end of a
8507: block. There are two consequences of this:
1.26 crook 8508:
1.28 crook 8509: @itemize @bullet
8510: @item
8511: The last character of one line wraps straight into the first character
8512: of the following line
8513: @item
8514: The word @code{\} -- comment to end of line -- requires special
8515: treatment; in the context of a block it causes all characters until the
8516: end of the current 64-character ``line'' to be ignored.
8517: @end itemize
8518:
8519: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8520: the current blocks file will be extended to the appropriate size and the
1.28 crook 8521: block buffer will be initialised with spaces.
8522:
1.47 crook 8523: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8524: for details) but doesn't encourage the use of blocks; the mechanism is
8525: only provided for backward compatibility -- ANS Forth requires blocks to
8526: be available when files are.
1.28 crook 8527:
8528: Common techniques that are used when working with blocks include:
8529:
8530: @itemize @bullet
8531: @item
8532: A screen editor that allows you to edit blocks without leaving the Forth
8533: environment.
8534: @item
8535: Shadow screens; where every code block has an associated block
8536: containing comments (for example: code in odd block numbers, comments in
8537: even block numbers). Typically, the block editor provides a convenient
8538: mechanism to toggle between code and comments.
8539: @item
8540: Load blocks; a single block (typically block 1) contains a number of
8541: @code{thru} commands which @code{load} the whole of the application.
8542: @end itemize
1.26 crook 8543:
1.29 crook 8544: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8545: integrated into a Forth programming environment.
1.26 crook 8546:
8547: @comment TODO what about errors on open-blocks?
1.44 crook 8548:
1.26 crook 8549: doc-open-blocks
8550: doc-use
1.75 anton 8551: doc-block-offset
1.26 crook 8552: doc-get-block-fid
8553: doc-block-position
1.28 crook 8554:
1.75 anton 8555: doc-list
1.28 crook 8556: doc-scr
8557:
1.45 crook 8558: doc---gforthman-block
1.28 crook 8559: doc-buffer
8560:
1.75 anton 8561: doc-empty-buffers
8562: doc-empty-buffer
1.26 crook 8563: doc-update
1.28 crook 8564: doc-updated?
1.26 crook 8565: doc-save-buffers
1.75 anton 8566: doc-save-buffer
1.26 crook 8567: doc-flush
1.28 crook 8568:
1.26 crook 8569: doc-load
8570: doc-thru
8571: doc-+load
8572: doc-+thru
1.45 crook 8573: doc---gforthman--->
1.26 crook 8574: doc-block-included
8575:
1.44 crook 8576:
1.26 crook 8577: @c -------------------------------------------------------------
1.126 pazsan 8578: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8579: @section Other I/O
1.28 crook 8580: @cindex I/O - keyboard and display
1.26 crook 8581:
8582: @menu
8583: * Simple numeric output:: Predefined formats
8584: * Formatted numeric output:: Formatted (pictured) output
8585: * String Formats:: How Forth stores strings in memory
1.67 anton 8586: * Displaying characters and strings:: Other stuff
1.26 crook 8587: * Input:: Input
1.112 anton 8588: * Pipes:: How to create your own pipes
1.26 crook 8589: @end menu
8590:
8591: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8592: @subsection Simple numeric output
1.28 crook 8593: @cindex numeric output - simple/free-format
1.5 anton 8594:
1.26 crook 8595: The simplest output functions are those that display numbers from the
8596: data or floating-point stacks. Floating-point output is always displayed
8597: using base 10. Numbers displayed from the data stack use the value stored
8598: in @code{base}.
1.5 anton 8599:
1.44 crook 8600:
1.26 crook 8601: doc-.
8602: doc-dec.
8603: doc-hex.
8604: doc-u.
8605: doc-.r
8606: doc-u.r
8607: doc-d.
8608: doc-ud.
8609: doc-d.r
8610: doc-ud.r
8611: doc-f.
8612: doc-fe.
8613: doc-fs.
1.111 anton 8614: doc-f.rdp
1.44 crook 8615:
1.26 crook 8616: Examples of printing the number 1234.5678E23 in the different floating-point output
8617: formats are shown below:
1.5 anton 8618:
8619: @example
1.26 crook 8620: f. 123456779999999000000000000.
8621: fe. 123.456779999999E24
8622: fs. 1.23456779999999E26
1.5 anton 8623: @end example
8624:
8625:
1.26 crook 8626: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8627: @subsection Formatted numeric output
1.28 crook 8628: @cindex formatted numeric output
1.26 crook 8629: @cindex pictured numeric output
1.28 crook 8630: @cindex numeric output - formatted
1.26 crook 8631:
1.29 crook 8632: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8633: output} for formatted printing of integers. In this technique, digits
8634: are extracted from the number (using the current output radix defined by
8635: @code{base}), converted to ASCII codes and appended to a string that is
8636: built in a scratch-pad area of memory (@pxref{core-idef,
8637: Implementation-defined options, Implementation-defined
8638: options}). Arbitrary characters can be appended to the string during the
8639: extraction process. The completed string is specified by an address
8640: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8641: under program control.
1.5 anton 8642:
1.75 anton 8643: All of the integer output words described in the previous section
8644: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8645: numeric output.
1.5 anton 8646:
1.47 crook 8647: Three important things to remember about pictured numeric output:
1.5 anton 8648:
1.26 crook 8649: @itemize @bullet
8650: @item
1.28 crook 8651: It always operates on double-precision numbers; to display a
1.49 anton 8652: single-precision number, convert it first (for ways of doing this
8653: @pxref{Double precision}).
1.26 crook 8654: @item
1.28 crook 8655: It always treats the double-precision number as though it were
8656: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8657: @item
8658: The string is built up from right to left; least significant digit first.
8659: @end itemize
1.5 anton 8660:
1.44 crook 8661:
1.26 crook 8662: doc-<#
1.47 crook 8663: doc-<<#
1.26 crook 8664: doc-#
8665: doc-#s
8666: doc-hold
8667: doc-sign
8668: doc-#>
1.47 crook 8669: doc-#>>
1.5 anton 8670:
1.26 crook 8671: doc-represent
1.111 anton 8672: doc-f>str-rdp
8673: doc-f>buf-rdp
1.5 anton 8674:
1.44 crook 8675:
8676: @noindent
1.26 crook 8677: Here are some examples of using pictured numeric output:
1.5 anton 8678:
8679: @example
1.26 crook 8680: : my-u. ( u -- )
8681: \ Simplest use of pns.. behaves like Standard u.
8682: 0 \ convert to unsigned double
1.75 anton 8683: <<# \ start conversion
1.26 crook 8684: #s \ convert all digits
8685: #> \ complete conversion
1.75 anton 8686: TYPE SPACE \ display, with trailing space
8687: #>> ; \ release hold area
1.5 anton 8688:
1.26 crook 8689: : cents-only ( u -- )
8690: 0 \ convert to unsigned double
1.75 anton 8691: <<# \ start conversion
1.26 crook 8692: # # \ convert two least-significant digits
8693: #> \ complete conversion, discard other digits
1.75 anton 8694: TYPE SPACE \ display, with trailing space
8695: #>> ; \ release hold area
1.5 anton 8696:
1.26 crook 8697: : dollars-and-cents ( u -- )
8698: 0 \ convert to unsigned double
1.75 anton 8699: <<# \ start conversion
1.26 crook 8700: # # \ convert two least-significant digits
8701: [char] . hold \ insert decimal point
8702: #s \ convert remaining digits
8703: [char] $ hold \ append currency symbol
8704: #> \ complete conversion
1.75 anton 8705: TYPE SPACE \ display, with trailing space
8706: #>> ; \ release hold area
1.5 anton 8707:
1.26 crook 8708: : my-. ( n -- )
8709: \ handling negatives.. behaves like Standard .
8710: s>d \ convert to signed double
8711: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8712: <<# \ start conversion
1.26 crook 8713: #s \ convert all digits
8714: rot sign \ get at sign byte, append "-" if needed
8715: #> \ complete conversion
1.75 anton 8716: TYPE SPACE \ display, with trailing space
8717: #>> ; \ release hold area
1.5 anton 8718:
1.26 crook 8719: : account. ( n -- )
1.75 anton 8720: \ accountants don't like minus signs, they use parentheses
1.26 crook 8721: \ for negative numbers
8722: s>d \ convert to signed double
8723: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8724: <<# \ start conversion
1.26 crook 8725: 2 pick \ get copy of sign byte
8726: 0< IF [char] ) hold THEN \ right-most character of output
8727: #s \ convert all digits
8728: rot \ get at sign byte
8729: 0< IF [char] ( hold THEN
8730: #> \ complete conversion
1.75 anton 8731: TYPE SPACE \ display, with trailing space
8732: #>> ; \ release hold area
8733:
1.5 anton 8734: @end example
8735:
1.26 crook 8736: Here are some examples of using these words:
1.5 anton 8737:
8738: @example
1.26 crook 8739: 1 my-u. 1
8740: hex -1 my-u. decimal FFFFFFFF
8741: 1 cents-only 01
8742: 1234 cents-only 34
8743: 2 dollars-and-cents $0.02
8744: 1234 dollars-and-cents $12.34
8745: 123 my-. 123
8746: -123 my. -123
8747: 123 account. 123
8748: -456 account. (456)
1.5 anton 8749: @end example
8750:
8751:
1.26 crook 8752: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8753: @subsection String Formats
1.27 crook 8754: @cindex strings - see character strings
8755: @cindex character strings - formats
1.28 crook 8756: @cindex I/O - see character strings
1.75 anton 8757: @cindex counted strings
8758:
8759: @c anton: this does not really belong here; maybe the memory section,
8760: @c or the principles chapter
1.26 crook 8761:
1.27 crook 8762: Forth commonly uses two different methods for representing character
8763: strings:
1.26 crook 8764:
8765: @itemize @bullet
8766: @item
8767: @cindex address of counted string
1.45 crook 8768: @cindex counted string
1.29 crook 8769: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8770: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8771: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8772: memory.
8773: @item
1.29 crook 8774: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8775: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8776: first byte of the string.
8777: @end itemize
8778:
8779: ANS Forth encourages the use of the second format when representing
1.75 anton 8780: strings.
1.26 crook 8781:
1.44 crook 8782:
1.26 crook 8783: doc-count
8784:
1.44 crook 8785:
1.49 anton 8786: For words that move, copy and search for strings see @ref{Memory
8787: Blocks}. For words that display characters and strings see
8788: @ref{Displaying characters and strings}.
1.26 crook 8789:
8790: @node Displaying characters and strings, Input, String Formats, Other I/O
8791: @subsection Displaying characters and strings
1.27 crook 8792: @cindex characters - compiling and displaying
8793: @cindex character strings - compiling and displaying
1.26 crook 8794:
8795: This section starts with a glossary of Forth words and ends with a set
8796: of examples.
8797:
1.44 crook 8798:
1.26 crook 8799: doc-bl
8800: doc-space
8801: doc-spaces
8802: doc-emit
8803: doc-toupper
8804: doc-."
8805: doc-.(
1.98 anton 8806: doc-.\"
1.26 crook 8807: doc-type
1.44 crook 8808: doc-typewhite
1.26 crook 8809: doc-cr
1.27 crook 8810: @cindex cursor control
1.26 crook 8811: doc-at-xy
8812: doc-page
8813: doc-s"
1.98 anton 8814: doc-s\"
1.26 crook 8815: doc-c"
8816: doc-char
8817: doc-[char]
8818:
1.44 crook 8819:
8820: @noindent
1.26 crook 8821: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8822:
8823: @example
1.26 crook 8824: .( text-1)
8825: : my-word
8826: ." text-2" cr
8827: .( text-3)
8828: ;
8829:
8830: ." text-4"
8831:
8832: : my-char
8833: [char] ALPHABET emit
8834: char emit
8835: ;
1.5 anton 8836: @end example
8837:
1.26 crook 8838: When you load this code into Gforth, the following output is generated:
1.5 anton 8839:
1.26 crook 8840: @example
1.30 anton 8841: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8842: @end example
1.5 anton 8843:
1.26 crook 8844: @itemize @bullet
8845: @item
8846: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8847: is an immediate word; it behaves in the same way whether it is used inside
8848: or outside a colon definition.
8849: @item
8850: Message @code{text-4} is displayed because of Gforth's added interpretation
8851: semantics for @code{."}.
8852: @item
1.29 crook 8853: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8854: performs the compilation semantics for @code{."} within the definition of
8855: @code{my-word}.
8856: @end itemize
1.5 anton 8857:
1.26 crook 8858: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8859:
1.26 crook 8860: @example
1.30 anton 8861: @kbd{my-word @key{RET}} text-2
1.26 crook 8862: ok
1.30 anton 8863: @kbd{my-char fred @key{RET}} Af ok
8864: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8865: @end example
1.5 anton 8866:
8867: @itemize @bullet
8868: @item
1.26 crook 8869: Message @code{text-2} is displayed because of the run-time behaviour of
8870: @code{."}.
8871: @item
8872: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8873: on the stack at run-time. @code{emit} always displays the character
8874: when @code{my-char} is executed.
8875: @item
8876: @code{char} parses a string at run-time and the second @code{emit} displays
8877: the first character of the string.
1.5 anton 8878: @item
1.26 crook 8879: If you type @code{see my-char} you can see that @code{[char]} discarded
8880: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8881: definition of @code{my-char}.
1.5 anton 8882: @end itemize
8883:
8884:
8885:
1.112 anton 8886: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8887: @subsection Input
8888: @cindex input
1.28 crook 8889: @cindex I/O - see input
8890: @cindex parsing a string
1.5 anton 8891:
1.49 anton 8892: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8893:
1.27 crook 8894: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8895: @comment then index them
1.27 crook 8896:
1.44 crook 8897:
1.27 crook 8898: doc-key
8899: doc-key?
1.45 crook 8900: doc-ekey
1.141 anton 8901: doc-ekey>char
1.45 crook 8902: doc-ekey?
1.141 anton 8903:
8904: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8905: you need the ANSI.SYS driver to get that behaviour). These are the
8906: keyboard events produced by various common keys:
8907:
8908: doc-k-left
8909: doc-k-right
8910: doc-k-up
8911: doc-k-down
8912: doc-k-home
8913: doc-k-end
8914: doc-k-prior
8915: doc-k-next
8916: doc-k-insert
8917: doc-k-delete
8918:
8919: The function keys (aka keypad keys) are:
8920:
8921: doc-k1
8922: doc-k2
8923: doc-k3
8924: doc-k4
8925: doc-k5
8926: doc-k6
8927: doc-k7
8928: doc-k8
8929: doc-k9
8930: doc-k10
8931: doc-k11
8932: doc-k12
8933:
8934: Note that K11 and K12 are not as widely available. The shifted
8935: function keys are also not very widely available:
8936:
8937: doc-s-k8
8938: doc-s-k1
8939: doc-s-k2
8940: doc-s-k3
8941: doc-s-k4
8942: doc-s-k5
8943: doc-s-k6
8944: doc-s-k7
8945: doc-s-k8
8946: doc-s-k9
8947: doc-s-k10
8948: doc-s-k11
8949: doc-s-k12
8950:
8951: Words for inputting one line from the keyboard:
8952:
8953: doc-accept
8954: doc-edit-line
8955:
8956: Conversion words:
8957:
1.143 anton 8958: doc-s>number?
8959: doc-s>unumber?
1.26 crook 8960: doc->number
8961: doc->float
1.143 anton 8962:
1.141 anton 8963:
1.27 crook 8964: @comment obsolescent words..
1.141 anton 8965: Obsolescent input and conversion words:
8966:
1.27 crook 8967: doc-convert
1.26 crook 8968: doc-expect
1.27 crook 8969: doc-span
1.5 anton 8970:
8971:
1.112 anton 8972: @node Pipes, , Input, Other I/O
8973: @subsection Pipes
8974: @cindex pipes, creating your own
8975:
8976: In addition to using Gforth in pipes created by other processes
8977: (@pxref{Gforth in pipes}), you can create your own pipe with
8978: @code{open-pipe}, and read from or write to it.
8979:
8980: doc-open-pipe
8981: doc-close-pipe
8982:
8983: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8984: you don't catch this exception, Gforth will catch it and exit, usually
8985: silently (@pxref{Gforth in pipes}). Since you probably do not want
8986: this, you should wrap a @code{catch} or @code{try} block around the code
8987: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8988: problem yourself, and then return to regular processing.
8989:
8990: doc-broken-pipe-error
8991:
8992:
1.121 anton 8993: @node OS command line arguments, Locals, Other I/O, Words
8994: @section OS command line arguments
8995: @cindex OS command line arguments
8996: @cindex command line arguments, OS
8997: @cindex arguments, OS command line
8998:
8999: The usual way to pass arguments to Gforth programs on the command line
9000: is via the @option{-e} option, e.g.
9001:
9002: @example
9003: gforth -e "123 456" foo.fs -e bye
9004: @end example
9005:
9006: However, you may want to interpret the command-line arguments directly.
9007: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9008: through @code{next-arg}:
1.121 anton 9009:
1.123 anton 9010: doc-next-arg
1.121 anton 9011:
1.123 anton 9012: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9013:
9014: @example
9015: : echo ( -- )
1.122 anton 9016: begin
1.123 anton 9017: next-arg 2dup 0 0 d<> while
9018: type space
9019: repeat
9020: 2drop ;
1.121 anton 9021:
9022: echo cr bye
9023: @end example
9024:
9025: This can be invoked with
9026:
9027: @example
9028: gforth echo.fs hello world
9029: @end example
1.123 anton 9030:
9031: and it will print
9032:
9033: @example
9034: hello world
9035: @end example
9036:
9037: The next lower level of dealing with the OS command line are the
9038: following words:
9039:
9040: doc-arg
9041: doc-shift-args
9042:
9043: Finally, at the lowest level Gforth provides the following words:
9044:
9045: doc-argc
9046: doc-argv
1.121 anton 9047:
1.78 anton 9048: @c -------------------------------------------------------------
1.126 pazsan 9049: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9050: @section Locals
9051: @cindex locals
9052:
9053: Local variables can make Forth programming more enjoyable and Forth
9054: programs easier to read. Unfortunately, the locals of ANS Forth are
9055: laden with restrictions. Therefore, we provide not only the ANS Forth
9056: locals wordset, but also our own, more powerful locals wordset (we
9057: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9058:
1.78 anton 9059: The ideas in this section have also been published in M. Anton Ertl,
9060: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9061: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9062:
9063: @menu
1.78 anton 9064: * Gforth locals::
9065: * ANS Forth locals::
1.5 anton 9066: @end menu
9067:
1.78 anton 9068: @node Gforth locals, ANS Forth locals, Locals, Locals
9069: @subsection Gforth locals
9070: @cindex Gforth locals
9071: @cindex locals, Gforth style
1.5 anton 9072:
1.78 anton 9073: Locals can be defined with
1.44 crook 9074:
1.78 anton 9075: @example
9076: @{ local1 local2 ... -- comment @}
9077: @end example
9078: or
9079: @example
9080: @{ local1 local2 ... @}
9081: @end example
1.5 anton 9082:
1.78 anton 9083: E.g.,
9084: @example
9085: : max @{ n1 n2 -- n3 @}
9086: n1 n2 > if
9087: n1
9088: else
9089: n2
9090: endif ;
9091: @end example
1.44 crook 9092:
1.78 anton 9093: The similarity of locals definitions with stack comments is intended. A
9094: locals definition often replaces the stack comment of a word. The order
9095: of the locals corresponds to the order in a stack comment and everything
9096: after the @code{--} is really a comment.
1.77 anton 9097:
1.78 anton 9098: This similarity has one disadvantage: It is too easy to confuse locals
9099: declarations with stack comments, causing bugs and making them hard to
9100: find. However, this problem can be avoided by appropriate coding
9101: conventions: Do not use both notations in the same program. If you do,
9102: they should be distinguished using additional means, e.g. by position.
1.77 anton 9103:
1.78 anton 9104: @cindex types of locals
9105: @cindex locals types
9106: The name of the local may be preceded by a type specifier, e.g.,
9107: @code{F:} for a floating point value:
1.5 anton 9108:
1.78 anton 9109: @example
9110: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9111: \ complex multiplication
9112: Ar Br f* Ai Bi f* f-
9113: Ar Bi f* Ai Br f* f+ ;
9114: @end example
1.44 crook 9115:
1.78 anton 9116: @cindex flavours of locals
9117: @cindex locals flavours
9118: @cindex value-flavoured locals
9119: @cindex variable-flavoured locals
9120: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9121: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9122: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9123: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9124: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9125: produces its address (which becomes invalid when the variable's scope is
9126: left). E.g., the standard word @code{emit} can be defined in terms of
9127: @code{type} like this:
1.5 anton 9128:
1.78 anton 9129: @example
9130: : emit @{ C^ char* -- @}
9131: char* 1 type ;
9132: @end example
1.5 anton 9133:
1.78 anton 9134: @cindex default type of locals
9135: @cindex locals, default type
9136: A local without type specifier is a @code{W:} local. Both flavours of
9137: locals are initialized with values from the data or FP stack.
1.44 crook 9138:
1.78 anton 9139: Currently there is no way to define locals with user-defined data
9140: structures, but we are working on it.
1.5 anton 9141:
1.78 anton 9142: Gforth allows defining locals everywhere in a colon definition. This
9143: poses the following questions:
1.5 anton 9144:
1.78 anton 9145: @menu
9146: * Where are locals visible by name?::
9147: * How long do locals live?::
9148: * Locals programming style::
9149: * Locals implementation::
9150: @end menu
1.44 crook 9151:
1.78 anton 9152: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9153: @subsubsection Where are locals visible by name?
9154: @cindex locals visibility
9155: @cindex visibility of locals
9156: @cindex scope of locals
1.5 anton 9157:
1.78 anton 9158: Basically, the answer is that locals are visible where you would expect
9159: it in block-structured languages, and sometimes a little longer. If you
9160: want to restrict the scope of a local, enclose its definition in
9161: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9162:
9163:
1.78 anton 9164: doc-scope
9165: doc-endscope
1.5 anton 9166:
9167:
1.78 anton 9168: These words behave like control structure words, so you can use them
9169: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9170: arbitrary ways.
1.77 anton 9171:
1.78 anton 9172: If you want a more exact answer to the visibility question, here's the
9173: basic principle: A local is visible in all places that can only be
9174: reached through the definition of the local@footnote{In compiler
9175: construction terminology, all places dominated by the definition of the
9176: local.}. In other words, it is not visible in places that can be reached
9177: without going through the definition of the local. E.g., locals defined
9178: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9179: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9180: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9181:
1.78 anton 9182: The reasoning behind this solution is: We want to have the locals
9183: visible as long as it is meaningful. The user can always make the
9184: visibility shorter by using explicit scoping. In a place that can
9185: only be reached through the definition of a local, the meaning of a
9186: local name is clear. In other places it is not: How is the local
9187: initialized at the control flow path that does not contain the
9188: definition? Which local is meant, if the same name is defined twice in
9189: two independent control flow paths?
1.77 anton 9190:
1.78 anton 9191: This should be enough detail for nearly all users, so you can skip the
9192: rest of this section. If you really must know all the gory details and
9193: options, read on.
1.77 anton 9194:
1.78 anton 9195: In order to implement this rule, the compiler has to know which places
9196: are unreachable. It knows this automatically after @code{AHEAD},
9197: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9198: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9199: compiler that the control flow never reaches that place. If
9200: @code{UNREACHABLE} is not used where it could, the only consequence is
9201: that the visibility of some locals is more limited than the rule above
9202: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9203: lie to the compiler), buggy code will be produced.
1.77 anton 9204:
1.5 anton 9205:
1.78 anton 9206: doc-unreachable
1.5 anton 9207:
1.23 crook 9208:
1.78 anton 9209: Another problem with this rule is that at @code{BEGIN}, the compiler
9210: does not know which locals will be visible on the incoming
9211: back-edge. All problems discussed in the following are due to this
9212: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9213: loops as examples; the discussion also applies to @code{?DO} and other
9214: loops). Perhaps the most insidious example is:
1.26 crook 9215: @example
1.78 anton 9216: AHEAD
9217: BEGIN
9218: x
9219: [ 1 CS-ROLL ] THEN
9220: @{ x @}
9221: ...
9222: UNTIL
1.26 crook 9223: @end example
1.23 crook 9224:
1.78 anton 9225: This should be legal according to the visibility rule. The use of
9226: @code{x} can only be reached through the definition; but that appears
9227: textually below the use.
9228:
9229: From this example it is clear that the visibility rules cannot be fully
9230: implemented without major headaches. Our implementation treats common
9231: cases as advertised and the exceptions are treated in a safe way: The
9232: compiler makes a reasonable guess about the locals visible after a
9233: @code{BEGIN}; if it is too pessimistic, the
9234: user will get a spurious error about the local not being defined; if the
9235: compiler is too optimistic, it will notice this later and issue a
9236: warning. In the case above the compiler would complain about @code{x}
9237: being undefined at its use. You can see from the obscure examples in
9238: this section that it takes quite unusual control structures to get the
9239: compiler into trouble, and even then it will often do fine.
1.23 crook 9240:
1.78 anton 9241: If the @code{BEGIN} is reachable from above, the most optimistic guess
9242: is that all locals visible before the @code{BEGIN} will also be
9243: visible after the @code{BEGIN}. This guess is valid for all loops that
9244: are entered only through the @code{BEGIN}, in particular, for normal
9245: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9246: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9247: compiler. When the branch to the @code{BEGIN} is finally generated by
9248: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9249: warns the user if it was too optimistic:
1.26 crook 9250: @example
1.78 anton 9251: IF
9252: @{ x @}
9253: BEGIN
9254: \ x ?
9255: [ 1 cs-roll ] THEN
9256: ...
9257: UNTIL
1.26 crook 9258: @end example
1.23 crook 9259:
1.78 anton 9260: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9261: optimistically assumes that it lives until the @code{THEN}. It notices
9262: this difference when it compiles the @code{UNTIL} and issues a
9263: warning. The user can avoid the warning, and make sure that @code{x}
9264: is not used in the wrong area by using explicit scoping:
9265: @example
9266: IF
9267: SCOPE
9268: @{ x @}
9269: ENDSCOPE
9270: BEGIN
9271: [ 1 cs-roll ] THEN
9272: ...
9273: UNTIL
9274: @end example
1.23 crook 9275:
1.78 anton 9276: Since the guess is optimistic, there will be no spurious error messages
9277: about undefined locals.
1.44 crook 9278:
1.78 anton 9279: If the @code{BEGIN} is not reachable from above (e.g., after
9280: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9281: optimistic guess, as the locals visible after the @code{BEGIN} may be
9282: defined later. Therefore, the compiler assumes that no locals are
9283: visible after the @code{BEGIN}. However, the user can use
9284: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9285: visible at the BEGIN as at the point where the top control-flow stack
9286: item was created.
1.23 crook 9287:
1.44 crook 9288:
1.78 anton 9289: doc-assume-live
1.26 crook 9290:
1.23 crook 9291:
1.78 anton 9292: @noindent
9293: E.g.,
9294: @example
9295: @{ x @}
9296: AHEAD
9297: ASSUME-LIVE
9298: BEGIN
9299: x
9300: [ 1 CS-ROLL ] THEN
9301: ...
9302: UNTIL
9303: @end example
1.44 crook 9304:
1.78 anton 9305: Other cases where the locals are defined before the @code{BEGIN} can be
9306: handled by inserting an appropriate @code{CS-ROLL} before the
9307: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9308: behind the @code{ASSUME-LIVE}).
1.23 crook 9309:
1.78 anton 9310: Cases where locals are defined after the @code{BEGIN} (but should be
9311: visible immediately after the @code{BEGIN}) can only be handled by
9312: rearranging the loop. E.g., the ``most insidious'' example above can be
9313: arranged into:
9314: @example
9315: BEGIN
9316: @{ x @}
9317: ... 0=
9318: WHILE
9319: x
9320: REPEAT
9321: @end example
1.44 crook 9322:
1.78 anton 9323: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9324: @subsubsection How long do locals live?
9325: @cindex locals lifetime
9326: @cindex lifetime of locals
1.23 crook 9327:
1.78 anton 9328: The right answer for the lifetime question would be: A local lives at
9329: least as long as it can be accessed. For a value-flavoured local this
9330: means: until the end of its visibility. However, a variable-flavoured
9331: local could be accessed through its address far beyond its visibility
9332: scope. Ultimately, this would mean that such locals would have to be
9333: garbage collected. Since this entails un-Forth-like implementation
9334: complexities, I adopted the same cowardly solution as some other
9335: languages (e.g., C): The local lives only as long as it is visible;
9336: afterwards its address is invalid (and programs that access it
9337: afterwards are erroneous).
1.23 crook 9338:
1.78 anton 9339: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9340: @subsubsection Locals programming style
9341: @cindex locals programming style
9342: @cindex programming style, locals
1.23 crook 9343:
1.78 anton 9344: The freedom to define locals anywhere has the potential to change
9345: programming styles dramatically. In particular, the need to use the
9346: return stack for intermediate storage vanishes. Moreover, all stack
9347: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9348: determined arguments) can be eliminated: If the stack items are in the
9349: wrong order, just write a locals definition for all of them; then
9350: write the items in the order you want.
1.23 crook 9351:
1.78 anton 9352: This seems a little far-fetched and eliminating stack manipulations is
9353: unlikely to become a conscious programming objective. Still, the number
9354: of stack manipulations will be reduced dramatically if local variables
9355: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9356: a traditional implementation of @code{max}).
1.23 crook 9357:
1.78 anton 9358: This shows one potential benefit of locals: making Forth programs more
9359: readable. Of course, this benefit will only be realized if the
9360: programmers continue to honour the principle of factoring instead of
9361: using the added latitude to make the words longer.
1.23 crook 9362:
1.78 anton 9363: @cindex single-assignment style for locals
9364: Using @code{TO} can and should be avoided. Without @code{TO},
9365: every value-flavoured local has only a single assignment and many
9366: advantages of functional languages apply to Forth. I.e., programs are
9367: easier to analyse, to optimize and to read: It is clear from the
9368: definition what the local stands for, it does not turn into something
9369: different later.
1.23 crook 9370:
1.78 anton 9371: E.g., a definition using @code{TO} might look like this:
9372: @example
9373: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9374: u1 u2 min 0
9375: ?do
9376: addr1 c@@ addr2 c@@ -
9377: ?dup-if
9378: unloop exit
9379: then
9380: addr1 char+ TO addr1
9381: addr2 char+ TO addr2
9382: loop
9383: u1 u2 - ;
1.26 crook 9384: @end example
1.78 anton 9385: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9386: every loop iteration. @code{strcmp} is a typical example of the
9387: readability problems of using @code{TO}. When you start reading
9388: @code{strcmp}, you think that @code{addr1} refers to the start of the
9389: string. Only near the end of the loop you realize that it is something
9390: else.
1.23 crook 9391:
1.78 anton 9392: This can be avoided by defining two locals at the start of the loop that
9393: are initialized with the right value for the current iteration.
9394: @example
9395: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9396: addr1 addr2
9397: u1 u2 min 0
9398: ?do @{ s1 s2 @}
9399: s1 c@@ s2 c@@ -
9400: ?dup-if
9401: unloop exit
9402: then
9403: s1 char+ s2 char+
9404: loop
9405: 2drop
9406: u1 u2 - ;
9407: @end example
9408: Here it is clear from the start that @code{s1} has a different value
9409: in every loop iteration.
1.23 crook 9410:
1.78 anton 9411: @node Locals implementation, , Locals programming style, Gforth locals
9412: @subsubsection Locals implementation
9413: @cindex locals implementation
9414: @cindex implementation of locals
1.23 crook 9415:
1.78 anton 9416: @cindex locals stack
9417: Gforth uses an extra locals stack. The most compelling reason for
9418: this is that the return stack is not float-aligned; using an extra stack
9419: also eliminates the problems and restrictions of using the return stack
9420: as locals stack. Like the other stacks, the locals stack grows toward
9421: lower addresses. A few primitives allow an efficient implementation:
9422:
9423:
9424: doc-@local#
9425: doc-f@local#
9426: doc-laddr#
9427: doc-lp+!#
9428: doc-lp!
9429: doc->l
9430: doc-f>l
9431:
9432:
9433: In addition to these primitives, some specializations of these
9434: primitives for commonly occurring inline arguments are provided for
9435: efficiency reasons, e.g., @code{@@local0} as specialization of
9436: @code{@@local#} for the inline argument 0. The following compiling words
9437: compile the right specialized version, or the general version, as
9438: appropriate:
1.23 crook 9439:
1.5 anton 9440:
1.107 dvdkhlng 9441: @c doc-compile-@local
9442: @c doc-compile-f@local
1.78 anton 9443: doc-compile-lp+!
1.5 anton 9444:
9445:
1.78 anton 9446: Combinations of conditional branches and @code{lp+!#} like
9447: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9448: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9449:
1.78 anton 9450: A special area in the dictionary space is reserved for keeping the
9451: local variable names. @code{@{} switches the dictionary pointer to this
9452: area and @code{@}} switches it back and generates the locals
9453: initializing code. @code{W:} etc.@ are normal defining words. This
9454: special area is cleared at the start of every colon definition.
1.5 anton 9455:
1.78 anton 9456: @cindex word list for defining locals
9457: A special feature of Gforth's dictionary is used to implement the
9458: definition of locals without type specifiers: every word list (aka
9459: vocabulary) has its own methods for searching
9460: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9461: with a special search method: When it is searched for a word, it
9462: actually creates that word using @code{W:}. @code{@{} changes the search
9463: order to first search the word list containing @code{@}}, @code{W:} etc.,
9464: and then the word list for defining locals without type specifiers.
1.5 anton 9465:
1.78 anton 9466: The lifetime rules support a stack discipline within a colon
9467: definition: The lifetime of a local is either nested with other locals
9468: lifetimes or it does not overlap them.
1.23 crook 9469:
1.78 anton 9470: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9471: pointer manipulation is generated. Between control structure words
9472: locals definitions can push locals onto the locals stack. @code{AGAIN}
9473: is the simplest of the other three control flow words. It has to
9474: restore the locals stack depth of the corresponding @code{BEGIN}
9475: before branching. The code looks like this:
9476: @format
9477: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9478: @code{branch} <begin>
9479: @end format
1.26 crook 9480:
1.78 anton 9481: @code{UNTIL} is a little more complicated: If it branches back, it
9482: must adjust the stack just like @code{AGAIN}. But if it falls through,
9483: the locals stack must not be changed. The compiler generates the
9484: following code:
9485: @format
9486: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9487: @end format
9488: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9489:
1.78 anton 9490: @code{THEN} can produce somewhat inefficient code:
9491: @format
9492: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9493: <orig target>:
9494: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9495: @end format
9496: The second @code{lp+!#} adjusts the locals stack pointer from the
9497: level at the @i{orig} point to the level after the @code{THEN}. The
9498: first @code{lp+!#} adjusts the locals stack pointer from the current
9499: level to the level at the orig point, so the complete effect is an
9500: adjustment from the current level to the right level after the
9501: @code{THEN}.
1.26 crook 9502:
1.78 anton 9503: @cindex locals information on the control-flow stack
9504: @cindex control-flow stack items, locals information
9505: In a conventional Forth implementation a dest control-flow stack entry
9506: is just the target address and an orig entry is just the address to be
9507: patched. Our locals implementation adds a word list to every orig or dest
9508: item. It is the list of locals visible (or assumed visible) at the point
9509: described by the entry. Our implementation also adds a tag to identify
9510: the kind of entry, in particular to differentiate between live and dead
9511: (reachable and unreachable) orig entries.
1.26 crook 9512:
1.78 anton 9513: A few unusual operations have to be performed on locals word lists:
1.44 crook 9514:
1.5 anton 9515:
1.78 anton 9516: doc-common-list
9517: doc-sub-list?
9518: doc-list-size
1.52 anton 9519:
9520:
1.78 anton 9521: Several features of our locals word list implementation make these
9522: operations easy to implement: The locals word lists are organised as
9523: linked lists; the tails of these lists are shared, if the lists
9524: contain some of the same locals; and the address of a name is greater
9525: than the address of the names behind it in the list.
1.5 anton 9526:
1.78 anton 9527: Another important implementation detail is the variable
9528: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9529: determine if they can be reached directly or only through the branch
9530: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9531: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9532: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9533:
1.78 anton 9534: Counted loops are similar to other loops in most respects, but
9535: @code{LEAVE} requires special attention: It performs basically the same
9536: service as @code{AHEAD}, but it does not create a control-flow stack
9537: entry. Therefore the information has to be stored elsewhere;
9538: traditionally, the information was stored in the target fields of the
9539: branches created by the @code{LEAVE}s, by organizing these fields into a
9540: linked list. Unfortunately, this clever trick does not provide enough
9541: space for storing our extended control flow information. Therefore, we
9542: introduce another stack, the leave stack. It contains the control-flow
9543: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9544:
1.78 anton 9545: Local names are kept until the end of the colon definition, even if
9546: they are no longer visible in any control-flow path. In a few cases
9547: this may lead to increased space needs for the locals name area, but
9548: usually less than reclaiming this space would cost in code size.
1.5 anton 9549:
1.44 crook 9550:
1.78 anton 9551: @node ANS Forth locals, , Gforth locals, Locals
9552: @subsection ANS Forth locals
9553: @cindex locals, ANS Forth style
1.5 anton 9554:
1.78 anton 9555: The ANS Forth locals wordset does not define a syntax for locals, but
9556: words that make it possible to define various syntaxes. One of the
9557: possible syntaxes is a subset of the syntax we used in the Gforth locals
9558: wordset, i.e.:
1.29 crook 9559:
9560: @example
1.78 anton 9561: @{ local1 local2 ... -- comment @}
9562: @end example
9563: @noindent
9564: or
9565: @example
9566: @{ local1 local2 ... @}
1.29 crook 9567: @end example
9568:
1.78 anton 9569: The order of the locals corresponds to the order in a stack comment. The
9570: restrictions are:
1.5 anton 9571:
1.78 anton 9572: @itemize @bullet
9573: @item
9574: Locals can only be cell-sized values (no type specifiers are allowed).
9575: @item
9576: Locals can be defined only outside control structures.
9577: @item
9578: Locals can interfere with explicit usage of the return stack. For the
9579: exact (and long) rules, see the standard. If you don't use return stack
9580: accessing words in a definition using locals, you will be all right. The
9581: purpose of this rule is to make locals implementation on the return
9582: stack easier.
9583: @item
9584: The whole definition must be in one line.
9585: @end itemize
1.5 anton 9586:
1.78 anton 9587: Locals defined in ANS Forth behave like @code{VALUE}s
9588: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9589: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9590:
1.78 anton 9591: Since the syntax above is supported by Gforth directly, you need not do
9592: anything to use it. If you want to port a program using this syntax to
9593: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9594: syntax on the other system.
1.5 anton 9595:
1.78 anton 9596: Note that a syntax shown in the standard, section A.13 looks
9597: similar, but is quite different in having the order of locals
9598: reversed. Beware!
1.5 anton 9599:
1.78 anton 9600: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9601:
1.78 anton 9602: doc-(local)
1.5 anton 9603:
1.78 anton 9604: The ANS Forth locals extension wordset defines a syntax using
9605: @code{locals|}, but it is so awful that we strongly recommend not to use
9606: it. We have implemented this syntax to make porting to Gforth easy, but
9607: do not document it here. The problem with this syntax is that the locals
9608: are defined in an order reversed with respect to the standard stack
9609: comment notation, making programs harder to read, and easier to misread
9610: and miswrite. The only merit of this syntax is that it is easy to
9611: implement using the ANS Forth locals wordset.
1.53 anton 9612:
9613:
1.78 anton 9614: @c ----------------------------------------------------------
9615: @node Structures, Object-oriented Forth, Locals, Words
9616: @section Structures
9617: @cindex structures
9618: @cindex records
1.53 anton 9619:
1.78 anton 9620: This section presents the structure package that comes with Gforth. A
9621: version of the package implemented in ANS Forth is available in
9622: @file{compat/struct.fs}. This package was inspired by a posting on
9623: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9624: possibly John Hayes). A version of this section has been published in
9625: M. Anton Ertl,
9626: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9627: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9628: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9629:
1.78 anton 9630: @menu
9631: * Why explicit structure support?::
9632: * Structure Usage::
9633: * Structure Naming Convention::
9634: * Structure Implementation::
9635: * Structure Glossary::
9636: @end menu
1.55 anton 9637:
1.78 anton 9638: @node Why explicit structure support?, Structure Usage, Structures, Structures
9639: @subsection Why explicit structure support?
1.53 anton 9640:
1.78 anton 9641: @cindex address arithmetic for structures
9642: @cindex structures using address arithmetic
9643: If we want to use a structure containing several fields, we could simply
9644: reserve memory for it, and access the fields using address arithmetic
9645: (@pxref{Address arithmetic}). As an example, consider a structure with
9646: the following fields
1.57 anton 9647:
1.78 anton 9648: @table @code
9649: @item a
9650: is a float
9651: @item b
9652: is a cell
9653: @item c
9654: is a float
9655: @end table
1.57 anton 9656:
1.78 anton 9657: Given the (float-aligned) base address of the structure we get the
9658: address of the field
1.52 anton 9659:
1.78 anton 9660: @table @code
9661: @item a
9662: without doing anything further.
9663: @item b
9664: with @code{float+}
9665: @item c
9666: with @code{float+ cell+ faligned}
9667: @end table
1.52 anton 9668:
1.78 anton 9669: It is easy to see that this can become quite tiring.
1.52 anton 9670:
1.78 anton 9671: Moreover, it is not very readable, because seeing a
9672: @code{cell+} tells us neither which kind of structure is
9673: accessed nor what field is accessed; we have to somehow infer the kind
9674: of structure, and then look up in the documentation, which field of
9675: that structure corresponds to that offset.
1.53 anton 9676:
1.78 anton 9677: Finally, this kind of address arithmetic also causes maintenance
9678: troubles: If you add or delete a field somewhere in the middle of the
9679: structure, you have to find and change all computations for the fields
9680: afterwards.
1.52 anton 9681:
1.78 anton 9682: So, instead of using @code{cell+} and friends directly, how
9683: about storing the offsets in constants:
1.52 anton 9684:
1.78 anton 9685: @example
9686: 0 constant a-offset
9687: 0 float+ constant b-offset
9688: 0 float+ cell+ faligned c-offset
9689: @end example
1.64 pazsan 9690:
1.78 anton 9691: Now we can get the address of field @code{x} with @code{x-offset
9692: +}. This is much better in all respects. Of course, you still
9693: have to change all later offset definitions if you add a field. You can
9694: fix this by declaring the offsets in the following way:
1.57 anton 9695:
1.78 anton 9696: @example
9697: 0 constant a-offset
9698: a-offset float+ constant b-offset
9699: b-offset cell+ faligned constant c-offset
9700: @end example
1.57 anton 9701:
1.78 anton 9702: Since we always use the offsets with @code{+}, we could use a defining
9703: word @code{cfield} that includes the @code{+} in the action of the
9704: defined word:
1.64 pazsan 9705:
1.78 anton 9706: @example
9707: : cfield ( n "name" -- )
9708: create ,
9709: does> ( name execution: addr1 -- addr2 )
9710: @@ + ;
1.64 pazsan 9711:
1.78 anton 9712: 0 cfield a
9713: 0 a float+ cfield b
9714: 0 b cell+ faligned cfield c
9715: @end example
1.64 pazsan 9716:
1.78 anton 9717: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9718:
1.78 anton 9719: The structure field words now can be used quite nicely. However,
9720: their definition is still a bit cumbersome: We have to repeat the
9721: name, the information about size and alignment is distributed before
9722: and after the field definitions etc. The structure package presented
9723: here addresses these problems.
1.64 pazsan 9724:
1.78 anton 9725: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9726: @subsection Structure Usage
9727: @cindex structure usage
1.57 anton 9728:
1.78 anton 9729: @cindex @code{field} usage
9730: @cindex @code{struct} usage
9731: @cindex @code{end-struct} usage
9732: You can define a structure for a (data-less) linked list with:
1.57 anton 9733: @example
1.78 anton 9734: struct
9735: cell% field list-next
9736: end-struct list%
1.57 anton 9737: @end example
9738:
1.78 anton 9739: With the address of the list node on the stack, you can compute the
9740: address of the field that contains the address of the next node with
9741: @code{list-next}. E.g., you can determine the length of a list
9742: with:
1.57 anton 9743:
9744: @example
1.78 anton 9745: : list-length ( list -- n )
9746: \ "list" is a pointer to the first element of a linked list
9747: \ "n" is the length of the list
9748: 0 BEGIN ( list1 n1 )
9749: over
9750: WHILE ( list1 n1 )
9751: 1+ swap list-next @@ swap
9752: REPEAT
9753: nip ;
1.57 anton 9754: @end example
9755:
1.78 anton 9756: You can reserve memory for a list node in the dictionary with
9757: @code{list% %allot}, which leaves the address of the list node on the
9758: stack. For the equivalent allocation on the heap you can use @code{list%
9759: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9760: use @code{list% %allocate}). You can get the the size of a list
9761: node with @code{list% %size} and its alignment with @code{list%
9762: %alignment}.
9763:
9764: Note that in ANS Forth the body of a @code{create}d word is
9765: @code{aligned} but not necessarily @code{faligned};
9766: therefore, if you do a:
1.57 anton 9767:
9768: @example
1.78 anton 9769: create @emph{name} foo% %allot drop
1.57 anton 9770: @end example
9771:
1.78 anton 9772: @noindent
9773: then the memory alloted for @code{foo%} is guaranteed to start at the
9774: body of @code{@emph{name}} only if @code{foo%} contains only character,
9775: cell and double fields. Therefore, if your structure contains floats,
9776: better use
1.57 anton 9777:
9778: @example
1.78 anton 9779: foo% %allot constant @emph{name}
1.57 anton 9780: @end example
9781:
1.78 anton 9782: @cindex structures containing structures
9783: You can include a structure @code{foo%} as a field of
9784: another structure, like this:
1.65 anton 9785: @example
1.78 anton 9786: struct
9787: ...
9788: foo% field ...
9789: ...
9790: end-struct ...
1.65 anton 9791: @end example
1.52 anton 9792:
1.78 anton 9793: @cindex structure extension
9794: @cindex extended records
9795: Instead of starting with an empty structure, you can extend an
9796: existing structure. E.g., a plain linked list without data, as defined
9797: above, is hardly useful; You can extend it to a linked list of integers,
9798: like this:@footnote{This feature is also known as @emph{extended
9799: records}. It is the main innovation in the Oberon language; in other
9800: words, adding this feature to Modula-2 led Wirth to create a new
9801: language, write a new compiler etc. Adding this feature to Forth just
9802: required a few lines of code.}
1.52 anton 9803:
1.78 anton 9804: @example
9805: list%
9806: cell% field intlist-int
9807: end-struct intlist%
9808: @end example
1.55 anton 9809:
1.78 anton 9810: @code{intlist%} is a structure with two fields:
9811: @code{list-next} and @code{intlist-int}.
1.55 anton 9812:
1.78 anton 9813: @cindex structures containing arrays
9814: You can specify an array type containing @emph{n} elements of
9815: type @code{foo%} like this:
1.55 anton 9816:
9817: @example
1.78 anton 9818: foo% @emph{n} *
1.56 anton 9819: @end example
1.55 anton 9820:
1.78 anton 9821: You can use this array type in any place where you can use a normal
9822: type, e.g., when defining a @code{field}, or with
9823: @code{%allot}.
9824:
9825: @cindex first field optimization
9826: The first field is at the base address of a structure and the word for
9827: this field (e.g., @code{list-next}) actually does not change the address
9828: on the stack. You may be tempted to leave it away in the interest of
9829: run-time and space efficiency. This is not necessary, because the
9830: structure package optimizes this case: If you compile a first-field
9831: words, no code is generated. So, in the interest of readability and
9832: maintainability you should include the word for the field when accessing
9833: the field.
1.52 anton 9834:
9835:
1.78 anton 9836: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9837: @subsection Structure Naming Convention
9838: @cindex structure naming convention
1.52 anton 9839:
1.78 anton 9840: The field names that come to (my) mind are often quite generic, and,
9841: if used, would cause frequent name clashes. E.g., many structures
9842: probably contain a @code{counter} field. The structure names
9843: that come to (my) mind are often also the logical choice for the names
9844: of words that create such a structure.
1.52 anton 9845:
1.78 anton 9846: Therefore, I have adopted the following naming conventions:
1.52 anton 9847:
1.78 anton 9848: @itemize @bullet
9849: @cindex field naming convention
9850: @item
9851: The names of fields are of the form
9852: @code{@emph{struct}-@emph{field}}, where
9853: @code{@emph{struct}} is the basic name of the structure, and
9854: @code{@emph{field}} is the basic name of the field. You can
9855: think of field words as converting the (address of the)
9856: structure into the (address of the) field.
1.52 anton 9857:
1.78 anton 9858: @cindex structure naming convention
9859: @item
9860: The names of structures are of the form
9861: @code{@emph{struct}%}, where
9862: @code{@emph{struct}} is the basic name of the structure.
9863: @end itemize
1.52 anton 9864:
1.78 anton 9865: This naming convention does not work that well for fields of extended
9866: structures; e.g., the integer list structure has a field
9867: @code{intlist-int}, but has @code{list-next}, not
9868: @code{intlist-next}.
1.53 anton 9869:
1.78 anton 9870: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9871: @subsection Structure Implementation
9872: @cindex structure implementation
9873: @cindex implementation of structures
1.52 anton 9874:
1.78 anton 9875: The central idea in the implementation is to pass the data about the
9876: structure being built on the stack, not in some global
9877: variable. Everything else falls into place naturally once this design
9878: decision is made.
1.53 anton 9879:
1.78 anton 9880: The type description on the stack is of the form @emph{align
9881: size}. Keeping the size on the top-of-stack makes dealing with arrays
9882: very simple.
1.53 anton 9883:
1.78 anton 9884: @code{field} is a defining word that uses @code{Create}
9885: and @code{DOES>}. The body of the field contains the offset
9886: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9887:
9888: @example
1.78 anton 9889: @@ +
1.53 anton 9890: @end example
9891:
1.78 anton 9892: @noindent
9893: i.e., add the offset to the address, giving the stack effect
9894: @i{addr1 -- addr2} for a field.
9895:
9896: @cindex first field optimization, implementation
9897: This simple structure is slightly complicated by the optimization
9898: for fields with offset 0, which requires a different
9899: @code{DOES>}-part (because we cannot rely on there being
9900: something on the stack if such a field is invoked during
9901: compilation). Therefore, we put the different @code{DOES>}-parts
9902: in separate words, and decide which one to invoke based on the
9903: offset. For a zero offset, the field is basically a noop; it is
9904: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9905:
1.78 anton 9906: @node Structure Glossary, , Structure Implementation, Structures
9907: @subsection Structure Glossary
9908: @cindex structure glossary
1.53 anton 9909:
1.5 anton 9910:
1.78 anton 9911: doc-%align
9912: doc-%alignment
9913: doc-%alloc
9914: doc-%allocate
9915: doc-%allot
9916: doc-cell%
9917: doc-char%
9918: doc-dfloat%
9919: doc-double%
9920: doc-end-struct
9921: doc-field
9922: doc-float%
9923: doc-naligned
9924: doc-sfloat%
9925: doc-%size
9926: doc-struct
1.54 anton 9927:
9928:
1.26 crook 9929: @c -------------------------------------------------------------
1.78 anton 9930: @node Object-oriented Forth, Programming Tools, Structures, Words
9931: @section Object-oriented Forth
9932:
9933: Gforth comes with three packages for object-oriented programming:
9934: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9935: is preloaded, so you have to @code{include} them before use. The most
9936: important differences between these packages (and others) are discussed
9937: in @ref{Comparison with other object models}. All packages are written
9938: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9939:
1.78 anton 9940: @menu
9941: * Why object-oriented programming?::
9942: * Object-Oriented Terminology::
9943: * Objects::
9944: * OOF::
9945: * Mini-OOF::
9946: * Comparison with other object models::
9947: @end menu
1.5 anton 9948:
1.78 anton 9949: @c ----------------------------------------------------------------
9950: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9951: @subsection Why object-oriented programming?
9952: @cindex object-oriented programming motivation
9953: @cindex motivation for object-oriented programming
1.44 crook 9954:
1.78 anton 9955: Often we have to deal with several data structures (@emph{objects}),
9956: that have to be treated similarly in some respects, but differently in
9957: others. Graphical objects are the textbook example: circles, triangles,
9958: dinosaurs, icons, and others, and we may want to add more during program
9959: development. We want to apply some operations to any graphical object,
9960: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9961: has to do something different for every kind of object.
9962: @comment TODO add some other operations eg perimeter, area
9963: @comment and tie in to concrete examples later..
1.5 anton 9964:
1.78 anton 9965: We could implement @code{draw} as a big @code{CASE}
9966: control structure that executes the appropriate code depending on the
9967: kind of object to be drawn. This would be not be very elegant, and,
9968: moreover, we would have to change @code{draw} every time we add
9969: a new kind of graphical object (say, a spaceship).
1.44 crook 9970:
1.78 anton 9971: What we would rather do is: When defining spaceships, we would tell
9972: the system: ``Here's how you @code{draw} a spaceship; you figure
9973: out the rest''.
1.5 anton 9974:
1.78 anton 9975: This is the problem that all systems solve that (rightfully) call
9976: themselves object-oriented; the object-oriented packages presented here
9977: solve this problem (and not much else).
9978: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9979:
1.78 anton 9980: @c ------------------------------------------------------------------------
9981: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9982: @subsection Object-Oriented Terminology
9983: @cindex object-oriented terminology
9984: @cindex terminology for object-oriented programming
1.5 anton 9985:
1.78 anton 9986: This section is mainly for reference, so you don't have to understand
9987: all of it right away. The terminology is mainly Smalltalk-inspired. In
9988: short:
1.44 crook 9989:
1.78 anton 9990: @table @emph
9991: @cindex class
9992: @item class
9993: a data structure definition with some extras.
1.5 anton 9994:
1.78 anton 9995: @cindex object
9996: @item object
9997: an instance of the data structure described by the class definition.
1.5 anton 9998:
1.78 anton 9999: @cindex instance variables
10000: @item instance variables
10001: fields of the data structure.
1.5 anton 10002:
1.78 anton 10003: @cindex selector
10004: @cindex method selector
10005: @cindex virtual function
10006: @item selector
10007: (or @emph{method selector}) a word (e.g.,
10008: @code{draw}) that performs an operation on a variety of data
10009: structures (classes). A selector describes @emph{what} operation to
10010: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10011:
1.78 anton 10012: @cindex method
10013: @item method
10014: the concrete definition that performs the operation
10015: described by the selector for a specific class. A method specifies
10016: @emph{how} the operation is performed for a specific class.
1.5 anton 10017:
1.78 anton 10018: @cindex selector invocation
10019: @cindex message send
10020: @cindex invoking a selector
10021: @item selector invocation
10022: a call of a selector. One argument of the call (the TOS (top-of-stack))
10023: is used for determining which method is used. In Smalltalk terminology:
10024: a message (consisting of the selector and the other arguments) is sent
10025: to the object.
1.5 anton 10026:
1.78 anton 10027: @cindex receiving object
10028: @item receiving object
10029: the object used for determining the method executed by a selector
10030: invocation. In the @file{objects.fs} model, it is the object that is on
10031: the TOS when the selector is invoked. (@emph{Receiving} comes from
10032: the Smalltalk @emph{message} terminology.)
1.5 anton 10033:
1.78 anton 10034: @cindex child class
10035: @cindex parent class
10036: @cindex inheritance
10037: @item child class
10038: a class that has (@emph{inherits}) all properties (instance variables,
10039: selectors, methods) from a @emph{parent class}. In Smalltalk
10040: terminology: The subclass inherits from the superclass. In C++
10041: terminology: The derived class inherits from the base class.
1.5 anton 10042:
1.78 anton 10043: @end table
1.5 anton 10044:
1.78 anton 10045: @c If you wonder about the message sending terminology, it comes from
10046: @c a time when each object had it's own task and objects communicated via
10047: @c message passing; eventually the Smalltalk developers realized that
10048: @c they can do most things through simple (indirect) calls. They kept the
10049: @c terminology.
1.5 anton 10050:
1.78 anton 10051: @c --------------------------------------------------------------
10052: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10053: @subsection The @file{objects.fs} model
10054: @cindex objects
10055: @cindex object-oriented programming
1.26 crook 10056:
1.78 anton 10057: @cindex @file{objects.fs}
10058: @cindex @file{oof.fs}
1.26 crook 10059:
1.78 anton 10060: This section describes the @file{objects.fs} package. This material also
10061: has been published in M. Anton Ertl,
10062: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10063: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10064: 37--43.
10065: @c McKewan's and Zsoter's packages
1.26 crook 10066:
1.78 anton 10067: This section assumes that you have read @ref{Structures}.
1.5 anton 10068:
1.78 anton 10069: The techniques on which this model is based have been used to implement
10070: the parser generator, Gray, and have also been used in Gforth for
10071: implementing the various flavours of word lists (hashed or not,
10072: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10073:
10074:
1.26 crook 10075: @menu
1.78 anton 10076: * Properties of the Objects model::
10077: * Basic Objects Usage::
10078: * The Objects base class::
10079: * Creating objects::
10080: * Object-Oriented Programming Style::
10081: * Class Binding::
10082: * Method conveniences::
10083: * Classes and Scoping::
10084: * Dividing classes::
10085: * Object Interfaces::
10086: * Objects Implementation::
10087: * Objects Glossary::
1.26 crook 10088: @end menu
1.5 anton 10089:
1.78 anton 10090: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10091:
1.78 anton 10092: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10093: @subsubsection Properties of the @file{objects.fs} model
10094: @cindex @file{objects.fs} properties
1.5 anton 10095:
1.78 anton 10096: @itemize @bullet
10097: @item
10098: It is straightforward to pass objects on the stack. Passing
10099: selectors on the stack is a little less convenient, but possible.
1.44 crook 10100:
1.78 anton 10101: @item
10102: Objects are just data structures in memory, and are referenced by their
10103: address. You can create words for objects with normal defining words
10104: like @code{constant}. Likewise, there is no difference between instance
10105: variables that contain objects and those that contain other data.
1.5 anton 10106:
1.78 anton 10107: @item
10108: Late binding is efficient and easy to use.
1.44 crook 10109:
1.78 anton 10110: @item
10111: It avoids parsing, and thus avoids problems with state-smartness
10112: and reduced extensibility; for convenience there are a few parsing
10113: words, but they have non-parsing counterparts. There are also a few
10114: defining words that parse. This is hard to avoid, because all standard
10115: defining words parse (except @code{:noname}); however, such
10116: words are not as bad as many other parsing words, because they are not
10117: state-smart.
1.5 anton 10118:
1.78 anton 10119: @item
10120: It does not try to incorporate everything. It does a few things and does
10121: them well (IMO). In particular, this model was not designed to support
10122: information hiding (although it has features that may help); you can use
10123: a separate package for achieving this.
1.5 anton 10124:
1.78 anton 10125: @item
10126: It is layered; you don't have to learn and use all features to use this
10127: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10128: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10129: are optional and independent of each other.
1.5 anton 10130:
1.78 anton 10131: @item
10132: An implementation in ANS Forth is available.
1.5 anton 10133:
1.78 anton 10134: @end itemize
1.5 anton 10135:
1.44 crook 10136:
1.78 anton 10137: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10138: @subsubsection Basic @file{objects.fs} Usage
10139: @cindex basic objects usage
10140: @cindex objects, basic usage
1.5 anton 10141:
1.78 anton 10142: You can define a class for graphical objects like this:
1.44 crook 10143:
1.78 anton 10144: @cindex @code{class} usage
10145: @cindex @code{end-class} usage
10146: @cindex @code{selector} usage
1.5 anton 10147: @example
1.78 anton 10148: object class \ "object" is the parent class
10149: selector draw ( x y graphical -- )
10150: end-class graphical
10151: @end example
10152:
10153: This code defines a class @code{graphical} with an
10154: operation @code{draw}. We can perform the operation
10155: @code{draw} on any @code{graphical} object, e.g.:
10156:
10157: @example
10158: 100 100 t-rex draw
1.26 crook 10159: @end example
1.5 anton 10160:
1.78 anton 10161: @noindent
10162: where @code{t-rex} is a word (say, a constant) that produces a
10163: graphical object.
10164:
10165: @comment TODO add a 2nd operation eg perimeter.. and use for
10166: @comment a concrete example
1.5 anton 10167:
1.78 anton 10168: @cindex abstract class
10169: How do we create a graphical object? With the present definitions,
10170: we cannot create a useful graphical object. The class
10171: @code{graphical} describes graphical objects in general, but not
10172: any concrete graphical object type (C++ users would call it an
10173: @emph{abstract class}); e.g., there is no method for the selector
10174: @code{draw} in the class @code{graphical}.
1.5 anton 10175:
1.78 anton 10176: For concrete graphical objects, we define child classes of the
10177: class @code{graphical}, e.g.:
1.5 anton 10178:
1.78 anton 10179: @cindex @code{overrides} usage
10180: @cindex @code{field} usage in class definition
1.26 crook 10181: @example
1.78 anton 10182: graphical class \ "graphical" is the parent class
10183: cell% field circle-radius
1.5 anton 10184:
1.78 anton 10185: :noname ( x y circle -- )
10186: circle-radius @@ draw-circle ;
10187: overrides draw
1.5 anton 10188:
1.78 anton 10189: :noname ( n-radius circle -- )
10190: circle-radius ! ;
10191: overrides construct
1.5 anton 10192:
1.78 anton 10193: end-class circle
10194: @end example
1.44 crook 10195:
1.78 anton 10196: Here we define a class @code{circle} as a child of @code{graphical},
10197: with field @code{circle-radius} (which behaves just like a field
10198: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10199: for the selectors @code{draw} and @code{construct} (@code{construct} is
10200: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10201:
1.78 anton 10202: Now we can create a circle on the heap (i.e.,
10203: @code{allocate}d memory) with:
1.44 crook 10204:
1.78 anton 10205: @cindex @code{heap-new} usage
1.5 anton 10206: @example
1.78 anton 10207: 50 circle heap-new constant my-circle
1.5 anton 10208: @end example
10209:
1.78 anton 10210: @noindent
10211: @code{heap-new} invokes @code{construct}, thus
10212: initializing the field @code{circle-radius} with 50. We can draw
10213: this new circle at (100,100) with:
1.5 anton 10214:
10215: @example
1.78 anton 10216: 100 100 my-circle draw
1.5 anton 10217: @end example
10218:
1.78 anton 10219: @cindex selector invocation, restrictions
10220: @cindex class definition, restrictions
10221: Note: You can only invoke a selector if the object on the TOS
10222: (the receiving object) belongs to the class where the selector was
10223: defined or one of its descendents; e.g., you can invoke
10224: @code{draw} only for objects belonging to @code{graphical}
10225: or its descendents (e.g., @code{circle}). Immediately before
10226: @code{end-class}, the search order has to be the same as
10227: immediately after @code{class}.
10228:
10229: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10230: @subsubsection The @file{object.fs} base class
10231: @cindex @code{object} class
10232:
10233: When you define a class, you have to specify a parent class. So how do
10234: you start defining classes? There is one class available from the start:
10235: @code{object}. It is ancestor for all classes and so is the
10236: only class that has no parent. It has two selectors: @code{construct}
10237: and @code{print}.
10238:
10239: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10240: @subsubsection Creating objects
10241: @cindex creating objects
10242: @cindex object creation
10243: @cindex object allocation options
10244:
10245: @cindex @code{heap-new} discussion
10246: @cindex @code{dict-new} discussion
10247: @cindex @code{construct} discussion
10248: You can create and initialize an object of a class on the heap with
10249: @code{heap-new} ( ... class -- object ) and in the dictionary
10250: (allocation with @code{allot}) with @code{dict-new} (
10251: ... class -- object ). Both words invoke @code{construct}, which
10252: consumes the stack items indicated by "..." above.
10253:
10254: @cindex @code{init-object} discussion
10255: @cindex @code{class-inst-size} discussion
10256: If you want to allocate memory for an object yourself, you can get its
10257: alignment and size with @code{class-inst-size 2@@} ( class --
10258: align size ). Once you have memory for an object, you can initialize
10259: it with @code{init-object} ( ... class object -- );
10260: @code{construct} does only a part of the necessary work.
10261:
10262: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10263: @subsubsection Object-Oriented Programming Style
10264: @cindex object-oriented programming style
10265: @cindex programming style, object-oriented
1.5 anton 10266:
1.78 anton 10267: This section is not exhaustive.
1.5 anton 10268:
1.78 anton 10269: @cindex stack effects of selectors
10270: @cindex selectors and stack effects
10271: In general, it is a good idea to ensure that all methods for the
10272: same selector have the same stack effect: when you invoke a selector,
10273: you often have no idea which method will be invoked, so, unless all
10274: methods have the same stack effect, you will not know the stack effect
10275: of the selector invocation.
1.5 anton 10276:
1.78 anton 10277: One exception to this rule is methods for the selector
10278: @code{construct}. We know which method is invoked, because we
10279: specify the class to be constructed at the same place. Actually, I
10280: defined @code{construct} as a selector only to give the users a
10281: convenient way to specify initialization. The way it is used, a
10282: mechanism different from selector invocation would be more natural
10283: (but probably would take more code and more space to explain).
1.5 anton 10284:
1.78 anton 10285: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10286: @subsubsection Class Binding
10287: @cindex class binding
10288: @cindex early binding
1.5 anton 10289:
1.78 anton 10290: @cindex late binding
10291: Normal selector invocations determine the method at run-time depending
10292: on the class of the receiving object. This run-time selection is called
10293: @i{late binding}.
1.5 anton 10294:
1.78 anton 10295: Sometimes it's preferable to invoke a different method. For example,
10296: you might want to use the simple method for @code{print}ing
10297: @code{object}s instead of the possibly long-winded @code{print} method
10298: of the receiver class. You can achieve this by replacing the invocation
10299: of @code{print} with:
1.5 anton 10300:
1.78 anton 10301: @cindex @code{[bind]} usage
1.5 anton 10302: @example
1.78 anton 10303: [bind] object print
1.5 anton 10304: @end example
10305:
1.78 anton 10306: @noindent
10307: in compiled code or:
10308:
10309: @cindex @code{bind} usage
1.5 anton 10310: @example
1.78 anton 10311: bind object print
1.5 anton 10312: @end example
10313:
1.78 anton 10314: @cindex class binding, alternative to
10315: @noindent
10316: in interpreted code. Alternatively, you can define the method with a
10317: name (e.g., @code{print-object}), and then invoke it through the
10318: name. Class binding is just a (often more convenient) way to achieve
10319: the same effect; it avoids name clutter and allows you to invoke
10320: methods directly without naming them first.
1.5 anton 10321:
1.78 anton 10322: @cindex superclass binding
10323: @cindex parent class binding
10324: A frequent use of class binding is this: When we define a method
10325: for a selector, we often want the method to do what the selector does
10326: in the parent class, and a little more. There is a special word for
10327: this purpose: @code{[parent]}; @code{[parent]
10328: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10329: selector}}, where @code{@emph{parent}} is the parent
10330: class of the current class. E.g., a method definition might look like:
1.44 crook 10331:
1.78 anton 10332: @cindex @code{[parent]} usage
10333: @example
10334: :noname
10335: dup [parent] foo \ do parent's foo on the receiving object
10336: ... \ do some more
10337: ; overrides foo
10338: @end example
1.6 pazsan 10339:
1.78 anton 10340: @cindex class binding as optimization
10341: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10342: March 1997), Andrew McKewan presents class binding as an optimization
10343: technique. I recommend not using it for this purpose unless you are in
10344: an emergency. Late binding is pretty fast with this model anyway, so the
10345: benefit of using class binding is small; the cost of using class binding
10346: where it is not appropriate is reduced maintainability.
1.44 crook 10347:
1.78 anton 10348: While we are at programming style questions: You should bind
10349: selectors only to ancestor classes of the receiving object. E.g., say,
10350: you know that the receiving object is of class @code{foo} or its
10351: descendents; then you should bind only to @code{foo} and its
10352: ancestors.
1.12 anton 10353:
1.78 anton 10354: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10355: @subsubsection Method conveniences
10356: @cindex method conveniences
1.44 crook 10357:
1.78 anton 10358: In a method you usually access the receiving object pretty often. If
10359: you define the method as a plain colon definition (e.g., with
10360: @code{:noname}), you may have to do a lot of stack
10361: gymnastics. To avoid this, you can define the method with @code{m:
10362: ... ;m}. E.g., you could define the method for
10363: @code{draw}ing a @code{circle} with
1.6 pazsan 10364:
1.78 anton 10365: @cindex @code{this} usage
10366: @cindex @code{m:} usage
10367: @cindex @code{;m} usage
10368: @example
10369: m: ( x y circle -- )
10370: ( x y ) this circle-radius @@ draw-circle ;m
10371: @end example
1.6 pazsan 10372:
1.78 anton 10373: @cindex @code{exit} in @code{m: ... ;m}
10374: @cindex @code{exitm} discussion
10375: @cindex @code{catch} in @code{m: ... ;m}
10376: When this method is executed, the receiver object is removed from the
10377: stack; you can access it with @code{this} (admittedly, in this
10378: example the use of @code{m: ... ;m} offers no advantage). Note
10379: that I specify the stack effect for the whole method (i.e. including
10380: the receiver object), not just for the code between @code{m:}
10381: and @code{;m}. You cannot use @code{exit} in
10382: @code{m:...;m}; instead, use
10383: @code{exitm}.@footnote{Moreover, for any word that calls
10384: @code{catch} and was defined before loading
10385: @code{objects.fs}, you have to redefine it like I redefined
10386: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10387:
1.78 anton 10388: @cindex @code{inst-var} usage
10389: You will frequently use sequences of the form @code{this
10390: @emph{field}} (in the example above: @code{this
10391: circle-radius}). If you use the field only in this way, you can
10392: define it with @code{inst-var} and eliminate the
10393: @code{this} before the field name. E.g., the @code{circle}
10394: class above could also be defined with:
1.6 pazsan 10395:
1.78 anton 10396: @example
10397: graphical class
10398: cell% inst-var radius
1.6 pazsan 10399:
1.78 anton 10400: m: ( x y circle -- )
10401: radius @@ draw-circle ;m
10402: overrides draw
1.6 pazsan 10403:
1.78 anton 10404: m: ( n-radius circle -- )
10405: radius ! ;m
10406: overrides construct
1.6 pazsan 10407:
1.78 anton 10408: end-class circle
10409: @end example
1.6 pazsan 10410:
1.78 anton 10411: @code{radius} can only be used in @code{circle} and its
10412: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10413:
1.78 anton 10414: @cindex @code{inst-value} usage
10415: You can also define fields with @code{inst-value}, which is
10416: to @code{inst-var} what @code{value} is to
10417: @code{variable}. You can change the value of such a field with
10418: @code{[to-inst]}. E.g., we could also define the class
10419: @code{circle} like this:
1.44 crook 10420:
1.78 anton 10421: @example
10422: graphical class
10423: inst-value radius
1.6 pazsan 10424:
1.78 anton 10425: m: ( x y circle -- )
10426: radius draw-circle ;m
10427: overrides draw
1.44 crook 10428:
1.78 anton 10429: m: ( n-radius circle -- )
10430: [to-inst] radius ;m
10431: overrides construct
1.6 pazsan 10432:
1.78 anton 10433: end-class circle
10434: @end example
1.6 pazsan 10435:
1.78 anton 10436: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10437:
1.78 anton 10438: @c Finally, you can define named methods with @code{:m}. One use of this
10439: @c feature is the definition of words that occur only in one class and are
10440: @c not intended to be overridden, but which still need method context
10441: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10442: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10443:
10444:
1.78 anton 10445: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10446: @subsubsection Classes and Scoping
10447: @cindex classes and scoping
10448: @cindex scoping and classes
1.6 pazsan 10449:
1.78 anton 10450: Inheritance is frequent, unlike structure extension. This exacerbates
10451: the problem with the field name convention (@pxref{Structure Naming
10452: Convention}): One always has to remember in which class the field was
10453: originally defined; changing a part of the class structure would require
10454: changes for renaming in otherwise unaffected code.
1.6 pazsan 10455:
1.78 anton 10456: @cindex @code{inst-var} visibility
10457: @cindex @code{inst-value} visibility
10458: To solve this problem, I added a scoping mechanism (which was not in my
10459: original charter): A field defined with @code{inst-var} (or
10460: @code{inst-value}) is visible only in the class where it is defined and in
10461: the descendent classes of this class. Using such fields only makes
10462: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10463:
1.78 anton 10464: This scoping mechanism allows us to use the unadorned field name,
10465: because name clashes with unrelated words become much less likely.
1.6 pazsan 10466:
1.78 anton 10467: @cindex @code{protected} discussion
10468: @cindex @code{private} discussion
10469: Once we have this mechanism, we can also use it for controlling the
10470: visibility of other words: All words defined after
10471: @code{protected} are visible only in the current class and its
10472: descendents. @code{public} restores the compilation
10473: (i.e. @code{current}) word list that was in effect before. If you
10474: have several @code{protected}s without an intervening
10475: @code{public} or @code{set-current}, @code{public}
10476: will restore the compilation word list in effect before the first of
10477: these @code{protected}s.
1.6 pazsan 10478:
1.78 anton 10479: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10480: @subsubsection Dividing classes
10481: @cindex Dividing classes
10482: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10483:
1.78 anton 10484: You may want to do the definition of methods separate from the
10485: definition of the class, its selectors, fields, and instance variables,
10486: i.e., separate the implementation from the definition. You can do this
10487: in the following way:
1.6 pazsan 10488:
1.78 anton 10489: @example
10490: graphical class
10491: inst-value radius
10492: end-class circle
1.6 pazsan 10493:
1.78 anton 10494: ... \ do some other stuff
1.6 pazsan 10495:
1.78 anton 10496: circle methods \ now we are ready
1.44 crook 10497:
1.78 anton 10498: m: ( x y circle -- )
10499: radius draw-circle ;m
10500: overrides draw
1.6 pazsan 10501:
1.78 anton 10502: m: ( n-radius circle -- )
10503: [to-inst] radius ;m
10504: overrides construct
1.44 crook 10505:
1.78 anton 10506: end-methods
10507: @end example
1.7 pazsan 10508:
1.78 anton 10509: You can use several @code{methods}...@code{end-methods} sections. The
10510: only things you can do to the class in these sections are: defining
10511: methods, and overriding the class's selectors. You must not define new
10512: selectors or fields.
1.7 pazsan 10513:
1.78 anton 10514: Note that you often have to override a selector before using it. In
10515: particular, you usually have to override @code{construct} with a new
10516: method before you can invoke @code{heap-new} and friends. E.g., you
10517: must not create a circle before the @code{overrides construct} sequence
10518: in the example above.
1.7 pazsan 10519:
1.78 anton 10520: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10521: @subsubsection Object Interfaces
10522: @cindex object interfaces
10523: @cindex interfaces for objects
1.7 pazsan 10524:
1.78 anton 10525: In this model you can only call selectors defined in the class of the
10526: receiving objects or in one of its ancestors. If you call a selector
10527: with a receiving object that is not in one of these classes, the
10528: result is undefined; if you are lucky, the program crashes
10529: immediately.
1.7 pazsan 10530:
1.78 anton 10531: @cindex selectors common to hardly-related classes
10532: Now consider the case when you want to have a selector (or several)
10533: available in two classes: You would have to add the selector to a
10534: common ancestor class, in the worst case to @code{object}. You
10535: may not want to do this, e.g., because someone else is responsible for
10536: this ancestor class.
1.7 pazsan 10537:
1.78 anton 10538: The solution for this problem is interfaces. An interface is a
10539: collection of selectors. If a class implements an interface, the
10540: selectors become available to the class and its descendents. A class
10541: can implement an unlimited number of interfaces. For the problem
10542: discussed above, we would define an interface for the selector(s), and
10543: both classes would implement the interface.
1.7 pazsan 10544:
1.78 anton 10545: As an example, consider an interface @code{storage} for
10546: writing objects to disk and getting them back, and a class
10547: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10548:
1.78 anton 10549: @cindex @code{interface} usage
10550: @cindex @code{end-interface} usage
10551: @cindex @code{implementation} usage
10552: @example
10553: interface
10554: selector write ( file object -- )
10555: selector read1 ( file object -- )
10556: end-interface storage
1.13 pazsan 10557:
1.78 anton 10558: bar class
10559: storage implementation
1.13 pazsan 10560:
1.78 anton 10561: ... overrides write
10562: ... overrides read1
10563: ...
10564: end-class foo
10565: @end example
1.13 pazsan 10566:
1.78 anton 10567: @noindent
10568: (I would add a word @code{read} @i{( file -- object )} that uses
10569: @code{read1} internally, but that's beyond the point illustrated
10570: here.)
1.13 pazsan 10571:
1.78 anton 10572: Note that you cannot use @code{protected} in an interface; and
10573: of course you cannot define fields.
1.13 pazsan 10574:
1.78 anton 10575: In the Neon model, all selectors are available for all classes;
10576: therefore it does not need interfaces. The price you pay in this model
10577: is slower late binding, and therefore, added complexity to avoid late
10578: binding.
1.13 pazsan 10579:
1.78 anton 10580: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10581: @subsubsection @file{objects.fs} Implementation
10582: @cindex @file{objects.fs} implementation
1.13 pazsan 10583:
1.78 anton 10584: @cindex @code{object-map} discussion
10585: An object is a piece of memory, like one of the data structures
10586: described with @code{struct...end-struct}. It has a field
10587: @code{object-map} that points to the method map for the object's
10588: class.
1.13 pazsan 10589:
1.78 anton 10590: @cindex method map
10591: @cindex virtual function table
10592: The @emph{method map}@footnote{This is Self terminology; in C++
10593: terminology: virtual function table.} is an array that contains the
10594: execution tokens (@i{xt}s) of the methods for the object's class. Each
10595: selector contains an offset into a method map.
1.13 pazsan 10596:
1.78 anton 10597: @cindex @code{selector} implementation, class
10598: @code{selector} is a defining word that uses
10599: @code{CREATE} and @code{DOES>}. The body of the
10600: selector contains the offset; the @code{DOES>} action for a
10601: class selector is, basically:
1.8 pazsan 10602:
10603: @example
1.78 anton 10604: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10605: @end example
10606:
1.78 anton 10607: Since @code{object-map} is the first field of the object, it
10608: does not generate any code. As you can see, calling a selector has a
10609: small, constant cost.
1.26 crook 10610:
1.78 anton 10611: @cindex @code{current-interface} discussion
10612: @cindex class implementation and representation
10613: A class is basically a @code{struct} combined with a method
10614: map. During the class definition the alignment and size of the class
10615: are passed on the stack, just as with @code{struct}s, so
10616: @code{field} can also be used for defining class
10617: fields. However, passing more items on the stack would be
10618: inconvenient, so @code{class} builds a data structure in memory,
10619: which is accessed through the variable
10620: @code{current-interface}. After its definition is complete, the
10621: class is represented on the stack by a pointer (e.g., as parameter for
10622: a child class definition).
1.26 crook 10623:
1.78 anton 10624: A new class starts off with the alignment and size of its parent,
10625: and a copy of the parent's method map. Defining new fields extends the
10626: size and alignment; likewise, defining new selectors extends the
10627: method map. @code{overrides} just stores a new @i{xt} in the method
10628: map at the offset given by the selector.
1.13 pazsan 10629:
1.78 anton 10630: @cindex class binding, implementation
10631: Class binding just gets the @i{xt} at the offset given by the selector
10632: from the class's method map and @code{compile,}s (in the case of
10633: @code{[bind]}) it.
1.13 pazsan 10634:
1.78 anton 10635: @cindex @code{this} implementation
10636: @cindex @code{catch} and @code{this}
10637: @cindex @code{this} and @code{catch}
10638: I implemented @code{this} as a @code{value}. At the
10639: start of an @code{m:...;m} method the old @code{this} is
10640: stored to the return stack and restored at the end; and the object on
10641: the TOS is stored @code{TO this}. This technique has one
10642: disadvantage: If the user does not leave the method via
10643: @code{;m}, but via @code{throw} or @code{exit},
10644: @code{this} is not restored (and @code{exit} may
10645: crash). To deal with the @code{throw} problem, I have redefined
10646: @code{catch} to save and restore @code{this}; the same
10647: should be done with any word that can catch an exception. As for
10648: @code{exit}, I simply forbid it (as a replacement, there is
10649: @code{exitm}).
1.13 pazsan 10650:
1.78 anton 10651: @cindex @code{inst-var} implementation
10652: @code{inst-var} is just the same as @code{field}, with
10653: a different @code{DOES>} action:
1.13 pazsan 10654: @example
1.78 anton 10655: @@ this +
1.8 pazsan 10656: @end example
1.78 anton 10657: Similar for @code{inst-value}.
1.8 pazsan 10658:
1.78 anton 10659: @cindex class scoping implementation
10660: Each class also has a word list that contains the words defined with
10661: @code{inst-var} and @code{inst-value}, and its protected
10662: words. It also has a pointer to its parent. @code{class} pushes
10663: the word lists of the class and all its ancestors onto the search order stack,
10664: and @code{end-class} drops them.
1.20 pazsan 10665:
1.78 anton 10666: @cindex interface implementation
10667: An interface is like a class without fields, parent and protected
10668: words; i.e., it just has a method map. If a class implements an
10669: interface, its method map contains a pointer to the method map of the
10670: interface. The positive offsets in the map are reserved for class
10671: methods, therefore interface map pointers have negative
10672: offsets. Interfaces have offsets that are unique throughout the
10673: system, unlike class selectors, whose offsets are only unique for the
10674: classes where the selector is available (invokable).
1.20 pazsan 10675:
1.78 anton 10676: This structure means that interface selectors have to perform one
10677: indirection more than class selectors to find their method. Their body
10678: contains the interface map pointer offset in the class method map, and
10679: the method offset in the interface method map. The
10680: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10681:
10682: @example
1.78 anton 10683: ( object selector-body )
10684: 2dup selector-interface @@ ( object selector-body object interface-offset )
10685: swap object-map @@ + @@ ( object selector-body map )
10686: swap selector-offset @@ + @@ execute
1.20 pazsan 10687: @end example
10688:
1.78 anton 10689: where @code{object-map} and @code{selector-offset} are
10690: first fields and generate no code.
1.20 pazsan 10691:
1.78 anton 10692: As a concrete example, consider the following code:
1.20 pazsan 10693:
10694: @example
1.78 anton 10695: interface
10696: selector if1sel1
10697: selector if1sel2
10698: end-interface if1
1.20 pazsan 10699:
1.78 anton 10700: object class
10701: if1 implementation
10702: selector cl1sel1
10703: cell% inst-var cl1iv1
1.20 pazsan 10704:
1.78 anton 10705: ' m1 overrides construct
10706: ' m2 overrides if1sel1
10707: ' m3 overrides if1sel2
10708: ' m4 overrides cl1sel2
10709: end-class cl1
1.20 pazsan 10710:
1.78 anton 10711: create obj1 object dict-new drop
10712: create obj2 cl1 dict-new drop
10713: @end example
1.20 pazsan 10714:
1.78 anton 10715: The data structure created by this code (including the data structure
10716: for @code{object}) is shown in the
10717: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10718: @comment TODO add this diagram..
1.20 pazsan 10719:
1.78 anton 10720: @node Objects Glossary, , Objects Implementation, Objects
10721: @subsubsection @file{objects.fs} Glossary
10722: @cindex @file{objects.fs} Glossary
1.20 pazsan 10723:
10724:
1.78 anton 10725: doc---objects-bind
10726: doc---objects-<bind>
10727: doc---objects-bind'
10728: doc---objects-[bind]
10729: doc---objects-class
10730: doc---objects-class->map
10731: doc---objects-class-inst-size
10732: doc---objects-class-override!
1.79 anton 10733: doc---objects-class-previous
10734: doc---objects-class>order
1.78 anton 10735: doc---objects-construct
10736: doc---objects-current'
10737: doc---objects-[current]
10738: doc---objects-current-interface
10739: doc---objects-dict-new
10740: doc---objects-end-class
10741: doc---objects-end-class-noname
10742: doc---objects-end-interface
10743: doc---objects-end-interface-noname
10744: doc---objects-end-methods
10745: doc---objects-exitm
10746: doc---objects-heap-new
10747: doc---objects-implementation
10748: doc---objects-init-object
10749: doc---objects-inst-value
10750: doc---objects-inst-var
10751: doc---objects-interface
10752: doc---objects-m:
10753: doc---objects-:m
10754: doc---objects-;m
10755: doc---objects-method
10756: doc---objects-methods
10757: doc---objects-object
10758: doc---objects-overrides
10759: doc---objects-[parent]
10760: doc---objects-print
10761: doc---objects-protected
10762: doc---objects-public
10763: doc---objects-selector
10764: doc---objects-this
10765: doc---objects-<to-inst>
10766: doc---objects-[to-inst]
10767: doc---objects-to-this
10768: doc---objects-xt-new
1.20 pazsan 10769:
10770:
1.78 anton 10771: @c -------------------------------------------------------------
10772: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10773: @subsection The @file{oof.fs} model
10774: @cindex oof
10775: @cindex object-oriented programming
1.20 pazsan 10776:
1.78 anton 10777: @cindex @file{objects.fs}
10778: @cindex @file{oof.fs}
1.20 pazsan 10779:
1.78 anton 10780: This section describes the @file{oof.fs} package.
1.20 pazsan 10781:
1.78 anton 10782: The package described in this section has been used in bigFORTH since 1991, and
10783: used for two large applications: a chromatographic system used to
10784: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10785:
1.78 anton 10786: You can find a description (in German) of @file{oof.fs} in @cite{Object
10787: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10788: 10(2), 1994.
1.20 pazsan 10789:
1.78 anton 10790: @menu
10791: * Properties of the OOF model::
10792: * Basic OOF Usage::
10793: * The OOF base class::
10794: * Class Declaration::
10795: * Class Implementation::
10796: @end menu
1.20 pazsan 10797:
1.78 anton 10798: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10799: @subsubsection Properties of the @file{oof.fs} model
10800: @cindex @file{oof.fs} properties
1.20 pazsan 10801:
1.78 anton 10802: @itemize @bullet
10803: @item
10804: This model combines object oriented programming with information
10805: hiding. It helps you writing large application, where scoping is
10806: necessary, because it provides class-oriented scoping.
1.20 pazsan 10807:
1.78 anton 10808: @item
10809: Named objects, object pointers, and object arrays can be created,
10810: selector invocation uses the ``object selector'' syntax. Selector invocation
10811: to objects and/or selectors on the stack is a bit less convenient, but
10812: possible.
1.44 crook 10813:
1.78 anton 10814: @item
10815: Selector invocation and instance variable usage of the active object is
10816: straightforward, since both make use of the active object.
1.44 crook 10817:
1.78 anton 10818: @item
10819: Late binding is efficient and easy to use.
1.20 pazsan 10820:
1.78 anton 10821: @item
10822: State-smart objects parse selectors. However, extensibility is provided
10823: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10824:
1.78 anton 10825: @item
10826: An implementation in ANS Forth is available.
1.20 pazsan 10827:
1.78 anton 10828: @end itemize
1.23 crook 10829:
10830:
1.78 anton 10831: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10832: @subsubsection Basic @file{oof.fs} Usage
10833: @cindex @file{oof.fs} usage
1.23 crook 10834:
1.78 anton 10835: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10836:
1.78 anton 10837: You can define a class for graphical objects like this:
1.23 crook 10838:
1.78 anton 10839: @cindex @code{class} usage
10840: @cindex @code{class;} usage
10841: @cindex @code{method} usage
10842: @example
10843: object class graphical \ "object" is the parent class
1.139 pazsan 10844: method draw ( x y -- )
1.78 anton 10845: class;
10846: @end example
1.23 crook 10847:
1.78 anton 10848: This code defines a class @code{graphical} with an
10849: operation @code{draw}. We can perform the operation
10850: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10851:
1.78 anton 10852: @example
10853: 100 100 t-rex draw
10854: @end example
1.23 crook 10855:
1.78 anton 10856: @noindent
10857: where @code{t-rex} is an object or object pointer, created with e.g.
10858: @code{graphical : t-rex}.
1.23 crook 10859:
1.78 anton 10860: @cindex abstract class
10861: How do we create a graphical object? With the present definitions,
10862: we cannot create a useful graphical object. The class
10863: @code{graphical} describes graphical objects in general, but not
10864: any concrete graphical object type (C++ users would call it an
10865: @emph{abstract class}); e.g., there is no method for the selector
10866: @code{draw} in the class @code{graphical}.
1.23 crook 10867:
1.78 anton 10868: For concrete graphical objects, we define child classes of the
10869: class @code{graphical}, e.g.:
1.23 crook 10870:
1.78 anton 10871: @example
10872: graphical class circle \ "graphical" is the parent class
10873: cell var circle-radius
10874: how:
10875: : draw ( x y -- )
10876: circle-radius @@ draw-circle ;
1.23 crook 10877:
1.139 pazsan 10878: : init ( n-radius -- )
1.78 anton 10879: circle-radius ! ;
10880: class;
10881: @end example
1.1 anton 10882:
1.78 anton 10883: Here we define a class @code{circle} as a child of @code{graphical},
10884: with a field @code{circle-radius}; it defines new methods for the
10885: selectors @code{draw} and @code{init} (@code{init} is defined in
10886: @code{object}, the parent class of @code{graphical}).
1.1 anton 10887:
1.78 anton 10888: Now we can create a circle in the dictionary with:
1.1 anton 10889:
1.78 anton 10890: @example
10891: 50 circle : my-circle
10892: @end example
1.21 crook 10893:
1.78 anton 10894: @noindent
10895: @code{:} invokes @code{init}, thus initializing the field
10896: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10897: with:
1.1 anton 10898:
1.78 anton 10899: @example
10900: 100 100 my-circle draw
10901: @end example
1.1 anton 10902:
1.78 anton 10903: @cindex selector invocation, restrictions
10904: @cindex class definition, restrictions
10905: Note: You can only invoke a selector if the receiving object belongs to
10906: the class where the selector was defined or one of its descendents;
10907: e.g., you can invoke @code{draw} only for objects belonging to
10908: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10909: mechanism will check if you try to invoke a selector that is not
10910: defined in this class hierarchy, so you'll get an error at compilation
10911: time.
1.1 anton 10912:
10913:
1.78 anton 10914: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10915: @subsubsection The @file{oof.fs} base class
10916: @cindex @file{oof.fs} base class
1.1 anton 10917:
1.78 anton 10918: When you define a class, you have to specify a parent class. So how do
10919: you start defining classes? There is one class available from the start:
10920: @code{object}. You have to use it as ancestor for all classes. It is the
10921: only class that has no parent. Classes are also objects, except that
10922: they don't have instance variables; class manipulation such as
10923: inheritance or changing definitions of a class is handled through
10924: selectors of the class @code{object}.
1.1 anton 10925:
1.78 anton 10926: @code{object} provides a number of selectors:
1.1 anton 10927:
1.78 anton 10928: @itemize @bullet
10929: @item
10930: @code{class} for subclassing, @code{definitions} to add definitions
10931: later on, and @code{class?} to get type informations (is the class a
10932: subclass of the class passed on the stack?).
1.1 anton 10933:
1.78 anton 10934: doc---object-class
10935: doc---object-definitions
10936: doc---object-class?
1.1 anton 10937:
10938:
1.26 crook 10939: @item
1.78 anton 10940: @code{init} and @code{dispose} as constructor and destructor of the
10941: object. @code{init} is invocated after the object's memory is allocated,
10942: while @code{dispose} also handles deallocation. Thus if you redefine
10943: @code{dispose}, you have to call the parent's dispose with @code{super
10944: dispose}, too.
10945:
10946: doc---object-init
10947: doc---object-dispose
10948:
1.1 anton 10949:
1.26 crook 10950: @item
1.78 anton 10951: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10952: @code{[]} to create named and unnamed objects and object arrays or
10953: object pointers.
10954:
10955: doc---object-new
10956: doc---object-new[]
10957: doc---object-:
10958: doc---object-ptr
10959: doc---object-asptr
10960: doc---object-[]
10961:
1.1 anton 10962:
1.26 crook 10963: @item
1.78 anton 10964: @code{::} and @code{super} for explicit scoping. You should use explicit
10965: scoping only for super classes or classes with the same set of instance
10966: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10967:
1.78 anton 10968: doc---object-::
10969: doc---object-super
1.21 crook 10970:
10971:
1.26 crook 10972: @item
1.78 anton 10973: @code{self} to get the address of the object
1.21 crook 10974:
1.78 anton 10975: doc---object-self
1.21 crook 10976:
10977:
1.78 anton 10978: @item
10979: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10980: pointers and instance defers.
1.21 crook 10981:
1.78 anton 10982: doc---object-bind
10983: doc---object-bound
10984: doc---object-link
10985: doc---object-is
1.21 crook 10986:
10987:
1.78 anton 10988: @item
10989: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10990: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10991:
1.78 anton 10992: doc---object-'
10993: doc---object-postpone
1.21 crook 10994:
10995:
1.78 anton 10996: @item
10997: @code{with} and @code{endwith} to select the active object from the
10998: stack, and enable its scope. Using @code{with} and @code{endwith}
10999: also allows you to create code using selector @code{postpone} without being
11000: trapped by the state-smart objects.
1.21 crook 11001:
1.78 anton 11002: doc---object-with
11003: doc---object-endwith
1.21 crook 11004:
11005:
1.78 anton 11006: @end itemize
1.21 crook 11007:
1.78 anton 11008: @node Class Declaration, Class Implementation, The OOF base class, OOF
11009: @subsubsection Class Declaration
11010: @cindex class declaration
1.21 crook 11011:
1.78 anton 11012: @itemize @bullet
11013: @item
11014: Instance variables
1.21 crook 11015:
1.78 anton 11016: doc---oof-var
1.21 crook 11017:
11018:
1.78 anton 11019: @item
11020: Object pointers
1.21 crook 11021:
1.78 anton 11022: doc---oof-ptr
11023: doc---oof-asptr
1.21 crook 11024:
11025:
1.78 anton 11026: @item
11027: Instance defers
1.21 crook 11028:
1.78 anton 11029: doc---oof-defer
1.21 crook 11030:
11031:
1.78 anton 11032: @item
11033: Method selectors
1.21 crook 11034:
1.78 anton 11035: doc---oof-early
11036: doc---oof-method
1.21 crook 11037:
11038:
1.78 anton 11039: @item
11040: Class-wide variables
1.21 crook 11041:
1.78 anton 11042: doc---oof-static
1.21 crook 11043:
11044:
1.78 anton 11045: @item
11046: End declaration
1.1 anton 11047:
1.78 anton 11048: doc---oof-how:
11049: doc---oof-class;
1.21 crook 11050:
11051:
1.78 anton 11052: @end itemize
1.21 crook 11053:
1.78 anton 11054: @c -------------------------------------------------------------
11055: @node Class Implementation, , Class Declaration, OOF
11056: @subsubsection Class Implementation
11057: @cindex class implementation
1.21 crook 11058:
1.78 anton 11059: @c -------------------------------------------------------------
11060: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11061: @subsection The @file{mini-oof.fs} model
11062: @cindex mini-oof
1.21 crook 11063:
1.78 anton 11064: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11065: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11066: and reduces to the bare minimum of features. This is based on a posting
11067: of Bernd Paysan in comp.lang.forth.
1.21 crook 11068:
1.78 anton 11069: @menu
11070: * Basic Mini-OOF Usage::
11071: * Mini-OOF Example::
11072: * Mini-OOF Implementation::
11073: @end menu
1.21 crook 11074:
1.78 anton 11075: @c -------------------------------------------------------------
11076: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11077: @subsubsection Basic @file{mini-oof.fs} Usage
11078: @cindex mini-oof usage
1.21 crook 11079:
1.78 anton 11080: There is a base class (@code{class}, which allocates one cell for the
11081: object pointer) plus seven other words: to define a method, a variable,
11082: a class; to end a class, to resolve binding, to allocate an object and
11083: to compile a class method.
11084: @comment TODO better description of the last one
1.26 crook 11085:
1.21 crook 11086:
1.78 anton 11087: doc-object
11088: doc-method
11089: doc-var
11090: doc-class
11091: doc-end-class
11092: doc-defines
11093: doc-new
11094: doc-::
1.21 crook 11095:
11096:
11097:
1.78 anton 11098: @c -------------------------------------------------------------
11099: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11100: @subsubsection Mini-OOF Example
11101: @cindex mini-oof example
1.1 anton 11102:
1.78 anton 11103: A short example shows how to use this package. This example, in slightly
11104: extended form, is supplied as @file{moof-exm.fs}
11105: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11106:
1.26 crook 11107: @example
1.78 anton 11108: object class
11109: method init
11110: method draw
11111: end-class graphical
1.26 crook 11112: @end example
1.20 pazsan 11113:
1.78 anton 11114: This code defines a class @code{graphical} with an
11115: operation @code{draw}. We can perform the operation
11116: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11117:
1.26 crook 11118: @example
1.78 anton 11119: 100 100 t-rex draw
1.26 crook 11120: @end example
1.12 anton 11121:
1.78 anton 11122: where @code{t-rex} is an object or object pointer, created with e.g.
11123: @code{graphical new Constant t-rex}.
1.12 anton 11124:
1.78 anton 11125: For concrete graphical objects, we define child classes of the
11126: class @code{graphical}, e.g.:
1.12 anton 11127:
1.26 crook 11128: @example
11129: graphical class
1.78 anton 11130: cell var circle-radius
11131: end-class circle \ "graphical" is the parent class
1.12 anton 11132:
1.78 anton 11133: :noname ( x y -- )
11134: circle-radius @@ draw-circle ; circle defines draw
11135: :noname ( r -- )
11136: circle-radius ! ; circle defines init
11137: @end example
1.12 anton 11138:
1.78 anton 11139: There is no implicit init method, so we have to define one. The creation
11140: code of the object now has to call init explicitely.
1.21 crook 11141:
1.78 anton 11142: @example
11143: circle new Constant my-circle
11144: 50 my-circle init
1.12 anton 11145: @end example
11146:
1.78 anton 11147: It is also possible to add a function to create named objects with
11148: automatic call of @code{init}, given that all objects have @code{init}
11149: on the same place:
1.38 anton 11150:
1.78 anton 11151: @example
11152: : new: ( .. o "name" -- )
11153: new dup Constant init ;
11154: 80 circle new: large-circle
11155: @end example
1.12 anton 11156:
1.78 anton 11157: We can draw this new circle at (100,100) with:
1.12 anton 11158:
1.78 anton 11159: @example
11160: 100 100 my-circle draw
11161: @end example
1.12 anton 11162:
1.78 anton 11163: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11164: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11165:
1.78 anton 11166: Object-oriented systems with late binding typically use a
11167: ``vtable''-approach: the first variable in each object is a pointer to a
11168: table, which contains the methods as function pointers. The vtable
11169: may also contain other information.
1.12 anton 11170:
1.79 anton 11171: So first, let's declare selectors:
1.37 anton 11172:
11173: @example
1.79 anton 11174: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11175: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11176: @end example
1.37 anton 11177:
1.79 anton 11178: During selector declaration, the number of selectors and instance
11179: variables is on the stack (in address units). @code{method} creates one
11180: selector and increments the selector number. To execute a selector, it
1.78 anton 11181: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11182: executes the method @i{xt} stored there. Each selector takes the object
11183: it is invoked with as top of stack parameter; it passes the parameters
11184: (including the object) unchanged to the appropriate method which should
1.78 anton 11185: consume that object.
1.37 anton 11186:
1.78 anton 11187: Now, we also have to declare instance variables
1.37 anton 11188:
1.78 anton 11189: @example
1.79 anton 11190: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11191: DOES> ( o -- addr ) @@ + ;
1.37 anton 11192: @end example
11193:
1.78 anton 11194: As before, a word is created with the current offset. Instance
11195: variables can have different sizes (cells, floats, doubles, chars), so
11196: all we do is take the size and add it to the offset. If your machine
11197: has alignment restrictions, put the proper @code{aligned} or
11198: @code{faligned} before the variable, to adjust the variable
11199: offset. That's why it is on the top of stack.
1.37 anton 11200:
1.78 anton 11201: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11202:
1.78 anton 11203: @example
11204: Create object 1 cells , 2 cells ,
1.79 anton 11205: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11206: @end example
1.12 anton 11207:
1.78 anton 11208: For inheritance, the vtable of the parent object has to be
11209: copied when a new, derived class is declared. This gives all the
11210: methods of the parent class, which can be overridden, though.
1.12 anton 11211:
1.78 anton 11212: @example
1.79 anton 11213: : end-class ( class selectors vars "name" -- )
1.78 anton 11214: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11215: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11216: @end example
1.12 anton 11217:
1.78 anton 11218: The first line creates the vtable, initialized with
11219: @code{noop}s. The second line is the inheritance mechanism, it
11220: copies the xts from the parent vtable.
1.12 anton 11221:
1.78 anton 11222: We still have no way to define new methods, let's do that now:
1.12 anton 11223:
1.26 crook 11224: @example
1.79 anton 11225: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11226: @end example
1.12 anton 11227:
1.78 anton 11228: To allocate a new object, we need a word, too:
1.12 anton 11229:
1.78 anton 11230: @example
11231: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11232: @end example
11233:
1.78 anton 11234: Sometimes derived classes want to access the method of the
11235: parent object. There are two ways to achieve this with Mini-OOF:
11236: first, you could use named words, and second, you could look up the
11237: vtable of the parent object.
1.12 anton 11238:
1.78 anton 11239: @example
11240: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11241: @end example
1.12 anton 11242:
11243:
1.78 anton 11244: Nothing can be more confusing than a good example, so here is
11245: one. First let's declare a text object (called
11246: @code{button}), that stores text and position:
1.12 anton 11247:
1.78 anton 11248: @example
11249: object class
11250: cell var text
11251: cell var len
11252: cell var x
11253: cell var y
11254: method init
11255: method draw
11256: end-class button
11257: @end example
1.12 anton 11258:
1.78 anton 11259: @noindent
11260: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11261:
1.26 crook 11262: @example
1.78 anton 11263: :noname ( o -- )
11264: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11265: button defines draw
11266: :noname ( addr u o -- )
11267: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11268: button defines init
1.26 crook 11269: @end example
1.12 anton 11270:
1.78 anton 11271: @noindent
11272: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11273: new data and no new selectors:
1.78 anton 11274:
11275: @example
11276: button class
11277: end-class bold-button
1.12 anton 11278:
1.78 anton 11279: : bold 27 emit ." [1m" ;
11280: : normal 27 emit ." [0m" ;
11281: @end example
1.1 anton 11282:
1.78 anton 11283: @noindent
11284: The class @code{bold-button} has a different draw method to
11285: @code{button}, but the new method is defined in terms of the draw method
11286: for @code{button}:
1.20 pazsan 11287:
1.78 anton 11288: @example
11289: :noname bold [ button :: draw ] normal ; bold-button defines draw
11290: @end example
1.21 crook 11291:
1.78 anton 11292: @noindent
1.79 anton 11293: Finally, create two objects and apply selectors:
1.21 crook 11294:
1.26 crook 11295: @example
1.78 anton 11296: button new Constant foo
11297: s" thin foo" foo init
11298: page
11299: foo draw
11300: bold-button new Constant bar
11301: s" fat bar" bar init
11302: 1 bar y !
11303: bar draw
1.26 crook 11304: @end example
1.21 crook 11305:
11306:
1.78 anton 11307: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11308: @subsection Comparison with other object models
11309: @cindex comparison of object models
11310: @cindex object models, comparison
11311:
11312: Many object-oriented Forth extensions have been proposed (@cite{A survey
11313: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11314: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11315: relation of the object models described here to two well-known and two
11316: closely-related (by the use of method maps) models. Andras Zsoter
11317: helped us with this section.
11318:
11319: @cindex Neon model
11320: The most popular model currently seems to be the Neon model (see
11321: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11322: 1997) by Andrew McKewan) but this model has a number of limitations
11323: @footnote{A longer version of this critique can be
11324: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11325: Dimensions, May 1997) by Anton Ertl.}:
11326:
11327: @itemize @bullet
11328: @item
11329: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11330: to pass objects on the stack.
1.21 crook 11331:
1.78 anton 11332: @item
11333: It requires that the selector parses the input stream (at
1.79 anton 11334: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11335: hard to find.
1.21 crook 11336:
1.78 anton 11337: @item
1.79 anton 11338: It allows using every selector on every object; this eliminates the
11339: need for interfaces, but makes it harder to create efficient
11340: implementations.
1.78 anton 11341: @end itemize
1.21 crook 11342:
1.78 anton 11343: @cindex Pountain's object-oriented model
11344: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11345: Press, London, 1987) by Dick Pountain. However, it is not really about
11346: object-oriented programming, because it hardly deals with late
11347: binding. Instead, it focuses on features like information hiding and
11348: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11349:
1.78 anton 11350: @cindex Zsoter's object-oriented model
1.79 anton 11351: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11352: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11353: describes a model that makes heavy use of an active object (like
11354: @code{this} in @file{objects.fs}): The active object is not only used
11355: for accessing all fields, but also specifies the receiving object of
11356: every selector invocation; you have to change the active object
11357: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11358: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11359: the method entry point is unnecessary with Zsoter's model, because the
11360: receiving object is the active object already. On the other hand, the
11361: explicit change is absolutely necessary in that model, because otherwise
11362: no one could ever change the active object. An ANS Forth implementation
11363: of this model is available through
11364: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11365:
1.78 anton 11366: @cindex @file{oof.fs}, differences to other models
11367: The @file{oof.fs} model combines information hiding and overloading
11368: resolution (by keeping names in various word lists) with object-oriented
11369: programming. It sets the active object implicitly on method entry, but
11370: also allows explicit changing (with @code{>o...o>} or with
11371: @code{with...endwith}). It uses parsing and state-smart objects and
11372: classes for resolving overloading and for early binding: the object or
11373: class parses the selector and determines the method from this. If the
11374: selector is not parsed by an object or class, it performs a call to the
11375: selector for the active object (late binding), like Zsoter's model.
11376: Fields are always accessed through the active object. The big
11377: disadvantage of this model is the parsing and the state-smartness, which
11378: reduces extensibility and increases the opportunities for subtle bugs;
11379: essentially, you are only safe if you never tick or @code{postpone} an
11380: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11381:
1.78 anton 11382: @cindex @file{mini-oof.fs}, differences to other models
11383: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11384: version of the @file{objects.fs} model, but syntactically it is a
11385: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11386:
11387:
1.78 anton 11388: @c -------------------------------------------------------------
11389: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11390: @section Programming Tools
11391: @cindex programming tools
1.21 crook 11392:
1.78 anton 11393: @c !! move this and assembler down below OO stuff.
1.21 crook 11394:
1.78 anton 11395: @menu
11396: * Examining::
11397: * Forgetting words::
11398: * Debugging:: Simple and quick.
11399: * Assertions:: Making your programs self-checking.
11400: * Singlestep Debugger:: Executing your program word by word.
11401: @end menu
1.21 crook 11402:
1.78 anton 11403: @node Examining, Forgetting words, Programming Tools, Programming Tools
11404: @subsection Examining data and code
11405: @cindex examining data and code
11406: @cindex data examination
11407: @cindex code examination
1.44 crook 11408:
1.78 anton 11409: The following words inspect the stack non-destructively:
1.21 crook 11410:
1.78 anton 11411: doc-.s
11412: doc-f.s
1.44 crook 11413:
1.78 anton 11414: There is a word @code{.r} but it does @i{not} display the return stack!
11415: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11416:
1.78 anton 11417: doc-depth
11418: doc-fdepth
11419: doc-clearstack
1.124 anton 11420: doc-clearstacks
1.21 crook 11421:
1.78 anton 11422: The following words inspect memory.
1.21 crook 11423:
1.78 anton 11424: doc-?
11425: doc-dump
1.21 crook 11426:
1.78 anton 11427: And finally, @code{see} allows to inspect code:
1.21 crook 11428:
1.78 anton 11429: doc-see
11430: doc-xt-see
1.111 anton 11431: doc-simple-see
11432: doc-simple-see-range
1.21 crook 11433:
1.78 anton 11434: @node Forgetting words, Debugging, Examining, Programming Tools
11435: @subsection Forgetting words
11436: @cindex words, forgetting
11437: @cindex forgeting words
1.21 crook 11438:
1.78 anton 11439: @c anton: other, maybe better places for this subsection: Defining Words;
11440: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11441:
1.78 anton 11442: Forth allows you to forget words (and everything that was alloted in the
11443: dictonary after them) in a LIFO manner.
1.21 crook 11444:
1.78 anton 11445: doc-marker
1.21 crook 11446:
1.78 anton 11447: The most common use of this feature is during progam development: when
11448: you change a source file, forget all the words it defined and load it
11449: again (since you also forget everything defined after the source file
11450: was loaded, you have to reload that, too). Note that effects like
11451: storing to variables and destroyed system words are not undone when you
11452: forget words. With a system like Gforth, that is fast enough at
11453: starting up and compiling, I find it more convenient to exit and restart
11454: Gforth, as this gives me a clean slate.
1.21 crook 11455:
1.78 anton 11456: Here's an example of using @code{marker} at the start of a source file
11457: that you are debugging; it ensures that you only ever have one copy of
11458: the file's definitions compiled at any time:
1.21 crook 11459:
1.78 anton 11460: @example
11461: [IFDEF] my-code
11462: my-code
11463: [ENDIF]
1.26 crook 11464:
1.78 anton 11465: marker my-code
11466: init-included-files
1.21 crook 11467:
1.78 anton 11468: \ .. definitions start here
11469: \ .
11470: \ .
11471: \ end
11472: @end example
1.21 crook 11473:
1.26 crook 11474:
1.78 anton 11475: @node Debugging, Assertions, Forgetting words, Programming Tools
11476: @subsection Debugging
11477: @cindex debugging
1.21 crook 11478:
1.78 anton 11479: Languages with a slow edit/compile/link/test development loop tend to
11480: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11481:
1.78 anton 11482: A much better (faster) way in fast-compiling languages is to add
11483: printing code at well-selected places, let the program run, look at
11484: the output, see where things went wrong, add more printing code, etc.,
11485: until the bug is found.
1.21 crook 11486:
1.78 anton 11487: The simple debugging aids provided in @file{debugs.fs}
11488: are meant to support this style of debugging.
1.21 crook 11489:
1.78 anton 11490: The word @code{~~} prints debugging information (by default the source
11491: location and the stack contents). It is easy to insert. If you use Emacs
11492: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11493: query-replace them with nothing). The deferred words
1.101 anton 11494: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11495: @code{~~}. The default source location output format works well with
11496: Emacs' compilation mode, so you can step through the program at the
11497: source level using @kbd{C-x `} (the advantage over a stepping debugger
11498: is that you can step in any direction and you know where the crash has
11499: happened or where the strange data has occurred).
1.21 crook 11500:
1.78 anton 11501: doc-~~
11502: doc-printdebugdata
1.101 anton 11503: doc-.debugline
1.21 crook 11504:
1.106 anton 11505: @cindex filenames in @code{~~} output
11506: @code{~~} (and assertions) will usually print the wrong file name if a
11507: marker is executed in the same file after their occurance. They will
11508: print @samp{*somewhere*} as file name if a marker is executed in the
11509: same file before their occurance.
11510:
11511:
1.78 anton 11512: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11513: @subsection Assertions
11514: @cindex assertions
1.21 crook 11515:
1.78 anton 11516: It is a good idea to make your programs self-checking, especially if you
11517: make an assumption that may become invalid during maintenance (for
11518: example, that a certain field of a data structure is never zero). Gforth
11519: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11520:
11521: @example
1.78 anton 11522: assert( @i{flag} )
1.26 crook 11523: @end example
11524:
1.78 anton 11525: The code between @code{assert(} and @code{)} should compute a flag, that
11526: should be true if everything is alright and false otherwise. It should
11527: not change anything else on the stack. The overall stack effect of the
11528: assertion is @code{( -- )}. E.g.
1.21 crook 11529:
1.26 crook 11530: @example
1.78 anton 11531: assert( 1 1 + 2 = ) \ what we learn in school
11532: assert( dup 0<> ) \ assert that the top of stack is not zero
11533: assert( false ) \ this code should not be reached
1.21 crook 11534: @end example
11535:
1.78 anton 11536: The need for assertions is different at different times. During
11537: debugging, we want more checking, in production we sometimes care more
11538: for speed. Therefore, assertions can be turned off, i.e., the assertion
11539: becomes a comment. Depending on the importance of an assertion and the
11540: time it takes to check it, you may want to turn off some assertions and
11541: keep others turned on. Gforth provides several levels of assertions for
11542: this purpose:
11543:
11544:
11545: doc-assert0(
11546: doc-assert1(
11547: doc-assert2(
11548: doc-assert3(
11549: doc-assert(
11550: doc-)
1.21 crook 11551:
11552:
1.78 anton 11553: The variable @code{assert-level} specifies the highest assertions that
11554: are turned on. I.e., at the default @code{assert-level} of one,
11555: @code{assert0(} and @code{assert1(} assertions perform checking, while
11556: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11557:
1.78 anton 11558: The value of @code{assert-level} is evaluated at compile-time, not at
11559: run-time. Therefore you cannot turn assertions on or off at run-time;
11560: you have to set the @code{assert-level} appropriately before compiling a
11561: piece of code. You can compile different pieces of code at different
11562: @code{assert-level}s (e.g., a trusted library at level 1 and
11563: newly-written code at level 3).
1.26 crook 11564:
11565:
1.78 anton 11566: doc-assert-level
1.26 crook 11567:
11568:
1.78 anton 11569: If an assertion fails, a message compatible with Emacs' compilation mode
11570: is produced and the execution is aborted (currently with @code{ABORT"}.
11571: If there is interest, we will introduce a special throw code. But if you
11572: intend to @code{catch} a specific condition, using @code{throw} is
11573: probably more appropriate than an assertion).
1.106 anton 11574:
11575: @cindex filenames in assertion output
11576: Assertions (and @code{~~}) will usually print the wrong file name if a
11577: marker is executed in the same file after their occurance. They will
11578: print @samp{*somewhere*} as file name if a marker is executed in the
11579: same file before their occurance.
1.44 crook 11580:
1.78 anton 11581: Definitions in ANS Forth for these assertion words are provided
11582: in @file{compat/assert.fs}.
1.26 crook 11583:
1.44 crook 11584:
1.78 anton 11585: @node Singlestep Debugger, , Assertions, Programming Tools
11586: @subsection Singlestep Debugger
11587: @cindex singlestep Debugger
11588: @cindex debugging Singlestep
1.44 crook 11589:
1.112 anton 11590: The singlestep debugger does not work in this release.
11591:
1.78 anton 11592: When you create a new word there's often the need to check whether it
11593: behaves correctly or not. You can do this by typing @code{dbg
11594: badword}. A debug session might look like this:
1.26 crook 11595:
1.78 anton 11596: @example
11597: : badword 0 DO i . LOOP ; ok
11598: 2 dbg badword
11599: : badword
11600: Scanning code...
1.44 crook 11601:
1.78 anton 11602: Nesting debugger ready!
1.44 crook 11603:
1.78 anton 11604: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11605: 400D4740 8049F68 DO -> [ 0 ]
11606: 400D4744 804A0C8 i -> [ 1 ] 00000
11607: 400D4748 400C5E60 . -> 0 [ 0 ]
11608: 400D474C 8049D0C LOOP -> [ 0 ]
11609: 400D4744 804A0C8 i -> [ 1 ] 00001
11610: 400D4748 400C5E60 . -> 1 [ 0 ]
11611: 400D474C 8049D0C LOOP -> [ 0 ]
11612: 400D4758 804B384 ; -> ok
11613: @end example
1.21 crook 11614:
1.78 anton 11615: Each line displayed is one step. You always have to hit return to
11616: execute the next word that is displayed. If you don't want to execute
11617: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11618: an overview what keys are available:
1.44 crook 11619:
1.78 anton 11620: @table @i
1.44 crook 11621:
1.78 anton 11622: @item @key{RET}
11623: Next; Execute the next word.
1.21 crook 11624:
1.78 anton 11625: @item n
11626: Nest; Single step through next word.
1.44 crook 11627:
1.78 anton 11628: @item u
11629: Unnest; Stop debugging and execute rest of word. If we got to this word
11630: with nest, continue debugging with the calling word.
1.44 crook 11631:
1.78 anton 11632: @item d
11633: Done; Stop debugging and execute rest.
1.21 crook 11634:
1.78 anton 11635: @item s
11636: Stop; Abort immediately.
1.44 crook 11637:
1.78 anton 11638: @end table
1.44 crook 11639:
1.78 anton 11640: Debugging large application with this mechanism is very difficult, because
11641: you have to nest very deeply into the program before the interesting part
11642: begins. This takes a lot of time.
1.26 crook 11643:
1.78 anton 11644: To do it more directly put a @code{BREAK:} command into your source code.
11645: When program execution reaches @code{BREAK:} the single step debugger is
11646: invoked and you have all the features described above.
1.44 crook 11647:
1.78 anton 11648: If you have more than one part to debug it is useful to know where the
11649: program has stopped at the moment. You can do this by the
11650: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11651: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11652:
1.26 crook 11653:
1.78 anton 11654: doc-dbg
11655: doc-break:
11656: doc-break"
1.44 crook 11657:
11658:
1.26 crook 11659:
1.78 anton 11660: @c -------------------------------------------------------------
11661: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11662: @section Assembler and Code Words
11663: @cindex assembler
11664: @cindex code words
1.44 crook 11665:
1.78 anton 11666: @menu
11667: * Code and ;code::
11668: * Common Assembler:: Assembler Syntax
11669: * Common Disassembler::
11670: * 386 Assembler:: Deviations and special cases
11671: * Alpha Assembler:: Deviations and special cases
11672: * MIPS assembler:: Deviations and special cases
11673: * Other assemblers:: How to write them
11674: @end menu
1.21 crook 11675:
1.78 anton 11676: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11677: @subsection @code{Code} and @code{;code}
1.26 crook 11678:
1.78 anton 11679: Gforth provides some words for defining primitives (words written in
11680: machine code), and for defining the machine-code equivalent of
11681: @code{DOES>}-based defining words. However, the machine-independent
11682: nature of Gforth poses a few problems: First of all, Gforth runs on
11683: several architectures, so it can provide no standard assembler. What's
11684: worse is that the register allocation not only depends on the processor,
11685: but also on the @code{gcc} version and options used.
1.44 crook 11686:
1.78 anton 11687: The words that Gforth offers encapsulate some system dependences (e.g.,
11688: the header structure), so a system-independent assembler may be used in
11689: Gforth. If you do not have an assembler, you can compile machine code
11690: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11691: because these words emit stuff in @i{data} space; it works because
11692: Gforth has unified code/data spaces. Assembler isn't likely to be
11693: portable anyway.}.
1.21 crook 11694:
1.44 crook 11695:
1.78 anton 11696: doc-assembler
11697: doc-init-asm
11698: doc-code
11699: doc-end-code
11700: doc-;code
11701: doc-flush-icache
1.44 crook 11702:
1.21 crook 11703:
1.78 anton 11704: If @code{flush-icache} does not work correctly, @code{code} words
11705: etc. will not work (reliably), either.
1.44 crook 11706:
1.78 anton 11707: The typical usage of these @code{code} words can be shown most easily by
11708: analogy to the equivalent high-level defining words:
1.44 crook 11709:
1.78 anton 11710: @example
11711: : foo code foo
11712: <high-level Forth words> <assembler>
11713: ; end-code
11714:
11715: : bar : bar
11716: <high-level Forth words> <high-level Forth words>
11717: CREATE CREATE
11718: <high-level Forth words> <high-level Forth words>
11719: DOES> ;code
11720: <high-level Forth words> <assembler>
11721: ; end-code
11722: @end example
1.21 crook 11723:
1.78 anton 11724: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11725:
1.78 anton 11726: @cindex registers of the inner interpreter
11727: In the assembly code you will want to refer to the inner interpreter's
11728: registers (e.g., the data stack pointer) and you may want to use other
11729: registers for temporary storage. Unfortunately, the register allocation
11730: is installation-dependent.
1.44 crook 11731:
1.78 anton 11732: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11733: (return stack pointer) may be in different places in @code{gforth} and
11734: @code{gforth-fast}, or different installations. This means that you
11735: cannot write a @code{NEXT} routine that works reliably on both versions
11736: or different installations; so for doing @code{NEXT}, I recommend
11737: jumping to @code{' noop >code-address}, which contains nothing but a
11738: @code{NEXT}.
1.21 crook 11739:
1.78 anton 11740: For general accesses to the inner interpreter's registers, the easiest
11741: solution is to use explicit register declarations (@pxref{Explicit Reg
11742: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11743: all of the inner interpreter's registers: You have to compile Gforth
11744: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11745: the appropriate declarations must be present in the @code{machine.h}
11746: file (see @code{mips.h} for an example; you can find a full list of all
11747: declarable register symbols with @code{grep register engine.c}). If you
11748: give explicit registers to all variables that are declared at the
11749: beginning of @code{engine()}, you should be able to use the other
11750: caller-saved registers for temporary storage. Alternatively, you can use
11751: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11752: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11753: reserve a register (however, this restriction on register allocation may
11754: slow Gforth significantly).
1.44 crook 11755:
1.78 anton 11756: If this solution is not viable (e.g., because @code{gcc} does not allow
11757: you to explicitly declare all the registers you need), you have to find
11758: out by looking at the code where the inner interpreter's registers
11759: reside and which registers can be used for temporary storage. You can
11760: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11761:
1.78 anton 11762: In any case, it is good practice to abstract your assembly code from the
11763: actual register allocation. E.g., if the data stack pointer resides in
11764: register @code{$17}, create an alias for this register called @code{sp},
11765: and use that in your assembly code.
1.21 crook 11766:
1.78 anton 11767: @cindex code words, portable
11768: Another option for implementing normal and defining words efficiently
11769: is to add the desired functionality to the source of Gforth. For normal
11770: words you just have to edit @file{primitives} (@pxref{Automatic
11771: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11772: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11773: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11774:
1.78 anton 11775: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11776: @subsection Common Assembler
1.44 crook 11777:
1.78 anton 11778: The assemblers in Gforth generally use a postfix syntax, i.e., the
11779: instruction name follows the operands.
1.21 crook 11780:
1.78 anton 11781: The operands are passed in the usual order (the same that is used in the
11782: manual of the architecture). Since they all are Forth words, they have
11783: to be separated by spaces; you can also use Forth words to compute the
11784: operands.
1.44 crook 11785:
1.78 anton 11786: The instruction names usually end with a @code{,}. This makes it easier
11787: to visually separate instructions if you put several of them on one
11788: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11789:
1.78 anton 11790: Registers are usually specified by number; e.g., (decimal) @code{11}
11791: specifies registers R11 and F11 on the Alpha architecture (which one,
11792: depends on the instruction). The usual names are also available, e.g.,
11793: @code{s2} for R11 on Alpha.
1.21 crook 11794:
1.78 anton 11795: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11796: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11797: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11798: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11799: conditions are specified in a way specific to each assembler.
1.1 anton 11800:
1.78 anton 11801: Note that the register assignments of the Gforth engine can change
11802: between Gforth versions, or even between different compilations of the
11803: same Gforth version (e.g., if you use a different GCC version). So if
11804: you want to refer to Gforth's registers (e.g., the stack pointer or
11805: TOS), I recommend defining your own words for refering to these
11806: registers, and using them later on; then you can easily adapt to a
11807: changed register assignment. The stability of the register assignment
11808: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11809:
1.100 anton 11810: The most common use of these registers is to dispatch to the next word
11811: (the @code{next} routine). A portable way to do this is to jump to
11812: @code{' noop >code-address} (of course, this is less efficient than
11813: integrating the @code{next} code and scheduling it well).
1.1 anton 11814:
1.96 anton 11815: Another difference between Gforth version is that the top of stack is
11816: kept in memory in @code{gforth} and, on most platforms, in a register in
11817: @code{gforth-fast}.
11818:
1.78 anton 11819: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11820: @subsection Common Disassembler
1.127 anton 11821: @cindex disassembler, general
11822: @cindex gdb disassembler
1.1 anton 11823:
1.78 anton 11824: You can disassemble a @code{code} word with @code{see}
11825: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11826:
1.127 anton 11827: doc-discode
1.44 crook 11828:
1.127 anton 11829: There are two kinds of disassembler for Gforth: The Forth disassembler
11830: (available on some CPUs) and the gdb disassembler (available on
11831: platforms with @command{gdb} and @command{mktemp}). If both are
11832: available, the Forth disassembler is used by default. If you prefer
11833: the gdb disassembler, say
11834:
11835: @example
11836: ' disasm-gdb is discode
11837: @end example
11838:
11839: If neither is available, @code{discode} performs @code{dump}.
11840:
11841: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11842: assembler (i.e., same syntax, etc.). It also includes additional
11843: information in comments. In particular, the address of the instruction
11844: is given in a comment before the instruction.
1.1 anton 11845:
1.127 anton 11846: The gdb disassembler produces output in the same format as the gdb
11847: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11848: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11849: the 386 and AMD64 architectures).
11850:
1.78 anton 11851: @code{See} may display more or less than the actual code of the word,
11852: because the recognition of the end of the code is unreliable. You can
1.127 anton 11853: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11854: the code word is not immediately followed by a named word. If you have
1.116 anton 11855: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11856: to ensure that the end is recognized.
1.21 crook 11857:
1.78 anton 11858: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11859: @subsection 386 Assembler
1.44 crook 11860:
1.78 anton 11861: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11862: available under GPL, and originally part of bigFORTH.
1.21 crook 11863:
1.78 anton 11864: The 386 disassembler included in Gforth was written by Andrew McKewan
11865: and is in the public domain.
1.21 crook 11866:
1.91 anton 11867: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11868:
1.78 anton 11869: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11870:
1.78 anton 11871: The assembler includes all instruction of the Athlon, i.e. 486 core
11872: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11873: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11874: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11875:
1.78 anton 11876: There are several prefixes to switch between different operation sizes,
11877: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11878: double-word accesses. Addressing modes can be switched with @code{.wa}
11879: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11880: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11881:
1.78 anton 11882: For floating point operations, the prefixes are @code{.fs} (IEEE
11883: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11884: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11885:
1.78 anton 11886: The MMX opcodes don't have size prefixes, they are spelled out like in
11887: the Intel assembler. Instead of move from and to memory, there are
11888: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11889:
1.78 anton 11890: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11891: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11892: e.g., @code{3 #}. Here are some examples of addressing modes in various
11893: syntaxes:
1.21 crook 11894:
1.26 crook 11895: @example
1.91 anton 11896: Gforth Intel (NASM) AT&T (gas) Name
11897: .w ax ax %ax register (16 bit)
11898: ax eax %eax register (32 bit)
11899: 3 # offset 3 $3 immediate
11900: 1000 #) byte ptr 1000 1000 displacement
11901: bx ) [ebx] (%ebx) base
11902: 100 di d) 100[edi] 100(%edi) base+displacement
11903: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11904: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11905: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11906: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11907: @end example
11908:
11909: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11910: @code{DI)} to enforce 32-bit displacement fields (useful for
11911: later patching).
1.21 crook 11912:
1.78 anton 11913: Some example of instructions are:
1.1 anton 11914:
11915: @example
1.78 anton 11916: ax bx mov \ move ebx,eax
11917: 3 # ax mov \ mov eax,3
1.137 pazsan 11918: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 11919: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11920: .w ax bx mov \ mov bx,ax
1.1 anton 11921: @end example
11922:
1.78 anton 11923: The following forms are supported for binary instructions:
1.1 anton 11924:
11925: @example
1.78 anton 11926: <reg> <reg> <inst>
11927: <n> # <reg> <inst>
11928: <mem> <reg> <inst>
11929: <reg> <mem> <inst>
1.136 pazsan 11930: <n> # <mem> <inst>
1.1 anton 11931: @end example
11932:
1.136 pazsan 11933: The shift/rotate syntax is:
1.1 anton 11934:
1.26 crook 11935: @example
1.78 anton 11936: <reg/mem> 1 # shl \ shortens to shift without immediate
11937: <reg/mem> 4 # shl
11938: <reg/mem> cl shl
1.26 crook 11939: @end example
1.1 anton 11940:
1.78 anton 11941: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11942: the byte version.
1.1 anton 11943:
1.78 anton 11944: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11945: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11946: pc < >= <= >}. (Note that most of these words shadow some Forth words
11947: when @code{assembler} is in front of @code{forth} in the search path,
11948: e.g., in @code{code} words). Currently the control structure words use
11949: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11950: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11951:
1.78 anton 11952: Here is an example of a @code{code} word (assumes that the stack pointer
11953: is in esi and the TOS is in ebx):
1.21 crook 11954:
1.26 crook 11955: @example
1.78 anton 11956: code my+ ( n1 n2 -- n )
11957: 4 si D) bx add
11958: 4 # si add
11959: Next
11960: end-code
1.26 crook 11961: @end example
1.21 crook 11962:
1.78 anton 11963: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11964: @subsection Alpha Assembler
1.21 crook 11965:
1.78 anton 11966: The Alpha assembler and disassembler were originally written by Bernd
11967: Thallner.
1.26 crook 11968:
1.78 anton 11969: The register names @code{a0}--@code{a5} are not available to avoid
11970: shadowing hex numbers.
1.2 jwilke 11971:
1.78 anton 11972: Immediate forms of arithmetic instructions are distinguished by a
11973: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11974: does not count as arithmetic instruction).
1.2 jwilke 11975:
1.78 anton 11976: You have to specify all operands to an instruction, even those that
11977: other assemblers consider optional, e.g., the destination register for
11978: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11979:
1.78 anton 11980: You can specify conditions for @code{if,} by removing the first @code{b}
11981: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11982:
1.26 crook 11983: @example
1.78 anton 11984: 11 fgt if, \ if F11>0e
11985: ...
11986: endif,
1.26 crook 11987: @end example
1.2 jwilke 11988:
1.78 anton 11989: @code{fbgt,} gives @code{fgt}.
11990:
11991: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11992: @subsection MIPS assembler
1.2 jwilke 11993:
1.78 anton 11994: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11995:
1.78 anton 11996: Currently the assembler and disassembler only cover the MIPS-I
11997: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11998:
1.78 anton 11999: The register names @code{$a0}--@code{$a3} are not available to avoid
12000: shadowing hex numbers.
1.2 jwilke 12001:
1.78 anton 12002: Because there is no way to distinguish registers from immediate values,
12003: you have to explicitly use the immediate forms of instructions, i.e.,
12004: @code{addiu,}, not just @code{addu,} (@command{as} does this
12005: implicitly).
1.2 jwilke 12006:
1.78 anton 12007: If the architecture manual specifies several formats for the instruction
12008: (e.g., for @code{jalr,}), you usually have to use the one with more
12009: arguments (i.e., two for @code{jalr,}). When in doubt, see
12010: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12011:
1.78 anton 12012: Branches and jumps in the MIPS architecture have a delay slot. You have
12013: to fill it yourself (the simplest way is to use @code{nop,}), the
12014: assembler does not do it for you (unlike @command{as}). Even
12015: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12016: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12017: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12018:
1.78 anton 12019: Note that you must not put branches, jumps, or @code{li,} into the delay
12020: slot: @code{li,} may expand to several instructions, and control flow
12021: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12022:
1.78 anton 12023: For branches the argument specifying the target is a relative address;
12024: You have to add the address of the delay slot to get the absolute
12025: address.
1.1 anton 12026:
1.78 anton 12027: The MIPS architecture also has load delay slots and restrictions on
12028: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12029: yourself to satisfy these restrictions, the assembler does not do it for
12030: you.
1.1 anton 12031:
1.78 anton 12032: You can specify the conditions for @code{if,} etc. by taking a
12033: conditional branch and leaving away the @code{b} at the start and the
12034: @code{,} at the end. E.g.,
1.1 anton 12035:
1.26 crook 12036: @example
1.78 anton 12037: 4 5 eq if,
12038: ... \ do something if $4 equals $5
12039: then,
1.26 crook 12040: @end example
1.1 anton 12041:
1.78 anton 12042: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12043: @subsection Other assemblers
12044:
12045: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12046: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12047: an assembler already. If you are writing them from scratch, please use
12048: a similar syntax style as the one we use (i.e., postfix, commas at the
12049: end of the instruction names, @pxref{Common Assembler}); make the output
12050: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12051: similar to the style we used.
12052:
12053: Hints on implementation: The most important part is to have a good test
12054: suite that contains all instructions. Once you have that, the rest is
12055: easy. For actual coding you can take a look at
12056: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12057: the assembler and disassembler, avoiding redundancy and some potential
12058: bugs. You can also look at that file (and @pxref{Advanced does> usage
12059: example}) to get ideas how to factor a disassembler.
12060:
12061: Start with the disassembler, because it's easier to reuse data from the
12062: disassembler for the assembler than the other way round.
1.1 anton 12063:
1.78 anton 12064: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12065: how simple it can be.
1.1 anton 12066:
1.78 anton 12067: @c -------------------------------------------------------------
12068: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12069: @section Threading Words
12070: @cindex threading words
1.1 anton 12071:
1.78 anton 12072: @cindex code address
12073: These words provide access to code addresses and other threading stuff
12074: in Gforth (and, possibly, other interpretive Forths). It more or less
12075: abstracts away the differences between direct and indirect threading
12076: (and, for direct threading, the machine dependences). However, at
12077: present this wordset is still incomplete. It is also pretty low-level;
12078: some day it will hopefully be made unnecessary by an internals wordset
12079: that abstracts implementation details away completely.
1.1 anton 12080:
1.78 anton 12081: The terminology used here stems from indirect threaded Forth systems; in
12082: such a system, the XT of a word is represented by the CFA (code field
12083: address) of a word; the CFA points to a cell that contains the code
12084: address. The code address is the address of some machine code that
12085: performs the run-time action of invoking the word (e.g., the
12086: @code{dovar:} routine pushes the address of the body of the word (a
12087: variable) on the stack
12088: ).
1.1 anton 12089:
1.78 anton 12090: @cindex code address
12091: @cindex code field address
12092: In an indirect threaded Forth, you can get the code address of @i{name}
12093: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12094: >code-address}, independent of the threading method.
1.1 anton 12095:
1.78 anton 12096: doc-threading-method
12097: doc->code-address
12098: doc-code-address!
1.1 anton 12099:
1.78 anton 12100: @cindex @code{does>}-handler
12101: @cindex @code{does>}-code
12102: For a word defined with @code{DOES>}, the code address usually points to
12103: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12104: routine (in Gforth on some platforms, it can also point to the dodoes
12105: routine itself). What you are typically interested in, though, is
12106: whether a word is a @code{DOES>}-defined word, and what Forth code it
12107: executes; @code{>does-code} tells you that.
1.1 anton 12108:
1.78 anton 12109: doc->does-code
1.1 anton 12110:
1.78 anton 12111: To create a @code{DOES>}-defined word with the following basic words,
12112: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12113: @code{/does-handler} aus behind you have to place your executable Forth
12114: code. Finally you have to create a word and modify its behaviour with
12115: @code{does-handler!}.
1.1 anton 12116:
1.78 anton 12117: doc-does-code!
12118: doc-does-handler!
12119: doc-/does-handler
1.1 anton 12120:
1.78 anton 12121: The code addresses produced by various defining words are produced by
12122: the following words:
1.1 anton 12123:
1.78 anton 12124: doc-docol:
12125: doc-docon:
12126: doc-dovar:
12127: doc-douser:
12128: doc-dodefer:
12129: doc-dofield:
1.1 anton 12130:
1.99 anton 12131: @cindex definer
12132: The following two words generalize @code{>code-address},
12133: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12134:
12135: doc->definer
12136: doc-definer!
12137:
1.26 crook 12138: @c -------------------------------------------------------------
1.78 anton 12139: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12140: @section Passing Commands to the Operating System
12141: @cindex operating system - passing commands
12142: @cindex shell commands
12143:
12144: Gforth allows you to pass an arbitrary string to the host operating
12145: system shell (if such a thing exists) for execution.
12146:
12147: doc-sh
12148: doc-system
12149: doc-$?
1.23 crook 12150: doc-getenv
1.44 crook 12151:
1.26 crook 12152: @c -------------------------------------------------------------
1.47 crook 12153: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12154: @section Keeping track of Time
12155: @cindex time-related words
12156:
12157: doc-ms
12158: doc-time&date
1.79 anton 12159: doc-utime
12160: doc-cputime
1.47 crook 12161:
12162:
12163: @c -------------------------------------------------------------
12164: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12165: @section Miscellaneous Words
12166: @cindex miscellaneous words
12167:
1.29 crook 12168: @comment TODO find homes for these
12169:
1.26 crook 12170: These section lists the ANS Forth words that are not documented
1.21 crook 12171: elsewhere in this manual. Ultimately, they all need proper homes.
12172:
1.68 anton 12173: doc-quit
1.44 crook 12174:
1.26 crook 12175: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12176: (@pxref{ANS conformance}):
1.21 crook 12177:
12178: @code{EDITOR}
12179: @code{EMIT?}
12180: @code{FORGET}
12181:
1.24 anton 12182: @c ******************************************************************
12183: @node Error messages, Tools, Words, Top
12184: @chapter Error messages
12185: @cindex error messages
12186: @cindex backtrace
12187:
12188: A typical Gforth error message looks like this:
12189:
12190: @example
1.86 anton 12191: in file included from \evaluated string/:-1
1.24 anton 12192: in file included from ./yyy.fs:1
12193: ./xxx.fs:4: Invalid memory address
1.134 anton 12194: >>>bar<<<
1.79 anton 12195: Backtrace:
1.25 anton 12196: $400E664C @@
12197: $400E6664 foo
1.24 anton 12198: @end example
12199:
12200: The message identifying the error is @code{Invalid memory address}. The
12201: error happened when text-interpreting line 4 of the file
12202: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12203: word on the line where the error happened, is pointed out (with
1.134 anton 12204: @code{>>>} and @code{<<<}).
1.24 anton 12205:
12206: The file containing the error was included in line 1 of @file{./yyy.fs},
12207: and @file{yyy.fs} was included from a non-file (in this case, by giving
12208: @file{yyy.fs} as command-line parameter to Gforth).
12209:
12210: At the end of the error message you find a return stack dump that can be
12211: interpreted as a backtrace (possibly empty). On top you find the top of
12212: the return stack when the @code{throw} happened, and at the bottom you
12213: find the return stack entry just above the return stack of the topmost
12214: text interpreter.
12215:
12216: To the right of most return stack entries you see a guess for the word
12217: that pushed that return stack entry as its return address. This gives a
12218: backtrace. In our case we see that @code{bar} called @code{foo}, and
12219: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12220: address} exception).
12221:
12222: Note that the backtrace is not perfect: We don't know which return stack
12223: entries are return addresses (so we may get false positives); and in
12224: some cases (e.g., for @code{abort"}) we cannot determine from the return
12225: address the word that pushed the return address, so for some return
12226: addresses you see no names in the return stack dump.
1.25 anton 12227:
12228: @cindex @code{catch} and backtraces
12229: The return stack dump represents the return stack at the time when a
12230: specific @code{throw} was executed. In programs that make use of
12231: @code{catch}, it is not necessarily clear which @code{throw} should be
12232: used for the return stack dump (e.g., consider one @code{throw} that
12233: indicates an error, which is caught, and during recovery another error
1.42 anton 12234: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12235: presents the return stack dump for the first @code{throw} after the last
12236: executed (not returned-to) @code{catch}; this works well in the usual
12237: case.
12238:
12239: @cindex @code{gforth-fast} and backtraces
12240: @cindex @code{gforth-fast}, difference from @code{gforth}
12241: @cindex backtraces with @code{gforth-fast}
12242: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12243: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12244: from primitives (e.g., invalid memory address, stack empty etc.);
12245: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12246: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12247: exception caused by a primitive in @code{gforth-fast}, you will
12248: typically see no return stack dump at all; however, if the exception is
12249: caught by @code{catch} (e.g., for restoring some state), and then
12250: @code{throw}n again, the return stack dump will be for the first such
12251: @code{throw}.
1.2 jwilke 12252:
1.5 anton 12253: @c ******************************************************************
1.24 anton 12254: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12255: @chapter Tools
12256:
12257: @menu
12258: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12259: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12260: @end menu
12261:
12262: See also @ref{Emacs and Gforth}.
12263:
1.126 pazsan 12264: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12265: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12266: @cindex @file{ans-report.fs}
12267: @cindex report the words used in your program
12268: @cindex words used in your program
12269:
12270: If you want to label a Forth program as ANS Forth Program, you must
12271: document which wordsets the program uses; for extension wordsets, it is
12272: helpful to list the words the program requires from these wordsets
12273: (because Forth systems are allowed to provide only some words of them).
12274:
12275: The @file{ans-report.fs} tool makes it easy for you to determine which
12276: words from which wordset and which non-ANS words your application
12277: uses. You simply have to include @file{ans-report.fs} before loading the
12278: program you want to check. After loading your program, you can get the
12279: report with @code{print-ans-report}. A typical use is to run this as
12280: batch job like this:
12281: @example
12282: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12283: @end example
12284:
12285: The output looks like this (for @file{compat/control.fs}):
12286: @example
12287: The program uses the following words
12288: from CORE :
12289: : POSTPONE THEN ; immediate ?dup IF 0=
12290: from BLOCK-EXT :
12291: \
12292: from FILE :
12293: (
12294: @end example
12295:
12296: @subsection Caveats
12297:
12298: Note that @file{ans-report.fs} just checks which words are used, not whether
12299: they are used in an ANS Forth conforming way!
12300:
12301: Some words are defined in several wordsets in the
12302: standard. @file{ans-report.fs} reports them for only one of the
12303: wordsets, and not necessarily the one you expect. It depends on usage
12304: which wordset is the right one to specify. E.g., if you only use the
12305: compilation semantics of @code{S"}, it is a Core word; if you also use
12306: its interpretation semantics, it is a File word.
1.124 anton 12307:
12308:
1.127 anton 12309: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12310: @section Stack depth changes during interpretation
12311: @cindex @file{depth-changes.fs}
12312: @cindex depth changes during interpretation
12313: @cindex stack depth changes during interpretation
12314: @cindex items on the stack after interpretation
12315:
12316: Sometimes you notice that, after loading a file, there are items left
12317: on the stack. The tool @file{depth-changes.fs} helps you find out
12318: quickly where in the file these stack items are coming from.
12319:
12320: The simplest way of using @file{depth-changes.fs} is to include it
12321: before the file(s) you want to check, e.g.:
12322:
12323: @example
12324: gforth depth-changes.fs my-file.fs
12325: @end example
12326:
12327: This will compare the stack depths of the data and FP stack at every
12328: empty line (in interpretation state) against these depths at the last
12329: empty line (in interpretation state). If the depths are not equal,
12330: the position in the file and the stack contents are printed with
12331: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12332: change has occured in the paragraph of non-empty lines before the
12333: indicated line. It is a good idea to leave an empty line at the end
12334: of the file, so the last paragraph is checked, too.
12335:
12336: Checking only at empty lines usually works well, but sometimes you
12337: have big blocks of non-empty lines (e.g., when building a big table),
12338: and you want to know where in this block the stack depth changed. You
12339: can check all interpreted lines with
12340:
12341: @example
12342: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12343: @end example
12344:
12345: This checks the stack depth at every end-of-line. So the depth change
12346: occured in the line reported by the @code{~~} (not in the line
12347: before).
12348:
12349: Note that, while this offers better accuracy in indicating where the
12350: stack depth changes, it will often report many intentional stack depth
12351: changes (e.g., when an interpreted computation stretches across
12352: several lines). You can suppress the checking of some lines by
12353: putting backslashes at the end of these lines (not followed by white
12354: space), and using
12355:
12356: @example
12357: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12358: @end example
1.1 anton 12359:
12360: @c ******************************************************************
1.65 anton 12361: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12362: @chapter ANS conformance
12363: @cindex ANS conformance of Gforth
12364:
12365: To the best of our knowledge, Gforth is an
12366:
12367: ANS Forth System
12368: @itemize @bullet
12369: @item providing the Core Extensions word set
12370: @item providing the Block word set
12371: @item providing the Block Extensions word set
12372: @item providing the Double-Number word set
12373: @item providing the Double-Number Extensions word set
12374: @item providing the Exception word set
12375: @item providing the Exception Extensions word set
12376: @item providing the Facility word set
1.40 anton 12377: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12378: @item providing the File Access word set
12379: @item providing the File Access Extensions word set
12380: @item providing the Floating-Point word set
12381: @item providing the Floating-Point Extensions word set
12382: @item providing the Locals word set
12383: @item providing the Locals Extensions word set
12384: @item providing the Memory-Allocation word set
12385: @item providing the Memory-Allocation Extensions word set (that one's easy)
12386: @item providing the Programming-Tools word set
12387: @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
12388: @item providing the Search-Order word set
12389: @item providing the Search-Order Extensions word set
12390: @item providing the String word set
12391: @item providing the String Extensions word set (another easy one)
12392: @end itemize
12393:
1.118 anton 12394: Gforth has the following environmental restrictions:
12395:
12396: @cindex environmental restrictions
12397: @itemize @bullet
12398: @item
12399: While processing the OS command line, if an exception is not caught,
12400: Gforth exits with a non-zero exit code instyead of performing QUIT.
12401:
12402: @item
12403: When an @code{throw} is performed after a @code{query}, Gforth does not
12404: allways restore the input source specification in effect at the
12405: corresponding catch.
12406:
12407: @end itemize
12408:
12409:
1.1 anton 12410: @cindex system documentation
12411: In addition, ANS Forth systems are required to document certain
12412: implementation choices. This chapter tries to meet these
12413: requirements. In many cases it gives a way to ask the system for the
12414: information instead of providing the information directly, in
12415: particular, if the information depends on the processor, the operating
12416: system or the installation options chosen, or if they are likely to
12417: change during the maintenance of Gforth.
12418:
12419: @comment The framework for the rest has been taken from pfe.
12420:
12421: @menu
12422: * The Core Words::
12423: * The optional Block word set::
12424: * The optional Double Number word set::
12425: * The optional Exception word set::
12426: * The optional Facility word set::
12427: * The optional File-Access word set::
12428: * The optional Floating-Point word set::
12429: * The optional Locals word set::
12430: * The optional Memory-Allocation word set::
12431: * The optional Programming-Tools word set::
12432: * The optional Search-Order word set::
12433: @end menu
12434:
12435:
12436: @c =====================================================================
12437: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12438: @comment node-name, next, previous, up
12439: @section The Core Words
12440: @c =====================================================================
12441: @cindex core words, system documentation
12442: @cindex system documentation, core words
12443:
12444: @menu
12445: * core-idef:: Implementation Defined Options
12446: * core-ambcond:: Ambiguous Conditions
12447: * core-other:: Other System Documentation
12448: @end menu
12449:
12450: @c ---------------------------------------------------------------------
12451: @node core-idef, core-ambcond, The Core Words, The Core Words
12452: @subsection Implementation Defined Options
12453: @c ---------------------------------------------------------------------
12454: @cindex core words, implementation-defined options
12455: @cindex implementation-defined options, core words
12456:
12457:
12458: @table @i
12459: @item (Cell) aligned addresses:
12460: @cindex cell-aligned addresses
12461: @cindex aligned addresses
12462: processor-dependent. Gforth's alignment words perform natural alignment
12463: (e.g., an address aligned for a datum of size 8 is divisible by
12464: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12465:
12466: @item @code{EMIT} and non-graphic characters:
12467: @cindex @code{EMIT} and non-graphic characters
12468: @cindex non-graphic characters and @code{EMIT}
12469: The character is output using the C library function (actually, macro)
12470: @code{putc}.
12471:
12472: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12473: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12474: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12475: @cindex @code{ACCEPT}, editing
12476: @cindex @code{EXPECT}, editing
12477: This is modeled on the GNU readline library (@pxref{Readline
12478: Interaction, , Command Line Editing, readline, The GNU Readline
12479: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12480: producing a full word completion every time you type it (instead of
1.28 crook 12481: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12482:
12483: @item character set:
12484: @cindex character set
12485: The character set of your computer and display device. Gforth is
12486: 8-bit-clean (but some other component in your system may make trouble).
12487:
12488: @item Character-aligned address requirements:
12489: @cindex character-aligned address requirements
12490: installation-dependent. Currently a character is represented by a C
12491: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12492: (Comments on that requested).
12493:
12494: @item character-set extensions and matching of names:
12495: @cindex character-set extensions and matching of names
1.26 crook 12496: @cindex case-sensitivity for name lookup
12497: @cindex name lookup, case-sensitivity
12498: @cindex locale and case-sensitivity
1.21 crook 12499: Any character except the ASCII NUL character can be used in a
1.1 anton 12500: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12501: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12502: function is probably influenced by the locale. E.g., the @code{C} locale
12503: does not know about accents and umlauts, so they are matched
12504: case-sensitively in that locale. For portability reasons it is best to
12505: write programs such that they work in the @code{C} locale. Then one can
12506: use libraries written by a Polish programmer (who might use words
12507: containing ISO Latin-2 encoded characters) and by a French programmer
12508: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12509: funny results for some of the words (which ones, depends on the font you
12510: are using)). Also, the locale you prefer may not be available in other
12511: operating systems. Hopefully, Unicode will solve these problems one day.
12512:
12513: @item conditions under which control characters match a space delimiter:
12514: @cindex space delimiters
12515: @cindex control characters as delimiters
1.117 anton 12516: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12517: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12518: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12519: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12520: interpreter (aka text interpreter) by default, treats all white-space
12521: characters as delimiters.
12522:
1.26 crook 12523: @item format of the control-flow stack:
12524: @cindex control-flow stack, format
12525: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12526: stack item in cells is given by the constant @code{cs-item-size}. At the
12527: time of this writing, an item consists of a (pointer to a) locals list
12528: (third), an address in the code (second), and a tag for identifying the
12529: item (TOS). The following tags are used: @code{defstart},
12530: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12531: @code{scopestart}.
12532:
12533: @item conversion of digits > 35
12534: @cindex digits > 35
12535: The characters @code{[\]^_'} are the digits with the decimal value
12536: 36@minus{}41. There is no way to input many of the larger digits.
12537:
12538: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12539: @cindex @code{EXPECT}, display after end of input
12540: @cindex @code{ACCEPT}, display after end of input
12541: The cursor is moved to the end of the entered string. If the input is
12542: terminated using the @kbd{Return} key, a space is typed.
12543:
12544: @item exception abort sequence of @code{ABORT"}:
12545: @cindex exception abort sequence of @code{ABORT"}
12546: @cindex @code{ABORT"}, exception abort sequence
12547: The error string is stored into the variable @code{"error} and a
12548: @code{-2 throw} is performed.
12549:
12550: @item input line terminator:
12551: @cindex input line terminator
12552: @cindex line terminator on input
1.26 crook 12553: @cindex newline character on input
1.1 anton 12554: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12555: lines. One of these characters is typically produced when you type the
12556: @kbd{Enter} or @kbd{Return} key.
12557:
12558: @item maximum size of a counted string:
12559: @cindex maximum size of a counted string
12560: @cindex counted string, maximum size
12561: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12562: on all platforms, but this may change.
1.1 anton 12563:
12564: @item maximum size of a parsed string:
12565: @cindex maximum size of a parsed string
12566: @cindex parsed string, maximum size
12567: Given by the constant @code{/line}. Currently 255 characters.
12568:
12569: @item maximum size of a definition name, in characters:
12570: @cindex maximum size of a definition name, in characters
12571: @cindex name, maximum length
1.113 anton 12572: MAXU/8
1.1 anton 12573:
12574: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12575: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12576: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12577: MAXU/8
1.1 anton 12578:
12579: @item method of selecting the user input device:
12580: @cindex user input device, method of selecting
12581: The user input device is the standard input. There is currently no way to
12582: change it from within Gforth. However, the input can typically be
12583: redirected in the command line that starts Gforth.
12584:
12585: @item method of selecting the user output device:
12586: @cindex user output device, method of selecting
12587: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12588: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12589: output when the user output device is a terminal, otherwise the output
12590: is buffered.
1.1 anton 12591:
12592: @item methods of dictionary compilation:
12593: What are we expected to document here?
12594:
12595: @item number of bits in one address unit:
12596: @cindex number of bits in one address unit
12597: @cindex address unit, size in bits
12598: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12599: platforms.
1.1 anton 12600:
12601: @item number representation and arithmetic:
12602: @cindex number representation and arithmetic
1.79 anton 12603: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12604:
12605: @item ranges for integer types:
12606: @cindex ranges for integer types
12607: @cindex integer types, ranges
12608: Installation-dependent. Make environmental queries for @code{MAX-N},
12609: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12610: unsigned (and positive) types is 0. The lower bound for signed types on
12611: two's complement and one's complement machines machines can be computed
12612: by adding 1 to the upper bound.
12613:
12614: @item read-only data space regions:
12615: @cindex read-only data space regions
12616: @cindex data-space, read-only regions
12617: The whole Forth data space is writable.
12618:
12619: @item size of buffer at @code{WORD}:
12620: @cindex size of buffer at @code{WORD}
12621: @cindex @code{WORD} buffer size
12622: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12623: shared with the pictured numeric output string. If overwriting
12624: @code{PAD} is acceptable, it is as large as the remaining dictionary
12625: space, although only as much can be sensibly used as fits in a counted
12626: string.
12627:
12628: @item size of one cell in address units:
12629: @cindex cell size
12630: @code{1 cells .}.
12631:
12632: @item size of one character in address units:
12633: @cindex char size
1.79 anton 12634: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12635:
12636: @item size of the keyboard terminal buffer:
12637: @cindex size of the keyboard terminal buffer
12638: @cindex terminal buffer, size
12639: Varies. You can determine the size at a specific time using @code{lp@@
12640: tib - .}. It is shared with the locals stack and TIBs of files that
12641: include the current file. You can change the amount of space for TIBs
12642: and locals stack at Gforth startup with the command line option
12643: @code{-l}.
12644:
12645: @item size of the pictured numeric output buffer:
12646: @cindex size of the pictured numeric output buffer
12647: @cindex pictured numeric output buffer, size
12648: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12649: shared with @code{WORD}.
12650:
12651: @item size of the scratch area returned by @code{PAD}:
12652: @cindex size of the scratch area returned by @code{PAD}
12653: @cindex @code{PAD} size
12654: The remainder of dictionary space. @code{unused pad here - - .}.
12655:
12656: @item system case-sensitivity characteristics:
12657: @cindex case-sensitivity characteristics
1.26 crook 12658: Dictionary searches are case-insensitive (except in
1.1 anton 12659: @code{TABLE}s). However, as explained above under @i{character-set
12660: extensions}, the matching for non-ASCII characters is determined by the
12661: locale you are using. In the default @code{C} locale all non-ASCII
12662: characters are matched case-sensitively.
12663:
12664: @item system prompt:
12665: @cindex system prompt
12666: @cindex prompt
12667: @code{ ok} in interpret state, @code{ compiled} in compile state.
12668:
12669: @item division rounding:
12670: @cindex division rounding
12671: installation dependent. @code{s" floored" environment? drop .}. We leave
12672: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12673: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12674:
12675: @item values of @code{STATE} when true:
12676: @cindex @code{STATE} values
12677: -1.
12678:
12679: @item values returned after arithmetic overflow:
12680: On two's complement machines, arithmetic is performed modulo
12681: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12682: arithmetic (with appropriate mapping for signed types). Division by zero
12683: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12684: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12685:
12686: @item whether the current definition can be found after @t{DOES>}:
12687: @cindex @t{DOES>}, visibility of current definition
12688: No.
12689:
12690: @end table
12691:
12692: @c ---------------------------------------------------------------------
12693: @node core-ambcond, core-other, core-idef, The Core Words
12694: @subsection Ambiguous conditions
12695: @c ---------------------------------------------------------------------
12696: @cindex core words, ambiguous conditions
12697: @cindex ambiguous conditions, core words
12698:
12699: @table @i
12700:
12701: @item a name is neither a word nor a number:
12702: @cindex name not found
1.26 crook 12703: @cindex undefined word
1.80 anton 12704: @code{-13 throw} (Undefined word).
1.1 anton 12705:
12706: @item a definition name exceeds the maximum length allowed:
1.26 crook 12707: @cindex word name too long
1.1 anton 12708: @code{-19 throw} (Word name too long)
12709:
12710: @item addressing a region not inside the various data spaces of the forth system:
12711: @cindex Invalid memory address
1.32 anton 12712: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12713: typically readable. Accessing other addresses gives results dependent on
12714: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12715: address).
12716:
12717: @item argument type incompatible with parameter:
1.26 crook 12718: @cindex argument type mismatch
1.1 anton 12719: This is usually not caught. Some words perform checks, e.g., the control
12720: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12721: mismatch).
12722:
12723: @item attempting to obtain the execution token of a word with undefined execution semantics:
12724: @cindex Interpreting a compile-only word, for @code{'} etc.
12725: @cindex execution token of words with undefined execution semantics
12726: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12727: get an execution token for @code{compile-only-error} (which performs a
12728: @code{-14 throw} when executed).
12729:
12730: @item dividing by zero:
12731: @cindex dividing by zero
12732: @cindex floating point unidentified fault, integer division
1.80 anton 12733: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12734: zero); on other systems, this typically results in a @code{-55 throw}
12735: (Floating-point unidentified fault).
1.1 anton 12736:
12737: @item insufficient data stack or return stack space:
12738: @cindex insufficient data stack or return stack space
12739: @cindex stack overflow
1.26 crook 12740: @cindex address alignment exception, stack overflow
1.1 anton 12741: @cindex Invalid memory address, stack overflow
12742: Depending on the operating system, the installation, and the invocation
12743: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12744: it is not checked. If it is checked, you typically get a @code{-3 throw}
12745: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12746: throw} (Invalid memory address) (depending on the platform and how you
12747: achieved the overflow) as soon as the overflow happens. If it is not
12748: checked, overflows typically result in mysterious illegal memory
12749: accesses, producing @code{-9 throw} (Invalid memory address) or
12750: @code{-23 throw} (Address alignment exception); they might also destroy
12751: the internal data structure of @code{ALLOCATE} and friends, resulting in
12752: various errors in these words.
1.1 anton 12753:
12754: @item insufficient space for loop control parameters:
12755: @cindex insufficient space for loop control parameters
1.80 anton 12756: Like other return stack overflows.
1.1 anton 12757:
12758: @item insufficient space in the dictionary:
12759: @cindex insufficient space in the dictionary
12760: @cindex dictionary overflow
1.12 anton 12761: If you try to allot (either directly with @code{allot}, or indirectly
12762: with @code{,}, @code{create} etc.) more memory than available in the
12763: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12764: to access memory beyond the end of the dictionary, the results are
12765: similar to stack overflows.
1.1 anton 12766:
12767: @item interpreting a word with undefined interpretation semantics:
12768: @cindex interpreting a word with undefined interpretation semantics
12769: @cindex Interpreting a compile-only word
12770: For some words, we have defined interpretation semantics. For the
12771: others: @code{-14 throw} (Interpreting a compile-only word).
12772:
12773: @item modifying the contents of the input buffer or a string literal:
12774: @cindex modifying the contents of the input buffer or a string literal
12775: These are located in writable memory and can be modified.
12776:
12777: @item overflow of the pictured numeric output string:
12778: @cindex overflow of the pictured numeric output string
12779: @cindex pictured numeric output string, overflow
1.24 anton 12780: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12781:
12782: @item parsed string overflow:
12783: @cindex parsed string overflow
12784: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12785:
12786: @item producing a result out of range:
12787: @cindex result out of range
12788: On two's complement machines, arithmetic is performed modulo
12789: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12790: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12791: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12792: throw} (floating point unidentified fault). @code{convert} and
12793: @code{>number} currently overflow silently.
1.1 anton 12794:
12795: @item reading from an empty data or return stack:
12796: @cindex stack empty
12797: @cindex stack underflow
1.24 anton 12798: @cindex return stack underflow
1.1 anton 12799: The data stack is checked by the outer (aka text) interpreter after
12800: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12801: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12802: depending on operating system, installation, and invocation. If they are
12803: caught by a check, they typically result in @code{-4 throw} (Stack
12804: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12805: (Invalid memory address), depending on the platform and which stack
12806: underflows and by how much. Note that even if the system uses checking
12807: (through the MMU), your program may have to underflow by a significant
12808: number of stack items to trigger the reaction (the reason for this is
12809: that the MMU, and therefore the checking, works with a page-size
12810: granularity). If there is no checking, the symptoms resulting from an
12811: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12812: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12813: (Invalid memory address) and Illegal Instruction (typically @code{-260
12814: throw}).
1.1 anton 12815:
12816: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12817: @cindex unexpected end of the input buffer
12818: @cindex zero-length string as a name
12819: @cindex Attempt to use zero-length string as a name
12820: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12821: use zero-length string as a name). Words like @code{'} probably will not
12822: find what they search. Note that it is possible to create zero-length
12823: names with @code{nextname} (should it not?).
12824:
12825: @item @code{>IN} greater than input buffer:
12826: @cindex @code{>IN} greater than input buffer
12827: The next invocation of a parsing word returns a string with length 0.
12828:
12829: @item @code{RECURSE} appears after @code{DOES>}:
12830: @cindex @code{RECURSE} appears after @code{DOES>}
12831: Compiles a recursive call to the defining word, not to the defined word.
12832:
12833: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12834: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12835: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12836: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12837: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12838: the end of the file was reached), its source-id may be
12839: reused. Therefore, restoring an input source specification referencing a
12840: closed file may lead to unpredictable results instead of a @code{-12
12841: THROW}.
12842:
12843: In the future, Gforth may be able to restore input source specifications
12844: from other than the current input source.
12845:
12846: @item data space containing definitions gets de-allocated:
12847: @cindex data space containing definitions gets de-allocated
12848: Deallocation with @code{allot} is not checked. This typically results in
12849: memory access faults or execution of illegal instructions.
12850:
12851: @item data space read/write with incorrect alignment:
12852: @cindex data space read/write with incorrect alignment
12853: @cindex alignment faults
1.26 crook 12854: @cindex address alignment exception
1.1 anton 12855: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12856: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12857: alignment turned on, incorrect alignment results in a @code{-9 throw}
12858: (Invalid memory address). There are reportedly some processors with
1.12 anton 12859: alignment restrictions that do not report violations.
1.1 anton 12860:
12861: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12862: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12863: Like other alignment errors.
12864:
12865: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12866: Like other stack underflows.
12867:
12868: @item loop control parameters not available:
12869: @cindex loop control parameters not available
12870: Not checked. The counted loop words simply assume that the top of return
12871: stack items are loop control parameters and behave accordingly.
12872:
12873: @item most recent definition does not have a name (@code{IMMEDIATE}):
12874: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12875: @cindex last word was headerless
12876: @code{abort" last word was headerless"}.
12877:
12878: @item name not defined by @code{VALUE} used by @code{TO}:
12879: @cindex name not defined by @code{VALUE} used by @code{TO}
12880: @cindex @code{TO} on non-@code{VALUE}s
12881: @cindex Invalid name argument, @code{TO}
12882: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12883: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12884:
12885: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12886: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12887: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12888: @code{-13 throw} (Undefined word)
12889:
12890: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12891: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12892: Gforth behaves as if they were of the same type. I.e., you can predict
12893: the behaviour by interpreting all parameters as, e.g., signed.
12894:
12895: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12896: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12897: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12898: compilation semantics of @code{TO}.
12899:
12900: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12901: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12902: @cindex @code{WORD}, string overflow
12903: Not checked. The string will be ok, but the count will, of course,
12904: contain only the least significant bits of the length.
12905:
12906: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12907: @cindex @code{LSHIFT}, large shift counts
12908: @cindex @code{RSHIFT}, large shift counts
12909: Processor-dependent. Typical behaviours are returning 0 and using only
12910: the low bits of the shift count.
12911:
12912: @item word not defined via @code{CREATE}:
12913: @cindex @code{>BODY} of non-@code{CREATE}d words
12914: @code{>BODY} produces the PFA of the word no matter how it was defined.
12915:
12916: @cindex @code{DOES>} of non-@code{CREATE}d words
12917: @code{DOES>} changes the execution semantics of the last defined word no
12918: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12919: @code{CREATE , DOES>}.
12920:
12921: @item words improperly used outside @code{<#} and @code{#>}:
12922: Not checked. As usual, you can expect memory faults.
12923:
12924: @end table
12925:
12926:
12927: @c ---------------------------------------------------------------------
12928: @node core-other, , core-ambcond, The Core Words
12929: @subsection Other system documentation
12930: @c ---------------------------------------------------------------------
12931: @cindex other system documentation, core words
12932: @cindex core words, other system documentation
12933:
12934: @table @i
12935: @item nonstandard words using @code{PAD}:
12936: @cindex @code{PAD} use by nonstandard words
12937: None.
12938:
12939: @item operator's terminal facilities available:
12940: @cindex operator's terminal facilities available
1.80 anton 12941: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12942: and you can give commands to Gforth interactively. The actual facilities
12943: available depend on how you invoke Gforth.
12944:
12945: @item program data space available:
12946: @cindex program data space available
12947: @cindex data space available
12948: @code{UNUSED .} gives the remaining dictionary space. The total
12949: dictionary space can be specified with the @code{-m} switch
12950: (@pxref{Invoking Gforth}) when Gforth starts up.
12951:
12952: @item return stack space available:
12953: @cindex return stack space available
12954: You can compute the total return stack space in cells with
12955: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12956: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12957:
12958: @item stack space available:
12959: @cindex stack space available
12960: You can compute the total data stack space in cells with
12961: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12962: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12963:
12964: @item system dictionary space required, in address units:
12965: @cindex system dictionary space required, in address units
12966: Type @code{here forthstart - .} after startup. At the time of this
12967: writing, this gives 80080 (bytes) on a 32-bit system.
12968: @end table
12969:
12970:
12971: @c =====================================================================
12972: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12973: @section The optional Block word set
12974: @c =====================================================================
12975: @cindex system documentation, block words
12976: @cindex block words, system documentation
12977:
12978: @menu
12979: * block-idef:: Implementation Defined Options
12980: * block-ambcond:: Ambiguous Conditions
12981: * block-other:: Other System Documentation
12982: @end menu
12983:
12984:
12985: @c ---------------------------------------------------------------------
12986: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12987: @subsection Implementation Defined Options
12988: @c ---------------------------------------------------------------------
12989: @cindex implementation-defined options, block words
12990: @cindex block words, implementation-defined options
12991:
12992: @table @i
12993: @item the format for display by @code{LIST}:
12994: @cindex @code{LIST} display format
12995: First the screen number is displayed, then 16 lines of 64 characters,
12996: each line preceded by the line number.
12997:
12998: @item the length of a line affected by @code{\}:
12999: @cindex length of a line affected by @code{\}
13000: @cindex @code{\}, line length in blocks
13001: 64 characters.
13002: @end table
13003:
13004:
13005: @c ---------------------------------------------------------------------
13006: @node block-ambcond, block-other, block-idef, The optional Block word set
13007: @subsection Ambiguous conditions
13008: @c ---------------------------------------------------------------------
13009: @cindex block words, ambiguous conditions
13010: @cindex ambiguous conditions, block words
13011:
13012: @table @i
13013: @item correct block read was not possible:
13014: @cindex block read not possible
13015: Typically results in a @code{throw} of some OS-derived value (between
13016: -512 and -2048). If the blocks file was just not long enough, blanks are
13017: supplied for the missing portion.
13018:
13019: @item I/O exception in block transfer:
13020: @cindex I/O exception in block transfer
13021: @cindex block transfer, I/O exception
13022: Typically results in a @code{throw} of some OS-derived value (between
13023: -512 and -2048).
13024:
13025: @item invalid block number:
13026: @cindex invalid block number
13027: @cindex block number invalid
13028: @code{-35 throw} (Invalid block number)
13029:
13030: @item a program directly alters the contents of @code{BLK}:
13031: @cindex @code{BLK}, altering @code{BLK}
13032: The input stream is switched to that other block, at the same
13033: position. If the storing to @code{BLK} happens when interpreting
13034: non-block input, the system will get quite confused when the block ends.
13035:
13036: @item no current block buffer for @code{UPDATE}:
13037: @cindex @code{UPDATE}, no current block buffer
13038: @code{UPDATE} has no effect.
13039:
13040: @end table
13041:
13042: @c ---------------------------------------------------------------------
13043: @node block-other, , block-ambcond, The optional Block word set
13044: @subsection Other system documentation
13045: @c ---------------------------------------------------------------------
13046: @cindex other system documentation, block words
13047: @cindex block words, other system documentation
13048:
13049: @table @i
13050: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13051: No restrictions (yet).
13052:
13053: @item the number of blocks available for source and data:
13054: depends on your disk space.
13055:
13056: @end table
13057:
13058:
13059: @c =====================================================================
13060: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13061: @section The optional Double Number word set
13062: @c =====================================================================
13063: @cindex system documentation, double words
13064: @cindex double words, system documentation
13065:
13066: @menu
13067: * double-ambcond:: Ambiguous Conditions
13068: @end menu
13069:
13070:
13071: @c ---------------------------------------------------------------------
13072: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13073: @subsection Ambiguous conditions
13074: @c ---------------------------------------------------------------------
13075: @cindex double words, ambiguous conditions
13076: @cindex ambiguous conditions, double words
13077:
13078: @table @i
1.29 crook 13079: @item @i{d} outside of range of @i{n} in @code{D>S}:
13080: @cindex @code{D>S}, @i{d} out of range of @i{n}
13081: The least significant cell of @i{d} is produced.
1.1 anton 13082:
13083: @end table
13084:
13085:
13086: @c =====================================================================
13087: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13088: @section The optional Exception word set
13089: @c =====================================================================
13090: @cindex system documentation, exception words
13091: @cindex exception words, system documentation
13092:
13093: @menu
13094: * exception-idef:: Implementation Defined Options
13095: @end menu
13096:
13097:
13098: @c ---------------------------------------------------------------------
13099: @node exception-idef, , The optional Exception word set, The optional Exception word set
13100: @subsection Implementation Defined Options
13101: @c ---------------------------------------------------------------------
13102: @cindex implementation-defined options, exception words
13103: @cindex exception words, implementation-defined options
13104:
13105: @table @i
13106: @item @code{THROW}-codes used in the system:
13107: @cindex @code{THROW}-codes used in the system
13108: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13109: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13110: codes -512@minus{}-2047 are used for OS errors (for file and memory
13111: allocation operations). The mapping from OS error numbers to throw codes
13112: is -512@minus{}@code{errno}. One side effect of this mapping is that
13113: undefined OS errors produce a message with a strange number; e.g.,
13114: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13115: @end table
13116:
13117: @c =====================================================================
13118: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13119: @section The optional Facility word set
13120: @c =====================================================================
13121: @cindex system documentation, facility words
13122: @cindex facility words, system documentation
13123:
13124: @menu
13125: * facility-idef:: Implementation Defined Options
13126: * facility-ambcond:: Ambiguous Conditions
13127: @end menu
13128:
13129:
13130: @c ---------------------------------------------------------------------
13131: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13132: @subsection Implementation Defined Options
13133: @c ---------------------------------------------------------------------
13134: @cindex implementation-defined options, facility words
13135: @cindex facility words, implementation-defined options
13136:
13137: @table @i
13138: @item encoding of keyboard events (@code{EKEY}):
13139: @cindex keyboard events, encoding in @code{EKEY}
13140: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13141: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13142: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13143: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13144: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13145: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13146:
1.1 anton 13147:
13148: @item duration of a system clock tick:
13149: @cindex duration of a system clock tick
13150: @cindex clock tick duration
13151: System dependent. With respect to @code{MS}, the time is specified in
13152: microseconds. How well the OS and the hardware implement this, is
13153: another question.
13154:
13155: @item repeatability to be expected from the execution of @code{MS}:
13156: @cindex repeatability to be expected from the execution of @code{MS}
13157: @cindex @code{MS}, repeatability to be expected
13158: System dependent. On Unix, a lot depends on load. If the system is
13159: lightly loaded, and the delay is short enough that Gforth does not get
13160: swapped out, the performance should be acceptable. Under MS-DOS and
13161: other single-tasking systems, it should be good.
13162:
13163: @end table
13164:
13165:
13166: @c ---------------------------------------------------------------------
13167: @node facility-ambcond, , facility-idef, The optional Facility word set
13168: @subsection Ambiguous conditions
13169: @c ---------------------------------------------------------------------
13170: @cindex facility words, ambiguous conditions
13171: @cindex ambiguous conditions, facility words
13172:
13173: @table @i
13174: @item @code{AT-XY} can't be performed on user output device:
13175: @cindex @code{AT-XY} can't be performed on user output device
13176: Largely terminal dependent. No range checks are done on the arguments.
13177: No errors are reported. You may see some garbage appearing, you may see
13178: simply nothing happen.
13179:
13180: @end table
13181:
13182:
13183: @c =====================================================================
13184: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13185: @section The optional File-Access word set
13186: @c =====================================================================
13187: @cindex system documentation, file words
13188: @cindex file words, system documentation
13189:
13190: @menu
13191: * file-idef:: Implementation Defined Options
13192: * file-ambcond:: Ambiguous Conditions
13193: @end menu
13194:
13195: @c ---------------------------------------------------------------------
13196: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13197: @subsection Implementation Defined Options
13198: @c ---------------------------------------------------------------------
13199: @cindex implementation-defined options, file words
13200: @cindex file words, implementation-defined options
13201:
13202: @table @i
13203: @item file access methods used:
13204: @cindex file access methods used
13205: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13206: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13207: @code{wb}): The file is cleared, if it exists, and created, if it does
13208: not (with both @code{open-file} and @code{create-file}). Under Unix
13209: @code{create-file} creates a file with 666 permissions modified by your
13210: umask.
13211:
13212: @item file exceptions:
13213: @cindex file exceptions
13214: The file words do not raise exceptions (except, perhaps, memory access
13215: faults when you pass illegal addresses or file-ids).
13216:
13217: @item file line terminator:
13218: @cindex file line terminator
13219: System-dependent. Gforth uses C's newline character as line
13220: terminator. What the actual character code(s) of this are is
13221: system-dependent.
13222:
13223: @item file name format:
13224: @cindex file name format
13225: System dependent. Gforth just uses the file name format of your OS.
13226:
13227: @item information returned by @code{FILE-STATUS}:
13228: @cindex @code{FILE-STATUS}, returned information
13229: @code{FILE-STATUS} returns the most powerful file access mode allowed
13230: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13231: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13232: along with the returned mode.
13233:
13234: @item input file state after an exception when including source:
13235: @cindex exception when including source
13236: All files that are left via the exception are closed.
13237:
1.29 crook 13238: @item @i{ior} values and meaning:
13239: @cindex @i{ior} values and meaning
1.68 anton 13240: @cindex @i{wior} values and meaning
1.29 crook 13241: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13242: intended as throw codes. They typically are in the range
13243: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13244: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13245:
13246: @item maximum depth of file input nesting:
13247: @cindex maximum depth of file input nesting
13248: @cindex file input nesting, maximum depth
13249: limited by the amount of return stack, locals/TIB stack, and the number
13250: of open files available. This should not give you troubles.
13251:
13252: @item maximum size of input line:
13253: @cindex maximum size of input line
13254: @cindex input line size, maximum
13255: @code{/line}. Currently 255.
13256:
13257: @item methods of mapping block ranges to files:
13258: @cindex mapping block ranges to files
13259: @cindex files containing blocks
13260: @cindex blocks in files
13261: By default, blocks are accessed in the file @file{blocks.fb} in the
13262: current working directory. The file can be switched with @code{USE}.
13263:
13264: @item number of string buffers provided by @code{S"}:
13265: @cindex @code{S"}, number of string buffers
13266: 1
13267:
13268: @item size of string buffer used by @code{S"}:
13269: @cindex @code{S"}, size of string buffer
13270: @code{/line}. currently 255.
13271:
13272: @end table
13273:
13274: @c ---------------------------------------------------------------------
13275: @node file-ambcond, , file-idef, The optional File-Access word set
13276: @subsection Ambiguous conditions
13277: @c ---------------------------------------------------------------------
13278: @cindex file words, ambiguous conditions
13279: @cindex ambiguous conditions, file words
13280:
13281: @table @i
13282: @item attempting to position a file outside its boundaries:
13283: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13284: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13285: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13286:
13287: @item attempting to read from file positions not yet written:
13288: @cindex reading from file positions not yet written
13289: End-of-file, i.e., zero characters are read and no error is reported.
13290:
1.29 crook 13291: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13292: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13293: An appropriate exception may be thrown, but a memory fault or other
13294: problem is more probable.
13295:
1.29 crook 13296: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13297: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13298: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13299: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13300: thrown.
13301:
13302: @item named file cannot be opened (@code{INCLUDED}):
13303: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13304: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13305:
13306: @item requesting an unmapped block number:
13307: @cindex unmapped block numbers
13308: There are no unmapped legal block numbers. On some operating systems,
13309: writing a block with a large number may overflow the file system and
13310: have an error message as consequence.
13311:
13312: @item using @code{source-id} when @code{blk} is non-zero:
13313: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13314: @code{source-id} performs its function. Typically it will give the id of
13315: the source which loaded the block. (Better ideas?)
13316:
13317: @end table
13318:
13319:
13320: @c =====================================================================
13321: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13322: @section The optional Floating-Point word set
13323: @c =====================================================================
13324: @cindex system documentation, floating-point words
13325: @cindex floating-point words, system documentation
13326:
13327: @menu
13328: * floating-idef:: Implementation Defined Options
13329: * floating-ambcond:: Ambiguous Conditions
13330: @end menu
13331:
13332:
13333: @c ---------------------------------------------------------------------
13334: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13335: @subsection Implementation Defined Options
13336: @c ---------------------------------------------------------------------
13337: @cindex implementation-defined options, floating-point words
13338: @cindex floating-point words, implementation-defined options
13339:
13340: @table @i
13341: @item format and range of floating point numbers:
13342: @cindex format and range of floating point numbers
13343: @cindex floating point numbers, format and range
13344: System-dependent; the @code{double} type of C.
13345:
1.29 crook 13346: @item results of @code{REPRESENT} when @i{float} is out of range:
13347: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13348: System dependent; @code{REPRESENT} is implemented using the C library
13349: function @code{ecvt()} and inherits its behaviour in this respect.
13350:
13351: @item rounding or truncation of floating-point numbers:
13352: @cindex rounding of floating-point numbers
13353: @cindex truncation of floating-point numbers
13354: @cindex floating-point numbers, rounding or truncation
13355: System dependent; the rounding behaviour is inherited from the hosting C
13356: compiler. IEEE-FP-based (i.e., most) systems by default round to
13357: nearest, and break ties by rounding to even (i.e., such that the last
13358: bit of the mantissa is 0).
13359:
13360: @item size of floating-point stack:
13361: @cindex floating-point stack size
13362: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13363: the floating-point stack (in floats). You can specify this on startup
13364: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13365:
13366: @item width of floating-point stack:
13367: @cindex floating-point stack width
13368: @code{1 floats}.
13369:
13370: @end table
13371:
13372:
13373: @c ---------------------------------------------------------------------
13374: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13375: @subsection Ambiguous conditions
13376: @c ---------------------------------------------------------------------
13377: @cindex floating-point words, ambiguous conditions
13378: @cindex ambiguous conditions, floating-point words
13379:
13380: @table @i
13381: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13382: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13383: System-dependent. Typically results in a @code{-23 THROW} like other
13384: alignment violations.
13385:
13386: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13387: @cindex @code{f@@} used with an address that is not float aligned
13388: @cindex @code{f!} used with an address that is not float aligned
13389: System-dependent. Typically results in a @code{-23 THROW} like other
13390: alignment violations.
13391:
13392: @item floating-point result out of range:
13393: @cindex floating-point result out of range
1.80 anton 13394: System-dependent. Can result in a @code{-43 throw} (floating point
13395: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13396: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13397: unidentified fault), or can produce a special value representing, e.g.,
13398: Infinity.
13399:
13400: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13401: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13402: System-dependent. Typically results in an alignment fault like other
13403: alignment violations.
13404:
1.35 anton 13405: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13406: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13407: The floating-point number is converted into decimal nonetheless.
13408:
13409: @item Both arguments are equal to zero (@code{FATAN2}):
13410: @cindex @code{FATAN2}, both arguments are equal to zero
13411: System-dependent. @code{FATAN2} is implemented using the C library
13412: function @code{atan2()}.
13413:
1.29 crook 13414: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13415: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13416: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13417: because of small errors and the tan will be a very large (or very small)
13418: but finite number.
13419:
1.29 crook 13420: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13421: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13422: The result is rounded to the nearest float.
13423:
13424: @item dividing by zero:
13425: @cindex dividing by zero, floating-point
13426: @cindex floating-point dividing by zero
13427: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13428: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13429: (floating point divide by zero) or @code{-55 throw} (Floating-point
13430: unidentified fault).
1.1 anton 13431:
13432: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13433: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13434: System dependent. On IEEE-FP based systems the number is converted into
13435: an infinity.
13436:
1.29 crook 13437: @item @i{float}<1 (@code{FACOSH}):
13438: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13439: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13440: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13441:
1.29 crook 13442: @item @i{float}=<-1 (@code{FLNP1}):
13443: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13444: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13445: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13446: negative infinity for @i{float}=-1).
1.1 anton 13447:
1.29 crook 13448: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13449: @cindex @code{FLN}, @i{float}=<0
13450: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13451: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13452: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13453: negative infinity for @i{float}=0).
1.1 anton 13454:
1.29 crook 13455: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13456: @cindex @code{FASINH}, @i{float}<0
13457: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13458: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13459: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13460: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13461: C library?).
1.1 anton 13462:
1.29 crook 13463: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13464: @cindex @code{FACOS}, |@i{float}|>1
13465: @cindex @code{FASIN}, |@i{float}|>1
13466: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13467: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13468: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13469:
1.29 crook 13470: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13471: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13472: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13473: Platform-dependent; typically, some double number is produced and no
13474: error is reported.
1.1 anton 13475:
13476: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13477: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13478: @code{Precision} characters of the numeric output area are used. If
13479: @code{precision} is too high, these words will smash the data or code
13480: close to @code{here}.
1.1 anton 13481: @end table
13482:
13483: @c =====================================================================
13484: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13485: @section The optional Locals word set
13486: @c =====================================================================
13487: @cindex system documentation, locals words
13488: @cindex locals words, system documentation
13489:
13490: @menu
13491: * locals-idef:: Implementation Defined Options
13492: * locals-ambcond:: Ambiguous Conditions
13493: @end menu
13494:
13495:
13496: @c ---------------------------------------------------------------------
13497: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13498: @subsection Implementation Defined Options
13499: @c ---------------------------------------------------------------------
13500: @cindex implementation-defined options, locals words
13501: @cindex locals words, implementation-defined options
13502:
13503: @table @i
13504: @item maximum number of locals in a definition:
13505: @cindex maximum number of locals in a definition
13506: @cindex locals, maximum number in a definition
13507: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13508: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13509: characters. The number of locals in a definition is bounded by the size
13510: of locals-buffer, which contains the names of the locals.
13511:
13512: @end table
13513:
13514:
13515: @c ---------------------------------------------------------------------
13516: @node locals-ambcond, , locals-idef, The optional Locals word set
13517: @subsection Ambiguous conditions
13518: @c ---------------------------------------------------------------------
13519: @cindex locals words, ambiguous conditions
13520: @cindex ambiguous conditions, locals words
13521:
13522: @table @i
13523: @item executing a named local in interpretation state:
13524: @cindex local in interpretation state
13525: @cindex Interpreting a compile-only word, for a local
13526: Locals have no interpretation semantics. If you try to perform the
13527: interpretation semantics, you will get a @code{-14 throw} somewhere
13528: (Interpreting a compile-only word). If you perform the compilation
13529: semantics, the locals access will be compiled (irrespective of state).
13530:
1.29 crook 13531: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13532: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13533: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13534: @cindex Invalid name argument, @code{TO}
13535: @code{-32 throw} (Invalid name argument)
13536:
13537: @end table
13538:
13539:
13540: @c =====================================================================
13541: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13542: @section The optional Memory-Allocation word set
13543: @c =====================================================================
13544: @cindex system documentation, memory-allocation words
13545: @cindex memory-allocation words, system documentation
13546:
13547: @menu
13548: * memory-idef:: Implementation Defined Options
13549: @end menu
13550:
13551:
13552: @c ---------------------------------------------------------------------
13553: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13554: @subsection Implementation Defined Options
13555: @c ---------------------------------------------------------------------
13556: @cindex implementation-defined options, memory-allocation words
13557: @cindex memory-allocation words, implementation-defined options
13558:
13559: @table @i
1.29 crook 13560: @item values and meaning of @i{ior}:
13561: @cindex @i{ior} values and meaning
13562: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13563: intended as throw codes. They typically are in the range
13564: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13565: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13566:
13567: @end table
13568:
13569: @c =====================================================================
13570: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13571: @section The optional Programming-Tools word set
13572: @c =====================================================================
13573: @cindex system documentation, programming-tools words
13574: @cindex programming-tools words, system documentation
13575:
13576: @menu
13577: * programming-idef:: Implementation Defined Options
13578: * programming-ambcond:: Ambiguous Conditions
13579: @end menu
13580:
13581:
13582: @c ---------------------------------------------------------------------
13583: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13584: @subsection Implementation Defined Options
13585: @c ---------------------------------------------------------------------
13586: @cindex implementation-defined options, programming-tools words
13587: @cindex programming-tools words, implementation-defined options
13588:
13589: @table @i
13590: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13591: @cindex @code{;CODE} ending sequence
13592: @cindex @code{CODE} ending sequence
13593: @code{END-CODE}
13594:
13595: @item manner of processing input following @code{;CODE} and @code{CODE}:
13596: @cindex @code{;CODE}, processing input
13597: @cindex @code{CODE}, processing input
13598: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13599: the input is processed by the text interpreter, (starting) in interpret
13600: state.
13601:
13602: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13603: @cindex @code{ASSEMBLER}, search order capability
13604: The ANS Forth search order word set.
13605:
13606: @item source and format of display by @code{SEE}:
13607: @cindex @code{SEE}, source and format of output
1.80 anton 13608: The source for @code{see} is the executable code used by the inner
1.1 anton 13609: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13610: (and on some platforms, assembly code for primitives) as well as
13611: possible.
1.1 anton 13612:
13613: @end table
13614:
13615: @c ---------------------------------------------------------------------
13616: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13617: @subsection Ambiguous conditions
13618: @c ---------------------------------------------------------------------
13619: @cindex programming-tools words, ambiguous conditions
13620: @cindex ambiguous conditions, programming-tools words
13621:
13622: @table @i
13623:
1.21 crook 13624: @item deleting the compilation word list (@code{FORGET}):
13625: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13626: Not implemented (yet).
13627:
1.29 crook 13628: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13629: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13630: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13631: @cindex control-flow stack underflow
13632: This typically results in an @code{abort"} with a descriptive error
13633: message (may change into a @code{-22 throw} (Control structure mismatch)
13634: in the future). You may also get a memory access error. If you are
13635: unlucky, this ambiguous condition is not caught.
13636:
1.29 crook 13637: @item @i{name} can't be found (@code{FORGET}):
13638: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13639: Not implemented (yet).
13640:
1.29 crook 13641: @item @i{name} not defined via @code{CREATE}:
13642: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13643: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13644: the execution semantics of the last defined word no matter how it was
13645: defined.
13646:
13647: @item @code{POSTPONE} applied to @code{[IF]}:
13648: @cindex @code{POSTPONE} applied to @code{[IF]}
13649: @cindex @code{[IF]} and @code{POSTPONE}
13650: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13651: equivalent to @code{[IF]}.
13652:
13653: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13654: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13655: Continue in the same state of conditional compilation in the next outer
13656: input source. Currently there is no warning to the user about this.
13657:
13658: @item removing a needed definition (@code{FORGET}):
13659: @cindex @code{FORGET}, removing a needed definition
13660: Not implemented (yet).
13661:
13662: @end table
13663:
13664:
13665: @c =====================================================================
13666: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13667: @section The optional Search-Order word set
13668: @c =====================================================================
13669: @cindex system documentation, search-order words
13670: @cindex search-order words, system documentation
13671:
13672: @menu
13673: * search-idef:: Implementation Defined Options
13674: * search-ambcond:: Ambiguous Conditions
13675: @end menu
13676:
13677:
13678: @c ---------------------------------------------------------------------
13679: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13680: @subsection Implementation Defined Options
13681: @c ---------------------------------------------------------------------
13682: @cindex implementation-defined options, search-order words
13683: @cindex search-order words, implementation-defined options
13684:
13685: @table @i
13686: @item maximum number of word lists in search order:
13687: @cindex maximum number of word lists in search order
13688: @cindex search order, maximum depth
13689: @code{s" wordlists" environment? drop .}. Currently 16.
13690:
13691: @item minimum search order:
13692: @cindex minimum search order
13693: @cindex search order, minimum
13694: @code{root root}.
13695:
13696: @end table
13697:
13698: @c ---------------------------------------------------------------------
13699: @node search-ambcond, , search-idef, The optional Search-Order word set
13700: @subsection Ambiguous conditions
13701: @c ---------------------------------------------------------------------
13702: @cindex search-order words, ambiguous conditions
13703: @cindex ambiguous conditions, search-order words
13704:
13705: @table @i
1.21 crook 13706: @item changing the compilation word list (during compilation):
13707: @cindex changing the compilation word list (during compilation)
13708: @cindex compilation word list, change before definition ends
13709: The word is entered into the word list that was the compilation word list
1.1 anton 13710: at the start of the definition. Any changes to the name field (e.g.,
13711: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13712: are applied to the latest defined word (as reported by @code{latest} or
13713: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13714:
13715: @item search order empty (@code{previous}):
13716: @cindex @code{previous}, search order empty
1.26 crook 13717: @cindex vocstack empty, @code{previous}
1.1 anton 13718: @code{abort" Vocstack empty"}.
13719:
13720: @item too many word lists in search order (@code{also}):
13721: @cindex @code{also}, too many word lists in search order
1.26 crook 13722: @cindex vocstack full, @code{also}
1.1 anton 13723: @code{abort" Vocstack full"}.
13724:
13725: @end table
13726:
13727: @c ***************************************************************
1.65 anton 13728: @node Standard vs Extensions, Model, ANS conformance, Top
13729: @chapter Should I use Gforth extensions?
13730: @cindex Gforth extensions
13731:
13732: As you read through the rest of this manual, you will see documentation
13733: for @i{Standard} words, and documentation for some appealing Gforth
13734: @i{extensions}. You might ask yourself the question: @i{``Should I
13735: restrict myself to the standard, or should I use the extensions?''}
13736:
13737: The answer depends on the goals you have for the program you are working
13738: on:
13739:
13740: @itemize @bullet
13741:
13742: @item Is it just for yourself or do you want to share it with others?
13743:
13744: @item
13745: If you want to share it, do the others all use Gforth?
13746:
13747: @item
13748: If it is just for yourself, do you want to restrict yourself to Gforth?
13749:
13750: @end itemize
13751:
13752: If restricting the program to Gforth is ok, then there is no reason not
13753: to use extensions. It is still a good idea to keep to the standard
13754: where it is easy, in case you want to reuse these parts in another
13755: program that you want to be portable.
13756:
13757: If you want to be able to port the program to other Forth systems, there
13758: are the following points to consider:
13759:
13760: @itemize @bullet
13761:
13762: @item
13763: Most Forth systems that are being maintained support the ANS Forth
13764: standard. So if your program complies with the standard, it will be
13765: portable among many systems.
13766:
13767: @item
13768: A number of the Gforth extensions can be implemented in ANS Forth using
13769: public-domain files provided in the @file{compat/} directory. These are
13770: mentioned in the text in passing. There is no reason not to use these
13771: extensions, your program will still be ANS Forth compliant; just include
13772: the appropriate compat files with your program.
13773:
13774: @item
13775: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13776: analyse your program and determine what non-Standard words it relies
13777: upon. However, it does not check whether you use standard words in a
13778: non-standard way.
13779:
13780: @item
13781: Some techniques are not standardized by ANS Forth, and are hard or
13782: impossible to implement in a standard way, but can be implemented in
13783: most Forth systems easily, and usually in similar ways (e.g., accessing
13784: word headers). Forth has a rich historical precedent for programmers
13785: taking advantage of implementation-dependent features of their tools
13786: (for example, relying on a knowledge of the dictionary
13787: structure). Sometimes these techniques are necessary to extract every
13788: last bit of performance from the hardware, sometimes they are just a
13789: programming shorthand.
13790:
13791: @item
13792: Does using a Gforth extension save more work than the porting this part
13793: to other Forth systems (if any) will cost?
13794:
13795: @item
13796: Is the additional functionality worth the reduction in portability and
13797: the additional porting problems?
13798:
13799: @end itemize
13800:
13801: In order to perform these consideratios, you need to know what's
13802: standard and what's not. This manual generally states if something is
1.81 anton 13803: non-standard, but the authoritative source is the
13804: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13805: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13806: into the thought processes of the technical committee.
13807:
13808: Note also that portability between Forth systems is not the only
13809: portability issue; there is also the issue of portability between
13810: different platforms (processor/OS combinations).
13811:
13812: @c ***************************************************************
13813: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13814: @chapter Model
13815:
13816: This chapter has yet to be written. It will contain information, on
13817: which internal structures you can rely.
13818:
13819: @c ***************************************************************
13820: @node Integrating Gforth, Emacs and Gforth, Model, Top
13821: @chapter Integrating Gforth into C programs
13822:
13823: This is not yet implemented.
13824:
13825: Several people like to use Forth as scripting language for applications
13826: that are otherwise written in C, C++, or some other language.
13827:
13828: The Forth system ATLAST provides facilities for embedding it into
13829: applications; unfortunately it has several disadvantages: most
13830: importantly, it is not based on ANS Forth, and it is apparently dead
13831: (i.e., not developed further and not supported). The facilities
1.21 crook 13832: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13833: making the switch should not be hard.
13834:
13835: We also tried to design the interface such that it can easily be
13836: implemented by other Forth systems, so that we may one day arrive at a
13837: standardized interface. Such a standard interface would allow you to
13838: replace the Forth system without having to rewrite C code.
13839:
13840: You embed the Gforth interpreter by linking with the library
13841: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13842: global symbols in this library that belong to the interface, have the
13843: prefix @code{forth_}. (Global symbols that are used internally have the
13844: prefix @code{gforth_}).
13845:
13846: You can include the declarations of Forth types and the functions and
13847: variables of the interface with @code{#include <forth.h>}.
13848:
13849: Types.
13850:
13851: Variables.
13852:
13853: Data and FP Stack pointer. Area sizes.
13854:
13855: functions.
13856:
13857: forth_init(imagefile)
13858: forth_evaluate(string) exceptions?
13859: forth_goto(address) (or forth_execute(xt)?)
13860: forth_continue() (a corountining mechanism)
13861:
13862: Adding primitives.
13863:
13864: No checking.
13865:
13866: Signals?
13867:
13868: Accessing the Stacks
13869:
1.26 crook 13870: @c ******************************************************************
1.1 anton 13871: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13872: @chapter Emacs and Gforth
13873: @cindex Emacs and Gforth
13874:
13875: @cindex @file{gforth.el}
13876: @cindex @file{forth.el}
13877: @cindex Rydqvist, Goran
1.107 dvdkhlng 13878: @cindex Kuehling, David
1.1 anton 13879: @cindex comment editing commands
13880: @cindex @code{\}, editing with Emacs
13881: @cindex debug tracer editing commands
13882: @cindex @code{~~}, removal with Emacs
13883: @cindex Forth mode in Emacs
1.107 dvdkhlng 13884:
1.1 anton 13885: Gforth comes with @file{gforth.el}, an improved version of
13886: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13887: improvements are:
13888:
13889: @itemize @bullet
13890: @item
1.107 dvdkhlng 13891: A better handling of indentation.
13892: @item
13893: A custom hilighting engine for Forth-code.
1.26 crook 13894: @item
13895: Comment paragraph filling (@kbd{M-q})
13896: @item
13897: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13898: @item
13899: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13900: @item
13901: Support of the @code{info-lookup} feature for looking up the
13902: documentation of a word.
1.107 dvdkhlng 13903: @item
13904: Support for reading and writing blocks files.
1.26 crook 13905: @end itemize
13906:
1.107 dvdkhlng 13907: To get a basic description of these features, enter Forth mode and
13908: type @kbd{C-h m}.
1.1 anton 13909:
13910: @cindex source location of error or debugging output in Emacs
13911: @cindex error output, finding the source location in Emacs
13912: @cindex debugging output, finding the source location in Emacs
13913: In addition, Gforth supports Emacs quite well: The source code locations
13914: given in error messages, debugging output (from @code{~~}) and failed
13915: assertion messages are in the right format for Emacs' compilation mode
13916: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13917: Manual}) so the source location corresponding to an error or other
13918: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13919: @kbd{C-c C-c} for the error under the cursor).
13920:
1.107 dvdkhlng 13921: @cindex viewing the documentation of a word in Emacs
13922: @cindex context-sensitive help
13923: Moreover, for words documented in this manual, you can look up the
13924: glossary entry quickly by using @kbd{C-h TAB}
13925: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13926: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13927: later and does not work for words containing @code{:}.
13928:
13929: @menu
13930: * Installing gforth.el:: Making Emacs aware of Forth.
13931: * Emacs Tags:: Viewing the source of a word in Emacs.
13932: * Hilighting:: Making Forth code look prettier.
13933: * Auto-Indentation:: Customizing auto-indentation.
13934: * Blocks Files:: Reading and writing blocks files.
13935: @end menu
13936:
13937: @c ----------------------------------
1.109 anton 13938: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13939: @section Installing gforth.el
13940: @cindex @file{.emacs}
13941: @cindex @file{gforth.el}, installation
13942: To make the features from @file{gforth.el} available in Emacs, add
13943: the following lines to your @file{.emacs} file:
13944:
13945: @example
13946: (autoload 'forth-mode "gforth.el")
13947: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13948: auto-mode-alist))
13949: (autoload 'forth-block-mode "gforth.el")
13950: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13951: auto-mode-alist))
13952: (add-hook 'forth-mode-hook (function (lambda ()
13953: ;; customize variables here:
13954: (setq forth-indent-level 4)
13955: (setq forth-minor-indent-level 2)
13956: (setq forth-hilight-level 3)
13957: ;;; ...
13958: )))
13959: @end example
13960:
13961: @c ----------------------------------
13962: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13963: @section Emacs Tags
1.1 anton 13964: @cindex @file{TAGS} file
13965: @cindex @file{etags.fs}
13966: @cindex viewing the source of a word in Emacs
1.43 anton 13967: @cindex @code{require}, placement in files
13968: @cindex @code{include}, placement in files
1.107 dvdkhlng 13969: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13970: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13971: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13972: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13973: several tags files at the same time (e.g., one for the Gforth sources
13974: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13975: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13976: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13977: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13978: with @file{etags.fs}, you should avoid putting definitions both before
13979: and after @code{require} etc., otherwise you will see the same file
13980: visited several times by commands like @code{tags-search}.
1.1 anton 13981:
1.107 dvdkhlng 13982: @c ----------------------------------
13983: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13984: @section Hilighting
13985: @cindex hilighting Forth code in Emacs
13986: @cindex highlighting Forth code in Emacs
13987: @file{gforth.el} comes with a custom source hilighting engine. When
13988: you open a file in @code{forth-mode}, it will be completely parsed,
13989: assigning faces to keywords, comments, strings etc. While you edit
13990: the file, modified regions get parsed and updated on-the-fly.
13991:
13992: Use the variable `forth-hilight-level' to change the level of
13993: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13994: you set the hilighting level to 0, the parser will still work in the
13995: background, collecting information about whether regions of text are
13996: ``compiled'' or ``interpreted''. Those information are required for
13997: auto-indentation to work properly. Set `forth-disable-parser' to
13998: non-nil if your computer is too slow to handle parsing. This will
13999: have an impact on the smartness of the auto-indentation engine,
14000: though.
14001:
14002: Sometimes Forth sources define new features that should be hilighted,
14003: new control structures, defining-words etc. You can use the variable
14004: `forth-custom-words' to make @code{forth-mode} hilight additional
14005: words and constructs. See the docstring of `forth-words' for details
14006: (in Emacs, type @kbd{C-h v forth-words}).
14007:
14008: `forth-custom-words' is meant to be customized in your
14009: @file{.emacs} file. To customize hilighing in a file-specific manner,
14010: set `forth-local-words' in a local-variables section at the end of
14011: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14012:
14013: Example:
14014: @example
14015: 0 [IF]
14016: Local Variables:
14017: forth-local-words:
14018: ((("t:") definition-starter (font-lock-keyword-face . 1)
14019: "[ \t\n]" t name (font-lock-function-name-face . 3))
14020: ((";t") definition-ender (font-lock-keyword-face . 1)))
14021: End:
14022: [THEN]
14023: @end example
14024:
14025: @c ----------------------------------
14026: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14027: @section Auto-Indentation
14028: @cindex auto-indentation of Forth code in Emacs
14029: @cindex indentation of Forth code in Emacs
14030: @code{forth-mode} automatically tries to indent lines in a smart way,
14031: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14032:
14033: Simple customization can be achieved by setting
14034: `forth-indent-level' and `forth-minor-indent-level' in your
14035: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14036: per default by multiples of 4 columns. To use the more traditional
14037: 3-column indentation, add the following lines to your @file{.emacs}:
14038:
14039: @example
14040: (add-hook 'forth-mode-hook (function (lambda ()
14041: ;; customize variables here:
14042: (setq forth-indent-level 3)
14043: (setq forth-minor-indent-level 1)
14044: )))
14045: @end example
14046:
14047: If you want indentation to recognize non-default words, customize it
14048: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14049: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14050: v forth-indent-words}).
14051:
14052: To customize indentation in a file-specific manner, set
14053: `forth-local-indent-words' in a local-variables section at the end of
14054: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14055: Emacs Manual}).
14056:
14057: Example:
14058: @example
14059: 0 [IF]
14060: Local Variables:
14061: forth-local-indent-words:
14062: ((("t:") (0 . 2) (0 . 2))
14063: ((";t") (-2 . 0) (0 . -2)))
14064: End:
14065: [THEN]
14066: @end example
14067:
14068: @c ----------------------------------
1.109 anton 14069: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14070: @section Blocks Files
14071: @cindex blocks files, use with Emacs
14072: @code{forth-mode} Autodetects blocks files by checking whether the
14073: length of the first line exceeds 1023 characters. It then tries to
14074: convert the file into normal text format. When you save the file, it
14075: will be written to disk as normal stream-source file.
14076:
14077: If you want to write blocks files, use @code{forth-blocks-mode}. It
14078: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14079:
1.107 dvdkhlng 14080: @itemize @bullet
14081: @item
14082: Files are written to disk in blocks file format.
14083: @item
14084: Screen numbers are displayed in the mode line (enumerated beginning
14085: with the value of `forth-block-base')
14086: @item
14087: Warnings are displayed when lines exceed 64 characters.
14088: @item
14089: The beginning of the currently edited block is marked with an
14090: overlay-arrow.
14091: @end itemize
1.41 anton 14092:
1.107 dvdkhlng 14093: There are some restrictions you should be aware of. When you open a
14094: blocks file that contains tabulator or newline characters, these
14095: characters will be translated into spaces when the file is written
14096: back to disk. If tabs or newlines are encountered during blocks file
14097: reading, an error is output to the echo area. So have a look at the
14098: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14099:
1.107 dvdkhlng 14100: Please consult the docstring of @code{forth-blocks-mode} for more
14101: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14102:
1.26 crook 14103: @c ******************************************************************
1.1 anton 14104: @node Image Files, Engine, Emacs and Gforth, Top
14105: @chapter Image Files
1.26 crook 14106: @cindex image file
14107: @cindex @file{.fi} files
1.1 anton 14108: @cindex precompiled Forth code
14109: @cindex dictionary in persistent form
14110: @cindex persistent form of dictionary
14111:
14112: An image file is a file containing an image of the Forth dictionary,
14113: i.e., compiled Forth code and data residing in the dictionary. By
14114: convention, we use the extension @code{.fi} for image files.
14115:
14116: @menu
1.18 anton 14117: * Image Licensing Issues:: Distribution terms for images.
14118: * Image File Background:: Why have image files?
1.67 anton 14119: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14120: * Data-Relocatable Image Files:: are better.
1.67 anton 14121: * Fully Relocatable Image Files:: better yet.
1.18 anton 14122: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14123: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14124: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14125: @end menu
14126:
1.18 anton 14127: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14128: @section Image Licensing Issues
14129: @cindex license for images
14130: @cindex image license
14131:
14132: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14133: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14134: original image; i.e., according to copyright law it is a derived work of
14135: the original image.
14136:
14137: Since Gforth is distributed under the GNU GPL, the newly created image
14138: falls under the GNU GPL, too. In particular, this means that if you
14139: distribute the image, you have to make all of the sources for the image
1.113 anton 14140: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14141: GNU General Public License (Section 3)}.
14142:
14143: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14144: contains only code compiled from the sources you gave it; if none of
14145: these sources is under the GPL, the terms discussed above do not apply
14146: to the image. However, if your image needs an engine (a gforth binary)
14147: that is under the GPL, you should make sure that you distribute both in
14148: a way that is at most a @emph{mere aggregation}, if you don't want the
14149: terms of the GPL to apply to the image.
14150:
14151: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14152: @section Image File Background
14153: @cindex image file background
14154:
1.80 anton 14155: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14156: definitions written in Forth. Since the Forth compiler itself belongs to
14157: those definitions, it is not possible to start the system with the
1.80 anton 14158: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14159: code as an image file in nearly executable form. When Gforth starts up,
14160: a C routine loads the image file into memory, optionally relocates the
14161: addresses, then sets up the memory (stacks etc.) according to
14162: information in the image file, and (finally) starts executing Forth
14163: code.
1.1 anton 14164:
14165: The image file variants represent different compromises between the
14166: goals of making it easy to generate image files and making them
14167: portable.
14168:
14169: @cindex relocation at run-time
1.26 crook 14170: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14171: run-time. This avoids many of the complications discussed below (image
14172: files are data relocatable without further ado), but costs performance
14173: (one addition per memory access).
14174:
14175: @cindex relocation at load-time
1.26 crook 14176: By contrast, the Gforth loader performs relocation at image load time. The
14177: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14178: appropriate code-field addresses (or code addresses in the case of
14179: direct threading).
14180:
14181: There are three kinds of image files, with different degrees of
14182: relocatability: non-relocatable, data-relocatable, and fully relocatable
14183: image files.
14184:
14185: @cindex image file loader
14186: @cindex relocating loader
14187: @cindex loader for image files
14188: These image file variants have several restrictions in common; they are
14189: caused by the design of the image file loader:
14190:
14191: @itemize @bullet
14192: @item
14193: There is only one segment; in particular, this means, that an image file
14194: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14195: them). The contents of the stacks are not represented, either.
1.1 anton 14196:
14197: @item
14198: The only kinds of relocation supported are: adding the same offset to
14199: all cells that represent data addresses; and replacing special tokens
14200: with code addresses or with pieces of machine code.
14201:
14202: If any complex computations involving addresses are performed, the
14203: results cannot be represented in the image file. Several applications that
14204: use such computations come to mind:
14205: @itemize @minus
14206: @item
14207: Hashing addresses (or data structures which contain addresses) for table
14208: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14209: purpose, you will have no problem, because the hash tables are
14210: recomputed automatically when the system is started. If you use your own
14211: hash tables, you will have to do something similar.
14212:
14213: @item
14214: There's a cute implementation of doubly-linked lists that uses
14215: @code{XOR}ed addresses. You could represent such lists as singly-linked
14216: in the image file, and restore the doubly-linked representation on
14217: startup.@footnote{In my opinion, though, you should think thrice before
14218: using a doubly-linked list (whatever implementation).}
14219:
14220: @item
14221: The code addresses of run-time routines like @code{docol:} cannot be
14222: represented in the image file (because their tokens would be replaced by
14223: machine code in direct threaded implementations). As a workaround,
14224: compute these addresses at run-time with @code{>code-address} from the
14225: executions tokens of appropriate words (see the definitions of
1.80 anton 14226: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14227:
14228: @item
14229: On many architectures addresses are represented in machine code in some
14230: shifted or mangled form. You cannot put @code{CODE} words that contain
14231: absolute addresses in this form in a relocatable image file. Workarounds
14232: are representing the address in some relative form (e.g., relative to
14233: the CFA, which is present in some register), or loading the address from
14234: a place where it is stored in a non-mangled form.
14235: @end itemize
14236: @end itemize
14237:
14238: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14239: @section Non-Relocatable Image Files
14240: @cindex non-relocatable image files
1.26 crook 14241: @cindex image file, non-relocatable
1.1 anton 14242:
14243: These files are simple memory dumps of the dictionary. They are specific
14244: to the executable (i.e., @file{gforth} file) they were created
14245: with. What's worse, they are specific to the place on which the
14246: dictionary resided when the image was created. Now, there is no
14247: guarantee that the dictionary will reside at the same place the next
14248: time you start Gforth, so there's no guarantee that a non-relocatable
14249: image will work the next time (Gforth will complain instead of crashing,
14250: though).
14251:
14252: You can create a non-relocatable image file with
14253:
1.44 crook 14254:
1.1 anton 14255: doc-savesystem
14256:
1.44 crook 14257:
1.1 anton 14258: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14259: @section Data-Relocatable Image Files
14260: @cindex data-relocatable image files
1.26 crook 14261: @cindex image file, data-relocatable
1.1 anton 14262:
14263: These files contain relocatable data addresses, but fixed code addresses
14264: (instead of tokens). They are specific to the executable (i.e.,
14265: @file{gforth} file) they were created with. For direct threading on some
14266: architectures (e.g., the i386), data-relocatable images do not work. You
14267: get a data-relocatable image, if you use @file{gforthmi} with a
14268: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14269: Relocatable Image Files}).
14270:
14271: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14272: @section Fully Relocatable Image Files
14273: @cindex fully relocatable image files
1.26 crook 14274: @cindex image file, fully relocatable
1.1 anton 14275:
14276: @cindex @file{kern*.fi}, relocatability
14277: @cindex @file{gforth.fi}, relocatability
14278: These image files have relocatable data addresses, and tokens for code
14279: addresses. They can be used with different binaries (e.g., with and
14280: without debugging) on the same machine, and even across machines with
14281: the same data formats (byte order, cell size, floating point
14282: format). However, they are usually specific to the version of Gforth
14283: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14284: are fully relocatable.
14285:
14286: There are two ways to create a fully relocatable image file:
14287:
14288: @menu
1.29 crook 14289: * gforthmi:: The normal way
1.1 anton 14290: * cross.fs:: The hard way
14291: @end menu
14292:
14293: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14294: @subsection @file{gforthmi}
14295: @cindex @file{comp-i.fs}
14296: @cindex @file{gforthmi}
14297:
14298: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14299: image @i{file} that contains everything you would load by invoking
14300: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14301: @example
1.29 crook 14302: gforthmi @i{file} @i{options}
1.1 anton 14303: @end example
14304:
14305: E.g., if you want to create an image @file{asm.fi} that has the file
14306: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14307: like this:
14308:
14309: @example
14310: gforthmi asm.fi asm.fs
14311: @end example
14312:
1.27 crook 14313: @file{gforthmi} is implemented as a sh script and works like this: It
14314: produces two non-relocatable images for different addresses and then
14315: compares them. Its output reflects this: first you see the output (if
1.62 crook 14316: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14317: files, then you see the output of the comparing program: It displays the
14318: offset used for data addresses and the offset used for code addresses;
1.1 anton 14319: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14320: image files, it displays a line like this:
1.1 anton 14321:
14322: @example
14323: 78DC BFFFFA50 BFFFFA40
14324: @end example
14325:
14326: This means that at offset $78dc from @code{forthstart}, one input image
14327: contains $bffffa50, and the other contains $bffffa40. Since these cells
14328: cannot be represented correctly in the output image, you should examine
14329: these places in the dictionary and verify that these cells are dead
14330: (i.e., not read before they are written).
1.39 anton 14331:
14332: @cindex --application, @code{gforthmi} option
14333: If you insert the option @code{--application} in front of the image file
14334: name, you will get an image that uses the @code{--appl-image} option
14335: instead of the @code{--image-file} option (@pxref{Invoking
14336: Gforth}). When you execute such an image on Unix (by typing the image
14337: name as command), the Gforth engine will pass all options to the image
14338: instead of trying to interpret them as engine options.
1.1 anton 14339:
1.27 crook 14340: If you type @file{gforthmi} with no arguments, it prints some usage
14341: instructions.
14342:
1.1 anton 14343: @cindex @code{savesystem} during @file{gforthmi}
14344: @cindex @code{bye} during @file{gforthmi}
14345: @cindex doubly indirect threaded code
1.44 crook 14346: @cindex environment variables
14347: @cindex @code{GFORTHD} -- environment variable
14348: @cindex @code{GFORTH} -- environment variable
1.1 anton 14349: @cindex @code{gforth-ditc}
1.29 crook 14350: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14351: words @code{savesystem} and @code{bye} must be visible. A special doubly
14352: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14353: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14354: this executable through the environment variable @code{GFORTHD}
14355: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14356: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14357: data-relocatable image (because there is no code address offset). The
14358: normal @file{gforth} executable is used for creating the relocatable
14359: image; you can pass the exact filename of this executable through the
14360: environment variable @code{GFORTH}.
1.1 anton 14361:
14362: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14363: @subsection @file{cross.fs}
14364: @cindex @file{cross.fs}
14365: @cindex cross-compiler
14366: @cindex metacompiler
1.47 crook 14367: @cindex target compiler
1.1 anton 14368:
14369: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14370: programming language (@pxref{Cross Compiler}).
1.1 anton 14371:
1.47 crook 14372: @code{cross} allows you to create image files for machines with
1.1 anton 14373: different data sizes and data formats than the one used for generating
14374: the image file. You can also use it to create an application image that
14375: does not contain a Forth compiler. These features are bought with
14376: restrictions and inconveniences in programming. E.g., addresses have to
14377: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14378: order to make the code relocatable.
14379:
14380:
14381: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14382: @section Stack and Dictionary Sizes
14383: @cindex image file, stack and dictionary sizes
14384: @cindex dictionary size default
14385: @cindex stack size default
14386:
14387: If you invoke Gforth with a command line flag for the size
14388: (@pxref{Invoking Gforth}), the size you specify is stored in the
14389: dictionary. If you save the dictionary with @code{savesystem} or create
14390: an image with @file{gforthmi}, this size will become the default
14391: for the resulting image file. E.g., the following will create a
1.21 crook 14392: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14393:
14394: @example
14395: gforthmi gforth.fi -m 1M
14396: @end example
14397:
14398: In other words, if you want to set the default size for the dictionary
14399: and the stacks of an image, just invoke @file{gforthmi} with the
14400: appropriate options when creating the image.
14401:
14402: @cindex stack size, cache-friendly
14403: Note: For cache-friendly behaviour (i.e., good performance), you should
14404: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14405: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14406: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14407:
14408: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14409: @section Running Image Files
14410: @cindex running image files
14411: @cindex invoking image files
14412: @cindex image file invocation
14413:
14414: @cindex -i, invoke image file
14415: @cindex --image file, invoke image file
1.29 crook 14416: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14417: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14418: @example
1.29 crook 14419: gforth -i @i{image}
1.1 anton 14420: @end example
14421:
14422: @cindex executable image file
1.26 crook 14423: @cindex image file, executable
1.1 anton 14424: If your operating system supports starting scripts with a line of the
14425: form @code{#! ...}, you just have to type the image file name to start
14426: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14427: just a convention). I.e., to run Gforth with the image file @i{image},
14428: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14429: This works because every @code{.fi} file starts with a line of this
14430: format:
14431:
14432: @example
14433: #! /usr/local/bin/gforth-0.4.0 -i
14434: @end example
14435:
14436: The file and pathname for the Gforth engine specified on this line is
14437: the specific Gforth executable that it was built against; i.e. the value
14438: of the environment variable @code{GFORTH} at the time that
14439: @file{gforthmi} was executed.
1.1 anton 14440:
1.27 crook 14441: You can make use of the same shell capability to make a Forth source
14442: file into an executable. For example, if you place this text in a file:
1.26 crook 14443:
14444: @example
14445: #! /usr/local/bin/gforth
14446:
14447: ." Hello, world" CR
14448: bye
14449: @end example
14450:
14451: @noindent
1.27 crook 14452: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14453: directly from the command line. The sequence @code{#!} is used in two
14454: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14455: system@footnote{The Unix kernel actually recognises two types of files:
14456: executable files and files of data, where the data is processed by an
14457: interpreter that is specified on the ``interpreter line'' -- the first
14458: line of the file, starting with the sequence #!. There may be a small
14459: limit (e.g., 32) on the number of characters that may be specified on
14460: the interpreter line.} secondly it is treated as a comment character by
14461: Gforth. Because of the second usage, a space is required between
1.80 anton 14462: @code{#!} and the path to the executable (moreover, some Unixes
14463: require the sequence @code{#! /}).
1.27 crook 14464:
14465: The disadvantage of this latter technique, compared with using
1.80 anton 14466: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14467: compiled on-the-fly, each time the program is invoked.
1.26 crook 14468:
1.1 anton 14469: doc-#!
14470:
1.44 crook 14471:
1.1 anton 14472: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14473: @section Modifying the Startup Sequence
14474: @cindex startup sequence for image file
14475: @cindex image file initialization sequence
14476: @cindex initialization sequence of image file
14477:
1.120 anton 14478: You can add your own initialization to the startup sequence of an image
14479: through the deferred word @code{'cold}. @code{'cold} is invoked just
14480: before the image-specific command line processing (i.e., loading files
14481: and evaluating (@code{-e}) strings) starts.
1.1 anton 14482:
14483: A sequence for adding your initialization usually looks like this:
14484:
14485: @example
14486: :noname
14487: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14488: ... \ your stuff
14489: ; IS 'cold
14490: @end example
14491:
14492: @cindex turnkey image files
1.26 crook 14493: @cindex image file, turnkey applications
1.1 anton 14494: You can make a turnkey image by letting @code{'cold} execute a word
14495: (your turnkey application) that never returns; instead, it exits Gforth
14496: via @code{bye} or @code{throw}.
14497:
1.121 anton 14498: You can access the (image-specific) command-line arguments through
14499: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14500: arguments}).
1.1 anton 14501:
1.26 crook 14502: If @code{'cold} exits normally, Gforth processes the command-line
14503: arguments as files to be loaded and strings to be evaluated. Therefore,
14504: @code{'cold} should remove the arguments it has used in this case.
14505:
14506: doc-'cold
1.44 crook 14507:
1.1 anton 14508: @c ******************************************************************
1.113 anton 14509: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14510: @chapter Engine
14511: @cindex engine
14512: @cindex virtual machine
14513:
1.26 crook 14514: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14515: may be helpful for finding your way in the Gforth sources.
14516:
1.109 anton 14517: The ideas in this section have also been published in the following
14518: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14519: Forth-Tagung '93; M. Anton Ertl,
14520: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14521: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14522: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14523: Threaded code variations and optimizations (extended version)}},
14524: Forth-Tagung '02.
1.1 anton 14525:
14526: @menu
14527: * Portability::
14528: * Threading::
14529: * Primitives::
14530: * Performance::
14531: @end menu
14532:
14533: @node Portability, Threading, Engine, Engine
14534: @section Portability
14535: @cindex engine portability
14536:
1.26 crook 14537: An important goal of the Gforth Project is availability across a wide
14538: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14539: achieved this goal by manually coding the engine in assembly language
14540: for several then-popular processors. This approach is very
14541: labor-intensive and the results are short-lived due to progress in
14542: computer architecture.
1.1 anton 14543:
14544: @cindex C, using C for the engine
14545: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14546: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14547: particularly popular for UNIX-based Forths due to the large variety of
14548: architectures of UNIX machines. Unfortunately an implementation in C
14549: does not mix well with the goals of efficiency and with using
14550: traditional techniques: Indirect or direct threading cannot be expressed
14551: in C, and switch threading, the fastest technique available in C, is
14552: significantly slower. Another problem with C is that it is very
14553: cumbersome to express double integer arithmetic.
14554:
14555: @cindex GNU C for the engine
14556: @cindex long long
14557: Fortunately, there is a portable language that does not have these
14558: limitations: GNU C, the version of C processed by the GNU C compiler
14559: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14560: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14561: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14562: threading possible, its @code{long long} type (@pxref{Long Long, ,
14563: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14564: double numbers on many systems. GNU C is freely available on all
1.1 anton 14565: important (and many unimportant) UNIX machines, VMS, 80386s running
14566: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14567: on all these machines.
14568:
14569: Writing in a portable language has the reputation of producing code that
14570: is slower than assembly. For our Forth engine we repeatedly looked at
14571: the code produced by the compiler and eliminated most compiler-induced
14572: inefficiencies by appropriate changes in the source code.
14573:
14574: @cindex explicit register declarations
14575: @cindex --enable-force-reg, configuration flag
14576: @cindex -DFORCE_REG
14577: However, register allocation cannot be portably influenced by the
14578: programmer, leading to some inefficiencies on register-starved
14579: machines. We use explicit register declarations (@pxref{Explicit Reg
14580: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14581: improve the speed on some machines. They are turned on by using the
14582: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14583: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14584: machine, but also on the compiler version: On some machines some
14585: compiler versions produce incorrect code when certain explicit register
14586: declarations are used. So by default @code{-DFORCE_REG} is not used.
14587:
14588: @node Threading, Primitives, Portability, Engine
14589: @section Threading
14590: @cindex inner interpreter implementation
14591: @cindex threaded code implementation
14592:
14593: @cindex labels as values
14594: GNU C's labels as values extension (available since @code{gcc-2.0},
14595: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14596: makes it possible to take the address of @i{label} by writing
14597: @code{&&@i{label}}. This address can then be used in a statement like
14598: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14599: @code{goto x}.
14600:
1.26 crook 14601: @cindex @code{NEXT}, indirect threaded
1.1 anton 14602: @cindex indirect threaded inner interpreter
14603: @cindex inner interpreter, indirect threaded
1.26 crook 14604: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14605: @example
14606: cfa = *ip++;
14607: ca = *cfa;
14608: goto *ca;
14609: @end example
14610: @cindex instruction pointer
14611: For those unfamiliar with the names: @code{ip} is the Forth instruction
14612: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14613: execution token and points to the code field of the next word to be
14614: executed; The @code{ca} (code address) fetched from there points to some
14615: executable code, e.g., a primitive or the colon definition handler
14616: @code{docol}.
14617:
1.26 crook 14618: @cindex @code{NEXT}, direct threaded
1.1 anton 14619: @cindex direct threaded inner interpreter
14620: @cindex inner interpreter, direct threaded
14621: Direct threading is even simpler:
14622: @example
14623: ca = *ip++;
14624: goto *ca;
14625: @end example
14626:
14627: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14628: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14629:
14630: @menu
14631: * Scheduling::
14632: * Direct or Indirect Threaded?::
1.109 anton 14633: * Dynamic Superinstructions::
1.1 anton 14634: * DOES>::
14635: @end menu
14636:
14637: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14638: @subsection Scheduling
14639: @cindex inner interpreter optimization
14640:
14641: There is a little complication: Pipelined and superscalar processors,
14642: i.e., RISC and some modern CISC machines can process independent
14643: instructions while waiting for the results of an instruction. The
14644: compiler usually reorders (schedules) the instructions in a way that
14645: achieves good usage of these delay slots. However, on our first tries
14646: the compiler did not do well on scheduling primitives. E.g., for
14647: @code{+} implemented as
14648: @example
14649: n=sp[0]+sp[1];
14650: sp++;
14651: sp[0]=n;
14652: NEXT;
14653: @end example
1.81 anton 14654: the @code{NEXT} comes strictly after the other code, i.e., there is
14655: nearly no scheduling. After a little thought the problem becomes clear:
14656: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14657: addresses (and the version of @code{gcc} we used would not know it even
14658: if it was possible), so it could not move the load of the cfa above the
14659: store to the TOS. Indeed the pointers could be the same, if code on or
14660: very near the top of stack were executed. In the interest of speed we
14661: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14662: in scheduling: @code{NEXT} is divided into several parts:
14663: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14664: like:
1.1 anton 14665: @example
1.81 anton 14666: NEXT_P0;
1.1 anton 14667: n=sp[0]+sp[1];
14668: sp++;
14669: NEXT_P1;
14670: sp[0]=n;
14671: NEXT_P2;
14672: @end example
14673:
1.81 anton 14674: There are various schemes that distribute the different operations of
14675: NEXT between these parts in several ways; in general, different schemes
14676: perform best on different processors. We use a scheme for most
14677: architectures that performs well for most processors of this
1.109 anton 14678: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14679: the scheme on installation time.
14680:
1.1 anton 14681:
1.109 anton 14682: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14683: @subsection Direct or Indirect Threaded?
14684: @cindex threading, direct or indirect?
14685:
1.109 anton 14686: Threaded forth code consists of references to primitives (simple machine
14687: code routines like @code{+}) and to non-primitives (e.g., colon
14688: definitions, variables, constants); for a specific class of
14689: non-primitives (e.g., variables) there is one code routine (e.g.,
14690: @code{dovar}), but each variable needs a separate reference to its data.
14691:
14692: Traditionally Forth has been implemented as indirect threaded code,
14693: because this allows to use only one cell to reference a non-primitive
14694: (basically you point to the data, and find the code address there).
14695:
14696: @cindex primitive-centric threaded code
14697: However, threaded code in Gforth (since 0.6.0) uses two cells for
14698: non-primitives, one for the code address, and one for the data address;
14699: the data pointer is an immediate argument for the virtual machine
14700: instruction represented by the code address. We call this
14701: @emph{primitive-centric} threaded code, because all code addresses point
14702: to simple primitives. E.g., for a variable, the code address is for
14703: @code{lit} (also used for integer literals like @code{99}).
14704:
14705: Primitive-centric threaded code allows us to use (faster) direct
14706: threading as dispatch method, completely portably (direct threaded code
14707: in Gforth before 0.6.0 required architecture-specific code). It also
14708: eliminates the performance problems related to I-cache consistency that
14709: 386 implementations have with direct threaded code, and allows
14710: additional optimizations.
14711:
14712: @cindex hybrid direct/indirect threaded code
14713: There is a catch, however: the @var{xt} parameter of @code{execute} can
14714: occupy only one cell, so how do we pass non-primitives with their code
14715: @emph{and} data addresses to them? Our answer is to use indirect
14716: threaded dispatch for @code{execute} and other words that use a
14717: single-cell xt. So, normal threaded code in colon definitions uses
14718: direct threading, and @code{execute} and similar words, which dispatch
14719: to xts on the data stack, use indirect threaded code. We call this
14720: @emph{hybrid direct/indirect} threaded code.
14721:
14722: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14723: @cindex gforth engine
14724: @cindex gforth-fast engine
14725: The engines @command{gforth} and @command{gforth-fast} use hybrid
14726: direct/indirect threaded code. This means that with these engines you
14727: cannot use @code{,} to compile an xt. Instead, you have to use
14728: @code{compile,}.
14729:
14730: @cindex gforth-itc engine
1.115 anton 14731: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14732: This engine uses plain old indirect threaded code. It still compiles in
14733: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14734: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14735: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14736: and execute @code{' , is compile,}. Your program can check if it is
14737: running on a hybrid direct/indirect threaded engine or a pure indirect
14738: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14739:
14740:
14741: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14742: @subsection Dynamic Superinstructions
14743: @cindex Dynamic superinstructions with replication
14744: @cindex Superinstructions
14745: @cindex Replication
14746:
14747: The engines @command{gforth} and @command{gforth-fast} use another
14748: optimization: Dynamic superinstructions with replication. As an
14749: example, consider the following colon definition:
14750:
14751: @example
14752: : squared ( n1 -- n2 )
14753: dup * ;
14754: @end example
14755:
14756: Gforth compiles this into the threaded code sequence
14757:
14758: @example
14759: dup
14760: *
14761: ;s
14762: @end example
14763:
14764: In normal direct threaded code there is a code address occupying one
14765: cell for each of these primitives. Each code address points to a
14766: machine code routine, and the interpreter jumps to this machine code in
14767: order to execute the primitive. The routines for these three
14768: primitives are (in @command{gforth-fast} on the 386):
14769:
14770: @example
14771: Code dup
14772: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14773: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14774: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14775: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14776: end-code
14777: Code *
14778: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14779: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14780: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14781: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14782: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14783: end-code
14784: Code ;s
14785: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14786: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14787: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14788: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14789: end-code
14790: @end example
14791:
14792: With dynamic superinstructions and replication the compiler does not
14793: just lay down the threaded code, but also copies the machine code
14794: fragments, usually without the jump at the end.
14795:
14796: @example
14797: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14798: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14799: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14800: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14801: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14802: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14803: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14804: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14805: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14806: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14807: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14808: @end example
14809:
14810: Only when a threaded-code control-flow change happens (e.g., in
14811: @code{;s}), the jump is appended. This optimization eliminates many of
14812: these jumps and makes the rest much more predictable. The speedup
14813: depends on the processor and the application; on the Athlon and Pentium
14814: III this optimization typically produces a speedup by a factor of 2.
14815:
14816: The code addresses in the direct-threaded code are set to point to the
14817: appropriate points in the copied machine code, in this example like
14818: this:
1.1 anton 14819:
1.109 anton 14820: @example
14821: primitive code address
14822: dup $4057D27D
14823: * $4057D286
14824: ;s $4057D292
14825: @end example
14826:
14827: Thus there can be threaded-code jumps to any place in this piece of
14828: code. This also simplifies decompilation quite a bit.
14829:
14830: @cindex --no-dynamic command-line option
14831: @cindex --no-super command-line option
14832: You can disable this optimization with @option{--no-dynamic}. You can
14833: use the copying without eliminating the jumps (i.e., dynamic
14834: replication, but without superinstructions) with @option{--no-super};
14835: this gives the branch prediction benefit alone; the effect on
1.110 anton 14836: performance depends on the CPU; on the Athlon and Pentium III the
14837: speedup is a little less than for dynamic superinstructions with
14838: replication.
14839:
14840: @cindex patching threaded code
14841: One use of these options is if you want to patch the threaded code.
14842: With superinstructions, many of the dispatch jumps are eliminated, so
14843: patching often has no effect. These options preserve all the dispatch
14844: jumps.
1.109 anton 14845:
14846: @cindex --dynamic command-line option
1.110 anton 14847: On some machines dynamic superinstructions are disabled by default,
14848: because it is unsafe on these machines. However, if you feel
14849: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14850:
14851: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14852: @subsection DOES>
14853: @cindex @code{DOES>} implementation
14854:
1.26 crook 14855: @cindex @code{dodoes} routine
14856: @cindex @code{DOES>}-code
1.1 anton 14857: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14858: the chunk of code executed by every word defined by a
1.109 anton 14859: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14860: this is only needed if the xt of the word is @code{execute}d. The main
14861: problem here is: How to find the Forth code to be executed, i.e. the
14862: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14863: solutions:
1.1 anton 14864:
1.21 crook 14865: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14866: @code{DOES>}-code address is stored in the cell after the code address
14867: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14868: illegal in the Forth-79 and all later standards, because in fig-Forth
14869: this address lies in the body (which is illegal in these
14870: standards). However, by making the code field larger for all words this
14871: solution becomes legal again. We use this approach. Leaving a cell
14872: unused in most words is a bit wasteful, but on the machines we are
14873: targeting this is hardly a problem.
14874:
1.1 anton 14875:
14876: @node Primitives, Performance, Threading, Engine
14877: @section Primitives
14878: @cindex primitives, implementation
14879: @cindex virtual machine instructions, implementation
14880:
14881: @menu
14882: * Automatic Generation::
14883: * TOS Optimization::
14884: * Produced code::
14885: @end menu
14886:
14887: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14888: @subsection Automatic Generation
14889: @cindex primitives, automatic generation
14890:
14891: @cindex @file{prims2x.fs}
1.109 anton 14892:
1.1 anton 14893: Since the primitives are implemented in a portable language, there is no
14894: longer any need to minimize the number of primitives. On the contrary,
14895: having many primitives has an advantage: speed. In order to reduce the
14896: number of errors in primitives and to make programming them easier, we
1.109 anton 14897: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14898: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14899: generates most (and sometimes all) of the C code for a primitive from
14900: the stack effect notation. The source for a primitive has the following
14901: form:
1.1 anton 14902:
14903: @cindex primitive source format
14904: @format
1.58 anton 14905: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14906: [@code{""}@i{glossary entry}@code{""}]
14907: @i{C code}
1.1 anton 14908: [@code{:}
1.29 crook 14909: @i{Forth code}]
1.1 anton 14910: @end format
14911:
14912: The items in brackets are optional. The category and glossary fields
14913: are there for generating the documentation, the Forth code is there
14914: for manual implementations on machines without GNU C. E.g., the source
14915: for the primitive @code{+} is:
14916: @example
1.58 anton 14917: + ( n1 n2 -- n ) core plus
1.1 anton 14918: n = n1+n2;
14919: @end example
14920:
14921: This looks like a specification, but in fact @code{n = n1+n2} is C
14922: code. Our primitive generation tool extracts a lot of information from
14923: the stack effect notations@footnote{We use a one-stack notation, even
14924: though we have separate data and floating-point stacks; The separate
14925: notation can be generated easily from the unified notation.}: The number
14926: of items popped from and pushed on the stack, their type, and by what
14927: name they are referred to in the C code. It then generates a C code
14928: prelude and postlude for each primitive. The final C code for @code{+}
14929: looks like this:
14930:
14931: @example
1.46 pazsan 14932: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14933: /* */ /* documentation */
1.81 anton 14934: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14935: @{
14936: DEF_CA /* definition of variable ca (indirect threading) */
14937: Cell n1; /* definitions of variables */
14938: Cell n2;
14939: Cell n;
1.81 anton 14940: NEXT_P0; /* NEXT part 0 */
1.1 anton 14941: n1 = (Cell) sp[1]; /* input */
14942: n2 = (Cell) TOS;
14943: sp += 1; /* stack adjustment */
14944: @{
14945: n = n1+n2; /* C code taken from the source */
14946: @}
14947: NEXT_P1; /* NEXT part 1 */
14948: TOS = (Cell)n; /* output */
14949: NEXT_P2; /* NEXT part 2 */
14950: @}
14951: @end example
14952:
14953: This looks long and inefficient, but the GNU C compiler optimizes quite
14954: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14955: HP RISC machines: Defining the @code{n}s does not produce any code, and
14956: using them as intermediate storage also adds no cost.
14957:
1.26 crook 14958: There are also other optimizations that are not illustrated by this
14959: example: assignments between simple variables are usually for free (copy
1.1 anton 14960: propagation). If one of the stack items is not used by the primitive
14961: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14962: (dead code elimination). On the other hand, there are some things that
14963: the compiler does not do, therefore they are performed by
14964: @file{prims2x.fs}: The compiler does not optimize code away that stores
14965: a stack item to the place where it just came from (e.g., @code{over}).
14966:
14967: While programming a primitive is usually easy, there are a few cases
14968: where the programmer has to take the actions of the generator into
14969: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14970: fall through to @code{NEXT}.
1.109 anton 14971:
14972: For more information
1.1 anton 14973:
14974: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14975: @subsection TOS Optimization
14976: @cindex TOS optimization for primitives
14977: @cindex primitives, keeping the TOS in a register
14978:
14979: An important optimization for stack machine emulators, e.g., Forth
14980: engines, is keeping one or more of the top stack items in
1.29 crook 14981: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14982: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14983: @itemize @bullet
14984: @item
1.29 crook 14985: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14986: due to fewer loads from and stores to the stack.
1.29 crook 14987: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14988: @i{y<n}, due to additional moves between registers.
1.1 anton 14989: @end itemize
14990:
14991: @cindex -DUSE_TOS
14992: @cindex -DUSE_NO_TOS
14993: In particular, keeping one item in a register is never a disadvantage,
14994: if there are enough registers. Keeping two items in registers is a
14995: disadvantage for frequent words like @code{?branch}, constants,
14996: variables, literals and @code{i}. Therefore our generator only produces
14997: code that keeps zero or one items in registers. The generated C code
14998: covers both cases; the selection between these alternatives is made at
14999: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15000: code for @code{+} is just a simple variable name in the one-item case,
15001: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15002: GNU C compiler tries to keep simple variables like @code{TOS} in
15003: registers, and it usually succeeds, if there are enough registers.
15004:
15005: @cindex -DUSE_FTOS
15006: @cindex -DUSE_NO_FTOS
15007: The primitive generator performs the TOS optimization for the
15008: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15009: operations the benefit of this optimization is even larger:
15010: floating-point operations take quite long on most processors, but can be
15011: performed in parallel with other operations as long as their results are
15012: not used. If the FP-TOS is kept in a register, this works. If
15013: it is kept on the stack, i.e., in memory, the store into memory has to
15014: wait for the result of the floating-point operation, lengthening the
15015: execution time of the primitive considerably.
15016:
15017: The TOS optimization makes the automatic generation of primitives a
15018: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15019: @code{TOS} is not sufficient. There are some special cases to
15020: consider:
15021: @itemize @bullet
15022: @item In the case of @code{dup ( w -- w w )} the generator must not
15023: eliminate the store to the original location of the item on the stack,
15024: if the TOS optimization is turned on.
15025: @item Primitives with stack effects of the form @code{--}
1.29 crook 15026: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15027: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15028: must load the TOS from the stack at the end. But for the null stack
15029: effect @code{--} no stores or loads should be generated.
15030: @end itemize
15031:
15032: @node Produced code, , TOS Optimization, Primitives
15033: @subsection Produced code
15034: @cindex primitives, assembly code listing
15035:
15036: @cindex @file{engine.s}
15037: To see what assembly code is produced for the primitives on your machine
15038: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15039: look at the resulting file @file{engine.s}. Alternatively, you can also
15040: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15041:
15042: @node Performance, , Primitives, Engine
15043: @section Performance
15044: @cindex performance of some Forth interpreters
15045: @cindex engine performance
15046: @cindex benchmarking Forth systems
15047: @cindex Gforth performance
15048:
15049: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15050: impossible to write a significantly faster threaded-code engine.
1.1 anton 15051:
15052: On register-starved machines like the 386 architecture processors
15053: improvements are possible, because @code{gcc} does not utilize the
15054: registers as well as a human, even with explicit register declarations;
15055: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15056: and hand-tuned it for the 486; this system is 1.19 times faster on the
15057: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15058: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15059: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15060: registers fit in real registers (and we can even afford to use the TOS
15061: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15062: earlier results. And dynamic superinstructions provide another speedup
15063: (but only around a factor 1.2 on the 486).
1.1 anton 15064:
15065: @cindex Win32Forth performance
15066: @cindex NT Forth performance
15067: @cindex eforth performance
15068: @cindex ThisForth performance
15069: @cindex PFE performance
15070: @cindex TILE performance
1.81 anton 15071: The potential advantage of assembly language implementations is not
1.112 anton 15072: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15073: (direct threaded, compiled with @code{gcc-2.95.1} and
15074: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15075: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15076: (with and without peephole (aka pinhole) optimization of the threaded
15077: code); all these systems were written in assembly language. We also
15078: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15079: with @code{gcc-2.6.3} with the default configuration for Linux:
15080: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15081: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15082: employs peephole optimization of the threaded code) and TILE (compiled
15083: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15084: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15085: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15086: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15087: then extended it to run the benchmarks, added the peephole optimizer,
15088: ran the benchmarks and reported the results.
1.40 anton 15089:
1.1 anton 15090: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15091: matrix multiplication come from the Stanford integer benchmarks and have
15092: been translated into Forth by Martin Fraeman; we used the versions
15093: included in the TILE Forth package, but with bigger data set sizes; and
15094: a recursive Fibonacci number computation for benchmarking calling
15095: performance. The following table shows the time taken for the benchmarks
15096: scaled by the time taken by Gforth (in other words, it shows the speedup
15097: factor that Gforth achieved over the other systems).
15098:
15099: @example
1.112 anton 15100: relative Win32- NT eforth This-
15101: time Gforth Forth Forth eforth +opt PFE Forth TILE
15102: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15103: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15104: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15105: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15106: @end example
15107:
1.26 crook 15108: You may be quite surprised by the good performance of Gforth when
15109: compared with systems written in assembly language. One important reason
15110: for the disappointing performance of these other systems is probably
15111: that they are not written optimally for the 486 (e.g., they use the
15112: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15113: but costly method for relocating the Forth image: like @code{cforth}, it
15114: computes the actual addresses at run time, resulting in two address
15115: computations per @code{NEXT} (@pxref{Image File Background}).
15116:
1.1 anton 15117: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15118: explained with the self-imposed restriction of the latter systems to
15119: standard C, which makes efficient threading impossible (however, the
1.4 anton 15120: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15121: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15122: Moreover, current C compilers have a hard time optimizing other aspects
15123: of the ThisForth and the TILE source.
15124:
1.26 crook 15125: The performance of Gforth on 386 architecture processors varies widely
15126: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15127: allocate any of the virtual machine registers into real machine
15128: registers by itself and would not work correctly with explicit register
1.112 anton 15129: declarations, giving a significantly slower engine (on a 486DX2/66
15130: running the Sieve) than the one measured above.
1.1 anton 15131:
1.26 crook 15132: Note that there have been several releases of Win32Forth since the
15133: release presented here, so the results presented above may have little
1.40 anton 15134: predictive value for the performance of Win32Forth today (results for
15135: the current release on an i486DX2/66 are welcome).
1.1 anton 15136:
15137: @cindex @file{Benchres}
1.66 anton 15138: In
15139: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15140: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15141: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15142: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15143: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15144: than the version used here. You can find a newer version of these
15145: measurements at
1.47 crook 15146: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15147: find numbers for Gforth on various machines in @file{Benchres}.
15148:
1.26 crook 15149: @c ******************************************************************
1.113 anton 15150: @c @node Binding to System Library, Cross Compiler, Engine, Top
15151: @c @chapter Binding to System Library
1.13 pazsan 15152:
1.113 anton 15153: @c ****************************************************************
15154: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15155: @chapter Cross Compiler
1.47 crook 15156: @cindex @file{cross.fs}
15157: @cindex cross-compiler
15158: @cindex metacompiler
15159: @cindex target compiler
1.13 pazsan 15160:
1.46 pazsan 15161: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15162: mostly written in Forth, including crucial parts like the outer
15163: interpreter and compiler, it needs compiled Forth code to get
15164: started. The cross compiler allows to create new images for other
15165: architectures, even running under another Forth system.
1.13 pazsan 15166:
15167: @menu
1.67 anton 15168: * Using the Cross Compiler::
15169: * How the Cross Compiler Works::
1.13 pazsan 15170: @end menu
15171:
1.21 crook 15172: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15173: @section Using the Cross Compiler
1.46 pazsan 15174:
15175: The cross compiler uses a language that resembles Forth, but isn't. The
15176: main difference is that you can execute Forth code after definition,
15177: while you usually can't execute the code compiled by cross, because the
15178: code you are compiling is typically for a different computer than the
15179: one you are compiling on.
15180:
1.81 anton 15181: @c anton: This chapter is somewhat different from waht I would expect: I
15182: @c would expect an explanation of the cross language and how to create an
15183: @c application image with it. The section explains some aspects of
15184: @c creating a Gforth kernel.
15185:
1.46 pazsan 15186: The Makefile is already set up to allow you to create kernels for new
15187: architectures with a simple make command. The generic kernels using the
15188: GCC compiled virtual machine are created in the normal build process
15189: with @code{make}. To create a embedded Gforth executable for e.g. the
15190: 8086 processor (running on a DOS machine), type
15191:
15192: @example
15193: make kernl-8086.fi
15194: @end example
15195:
15196: This will use the machine description from the @file{arch/8086}
15197: directory to create a new kernel. A machine file may look like that:
15198:
15199: @example
15200: \ Parameter for target systems 06oct92py
15201:
15202: 4 Constant cell \ cell size in bytes
15203: 2 Constant cell<< \ cell shift to bytes
15204: 5 Constant cell>bit \ cell shift to bits
15205: 8 Constant bits/char \ bits per character
15206: 8 Constant bits/byte \ bits per byte [default: 8]
15207: 8 Constant float \ bytes per float
15208: 8 Constant /maxalign \ maximum alignment in bytes
15209: false Constant bigendian \ byte order
15210: ( true=big, false=little )
15211:
15212: include machpc.fs \ feature list
15213: @end example
15214:
15215: This part is obligatory for the cross compiler itself, the feature list
15216: is used by the kernel to conditionally compile some features in and out,
15217: depending on whether the target supports these features.
15218:
15219: There are some optional features, if you define your own primitives,
15220: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15221: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15222: @code{prims-include} includes primitives, and @code{>boot} prepares for
15223: booting.
15224:
15225: @example
15226: : asm-include ." Include assembler" cr
15227: s" arch/8086/asm.fs" included ;
15228:
15229: : prims-include ." Include primitives" cr
15230: s" arch/8086/prim.fs" included ;
15231:
15232: : >boot ." Prepare booting" cr
15233: s" ' boot >body into-forth 1+ !" evaluate ;
15234: @end example
15235:
15236: These words are used as sort of macro during the cross compilation in
1.81 anton 15237: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15238: be possible --- but more complicated --- to write a new kernel project
15239: file, too.
15240:
15241: @file{kernel/main.fs} expects the machine description file name on the
15242: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15243: @code{mach-file} leaves a counted string on the stack, or
15244: @code{machine-file} leaves an address, count pair of the filename on the
15245: stack.
15246:
15247: The feature list is typically controlled using @code{SetValue}, generic
15248: files that are used by several projects can use @code{DefaultValue}
15249: instead. Both functions work like @code{Value}, when the value isn't
15250: defined, but @code{SetValue} works like @code{to} if the value is
15251: defined, and @code{DefaultValue} doesn't set anything, if the value is
15252: defined.
15253:
15254: @example
15255: \ generic mach file for pc gforth 03sep97jaw
15256:
15257: true DefaultValue NIL \ relocating
15258:
15259: >ENVIRON
15260:
15261: true DefaultValue file \ controls the presence of the
15262: \ file access wordset
15263: true DefaultValue OS \ flag to indicate a operating system
15264:
15265: true DefaultValue prims \ true: primitives are c-code
15266:
15267: true DefaultValue floating \ floating point wordset is present
15268:
15269: true DefaultValue glocals \ gforth locals are present
15270: \ will be loaded
15271: true DefaultValue dcomps \ double number comparisons
15272:
15273: true DefaultValue hash \ hashing primitives are loaded/present
15274:
15275: true DefaultValue xconds \ used together with glocals,
15276: \ special conditionals supporting gforths'
15277: \ local variables
15278: true DefaultValue header \ save a header information
15279:
15280: true DefaultValue backtrace \ enables backtrace code
15281:
15282: false DefaultValue ec
15283: false DefaultValue crlf
15284:
15285: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15286:
15287: &16 KB DefaultValue stack-size
15288: &15 KB &512 + DefaultValue fstack-size
15289: &15 KB DefaultValue rstack-size
15290: &14 KB &512 + DefaultValue lstack-size
15291: @end example
1.13 pazsan 15292:
1.48 anton 15293: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15294: @section How the Cross Compiler Works
1.13 pazsan 15295:
15296: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15297: @appendix Bugs
1.1 anton 15298: @cindex bug reporting
15299:
1.21 crook 15300: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15301:
1.103 anton 15302: If you find a bug, please submit a bug report through
15303: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15304:
15305: @itemize @bullet
15306: @item
1.81 anton 15307: A program (or a sequence of keyboard commands) that reproduces the bug.
15308: @item
15309: A description of what you think constitutes the buggy behaviour.
15310: @item
1.21 crook 15311: The Gforth version used (it is announced at the start of an
15312: interactive Gforth session).
15313: @item
15314: The machine and operating system (on Unix
15315: systems @code{uname -a} will report this information).
15316: @item
1.81 anton 15317: The installation options (you can find the configure options at the
15318: start of @file{config.status}) and configuration (@code{configure}
15319: output or @file{config.cache}).
1.21 crook 15320: @item
15321: A complete list of changes (if any) you (or your installer) have made to the
15322: Gforth sources.
15323: @end itemize
1.1 anton 15324:
15325: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15326: to Report Bugs, gcc.info, GNU C Manual}.
15327:
15328:
1.21 crook 15329: @node Origin, Forth-related information, Bugs, Top
15330: @appendix Authors and Ancestors of Gforth
1.1 anton 15331:
15332: @section Authors and Contributors
15333: @cindex authors of Gforth
15334: @cindex contributors to Gforth
15335:
15336: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15337: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15338: lot to the manual. Assemblers and disassemblers were contributed by
15339: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15340: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15341: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15342: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15343: support for calling C libraries. Helpful comments also came from Paul
15344: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15345: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15346: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15347: Gforth-0.2.1 there were also helpful comments from many others; thank
15348: you all, sorry for not listing you here (but digging through my mailbox
15349: to extract your names is on my to-do list).
1.1 anton 15350:
15351: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15352: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15353: was developed across the Internet, and its authors did not meet
1.20 pazsan 15354: physically for the first 4 years of development.
1.1 anton 15355:
15356: @section Pedigree
1.26 crook 15357: @cindex pedigree of Gforth
1.1 anton 15358:
1.81 anton 15359: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15360: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15361:
1.20 pazsan 15362: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15363: 32 bit native code version of VolksForth for the Atari ST, written
15364: mostly by Dietrich Weineck.
15365:
1.81 anton 15366: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15367: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15368: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15369:
1.147 anton 15370: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15371: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15372:
15373: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15374: 1979. Robert Selzer and Bill Ragsdale developed the original
15375: implementation of fig-Forth for the 6502 based on microForth.
15376:
15377: The principal architect of microForth was Dean Sanderson. microForth was
15378: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15379: the 1802, and subsequently implemented on the 8080, the 6800 and the
15380: Z80.
15381:
15382: All earlier Forth systems were custom-made, usually by Charles Moore,
15383: who discovered (as he puts it) Forth during the late 60s. The first full
15384: Forth existed in 1971.
15385:
1.81 anton 15386: A part of the information in this section comes from
15387: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15388: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15389: Charles H. Moore, presented at the HOPL-II conference and preprinted
15390: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15391: genealogical information about Forth there. For a more general (and
15392: graphical) Forth family tree look see
15393: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15394: Forth Family Tree and Timeline}.
1.1 anton 15395:
1.81 anton 15396: @c ------------------------------------------------------------------
1.113 anton 15397: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15398: @appendix Other Forth-related information
15399: @cindex Forth-related information
15400:
1.81 anton 15401: @c anton: I threw most of this stuff out, because it can be found through
15402: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15403:
15404: @cindex comp.lang.forth
15405: @cindex frequently asked questions
1.81 anton 15406: There is an active news group (comp.lang.forth) discussing Forth
15407: (including Gforth) and Forth-related issues. Its
15408: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15409: (frequently asked questions and their answers) contains a lot of
15410: information on Forth. You should read it before posting to
15411: comp.lang.forth.
1.21 crook 15412:
1.81 anton 15413: The ANS Forth standard is most usable in its
15414: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15415:
1.113 anton 15416: @c ---------------------------------------------------
15417: @node Licenses, Word Index, Forth-related information, Top
15418: @appendix Licenses
15419:
15420: @menu
15421: * GNU Free Documentation License:: License for copying this manual.
15422: * Copying:: GPL (for copying this software).
15423: @end menu
15424:
15425: @include fdl.texi
15426:
15427: @include gpl.texi
15428:
15429:
15430:
1.81 anton 15431: @c ------------------------------------------------------------------
1.113 anton 15432: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15433: @unnumbered Word Index
15434:
1.26 crook 15435: This index is a list of Forth words that have ``glossary'' entries
15436: within this manual. Each word is listed with its stack effect and
15437: wordset.
1.1 anton 15438:
15439: @printindex fn
15440:
1.81 anton 15441: @c anton: the name index seems superfluous given the word and concept indices.
15442:
15443: @c @node Name Index, Concept Index, Word Index, Top
15444: @c @unnumbered Name Index
1.41 anton 15445:
1.81 anton 15446: @c This index is a list of Forth words that have ``glossary'' entries
15447: @c within this manual.
1.41 anton 15448:
1.81 anton 15449: @c @printindex ky
1.41 anton 15450:
1.113 anton 15451: @c -------------------------------------------------------
1.81 anton 15452: @node Concept Index, , Word Index, Top
1.1 anton 15453: @unnumbered Concept and Word Index
15454:
1.26 crook 15455: Not all entries listed in this index are present verbatim in the
15456: text. This index also duplicates, in abbreviated form, all of the words
15457: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15458:
15459: @printindex cp
15460:
15461: @bye
1.81 anton 15462:
15463:
1.1 anton 15464:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>