Annotation of gforth/doc/gforth.ds, revision 1.128
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.113 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
226: * Assembler and Code Words::
227: * Threading Words::
1.65 anton 228: * Passing Commands to the OS::
229: * Keeping track of Time::
230: * Miscellaneous Words::
1.12 anton 231:
232: Arithmetic
233:
234: * Single precision::
1.67 anton 235: * Double precision:: Double-cell integer arithmetic
1.12 anton 236: * Bitwise operations::
1.67 anton 237: * Numeric comparison::
1.32 anton 238: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 239: * Floating Point::
240:
241: Stack Manipulation
242:
243: * Data stack::
244: * Floating point stack::
245: * Return stack::
246: * Locals stack::
247: * Stack pointer manipulation::
248:
249: Memory
250:
1.32 anton 251: * Memory model::
252: * Dictionary allocation::
253: * Heap Allocation::
254: * Memory Access::
255: * Address arithmetic::
256: * Memory Blocks::
1.12 anton 257:
258: Control Structures
259:
1.41 anton 260: * Selection:: IF ... ELSE ... ENDIF
261: * Simple Loops:: BEGIN ...
1.32 anton 262: * Counted Loops:: DO
1.67 anton 263: * Arbitrary control structures::
264: * Calls and returns::
1.12 anton 265: * Exception Handling::
266:
267: Defining Words
268:
1.67 anton 269: * CREATE::
1.44 crook 270: * Variables:: Variables and user variables
1.67 anton 271: * Constants::
1.44 crook 272: * Values:: Initialised variables
1.67 anton 273: * Colon Definitions::
1.44 crook 274: * Anonymous Definitions:: Definitions without names
1.71 anton 275: * Supplying names:: Passing definition names as strings
1.67 anton 276: * User-defined Defining Words::
1.44 crook 277: * Deferred words:: Allow forward references
1.67 anton 278: * Aliases::
1.47 crook 279:
1.63 anton 280: User-defined Defining Words
281:
282: * CREATE..DOES> applications::
283: * CREATE..DOES> details::
284: * Advanced does> usage example::
1.91 anton 285: * @code{Const-does>}::
1.63 anton 286:
1.47 crook 287: Interpretation and Compilation Semantics
288:
1.67 anton 289: * Combined words::
1.12 anton 290:
1.71 anton 291: Tokens for Words
292:
293: * Execution token:: represents execution/interpretation semantics
294: * Compilation token:: represents compilation semantics
295: * Name token:: represents named words
296:
1.82 anton 297: Compiling words
298:
299: * Literals:: Compiling data values
300: * Macros:: Compiling words
301:
1.21 crook 302: The Text Interpreter
303:
1.67 anton 304: * Input Sources::
305: * Number Conversion::
306: * Interpret/Compile states::
307: * Interpreter Directives::
1.21 crook 308:
1.26 crook 309: Word Lists
310:
1.75 anton 311: * Vocabularies::
1.67 anton 312: * Why use word lists?::
1.75 anton 313: * Word list example::
1.26 crook 314:
315: Files
316:
1.48 anton 317: * Forth source files::
318: * General files::
319: * Search Paths::
320:
321: Search Paths
322:
1.75 anton 323: * Source Search Paths::
1.26 crook 324: * General Search Paths::
325:
326: Other I/O
327:
1.32 anton 328: * Simple numeric output:: Predefined formats
329: * Formatted numeric output:: Formatted (pictured) output
330: * String Formats:: How Forth stores strings in memory
1.67 anton 331: * Displaying characters and strings:: Other stuff
1.32 anton 332: * Input:: Input
1.112 anton 333: * Pipes:: How to create your own pipes
1.26 crook 334:
335: Locals
336:
337: * Gforth locals::
338: * ANS Forth locals::
339:
340: Gforth locals
341:
342: * Where are locals visible by name?::
343: * How long do locals live?::
1.78 anton 344: * Locals programming style::
345: * Locals implementation::
1.26 crook 346:
1.12 anton 347: Structures
348:
349: * Why explicit structure support?::
350: * Structure Usage::
351: * Structure Naming Convention::
352: * Structure Implementation::
353: * Structure Glossary::
354:
355: Object-oriented Forth
356:
1.48 anton 357: * Why object-oriented programming?::
358: * Object-Oriented Terminology::
359: * Objects::
360: * OOF::
361: * Mini-OOF::
1.23 crook 362: * Comparison with other object models::
1.12 anton 363:
1.24 anton 364: The @file{objects.fs} model
1.12 anton 365:
366: * Properties of the Objects model::
367: * Basic Objects Usage::
1.41 anton 368: * The Objects base class::
1.12 anton 369: * Creating objects::
370: * Object-Oriented Programming Style::
371: * Class Binding::
372: * Method conveniences::
373: * Classes and Scoping::
1.41 anton 374: * Dividing classes::
1.12 anton 375: * Object Interfaces::
376: * Objects Implementation::
377: * Objects Glossary::
378:
1.24 anton 379: The @file{oof.fs} model
1.12 anton 380:
1.67 anton 381: * Properties of the OOF model::
382: * Basic OOF Usage::
383: * The OOF base class::
384: * Class Declaration::
385: * Class Implementation::
1.12 anton 386:
1.24 anton 387: The @file{mini-oof.fs} model
1.23 crook 388:
1.48 anton 389: * Basic Mini-OOF Usage::
390: * Mini-OOF Example::
391: * Mini-OOF Implementation::
1.23 crook 392:
1.78 anton 393: Programming Tools
394:
395: * Examining::
396: * Forgetting words::
397: * Debugging:: Simple and quick.
398: * Assertions:: Making your programs self-checking.
399: * Singlestep Debugger:: Executing your program word by word.
400:
401: Assembler and Code Words
402:
403: * Code and ;code::
404: * Common Assembler:: Assembler Syntax
405: * Common Disassembler::
406: * 386 Assembler:: Deviations and special cases
407: * Alpha Assembler:: Deviations and special cases
408: * MIPS assembler:: Deviations and special cases
409: * Other assemblers:: How to write them
410:
1.12 anton 411: Tools
412:
413: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 414: * Stack depth changes:: Where does this stack item come from?
1.12 anton 415:
416: ANS conformance
417:
418: * The Core Words::
419: * The optional Block word set::
420: * The optional Double Number word set::
421: * The optional Exception word set::
422: * The optional Facility word set::
423: * The optional File-Access word set::
424: * The optional Floating-Point word set::
425: * The optional Locals word set::
426: * The optional Memory-Allocation word set::
427: * The optional Programming-Tools word set::
428: * The optional Search-Order word set::
429:
430: The Core Words
431:
432: * core-idef:: Implementation Defined Options
433: * core-ambcond:: Ambiguous Conditions
434: * core-other:: Other System Documentation
435:
436: The optional Block word set
437:
438: * block-idef:: Implementation Defined Options
439: * block-ambcond:: Ambiguous Conditions
440: * block-other:: Other System Documentation
441:
442: The optional Double Number word set
443:
444: * double-ambcond:: Ambiguous Conditions
445:
446: The optional Exception word set
447:
448: * exception-idef:: Implementation Defined Options
449:
450: The optional Facility word set
451:
452: * facility-idef:: Implementation Defined Options
453: * facility-ambcond:: Ambiguous Conditions
454:
455: The optional File-Access word set
456:
457: * file-idef:: Implementation Defined Options
458: * file-ambcond:: Ambiguous Conditions
459:
460: The optional Floating-Point word set
461:
462: * floating-idef:: Implementation Defined Options
463: * floating-ambcond:: Ambiguous Conditions
464:
465: The optional Locals word set
466:
467: * locals-idef:: Implementation Defined Options
468: * locals-ambcond:: Ambiguous Conditions
469:
470: The optional Memory-Allocation word set
471:
472: * memory-idef:: Implementation Defined Options
473:
474: The optional Programming-Tools word set
475:
476: * programming-idef:: Implementation Defined Options
477: * programming-ambcond:: Ambiguous Conditions
478:
479: The optional Search-Order word set
480:
481: * search-idef:: Implementation Defined Options
482: * search-ambcond:: Ambiguous Conditions
483:
1.109 anton 484: Emacs and Gforth
485:
486: * Installing gforth.el:: Making Emacs aware of Forth.
487: * Emacs Tags:: Viewing the source of a word in Emacs.
488: * Hilighting:: Making Forth code look prettier.
489: * Auto-Indentation:: Customizing auto-indentation.
490: * Blocks Files:: Reading and writing blocks files.
491:
1.12 anton 492: Image Files
493:
1.24 anton 494: * Image Licensing Issues:: Distribution terms for images.
495: * Image File Background:: Why have image files?
1.67 anton 496: * Non-Relocatable Image Files:: don't always work.
1.24 anton 497: * Data-Relocatable Image Files:: are better.
1.67 anton 498: * Fully Relocatable Image Files:: better yet.
1.24 anton 499: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 500: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 501: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 502:
503: Fully Relocatable Image Files
504:
1.27 crook 505: * gforthmi:: The normal way
1.12 anton 506: * cross.fs:: The hard way
507:
508: Engine
509:
510: * Portability::
511: * Threading::
512: * Primitives::
513: * Performance::
514:
515: Threading
516:
517: * Scheduling::
518: * Direct or Indirect Threaded?::
1.109 anton 519: * Dynamic Superinstructions::
1.12 anton 520: * DOES>::
521:
522: Primitives
523:
524: * Automatic Generation::
525: * TOS Optimization::
526: * Produced code::
1.13 pazsan 527:
528: Cross Compiler
529:
1.67 anton 530: * Using the Cross Compiler::
531: * How the Cross Compiler Works::
1.13 pazsan 532:
1.113 anton 533: Licenses
534:
535: * GNU Free Documentation License:: License for copying this manual.
536: * Copying:: GPL (for copying this software).
537:
1.24 anton 538: @end detailmenu
1.1 anton 539: @end menu
540:
1.113 anton 541: @c ----------------------------------------------------------
1.1 anton 542: @iftex
543: @unnumbered Preface
544: @cindex Preface
1.21 crook 545: This manual documents Gforth. Some introductory material is provided for
546: readers who are unfamiliar with Forth or who are migrating to Gforth
547: from other Forth compilers. However, this manual is primarily a
548: reference manual.
1.1 anton 549: @end iftex
550:
1.28 crook 551: @comment TODO much more blurb here.
1.26 crook 552:
553: @c ******************************************************************
1.113 anton 554: @node Goals, Gforth Environment, Top, Top
1.26 crook 555: @comment node-name, next, previous, up
556: @chapter Goals of Gforth
557: @cindex goals of the Gforth project
558: The goal of the Gforth Project is to develop a standard model for
559: ANS Forth. This can be split into several subgoals:
560:
561: @itemize @bullet
562: @item
563: Gforth should conform to the ANS Forth Standard.
564: @item
565: It should be a model, i.e. it should define all the
566: implementation-dependent things.
567: @item
568: It should become standard, i.e. widely accepted and used. This goal
569: is the most difficult one.
570: @end itemize
571:
572: To achieve these goals Gforth should be
573: @itemize @bullet
574: @item
575: Similar to previous models (fig-Forth, F83)
576: @item
577: Powerful. It should provide for all the things that are considered
578: necessary today and even some that are not yet considered necessary.
579: @item
580: Efficient. It should not get the reputation of being exceptionally
581: slow.
582: @item
583: Free.
584: @item
585: Available on many machines/easy to port.
586: @end itemize
587:
588: Have we achieved these goals? Gforth conforms to the ANS Forth
589: standard. It may be considered a model, but we have not yet documented
590: which parts of the model are stable and which parts we are likely to
591: change. It certainly has not yet become a de facto standard, but it
592: appears to be quite popular. It has some similarities to and some
593: differences from previous models. It has some powerful features, but not
594: yet everything that we envisioned. We certainly have achieved our
1.65 anton 595: execution speed goals (@pxref{Performance})@footnote{However, in 1998
596: the bar was raised when the major commercial Forth vendors switched to
597: native code compilers.}. It is free and available on many machines.
1.29 crook 598:
1.26 crook 599: @c ******************************************************************
1.48 anton 600: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 601: @chapter Gforth Environment
602: @cindex Gforth environment
1.21 crook 603:
1.45 crook 604: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 605: material in this chapter.
1.21 crook 606:
607: @menu
1.29 crook 608: * Invoking Gforth:: Getting in
609: * Leaving Gforth:: Getting out
610: * Command-line editing::
1.48 anton 611: * Environment variables:: that affect how Gforth starts up
1.29 crook 612: * Gforth Files:: What gets installed and where
1.112 anton 613: * Gforth in pipes::
1.48 anton 614: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 615: @end menu
616:
1.49 anton 617: For related information about the creation of images see @ref{Image Files}.
1.29 crook 618:
1.21 crook 619: @comment ----------------------------------------------
1.48 anton 620: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 621: @section Invoking Gforth
622: @cindex invoking Gforth
623: @cindex running Gforth
624: @cindex command-line options
625: @cindex options on the command line
626: @cindex flags on the command line
1.21 crook 627:
1.30 anton 628: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 629: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 630: will usually just say @code{gforth} -- this automatically loads the
631: default image file @file{gforth.fi}. In many other cases the default
632: Gforth image will be invoked like this:
1.21 crook 633: @example
1.30 anton 634: gforth [file | -e forth-code] ...
1.21 crook 635: @end example
1.29 crook 636: @noindent
637: This interprets the contents of the files and the Forth code in the order they
638: are given.
1.21 crook 639:
1.109 anton 640: In addition to the @command{gforth} engine, there is also an engine
641: called @command{gforth-fast}, which is faster, but gives less
642: informative error messages (@pxref{Error messages}) and may catch some
643: stack underflows later or not at all. You should use it for debugged,
644: performance-critical programs.
645:
646: Moreover, there is an engine called @command{gforth-itc}, which is
647: useful in some backwards-compatibility situations (@pxref{Direct or
648: Indirect Threaded?}).
1.30 anton 649:
1.29 crook 650: In general, the command line looks like this:
1.21 crook 651:
652: @example
1.30 anton 653: gforth[-fast] [engine options] [image options]
1.21 crook 654: @end example
655:
1.30 anton 656: The engine options must come before the rest of the command
1.29 crook 657: line. They are:
1.26 crook 658:
1.29 crook 659: @table @code
660: @cindex -i, command-line option
661: @cindex --image-file, command-line option
662: @item --image-file @i{file}
663: @itemx -i @i{file}
664: Loads the Forth image @i{file} instead of the default
665: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 666:
1.39 anton 667: @cindex --appl-image, command-line option
668: @item --appl-image @i{file}
669: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 670: to the image (instead of processing them as engine options). This is
671: useful for building executable application images on Unix, built with
1.39 anton 672: @code{gforthmi --application ...}.
673:
1.29 crook 674: @cindex --path, command-line option
675: @cindex -p, command-line option
676: @item --path @i{path}
677: @itemx -p @i{path}
678: Uses @i{path} for searching the image file and Forth source code files
679: instead of the default in the environment variable @code{GFORTHPATH} or
680: the path specified at installation time (e.g.,
681: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
682: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 683:
1.29 crook 684: @cindex --dictionary-size, command-line option
685: @cindex -m, command-line option
686: @cindex @i{size} parameters for command-line options
687: @cindex size of the dictionary and the stacks
688: @item --dictionary-size @i{size}
689: @itemx -m @i{size}
690: Allocate @i{size} space for the Forth dictionary space instead of
691: using the default specified in the image (typically 256K). The
692: @i{size} specification for this and subsequent options consists of
693: an integer and a unit (e.g.,
694: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
695: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
696: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
697: @code{e} is used.
1.21 crook 698:
1.29 crook 699: @cindex --data-stack-size, command-line option
700: @cindex -d, command-line option
701: @item --data-stack-size @i{size}
702: @itemx -d @i{size}
703: Allocate @i{size} space for the data stack instead of using the
704: default specified in the image (typically 16K).
1.21 crook 705:
1.29 crook 706: @cindex --return-stack-size, command-line option
707: @cindex -r, command-line option
708: @item --return-stack-size @i{size}
709: @itemx -r @i{size}
710: Allocate @i{size} space for the return stack instead of using the
711: default specified in the image (typically 15K).
1.21 crook 712:
1.29 crook 713: @cindex --fp-stack-size, command-line option
714: @cindex -f, command-line option
715: @item --fp-stack-size @i{size}
716: @itemx -f @i{size}
717: Allocate @i{size} space for the floating point stack instead of
718: using the default specified in the image (typically 15.5K). In this case
719: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 720:
1.48 anton 721: @cindex --locals-stack-size, command-line option
722: @cindex -l, command-line option
723: @item --locals-stack-size @i{size}
724: @itemx -l @i{size}
725: Allocate @i{size} space for the locals stack instead of using the
726: default specified in the image (typically 14.5K).
727:
728: @cindex -h, command-line option
729: @cindex --help, command-line option
730: @item --help
731: @itemx -h
732: Print a message about the command-line options
733:
734: @cindex -v, command-line option
735: @cindex --version, command-line option
736: @item --version
737: @itemx -v
738: Print version and exit
739:
740: @cindex --debug, command-line option
741: @item --debug
742: Print some information useful for debugging on startup.
743:
744: @cindex --offset-image, command-line option
745: @item --offset-image
746: Start the dictionary at a slightly different position than would be used
747: otherwise (useful for creating data-relocatable images,
748: @pxref{Data-Relocatable Image Files}).
749:
750: @cindex --no-offset-im, command-line option
751: @item --no-offset-im
752: Start the dictionary at the normal position.
753:
754: @cindex --clear-dictionary, command-line option
755: @item --clear-dictionary
756: Initialize all bytes in the dictionary to 0 before loading the image
757: (@pxref{Data-Relocatable Image Files}).
758:
759: @cindex --die-on-signal, command-line-option
760: @item --die-on-signal
761: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
762: or the segmentation violation SIGSEGV) by translating it into a Forth
763: @code{THROW}. With this option, Gforth exits if it receives such a
764: signal. This option is useful when the engine and/or the image might be
765: severely broken (such that it causes another signal before recovering
766: from the first); this option avoids endless loops in such cases.
1.109 anton 767:
1.119 anton 768: @cindex --no-dynamic, command-line option
769: @cindex --dynamic, command-line option
1.109 anton 770: @item --no-dynamic
771: @item --dynamic
772: Disable or enable dynamic superinstructions with replication
773: (@pxref{Dynamic Superinstructions}).
774:
1.119 anton 775: @cindex --no-super, command-line option
1.109 anton 776: @item --no-super
1.110 anton 777: Disable dynamic superinstructions, use just dynamic replication; this is
778: useful if you want to patch threaded code (@pxref{Dynamic
779: Superinstructions}).
1.119 anton 780:
781: @cindex --ss-number, command-line option
782: @item --ss-number=@var{N}
783: Use only the first @var{N} static superinstructions compiled into the
784: engine (default: use them all; note that only @code{gforth-fast} has
785: any). This option is useful for measuring the performance impact of
786: static superinstructions.
787:
788: @cindex --ss-min-..., command-line options
789: @item --ss-min-codesize
790: @item --ss-min-ls
791: @item --ss-min-lsu
792: @item --ss-min-nexts
793: Use specified metric for determining the cost of a primitive or static
794: superinstruction for static superinstruction selection. @code{Codesize}
795: is the native code size of the primive or static superinstruction,
796: @code{ls} is the number of loads and stores, @code{lsu} is the number of
797: loads, stores, and updates, and @code{nexts} is the number of dispatches
798: (not taking dynamic superinstructions into account), i.e. every
799: primitive or static superinstruction has cost 1. Default:
800: @code{codesize} if you use dynamic code generation, otherwise
801: @code{nexts}.
802:
803: @cindex --ss-greedy, command-line option
804: @item --ss-greedy
805: This option is useful for measuring the performance impact of static
806: superinstructions. By default, an optimal shortest-path algorithm is
807: used for selecting static superinstructions. With @option{--ss-greedy}
808: this algorithm is modified to assume that anything after the static
809: superinstruction currently under consideration is not combined into
810: static superinstructions. With @option{--ss-min-nexts} this produces
811: the same result as a greedy algorithm that always selects the longest
812: superinstruction available at the moment. E.g., if there are
813: superinstructions AB and BCD, then for the sequence A B C D the optimal
814: algorithm will select A BCD and the greedy algorithm will select AB C D.
815:
816: @cindex --print-metrics, command-line option
817: @item --print-metrics
818: Prints some metrics used during static superinstruction selection:
819: @code{code size} is the actual size of the dynamically generated code.
820: @code{Metric codesize} is the sum of the codesize metrics as seen by
821: static superinstruction selection; there is a difference from @code{code
822: size}, because not all primitives and static superinstructions are
823: compiled into dynamically generated code, and because of markers. The
824: other metrics correspond to the @option{ss-min-...} options. This
825: option is useful for evaluating the effects of the @option{--ss-...}
826: options.
1.109 anton 827:
1.48 anton 828: @end table
829:
830: @cindex loading files at startup
831: @cindex executing code on startup
832: @cindex batch processing with Gforth
833: As explained above, the image-specific command-line arguments for the
834: default image @file{gforth.fi} consist of a sequence of filenames and
835: @code{-e @var{forth-code}} options that are interpreted in the sequence
836: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 837: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
838: option takes only one argument; if you want to evaluate more Forth
839: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 840: after processing the command line (instead of entering interactive mode)
1.121 anton 841: append @code{-e bye} to the command line. You can also process the
842: command-line arguments with a Forth program (@pxref{OS command line
843: arguments}).
1.48 anton 844:
845: @cindex versions, invoking other versions of Gforth
846: If you have several versions of Gforth installed, @code{gforth} will
847: invoke the version that was installed last. @code{gforth-@i{version}}
848: invokes a specific version. If your environment contains the variable
849: @code{GFORTHPATH}, you may want to override it by using the
850: @code{--path} option.
851:
852: Not yet implemented:
853: On startup the system first executes the system initialization file
854: (unless the option @code{--no-init-file} is given; note that the system
855: resulting from using this option may not be ANS Forth conformant). Then
856: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 857: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 858: then in @file{~}, then in the normal path (see above).
859:
860:
861:
862: @comment ----------------------------------------------
863: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
864: @section Leaving Gforth
865: @cindex Gforth - leaving
866: @cindex leaving Gforth
867:
868: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
869: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
870: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 871: data are discarded. For ways of saving the state of the system before
872: leaving Gforth see @ref{Image Files}.
1.48 anton 873:
874: doc-bye
875:
876:
877: @comment ----------------------------------------------
1.65 anton 878: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 879: @section Command-line editing
880: @cindex command-line editing
881:
882: Gforth maintains a history file that records every line that you type to
883: the text interpreter. This file is preserved between sessions, and is
884: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
885: repeatedly you can recall successively older commands from this (or
886: previous) session(s). The full list of command-line editing facilities is:
887:
888: @itemize @bullet
889: @item
890: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
891: commands from the history buffer.
892: @item
893: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
894: from the history buffer.
895: @item
896: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
897: @item
898: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
899: @item
900: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
901: closing up the line.
902: @item
903: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
904: @item
905: @kbd{Ctrl-a} to move the cursor to the start of the line.
906: @item
907: @kbd{Ctrl-e} to move the cursor to the end of the line.
908: @item
909: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
910: line.
911: @item
912: @key{TAB} to step through all possible full-word completions of the word
913: currently being typed.
914: @item
1.65 anton 915: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
916: using @code{bye}).
917: @item
918: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
919: character under the cursor.
1.48 anton 920: @end itemize
921:
922: When editing, displayable characters are inserted to the left of the
923: cursor position; the line is always in ``insert'' (as opposed to
924: ``overstrike'') mode.
925:
926: @cindex history file
927: @cindex @file{.gforth-history}
928: On Unix systems, the history file is @file{~/.gforth-history} by
929: default@footnote{i.e. it is stored in the user's home directory.}. You
930: can find out the name and location of your history file using:
931:
932: @example
933: history-file type \ Unix-class systems
934:
935: history-file type \ Other systems
936: history-dir type
937: @end example
938:
939: If you enter long definitions by hand, you can use a text editor to
940: paste them out of the history file into a Forth source file for reuse at
941: a later time.
942:
943: Gforth never trims the size of the history file, so you should do this
944: periodically, if necessary.
945:
946: @comment this is all defined in history.fs
947: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
948: @comment chosen?
949:
950:
951: @comment ----------------------------------------------
1.65 anton 952: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 953: @section Environment variables
954: @cindex environment variables
955:
956: Gforth uses these environment variables:
957:
958: @itemize @bullet
959: @item
960: @cindex @code{GFORTHHIST} -- environment variable
961: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
962: open/create the history file, @file{.gforth-history}. Default:
963: @code{$HOME}.
964:
965: @item
966: @cindex @code{GFORTHPATH} -- environment variable
967: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
968: for Forth source-code files.
969:
970: @item
971: @cindex @code{GFORTH} -- environment variable
1.49 anton 972: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 973:
974: @item
975: @cindex @code{GFORTHD} -- environment variable
1.62 crook 976: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 977:
978: @item
979: @cindex @code{TMP}, @code{TEMP} - environment variable
980: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
981: location for the history file.
982: @end itemize
983:
984: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
985: @comment mentioning these.
986:
987: All the Gforth environment variables default to sensible values if they
988: are not set.
989:
990:
991: @comment ----------------------------------------------
1.112 anton 992: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 993: @section Gforth files
994: @cindex Gforth files
995:
996: When you install Gforth on a Unix system, it installs files in these
997: locations by default:
998:
999: @itemize @bullet
1000: @item
1001: @file{/usr/local/bin/gforth}
1002: @item
1003: @file{/usr/local/bin/gforthmi}
1004: @item
1005: @file{/usr/local/man/man1/gforth.1} - man page.
1006: @item
1007: @file{/usr/local/info} - the Info version of this manual.
1008: @item
1009: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1010: @item
1011: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1012: @item
1013: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1014: @item
1015: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1016: @end itemize
1017:
1018: You can select different places for installation by using
1019: @code{configure} options (listed with @code{configure --help}).
1020:
1021: @comment ----------------------------------------------
1.112 anton 1022: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1023: @section Gforth in pipes
1024: @cindex pipes, Gforth as part of
1025:
1026: Gforth can be used in pipes created elsewhere (described here). It can
1027: also create pipes on its own (@pxref{Pipes}).
1028:
1029: @cindex input from pipes
1030: If you pipe into Gforth, your program should read with @code{read-file}
1031: or @code{read-line} from @code{stdin} (@pxref{General files}).
1032: @code{Key} does not recognize the end of input. Words like
1033: @code{accept} echo the input and are therefore usually not useful for
1034: reading from a pipe. You have to invoke the Forth program with an OS
1035: command-line option, as you have no chance to use the Forth command line
1036: (the text interpreter would try to interpret the pipe input).
1037:
1038: @cindex output in pipes
1039: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1040:
1041: @cindex silent exiting from Gforth
1042: When you write to a pipe that has been closed at the other end, Gforth
1043: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1044: into the exception @code{broken-pipe-error}. If your application does
1045: not catch that exception, the system catches it and exits, usually
1046: silently (unless you were working on the Forth command line; then it
1047: prints an error message and exits). This is usually the desired
1048: behaviour.
1049:
1050: If you do not like this behaviour, you have to catch the exception
1051: yourself, and react to it.
1052:
1053: Here's an example of an invocation of Gforth that is usable in a pipe:
1054:
1055: @example
1056: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1057: type repeat ; foo bye"
1058: @end example
1059:
1060: This example just copies the input verbatim to the output. A very
1061: simple pipe containing this example looks like this:
1062:
1063: @example
1064: cat startup.fs |
1065: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1066: type repeat ; foo bye"|
1067: head
1068: @end example
1069:
1070: @cindex stderr and pipes
1071: Pipes involving Gforth's @code{stderr} output do not work.
1072:
1073: @comment ----------------------------------------------
1074: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1075: @section Startup speed
1076: @cindex Startup speed
1077: @cindex speed, startup
1078:
1079: If Gforth is used for CGI scripts or in shell scripts, its startup
1080: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1081: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1082: system time.
1083:
1084: If startup speed is a problem, you may consider the following ways to
1085: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1086: (for example, by using Fast-CGI).
1.48 anton 1087:
1.112 anton 1088: An easy step that influences Gforth startup speed is the use of the
1089: @option{--no-dynamic} option; this decreases image loading speed, but
1090: increases compile-time and run-time.
1091:
1092: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1093: building it with @code{XLDFLAGS=-static}. This requires more memory for
1094: the code and will therefore slow down the first invocation, but
1095: subsequent invocations avoid the dynamic linking overhead. Another
1096: disadvantage is that Gforth won't profit from library upgrades. As a
1097: result, @code{gforth-static -e bye} takes about 17.1ms user and
1098: 8.2ms system time.
1099:
1100: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1101: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1102: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1103: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1104: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1105: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1106: address for the dictionary, for whatever reason; so you better provide a
1107: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1108: bye} takes about 15.3ms user and 7.5ms system time.
1109:
1110: The final step is to disable dictionary hashing in Gforth. Gforth
1111: builds the hash table on startup, which takes much of the startup
1112: overhead. You can do this by commenting out the @code{include hash.fs}
1113: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1114: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1115: The disadvantages are that functionality like @code{table} and
1116: @code{ekey} is missing and that text interpretation (e.g., compiling)
1117: now takes much longer. So, you should only use this method if there is
1118: no significant text interpretation to perform (the script should be
1.62 crook 1119: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1120: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1121:
1122: @c ******************************************************************
1123: @node Tutorial, Introduction, Gforth Environment, Top
1124: @chapter Forth Tutorial
1125: @cindex Tutorial
1126: @cindex Forth Tutorial
1127:
1.67 anton 1128: @c Topics from nac's Introduction that could be mentioned:
1129: @c press <ret> after each line
1130: @c Prompt
1131: @c numbers vs. words in dictionary on text interpretation
1132: @c what happens on redefinition
1133: @c parsing words (in particular, defining words)
1134:
1.83 anton 1135: The difference of this chapter from the Introduction
1136: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1137: be used while sitting in front of a computer, and covers much more
1138: material, but does not explain how the Forth system works.
1139:
1.62 crook 1140: This tutorial can be used with any ANS-compliant Forth; any
1141: Gforth-specific features are marked as such and you can skip them if you
1142: work with another Forth. This tutorial does not explain all features of
1143: Forth, just enough to get you started and give you some ideas about the
1144: facilities available in Forth. Read the rest of the manual and the
1145: standard when you are through this.
1.48 anton 1146:
1147: The intended way to use this tutorial is that you work through it while
1148: sitting in front of the console, take a look at the examples and predict
1149: what they will do, then try them out; if the outcome is not as expected,
1150: find out why (e.g., by trying out variations of the example), so you
1151: understand what's going on. There are also some assignments that you
1152: should solve.
1153:
1154: This tutorial assumes that you have programmed before and know what,
1155: e.g., a loop is.
1156:
1157: @c !! explain compat library
1158:
1159: @menu
1160: * Starting Gforth Tutorial::
1161: * Syntax Tutorial::
1162: * Crash Course Tutorial::
1163: * Stack Tutorial::
1164: * Arithmetics Tutorial::
1165: * Stack Manipulation Tutorial::
1166: * Using files for Forth code Tutorial::
1167: * Comments Tutorial::
1168: * Colon Definitions Tutorial::
1169: * Decompilation Tutorial::
1170: * Stack-Effect Comments Tutorial::
1171: * Types Tutorial::
1172: * Factoring Tutorial::
1173: * Designing the stack effect Tutorial::
1174: * Local Variables Tutorial::
1175: * Conditional execution Tutorial::
1176: * Flags and Comparisons Tutorial::
1177: * General Loops Tutorial::
1178: * Counted loops Tutorial::
1179: * Recursion Tutorial::
1180: * Leaving definitions or loops Tutorial::
1181: * Return Stack Tutorial::
1182: * Memory Tutorial::
1183: * Characters and Strings Tutorial::
1184: * Alignment Tutorial::
1.87 anton 1185: * Files Tutorial::
1.48 anton 1186: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1187: * Execution Tokens Tutorial::
1188: * Exceptions Tutorial::
1189: * Defining Words Tutorial::
1190: * Arrays and Records Tutorial::
1191: * POSTPONE Tutorial::
1192: * Literal Tutorial::
1193: * Advanced macros Tutorial::
1194: * Compilation Tokens Tutorial::
1195: * Wordlists and Search Order Tutorial::
1196: @end menu
1197:
1198: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1199: @section Starting Gforth
1.66 anton 1200: @cindex starting Gforth tutorial
1.48 anton 1201: You can start Gforth by typing its name:
1202:
1203: @example
1204: gforth
1205: @end example
1206:
1207: That puts you into interactive mode; you can leave Gforth by typing
1208: @code{bye}. While in Gforth, you can edit the command line and access
1209: the command line history with cursor keys, similar to bash.
1210:
1211:
1212: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1213: @section Syntax
1.66 anton 1214: @cindex syntax tutorial
1.48 anton 1215:
1216: A @dfn{word} is a sequence of arbitrary characters (expcept white
1217: space). Words are separated by white space. E.g., each of the
1218: following lines contains exactly one word:
1219:
1220: @example
1221: word
1222: !@@#$%^&*()
1223: 1234567890
1224: 5!a
1225: @end example
1226:
1227: A frequent beginner's error is to leave away necessary white space,
1228: resulting in an error like @samp{Undefined word}; so if you see such an
1229: error, check if you have put spaces wherever necessary.
1230:
1231: @example
1232: ." hello, world" \ correct
1233: ."hello, world" \ gives an "Undefined word" error
1234: @end example
1235:
1.65 anton 1236: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1237: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1238: your system is case-sensitive, you may have to type all the examples
1239: given here in upper case.
1240:
1241:
1242: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1243: @section Crash Course
1244:
1245: Type
1246:
1247: @example
1248: 0 0 !
1249: here execute
1250: ' catch >body 20 erase abort
1251: ' (quit) >body 20 erase
1252: @end example
1253:
1254: The last two examples are guaranteed to destroy parts of Gforth (and
1255: most other systems), so you better leave Gforth afterwards (if it has
1256: not finished by itself). On some systems you may have to kill gforth
1257: from outside (e.g., in Unix with @code{kill}).
1258:
1259: Now that you know how to produce crashes (and that there's not much to
1260: them), let's learn how to produce meaningful programs.
1261:
1262:
1263: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1264: @section Stack
1.66 anton 1265: @cindex stack tutorial
1.48 anton 1266:
1267: The most obvious feature of Forth is the stack. When you type in a
1268: number, it is pushed on the stack. You can display the content of the
1269: stack with @code{.s}.
1270:
1271: @example
1272: 1 2 .s
1273: 3 .s
1274: @end example
1275:
1276: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1277: appear in @code{.s} output as they appeared in the input.
1278:
1279: You can print the top of stack element with @code{.}.
1280:
1281: @example
1282: 1 2 3 . . .
1283: @end example
1284:
1285: In general, words consume their stack arguments (@code{.s} is an
1286: exception).
1287:
1288: @assignment
1289: What does the stack contain after @code{5 6 7 .}?
1290: @endassignment
1291:
1292:
1293: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1294: @section Arithmetics
1.66 anton 1295: @cindex arithmetics tutorial
1.48 anton 1296:
1297: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1298: operate on the top two stack items:
1299:
1300: @example
1.67 anton 1301: 2 2 .s
1302: + .s
1303: .
1.48 anton 1304: 2 1 - .
1305: 7 3 mod .
1306: @end example
1307:
1308: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1309: as in the corresponding infix expression (this is generally the case in
1310: Forth).
1311:
1312: Parentheses are superfluous (and not available), because the order of
1313: the words unambiguously determines the order of evaluation and the
1314: operands:
1315:
1316: @example
1317: 3 4 + 5 * .
1318: 3 4 5 * + .
1319: @end example
1320:
1321: @assignment
1322: What are the infix expressions corresponding to the Forth code above?
1323: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1324: known as Postfix or RPN (Reverse Polish Notation).}.
1325: @endassignment
1326:
1327: To change the sign, use @code{negate}:
1328:
1329: @example
1330: 2 negate .
1331: @end example
1332:
1333: @assignment
1334: Convert -(-3)*4-5 to Forth.
1335: @endassignment
1336:
1337: @code{/mod} performs both @code{/} and @code{mod}.
1338:
1339: @example
1340: 7 3 /mod . .
1341: @end example
1342:
1.66 anton 1343: Reference: @ref{Arithmetic}.
1344:
1345:
1.48 anton 1346: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1347: @section Stack Manipulation
1.66 anton 1348: @cindex stack manipulation tutorial
1.48 anton 1349:
1350: Stack manipulation words rearrange the data on the stack.
1351:
1352: @example
1353: 1 .s drop .s
1354: 1 .s dup .s drop drop .s
1355: 1 2 .s over .s drop drop drop
1356: 1 2 .s swap .s drop drop
1357: 1 2 3 .s rot .s drop drop drop
1358: @end example
1359:
1360: These are the most important stack manipulation words. There are also
1361: variants that manipulate twice as many stack items:
1362:
1363: @example
1364: 1 2 3 4 .s 2swap .s 2drop 2drop
1365: @end example
1366:
1367: Two more stack manipulation words are:
1368:
1369: @example
1370: 1 2 .s nip .s drop
1371: 1 2 .s tuck .s 2drop drop
1372: @end example
1373:
1374: @assignment
1375: Replace @code{nip} and @code{tuck} with combinations of other stack
1376: manipulation words.
1377:
1378: @example
1379: Given: How do you get:
1380: 1 2 3 3 2 1
1381: 1 2 3 1 2 3 2
1382: 1 2 3 1 2 3 3
1383: 1 2 3 1 3 3
1384: 1 2 3 2 1 3
1385: 1 2 3 4 4 3 2 1
1386: 1 2 3 1 2 3 1 2 3
1387: 1 2 3 4 1 2 3 4 1 2
1388: 1 2 3
1389: 1 2 3 1 2 3 4
1390: 1 2 3 1 3
1391: @end example
1392: @endassignment
1393:
1394: @example
1395: 5 dup * .
1396: @end example
1397:
1398: @assignment
1399: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1400: Write a piece of Forth code that expects two numbers on the stack
1401: (@var{a} and @var{b}, with @var{b} on top) and computes
1402: @code{(a-b)(a+1)}.
1403: @endassignment
1404:
1.66 anton 1405: Reference: @ref{Stack Manipulation}.
1406:
1407:
1.48 anton 1408: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1409: @section Using files for Forth code
1.66 anton 1410: @cindex loading Forth code, tutorial
1411: @cindex files containing Forth code, tutorial
1.48 anton 1412:
1413: While working at the Forth command line is convenient for one-line
1414: examples and short one-off code, you probably want to store your source
1415: code in files for convenient editing and persistence. You can use your
1416: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1417: Gforth}) to create @var{file.fs} and use
1.48 anton 1418:
1419: @example
1.102 anton 1420: s" @var{file.fs}" included
1.48 anton 1421: @end example
1422:
1423: to load it into your Forth system. The file name extension I use for
1424: Forth files is @samp{.fs}.
1425:
1426: You can easily start Gforth with some files loaded like this:
1427:
1428: @example
1.102 anton 1429: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1430: @end example
1431:
1432: If an error occurs during loading these files, Gforth terminates,
1433: whereas an error during @code{INCLUDED} within Gforth usually gives you
1434: a Gforth command line. Starting the Forth system every time gives you a
1435: clean start every time, without interference from the results of earlier
1436: tries.
1437:
1438: I often put all the tests in a file, then load the code and run the
1439: tests with
1440:
1441: @example
1.102 anton 1442: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1443: @end example
1444:
1445: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1446: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1447: restart this command without ado.
1448:
1449: The advantage of this approach is that the tests can be repeated easily
1450: every time the program ist changed, making it easy to catch bugs
1451: introduced by the change.
1452:
1.66 anton 1453: Reference: @ref{Forth source files}.
1454:
1.48 anton 1455:
1456: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1457: @section Comments
1.66 anton 1458: @cindex comments tutorial
1.48 anton 1459:
1460: @example
1461: \ That's a comment; it ends at the end of the line
1462: ( Another comment; it ends here: ) .s
1463: @end example
1464:
1465: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1466: separated with white space from the following text.
1467:
1468: @example
1469: \This gives an "Undefined word" error
1470: @end example
1471:
1472: The first @code{)} ends a comment started with @code{(}, so you cannot
1473: nest @code{(}-comments; and you cannot comment out text containing a
1474: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1475: avoid @code{)} in word names.}.
1476:
1477: I use @code{\}-comments for descriptive text and for commenting out code
1478: of one or more line; I use @code{(}-comments for describing the stack
1479: effect, the stack contents, or for commenting out sub-line pieces of
1480: code.
1481:
1482: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1483: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1484: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1485: with @kbd{M-q}.
1486:
1.66 anton 1487: Reference: @ref{Comments}.
1488:
1.48 anton 1489:
1490: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1491: @section Colon Definitions
1.66 anton 1492: @cindex colon definitions, tutorial
1493: @cindex definitions, tutorial
1494: @cindex procedures, tutorial
1495: @cindex functions, tutorial
1.48 anton 1496:
1497: are similar to procedures and functions in other programming languages.
1498:
1499: @example
1500: : squared ( n -- n^2 )
1501: dup * ;
1502: 5 squared .
1503: 7 squared .
1504: @end example
1505:
1506: @code{:} starts the colon definition; its name is @code{squared}. The
1507: following comment describes its stack effect. The words @code{dup *}
1508: are not executed, but compiled into the definition. @code{;} ends the
1509: colon definition.
1510:
1511: The newly-defined word can be used like any other word, including using
1512: it in other definitions:
1513:
1514: @example
1515: : cubed ( n -- n^3 )
1516: dup squared * ;
1517: -5 cubed .
1518: : fourth-power ( n -- n^4 )
1519: squared squared ;
1520: 3 fourth-power .
1521: @end example
1522:
1523: @assignment
1524: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1525: @code{/mod} in terms of other Forth words, and check if they work (hint:
1526: test your tests on the originals first). Don't let the
1527: @samp{redefined}-Messages spook you, they are just warnings.
1528: @endassignment
1529:
1.66 anton 1530: Reference: @ref{Colon Definitions}.
1531:
1.48 anton 1532:
1533: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1534: @section Decompilation
1.66 anton 1535: @cindex decompilation tutorial
1536: @cindex see tutorial
1.48 anton 1537:
1538: You can decompile colon definitions with @code{see}:
1539:
1540: @example
1541: see squared
1542: see cubed
1543: @end example
1544:
1545: In Gforth @code{see} shows you a reconstruction of the source code from
1546: the executable code. Informations that were present in the source, but
1547: not in the executable code, are lost (e.g., comments).
1548:
1.65 anton 1549: You can also decompile the predefined words:
1550:
1551: @example
1552: see .
1553: see +
1554: @end example
1555:
1556:
1.48 anton 1557: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1558: @section Stack-Effect Comments
1.66 anton 1559: @cindex stack-effect comments, tutorial
1560: @cindex --, tutorial
1.48 anton 1561: By convention the comment after the name of a definition describes the
1562: stack effect: The part in from of the @samp{--} describes the state of
1563: the stack before the execution of the definition, i.e., the parameters
1564: that are passed into the colon definition; the part behind the @samp{--}
1565: is the state of the stack after the execution of the definition, i.e.,
1566: the results of the definition. The stack comment only shows the top
1567: stack items that the definition accesses and/or changes.
1568:
1569: You should put a correct stack effect on every definition, even if it is
1570: just @code{( -- )}. You should also add some descriptive comment to
1571: more complicated words (I usually do this in the lines following
1572: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1573: you have to work through every definition before you can understand
1.48 anton 1574: any).
1575:
1576: @assignment
1577: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1578: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1579: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1580: are done, you can compare your stack effects to those in this manual
1.48 anton 1581: (@pxref{Word Index}).
1582: @endassignment
1583:
1584: Sometimes programmers put comments at various places in colon
1585: definitions that describe the contents of the stack at that place (stack
1586: comments); i.e., they are like the first part of a stack-effect
1587: comment. E.g.,
1588:
1589: @example
1590: : cubed ( n -- n^3 )
1591: dup squared ( n n^2 ) * ;
1592: @end example
1593:
1594: In this case the stack comment is pretty superfluous, because the word
1595: is simple enough. If you think it would be a good idea to add such a
1596: comment to increase readability, you should also consider factoring the
1597: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1598: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1599: however, if you decide not to refactor it, then having such a comment is
1600: better than not having it.
1601:
1602: The names of the stack items in stack-effect and stack comments in the
1603: standard, in this manual, and in many programs specify the type through
1604: a type prefix, similar to Fortran and Hungarian notation. The most
1605: frequent prefixes are:
1606:
1607: @table @code
1608: @item n
1609: signed integer
1610: @item u
1611: unsigned integer
1612: @item c
1613: character
1614: @item f
1615: Boolean flags, i.e. @code{false} or @code{true}.
1616: @item a-addr,a-
1617: Cell-aligned address
1618: @item c-addr,c-
1619: Char-aligned address (note that a Char may have two bytes in Windows NT)
1620: @item xt
1621: Execution token, same size as Cell
1622: @item w,x
1623: Cell, can contain an integer or an address. It usually takes 32, 64 or
1624: 16 bits (depending on your platform and Forth system). A cell is more
1625: commonly known as machine word, but the term @emph{word} already means
1626: something different in Forth.
1627: @item d
1628: signed double-cell integer
1629: @item ud
1630: unsigned double-cell integer
1631: @item r
1632: Float (on the FP stack)
1633: @end table
1634:
1635: You can find a more complete list in @ref{Notation}.
1636:
1637: @assignment
1638: Write stack-effect comments for all definitions you have written up to
1639: now.
1640: @endassignment
1641:
1642:
1643: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1644: @section Types
1.66 anton 1645: @cindex types tutorial
1.48 anton 1646:
1647: In Forth the names of the operations are not overloaded; so similar
1648: operations on different types need different names; e.g., @code{+} adds
1649: integers, and you have to use @code{f+} to add floating-point numbers.
1650: The following prefixes are often used for related operations on
1651: different types:
1652:
1653: @table @code
1654: @item (none)
1655: signed integer
1656: @item u
1657: unsigned integer
1658: @item c
1659: character
1660: @item d
1661: signed double-cell integer
1662: @item ud, du
1663: unsigned double-cell integer
1664: @item 2
1665: two cells (not-necessarily double-cell numbers)
1666: @item m, um
1667: mixed single-cell and double-cell operations
1668: @item f
1669: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1670: and @samp{r} represents FP numbers).
1.48 anton 1671: @end table
1672:
1673: If there are no differences between the signed and the unsigned variant
1674: (e.g., for @code{+}), there is only the prefix-less variant.
1675:
1676: Forth does not perform type checking, neither at compile time, nor at
1677: run time. If you use the wrong oeration, the data are interpreted
1678: incorrectly:
1679:
1680: @example
1681: -1 u.
1682: @end example
1683:
1684: If you have only experience with type-checked languages until now, and
1685: have heard how important type-checking is, don't panic! In my
1686: experience (and that of other Forthers), type errors in Forth code are
1687: usually easy to find (once you get used to it), the increased vigilance
1688: of the programmer tends to catch some harder errors in addition to most
1689: type errors, and you never have to work around the type system, so in
1690: most situations the lack of type-checking seems to be a win (projects to
1691: add type checking to Forth have not caught on).
1692:
1693:
1694: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1695: @section Factoring
1.66 anton 1696: @cindex factoring tutorial
1.48 anton 1697:
1698: If you try to write longer definitions, you will soon find it hard to
1699: keep track of the stack contents. Therefore, good Forth programmers
1700: tend to write only short definitions (e.g., three lines). The art of
1701: finding meaningful short definitions is known as factoring (as in
1702: factoring polynomials).
1703:
1704: Well-factored programs offer additional advantages: smaller, more
1705: general words, are easier to test and debug and can be reused more and
1706: better than larger, specialized words.
1707:
1708: So, if you run into difficulties with stack management, when writing
1709: code, try to define meaningful factors for the word, and define the word
1710: in terms of those. Even if a factor contains only two words, it is
1711: often helpful.
1712:
1.65 anton 1713: Good factoring is not easy, and it takes some practice to get the knack
1714: for it; but even experienced Forth programmers often don't find the
1715: right solution right away, but only when rewriting the program. So, if
1716: you don't come up with a good solution immediately, keep trying, don't
1717: despair.
1.48 anton 1718:
1719: @c example !!
1720:
1721:
1722: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1723: @section Designing the stack effect
1.66 anton 1724: @cindex Stack effect design, tutorial
1725: @cindex design of stack effects, tutorial
1.48 anton 1726:
1727: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1728: function; and since there is only one result, you don't have to deal with
1.48 anton 1729: the order of results, either.
1730:
1.117 anton 1731: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1732: parameter and result order of a definition is important and should be
1733: designed well. The general guideline is to design the stack effect such
1734: that the word is simple to use in most cases, even if that complicates
1735: the implementation of the word. Some concrete rules are:
1736:
1737: @itemize @bullet
1738:
1739: @item
1740: Words consume all of their parameters (e.g., @code{.}).
1741:
1742: @item
1743: If there is a convention on the order of parameters (e.g., from
1744: mathematics or another programming language), stick with it (e.g.,
1745: @code{-}).
1746:
1747: @item
1748: If one parameter usually requires only a short computation (e.g., it is
1749: a constant), pass it on the top of the stack. Conversely, parameters
1750: that usually require a long sequence of code to compute should be passed
1751: as the bottom (i.e., first) parameter. This makes the code easier to
1752: read, because reader does not need to keep track of the bottom item
1753: through a long sequence of code (or, alternatively, through stack
1.49 anton 1754: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1755: address on top of the stack because it is usually simpler to compute
1756: than the stored value (often the address is just a variable).
1757:
1758: @item
1759: Similarly, results that are usually consumed quickly should be returned
1760: on the top of stack, whereas a result that is often used in long
1761: computations should be passed as bottom result. E.g., the file words
1762: like @code{open-file} return the error code on the top of stack, because
1763: it is usually consumed quickly by @code{throw}; moreover, the error code
1764: has to be checked before doing anything with the other results.
1765:
1766: @end itemize
1767:
1768: These rules are just general guidelines, don't lose sight of the overall
1769: goal to make the words easy to use. E.g., if the convention rule
1770: conflicts with the computation-length rule, you might decide in favour
1771: of the convention if the word will be used rarely, and in favour of the
1772: computation-length rule if the word will be used frequently (because
1773: with frequent use the cost of breaking the computation-length rule would
1774: be quite high, and frequent use makes it easier to remember an
1775: unconventional order).
1776:
1777: @c example !! structure package
1778:
1.65 anton 1779:
1.48 anton 1780: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1781: @section Local Variables
1.66 anton 1782: @cindex local variables, tutorial
1.48 anton 1783:
1784: You can define local variables (@emph{locals}) in a colon definition:
1785:
1786: @example
1787: : swap @{ a b -- b a @}
1788: b a ;
1789: 1 2 swap .s 2drop
1790: @end example
1791:
1792: (If your Forth system does not support this syntax, include
1793: @file{compat/anslocals.fs} first).
1794:
1795: In this example @code{@{ a b -- b a @}} is the locals definition; it
1796: takes two cells from the stack, puts the top of stack in @code{b} and
1797: the next stack element in @code{a}. @code{--} starts a comment ending
1798: with @code{@}}. After the locals definition, using the name of the
1799: local will push its value on the stack. You can leave the comment
1800: part (@code{-- b a}) away:
1801:
1802: @example
1803: : swap ( x1 x2 -- x2 x1 )
1804: @{ a b @} b a ;
1805: @end example
1806:
1807: In Gforth you can have several locals definitions, anywhere in a colon
1808: definition; in contrast, in a standard program you can have only one
1809: locals definition per colon definition, and that locals definition must
1810: be outside any controll structure.
1811:
1812: With locals you can write slightly longer definitions without running
1813: into stack trouble. However, I recommend trying to write colon
1814: definitions without locals for exercise purposes to help you gain the
1815: essential factoring skills.
1816:
1817: @assignment
1818: Rewrite your definitions until now with locals
1819: @endassignment
1820:
1.66 anton 1821: Reference: @ref{Locals}.
1822:
1.48 anton 1823:
1824: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1825: @section Conditional execution
1.66 anton 1826: @cindex conditionals, tutorial
1827: @cindex if, tutorial
1.48 anton 1828:
1829: In Forth you can use control structures only inside colon definitions.
1830: An @code{if}-structure looks like this:
1831:
1832: @example
1833: : abs ( n1 -- +n2 )
1834: dup 0 < if
1835: negate
1836: endif ;
1837: 5 abs .
1838: -5 abs .
1839: @end example
1840:
1841: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1842: the following code is performed, otherwise execution continues after the
1.51 pazsan 1843: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1844: elements and prioduces a flag:
1845:
1846: @example
1847: 1 2 < .
1848: 2 1 < .
1849: 1 1 < .
1850: @end example
1851:
1852: Actually the standard name for @code{endif} is @code{then}. This
1853: tutorial presents the examples using @code{endif}, because this is often
1854: less confusing for people familiar with other programming languages
1855: where @code{then} has a different meaning. If your system does not have
1856: @code{endif}, define it with
1857:
1858: @example
1859: : endif postpone then ; immediate
1860: @end example
1861:
1862: You can optionally use an @code{else}-part:
1863:
1864: @example
1865: : min ( n1 n2 -- n )
1866: 2dup < if
1867: drop
1868: else
1869: nip
1870: endif ;
1871: 2 3 min .
1872: 3 2 min .
1873: @end example
1874:
1875: @assignment
1876: Write @code{min} without @code{else}-part (hint: what's the definition
1877: of @code{nip}?).
1878: @endassignment
1879:
1.66 anton 1880: Reference: @ref{Selection}.
1881:
1.48 anton 1882:
1883: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1884: @section Flags and Comparisons
1.66 anton 1885: @cindex flags tutorial
1886: @cindex comparison tutorial
1.48 anton 1887:
1888: In a false-flag all bits are clear (0 when interpreted as integer). In
1889: a canonical true-flag all bits are set (-1 as a twos-complement signed
1890: integer); in many contexts (e.g., @code{if}) any non-zero value is
1891: treated as true flag.
1892:
1893: @example
1894: false .
1895: true .
1896: true hex u. decimal
1897: @end example
1898:
1899: Comparison words produce canonical flags:
1900:
1901: @example
1902: 1 1 = .
1903: 1 0= .
1904: 0 1 < .
1905: 0 0 < .
1906: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1907: -1 1 < .
1908: @end example
1909:
1.66 anton 1910: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1911: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1912: these combinations are standard (for details see the standard,
1913: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1914:
1915: You can use @code{and or xor invert} can be used as operations on
1916: canonical flags. Actually they are bitwise operations:
1917:
1918: @example
1919: 1 2 and .
1920: 1 2 or .
1921: 1 3 xor .
1922: 1 invert .
1923: @end example
1924:
1925: You can convert a zero/non-zero flag into a canonical flag with
1926: @code{0<>} (and complement it on the way with @code{0=}).
1927:
1928: @example
1929: 1 0= .
1930: 1 0<> .
1931: @end example
1932:
1.65 anton 1933: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1934: operation of the Boolean operations to avoid @code{if}s:
1935:
1936: @example
1937: : foo ( n1 -- n2 )
1938: 0= if
1939: 14
1940: else
1941: 0
1942: endif ;
1943: 0 foo .
1944: 1 foo .
1945:
1946: : foo ( n1 -- n2 )
1947: 0= 14 and ;
1948: 0 foo .
1949: 1 foo .
1950: @end example
1951:
1952: @assignment
1953: Write @code{min} without @code{if}.
1954: @endassignment
1955:
1.66 anton 1956: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1957: @ref{Bitwise operations}.
1958:
1.48 anton 1959:
1960: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1961: @section General Loops
1.66 anton 1962: @cindex loops, indefinite, tutorial
1.48 anton 1963:
1964: The endless loop is the most simple one:
1965:
1966: @example
1967: : endless ( -- )
1968: 0 begin
1969: dup . 1+
1970: again ;
1971: endless
1972: @end example
1973:
1974: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
1975: does nothing at run-time, @code{again} jumps back to @code{begin}.
1976:
1977: A loop with one exit at any place looks like this:
1978:
1979: @example
1980: : log2 ( +n1 -- n2 )
1981: \ logarithmus dualis of n1>0, rounded down to the next integer
1982: assert( dup 0> )
1983: 2/ 0 begin
1984: over 0> while
1985: 1+ swap 2/ swap
1986: repeat
1987: nip ;
1988: 7 log2 .
1989: 8 log2 .
1990: @end example
1991:
1992: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 1993: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 1994: continues behind the @code{while}. @code{Repeat} jumps back to
1995: @code{begin}, just like @code{again}.
1996:
1997: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 1998: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 1999: one bit (arithmetic shift right):
2000:
2001: @example
2002: -5 2 / .
2003: -5 2/ .
2004: @end example
2005:
2006: @code{assert(} is no standard word, but you can get it on systems other
2007: then Gforth by including @file{compat/assert.fs}. You can see what it
2008: does by trying
2009:
2010: @example
2011: 0 log2 .
2012: @end example
2013:
2014: Here's a loop with an exit at the end:
2015:
2016: @example
2017: : log2 ( +n1 -- n2 )
2018: \ logarithmus dualis of n1>0, rounded down to the next integer
2019: assert( dup 0 > )
2020: -1 begin
2021: 1+ swap 2/ swap
2022: over 0 <=
2023: until
2024: nip ;
2025: @end example
2026:
2027: @code{Until} consumes a flag; if it is non-zero, execution continues at
2028: the @code{begin}, otherwise after the @code{until}.
2029:
2030: @assignment
2031: Write a definition for computing the greatest common divisor.
2032: @endassignment
2033:
1.66 anton 2034: Reference: @ref{Simple Loops}.
2035:
1.48 anton 2036:
2037: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2038: @section Counted loops
1.66 anton 2039: @cindex loops, counted, tutorial
1.48 anton 2040:
2041: @example
2042: : ^ ( n1 u -- n )
2043: \ n = the uth power of u1
2044: 1 swap 0 u+do
2045: over *
2046: loop
2047: nip ;
2048: 3 2 ^ .
2049: 4 3 ^ .
2050: @end example
2051:
2052: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2053: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2054: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2055: times (or not at all, if @code{u3-u4<0}).
2056:
2057: You can see the stack effect design rules at work in the stack effect of
2058: the loop start words: Since the start value of the loop is more
2059: frequently constant than the end value, the start value is passed on
2060: the top-of-stack.
2061:
2062: You can access the counter of a counted loop with @code{i}:
2063:
2064: @example
2065: : fac ( u -- u! )
2066: 1 swap 1+ 1 u+do
2067: i *
2068: loop ;
2069: 5 fac .
2070: 7 fac .
2071: @end example
2072:
2073: There is also @code{+do}, which expects signed numbers (important for
2074: deciding whether to enter the loop).
2075:
2076: @assignment
2077: Write a definition for computing the nth Fibonacci number.
2078: @endassignment
2079:
1.65 anton 2080: You can also use increments other than 1:
2081:
2082: @example
2083: : up2 ( n1 n2 -- )
2084: +do
2085: i .
2086: 2 +loop ;
2087: 10 0 up2
2088:
2089: : down2 ( n1 n2 -- )
2090: -do
2091: i .
2092: 2 -loop ;
2093: 0 10 down2
2094: @end example
1.48 anton 2095:
1.66 anton 2096: Reference: @ref{Counted Loops}.
2097:
1.48 anton 2098:
2099: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2100: @section Recursion
1.66 anton 2101: @cindex recursion tutorial
1.48 anton 2102:
2103: Usually the name of a definition is not visible in the definition; but
2104: earlier definitions are usually visible:
2105:
2106: @example
2107: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2108: : / ( n1 n2 -- n )
2109: dup 0= if
2110: -10 throw \ report division by zero
2111: endif
2112: / \ old version
2113: ;
2114: 1 0 /
2115: @end example
2116:
2117: For recursive definitions you can use @code{recursive} (non-standard) or
2118: @code{recurse}:
2119:
2120: @example
2121: : fac1 ( n -- n! ) recursive
2122: dup 0> if
2123: dup 1- fac1 *
2124: else
2125: drop 1
2126: endif ;
2127: 7 fac1 .
2128:
2129: : fac2 ( n -- n! )
2130: dup 0> if
2131: dup 1- recurse *
2132: else
2133: drop 1
2134: endif ;
2135: 8 fac2 .
2136: @end example
2137:
2138: @assignment
2139: Write a recursive definition for computing the nth Fibonacci number.
2140: @endassignment
2141:
1.66 anton 2142: Reference (including indirect recursion): @xref{Calls and returns}.
2143:
1.48 anton 2144:
2145: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2146: @section Leaving definitions or loops
1.66 anton 2147: @cindex leaving definitions, tutorial
2148: @cindex leaving loops, tutorial
1.48 anton 2149:
2150: @code{EXIT} exits the current definition right away. For every counted
2151: loop that is left in this way, an @code{UNLOOP} has to be performed
2152: before the @code{EXIT}:
2153:
2154: @c !! real examples
2155: @example
2156: : ...
2157: ... u+do
2158: ... if
2159: ... unloop exit
2160: endif
2161: ...
2162: loop
2163: ... ;
2164: @end example
2165:
2166: @code{LEAVE} leaves the innermost counted loop right away:
2167:
2168: @example
2169: : ...
2170: ... u+do
2171: ... if
2172: ... leave
2173: endif
2174: ...
2175: loop
2176: ... ;
2177: @end example
2178:
1.65 anton 2179: @c !! example
1.48 anton 2180:
1.66 anton 2181: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2182:
2183:
1.48 anton 2184: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2185: @section Return Stack
1.66 anton 2186: @cindex return stack tutorial
1.48 anton 2187:
2188: In addition to the data stack Forth also has a second stack, the return
2189: stack; most Forth systems store the return addresses of procedure calls
2190: there (thus its name). Programmers can also use this stack:
2191:
2192: @example
2193: : foo ( n1 n2 -- )
2194: .s
2195: >r .s
1.50 anton 2196: r@@ .
1.48 anton 2197: >r .s
1.50 anton 2198: r@@ .
1.48 anton 2199: r> .
1.50 anton 2200: r@@ .
1.48 anton 2201: r> . ;
2202: 1 2 foo
2203: @end example
2204:
2205: @code{>r} takes an element from the data stack and pushes it onto the
2206: return stack; conversely, @code{r>} moves an elementm from the return to
2207: the data stack; @code{r@@} pushes a copy of the top of the return stack
2208: on the return stack.
2209:
2210: Forth programmers usually use the return stack for storing data
2211: temporarily, if using the data stack alone would be too complex, and
2212: factoring and locals are not an option:
2213:
2214: @example
2215: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2216: rot >r rot r> ;
2217: @end example
2218:
2219: The return address of the definition and the loop control parameters of
2220: counted loops usually reside on the return stack, so you have to take
2221: all items, that you have pushed on the return stack in a colon
2222: definition or counted loop, from the return stack before the definition
2223: or loop ends. You cannot access items that you pushed on the return
2224: stack outside some definition or loop within the definition of loop.
2225:
2226: If you miscount the return stack items, this usually ends in a crash:
2227:
2228: @example
2229: : crash ( n -- )
2230: >r ;
2231: 5 crash
2232: @end example
2233:
2234: You cannot mix using locals and using the return stack (according to the
2235: standard; Gforth has no problem). However, they solve the same
2236: problems, so this shouldn't be an issue.
2237:
2238: @assignment
2239: Can you rewrite any of the definitions you wrote until now in a better
2240: way using the return stack?
2241: @endassignment
2242:
1.66 anton 2243: Reference: @ref{Return stack}.
2244:
1.48 anton 2245:
2246: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2247: @section Memory
1.66 anton 2248: @cindex memory access/allocation tutorial
1.48 anton 2249:
2250: You can create a global variable @code{v} with
2251:
2252: @example
2253: variable v ( -- addr )
2254: @end example
2255:
2256: @code{v} pushes the address of a cell in memory on the stack. This cell
2257: was reserved by @code{variable}. You can use @code{!} (store) to store
2258: values into this cell and @code{@@} (fetch) to load the value from the
2259: stack into memory:
2260:
2261: @example
2262: v .
2263: 5 v ! .s
1.50 anton 2264: v @@ .
1.48 anton 2265: @end example
2266:
1.65 anton 2267: You can see a raw dump of memory with @code{dump}:
2268:
2269: @example
2270: v 1 cells .s dump
2271: @end example
2272:
2273: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2274: generally, address units (aus)) that @code{n1 cells} occupy. You can
2275: also reserve more memory:
1.48 anton 2276:
2277: @example
2278: create v2 20 cells allot
1.65 anton 2279: v2 20 cells dump
1.48 anton 2280: @end example
2281:
1.65 anton 2282: creates a word @code{v2} and reserves 20 uninitialized cells; the
2283: address pushed by @code{v2} points to the start of these 20 cells. You
2284: can use address arithmetic to access these cells:
1.48 anton 2285:
2286: @example
2287: 3 v2 5 cells + !
1.65 anton 2288: v2 20 cells dump
1.48 anton 2289: @end example
2290:
2291: You can reserve and initialize memory with @code{,}:
2292:
2293: @example
2294: create v3
2295: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2296: v3 @@ .
2297: v3 cell+ @@ .
2298: v3 2 cells + @@ .
1.65 anton 2299: v3 5 cells dump
1.48 anton 2300: @end example
2301:
2302: @assignment
2303: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2304: @code{u} cells, with the first of these cells at @code{addr}, the next
2305: one at @code{addr cell+} etc.
2306: @endassignment
2307:
2308: You can also reserve memory without creating a new word:
2309:
2310: @example
1.60 anton 2311: here 10 cells allot .
2312: here .
1.48 anton 2313: @end example
2314:
2315: @code{Here} pushes the start address of the memory area. You should
2316: store it somewhere, or you will have a hard time finding the memory area
2317: again.
2318:
2319: @code{Allot} manages dictionary memory. The dictionary memory contains
2320: the system's data structures for words etc. on Gforth and most other
2321: Forth systems. It is managed like a stack: You can free the memory that
2322: you have just @code{allot}ed with
2323:
2324: @example
2325: -10 cells allot
1.60 anton 2326: here .
1.48 anton 2327: @end example
2328:
2329: Note that you cannot do this if you have created a new word in the
2330: meantime (because then your @code{allot}ed memory is no longer on the
2331: top of the dictionary ``stack'').
2332:
2333: Alternatively, you can use @code{allocate} and @code{free} which allow
2334: freeing memory in any order:
2335:
2336: @example
2337: 10 cells allocate throw .s
2338: 20 cells allocate throw .s
2339: swap
2340: free throw
2341: free throw
2342: @end example
2343:
2344: The @code{throw}s deal with errors (e.g., out of memory).
2345:
1.65 anton 2346: And there is also a
2347: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2348: garbage collector}, which eliminates the need to @code{free} memory
2349: explicitly.
1.48 anton 2350:
1.66 anton 2351: Reference: @ref{Memory}.
2352:
1.48 anton 2353:
2354: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2355: @section Characters and Strings
1.66 anton 2356: @cindex strings tutorial
2357: @cindex characters tutorial
1.48 anton 2358:
2359: On the stack characters take up a cell, like numbers. In memory they
2360: have their own size (one 8-bit byte on most systems), and therefore
2361: require their own words for memory access:
2362:
2363: @example
2364: create v4
2365: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2366: v4 4 chars + c@@ .
1.65 anton 2367: v4 5 chars dump
1.48 anton 2368: @end example
2369:
2370: The preferred representation of strings on the stack is @code{addr
2371: u-count}, where @code{addr} is the address of the first character and
2372: @code{u-count} is the number of characters in the string.
2373:
2374: @example
2375: v4 5 type
2376: @end example
2377:
2378: You get a string constant with
2379:
2380: @example
2381: s" hello, world" .s
2382: type
2383: @end example
2384:
2385: Make sure you have a space between @code{s"} and the string; @code{s"}
2386: is a normal Forth word and must be delimited with white space (try what
2387: happens when you remove the space).
2388:
2389: However, this interpretive use of @code{s"} is quite restricted: the
2390: string exists only until the next call of @code{s"} (some Forth systems
2391: keep more than one of these strings, but usually they still have a
1.62 crook 2392: limited lifetime).
1.48 anton 2393:
2394: @example
2395: s" hello," s" world" .s
2396: type
2397: type
2398: @end example
2399:
1.62 crook 2400: You can also use @code{s"} in a definition, and the resulting
2401: strings then live forever (well, for as long as the definition):
1.48 anton 2402:
2403: @example
2404: : foo s" hello," s" world" ;
2405: foo .s
2406: type
2407: type
2408: @end example
2409:
2410: @assignment
2411: @code{Emit ( c -- )} types @code{c} as character (not a number).
2412: Implement @code{type ( addr u -- )}.
2413: @endassignment
2414:
1.66 anton 2415: Reference: @ref{Memory Blocks}.
2416:
2417:
1.84 pazsan 2418: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2419: @section Alignment
1.66 anton 2420: @cindex alignment tutorial
2421: @cindex memory alignment tutorial
1.48 anton 2422:
2423: On many processors cells have to be aligned in memory, if you want to
2424: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2425: not require alignment, access to aligned cells is faster).
1.48 anton 2426:
2427: @code{Create} aligns @code{here} (i.e., the place where the next
2428: allocation will occur, and that the @code{create}d word points to).
2429: Likewise, the memory produced by @code{allocate} starts at an aligned
2430: address. Adding a number of @code{cells} to an aligned address produces
2431: another aligned address.
2432:
2433: However, address arithmetic involving @code{char+} and @code{chars} can
2434: create an address that is not cell-aligned. @code{Aligned ( addr --
2435: a-addr )} produces the next aligned address:
2436:
2437: @example
1.50 anton 2438: v3 char+ aligned .s @@ .
2439: v3 char+ .s @@ .
1.48 anton 2440: @end example
2441:
2442: Similarly, @code{align} advances @code{here} to the next aligned
2443: address:
2444:
2445: @example
2446: create v5 97 c,
2447: here .
2448: align here .
2449: 1000 ,
2450: @end example
2451:
2452: Note that you should use aligned addresses even if your processor does
2453: not require them, if you want your program to be portable.
2454:
1.66 anton 2455: Reference: @ref{Address arithmetic}.
2456:
1.48 anton 2457:
1.84 pazsan 2458: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2459: @section Files
2460: @cindex files tutorial
2461:
2462: This section gives a short introduction into how to use files inside
2463: Forth. It's broken up into five easy steps:
2464:
2465: @enumerate 1
2466: @item Opened an ASCII text file for input
2467: @item Opened a file for output
2468: @item Read input file until string matched (or some other condition matched)
2469: @item Wrote some lines from input ( modified or not) to output
2470: @item Closed the files.
2471: @end enumerate
2472:
2473: @subsection Open file for input
2474:
2475: @example
2476: s" foo.in" r/o open-file throw Value fd-in
2477: @end example
2478:
2479: @subsection Create file for output
2480:
2481: @example
2482: s" foo.out" w/o create-file throw Value fd-out
2483: @end example
2484:
2485: The available file modes are r/o for read-only access, r/w for
2486: read-write access, and w/o for write-only access. You could open both
2487: files with r/w, too, if you like. All file words return error codes; for
2488: most applications, it's best to pass there error codes with @code{throw}
2489: to the outer error handler.
2490:
2491: If you want words for opening and assigning, define them as follows:
2492:
2493: @example
2494: 0 Value fd-in
2495: 0 Value fd-out
2496: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2497: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2498: @end example
2499:
2500: Usage example:
2501:
2502: @example
2503: s" foo.in" open-input
2504: s" foo.out" open-output
2505: @end example
2506:
2507: @subsection Scan file for a particular line
2508:
2509: @example
2510: 256 Constant max-line
2511: Create line-buffer max-line 2 + allot
2512:
2513: : scan-file ( addr u -- )
2514: begin
2515: line-buffer max-line fd-in read-line throw
2516: while
2517: >r 2dup line-buffer r> compare 0=
2518: until
2519: else
2520: drop
2521: then
2522: 2drop ;
2523: @end example
2524:
2525: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2526: the buffer at addr, and returns the number of bytes read, a flag that is
2527: false when the end of file is reached, and an error code.
1.84 pazsan 2528:
2529: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2530: returns zero if both strings are equal. It returns a positive number if
2531: the first string is lexically greater, a negative if the second string
2532: is lexically greater.
2533:
2534: We haven't seen this loop here; it has two exits. Since the @code{while}
2535: exits with the number of bytes read on the stack, we have to clean up
2536: that separately; that's after the @code{else}.
2537:
2538: Usage example:
2539:
2540: @example
2541: s" The text I search is here" scan-file
2542: @end example
2543:
2544: @subsection Copy input to output
2545:
2546: @example
2547: : copy-file ( -- )
2548: begin
2549: line-buffer max-line fd-in read-line throw
2550: while
2551: line-buffer swap fd-out write-file throw
2552: repeat ;
2553: @end example
2554:
2555: @subsection Close files
2556:
2557: @example
2558: fd-in close-file throw
2559: fd-out close-file throw
2560: @end example
2561:
2562: Likewise, you can put that into definitions, too:
2563:
2564: @example
2565: : close-input ( -- ) fd-in close-file throw ;
2566: : close-output ( -- ) fd-out close-file throw ;
2567: @end example
2568:
2569: @assignment
2570: How could you modify @code{copy-file} so that it copies until a second line is
2571: matched? Can you write a program that extracts a section of a text file,
2572: given the line that starts and the line that terminates that section?
2573: @endassignment
2574:
2575: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2576: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2577: @cindex semantics tutorial
2578: @cindex interpretation semantics tutorial
2579: @cindex compilation semantics tutorial
2580: @cindex immediate, tutorial
1.48 anton 2581:
2582: When a word is compiled, it behaves differently from being interpreted.
2583: E.g., consider @code{+}:
2584:
2585: @example
2586: 1 2 + .
2587: : foo + ;
2588: @end example
2589:
2590: These two behaviours are known as compilation and interpretation
2591: semantics. For normal words (e.g., @code{+}), the compilation semantics
2592: is to append the interpretation semantics to the currently defined word
2593: (@code{foo} in the example above). I.e., when @code{foo} is executed
2594: later, the interpretation semantics of @code{+} (i.e., adding two
2595: numbers) will be performed.
2596:
2597: However, there are words with non-default compilation semantics, e.g.,
2598: the control-flow words like @code{if}. You can use @code{immediate} to
2599: change the compilation semantics of the last defined word to be equal to
2600: the interpretation semantics:
2601:
2602: @example
2603: : [FOO] ( -- )
2604: 5 . ; immediate
2605:
2606: [FOO]
2607: : bar ( -- )
2608: [FOO] ;
2609: bar
2610: see bar
2611: @end example
2612:
2613: Two conventions to mark words with non-default compilation semnatics are
2614: names with brackets (more frequently used) and to write them all in
2615: upper case (less frequently used).
2616:
2617: In Gforth (and many other systems) you can also remove the
2618: interpretation semantics with @code{compile-only} (the compilation
2619: semantics is derived from the original interpretation semantics):
2620:
2621: @example
2622: : flip ( -- )
2623: 6 . ; compile-only \ but not immediate
2624: flip
2625:
2626: : flop ( -- )
2627: flip ;
2628: flop
2629: @end example
2630:
2631: In this example the interpretation semantics of @code{flop} is equal to
2632: the original interpretation semantics of @code{flip}.
2633:
2634: The text interpreter has two states: in interpret state, it performs the
2635: interpretation semantics of words it encounters; in compile state, it
2636: performs the compilation semantics of these words.
2637:
2638: Among other things, @code{:} switches into compile state, and @code{;}
2639: switches back to interpret state. They contain the factors @code{]}
2640: (switch to compile state) and @code{[} (switch to interpret state), that
2641: do nothing but switch the state.
2642:
2643: @example
2644: : xxx ( -- )
2645: [ 5 . ]
2646: ;
2647:
2648: xxx
2649: see xxx
2650: @end example
2651:
2652: These brackets are also the source of the naming convention mentioned
2653: above.
2654:
1.66 anton 2655: Reference: @ref{Interpretation and Compilation Semantics}.
2656:
1.48 anton 2657:
2658: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2659: @section Execution Tokens
1.66 anton 2660: @cindex execution tokens tutorial
2661: @cindex XT tutorial
1.48 anton 2662:
2663: @code{' word} gives you the execution token (XT) of a word. The XT is a
2664: cell representing the interpretation semantics of a word. You can
2665: execute this semantics with @code{execute}:
2666:
2667: @example
2668: ' + .s
2669: 1 2 rot execute .
2670: @end example
2671:
2672: The XT is similar to a function pointer in C. However, parameter
2673: passing through the stack makes it a little more flexible:
2674:
2675: @example
2676: : map-array ( ... addr u xt -- ... )
1.50 anton 2677: \ executes xt ( ... x -- ... ) for every element of the array starting
2678: \ at addr and containing u elements
1.48 anton 2679: @{ xt @}
2680: cells over + swap ?do
1.50 anton 2681: i @@ xt execute
1.48 anton 2682: 1 cells +loop ;
2683:
2684: create a 3 , 4 , 2 , -1 , 4 ,
2685: a 5 ' . map-array .s
2686: 0 a 5 ' + map-array .
2687: s" max-n" environment? drop .s
2688: a 5 ' min map-array .
2689: @end example
2690:
2691: You can use map-array with the XTs of words that consume one element
2692: more than they produce. In theory you can also use it with other XTs,
2693: but the stack effect then depends on the size of the array, which is
2694: hard to understand.
2695:
1.51 pazsan 2696: Since XTs are cell-sized, you can store them in memory and manipulate
2697: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2698: word with @code{compile,}:
2699:
2700: @example
2701: : foo1 ( n1 n2 -- n )
2702: [ ' + compile, ] ;
2703: see foo
2704: @end example
2705:
2706: This is non-standard, because @code{compile,} has no compilation
2707: semantics in the standard, but it works in good Forth systems. For the
2708: broken ones, use
2709:
2710: @example
2711: : [compile,] compile, ; immediate
2712:
2713: : foo1 ( n1 n2 -- n )
2714: [ ' + ] [compile,] ;
2715: see foo
2716: @end example
2717:
2718: @code{'} is a word with default compilation semantics; it parses the
2719: next word when its interpretation semantics are executed, not during
2720: compilation:
2721:
2722: @example
2723: : foo ( -- xt )
2724: ' ;
2725: see foo
2726: : bar ( ... "word" -- ... )
2727: ' execute ;
2728: see bar
1.60 anton 2729: 1 2 bar + .
1.48 anton 2730: @end example
2731:
2732: You often want to parse a word during compilation and compile its XT so
2733: it will be pushed on the stack at run-time. @code{[']} does this:
2734:
2735: @example
2736: : xt-+ ( -- xt )
2737: ['] + ;
2738: see xt-+
2739: 1 2 xt-+ execute .
2740: @end example
2741:
2742: Many programmers tend to see @code{'} and the word it parses as one
2743: unit, and expect it to behave like @code{[']} when compiled, and are
2744: confused by the actual behaviour. If you are, just remember that the
2745: Forth system just takes @code{'} as one unit and has no idea that it is
2746: a parsing word (attempts to convenience programmers in this issue have
2747: usually resulted in even worse pitfalls, see
1.66 anton 2748: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2749: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2750:
2751: Note that the state of the interpreter does not come into play when
1.51 pazsan 2752: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2753: compile state, it still gives you the interpretation semantics. And
2754: whatever that state is, @code{execute} performs the semantics
1.66 anton 2755: represented by the XT (i.e., for XTs produced with @code{'} the
2756: interpretation semantics).
2757:
2758: Reference: @ref{Tokens for Words}.
1.48 anton 2759:
2760:
2761: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2762: @section Exceptions
1.66 anton 2763: @cindex exceptions tutorial
1.48 anton 2764:
2765: @code{throw ( n -- )} causes an exception unless n is zero.
2766:
2767: @example
2768: 100 throw .s
2769: 0 throw .s
2770: @end example
2771:
2772: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2773: it catches exceptions and pushes the number of the exception on the
2774: stack (or 0, if the xt executed without exception). If there was an
2775: exception, the stacks have the same depth as when entering @code{catch}:
2776:
2777: @example
2778: .s
2779: 3 0 ' / catch .s
2780: 3 2 ' / catch .s
2781: @end example
2782:
2783: @assignment
2784: Try the same with @code{execute} instead of @code{catch}.
2785: @endassignment
2786:
2787: @code{Throw} always jumps to the dynamically next enclosing
2788: @code{catch}, even if it has to leave several call levels to achieve
2789: this:
2790:
2791: @example
2792: : foo 100 throw ;
2793: : foo1 foo ." after foo" ;
1.51 pazsan 2794: : bar ['] foo1 catch ;
1.60 anton 2795: bar .
1.48 anton 2796: @end example
2797:
2798: It is often important to restore a value upon leaving a definition, even
2799: if the definition is left through an exception. You can ensure this
2800: like this:
2801:
2802: @example
2803: : ...
2804: save-x
1.51 pazsan 2805: ['] word-changing-x catch ( ... n )
1.48 anton 2806: restore-x
2807: ( ... n ) throw ;
2808: @end example
2809:
1.55 anton 2810: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2811: @code{try ... recover ... endtry}. If the code between @code{try} and
2812: @code{recover} has an exception, the stack depths are restored, the
2813: exception number is pushed on the stack, and the code between
2814: @code{recover} and @code{endtry} is performed. E.g., the definition for
2815: @code{catch} is
2816:
2817: @example
2818: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2819: try
2820: execute 0
2821: recover
2822: nip
2823: endtry ;
2824: @end example
2825:
2826: The equivalent to the restoration code above is
2827:
2828: @example
2829: : ...
2830: save-x
2831: try
1.92 anton 2832: word-changing-x 0
2833: recover endtry
1.48 anton 2834: restore-x
2835: throw ;
2836: @end example
2837:
1.92 anton 2838: This works if @code{word-changing-x} does not change the stack depth,
2839: otherwise you should add some code between @code{recover} and
2840: @code{endtry} to balance the stack.
1.48 anton 2841:
1.66 anton 2842: Reference: @ref{Exception Handling}.
2843:
1.48 anton 2844:
2845: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2846: @section Defining Words
1.66 anton 2847: @cindex defining words tutorial
2848: @cindex does> tutorial
2849: @cindex create...does> tutorial
2850:
2851: @c before semantics?
1.48 anton 2852:
2853: @code{:}, @code{create}, and @code{variable} are definition words: They
2854: define other words. @code{Constant} is another definition word:
2855:
2856: @example
2857: 5 constant foo
2858: foo .
2859: @end example
2860:
2861: You can also use the prefixes @code{2} (double-cell) and @code{f}
2862: (floating point) with @code{variable} and @code{constant}.
2863:
2864: You can also define your own defining words. E.g.:
2865:
2866: @example
2867: : variable ( "name" -- )
2868: create 0 , ;
2869: @end example
2870:
2871: You can also define defining words that create words that do something
2872: other than just producing their address:
2873:
2874: @example
2875: : constant ( n "name" -- )
2876: create ,
2877: does> ( -- n )
1.50 anton 2878: ( addr ) @@ ;
1.48 anton 2879:
2880: 5 constant foo
2881: foo .
2882: @end example
2883:
2884: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2885: @code{does>} replaces @code{;}, but it also does something else: It
2886: changes the last defined word such that it pushes the address of the
2887: body of the word and then performs the code after the @code{does>}
2888: whenever it is called.
2889:
2890: In the example above, @code{constant} uses @code{,} to store 5 into the
2891: body of @code{foo}. When @code{foo} executes, it pushes the address of
2892: the body onto the stack, then (in the code after the @code{does>})
2893: fetches the 5 from there.
2894:
2895: The stack comment near the @code{does>} reflects the stack effect of the
2896: defined word, not the stack effect of the code after the @code{does>}
2897: (the difference is that the code expects the address of the body that
2898: the stack comment does not show).
2899:
2900: You can use these definition words to do factoring in cases that involve
2901: (other) definition words. E.g., a field offset is always added to an
2902: address. Instead of defining
2903:
2904: @example
2905: 2 cells constant offset-field1
2906: @end example
2907:
2908: and using this like
2909:
2910: @example
2911: ( addr ) offset-field1 +
2912: @end example
2913:
2914: you can define a definition word
2915:
2916: @example
2917: : simple-field ( n "name" -- )
2918: create ,
2919: does> ( n1 -- n1+n )
1.50 anton 2920: ( addr ) @@ + ;
1.48 anton 2921: @end example
1.21 crook 2922:
1.48 anton 2923: Definition and use of field offsets now look like this:
1.21 crook 2924:
1.48 anton 2925: @example
2926: 2 cells simple-field field1
1.60 anton 2927: create mystruct 4 cells allot
2928: mystruct .s field1 .s drop
1.48 anton 2929: @end example
1.21 crook 2930:
1.48 anton 2931: If you want to do something with the word without performing the code
2932: after the @code{does>}, you can access the body of a @code{create}d word
2933: with @code{>body ( xt -- addr )}:
1.21 crook 2934:
1.48 anton 2935: @example
2936: : value ( n "name" -- )
2937: create ,
2938: does> ( -- n1 )
1.50 anton 2939: @@ ;
1.48 anton 2940: : to ( n "name" -- )
2941: ' >body ! ;
1.21 crook 2942:
1.48 anton 2943: 5 value foo
2944: foo .
2945: 7 to foo
2946: foo .
2947: @end example
1.21 crook 2948:
1.48 anton 2949: @assignment
2950: Define @code{defer ( "name" -- )}, which creates a word that stores an
2951: XT (at the start the XT of @code{abort}), and upon execution
2952: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2953: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2954: recursion is one application of @code{defer}.
2955: @endassignment
1.29 crook 2956:
1.66 anton 2957: Reference: @ref{User-defined Defining Words}.
2958:
2959:
1.48 anton 2960: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2961: @section Arrays and Records
1.66 anton 2962: @cindex arrays tutorial
2963: @cindex records tutorial
2964: @cindex structs tutorial
1.29 crook 2965:
1.48 anton 2966: Forth has no standard words for defining data structures such as arrays
2967: and records (structs in C terminology), but you can build them yourself
2968: based on address arithmetic. You can also define words for defining
2969: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2970:
1.48 anton 2971: One of the first projects a Forth newcomer sets out upon when learning
2972: about defining words is an array defining word (possibly for
2973: n-dimensional arrays). Go ahead and do it, I did it, too; you will
2974: learn something from it. However, don't be disappointed when you later
2975: learn that you have little use for these words (inappropriate use would
2976: be even worse). I have not yet found a set of useful array words yet;
2977: the needs are just too diverse, and named, global arrays (the result of
2978: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 2979: consider how to pass them as parameters). Another such project is a set
2980: of words to help dealing with strings.
1.29 crook 2981:
1.48 anton 2982: On the other hand, there is a useful set of record words, and it has
2983: been defined in @file{compat/struct.fs}; these words are predefined in
2984: Gforth. They are explained in depth elsewhere in this manual (see
2985: @pxref{Structures}). The @code{simple-field} example above is
2986: simplified variant of fields in this package.
1.21 crook 2987:
2988:
1.48 anton 2989: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
2990: @section @code{POSTPONE}
1.66 anton 2991: @cindex postpone tutorial
1.21 crook 2992:
1.48 anton 2993: You can compile the compilation semantics (instead of compiling the
2994: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 2995:
1.48 anton 2996: @example
2997: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 2998: POSTPONE + ; immediate
1.48 anton 2999: : foo ( n1 n2 -- n )
3000: MY-+ ;
3001: 1 2 foo .
3002: see foo
3003: @end example
1.21 crook 3004:
1.48 anton 3005: During the definition of @code{foo} the text interpreter performs the
3006: compilation semantics of @code{MY-+}, which performs the compilation
3007: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3008:
3009: This example also displays separate stack comments for the compilation
3010: semantics and for the stack effect of the compiled code. For words with
3011: default compilation semantics these stack effects are usually not
3012: displayed; the stack effect of the compilation semantics is always
3013: @code{( -- )} for these words, the stack effect for the compiled code is
3014: the stack effect of the interpretation semantics.
3015:
3016: Note that the state of the interpreter does not come into play when
3017: performing the compilation semantics in this way. You can also perform
3018: it interpretively, e.g.:
3019:
3020: @example
3021: : foo2 ( n1 n2 -- n )
3022: [ MY-+ ] ;
3023: 1 2 foo .
3024: see foo
3025: @end example
1.21 crook 3026:
1.48 anton 3027: However, there are some broken Forth systems where this does not always
1.62 crook 3028: work, and therefore this practice was been declared non-standard in
1.48 anton 3029: 1999.
3030: @c !! repair.fs
3031:
3032: Here is another example for using @code{POSTPONE}:
1.44 crook 3033:
1.48 anton 3034: @example
3035: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3036: POSTPONE negate POSTPONE + ; immediate compile-only
3037: : bar ( n1 n2 -- n )
3038: MY-- ;
3039: 2 1 bar .
3040: see bar
3041: @end example
1.21 crook 3042:
1.48 anton 3043: You can define @code{ENDIF} in this way:
1.21 crook 3044:
1.48 anton 3045: @example
3046: : ENDIF ( Compilation: orig -- )
3047: POSTPONE then ; immediate
3048: @end example
1.21 crook 3049:
1.48 anton 3050: @assignment
3051: Write @code{MY-2DUP} that has compilation semantics equivalent to
3052: @code{2dup}, but compiles @code{over over}.
3053: @endassignment
1.29 crook 3054:
1.66 anton 3055: @c !! @xref{Macros} for reference
3056:
3057:
1.48 anton 3058: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3059: @section @code{Literal}
1.66 anton 3060: @cindex literal tutorial
1.29 crook 3061:
1.48 anton 3062: You cannot @code{POSTPONE} numbers:
1.21 crook 3063:
1.48 anton 3064: @example
3065: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3066: @end example
3067:
1.48 anton 3068: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3069:
1.48 anton 3070: @example
3071: : [FOO] ( compilation: --; run-time: -- n )
3072: 500 POSTPONE literal ; immediate
1.29 crook 3073:
1.60 anton 3074: : flip [FOO] ;
1.48 anton 3075: flip .
3076: see flip
3077: @end example
1.29 crook 3078:
1.48 anton 3079: @code{LITERAL} consumes a number at compile-time (when it's compilation
3080: semantics are executed) and pushes it at run-time (when the code it
3081: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3082: number computed at compile time into the current word:
1.29 crook 3083:
1.48 anton 3084: @example
3085: : bar ( -- n )
3086: [ 2 2 + ] literal ;
3087: see bar
3088: @end example
1.29 crook 3089:
1.48 anton 3090: @assignment
3091: Write @code{]L} which allows writing the example above as @code{: bar (
3092: -- n ) [ 2 2 + ]L ;}
3093: @endassignment
3094:
1.66 anton 3095: @c !! @xref{Macros} for reference
3096:
1.48 anton 3097:
3098: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3099: @section Advanced macros
1.66 anton 3100: @cindex macros, advanced tutorial
3101: @cindex run-time code generation, tutorial
1.48 anton 3102:
1.66 anton 3103: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3104: Execution Tokens}. It frequently performs @code{execute}, a relatively
3105: expensive operation in some Forth implementations. You can use
1.48 anton 3106: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3107: and produce a word that contains the word to be performed directly:
3108:
3109: @c use ]] ... [[
3110: @example
3111: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3112: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3113: \ array beginning at addr and containing u elements
3114: @{ xt @}
3115: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3116: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3117: 1 cells POSTPONE literal POSTPONE +loop ;
3118:
3119: : sum-array ( addr u -- n )
3120: 0 rot rot [ ' + compile-map-array ] ;
3121: see sum-array
3122: a 5 sum-array .
3123: @end example
3124:
3125: You can use the full power of Forth for generating the code; here's an
3126: example where the code is generated in a loop:
3127:
3128: @example
3129: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3130: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3131: POSTPONE tuck POSTPONE @@
1.48 anton 3132: POSTPONE literal POSTPONE * POSTPONE +
3133: POSTPONE swap POSTPONE cell+ ;
3134:
3135: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3136: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3137: 0 postpone literal postpone swap
3138: [ ' compile-vmul-step compile-map-array ]
3139: postpone drop ;
3140: see compile-vmul
3141:
3142: : a-vmul ( addr -- n )
1.51 pazsan 3143: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3144: [ a 5 compile-vmul ] ;
3145: see a-vmul
3146: a a-vmul .
3147: @end example
3148:
3149: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3150: also use @code{map-array} instead (try it now!).
1.48 anton 3151:
3152: You can use this technique for efficient multiplication of large
3153: matrices. In matrix multiplication, you multiply every line of one
3154: matrix with every column of the other matrix. You can generate the code
3155: for one line once, and use it for every column. The only downside of
3156: this technique is that it is cumbersome to recover the memory consumed
3157: by the generated code when you are done (and in more complicated cases
3158: it is not possible portably).
3159:
1.66 anton 3160: @c !! @xref{Macros} for reference
3161:
3162:
1.48 anton 3163: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3164: @section Compilation Tokens
1.66 anton 3165: @cindex compilation tokens, tutorial
3166: @cindex CT, tutorial
1.48 anton 3167:
3168: This section is Gforth-specific. You can skip it.
3169:
3170: @code{' word compile,} compiles the interpretation semantics. For words
3171: with default compilation semantics this is the same as performing the
3172: compilation semantics. To represent the compilation semantics of other
3173: words (e.g., words like @code{if} that have no interpretation
3174: semantics), Gforth has the concept of a compilation token (CT,
3175: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3176: You can perform the compilation semantics represented by a CT with
3177: @code{execute}:
1.29 crook 3178:
1.48 anton 3179: @example
3180: : foo2 ( n1 n2 -- n )
3181: [ comp' + execute ] ;
3182: see foo
3183: @end example
1.29 crook 3184:
1.48 anton 3185: You can compile the compilation semantics represented by a CT with
3186: @code{postpone,}:
1.30 anton 3187:
1.48 anton 3188: @example
3189: : foo3 ( -- )
3190: [ comp' + postpone, ] ;
3191: see foo3
3192: @end example
1.30 anton 3193:
1.51 pazsan 3194: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3195: @code{comp'} is particularly useful for words that have no
3196: interpretation semantics:
1.29 crook 3197:
1.30 anton 3198: @example
1.48 anton 3199: ' if
1.60 anton 3200: comp' if .s 2drop
1.30 anton 3201: @end example
3202:
1.66 anton 3203: Reference: @ref{Tokens for Words}.
3204:
1.29 crook 3205:
1.48 anton 3206: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3207: @section Wordlists and Search Order
1.66 anton 3208: @cindex wordlists tutorial
3209: @cindex search order, tutorial
1.48 anton 3210:
3211: The dictionary is not just a memory area that allows you to allocate
3212: memory with @code{allot}, it also contains the Forth words, arranged in
3213: several wordlists. When searching for a word in a wordlist,
3214: conceptually you start searching at the youngest and proceed towards
3215: older words (in reality most systems nowadays use hash-tables); i.e., if
3216: you define a word with the same name as an older word, the new word
3217: shadows the older word.
3218:
3219: Which wordlists are searched in which order is determined by the search
3220: order. You can display the search order with @code{order}. It displays
3221: first the search order, starting with the wordlist searched first, then
3222: it displays the wordlist that will contain newly defined words.
1.21 crook 3223:
1.48 anton 3224: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3225:
1.48 anton 3226: @example
3227: wordlist constant mywords
3228: @end example
1.21 crook 3229:
1.48 anton 3230: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3231: defined words (the @emph{current} wordlist):
1.21 crook 3232:
1.48 anton 3233: @example
3234: mywords set-current
3235: order
3236: @end example
1.26 crook 3237:
1.48 anton 3238: Gforth does not display a name for the wordlist in @code{mywords}
3239: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3240:
1.48 anton 3241: You can get the current wordlist with @code{get-current ( -- wid)}. If
3242: you want to put something into a specific wordlist without overall
3243: effect on the current wordlist, this typically looks like this:
1.21 crook 3244:
1.48 anton 3245: @example
3246: get-current mywords set-current ( wid )
3247: create someword
3248: ( wid ) set-current
3249: @end example
1.21 crook 3250:
1.48 anton 3251: You can write the search order with @code{set-order ( wid1 .. widn n --
3252: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3253: searched wordlist is topmost.
1.21 crook 3254:
1.48 anton 3255: @example
3256: get-order mywords swap 1+ set-order
3257: order
3258: @end example
1.21 crook 3259:
1.48 anton 3260: Yes, the order of wordlists in the output of @code{order} is reversed
3261: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3262:
1.48 anton 3263: @assignment
3264: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3265: wordlist to the search order. Define @code{previous ( -- )}, which
3266: removes the first searched wordlist from the search order. Experiment
3267: with boundary conditions (you will see some crashes or situations that
3268: are hard or impossible to leave).
3269: @endassignment
1.21 crook 3270:
1.48 anton 3271: The search order is a powerful foundation for providing features similar
3272: to Modula-2 modules and C++ namespaces. However, trying to modularize
3273: programs in this way has disadvantages for debugging and reuse/factoring
3274: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3275: though). These disadvantages are not so clear in other
1.82 anton 3276: languages/programming environments, because these languages are not so
1.48 anton 3277: strong in debugging and reuse.
1.21 crook 3278:
1.66 anton 3279: @c !! example
3280:
3281: Reference: @ref{Word Lists}.
1.21 crook 3282:
1.29 crook 3283: @c ******************************************************************
1.48 anton 3284: @node Introduction, Words, Tutorial, Top
1.29 crook 3285: @comment node-name, next, previous, up
3286: @chapter An Introduction to ANS Forth
3287: @cindex Forth - an introduction
1.21 crook 3288:
1.83 anton 3289: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3290: that it is slower-paced in its examples, but uses them to dive deep into
3291: explaining Forth internals (not covered by the Tutorial). Apart from
3292: that, this chapter covers far less material. It is suitable for reading
3293: without using a computer.
3294:
1.29 crook 3295: The primary purpose of this manual is to document Gforth. However, since
3296: Forth is not a widely-known language and there is a lack of up-to-date
3297: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3298: material. For other sources of Forth-related
3299: information, see @ref{Forth-related information}.
1.21 crook 3300:
1.29 crook 3301: The examples in this section should work on any ANS Forth; the
3302: output shown was produced using Gforth. Each example attempts to
3303: reproduce the exact output that Gforth produces. If you try out the
3304: examples (and you should), what you should type is shown @kbd{like this}
3305: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3306: that, where the example shows @key{RET} it means that you should
1.29 crook 3307: press the ``carriage return'' key. Unfortunately, some output formats for
3308: this manual cannot show the difference between @kbd{this} and
3309: @code{this} which will make trying out the examples harder (but not
3310: impossible).
1.21 crook 3311:
1.29 crook 3312: Forth is an unusual language. It provides an interactive development
3313: environment which includes both an interpreter and compiler. Forth
3314: programming style encourages you to break a problem down into many
3315: @cindex factoring
3316: small fragments (@dfn{factoring}), and then to develop and test each
3317: fragment interactively. Forth advocates assert that breaking the
3318: edit-compile-test cycle used by conventional programming languages can
3319: lead to great productivity improvements.
1.21 crook 3320:
1.29 crook 3321: @menu
1.67 anton 3322: * Introducing the Text Interpreter::
3323: * Stacks and Postfix notation::
3324: * Your first definition::
3325: * How does that work?::
3326: * Forth is written in Forth::
3327: * Review - elements of a Forth system::
3328: * Where to go next::
3329: * Exercises::
1.29 crook 3330: @end menu
1.21 crook 3331:
1.29 crook 3332: @comment ----------------------------------------------
3333: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3334: @section Introducing the Text Interpreter
3335: @cindex text interpreter
3336: @cindex outer interpreter
1.21 crook 3337:
1.30 anton 3338: @c IMO this is too detailed and the pace is too slow for
3339: @c an introduction. If you know German, take a look at
3340: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3341: @c to see how I do it - anton
3342:
1.44 crook 3343: @c nac-> Where I have accepted your comments 100% and modified the text
3344: @c accordingly, I have deleted your comments. Elsewhere I have added a
3345: @c response like this to attempt to rationalise what I have done. Of
3346: @c course, this is a very clumsy mechanism for something that would be
3347: @c done far more efficiently over a beer. Please delete any dialogue
3348: @c you consider closed.
3349:
1.29 crook 3350: When you invoke the Forth image, you will see a startup banner printed
3351: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3352: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3353: its command line interpreter, which is called the @dfn{Text Interpreter}
3354: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3355: about the text interpreter as you read through this chapter, for more
3356: detail @pxref{The Text Interpreter}).
1.21 crook 3357:
1.29 crook 3358: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3359: input. Type a number and press the @key{RET} key:
1.21 crook 3360:
1.26 crook 3361: @example
1.30 anton 3362: @kbd{45@key{RET}} ok
1.26 crook 3363: @end example
1.21 crook 3364:
1.29 crook 3365: Rather than give you a prompt to invite you to input something, the text
3366: interpreter prints a status message @i{after} it has processed a line
3367: of input. The status message in this case (``@code{ ok}'' followed by
3368: carriage-return) indicates that the text interpreter was able to process
3369: all of your input successfully. Now type something illegal:
3370:
3371: @example
1.30 anton 3372: @kbd{qwer341@key{RET}}
1.29 crook 3373: :1: Undefined word
3374: qwer341
3375: ^^^^^^^
3376: $400D2BA8 Bounce
3377: $400DBDA8 no.extensions
3378: @end example
1.23 crook 3379:
1.29 crook 3380: The exact text, other than the ``Undefined word'' may differ slightly on
3381: your system, but the effect is the same; when the text interpreter
3382: detects an error, it discards any remaining text on a line, resets
1.49 anton 3383: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3384: messages}.
1.23 crook 3385:
1.29 crook 3386: The text interpreter waits for you to press carriage-return, and then
3387: processes your input line. Starting at the beginning of the line, it
3388: breaks the line into groups of characters separated by spaces. For each
3389: group of characters in turn, it makes two attempts to do something:
1.23 crook 3390:
1.29 crook 3391: @itemize @bullet
3392: @item
1.44 crook 3393: @cindex name dictionary
1.29 crook 3394: It tries to treat it as a command. It does this by searching a @dfn{name
3395: dictionary}. If the group of characters matches an entry in the name
3396: dictionary, the name dictionary provides the text interpreter with
3397: information that allows the text interpreter perform some actions. In
3398: Forth jargon, we say that the group
3399: @cindex word
3400: @cindex definition
3401: @cindex execution token
3402: @cindex xt
3403: of characters names a @dfn{word}, that the dictionary search returns an
3404: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3405: word, and that the text interpreter executes the xt. Often, the terms
3406: @dfn{word} and @dfn{definition} are used interchangeably.
3407: @item
3408: If the text interpreter fails to find a match in the name dictionary, it
3409: tries to treat the group of characters as a number in the current number
3410: base (when you start up Forth, the current number base is base 10). If
3411: the group of characters legitimately represents a number, the text
3412: interpreter pushes the number onto a stack (we'll learn more about that
3413: in the next section).
3414: @end itemize
1.23 crook 3415:
1.29 crook 3416: If the text interpreter is unable to do either of these things with any
3417: group of characters, it discards the group of characters and the rest of
3418: the line, then prints an error message. If the text interpreter reaches
3419: the end of the line without error, it prints the status message ``@code{ ok}''
3420: followed by carriage-return.
1.21 crook 3421:
1.29 crook 3422: This is the simplest command we can give to the text interpreter:
1.23 crook 3423:
3424: @example
1.30 anton 3425: @key{RET} ok
1.23 crook 3426: @end example
1.21 crook 3427:
1.29 crook 3428: The text interpreter did everything we asked it to do (nothing) without
3429: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3430: command:
1.21 crook 3431:
1.23 crook 3432: @example
1.30 anton 3433: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3434: :1: Undefined word
3435: 12 dup fred dup
3436: ^^^^
3437: $400D2BA8 Bounce
3438: $400DBDA8 no.extensions
1.23 crook 3439: @end example
1.21 crook 3440:
1.29 crook 3441: When you press the carriage-return key, the text interpreter starts to
3442: work its way along the line:
1.21 crook 3443:
1.29 crook 3444: @itemize @bullet
3445: @item
3446: When it gets to the space after the @code{2}, it takes the group of
3447: characters @code{12} and looks them up in the name
3448: dictionary@footnote{We can't tell if it found them or not, but assume
3449: for now that it did not}. There is no match for this group of characters
3450: in the name dictionary, so it tries to treat them as a number. It is
3451: able to do this successfully, so it puts the number, 12, ``on the stack''
3452: (whatever that means).
3453: @item
3454: The text interpreter resumes scanning the line and gets the next group
3455: of characters, @code{dup}. It looks it up in the name dictionary and
3456: (you'll have to take my word for this) finds it, and executes the word
3457: @code{dup} (whatever that means).
3458: @item
3459: Once again, the text interpreter resumes scanning the line and gets the
3460: group of characters @code{fred}. It looks them up in the name
3461: dictionary, but can't find them. It tries to treat them as a number, but
3462: they don't represent any legal number.
3463: @end itemize
1.21 crook 3464:
1.29 crook 3465: At this point, the text interpreter gives up and prints an error
3466: message. The error message shows exactly how far the text interpreter
3467: got in processing the line. In particular, it shows that the text
3468: interpreter made no attempt to do anything with the final character
3469: group, @code{dup}, even though we have good reason to believe that the
3470: text interpreter would have no problem looking that word up and
3471: executing it a second time.
1.21 crook 3472:
3473:
1.29 crook 3474: @comment ----------------------------------------------
3475: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3476: @section Stacks, postfix notation and parameter passing
3477: @cindex text interpreter
3478: @cindex outer interpreter
1.21 crook 3479:
1.29 crook 3480: In procedural programming languages (like C and Pascal), the
3481: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3482: functions or procedures are called with @dfn{explicit parameters}. For
3483: example, in C we might write:
1.21 crook 3484:
1.23 crook 3485: @example
1.29 crook 3486: total = total + new_volume(length,height,depth);
1.23 crook 3487: @end example
1.21 crook 3488:
1.23 crook 3489: @noindent
1.29 crook 3490: where new_volume is a function-call to another piece of code, and total,
3491: length, height and depth are all variables. length, height and depth are
3492: parameters to the function-call.
1.21 crook 3493:
1.29 crook 3494: In Forth, the equivalent of the function or procedure is the
3495: @dfn{definition} and parameters are implicitly passed between
3496: definitions using a shared stack that is visible to the
3497: programmer. Although Forth does support variables, the existence of the
3498: stack means that they are used far less often than in most other
3499: programming languages. When the text interpreter encounters a number, it
3500: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3501: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3502: used for any operation is implied unambiguously by the operation being
3503: performed. The stack used for all integer operations is called the @dfn{data
3504: stack} and, since this is the stack used most commonly, references to
3505: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3506:
1.29 crook 3507: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3508:
1.23 crook 3509: @example
1.30 anton 3510: @kbd{1 2 3@key{RET}} ok
1.23 crook 3511: @end example
1.21 crook 3512:
1.29 crook 3513: Then this instructs the text interpreter to placed three numbers on the
3514: (data) stack. An analogy for the behaviour of the stack is to take a
3515: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3516: the table. The 3 was the last card onto the pile (``last-in'') and if
3517: you take a card off the pile then, unless you're prepared to fiddle a
3518: bit, the card that you take off will be the 3 (``first-out''). The
3519: number that will be first-out of the stack is called the @dfn{top of
3520: stack}, which
3521: @cindex TOS definition
3522: is often abbreviated to @dfn{TOS}.
1.21 crook 3523:
1.29 crook 3524: To understand how parameters are passed in Forth, consider the
3525: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3526: be surprised to learn that this definition performs addition. More
3527: precisely, it adds two number together and produces a result. Where does
3528: it get the two numbers from? It takes the top two numbers off the
3529: stack. Where does it place the result? On the stack. You can act-out the
3530: behaviour of @code{+} with your playing cards like this:
1.21 crook 3531:
3532: @itemize @bullet
3533: @item
1.29 crook 3534: Pick up two cards from the stack on the table
1.21 crook 3535: @item
1.29 crook 3536: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3537: numbers''
1.21 crook 3538: @item
1.29 crook 3539: Decide that the answer is 5
1.21 crook 3540: @item
1.29 crook 3541: Shuffle the two cards back into the pack and find a 5
1.21 crook 3542: @item
1.29 crook 3543: Put a 5 on the remaining ace that's on the table.
1.21 crook 3544: @end itemize
3545:
1.29 crook 3546: If you don't have a pack of cards handy but you do have Forth running,
3547: you can use the definition @code{.s} to show the current state of the stack,
3548: without affecting the stack. Type:
1.21 crook 3549:
3550: @example
1.124 anton 3551: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3552: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3553: @end example
3554:
1.124 anton 3555: The text interpreter looks up the word @code{clearstacks} and executes
3556: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3557: left on it by earlier examples. The text interpreter pushes each of the
3558: three numbers in turn onto the stack. Finally, the text interpreter
3559: looks up the word @code{.s} and executes it. The effect of executing
3560: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3561: followed by a list of all the items on the stack; the item on the far
3562: right-hand side is the TOS.
1.21 crook 3563:
1.29 crook 3564: You can now type:
1.21 crook 3565:
1.29 crook 3566: @example
1.30 anton 3567: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3568: @end example
1.21 crook 3569:
1.29 crook 3570: @noindent
3571: which is correct; there are now 2 items on the stack and the result of
3572: the addition is 5.
1.23 crook 3573:
1.29 crook 3574: If you're playing with cards, try doing a second addition: pick up the
3575: two cards, work out that their sum is 6, shuffle them into the pack,
3576: look for a 6 and place that on the table. You now have just one item on
3577: the stack. What happens if you try to do a third addition? Pick up the
3578: first card, pick up the second card -- ah! There is no second card. This
3579: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3580: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3581: Underflow or an Invalid Memory Address error).
1.23 crook 3582:
1.29 crook 3583: The opposite situation to a stack underflow is a @dfn{stack overflow},
3584: which simply accepts that there is a finite amount of storage space
3585: reserved for the stack. To stretch the playing card analogy, if you had
3586: enough packs of cards and you piled the cards up on the table, you would
3587: eventually be unable to add another card; you'd hit the ceiling. Gforth
3588: allows you to set the maximum size of the stacks. In general, the only
3589: time that you will get a stack overflow is because a definition has a
3590: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3591:
1.29 crook 3592: There's one final use for the playing card analogy. If you model your
3593: stack using a pack of playing cards, the maximum number of items on
3594: your stack will be 52 (I assume you didn't use the Joker). The maximum
3595: @i{value} of any item on the stack is 13 (the King). In fact, the only
3596: possible numbers are positive integer numbers 1 through 13; you can't
3597: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3598: think about some of the cards, you can accommodate different
3599: numbers. For example, you could think of the Jack as representing 0,
3600: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3601: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3602: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3603:
1.29 crook 3604: In that analogy, the limit was the amount of information that a single
3605: stack entry could hold, and Forth has a similar limit. In Forth, the
3606: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3607: implementation dependent and affects the maximum value that a stack
3608: entry can hold. A Standard Forth provides a cell size of at least
3609: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3610:
1.29 crook 3611: Forth does not do any type checking for you, so you are free to
3612: manipulate and combine stack items in any way you wish. A convenient way
3613: of treating stack items is as 2's complement signed integers, and that
3614: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3615:
1.29 crook 3616: @example
1.30 anton 3617: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3618: @end example
1.21 crook 3619:
1.29 crook 3620: If you use numbers and definitions like @code{+} in order to turn Forth
3621: into a great big pocket calculator, you will realise that it's rather
3622: different from a normal calculator. Rather than typing 2 + 3 = you had
3623: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3624: result). The terminology used to describe this difference is to say that
3625: your calculator uses @dfn{Infix Notation} (parameters and operators are
3626: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3627: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3628:
1.29 crook 3629: Whilst postfix notation might look confusing to begin with, it has
3630: several important advantages:
1.21 crook 3631:
1.23 crook 3632: @itemize @bullet
3633: @item
1.29 crook 3634: it is unambiguous
1.23 crook 3635: @item
1.29 crook 3636: it is more concise
1.23 crook 3637: @item
1.29 crook 3638: it fits naturally with a stack-based system
1.23 crook 3639: @end itemize
1.21 crook 3640:
1.29 crook 3641: To examine these claims in more detail, consider these sums:
1.21 crook 3642:
1.29 crook 3643: @example
3644: 6 + 5 * 4 =
3645: 4 * 5 + 6 =
3646: @end example
1.21 crook 3647:
1.29 crook 3648: If you're just learning maths or your maths is very rusty, you will
3649: probably come up with the answer 44 for the first and 26 for the
3650: second. If you are a bit of a whizz at maths you will remember the
3651: @i{convention} that multiplication takes precendence over addition, and
3652: you'd come up with the answer 26 both times. To explain the answer 26
3653: to someone who got the answer 44, you'd probably rewrite the first sum
3654: like this:
1.21 crook 3655:
1.29 crook 3656: @example
3657: 6 + (5 * 4) =
3658: @end example
1.21 crook 3659:
1.29 crook 3660: If what you really wanted was to perform the addition before the
3661: multiplication, you would have to use parentheses to force it.
1.21 crook 3662:
1.29 crook 3663: If you did the first two sums on a pocket calculator you would probably
3664: get the right answers, unless you were very cautious and entered them using
3665: these keystroke sequences:
1.21 crook 3666:
1.29 crook 3667: 6 + 5 = * 4 =
3668: 4 * 5 = + 6 =
1.21 crook 3669:
1.29 crook 3670: Postfix notation is unambiguous because the order that the operators
3671: are applied is always explicit; that also means that parentheses are
3672: never required. The operators are @i{active} (the act of quoting the
3673: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3674:
1.29 crook 3675: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3676: equivalent ways:
1.26 crook 3677:
3678: @example
1.29 crook 3679: 6 5 4 * + or:
3680: 5 4 * 6 +
1.26 crook 3681: @end example
1.23 crook 3682:
1.29 crook 3683: An important thing that you should notice about this notation is that
3684: the @i{order} of the numbers does not change; if you want to subtract
3685: 2 from 10 you type @code{10 2 -}.
1.1 anton 3686:
1.29 crook 3687: The reason that Forth uses postfix notation is very simple to explain: it
3688: makes the implementation extremely simple, and it follows naturally from
3689: using the stack as a mechanism for passing parameters. Another way of
3690: thinking about this is to realise that all Forth definitions are
3691: @i{active}; they execute as they are encountered by the text
3692: interpreter. The result of this is that the syntax of Forth is trivially
3693: simple.
1.1 anton 3694:
3695:
3696:
1.29 crook 3697: @comment ----------------------------------------------
3698: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3699: @section Your first Forth definition
3700: @cindex first definition
1.1 anton 3701:
1.29 crook 3702: Until now, the examples we've seen have been trivial; we've just been
3703: using Forth as a bigger-than-pocket calculator. Also, each calculation
3704: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3705: again@footnote{That's not quite true. If you press the up-arrow key on
3706: your keyboard you should be able to scroll back to any earlier command,
3707: edit it and re-enter it.} In this section we'll see how to add new
3708: words to Forth's vocabulary.
1.1 anton 3709:
1.29 crook 3710: The easiest way to create a new word is to use a @dfn{colon
3711: definition}. We'll define a few and try them out before worrying too
3712: much about how they work. Try typing in these examples; be careful to
3713: copy the spaces accurately:
1.1 anton 3714:
1.29 crook 3715: @example
3716: : add-two 2 + . ;
3717: : greet ." Hello and welcome" ;
3718: : demo 5 add-two ;
3719: @end example
1.1 anton 3720:
1.29 crook 3721: @noindent
3722: Now try them out:
1.1 anton 3723:
1.29 crook 3724: @example
1.30 anton 3725: @kbd{greet@key{RET}} Hello and welcome ok
3726: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3727: @kbd{4 add-two@key{RET}} 6 ok
3728: @kbd{demo@key{RET}} 7 ok
3729: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3730: @end example
1.1 anton 3731:
1.29 crook 3732: The first new thing that we've introduced here is the pair of words
3733: @code{:} and @code{;}. These are used to start and terminate a new
3734: definition, respectively. The first word after the @code{:} is the name
3735: for the new definition.
1.1 anton 3736:
1.29 crook 3737: As you can see from the examples, a definition is built up of words that
3738: have already been defined; Forth makes no distinction between
3739: definitions that existed when you started the system up, and those that
3740: you define yourself.
1.1 anton 3741:
1.29 crook 3742: The examples also introduce the words @code{.} (dot), @code{."}
3743: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3744: the stack and displays it. It's like @code{.s} except that it only
3745: displays the top item of the stack and it is destructive; after it has
3746: executed, the number is no longer on the stack. There is always one
3747: space printed after the number, and no spaces before it. Dot-quote
3748: defines a string (a sequence of characters) that will be printed when
3749: the word is executed. The string can contain any printable characters
3750: except @code{"}. A @code{"} has a special function; it is not a Forth
3751: word but it acts as a delimiter (the way that delimiters work is
3752: described in the next section). Finally, @code{dup} duplicates the value
3753: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3754:
1.29 crook 3755: We already know that the text interpreter searches through the
3756: dictionary to locate names. If you've followed the examples earlier, you
3757: will already have a definition called @code{add-two}. Lets try modifying
3758: it by typing in a new definition:
1.1 anton 3759:
1.29 crook 3760: @example
1.30 anton 3761: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3762: @end example
1.5 anton 3763:
1.29 crook 3764: Forth recognised that we were defining a word that already exists, and
3765: printed a message to warn us of that fact. Let's try out the new
3766: definition:
1.5 anton 3767:
1.29 crook 3768: @example
1.30 anton 3769: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3770: @end example
1.1 anton 3771:
1.29 crook 3772: @noindent
3773: All that we've actually done here, though, is to create a new
3774: definition, with a particular name. The fact that there was already a
3775: definition with the same name did not make any difference to the way
3776: that the new definition was created (except that Forth printed a warning
3777: message). The old definition of add-two still exists (try @code{demo}
3778: again to see that this is true). Any new definition will use the new
3779: definition of @code{add-two}, but old definitions continue to use the
3780: version that already existed at the time that they were @code{compiled}.
1.1 anton 3781:
1.29 crook 3782: Before you go on to the next section, try defining and redefining some
3783: words of your own.
1.1 anton 3784:
1.29 crook 3785: @comment ----------------------------------------------
3786: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3787: @section How does that work?
3788: @cindex parsing words
1.1 anton 3789:
1.30 anton 3790: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3791:
3792: @c Is it a good idea to talk about the interpretation semantics of a
3793: @c number? We don't have an xt to go along with it. - anton
3794:
3795: @c Now that I have eliminated execution semantics, I wonder if it would not
3796: @c be better to keep them (or add run-time semantics), to make it easier to
3797: @c explain what compilation semantics usually does. - anton
3798:
1.44 crook 3799: @c nac-> I removed the term ``default compilation sematics'' from the
3800: @c introductory chapter. Removing ``execution semantics'' was making
3801: @c everything simpler to explain, then I think the use of this term made
3802: @c everything more complex again. I replaced it with ``default
3803: @c semantics'' (which is used elsewhere in the manual) by which I mean
3804: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3805: @c flag set''.
3806:
3807: @c anton: I have eliminated default semantics (except in one place where it
3808: @c means "default interpretation and compilation semantics"), because it
3809: @c makes no sense in the presence of combined words. I reverted to
3810: @c "execution semantics" where necessary.
3811:
3812: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3813: @c section (and, unusually for me, I think I even made it shorter!). See
3814: @c what you think -- I know I have not addressed your primary concern
3815: @c that it is too heavy-going for an introduction. From what I understood
3816: @c of your course notes it looks as though they might be a good framework.
3817: @c Things that I've tried to capture here are some things that came as a
3818: @c great revelation here when I first understood them. Also, I like the
3819: @c fact that a very simple code example shows up almost all of the issues
3820: @c that you need to understand to see how Forth works. That's unique and
3821: @c worthwhile to emphasise.
3822:
1.83 anton 3823: @c anton: I think it's a good idea to present the details, especially those
3824: @c that you found to be a revelation, and probably the tutorial tries to be
3825: @c too superficial and does not get some of the things across that make
3826: @c Forth special. I do believe that most of the time these things should
3827: @c be discussed at the end of a section or in separate sections instead of
3828: @c in the middle of a section (e.g., the stuff you added in "User-defined
3829: @c defining words" leads in a completely different direction from the rest
3830: @c of the section).
3831:
1.29 crook 3832: Now we're going to take another look at the definition of @code{add-two}
3833: from the previous section. From our knowledge of the way that the text
3834: interpreter works, we would have expected this result when we tried to
3835: define @code{add-two}:
1.21 crook 3836:
1.29 crook 3837: @example
1.44 crook 3838: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3839: ^^^^^^^
3840: Error: Undefined word
3841: @end example
1.28 crook 3842:
1.29 crook 3843: The reason that this didn't happen is bound up in the way that @code{:}
3844: works. The word @code{:} does two special things. The first special
3845: thing that it does prevents the text interpreter from ever seeing the
3846: characters @code{add-two}. The text interpreter uses a variable called
3847: @cindex modifying >IN
1.44 crook 3848: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3849: input line. When it encounters the word @code{:} it behaves in exactly
3850: the same way as it does for any other word; it looks it up in the name
3851: dictionary, finds its xt and executes it. When @code{:} executes, it
3852: looks at the input buffer, finds the word @code{add-two} and advances the
3853: value of @code{>IN} to point past it. It then does some other stuff
3854: associated with creating the new definition (including creating an entry
3855: for @code{add-two} in the name dictionary). When the execution of @code{:}
3856: completes, control returns to the text interpreter, which is oblivious
3857: to the fact that it has been tricked into ignoring part of the input
3858: line.
1.21 crook 3859:
1.29 crook 3860: @cindex parsing words
3861: Words like @code{:} -- words that advance the value of @code{>IN} and so
3862: prevent the text interpreter from acting on the whole of the input line
3863: -- are called @dfn{parsing words}.
1.21 crook 3864:
1.29 crook 3865: @cindex @code{state} - effect on the text interpreter
3866: @cindex text interpreter - effect of state
3867: The second special thing that @code{:} does is change the value of a
3868: variable called @code{state}, which affects the way that the text
3869: interpreter behaves. When Gforth starts up, @code{state} has the value
3870: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3871: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3872: the text interpreter is said to be @dfn{compiling}.
3873:
3874: In this example, the text interpreter is compiling when it processes the
3875: string ``@code{2 + . ;}''. It still breaks the string down into
3876: character sequences in the same way. However, instead of pushing the
3877: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3878: into the definition of @code{add-two} that will make the number @code{2} get
3879: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3880: the behaviours of @code{+} and @code{.} are also compiled into the
3881: definition.
3882:
3883: One category of words don't get compiled. These so-called @dfn{immediate
3884: words} get executed (performed @i{now}) regardless of whether the text
3885: interpreter is interpreting or compiling. The word @code{;} is an
3886: immediate word. Rather than being compiled into the definition, it
3887: executes. Its effect is to terminate the current definition, which
3888: includes changing the value of @code{state} back to 0.
3889:
3890: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3891: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3892: definition.
1.28 crook 3893:
1.30 anton 3894: In Forth, every word or number can be described in terms of two
1.29 crook 3895: properties:
1.28 crook 3896:
3897: @itemize @bullet
3898: @item
1.29 crook 3899: @cindex interpretation semantics
1.44 crook 3900: Its @dfn{interpretation semantics} describe how it will behave when the
3901: text interpreter encounters it in @dfn{interpret} state. The
3902: interpretation semantics of a word are represented by an @dfn{execution
3903: token}.
1.28 crook 3904: @item
1.29 crook 3905: @cindex compilation semantics
1.44 crook 3906: Its @dfn{compilation semantics} describe how it will behave when the
3907: text interpreter encounters it in @dfn{compile} state. The compilation
3908: semantics of a word are represented in an implementation-dependent way;
3909: Gforth uses a @dfn{compilation token}.
1.29 crook 3910: @end itemize
3911:
3912: @noindent
3913: Numbers are always treated in a fixed way:
3914:
3915: @itemize @bullet
1.28 crook 3916: @item
1.44 crook 3917: When the number is @dfn{interpreted}, its behaviour is to push the
3918: number onto the stack.
1.28 crook 3919: @item
1.30 anton 3920: When the number is @dfn{compiled}, a piece of code is appended to the
3921: current definition that pushes the number when it runs. (In other words,
3922: the compilation semantics of a number are to postpone its interpretation
3923: semantics until the run-time of the definition that it is being compiled
3924: into.)
1.29 crook 3925: @end itemize
3926:
1.44 crook 3927: Words don't behave in such a regular way, but most have @i{default
3928: semantics} which means that they behave like this:
1.29 crook 3929:
3930: @itemize @bullet
1.28 crook 3931: @item
1.30 anton 3932: The @dfn{interpretation semantics} of the word are to do something useful.
3933: @item
1.29 crook 3934: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3935: @dfn{interpretation semantics} to the current definition (so that its
3936: run-time behaviour is to do something useful).
1.28 crook 3937: @end itemize
3938:
1.30 anton 3939: @cindex immediate words
1.44 crook 3940: The actual behaviour of any particular word can be controlled by using
3941: the words @code{immediate} and @code{compile-only} when the word is
3942: defined. These words set flags in the name dictionary entry of the most
3943: recently defined word, and these flags are retrieved by the text
3944: interpreter when it finds the word in the name dictionary.
3945:
3946: A word that is marked as @dfn{immediate} has compilation semantics that
3947: are identical to its interpretation semantics. In other words, it
3948: behaves like this:
1.29 crook 3949:
3950: @itemize @bullet
3951: @item
1.30 anton 3952: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3953: @item
1.30 anton 3954: The @dfn{compilation semantics} of the word are to do something useful
3955: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3956: @end itemize
1.28 crook 3957:
1.44 crook 3958: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3959: performing the interpretation semantics of the word directly; an attempt
3960: to do so will generate an error. It is never necessary to use
3961: @code{compile-only} (and it is not even part of ANS Forth, though it is
3962: provided by many implementations) but it is good etiquette to apply it
3963: to a word that will not behave correctly (and might have unexpected
3964: side-effects) in interpret state. For example, it is only legal to use
3965: the conditional word @code{IF} within a definition. If you forget this
3966: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3967: @code{compile-only} allows the text interpreter to generate a helpful
3968: error message rather than subjecting you to the consequences of your
3969: folly.
3970:
1.29 crook 3971: This example shows the difference between an immediate and a
3972: non-immediate word:
1.28 crook 3973:
1.29 crook 3974: @example
3975: : show-state state @@ . ;
3976: : show-state-now show-state ; immediate
3977: : word1 show-state ;
3978: : word2 show-state-now ;
1.28 crook 3979: @end example
1.23 crook 3980:
1.29 crook 3981: The word @code{immediate} after the definition of @code{show-state-now}
3982: makes that word an immediate word. These definitions introduce a new
3983: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
3984: variable, and leaves it on the stack. Therefore, the behaviour of
3985: @code{show-state} is to print a number that represents the current value
3986: of @code{state}.
1.28 crook 3987:
1.29 crook 3988: When you execute @code{word1}, it prints the number 0, indicating that
3989: the system is interpreting. When the text interpreter compiled the
3990: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 3991: compilation semantics are to append its interpretation semantics to the
1.29 crook 3992: current definition. When you execute @code{word1}, it performs the
1.30 anton 3993: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 3994: (and therefore @code{show-state}) are executed, the system is
3995: interpreting.
1.28 crook 3996:
1.30 anton 3997: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 3998: you should have seen the number -1 printed, followed by ``@code{
3999: ok}''. When the text interpreter compiled the definition of
4000: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4001: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4002: semantics. It is executed straight away (even before the text
4003: interpreter has moved on to process another group of characters; the
4004: @code{;} in this example). The effect of executing it are to display the
4005: value of @code{state} @i{at the time that the definition of}
4006: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4007: system is compiling at this time. If you execute @code{word2} it does
4008: nothing at all.
1.28 crook 4009:
1.29 crook 4010: @cindex @code{."}, how it works
4011: Before leaving the subject of immediate words, consider the behaviour of
4012: @code{."} in the definition of @code{greet}, in the previous
4013: section. This word is both a parsing word and an immediate word. Notice
4014: that there is a space between @code{."} and the start of the text
4015: @code{Hello and welcome}, but that there is no space between the last
4016: letter of @code{welcome} and the @code{"} character. The reason for this
4017: is that @code{."} is a Forth word; it must have a space after it so that
4018: the text interpreter can identify it. The @code{"} is not a Forth word;
4019: it is a @dfn{delimiter}. The examples earlier show that, when the string
4020: is displayed, there is neither a space before the @code{H} nor after the
4021: @code{e}. Since @code{."} is an immediate word, it executes at the time
4022: that @code{greet} is defined. When it executes, its behaviour is to
4023: search forward in the input line looking for the delimiter. When it
4024: finds the delimiter, it updates @code{>IN} to point past the
4025: delimiter. It also compiles some magic code into the definition of
4026: @code{greet}; the xt of a run-time routine that prints a text string. It
4027: compiles the string @code{Hello and welcome} into memory so that it is
4028: available to be printed later. When the text interpreter gains control,
4029: the next word it finds in the input stream is @code{;} and so it
4030: terminates the definition of @code{greet}.
1.28 crook 4031:
4032:
4033: @comment ----------------------------------------------
1.29 crook 4034: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4035: @section Forth is written in Forth
4036: @cindex structure of Forth programs
4037:
4038: When you start up a Forth compiler, a large number of definitions
4039: already exist. In Forth, you develop a new application using bottom-up
4040: programming techniques to create new definitions that are defined in
4041: terms of existing definitions. As you create each definition you can
4042: test and debug it interactively.
4043:
4044: If you have tried out the examples in this section, you will probably
4045: have typed them in by hand; when you leave Gforth, your definitions will
4046: be lost. You can avoid this by using a text editor to enter Forth source
4047: code into a file, and then loading code from the file using
1.49 anton 4048: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4049: processed by the text interpreter, just as though you had typed it in by
4050: hand@footnote{Actually, there are some subtle differences -- see
4051: @ref{The Text Interpreter}.}.
4052:
4053: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4054: files for program entry (@pxref{Blocks}).
1.28 crook 4055:
1.29 crook 4056: In common with many, if not most, Forth compilers, most of Gforth is
4057: actually written in Forth. All of the @file{.fs} files in the
4058: installation directory@footnote{For example,
1.30 anton 4059: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4060: study to see examples of Forth programming.
1.28 crook 4061:
1.29 crook 4062: Gforth maintains a history file that records every line that you type to
4063: the text interpreter. This file is preserved between sessions, and is
4064: used to provide a command-line recall facility. If you enter long
4065: definitions by hand, you can use a text editor to paste them out of the
4066: history file into a Forth source file for reuse at a later time
1.49 anton 4067: (for more information @pxref{Command-line editing}).
1.28 crook 4068:
4069:
4070: @comment ----------------------------------------------
1.29 crook 4071: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4072: @section Review - elements of a Forth system
4073: @cindex elements of a Forth system
1.28 crook 4074:
1.29 crook 4075: To summarise this chapter:
1.28 crook 4076:
4077: @itemize @bullet
4078: @item
1.29 crook 4079: Forth programs use @dfn{factoring} to break a problem down into small
4080: fragments called @dfn{words} or @dfn{definitions}.
4081: @item
4082: Forth program development is an interactive process.
4083: @item
4084: The main command loop that accepts input, and controls both
4085: interpretation and compilation, is called the @dfn{text interpreter}
4086: (also known as the @dfn{outer interpreter}).
4087: @item
4088: Forth has a very simple syntax, consisting of words and numbers
4089: separated by spaces or carriage-return characters. Any additional syntax
4090: is imposed by @dfn{parsing words}.
4091: @item
4092: Forth uses a stack to pass parameters between words. As a result, it
4093: uses postfix notation.
4094: @item
4095: To use a word that has previously been defined, the text interpreter
4096: searches for the word in the @dfn{name dictionary}.
4097: @item
1.30 anton 4098: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4099: @item
1.29 crook 4100: The text interpreter uses the value of @code{state} to select between
4101: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4102: semantics} of a word that it encounters.
1.28 crook 4103: @item
1.30 anton 4104: The relationship between the @dfn{interpretation semantics} and
4105: @dfn{compilation semantics} for a word
1.29 crook 4106: depend upon the way in which the word was defined (for example, whether
4107: it is an @dfn{immediate} word).
1.28 crook 4108: @item
1.29 crook 4109: Forth definitions can be implemented in Forth (called @dfn{high-level
4110: definitions}) or in some other way (usually a lower-level language and
4111: as a result often called @dfn{low-level definitions}, @dfn{code
4112: definitions} or @dfn{primitives}).
1.28 crook 4113: @item
1.29 crook 4114: Many Forth systems are implemented mainly in Forth.
1.28 crook 4115: @end itemize
4116:
4117:
1.29 crook 4118: @comment ----------------------------------------------
1.48 anton 4119: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4120: @section Where To Go Next
4121: @cindex where to go next
1.28 crook 4122:
1.29 crook 4123: Amazing as it may seem, if you have read (and understood) this far, you
4124: know almost all the fundamentals about the inner workings of a Forth
4125: system. You certainly know enough to be able to read and understand the
4126: rest of this manual and the ANS Forth document, to learn more about the
4127: facilities that Forth in general and Gforth in particular provide. Even
4128: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4129: However, that's not a good idea just yet... better to try writing some
1.29 crook 4130: programs in Gforth.
1.28 crook 4131:
1.29 crook 4132: Forth has such a rich vocabulary that it can be hard to know where to
4133: start in learning it. This section suggests a few sets of words that are
4134: enough to write small but useful programs. Use the word index in this
4135: document to learn more about each word, then try it out and try to write
4136: small definitions using it. Start by experimenting with these words:
1.28 crook 4137:
4138: @itemize @bullet
4139: @item
1.29 crook 4140: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4141: @item
4142: Comparison: @code{MIN MAX =}
4143: @item
4144: Logic: @code{AND OR XOR NOT}
4145: @item
4146: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4147: @item
1.29 crook 4148: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4149: @item
1.29 crook 4150: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4151: @item
1.29 crook 4152: Defining words: @code{: ; CREATE}
1.28 crook 4153: @item
1.29 crook 4154: Memory allocation words: @code{ALLOT ,}
1.28 crook 4155: @item
1.29 crook 4156: Tools: @code{SEE WORDS .S MARKER}
4157: @end itemize
4158:
4159: When you have mastered those, go on to:
4160:
4161: @itemize @bullet
1.28 crook 4162: @item
1.29 crook 4163: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4164: @item
1.29 crook 4165: Memory access: @code{@@ !}
1.28 crook 4166: @end itemize
1.23 crook 4167:
1.29 crook 4168: When you have mastered these, there's nothing for it but to read through
4169: the whole of this manual and find out what you've missed.
4170:
4171: @comment ----------------------------------------------
1.48 anton 4172: @node Exercises, , Where to go next, Introduction
1.29 crook 4173: @section Exercises
4174: @cindex exercises
4175:
4176: TODO: provide a set of programming excercises linked into the stuff done
4177: already and into other sections of the manual. Provide solutions to all
4178: the exercises in a .fs file in the distribution.
4179:
4180: @c Get some inspiration from Starting Forth and Kelly&Spies.
4181:
4182: @c excercises:
4183: @c 1. take inches and convert to feet and inches.
4184: @c 2. take temperature and convert from fahrenheight to celcius;
4185: @c may need to care about symmetric vs floored??
4186: @c 3. take input line and do character substitution
4187: @c to encipher or decipher
4188: @c 4. as above but work on a file for in and out
4189: @c 5. take input line and convert to pig-latin
4190: @c
4191: @c thing of sets of things to exercise then come up with
4192: @c problems that need those things.
4193:
4194:
1.26 crook 4195: @c ******************************************************************
1.29 crook 4196: @node Words, Error messages, Introduction, Top
1.1 anton 4197: @chapter Forth Words
1.26 crook 4198: @cindex words
1.1 anton 4199:
4200: @menu
4201: * Notation::
1.65 anton 4202: * Case insensitivity::
4203: * Comments::
4204: * Boolean Flags::
1.1 anton 4205: * Arithmetic::
4206: * Stack Manipulation::
1.5 anton 4207: * Memory::
1.1 anton 4208: * Control Structures::
4209: * Defining Words::
1.65 anton 4210: * Interpretation and Compilation Semantics::
1.47 crook 4211: * Tokens for Words::
1.81 anton 4212: * Compiling words::
1.65 anton 4213: * The Text Interpreter::
1.111 anton 4214: * The Input Stream::
1.65 anton 4215: * Word Lists::
4216: * Environmental Queries::
1.12 anton 4217: * Files::
4218: * Blocks::
4219: * Other I/O::
1.121 anton 4220: * OS command line arguments::
1.78 anton 4221: * Locals::
4222: * Structures::
4223: * Object-oriented Forth::
1.12 anton 4224: * Programming Tools::
4225: * Assembler and Code Words::
4226: * Threading Words::
1.65 anton 4227: * Passing Commands to the OS::
4228: * Keeping track of Time::
4229: * Miscellaneous Words::
1.1 anton 4230: @end menu
4231:
1.65 anton 4232: @node Notation, Case insensitivity, Words, Words
1.1 anton 4233: @section Notation
4234: @cindex notation of glossary entries
4235: @cindex format of glossary entries
4236: @cindex glossary notation format
4237: @cindex word glossary entry format
4238:
4239: The Forth words are described in this section in the glossary notation
1.67 anton 4240: that has become a de-facto standard for Forth texts:
1.1 anton 4241:
4242: @format
1.29 crook 4243: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4244: @end format
1.29 crook 4245: @i{Description}
1.1 anton 4246:
4247: @table @var
4248: @item word
1.28 crook 4249: The name of the word.
1.1 anton 4250:
4251: @item Stack effect
4252: @cindex stack effect
1.29 crook 4253: The stack effect is written in the notation @code{@i{before} --
4254: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4255: stack entries before and after the execution of the word. The rest of
4256: the stack is not touched by the word. The top of stack is rightmost,
4257: i.e., a stack sequence is written as it is typed in. Note that Gforth
4258: uses a separate floating point stack, but a unified stack
1.29 crook 4259: notation. Also, return stack effects are not shown in @i{stack
4260: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4261: the type and/or the function of the item. See below for a discussion of
4262: the types.
4263:
4264: All words have two stack effects: A compile-time stack effect and a
4265: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4266: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4267: this standard behaviour, or the word does other unusual things at
4268: compile time, both stack effects are shown; otherwise only the run-time
4269: stack effect is shown.
4270:
4271: @cindex pronounciation of words
4272: @item pronunciation
4273: How the word is pronounced.
4274:
4275: @cindex wordset
1.67 anton 4276: @cindex environment wordset
1.1 anton 4277: @item wordset
1.21 crook 4278: The ANS Forth standard is divided into several word sets. A standard
4279: system need not support all of them. Therefore, in theory, the fewer
4280: word sets your program uses the more portable it will be. However, we
4281: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4282: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4283: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4284: describes words that will work in future releases of Gforth;
4285: @code{gforth-internal} words are more volatile. Environmental query
4286: strings are also displayed like words; you can recognize them by the
1.21 crook 4287: @code{environment} in the word set field.
1.1 anton 4288:
4289: @item Description
4290: A description of the behaviour of the word.
4291: @end table
4292:
4293: @cindex types of stack items
4294: @cindex stack item types
4295: The type of a stack item is specified by the character(s) the name
4296: starts with:
4297:
4298: @table @code
4299: @item f
4300: @cindex @code{f}, stack item type
4301: Boolean flags, i.e. @code{false} or @code{true}.
4302: @item c
4303: @cindex @code{c}, stack item type
4304: Char
4305: @item w
4306: @cindex @code{w}, stack item type
4307: Cell, can contain an integer or an address
4308: @item n
4309: @cindex @code{n}, stack item type
4310: signed integer
4311: @item u
4312: @cindex @code{u}, stack item type
4313: unsigned integer
4314: @item d
4315: @cindex @code{d}, stack item type
4316: double sized signed integer
4317: @item ud
4318: @cindex @code{ud}, stack item type
4319: double sized unsigned integer
4320: @item r
4321: @cindex @code{r}, stack item type
4322: Float (on the FP stack)
1.21 crook 4323: @item a-
1.1 anton 4324: @cindex @code{a_}, stack item type
4325: Cell-aligned address
1.21 crook 4326: @item c-
1.1 anton 4327: @cindex @code{c_}, stack item type
4328: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4329: @item f-
1.1 anton 4330: @cindex @code{f_}, stack item type
4331: Float-aligned address
1.21 crook 4332: @item df-
1.1 anton 4333: @cindex @code{df_}, stack item type
4334: Address aligned for IEEE double precision float
1.21 crook 4335: @item sf-
1.1 anton 4336: @cindex @code{sf_}, stack item type
4337: Address aligned for IEEE single precision float
4338: @item xt
4339: @cindex @code{xt}, stack item type
4340: Execution token, same size as Cell
4341: @item wid
4342: @cindex @code{wid}, stack item type
1.21 crook 4343: Word list ID, same size as Cell
1.68 anton 4344: @item ior, wior
4345: @cindex ior type description
4346: @cindex wior type description
4347: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4348: @item f83name
4349: @cindex @code{f83name}, stack item type
4350: Pointer to a name structure
4351: @item "
4352: @cindex @code{"}, stack item type
1.12 anton 4353: string in the input stream (not on the stack). The terminating character
4354: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4355: quotes.
4356: @end table
4357:
1.65 anton 4358: @comment ----------------------------------------------
4359: @node Case insensitivity, Comments, Notation, Words
4360: @section Case insensitivity
4361: @cindex case sensitivity
4362: @cindex upper and lower case
4363:
4364: Gforth is case-insensitive; you can enter definitions and invoke
4365: Standard words using upper, lower or mixed case (however,
4366: @pxref{core-idef, Implementation-defined options, Implementation-defined
4367: options}).
4368:
4369: ANS Forth only @i{requires} implementations to recognise Standard words
4370: when they are typed entirely in upper case. Therefore, a Standard
4371: program must use upper case for all Standard words. You can use whatever
4372: case you like for words that you define, but in a Standard program you
4373: have to use the words in the same case that you defined them.
4374:
4375: Gforth supports case sensitivity through @code{table}s (case-sensitive
4376: wordlists, @pxref{Word Lists}).
4377:
4378: Two people have asked how to convert Gforth to be case-sensitive; while
4379: we think this is a bad idea, you can change all wordlists into tables
4380: like this:
4381:
4382: @example
4383: ' table-find forth-wordlist wordlist-map @ !
4384: @end example
4385:
4386: Note that you now have to type the predefined words in the same case
4387: that we defined them, which are varying. You may want to convert them
4388: to your favourite case before doing this operation (I won't explain how,
4389: because if you are even contemplating doing this, you'd better have
4390: enough knowledge of Forth systems to know this already).
4391:
4392: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4393: @section Comments
1.26 crook 4394: @cindex comments
1.21 crook 4395:
1.29 crook 4396: Forth supports two styles of comment; the traditional @i{in-line} comment,
4397: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4398:
1.44 crook 4399:
1.23 crook 4400: doc-(
1.21 crook 4401: doc-\
1.23 crook 4402: doc-\G
1.21 crook 4403:
1.44 crook 4404:
1.21 crook 4405: @node Boolean Flags, Arithmetic, Comments, Words
4406: @section Boolean Flags
1.26 crook 4407: @cindex Boolean flags
1.21 crook 4408:
4409: A Boolean flag is cell-sized. A cell with all bits clear represents the
4410: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4411: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4412: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4413: @c on and off to Memory?
4414: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4415:
1.21 crook 4416: doc-true
4417: doc-false
1.29 crook 4418: doc-on
4419: doc-off
1.21 crook 4420:
1.44 crook 4421:
1.21 crook 4422: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4423: @section Arithmetic
4424: @cindex arithmetic words
4425:
4426: @cindex division with potentially negative operands
4427: Forth arithmetic is not checked, i.e., you will not hear about integer
4428: overflow on addition or multiplication, you may hear about division by
4429: zero if you are lucky. The operator is written after the operands, but
4430: the operands are still in the original order. I.e., the infix @code{2-1}
4431: corresponds to @code{2 1 -}. Forth offers a variety of division
4432: operators. If you perform division with potentially negative operands,
4433: you do not want to use @code{/} or @code{/mod} with its undefined
4434: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4435: former, @pxref{Mixed precision}).
1.26 crook 4436: @comment TODO discuss the different division forms and the std approach
1.1 anton 4437:
4438: @menu
4439: * Single precision::
1.67 anton 4440: * Double precision:: Double-cell integer arithmetic
1.1 anton 4441: * Bitwise operations::
1.67 anton 4442: * Numeric comparison::
1.29 crook 4443: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4444: * Floating Point::
4445: @end menu
4446:
1.67 anton 4447: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4448: @subsection Single precision
4449: @cindex single precision arithmetic words
4450:
1.67 anton 4451: @c !! cell undefined
4452:
4453: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4454: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4455: treat them. For the rules used by the text interpreter for recognising
4456: single-precision integers see @ref{Number Conversion}.
1.21 crook 4457:
1.67 anton 4458: These words are all defined for signed operands, but some of them also
4459: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4460: @code{*}.
1.44 crook 4461:
1.1 anton 4462: doc-+
1.21 crook 4463: doc-1+
1.128 ! anton 4464: doc-under+
1.1 anton 4465: doc--
1.21 crook 4466: doc-1-
1.1 anton 4467: doc-*
4468: doc-/
4469: doc-mod
4470: doc-/mod
4471: doc-negate
4472: doc-abs
4473: doc-min
4474: doc-max
1.27 crook 4475: doc-floored
1.1 anton 4476:
1.44 crook 4477:
1.67 anton 4478: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4479: @subsection Double precision
4480: @cindex double precision arithmetic words
4481:
1.49 anton 4482: For the rules used by the text interpreter for
4483: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4484:
4485: A double precision number is represented by a cell pair, with the most
1.67 anton 4486: significant cell at the TOS. It is trivial to convert an unsigned single
4487: to a double: simply push a @code{0} onto the TOS. Since numbers are
4488: represented by Gforth using 2's complement arithmetic, converting a
4489: signed single to a (signed) double requires sign-extension across the
4490: most significant cell. This can be achieved using @code{s>d}. The moral
4491: of the story is that you cannot convert a number without knowing whether
4492: it represents an unsigned or a signed number.
1.21 crook 4493:
1.67 anton 4494: These words are all defined for signed operands, but some of them also
4495: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4496:
1.21 crook 4497: doc-s>d
1.67 anton 4498: doc-d>s
1.21 crook 4499: doc-d+
4500: doc-d-
4501: doc-dnegate
4502: doc-dabs
4503: doc-dmin
4504: doc-dmax
4505:
1.44 crook 4506:
1.67 anton 4507: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4508: @subsection Bitwise operations
4509: @cindex bitwise operation words
4510:
4511:
4512: doc-and
4513: doc-or
4514: doc-xor
4515: doc-invert
4516: doc-lshift
4517: doc-rshift
4518: doc-2*
4519: doc-d2*
4520: doc-2/
4521: doc-d2/
4522:
4523:
4524: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4525: @subsection Numeric comparison
4526: @cindex numeric comparison words
4527:
1.67 anton 4528: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4529: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4530:
1.28 crook 4531: doc-<
4532: doc-<=
4533: doc-<>
4534: doc-=
4535: doc->
4536: doc->=
4537:
1.21 crook 4538: doc-0<
1.23 crook 4539: doc-0<=
1.21 crook 4540: doc-0<>
4541: doc-0=
1.23 crook 4542: doc-0>
4543: doc-0>=
1.28 crook 4544:
4545: doc-u<
4546: doc-u<=
1.44 crook 4547: @c u<> and u= exist but are the same as <> and =
1.31 anton 4548: @c doc-u<>
4549: @c doc-u=
1.28 crook 4550: doc-u>
4551: doc-u>=
4552:
4553: doc-within
4554:
4555: doc-d<
4556: doc-d<=
4557: doc-d<>
4558: doc-d=
4559: doc-d>
4560: doc-d>=
1.23 crook 4561:
1.21 crook 4562: doc-d0<
1.23 crook 4563: doc-d0<=
4564: doc-d0<>
1.21 crook 4565: doc-d0=
1.23 crook 4566: doc-d0>
4567: doc-d0>=
4568:
1.21 crook 4569: doc-du<
1.28 crook 4570: doc-du<=
1.44 crook 4571: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4572: @c doc-du<>
4573: @c doc-du=
1.28 crook 4574: doc-du>
4575: doc-du>=
1.1 anton 4576:
1.44 crook 4577:
1.21 crook 4578: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4579: @subsection Mixed precision
4580: @cindex mixed precision arithmetic words
4581:
1.44 crook 4582:
1.1 anton 4583: doc-m+
4584: doc-*/
4585: doc-*/mod
4586: doc-m*
4587: doc-um*
4588: doc-m*/
4589: doc-um/mod
4590: doc-fm/mod
4591: doc-sm/rem
4592:
1.44 crook 4593:
1.21 crook 4594: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4595: @subsection Floating Point
4596: @cindex floating point arithmetic words
4597:
1.49 anton 4598: For the rules used by the text interpreter for
4599: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4600:
1.67 anton 4601: Gforth has a separate floating point stack, but the documentation uses
4602: the unified notation.@footnote{It's easy to generate the separate
4603: notation from that by just separating the floating-point numbers out:
4604: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4605: r3 )}.}
1.1 anton 4606:
4607: @cindex floating-point arithmetic, pitfalls
4608: Floating point numbers have a number of unpleasant surprises for the
4609: unwary (e.g., floating point addition is not associative) and even a few
4610: for the wary. You should not use them unless you know what you are doing
4611: or you don't care that the results you get are totally bogus. If you
4612: want to learn about the problems of floating point numbers (and how to
1.66 anton 4613: avoid them), you might start with @cite{David Goldberg,
4614: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4615: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4616: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4617:
1.44 crook 4618:
1.21 crook 4619: doc-d>f
4620: doc-f>d
1.1 anton 4621: doc-f+
4622: doc-f-
4623: doc-f*
4624: doc-f/
4625: doc-fnegate
4626: doc-fabs
4627: doc-fmax
4628: doc-fmin
4629: doc-floor
4630: doc-fround
4631: doc-f**
4632: doc-fsqrt
4633: doc-fexp
4634: doc-fexpm1
4635: doc-fln
4636: doc-flnp1
4637: doc-flog
4638: doc-falog
1.32 anton 4639: doc-f2*
4640: doc-f2/
4641: doc-1/f
4642: doc-precision
4643: doc-set-precision
4644:
4645: @cindex angles in trigonometric operations
4646: @cindex trigonometric operations
4647: Angles in floating point operations are given in radians (a full circle
4648: has 2 pi radians).
4649:
1.1 anton 4650: doc-fsin
4651: doc-fcos
4652: doc-fsincos
4653: doc-ftan
4654: doc-fasin
4655: doc-facos
4656: doc-fatan
4657: doc-fatan2
4658: doc-fsinh
4659: doc-fcosh
4660: doc-ftanh
4661: doc-fasinh
4662: doc-facosh
4663: doc-fatanh
1.21 crook 4664: doc-pi
1.28 crook 4665:
1.32 anton 4666: @cindex equality of floats
4667: @cindex floating-point comparisons
1.31 anton 4668: One particular problem with floating-point arithmetic is that comparison
4669: for equality often fails when you would expect it to succeed. For this
4670: reason approximate equality is often preferred (but you still have to
1.67 anton 4671: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4672: differently from what you might expect. The comparison words are:
1.31 anton 4673:
4674: doc-f~rel
4675: doc-f~abs
1.68 anton 4676: doc-f~
1.31 anton 4677: doc-f=
4678: doc-f<>
4679:
4680: doc-f<
4681: doc-f<=
4682: doc-f>
4683: doc-f>=
4684:
1.21 crook 4685: doc-f0<
1.28 crook 4686: doc-f0<=
4687: doc-f0<>
1.21 crook 4688: doc-f0=
1.28 crook 4689: doc-f0>
4690: doc-f0>=
4691:
1.1 anton 4692:
4693: @node Stack Manipulation, Memory, Arithmetic, Words
4694: @section Stack Manipulation
4695: @cindex stack manipulation words
4696:
4697: @cindex floating-point stack in the standard
1.21 crook 4698: Gforth maintains a number of separate stacks:
4699:
1.29 crook 4700: @cindex data stack
4701: @cindex parameter stack
1.21 crook 4702: @itemize @bullet
4703: @item
1.29 crook 4704: A data stack (also known as the @dfn{parameter stack}) -- for
4705: characters, cells, addresses, and double cells.
1.21 crook 4706:
1.29 crook 4707: @cindex floating-point stack
1.21 crook 4708: @item
1.44 crook 4709: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4710:
1.29 crook 4711: @cindex return stack
1.21 crook 4712: @item
1.44 crook 4713: A return stack -- for holding the return addresses of colon
1.32 anton 4714: definitions and other (non-FP) data.
1.21 crook 4715:
1.29 crook 4716: @cindex locals stack
1.21 crook 4717: @item
1.44 crook 4718: A locals stack -- for holding local variables.
1.21 crook 4719: @end itemize
4720:
1.1 anton 4721: @menu
4722: * Data stack::
4723: * Floating point stack::
4724: * Return stack::
4725: * Locals stack::
4726: * Stack pointer manipulation::
4727: @end menu
4728:
4729: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4730: @subsection Data stack
4731: @cindex data stack manipulation words
4732: @cindex stack manipulations words, data stack
4733:
1.44 crook 4734:
1.1 anton 4735: doc-drop
4736: doc-nip
4737: doc-dup
4738: doc-over
4739: doc-tuck
4740: doc-swap
1.21 crook 4741: doc-pick
1.1 anton 4742: doc-rot
4743: doc--rot
4744: doc-?dup
4745: doc-roll
4746: doc-2drop
4747: doc-2nip
4748: doc-2dup
4749: doc-2over
4750: doc-2tuck
4751: doc-2swap
4752: doc-2rot
4753:
1.44 crook 4754:
1.1 anton 4755: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4756: @subsection Floating point stack
4757: @cindex floating-point stack manipulation words
4758: @cindex stack manipulation words, floating-point stack
4759:
1.32 anton 4760: Whilst every sane Forth has a separate floating-point stack, it is not
4761: strictly required; an ANS Forth system could theoretically keep
4762: floating-point numbers on the data stack. As an additional difficulty,
4763: you don't know how many cells a floating-point number takes. It is
4764: reportedly possible to write words in a way that they work also for a
4765: unified stack model, but we do not recommend trying it. Instead, just
4766: say that your program has an environmental dependency on a separate
4767: floating-point stack.
4768:
4769: doc-floating-stack
4770:
1.1 anton 4771: doc-fdrop
4772: doc-fnip
4773: doc-fdup
4774: doc-fover
4775: doc-ftuck
4776: doc-fswap
1.21 crook 4777: doc-fpick
1.1 anton 4778: doc-frot
4779:
1.44 crook 4780:
1.1 anton 4781: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4782: @subsection Return stack
4783: @cindex return stack manipulation words
4784: @cindex stack manipulation words, return stack
4785:
1.32 anton 4786: @cindex return stack and locals
4787: @cindex locals and return stack
4788: A Forth system is allowed to keep local variables on the
4789: return stack. This is reasonable, as local variables usually eliminate
4790: the need to use the return stack explicitly. So, if you want to produce
4791: a standard compliant program and you are using local variables in a
4792: word, forget about return stack manipulations in that word (refer to the
4793: standard document for the exact rules).
4794:
1.1 anton 4795: doc->r
4796: doc-r>
4797: doc-r@
4798: doc-rdrop
4799: doc-2>r
4800: doc-2r>
4801: doc-2r@
4802: doc-2rdrop
4803:
1.44 crook 4804:
1.1 anton 4805: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4806: @subsection Locals stack
4807:
1.78 anton 4808: Gforth uses an extra locals stack. It is described, along with the
4809: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4810:
1.1 anton 4811: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4812: @subsection Stack pointer manipulation
4813: @cindex stack pointer manipulation words
4814:
1.44 crook 4815: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4816: doc-sp0
1.1 anton 4817: doc-sp@
4818: doc-sp!
1.21 crook 4819: doc-fp0
1.1 anton 4820: doc-fp@
4821: doc-fp!
1.21 crook 4822: doc-rp0
1.1 anton 4823: doc-rp@
4824: doc-rp!
1.21 crook 4825: doc-lp0
1.1 anton 4826: doc-lp@
4827: doc-lp!
4828:
1.44 crook 4829:
1.1 anton 4830: @node Memory, Control Structures, Stack Manipulation, Words
4831: @section Memory
1.26 crook 4832: @cindex memory words
1.1 anton 4833:
1.32 anton 4834: @menu
4835: * Memory model::
4836: * Dictionary allocation::
4837: * Heap Allocation::
4838: * Memory Access::
4839: * Address arithmetic::
4840: * Memory Blocks::
4841: @end menu
4842:
1.67 anton 4843: In addition to the standard Forth memory allocation words, there is also
4844: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4845: garbage collector}.
4846:
1.32 anton 4847: @node Memory model, Dictionary allocation, Memory, Memory
4848: @subsection ANS Forth and Gforth memory models
4849:
4850: @c The ANS Forth description is a mess (e.g., is the heap part of
4851: @c the dictionary?), so let's not stick to closely with it.
4852:
1.67 anton 4853: ANS Forth considers a Forth system as consisting of several address
4854: spaces, of which only @dfn{data space} is managed and accessible with
4855: the memory words. Memory not necessarily in data space includes the
4856: stacks, the code (called code space) and the headers (called name
4857: space). In Gforth everything is in data space, but the code for the
4858: primitives is usually read-only.
1.32 anton 4859:
4860: Data space is divided into a number of areas: The (data space portion of
4861: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4862: refer to the search data structure embodied in word lists and headers,
4863: because it is used for looking up names, just as you would in a
4864: conventional dictionary.}, the heap, and a number of system-allocated
4865: buffers.
4866:
1.68 anton 4867: @cindex address arithmetic restrictions, ANS vs. Gforth
4868: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4869: In ANS Forth data space is also divided into contiguous regions. You
4870: can only use address arithmetic within a contiguous region, not between
4871: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4872: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4873: allocation}).
4874:
4875: Gforth provides one big address space, and address arithmetic can be
4876: performed between any addresses. However, in the dictionary headers or
4877: code are interleaved with data, so almost the only contiguous data space
4878: regions there are those described by ANS Forth as contiguous; but you
4879: can be sure that the dictionary is allocated towards increasing
4880: addresses even between contiguous regions. The memory order of
4881: allocations in the heap is platform-dependent (and possibly different
4882: from one run to the next).
4883:
1.27 crook 4884:
1.32 anton 4885: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4886: @subsection Dictionary allocation
1.27 crook 4887: @cindex reserving data space
4888: @cindex data space - reserving some
4889:
1.32 anton 4890: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4891: you want to deallocate X, you also deallocate everything
4892: allocated after X.
4893:
1.68 anton 4894: @cindex contiguous regions in dictionary allocation
1.32 anton 4895: The allocations using the words below are contiguous and grow the region
4896: towards increasing addresses. Other words that allocate dictionary
4897: memory of any kind (i.e., defining words including @code{:noname}) end
4898: the contiguous region and start a new one.
4899:
4900: In ANS Forth only @code{create}d words are guaranteed to produce an
4901: address that is the start of the following contiguous region. In
4902: particular, the cell allocated by @code{variable} is not guaranteed to
4903: be contiguous with following @code{allot}ed memory.
4904:
4905: You can deallocate memory by using @code{allot} with a negative argument
4906: (with some restrictions, see @code{allot}). For larger deallocations use
4907: @code{marker}.
1.27 crook 4908:
1.29 crook 4909:
1.27 crook 4910: doc-here
4911: doc-unused
4912: doc-allot
4913: doc-c,
1.29 crook 4914: doc-f,
1.27 crook 4915: doc-,
4916: doc-2,
4917:
1.32 anton 4918: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4919: course you should allocate memory in an aligned way, too. I.e., before
4920: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4921: The words below align @code{here} if it is not already. Basically it is
4922: only already aligned for a type, if the last allocation was a multiple
4923: of the size of this type and if @code{here} was aligned for this type
4924: before.
4925:
4926: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4927: ANS Forth (@code{maxalign}ed in Gforth).
4928:
4929: doc-align
4930: doc-falign
4931: doc-sfalign
4932: doc-dfalign
4933: doc-maxalign
4934: doc-cfalign
4935:
4936:
4937: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4938: @subsection Heap allocation
4939: @cindex heap allocation
4940: @cindex dynamic allocation of memory
4941: @cindex memory-allocation word set
4942:
1.68 anton 4943: @cindex contiguous regions and heap allocation
1.32 anton 4944: Heap allocation supports deallocation of allocated memory in any
4945: order. Dictionary allocation is not affected by it (i.e., it does not
4946: end a contiguous region). In Gforth, these words are implemented using
4947: the standard C library calls malloc(), free() and resize().
4948:
1.68 anton 4949: The memory region produced by one invocation of @code{allocate} or
4950: @code{resize} is internally contiguous. There is no contiguity between
4951: such a region and any other region (including others allocated from the
4952: heap).
4953:
1.32 anton 4954: doc-allocate
4955: doc-free
4956: doc-resize
4957:
1.27 crook 4958:
1.32 anton 4959: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4960: @subsection Memory Access
4961: @cindex memory access words
4962:
4963: doc-@
4964: doc-!
4965: doc-+!
4966: doc-c@
4967: doc-c!
4968: doc-2@
4969: doc-2!
4970: doc-f@
4971: doc-f!
4972: doc-sf@
4973: doc-sf!
4974: doc-df@
4975: doc-df!
4976:
1.68 anton 4977:
1.32 anton 4978: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4979: @subsection Address arithmetic
1.1 anton 4980: @cindex address arithmetic words
4981:
1.67 anton 4982: Address arithmetic is the foundation on which you can build data
4983: structures like arrays, records (@pxref{Structures}) and objects
4984: (@pxref{Object-oriented Forth}).
1.32 anton 4985:
1.68 anton 4986: @cindex address unit
4987: @cindex au (address unit)
1.1 anton 4988: ANS Forth does not specify the sizes of the data types. Instead, it
4989: offers a number of words for computing sizes and doing address
1.29 crook 4990: arithmetic. Address arithmetic is performed in terms of address units
4991: (aus); on most systems the address unit is one byte. Note that a
4992: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 4993: platforms where it is a noop, it compiles to nothing).
1.1 anton 4994:
1.67 anton 4995: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
4996: you have the address of a cell, perform @code{1 cells +}, and you will
4997: have the address of the next cell.
4998:
1.68 anton 4999: @cindex contiguous regions and address arithmetic
1.67 anton 5000: In ANS Forth you can perform address arithmetic only within a contiguous
5001: region, i.e., if you have an address into one region, you can only add
5002: and subtract such that the result is still within the region; you can
5003: only subtract or compare addresses from within the same contiguous
5004: region. Reasons: several contiguous regions can be arranged in memory
5005: in any way; on segmented systems addresses may have unusual
5006: representations, such that address arithmetic only works within a
5007: region. Gforth provides a few more guarantees (linear address space,
5008: dictionary grows upwards), but in general I have found it easy to stay
5009: within contiguous regions (exception: computing and comparing to the
5010: address just beyond the end of an array).
5011:
1.1 anton 5012: @cindex alignment of addresses for types
5013: ANS Forth also defines words for aligning addresses for specific
5014: types. Many computers require that accesses to specific data types
5015: must only occur at specific addresses; e.g., that cells may only be
5016: accessed at addresses divisible by 4. Even if a machine allows unaligned
5017: accesses, it can usually perform aligned accesses faster.
5018:
5019: For the performance-conscious: alignment operations are usually only
5020: necessary during the definition of a data structure, not during the
5021: (more frequent) accesses to it.
5022:
5023: ANS Forth defines no words for character-aligning addresses. This is not
5024: an oversight, but reflects the fact that addresses that are not
5025: char-aligned have no use in the standard and therefore will not be
5026: created.
5027:
5028: @cindex @code{CREATE} and alignment
1.29 crook 5029: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5030: are cell-aligned; in addition, Gforth guarantees that these addresses
5031: are aligned for all purposes.
5032:
1.26 crook 5033: Note that the ANS Forth word @code{char} has nothing to do with address
5034: arithmetic.
1.1 anton 5035:
1.44 crook 5036:
1.1 anton 5037: doc-chars
5038: doc-char+
5039: doc-cells
5040: doc-cell+
5041: doc-cell
5042: doc-aligned
5043: doc-floats
5044: doc-float+
5045: doc-float
5046: doc-faligned
5047: doc-sfloats
5048: doc-sfloat+
5049: doc-sfaligned
5050: doc-dfloats
5051: doc-dfloat+
5052: doc-dfaligned
5053: doc-maxaligned
5054: doc-cfaligned
5055: doc-address-unit-bits
5056:
1.44 crook 5057:
1.32 anton 5058: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5059: @subsection Memory Blocks
5060: @cindex memory block words
1.27 crook 5061: @cindex character strings - moving and copying
5062:
1.49 anton 5063: Memory blocks often represent character strings; For ways of storing
5064: character strings in memory see @ref{String Formats}. For other
5065: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5066:
1.67 anton 5067: A few of these words work on address unit blocks. In that case, you
5068: usually have to insert @code{CHARS} before the word when working on
5069: character strings. Most words work on character blocks, and expect a
5070: char-aligned address.
5071:
5072: When copying characters between overlapping memory regions, use
5073: @code{chars move} or choose carefully between @code{cmove} and
5074: @code{cmove>}.
1.44 crook 5075:
1.1 anton 5076: doc-move
5077: doc-erase
5078: doc-cmove
5079: doc-cmove>
5080: doc-fill
5081: doc-blank
1.21 crook 5082: doc-compare
1.111 anton 5083: doc-str=
5084: doc-str<
5085: doc-string-prefix?
1.21 crook 5086: doc-search
1.27 crook 5087: doc--trailing
5088: doc-/string
1.82 anton 5089: doc-bounds
1.44 crook 5090:
1.111 anton 5091:
1.27 crook 5092: @comment TODO examples
5093:
1.1 anton 5094:
1.26 crook 5095: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5096: @section Control Structures
5097: @cindex control structures
5098:
1.33 anton 5099: Control structures in Forth cannot be used interpretively, only in a
5100: colon definition@footnote{To be precise, they have no interpretation
5101: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5102: not like this limitation, but have not seen a satisfying way around it
5103: yet, although many schemes have been proposed.
1.1 anton 5104:
5105: @menu
1.33 anton 5106: * Selection:: IF ... ELSE ... ENDIF
5107: * Simple Loops:: BEGIN ...
1.29 crook 5108: * Counted Loops:: DO
1.67 anton 5109: * Arbitrary control structures::
5110: * Calls and returns::
1.1 anton 5111: * Exception Handling::
5112: @end menu
5113:
5114: @node Selection, Simple Loops, Control Structures, Control Structures
5115: @subsection Selection
5116: @cindex selection control structures
5117: @cindex control structures for selection
5118:
5119: @cindex @code{IF} control structure
5120: @example
1.29 crook 5121: @i{flag}
1.1 anton 5122: IF
1.29 crook 5123: @i{code}
1.1 anton 5124: ENDIF
5125: @end example
1.21 crook 5126: @noindent
1.33 anton 5127:
1.44 crook 5128: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5129: with any bit set represents truth) @i{code} is executed.
1.33 anton 5130:
1.1 anton 5131: @example
1.29 crook 5132: @i{flag}
1.1 anton 5133: IF
1.29 crook 5134: @i{code1}
1.1 anton 5135: ELSE
1.29 crook 5136: @i{code2}
1.1 anton 5137: ENDIF
5138: @end example
5139:
1.44 crook 5140: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5141: executed.
1.33 anton 5142:
1.1 anton 5143: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5144: standard, and @code{ENDIF} is not, although it is quite popular. We
5145: recommend using @code{ENDIF}, because it is less confusing for people
5146: who also know other languages (and is not prone to reinforcing negative
5147: prejudices against Forth in these people). Adding @code{ENDIF} to a
5148: system that only supplies @code{THEN} is simple:
5149: @example
1.82 anton 5150: : ENDIF POSTPONE then ; immediate
1.1 anton 5151: @end example
5152:
5153: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5154: (adv.)} has the following meanings:
5155: @quotation
5156: ... 2b: following next after in order ... 3d: as a necessary consequence
5157: (if you were there, then you saw them).
5158: @end quotation
5159: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5160: and many other programming languages has the meaning 3d.]
5161:
1.21 crook 5162: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5163: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5164: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5165: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5166: @file{compat/control.fs}.
5167:
5168: @cindex @code{CASE} control structure
5169: @example
1.29 crook 5170: @i{n}
1.1 anton 5171: CASE
1.29 crook 5172: @i{n1} OF @i{code1} ENDOF
5173: @i{n2} OF @i{code2} ENDOF
1.1 anton 5174: @dots{}
1.68 anton 5175: ( n ) @i{default-code} ( n )
1.1 anton 5176: ENDCASE
5177: @end example
5178:
1.68 anton 5179: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5180: @i{ni} matches, the optional @i{default-code} is executed. The optional
5181: default case can be added by simply writing the code after the last
5182: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5183: not consume it.
1.1 anton 5184:
1.69 anton 5185: @progstyle
5186: To keep the code understandable, you should ensure that on all paths
5187: through a selection construct the stack is changed in the same way
5188: (wrt. number and types of stack items consumed and pushed).
5189:
1.1 anton 5190: @node Simple Loops, Counted Loops, Selection, Control Structures
5191: @subsection Simple Loops
5192: @cindex simple loops
5193: @cindex loops without count
5194:
5195: @cindex @code{WHILE} loop
5196: @example
5197: BEGIN
1.29 crook 5198: @i{code1}
5199: @i{flag}
1.1 anton 5200: WHILE
1.29 crook 5201: @i{code2}
1.1 anton 5202: REPEAT
5203: @end example
5204:
1.29 crook 5205: @i{code1} is executed and @i{flag} is computed. If it is true,
5206: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5207: false, execution continues after the @code{REPEAT}.
5208:
5209: @cindex @code{UNTIL} loop
5210: @example
5211: BEGIN
1.29 crook 5212: @i{code}
5213: @i{flag}
1.1 anton 5214: UNTIL
5215: @end example
5216:
1.29 crook 5217: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5218:
1.69 anton 5219: @progstyle
5220: To keep the code understandable, a complete iteration of the loop should
5221: not change the number and types of the items on the stacks.
5222:
1.1 anton 5223: @cindex endless loop
5224: @cindex loops, endless
5225: @example
5226: BEGIN
1.29 crook 5227: @i{code}
1.1 anton 5228: AGAIN
5229: @end example
5230:
5231: This is an endless loop.
5232:
5233: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5234: @subsection Counted Loops
5235: @cindex counted loops
5236: @cindex loops, counted
5237: @cindex @code{DO} loops
5238:
5239: The basic counted loop is:
5240: @example
1.29 crook 5241: @i{limit} @i{start}
1.1 anton 5242: ?DO
1.29 crook 5243: @i{body}
1.1 anton 5244: LOOP
5245: @end example
5246:
1.29 crook 5247: This performs one iteration for every integer, starting from @i{start}
5248: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5249: accessed with @code{i}. For example, the loop:
1.1 anton 5250: @example
5251: 10 0 ?DO
5252: i .
5253: LOOP
5254: @end example
1.21 crook 5255: @noindent
5256: prints @code{0 1 2 3 4 5 6 7 8 9}
5257:
1.1 anton 5258: The index of the innermost loop can be accessed with @code{i}, the index
5259: of the next loop with @code{j}, and the index of the third loop with
5260: @code{k}.
5261:
1.44 crook 5262:
1.1 anton 5263: doc-i
5264: doc-j
5265: doc-k
5266:
1.44 crook 5267:
1.1 anton 5268: The loop control data are kept on the return stack, so there are some
1.21 crook 5269: restrictions on mixing return stack accesses and counted loop words. In
5270: particuler, if you put values on the return stack outside the loop, you
5271: cannot read them inside the loop@footnote{well, not in a way that is
5272: portable.}. If you put values on the return stack within a loop, you
5273: have to remove them before the end of the loop and before accessing the
5274: index of the loop.
1.1 anton 5275:
5276: There are several variations on the counted loop:
5277:
1.21 crook 5278: @itemize @bullet
5279: @item
5280: @code{LEAVE} leaves the innermost counted loop immediately; execution
5281: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5282:
5283: @example
5284: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5285: @end example
5286: prints @code{0 1 2 3}
5287:
1.1 anton 5288:
1.21 crook 5289: @item
5290: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5291: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5292: return stack so @code{EXIT} can get to its return address. For example:
5293:
5294: @example
5295: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5296: @end example
5297: prints @code{0 1 2 3}
5298:
5299:
5300: @item
1.29 crook 5301: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5302: (and @code{LOOP} iterates until they become equal by wrap-around
5303: arithmetic). This behaviour is usually not what you want. Therefore,
5304: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5305: @code{?DO}), which do not enter the loop if @i{start} is greater than
5306: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5307: unsigned loop parameters.
5308:
1.21 crook 5309: @item
5310: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5311: the loop, independent of the loop parameters. Do not use @code{DO}, even
5312: if you know that the loop is entered in any case. Such knowledge tends
5313: to become invalid during maintenance of a program, and then the
5314: @code{DO} will make trouble.
5315:
5316: @item
1.29 crook 5317: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5318: index by @i{n} instead of by 1. The loop is terminated when the border
5319: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5320:
1.21 crook 5321: @example
5322: 4 0 +DO i . 2 +LOOP
5323: @end example
5324: @noindent
5325: prints @code{0 2}
5326:
5327: @example
5328: 4 1 +DO i . 2 +LOOP
5329: @end example
5330: @noindent
5331: prints @code{1 3}
1.1 anton 5332:
1.68 anton 5333: @item
1.1 anton 5334: @cindex negative increment for counted loops
5335: @cindex counted loops with negative increment
1.29 crook 5336: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5337:
1.21 crook 5338: @example
5339: -1 0 ?DO i . -1 +LOOP
5340: @end example
5341: @noindent
5342: prints @code{0 -1}
1.1 anton 5343:
1.21 crook 5344: @example
5345: 0 0 ?DO i . -1 +LOOP
5346: @end example
5347: prints nothing.
1.1 anton 5348:
1.29 crook 5349: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5350: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5351: index by @i{u} each iteration. The loop is terminated when the border
5352: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5353: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5354:
1.21 crook 5355: @example
5356: -2 0 -DO i . 1 -LOOP
5357: @end example
5358: @noindent
5359: prints @code{0 -1}
1.1 anton 5360:
1.21 crook 5361: @example
5362: -1 0 -DO i . 1 -LOOP
5363: @end example
5364: @noindent
5365: prints @code{0}
5366:
5367: @example
5368: 0 0 -DO i . 1 -LOOP
5369: @end example
5370: @noindent
5371: prints nothing.
1.1 anton 5372:
1.21 crook 5373: @end itemize
1.1 anton 5374:
5375: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5376: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5377: for these words that uses only standard words is provided in
5378: @file{compat/loops.fs}.
1.1 anton 5379:
5380:
5381: @cindex @code{FOR} loops
1.26 crook 5382: Another counted loop is:
1.1 anton 5383: @example
1.29 crook 5384: @i{n}
1.1 anton 5385: FOR
1.29 crook 5386: @i{body}
1.1 anton 5387: NEXT
5388: @end example
5389: This is the preferred loop of native code compiler writers who are too
1.26 crook 5390: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5391: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5392: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5393: Forth systems may behave differently, even if they support @code{FOR}
5394: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5395:
5396: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5397: @subsection Arbitrary control structures
5398: @cindex control structures, user-defined
5399:
5400: @cindex control-flow stack
5401: ANS Forth permits and supports using control structures in a non-nested
5402: way. Information about incomplete control structures is stored on the
5403: control-flow stack. This stack may be implemented on the Forth data
5404: stack, and this is what we have done in Gforth.
5405:
5406: @cindex @code{orig}, control-flow stack item
5407: @cindex @code{dest}, control-flow stack item
5408: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5409: entry represents a backward branch target. A few words are the basis for
5410: building any control structure possible (except control structures that
5411: need storage, like calls, coroutines, and backtracking).
5412:
1.44 crook 5413:
1.1 anton 5414: doc-if
5415: doc-ahead
5416: doc-then
5417: doc-begin
5418: doc-until
5419: doc-again
5420: doc-cs-pick
5421: doc-cs-roll
5422:
1.44 crook 5423:
1.21 crook 5424: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5425: manipulate the control-flow stack in a portable way. Without them, you
5426: would need to know how many stack items are occupied by a control-flow
5427: entry (many systems use one cell. In Gforth they currently take three,
5428: but this may change in the future).
5429:
1.1 anton 5430: Some standard control structure words are built from these words:
5431:
1.44 crook 5432:
1.1 anton 5433: doc-else
5434: doc-while
5435: doc-repeat
5436:
1.44 crook 5437:
5438: @noindent
1.1 anton 5439: Gforth adds some more control-structure words:
5440:
1.44 crook 5441:
1.1 anton 5442: doc-endif
5443: doc-?dup-if
5444: doc-?dup-0=-if
5445:
1.44 crook 5446:
5447: @noindent
1.1 anton 5448: Counted loop words constitute a separate group of words:
5449:
1.44 crook 5450:
1.1 anton 5451: doc-?do
5452: doc-+do
5453: doc-u+do
5454: doc--do
5455: doc-u-do
5456: doc-do
5457: doc-for
5458: doc-loop
5459: doc-+loop
5460: doc--loop
5461: doc-next
5462: doc-leave
5463: doc-?leave
5464: doc-unloop
5465: doc-done
5466:
1.44 crook 5467:
1.21 crook 5468: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5469: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5470: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5471: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5472: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5473: resolved (by using one of the loop-ending words or @code{DONE}).
5474:
1.44 crook 5475: @noindent
1.26 crook 5476: Another group of control structure words are:
1.1 anton 5477:
1.44 crook 5478:
1.1 anton 5479: doc-case
5480: doc-endcase
5481: doc-of
5482: doc-endof
5483:
1.44 crook 5484:
1.21 crook 5485: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5486: @code{CS-ROLL}.
1.1 anton 5487:
5488: @subsubsection Programming Style
1.47 crook 5489: @cindex control structures programming style
5490: @cindex programming style, arbitrary control structures
1.1 anton 5491:
5492: In order to ensure readability we recommend that you do not create
5493: arbitrary control structures directly, but define new control structure
5494: words for the control structure you want and use these words in your
1.26 crook 5495: program. For example, instead of writing:
1.1 anton 5496:
5497: @example
1.26 crook 5498: BEGIN
1.1 anton 5499: ...
1.26 crook 5500: IF [ 1 CS-ROLL ]
1.1 anton 5501: ...
1.26 crook 5502: AGAIN THEN
1.1 anton 5503: @end example
5504:
1.21 crook 5505: @noindent
1.1 anton 5506: we recommend defining control structure words, e.g.,
5507:
5508: @example
1.26 crook 5509: : WHILE ( DEST -- ORIG DEST )
5510: POSTPONE IF
5511: 1 CS-ROLL ; immediate
5512:
5513: : REPEAT ( orig dest -- )
5514: POSTPONE AGAIN
5515: POSTPONE THEN ; immediate
1.1 anton 5516: @end example
5517:
1.21 crook 5518: @noindent
1.1 anton 5519: and then using these to create the control structure:
5520:
5521: @example
1.26 crook 5522: BEGIN
1.1 anton 5523: ...
1.26 crook 5524: WHILE
1.1 anton 5525: ...
1.26 crook 5526: REPEAT
1.1 anton 5527: @end example
5528:
5529: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5530: @code{WHILE} are predefined, so in this example it would not be
5531: necessary to define them.
5532:
5533: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5534: @subsection Calls and returns
5535: @cindex calling a definition
5536: @cindex returning from a definition
5537:
1.3 anton 5538: @cindex recursive definitions
5539: A definition can be called simply be writing the name of the definition
1.26 crook 5540: to be called. Normally a definition is invisible during its own
1.3 anton 5541: definition. If you want to write a directly recursive definition, you
1.26 crook 5542: can use @code{recursive} to make the current definition visible, or
5543: @code{recurse} to call the current definition directly.
1.3 anton 5544:
1.44 crook 5545:
1.3 anton 5546: doc-recursive
5547: doc-recurse
5548:
1.44 crook 5549:
1.21 crook 5550: @comment TODO add example of the two recursion methods
1.12 anton 5551: @quotation
5552: @progstyle
5553: I prefer using @code{recursive} to @code{recurse}, because calling the
5554: definition by name is more descriptive (if the name is well-chosen) than
5555: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5556: implementation, it is much better to read (and think) ``now sort the
5557: partitions'' than to read ``now do a recursive call''.
5558: @end quotation
1.3 anton 5559:
1.29 crook 5560: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5561:
5562: @example
1.28 crook 5563: Defer foo
1.3 anton 5564:
5565: : bar ( ... -- ... )
5566: ... foo ... ;
5567:
5568: :noname ( ... -- ... )
5569: ... bar ... ;
5570: IS foo
5571: @end example
5572:
1.44 crook 5573: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5574:
1.26 crook 5575: The current definition returns control to the calling definition when
1.33 anton 5576: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5577:
5578: doc-exit
5579: doc-;s
5580:
1.44 crook 5581:
1.1 anton 5582: @node Exception Handling, , Calls and returns, Control Structures
5583: @subsection Exception Handling
1.26 crook 5584: @cindex exceptions
1.1 anton 5585:
1.68 anton 5586: @c quit is a very bad idea for error handling,
5587: @c because it does not translate into a THROW
5588: @c it also does not belong into this chapter
5589:
5590: If a word detects an error condition that it cannot handle, it can
5591: @code{throw} an exception. In the simplest case, this will terminate
5592: your program, and report an appropriate error.
1.21 crook 5593:
1.68 anton 5594: doc-throw
1.1 anton 5595:
1.69 anton 5596: @code{Throw} consumes a cell-sized error number on the stack. There are
5597: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5598: Gforth (and most other systems) you can use the iors produced by various
5599: words as error numbers (e.g., a typical use of @code{allocate} is
5600: @code{allocate throw}). Gforth also provides the word @code{exception}
5601: to define your own error numbers (with decent error reporting); an ANS
5602: Forth version of this word (but without the error messages) is available
5603: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5604: numbers (anything outside the range -4095..0), but won't get nice error
5605: messages, only numbers. For example, try:
5606:
5607: @example
1.69 anton 5608: -10 throw \ ANS defined
5609: -267 throw \ system defined
5610: s" my error" exception throw \ user defined
5611: 7 throw \ arbitrary number
1.68 anton 5612: @end example
5613:
5614: doc---exception-exception
1.1 anton 5615:
1.69 anton 5616: A common idiom to @code{THROW} a specific error if a flag is true is
5617: this:
5618:
5619: @example
5620: @code{( flag ) 0<> @i{errno} and throw}
5621: @end example
5622:
5623: Your program can provide exception handlers to catch exceptions. An
5624: exception handler can be used to correct the problem, or to clean up
5625: some data structures and just throw the exception to the next exception
5626: handler. Note that @code{throw} jumps to the dynamically innermost
5627: exception handler. The system's exception handler is outermost, and just
5628: prints an error and restarts command-line interpretation (or, in batch
5629: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5630:
1.68 anton 5631: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5632:
1.68 anton 5633: doc-catch
5634:
5635: The most common use of exception handlers is to clean up the state when
5636: an error happens. E.g.,
1.1 anton 5637:
1.26 crook 5638: @example
1.68 anton 5639: base @ >r hex \ actually the hex should be inside foo, or we h
5640: ['] foo catch ( nerror|0 )
5641: r> base !
1.69 anton 5642: ( nerror|0 ) throw \ pass it on
1.26 crook 5643: @end example
1.1 anton 5644:
1.69 anton 5645: A use of @code{catch} for handling the error @code{myerror} might look
5646: like this:
1.44 crook 5647:
1.68 anton 5648: @example
1.69 anton 5649: ['] foo catch
5650: CASE
5651: myerror OF ... ( do something about it ) ENDOF
5652: dup throw \ default: pass other errors on, do nothing on non-errors
5653: ENDCASE
1.68 anton 5654: @end example
1.44 crook 5655:
1.68 anton 5656: Having to wrap the code into a separate word is often cumbersome,
5657: therefore Gforth provides an alternative syntax:
1.1 anton 5658:
5659: @example
1.69 anton 5660: TRY
1.68 anton 5661: @i{code1}
1.69 anton 5662: RECOVER \ optional
1.68 anton 5663: @i{code2} \ optional
1.69 anton 5664: ENDTRY
1.1 anton 5665: @end example
5666:
1.68 anton 5667: This performs @i{Code1}. If @i{code1} completes normally, execution
5668: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5669: reset to the state during @code{try}, the throw value is pushed on the
5670: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5671: through the @code{endtry} into the following code.
1.26 crook 5672:
1.68 anton 5673: doc-try
5674: doc-recover
5675: doc-endtry
1.26 crook 5676:
1.69 anton 5677: The cleanup example from above in this syntax:
1.26 crook 5678:
1.68 anton 5679: @example
1.69 anton 5680: base @ >r TRY
1.68 anton 5681: hex foo \ now the hex is placed correctly
1.69 anton 5682: 0 \ value for throw
1.92 anton 5683: RECOVER ENDTRY
1.68 anton 5684: r> base ! throw
1.1 anton 5685: @end example
5686:
1.69 anton 5687: And here's the error handling example:
1.1 anton 5688:
1.68 anton 5689: @example
1.69 anton 5690: TRY
1.68 anton 5691: foo
1.69 anton 5692: RECOVER
5693: CASE
5694: myerror OF ... ( do something about it ) ENDOF
5695: throw \ pass other errors on
5696: ENDCASE
5697: ENDTRY
1.68 anton 5698: @end example
1.1 anton 5699:
1.69 anton 5700: @progstyle
5701: As usual, you should ensure that the stack depth is statically known at
5702: the end: either after the @code{throw} for passing on errors, or after
5703: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5704: selection construct for handling the error).
5705:
1.68 anton 5706: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5707: and you can provide an error message. @code{Abort} just produces an
5708: ``Aborted'' error.
1.1 anton 5709:
1.68 anton 5710: The problem with these words is that exception handlers cannot
5711: differentiate between different @code{abort"}s; they just look like
5712: @code{-2 throw} to them (the error message cannot be accessed by
5713: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5714: exception handlers.
1.44 crook 5715:
1.68 anton 5716: doc-abort"
1.26 crook 5717: doc-abort
1.29 crook 5718:
5719:
1.44 crook 5720:
1.29 crook 5721: @c -------------------------------------------------------------
1.47 crook 5722: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5723: @section Defining Words
5724: @cindex defining words
5725:
1.47 crook 5726: Defining words are used to extend Forth by creating new entries in the dictionary.
5727:
1.29 crook 5728: @menu
1.67 anton 5729: * CREATE::
1.44 crook 5730: * Variables:: Variables and user variables
1.67 anton 5731: * Constants::
1.44 crook 5732: * Values:: Initialised variables
1.67 anton 5733: * Colon Definitions::
1.44 crook 5734: * Anonymous Definitions:: Definitions without names
1.69 anton 5735: * Supplying names:: Passing definition names as strings
1.67 anton 5736: * User-defined Defining Words::
1.44 crook 5737: * Deferred words:: Allow forward references
1.67 anton 5738: * Aliases::
1.29 crook 5739: @end menu
5740:
1.44 crook 5741: @node CREATE, Variables, Defining Words, Defining Words
5742: @subsection @code{CREATE}
1.29 crook 5743: @cindex simple defining words
5744: @cindex defining words, simple
5745:
5746: Defining words are used to create new entries in the dictionary. The
5747: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5748: this:
5749:
5750: @example
5751: CREATE new-word1
5752: @end example
5753:
1.69 anton 5754: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5755: input stream (@code{new-word1} in our example). It generates a
5756: dictionary entry for @code{new-word1}. When @code{new-word1} is
5757: executed, all that it does is leave an address on the stack. The address
5758: represents the value of the data space pointer (@code{HERE}) at the time
5759: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5760: associating a name with the address of a region of memory.
1.29 crook 5761:
1.34 anton 5762: doc-create
5763:
1.69 anton 5764: Note that in ANS Forth guarantees only for @code{create} that its body
5765: is in dictionary data space (i.e., where @code{here}, @code{allot}
5766: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5767: @code{create}d words can be modified with @code{does>}
5768: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5769: can only be applied to @code{create}d words.
5770:
1.29 crook 5771: By extending this example to reserve some memory in data space, we end
1.69 anton 5772: up with something like a @i{variable}. Here are two different ways to do
5773: it:
1.29 crook 5774:
5775: @example
5776: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5777: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5778: @end example
5779:
5780: The variable can be examined and modified using @code{@@} (``fetch'') and
5781: @code{!} (``store'') like this:
5782:
5783: @example
5784: new-word2 @@ . \ get address, fetch from it and display
5785: 1234 new-word2 ! \ new value, get address, store to it
5786: @end example
5787:
1.44 crook 5788: @cindex arrays
5789: A similar mechanism can be used to create arrays. For example, an
5790: 80-character text input buffer:
1.29 crook 5791:
5792: @example
1.44 crook 5793: CREATE text-buf 80 chars allot
5794:
5795: text-buf 0 chars c@@ \ the 1st character (offset 0)
5796: text-buf 3 chars c@@ \ the 4th character (offset 3)
5797: @end example
1.29 crook 5798:
1.44 crook 5799: You can build arbitrarily complex data structures by allocating
1.49 anton 5800: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5801: learn about some Gforth tools that make it easier,
1.49 anton 5802: @xref{Structures}.
1.44 crook 5803:
5804:
5805: @node Variables, Constants, CREATE, Defining Words
5806: @subsection Variables
5807: @cindex variables
5808:
5809: The previous section showed how a sequence of commands could be used to
5810: generate a variable. As a final refinement, the whole code sequence can
5811: be wrapped up in a defining word (pre-empting the subject of the next
5812: section), making it easier to create new variables:
5813:
5814: @example
5815: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5816: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5817:
5818: myvariableX foo \ variable foo starts off with an unknown value
5819: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5820:
5821: 45 3 * foo ! \ set foo to 135
5822: 1234 joe ! \ set joe to 1234
5823: 3 joe +! \ increment joe by 3.. to 1237
5824: @end example
5825:
5826: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5827: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5828: guarantee that a @code{Variable} is initialised when it is created
5829: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5830: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5831: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5832: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5833: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5834: store a boolean, you can use @code{on} and @code{off} to toggle its
5835: state.
1.29 crook 5836:
1.34 anton 5837: doc-variable
5838: doc-2variable
5839: doc-fvariable
5840:
1.29 crook 5841: @cindex user variables
5842: @cindex user space
5843: The defining word @code{User} behaves in the same way as @code{Variable}.
5844: The difference is that it reserves space in @i{user (data) space} rather
5845: than normal data space. In a Forth system that has a multi-tasker, each
5846: task has its own set of user variables.
5847:
1.34 anton 5848: doc-user
1.67 anton 5849: @c doc-udp
5850: @c doc-uallot
1.34 anton 5851:
1.29 crook 5852: @comment TODO is that stuff about user variables strictly correct? Is it
5853: @comment just terminal tasks that have user variables?
5854: @comment should document tasker.fs (with some examples) elsewhere
5855: @comment in this manual, then expand on user space and user variables.
5856:
1.44 crook 5857: @node Constants, Values, Variables, Defining Words
5858: @subsection Constants
5859: @cindex constants
5860:
5861: @code{Constant} allows you to declare a fixed value and refer to it by
5862: name. For example:
1.29 crook 5863:
5864: @example
5865: 12 Constant INCHES-PER-FOOT
5866: 3E+08 fconstant SPEED-O-LIGHT
5867: @end example
5868:
5869: A @code{Variable} can be both read and written, so its run-time
5870: behaviour is to supply an address through which its current value can be
5871: manipulated. In contrast, the value of a @code{Constant} cannot be
5872: changed once it has been declared@footnote{Well, often it can be -- but
5873: not in a Standard, portable way. It's safer to use a @code{Value} (read
5874: on).} so it's not necessary to supply the address -- it is more
5875: efficient to return the value of the constant directly. That's exactly
5876: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5877: the top of the stack (You can find one
5878: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5879:
1.69 anton 5880: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5881: double and floating-point constants, respectively.
5882:
1.34 anton 5883: doc-constant
5884: doc-2constant
5885: doc-fconstant
5886:
5887: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5888: @c nac-> How could that not be true in an ANS Forth? You can't define a
5889: @c constant, use it and then delete the definition of the constant..
1.69 anton 5890:
5891: @c anton->An ANS Forth system can compile a constant to a literal; On
5892: @c decompilation you would see only the number, just as if it had been used
5893: @c in the first place. The word will stay, of course, but it will only be
5894: @c used by the text interpreter (no run-time duties, except when it is
5895: @c POSTPONEd or somesuch).
5896:
5897: @c nac:
1.44 crook 5898: @c I agree that it's rather deep, but IMO it is an important difference
5899: @c relative to other programming languages.. often it's annoying: it
5900: @c certainly changes my programming style relative to C.
5901:
1.69 anton 5902: @c anton: In what way?
5903:
1.29 crook 5904: Constants in Forth behave differently from their equivalents in other
5905: programming languages. In other languages, a constant (such as an EQU in
5906: assembler or a #define in C) only exists at compile-time; in the
5907: executable program the constant has been translated into an absolute
5908: number and, unless you are using a symbolic debugger, it's impossible to
5909: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5910: an entry in the header space and remains there after the code that uses
5911: it has been defined. In fact, it must remain in the dictionary since it
5912: has run-time duties to perform. For example:
1.29 crook 5913:
5914: @example
5915: 12 Constant INCHES-PER-FOOT
5916: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5917: @end example
5918:
5919: @cindex in-lining of constants
5920: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5921: associated with the constant @code{INCHES-PER-FOOT}. If you use
5922: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5923: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5924: attempt to optimise constants by in-lining them where they are used. You
5925: can force Gforth to in-line a constant like this:
5926:
5927: @example
5928: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5929: @end example
5930:
5931: If you use @code{see} to decompile @i{this} version of
5932: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5933: longer present. To understand how this works, read
5934: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5935:
5936: In-lining constants in this way might improve execution time
5937: fractionally, and can ensure that a constant is now only referenced at
5938: compile-time. However, the definition of the constant still remains in
5939: the dictionary. Some Forth compilers provide a mechanism for controlling
5940: a second dictionary for holding transient words such that this second
5941: dictionary can be deleted later in order to recover memory
5942: space. However, there is no standard way of doing this.
5943:
5944:
1.44 crook 5945: @node Values, Colon Definitions, Constants, Defining Words
5946: @subsection Values
5947: @cindex values
1.34 anton 5948:
1.69 anton 5949: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5950: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5951: (not in ANS Forth) you can access (and change) a @code{value} also with
5952: @code{>body}.
5953:
5954: Here are some
5955: examples:
1.29 crook 5956:
5957: @example
1.69 anton 5958: 12 Value APPLES \ Define APPLES with an initial value of 12
5959: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5960: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5961: APPLES \ puts 35 on the top of the stack.
1.29 crook 5962: @end example
5963:
1.44 crook 5964: doc-value
5965: doc-to
1.29 crook 5966:
1.35 anton 5967:
1.69 anton 5968:
1.44 crook 5969: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5970: @subsection Colon Definitions
5971: @cindex colon definitions
1.35 anton 5972:
5973: @example
1.44 crook 5974: : name ( ... -- ... )
5975: word1 word2 word3 ;
1.29 crook 5976: @end example
5977:
1.44 crook 5978: @noindent
5979: Creates a word called @code{name} that, upon execution, executes
5980: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 5981:
1.49 anton 5982: The explanation above is somewhat superficial. For simple examples of
5983: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 5984: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 5985: Compilation Semantics}.
1.29 crook 5986:
1.44 crook 5987: doc-:
5988: doc-;
1.1 anton 5989:
1.34 anton 5990:
1.69 anton 5991: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 5992: @subsection Anonymous Definitions
5993: @cindex colon definitions
5994: @cindex defining words without name
1.34 anton 5995:
1.44 crook 5996: Sometimes you want to define an @dfn{anonymous word}; a word without a
5997: name. You can do this with:
1.1 anton 5998:
1.44 crook 5999: doc-:noname
1.1 anton 6000:
1.44 crook 6001: This leaves the execution token for the word on the stack after the
6002: closing @code{;}. Here's an example in which a deferred word is
6003: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6004:
1.29 crook 6005: @example
1.44 crook 6006: Defer deferred
6007: :noname ( ... -- ... )
6008: ... ;
6009: IS deferred
1.29 crook 6010: @end example
1.26 crook 6011:
1.44 crook 6012: @noindent
6013: Gforth provides an alternative way of doing this, using two separate
6014: words:
1.27 crook 6015:
1.44 crook 6016: doc-noname
6017: @cindex execution token of last defined word
1.116 anton 6018: doc-latestxt
1.1 anton 6019:
1.44 crook 6020: @noindent
6021: The previous example can be rewritten using @code{noname} and
1.116 anton 6022: @code{latestxt}:
1.1 anton 6023:
1.26 crook 6024: @example
1.44 crook 6025: Defer deferred
6026: noname : ( ... -- ... )
6027: ... ;
1.116 anton 6028: latestxt IS deferred
1.26 crook 6029: @end example
1.1 anton 6030:
1.29 crook 6031: @noindent
1.44 crook 6032: @code{noname} works with any defining word, not just @code{:}.
6033:
1.116 anton 6034: @code{latestxt} also works when the last word was not defined as
1.71 anton 6035: @code{noname}. It does not work for combined words, though. It also has
6036: the useful property that is is valid as soon as the header for a
6037: definition has been built. Thus:
1.44 crook 6038:
6039: @example
1.116 anton 6040: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6041: @end example
1.1 anton 6042:
1.44 crook 6043: @noindent
6044: prints 3 numbers; the last two are the same.
1.26 crook 6045:
1.69 anton 6046: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6047: @subsection Supplying the name of a defined word
6048: @cindex names for defined words
6049: @cindex defining words, name given in a string
6050:
6051: By default, a defining word takes the name for the defined word from the
6052: input stream. Sometimes you want to supply the name from a string. You
6053: can do this with:
6054:
6055: doc-nextname
6056:
6057: For example:
6058:
6059: @example
6060: s" foo" nextname create
6061: @end example
6062:
6063: @noindent
6064: is equivalent to:
6065:
6066: @example
6067: create foo
6068: @end example
6069:
6070: @noindent
6071: @code{nextname} works with any defining word.
6072:
1.1 anton 6073:
1.69 anton 6074: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6075: @subsection User-defined Defining Words
6076: @cindex user-defined defining words
6077: @cindex defining words, user-defined
1.1 anton 6078:
1.29 crook 6079: You can create a new defining word by wrapping defining-time code around
6080: an existing defining word and putting the sequence in a colon
1.69 anton 6081: definition.
6082:
6083: @c anton: This example is very complex and leads in a quite different
6084: @c direction from the CREATE-DOES> stuff that follows. It should probably
6085: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6086: @c subsection of Defining Words)
6087:
6088: For example, suppose that you have a word @code{stats} that
1.29 crook 6089: gathers statistics about colon definitions given the @i{xt} of the
6090: definition, and you want every colon definition in your application to
6091: make a call to @code{stats}. You can define and use a new version of
6092: @code{:} like this:
6093:
6094: @example
6095: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6096: ... ; \ other code
6097:
1.116 anton 6098: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6099:
6100: my: foo + - ;
6101: @end example
6102:
6103: When @code{foo} is defined using @code{my:} these steps occur:
6104:
6105: @itemize @bullet
6106: @item
6107: @code{my:} is executed.
6108: @item
6109: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6110: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6111: the input stream for a name, builds a dictionary header for the name
6112: @code{foo} and switches @code{state} from interpret to compile.
6113: @item
1.116 anton 6114: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6115: being defined -- @code{foo} -- onto the stack.
6116: @item
6117: The code that was produced by @code{postpone literal} is executed; this
6118: causes the value on the stack to be compiled as a literal in the code
6119: area of @code{foo}.
6120: @item
6121: The code @code{['] stats} compiles a literal into the definition of
6122: @code{my:}. When @code{compile,} is executed, that literal -- the
6123: execution token for @code{stats} -- is layed down in the code area of
6124: @code{foo} , following the literal@footnote{Strictly speaking, the
6125: mechanism that @code{compile,} uses to convert an @i{xt} into something
6126: in the code area is implementation-dependent. A threaded implementation
6127: might spit out the execution token directly whilst another
6128: implementation might spit out a native code sequence.}.
6129: @item
6130: At this point, the execution of @code{my:} is complete, and control
6131: returns to the text interpreter. The text interpreter is in compile
6132: state, so subsequent text @code{+ -} is compiled into the definition of
6133: @code{foo} and the @code{;} terminates the definition as always.
6134: @end itemize
6135:
6136: You can use @code{see} to decompile a word that was defined using
6137: @code{my:} and see how it is different from a normal @code{:}
6138: definition. For example:
6139:
6140: @example
6141: : bar + - ; \ like foo but using : rather than my:
6142: see bar
6143: : bar
6144: + - ;
6145: see foo
6146: : foo
6147: 107645672 stats + - ;
6148:
6149: \ use ' stats . to show that 107645672 is the xt for stats
6150: @end example
6151:
6152: You can use techniques like this to make new defining words in terms of
6153: @i{any} existing defining word.
1.1 anton 6154:
6155:
1.29 crook 6156: @cindex defining defining words
1.26 crook 6157: @cindex @code{CREATE} ... @code{DOES>}
6158: If you want the words defined with your defining words to behave
6159: differently from words defined with standard defining words, you can
6160: write your defining word like this:
1.1 anton 6161:
6162: @example
1.26 crook 6163: : def-word ( "name" -- )
1.29 crook 6164: CREATE @i{code1}
1.26 crook 6165: DOES> ( ... -- ... )
1.29 crook 6166: @i{code2} ;
1.26 crook 6167:
6168: def-word name
1.1 anton 6169: @end example
6170:
1.29 crook 6171: @cindex child words
6172: This fragment defines a @dfn{defining word} @code{def-word} and then
6173: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6174: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6175: is not executed at this time. The word @code{name} is sometimes called a
6176: @dfn{child} of @code{def-word}.
6177:
6178: When you execute @code{name}, the address of the body of @code{name} is
6179: put on the data stack and @i{code2} is executed (the address of the body
6180: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6181: @code{CREATE}, i.e., the address a @code{create}d word returns by
6182: default).
6183:
6184: @c anton:
6185: @c www.dictionary.com says:
6186: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6187: @c several generations of absence, usually caused by the chance
6188: @c recombination of genes. 2.An individual or a part that exhibits
6189: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6190: @c of previous behavior after a period of absence.
6191: @c
6192: @c Doesn't seem to fit.
1.29 crook 6193:
1.69 anton 6194: @c @cindex atavism in child words
1.33 anton 6195: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6196: similarly; they all have a common run-time behaviour determined by
6197: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6198: body of the child word. The structure of the data is common to all
6199: children of @code{def-word}, but the data values are specific -- and
6200: private -- to each child word. When a child word is executed, the
6201: address of its private data area is passed as a parameter on TOS to be
6202: used and manipulated@footnote{It is legitimate both to read and write to
6203: this data area.} by @i{code2}.
1.29 crook 6204:
6205: The two fragments of code that make up the defining words act (are
6206: executed) at two completely separate times:
1.1 anton 6207:
1.29 crook 6208: @itemize @bullet
6209: @item
6210: At @i{define time}, the defining word executes @i{code1} to generate a
6211: child word
6212: @item
6213: At @i{child execution time}, when a child word is invoked, @i{code2}
6214: is executed, using parameters (data) that are private and specific to
6215: the child word.
6216: @end itemize
6217:
1.44 crook 6218: Another way of understanding the behaviour of @code{def-word} and
6219: @code{name} is to say that, if you make the following definitions:
1.33 anton 6220: @example
6221: : def-word1 ( "name" -- )
6222: CREATE @i{code1} ;
6223:
6224: : action1 ( ... -- ... )
6225: @i{code2} ;
6226:
6227: def-word1 name1
6228: @end example
6229:
1.44 crook 6230: @noindent
6231: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6232:
1.29 crook 6233: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6234:
1.1 anton 6235: @example
1.29 crook 6236: : CONSTANT ( w "name" -- )
6237: CREATE ,
1.26 crook 6238: DOES> ( -- w )
6239: @@ ;
1.1 anton 6240: @end example
6241:
1.29 crook 6242: @comment There is a beautiful description of how this works and what
6243: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6244: @comment commentary on the Counting Fruits problem.
6245:
6246: When you create a constant with @code{5 CONSTANT five}, a set of
6247: define-time actions take place; first a new word @code{five} is created,
6248: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6249: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6250: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6251: no code of its own; it simply contains a data field and a pointer to the
6252: code that follows @code{DOES>} in its defining word. That makes words
6253: created in this way very compact.
6254:
6255: The final example in this section is intended to remind you that space
6256: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6257: both read and written by a Standard program@footnote{Exercise: use this
6258: example as a starting point for your own implementation of @code{Value}
6259: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6260: @code{[']}.}:
6261:
6262: @example
6263: : foo ( "name" -- )
6264: CREATE -1 ,
6265: DOES> ( -- )
1.33 anton 6266: @@ . ;
1.29 crook 6267:
6268: foo first-word
6269: foo second-word
6270:
6271: 123 ' first-word >BODY !
6272: @end example
6273:
6274: If @code{first-word} had been a @code{CREATE}d word, we could simply
6275: have executed it to get the address of its data field. However, since it
6276: was defined to have @code{DOES>} actions, its execution semantics are to
6277: perform those @code{DOES>} actions. To get the address of its data field
6278: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6279: translate the xt into the address of the data field. When you execute
6280: @code{first-word}, it will display @code{123}. When you execute
6281: @code{second-word} it will display @code{-1}.
1.26 crook 6282:
6283: @cindex stack effect of @code{DOES>}-parts
6284: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6285: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6286: the stack effect of the defined words, not the stack effect of the
6287: following code (the following code expects the address of the body on
6288: the top of stack, which is not reflected in the stack comment). This is
6289: the convention that I use and recommend (it clashes a bit with using
6290: locals declarations for stack effect specification, though).
1.1 anton 6291:
1.53 anton 6292: @menu
6293: * CREATE..DOES> applications::
6294: * CREATE..DOES> details::
1.63 anton 6295: * Advanced does> usage example::
1.91 anton 6296: * @code{Const-does>}::
1.53 anton 6297: @end menu
6298:
6299: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6300: @subsubsection Applications of @code{CREATE..DOES>}
6301: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6302:
1.26 crook 6303: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6304:
1.26 crook 6305: @cindex factoring similar colon definitions
6306: When you see a sequence of code occurring several times, and you can
6307: identify a meaning, you will factor it out as a colon definition. When
6308: you see similar colon definitions, you can factor them using
6309: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6310: that look very similar:
1.1 anton 6311: @example
1.26 crook 6312: : ori, ( reg-target reg-source n -- )
6313: 0 asm-reg-reg-imm ;
6314: : andi, ( reg-target reg-source n -- )
6315: 1 asm-reg-reg-imm ;
1.1 anton 6316: @end example
6317:
1.26 crook 6318: @noindent
6319: This could be factored with:
6320: @example
6321: : reg-reg-imm ( op-code -- )
6322: CREATE ,
6323: DOES> ( reg-target reg-source n -- )
6324: @@ asm-reg-reg-imm ;
6325:
6326: 0 reg-reg-imm ori,
6327: 1 reg-reg-imm andi,
6328: @end example
1.1 anton 6329:
1.26 crook 6330: @cindex currying
6331: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6332: supply a part of the parameters for a word (known as @dfn{currying} in
6333: the functional language community). E.g., @code{+} needs two
6334: parameters. Creating versions of @code{+} with one parameter fixed can
6335: be done like this:
1.82 anton 6336:
1.1 anton 6337: @example
1.82 anton 6338: : curry+ ( n1 "name" -- )
1.26 crook 6339: CREATE ,
6340: DOES> ( n2 -- n1+n2 )
6341: @@ + ;
6342:
6343: 3 curry+ 3+
6344: -2 curry+ 2-
1.1 anton 6345: @end example
6346:
1.91 anton 6347:
1.63 anton 6348: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6349: @subsubsection The gory details of @code{CREATE..DOES>}
6350: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6351:
1.26 crook 6352: doc-does>
1.1 anton 6353:
1.26 crook 6354: @cindex @code{DOES>} in a separate definition
6355: This means that you need not use @code{CREATE} and @code{DOES>} in the
6356: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6357: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6358: @example
6359: : does1
6360: DOES> ( ... -- ... )
1.44 crook 6361: ... ;
6362:
6363: : does2
6364: DOES> ( ... -- ... )
6365: ... ;
6366:
6367: : def-word ( ... -- ... )
6368: create ...
6369: IF
6370: does1
6371: ELSE
6372: does2
6373: ENDIF ;
6374: @end example
6375:
6376: In this example, the selection of whether to use @code{does1} or
1.69 anton 6377: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6378: @code{CREATE}d.
6379:
6380: @cindex @code{DOES>} in interpretation state
6381: In a standard program you can apply a @code{DOES>}-part only if the last
6382: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6383: will override the behaviour of the last word defined in any case. In a
6384: standard program, you can use @code{DOES>} only in a colon
6385: definition. In Gforth, you can also use it in interpretation state, in a
6386: kind of one-shot mode; for example:
6387: @example
6388: CREATE name ( ... -- ... )
6389: @i{initialization}
6390: DOES>
6391: @i{code} ;
6392: @end example
6393:
6394: @noindent
6395: is equivalent to the standard:
6396: @example
6397: :noname
6398: DOES>
6399: @i{code} ;
6400: CREATE name EXECUTE ( ... -- ... )
6401: @i{initialization}
6402: @end example
6403:
1.53 anton 6404: doc->body
6405:
1.91 anton 6406: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6407: @subsubsection Advanced does> usage example
6408:
6409: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6410: for disassembling instructions, that follow a very repetetive scheme:
6411:
6412: @example
6413: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6414: @var{entry-num} cells @var{table} + !
6415: @end example
6416:
6417: Of course, this inspires the idea to factor out the commonalities to
6418: allow a definition like
6419:
6420: @example
6421: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6422: @end example
6423:
6424: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6425: correlated. Moreover, before I wrote the disassembler, there already
6426: existed code that defines instructions like this:
1.63 anton 6427:
6428: @example
6429: @var{entry-num} @var{inst-format} @var{inst-name}
6430: @end example
6431:
6432: This code comes from the assembler and resides in
6433: @file{arch/mips/insts.fs}.
6434:
6435: So I had to define the @var{inst-format} words that performed the scheme
6436: above when executed. At first I chose to use run-time code-generation:
6437:
6438: @example
6439: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6440: :noname Postpone @var{disasm-operands}
6441: name Postpone sliteral Postpone type Postpone ;
6442: swap cells @var{table} + ! ;
6443: @end example
6444:
6445: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6446:
1.63 anton 6447: An alternative would have been to write this using
6448: @code{create}/@code{does>}:
6449:
6450: @example
6451: : @var{inst-format} ( entry-num "name" -- )
6452: here name string, ( entry-num c-addr ) \ parse and save "name"
6453: noname create , ( entry-num )
1.116 anton 6454: latestxt swap cells @var{table} + !
1.63 anton 6455: does> ( addr w -- )
6456: \ disassemble instruction w at addr
6457: @@ >r
6458: @var{disasm-operands}
6459: r> count type ;
6460: @end example
6461:
6462: Somehow the first solution is simpler, mainly because it's simpler to
6463: shift a string from definition-time to use-time with @code{sliteral}
6464: than with @code{string,} and friends.
6465:
6466: I wrote a lot of words following this scheme and soon thought about
6467: factoring out the commonalities among them. Note that this uses a
6468: two-level defining word, i.e., a word that defines ordinary defining
6469: words.
6470:
6471: This time a solution involving @code{postpone} and friends seemed more
6472: difficult (try it as an exercise), so I decided to use a
6473: @code{create}/@code{does>} word; since I was already at it, I also used
6474: @code{create}/@code{does>} for the lower level (try using
6475: @code{postpone} etc. as an exercise), resulting in the following
6476: definition:
6477:
6478: @example
6479: : define-format ( disasm-xt table-xt -- )
6480: \ define an instruction format that uses disasm-xt for
6481: \ disassembling and enters the defined instructions into table
6482: \ table-xt
6483: create 2,
6484: does> ( u "inst" -- )
6485: \ defines an anonymous word for disassembling instruction inst,
6486: \ and enters it as u-th entry into table-xt
6487: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6488: noname create 2, \ define anonymous word
1.116 anton 6489: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6490: does> ( addr w -- )
6491: \ disassemble instruction w at addr
6492: 2@@ >r ( addr w disasm-xt R: c-addr )
6493: execute ( R: c-addr ) \ disassemble operands
6494: r> count type ; \ print name
6495: @end example
6496:
6497: Note that the tables here (in contrast to above) do the @code{cells +}
6498: by themselves (that's why you have to pass an xt). This word is used in
6499: the following way:
6500:
6501: @example
6502: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6503: @end example
6504:
1.71 anton 6505: As shown above, the defined instruction format is then used like this:
6506:
6507: @example
6508: @var{entry-num} @var{inst-format} @var{inst-name}
6509: @end example
6510:
1.63 anton 6511: In terms of currying, this kind of two-level defining word provides the
6512: parameters in three stages: first @var{disasm-operands} and @var{table},
6513: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6514: the instruction to be disassembled.
6515:
6516: Of course this did not quite fit all the instruction format names used
6517: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6518: the parameters into the right form.
6519:
6520: If you have trouble following this section, don't worry. First, this is
6521: involved and takes time (and probably some playing around) to
6522: understand; second, this is the first two-level
6523: @code{create}/@code{does>} word I have written in seventeen years of
6524: Forth; and if I did not have @file{insts.fs} to start with, I may well
6525: have elected to use just a one-level defining word (with some repeating
6526: of parameters when using the defining word). So it is not necessary to
6527: understand this, but it may improve your understanding of Forth.
1.44 crook 6528:
6529:
1.91 anton 6530: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6531: @subsubsection @code{Const-does>}
6532:
6533: A frequent use of @code{create}...@code{does>} is for transferring some
6534: values from definition-time to run-time. Gforth supports this use with
6535:
6536: doc-const-does>
6537:
6538: A typical use of this word is:
6539:
6540: @example
6541: : curry+ ( n1 "name" -- )
6542: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6543: + ;
6544:
6545: 3 curry+ 3+
6546: @end example
6547:
6548: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6549: definition to run-time.
6550:
6551: The advantages of using @code{const-does>} are:
6552:
6553: @itemize
6554:
6555: @item
6556: You don't have to deal with storing and retrieving the values, i.e.,
6557: your program becomes more writable and readable.
6558:
6559: @item
6560: When using @code{does>}, you have to introduce a @code{@@} that cannot
6561: be optimized away (because you could change the data using
6562: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6563:
6564: @end itemize
6565:
6566: An ANS Forth implementation of @code{const-does>} is available in
6567: @file{compat/const-does.fs}.
6568:
6569:
1.44 crook 6570: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6571: @subsection Deferred words
6572: @cindex deferred words
6573:
6574: The defining word @code{Defer} allows you to define a word by name
6575: without defining its behaviour; the definition of its behaviour is
6576: deferred. Here are two situation where this can be useful:
6577:
6578: @itemize @bullet
6579: @item
6580: Where you want to allow the behaviour of a word to be altered later, and
6581: for all precompiled references to the word to change when its behaviour
6582: is changed.
6583: @item
6584: For mutual recursion; @xref{Calls and returns}.
6585: @end itemize
6586:
6587: In the following example, @code{foo} always invokes the version of
6588: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6589: always invokes the version that prints ``@code{Hello}''. There is no way
6590: of getting @code{foo} to use the later version without re-ordering the
6591: source code and recompiling it.
6592:
6593: @example
6594: : greet ." Good morning" ;
6595: : foo ... greet ... ;
6596: : greet ." Hello" ;
6597: : bar ... greet ... ;
6598: @end example
6599:
6600: This problem can be solved by defining @code{greet} as a @code{Defer}red
6601: word. The behaviour of a @code{Defer}red word can be defined and
6602: redefined at any time by using @code{IS} to associate the xt of a
6603: previously-defined word with it. The previous example becomes:
6604:
6605: @example
1.69 anton 6606: Defer greet ( -- )
1.44 crook 6607: : foo ... greet ... ;
6608: : bar ... greet ... ;
1.69 anton 6609: : greet1 ( -- ) ." Good morning" ;
6610: : greet2 ( -- ) ." Hello" ;
1.44 crook 6611: ' greet2 <IS> greet \ make greet behave like greet2
6612: @end example
6613:
1.69 anton 6614: @progstyle
6615: You should write a stack comment for every deferred word, and put only
6616: XTs into deferred words that conform to this stack effect. Otherwise
6617: it's too difficult to use the deferred word.
6618:
1.44 crook 6619: A deferred word can be used to improve the statistics-gathering example
6620: from @ref{User-defined Defining Words}; rather than edit the
6621: application's source code to change every @code{:} to a @code{my:}, do
6622: this:
6623:
6624: @example
6625: : real: : ; \ retain access to the original
6626: defer : \ redefine as a deferred word
1.69 anton 6627: ' my: <IS> : \ use special version of :
1.44 crook 6628: \
6629: \ load application here
6630: \
1.69 anton 6631: ' real: <IS> : \ go back to the original
1.44 crook 6632: @end example
6633:
6634:
6635: One thing to note is that @code{<IS>} consumes its name when it is
6636: executed. If you want to specify the name at compile time, use
6637: @code{[IS]}:
6638:
6639: @example
6640: : set-greet ( xt -- )
6641: [IS] greet ;
6642:
6643: ' greet1 set-greet
6644: @end example
6645:
1.69 anton 6646: A deferred word can only inherit execution semantics from the xt
6647: (because that is all that an xt can represent -- for more discussion of
6648: this @pxref{Tokens for Words}); by default it will have default
6649: interpretation and compilation semantics deriving from this execution
6650: semantics. However, you can change the interpretation and compilation
6651: semantics of the deferred word in the usual ways:
1.44 crook 6652:
6653: @example
6654: : bar .... ; compile-only
6655: Defer fred immediate
6656: Defer jim
6657:
6658: ' bar <IS> jim \ jim has default semantics
6659: ' bar <IS> fred \ fred is immediate
6660: @end example
6661:
6662: doc-defer
6663: doc-<is>
6664: doc-[is]
6665: doc-is
6666: @comment TODO document these: what's defers [is]
6667: doc-what's
6668: doc-defers
6669:
6670: @c Use @code{words-deferred} to see a list of deferred words.
6671:
6672: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6673: are provided in @file{compat/defer.fs}.
6674:
6675:
1.69 anton 6676: @node Aliases, , Deferred words, Defining Words
1.44 crook 6677: @subsection Aliases
6678: @cindex aliases
1.1 anton 6679:
1.44 crook 6680: The defining word @code{Alias} allows you to define a word by name that
6681: has the same behaviour as some other word. Here are two situation where
6682: this can be useful:
1.1 anton 6683:
1.44 crook 6684: @itemize @bullet
6685: @item
6686: When you want access to a word's definition from a different word list
6687: (for an example of this, see the definition of the @code{Root} word list
6688: in the Gforth source).
6689: @item
6690: When you want to create a synonym; a definition that can be known by
6691: either of two names (for example, @code{THEN} and @code{ENDIF} are
6692: aliases).
6693: @end itemize
1.1 anton 6694:
1.69 anton 6695: Like deferred words, an alias has default compilation and interpretation
6696: semantics at the beginning (not the modifications of the other word),
6697: but you can change them in the usual ways (@code{immediate},
6698: @code{compile-only}). For example:
1.1 anton 6699:
6700: @example
1.44 crook 6701: : foo ... ; immediate
6702:
6703: ' foo Alias bar \ bar is not an immediate word
6704: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6705: @end example
6706:
1.44 crook 6707: Words that are aliases have the same xt, different headers in the
6708: dictionary, and consequently different name tokens (@pxref{Tokens for
6709: Words}) and possibly different immediate flags. An alias can only have
6710: default or immediate compilation semantics; you can define aliases for
6711: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6712:
1.44 crook 6713: doc-alias
1.1 anton 6714:
6715:
1.47 crook 6716: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6717: @section Interpretation and Compilation Semantics
1.26 crook 6718: @cindex semantics, interpretation and compilation
1.1 anton 6719:
1.71 anton 6720: @c !! state and ' are used without explanation
6721: @c example for immediate/compile-only? or is the tutorial enough
6722:
1.26 crook 6723: @cindex interpretation semantics
1.71 anton 6724: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6725: interpreter does when it encounters the word in interpret state. It also
6726: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6727: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6728: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6729: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6730:
1.26 crook 6731: @cindex compilation semantics
1.71 anton 6732: The @dfn{compilation semantics} of a (named) word are what the text
6733: interpreter does when it encounters the word in compile state. It also
6734: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6735: compiles@footnote{In standard terminology, ``appends to the current
6736: definition''.} the compilation semantics of @i{word}.
1.1 anton 6737:
1.26 crook 6738: @cindex execution semantics
6739: The standard also talks about @dfn{execution semantics}. They are used
6740: only for defining the interpretation and compilation semantics of many
6741: words. By default, the interpretation semantics of a word are to
6742: @code{execute} its execution semantics, and the compilation semantics of
6743: a word are to @code{compile,} its execution semantics.@footnote{In
6744: standard terminology: The default interpretation semantics are its
6745: execution semantics; the default compilation semantics are to append its
6746: execution semantics to the execution semantics of the current
6747: definition.}
6748:
1.71 anton 6749: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6750: the text interpreter, ticked, or @code{postpone}d, so they have no
6751: interpretation or compilation semantics. Their behaviour is represented
6752: by their XT (@pxref{Tokens for Words}), and we call it execution
6753: semantics, too.
6754:
1.26 crook 6755: @comment TODO expand, make it co-operate with new sections on text interpreter.
6756:
6757: @cindex immediate words
6758: @cindex compile-only words
6759: You can change the semantics of the most-recently defined word:
6760:
1.44 crook 6761:
1.26 crook 6762: doc-immediate
6763: doc-compile-only
6764: doc-restrict
6765:
1.82 anton 6766: By convention, words with non-default compilation semantics (e.g.,
6767: immediate words) often have names surrounded with brackets (e.g.,
6768: @code{[']}, @pxref{Execution token}).
1.44 crook 6769:
1.26 crook 6770: Note that ticking (@code{'}) a compile-only word gives an error
6771: (``Interpreting a compile-only word'').
1.1 anton 6772:
1.47 crook 6773: @menu
1.67 anton 6774: * Combined words::
1.47 crook 6775: @end menu
1.44 crook 6776:
1.71 anton 6777:
1.48 anton 6778: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6779: @subsection Combined Words
6780: @cindex combined words
6781:
6782: Gforth allows you to define @dfn{combined words} -- words that have an
6783: arbitrary combination of interpretation and compilation semantics.
6784:
1.26 crook 6785: doc-interpret/compile:
1.1 anton 6786:
1.26 crook 6787: This feature was introduced for implementing @code{TO} and @code{S"}. I
6788: recommend that you do not define such words, as cute as they may be:
6789: they make it hard to get at both parts of the word in some contexts.
6790: E.g., assume you want to get an execution token for the compilation
6791: part. Instead, define two words, one that embodies the interpretation
6792: part, and one that embodies the compilation part. Once you have done
6793: that, you can define a combined word with @code{interpret/compile:} for
6794: the convenience of your users.
1.1 anton 6795:
1.26 crook 6796: You might try to use this feature to provide an optimizing
6797: implementation of the default compilation semantics of a word. For
6798: example, by defining:
1.1 anton 6799: @example
1.26 crook 6800: :noname
6801: foo bar ;
6802: :noname
6803: POSTPONE foo POSTPONE bar ;
1.29 crook 6804: interpret/compile: opti-foobar
1.1 anton 6805: @end example
1.26 crook 6806:
1.23 crook 6807: @noindent
1.26 crook 6808: as an optimizing version of:
6809:
1.1 anton 6810: @example
1.26 crook 6811: : foobar
6812: foo bar ;
1.1 anton 6813: @end example
6814:
1.26 crook 6815: Unfortunately, this does not work correctly with @code{[compile]},
6816: because @code{[compile]} assumes that the compilation semantics of all
6817: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6818: opti-foobar} would compile compilation semantics, whereas
6819: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6820:
1.26 crook 6821: @cindex state-smart words (are a bad idea)
1.82 anton 6822: @anchor{state-smartness}
1.29 crook 6823: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6824: by @code{interpret/compile:} (words are state-smart if they check
6825: @code{STATE} during execution). E.g., they would try to code
6826: @code{foobar} like this:
1.1 anton 6827:
1.26 crook 6828: @example
6829: : foobar
6830: STATE @@
6831: IF ( compilation state )
6832: POSTPONE foo POSTPONE bar
6833: ELSE
6834: foo bar
6835: ENDIF ; immediate
6836: @end example
1.1 anton 6837:
1.26 crook 6838: Although this works if @code{foobar} is only processed by the text
6839: interpreter, it does not work in other contexts (like @code{'} or
6840: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6841: for a state-smart word, not for the interpretation semantics of the
6842: original @code{foobar}; when you execute this execution token (directly
6843: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6844: state, the result will not be what you expected (i.e., it will not
6845: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6846: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6847: M. Anton Ertl,
6848: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6849: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6850:
1.26 crook 6851: @cindex defining words with arbitrary semantics combinations
6852: It is also possible to write defining words that define words with
6853: arbitrary combinations of interpretation and compilation semantics. In
6854: general, they look like this:
1.1 anton 6855:
1.26 crook 6856: @example
6857: : def-word
6858: create-interpret/compile
1.29 crook 6859: @i{code1}
1.26 crook 6860: interpretation>
1.29 crook 6861: @i{code2}
1.26 crook 6862: <interpretation
6863: compilation>
1.29 crook 6864: @i{code3}
1.26 crook 6865: <compilation ;
6866: @end example
1.1 anton 6867:
1.29 crook 6868: For a @i{word} defined with @code{def-word}, the interpretation
6869: semantics are to push the address of the body of @i{word} and perform
6870: @i{code2}, and the compilation semantics are to push the address of
6871: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6872: can also be defined like this (except that the defined constants don't
6873: behave correctly when @code{[compile]}d):
1.1 anton 6874:
1.26 crook 6875: @example
6876: : constant ( n "name" -- )
6877: create-interpret/compile
6878: ,
6879: interpretation> ( -- n )
6880: @@
6881: <interpretation
6882: compilation> ( compilation. -- ; run-time. -- n )
6883: @@ postpone literal
6884: <compilation ;
6885: @end example
1.1 anton 6886:
1.44 crook 6887:
1.26 crook 6888: doc-create-interpret/compile
6889: doc-interpretation>
6890: doc-<interpretation
6891: doc-compilation>
6892: doc-<compilation
1.1 anton 6893:
1.44 crook 6894:
1.29 crook 6895: Words defined with @code{interpret/compile:} and
1.26 crook 6896: @code{create-interpret/compile} have an extended header structure that
6897: differs from other words; however, unless you try to access them with
6898: plain address arithmetic, you should not notice this. Words for
6899: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6900: @code{'} @i{word} @code{>body} also gives you the body of a word created
6901: with @code{create-interpret/compile}.
1.1 anton 6902:
1.44 crook 6903:
1.47 crook 6904: @c -------------------------------------------------------------
1.81 anton 6905: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6906: @section Tokens for Words
6907: @cindex tokens for words
6908:
6909: This section describes the creation and use of tokens that represent
6910: words.
6911:
1.71 anton 6912: @menu
6913: * Execution token:: represents execution/interpretation semantics
6914: * Compilation token:: represents compilation semantics
6915: * Name token:: represents named words
6916: @end menu
1.47 crook 6917:
1.71 anton 6918: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6919: @subsection Execution token
1.47 crook 6920:
6921: @cindex xt
6922: @cindex execution token
1.71 anton 6923: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6924: You can use @code{execute} to invoke this behaviour.
1.47 crook 6925:
1.71 anton 6926: @cindex tick (')
6927: You can use @code{'} to get an execution token that represents the
6928: interpretation semantics of a named word:
1.47 crook 6929:
6930: @example
1.97 anton 6931: 5 ' . ( n xt )
6932: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6933: @end example
1.47 crook 6934:
1.71 anton 6935: doc-'
6936:
6937: @code{'} parses at run-time; there is also a word @code{[']} that parses
6938: when it is compiled, and compiles the resulting XT:
6939:
6940: @example
6941: : foo ['] . execute ;
6942: 5 foo
6943: : bar ' execute ; \ by contrast,
6944: 5 bar . \ ' parses "." when bar executes
6945: @end example
6946:
6947: doc-[']
6948:
6949: If you want the execution token of @i{word}, write @code{['] @i{word}}
6950: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6951: @code{'} and @code{[']} behave somewhat unusually by complaining about
6952: compile-only words (because these words have no interpretation
6953: semantics). You might get what you want by using @code{COMP' @i{word}
6954: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6955: token}).
6956:
1.116 anton 6957: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6958: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6959: for the only behaviour the word has (the execution semantics). For
1.116 anton 6960: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6961: would produce if the word was defined anonymously.
6962:
6963: @example
6964: :noname ." hello" ;
6965: execute
1.47 crook 6966: @end example
6967:
1.71 anton 6968: An XT occupies one cell and can be manipulated like any other cell.
6969:
1.47 crook 6970: @cindex code field address
6971: @cindex CFA
1.71 anton 6972: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6973: operations that produce or consume it). For old hands: In Gforth, the
6974: XT is implemented as a code field address (CFA).
6975:
6976: doc-execute
6977: doc-perform
6978:
6979: @node Compilation token, Name token, Execution token, Tokens for Words
6980: @subsection Compilation token
1.47 crook 6981:
6982: @cindex compilation token
1.71 anton 6983: @cindex CT (compilation token)
6984: Gforth represents the compilation semantics of a named word by a
1.47 crook 6985: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6986: @i{xt} is an execution token. The compilation semantics represented by
6987: the compilation token can be performed with @code{execute}, which
6988: consumes the whole compilation token, with an additional stack effect
6989: determined by the represented compilation semantics.
6990:
6991: At present, the @i{w} part of a compilation token is an execution token,
6992: and the @i{xt} part represents either @code{execute} or
6993: @code{compile,}@footnote{Depending upon the compilation semantics of the
6994: word. If the word has default compilation semantics, the @i{xt} will
6995: represent @code{compile,}. Otherwise (e.g., for immediate words), the
6996: @i{xt} will represent @code{execute}.}. However, don't rely on that
6997: knowledge, unless necessary; future versions of Gforth may introduce
6998: unusual compilation tokens (e.g., a compilation token that represents
6999: the compilation semantics of a literal).
7000:
1.71 anton 7001: You can perform the compilation semantics represented by the compilation
7002: token with @code{execute}. You can compile the compilation semantics
7003: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7004: equivalent to @code{postpone @i{word}}.
7005:
7006: doc-[comp']
7007: doc-comp'
7008: doc-postpone,
7009:
7010: @node Name token, , Compilation token, Tokens for Words
7011: @subsection Name token
1.47 crook 7012:
7013: @cindex name token
1.116 anton 7014: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7015: token is an abstract data type that occurs as argument or result of the
7016: words below.
7017:
7018: @c !! put this elswhere?
1.47 crook 7019: @cindex name field address
7020: @cindex NFA
1.116 anton 7021: The closest thing to the nt in older Forth systems is the name field
7022: address (NFA), but there are significant differences: in older Forth
7023: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7024: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7025: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7026: is a link field in the structure identified by the name token, but
7027: searching usually uses a hash table external to these structures; the
7028: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7029: implemented as the address of that count field.
1.47 crook 7030:
7031: doc-find-name
1.116 anton 7032: doc-latest
7033: doc->name
1.47 crook 7034: doc-name>int
7035: doc-name?int
7036: doc-name>comp
7037: doc-name>string
1.109 anton 7038: doc-id.
7039: doc-.name
7040: doc-.id
1.47 crook 7041:
1.81 anton 7042: @c ----------------------------------------------------------
7043: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7044: @section Compiling words
7045: @cindex compiling words
7046: @cindex macros
7047:
7048: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7049: between compilation and run-time. E.g., you can run arbitrary code
7050: between defining words (or for computing data used by defining words
7051: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7052: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7053: running arbitrary code while compiling a colon definition (exception:
7054: you must not allot dictionary space).
7055:
7056: @menu
7057: * Literals:: Compiling data values
7058: * Macros:: Compiling words
7059: @end menu
7060:
7061: @node Literals, Macros, Compiling words, Compiling words
7062: @subsection Literals
7063: @cindex Literals
7064:
7065: The simplest and most frequent example is to compute a literal during
7066: compilation. E.g., the following definition prints an array of strings,
7067: one string per line:
7068:
7069: @example
7070: : .strings ( addr u -- ) \ gforth
7071: 2* cells bounds U+DO
7072: cr i 2@@ type
7073: 2 cells +LOOP ;
7074: @end example
1.81 anton 7075:
1.82 anton 7076: With a simple-minded compiler like Gforth's, this computes @code{2
7077: cells} on every loop iteration. You can compute this value once and for
7078: all at compile time and compile it into the definition like this:
7079:
7080: @example
7081: : .strings ( addr u -- ) \ gforth
7082: 2* cells bounds U+DO
7083: cr i 2@@ type
7084: [ 2 cells ] literal +LOOP ;
7085: @end example
7086:
7087: @code{[} switches the text interpreter to interpret state (you will get
7088: an @code{ok} prompt if you type this example interactively and insert a
7089: newline between @code{[} and @code{]}), so it performs the
7090: interpretation semantics of @code{2 cells}; this computes a number.
7091: @code{]} switches the text interpreter back into compile state. It then
7092: performs @code{Literal}'s compilation semantics, which are to compile
7093: this number into the current word. You can decompile the word with
7094: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7095:
1.82 anton 7096: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7097: *} in this way.
1.81 anton 7098:
1.82 anton 7099: doc-[
7100: doc-]
1.81 anton 7101: doc-literal
7102: doc-]L
1.82 anton 7103:
7104: There are also words for compiling other data types than single cells as
7105: literals:
7106:
1.81 anton 7107: doc-2literal
7108: doc-fliteral
1.82 anton 7109: doc-sliteral
7110:
7111: @cindex colon-sys, passing data across @code{:}
7112: @cindex @code{:}, passing data across
7113: You might be tempted to pass data from outside a colon definition to the
7114: inside on the data stack. This does not work, because @code{:} puhes a
7115: colon-sys, making stuff below unaccessible. E.g., this does not work:
7116:
7117: @example
7118: 5 : foo literal ; \ error: "unstructured"
7119: @end example
7120:
7121: Instead, you have to pass the value in some other way, e.g., through a
7122: variable:
7123:
7124: @example
7125: variable temp
7126: 5 temp !
7127: : foo [ temp @@ ] literal ;
7128: @end example
7129:
7130:
7131: @node Macros, , Literals, Compiling words
7132: @subsection Macros
7133: @cindex Macros
7134: @cindex compiling compilation semantics
7135:
7136: @code{Literal} and friends compile data values into the current
7137: definition. You can also write words that compile other words into the
7138: current definition. E.g.,
7139:
7140: @example
7141: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7142: POSTPONE + ;
7143:
7144: : foo ( n1 n2 -- n )
7145: [ compile-+ ] ;
7146: 1 2 foo .
7147: @end example
7148:
7149: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7150: What happens in this example? @code{Postpone} compiles the compilation
7151: semantics of @code{+} into @code{compile-+}; later the text interpreter
7152: executes @code{compile-+} and thus the compilation semantics of +, which
7153: compile (the execution semantics of) @code{+} into
7154: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7155: should only be executed in compile state, so this example is not
7156: guaranteed to work on all standard systems, but on any decent system it
7157: will work.}
7158:
7159: doc-postpone
7160: doc-[compile]
7161:
7162: Compiling words like @code{compile-+} are usually immediate (or similar)
7163: so you do not have to switch to interpret state to execute them;
7164: mopifying the last example accordingly produces:
7165:
7166: @example
7167: : [compile-+] ( compilation: --; interpretation: -- )
7168: \ compiled code: ( n1 n2 -- n )
7169: POSTPONE + ; immediate
7170:
7171: : foo ( n1 n2 -- n )
7172: [compile-+] ;
7173: 1 2 foo .
7174: @end example
7175:
7176: Immediate compiling words are similar to macros in other languages (in
7177: particular, Lisp). The important differences to macros in, e.g., C are:
7178:
7179: @itemize @bullet
7180:
7181: @item
7182: You use the same language for defining and processing macros, not a
7183: separate preprocessing language and processor.
7184:
7185: @item
7186: Consequently, the full power of Forth is available in macro definitions.
7187: E.g., you can perform arbitrarily complex computations, or generate
7188: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7189: Tutorial}). This power is very useful when writing a parser generators
7190: or other code-generating software.
7191:
7192: @item
7193: Macros defined using @code{postpone} etc. deal with the language at a
7194: higher level than strings; name binding happens at macro definition
7195: time, so you can avoid the pitfalls of name collisions that can happen
7196: in C macros. Of course, Forth is a liberal language and also allows to
7197: shoot yourself in the foot with text-interpreted macros like
7198:
7199: @example
7200: : [compile-+] s" +" evaluate ; immediate
7201: @end example
7202:
7203: Apart from binding the name at macro use time, using @code{evaluate}
7204: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7205: @end itemize
7206:
7207: You may want the macro to compile a number into a word. The word to do
7208: it is @code{literal}, but you have to @code{postpone} it, so its
7209: compilation semantics take effect when the macro is executed, not when
7210: it is compiled:
7211:
7212: @example
7213: : [compile-5] ( -- ) \ compiled code: ( -- n )
7214: 5 POSTPONE literal ; immediate
7215:
7216: : foo [compile-5] ;
7217: foo .
7218: @end example
7219:
7220: You may want to pass parameters to a macro, that the macro should
7221: compile into the current definition. If the parameter is a number, then
7222: you can use @code{postpone literal} (similar for other values).
7223:
7224: If you want to pass a word that is to be compiled, the usual way is to
7225: pass an execution token and @code{compile,} it:
7226:
7227: @example
7228: : twice1 ( xt -- ) \ compiled code: ... -- ...
7229: dup compile, compile, ;
7230:
7231: : 2+ ( n1 -- n2 )
7232: [ ' 1+ twice1 ] ;
7233: @end example
7234:
7235: doc-compile,
7236:
7237: An alternative available in Gforth, that allows you to pass compile-only
7238: words as parameters is to use the compilation token (@pxref{Compilation
7239: token}). The same example in this technique:
7240:
7241: @example
7242: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7243: 2dup 2>r execute 2r> execute ;
7244:
7245: : 2+ ( n1 -- n2 )
7246: [ comp' 1+ twice ] ;
7247: @end example
7248:
7249: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7250: works even if the executed compilation semantics has an effect on the
7251: data stack.
7252:
7253: You can also define complete definitions with these words; this provides
7254: an alternative to using @code{does>} (@pxref{User-defined Defining
7255: Words}). E.g., instead of
7256:
7257: @example
7258: : curry+ ( n1 "name" -- )
7259: CREATE ,
7260: DOES> ( n2 -- n1+n2 )
7261: @@ + ;
7262: @end example
7263:
7264: you could define
7265:
7266: @example
7267: : curry+ ( n1 "name" -- )
7268: \ name execution: ( n2 -- n1+n2 )
7269: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7270:
1.82 anton 7271: -3 curry+ 3-
7272: see 3-
7273: @end example
1.81 anton 7274:
1.82 anton 7275: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7276: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7277:
1.82 anton 7278: This way of writing defining words is sometimes more, sometimes less
7279: convenient than using @code{does>} (@pxref{Advanced does> usage
7280: example}). One advantage of this method is that it can be optimized
7281: better, because the compiler knows that the value compiled with
7282: @code{literal} is fixed, whereas the data associated with a
7283: @code{create}d word can be changed.
1.47 crook 7284:
1.26 crook 7285: @c ----------------------------------------------------------
1.111 anton 7286: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7287: @section The Text Interpreter
7288: @cindex interpreter - outer
7289: @cindex text interpreter
7290: @cindex outer interpreter
1.1 anton 7291:
1.34 anton 7292: @c Should we really describe all these ugly details? IMO the text
7293: @c interpreter should be much cleaner, but that may not be possible within
7294: @c ANS Forth. - anton
1.44 crook 7295: @c nac-> I wanted to explain how it works to show how you can exploit
7296: @c it in your own programs. When I was writing a cross-compiler, figuring out
7297: @c some of these gory details was very helpful to me. None of the textbooks
7298: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7299: @c seems to positively avoid going into too much detail for some of
7300: @c the internals.
1.34 anton 7301:
1.71 anton 7302: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7303: @c it is; for the ugly details, I would prefer another place. I wonder
7304: @c whether we should have a chapter before "Words" that describes some
7305: @c basic concepts referred to in words, and a chapter after "Words" that
7306: @c describes implementation details.
7307:
1.29 crook 7308: The text interpreter@footnote{This is an expanded version of the
7309: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7310: that processes input from the current input device. It is also called
7311: the outer interpreter, in contrast to the inner interpreter
7312: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7313: implementations.
1.27 crook 7314:
1.29 crook 7315: @cindex interpret state
7316: @cindex compile state
7317: The text interpreter operates in one of two states: @dfn{interpret
7318: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7319: aptly-named variable @code{state}.
1.29 crook 7320:
7321: This section starts by describing how the text interpreter behaves when
7322: it is in interpret state, processing input from the user input device --
7323: the keyboard. This is the mode that a Forth system is in after it starts
7324: up.
7325:
7326: @cindex input buffer
7327: @cindex terminal input buffer
7328: The text interpreter works from an area of memory called the @dfn{input
7329: buffer}@footnote{When the text interpreter is processing input from the
7330: keyboard, this area of memory is called the @dfn{terminal input buffer}
7331: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7332: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7333: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7334: leading spaces (called @dfn{delimiters}) then parses a string (a
7335: sequence of non-space characters) until it reaches either a space
7336: character or the end of the buffer. Having parsed a string, it makes two
7337: attempts to process it:
1.27 crook 7338:
1.29 crook 7339: @cindex dictionary
1.27 crook 7340: @itemize @bullet
7341: @item
1.29 crook 7342: It looks for the string in a @dfn{dictionary} of definitions. If the
7343: string is found, the string names a @dfn{definition} (also known as a
7344: @dfn{word}) and the dictionary search returns information that allows
7345: the text interpreter to perform the word's @dfn{interpretation
7346: semantics}. In most cases, this simply means that the word will be
7347: executed.
1.27 crook 7348: @item
7349: If the string is not found in the dictionary, the text interpreter
1.29 crook 7350: attempts to treat it as a number, using the rules described in
7351: @ref{Number Conversion}. If the string represents a legal number in the
7352: current radix, the number is pushed onto a parameter stack (the data
7353: stack for integers, the floating-point stack for floating-point
7354: numbers).
7355: @end itemize
7356:
7357: If both attempts fail, or if the word is found in the dictionary but has
7358: no interpretation semantics@footnote{This happens if the word was
7359: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7360: remainder of the input buffer, issues an error message and waits for
7361: more input. If one of the attempts succeeds, the text interpreter
7362: repeats the parsing process until the whole of the input buffer has been
7363: processed, at which point it prints the status message ``@code{ ok}''
7364: and waits for more input.
7365:
1.71 anton 7366: @c anton: this should be in the input stream subsection (or below it)
7367:
1.29 crook 7368: @cindex parse area
7369: The text interpreter keeps track of its position in the input buffer by
7370: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7371: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7372: of the input buffer. The region from offset @code{>IN @@} to the end of
7373: the input buffer is called the @dfn{parse area}@footnote{In other words,
7374: the text interpreter processes the contents of the input buffer by
7375: parsing strings from the parse area until the parse area is empty.}.
7376: This example shows how @code{>IN} changes as the text interpreter parses
7377: the input buffer:
7378:
7379: @example
7380: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7381: CR ." ->" TYPE ." <-" ; IMMEDIATE
7382:
7383: 1 2 3 remaining + remaining .
7384:
7385: : foo 1 2 3 remaining SWAP remaining ;
7386: @end example
7387:
7388: @noindent
7389: The result is:
7390:
7391: @example
7392: ->+ remaining .<-
7393: ->.<-5 ok
7394:
7395: ->SWAP remaining ;-<
7396: ->;<- ok
7397: @end example
7398:
7399: @cindex parsing words
7400: The value of @code{>IN} can also be modified by a word in the input
7401: buffer that is executed by the text interpreter. This means that a word
7402: can ``trick'' the text interpreter into either skipping a section of the
7403: input buffer@footnote{This is how parsing words work.} or into parsing a
7404: section twice. For example:
1.27 crook 7405:
1.29 crook 7406: @example
1.71 anton 7407: : lat ." <<foo>>" ;
7408: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7409: @end example
7410:
7411: @noindent
7412: When @code{flat} is executed, this output is produced@footnote{Exercise
7413: for the reader: what would happen if the @code{3} were replaced with
7414: @code{4}?}:
7415:
7416: @example
1.71 anton 7417: <<bar>><<foo>>
1.29 crook 7418: @end example
7419:
1.71 anton 7420: This technique can be used to work around some of the interoperability
7421: problems of parsing words. Of course, it's better to avoid parsing
7422: words where possible.
7423:
1.29 crook 7424: @noindent
7425: Two important notes about the behaviour of the text interpreter:
1.27 crook 7426:
7427: @itemize @bullet
7428: @item
7429: It processes each input string to completion before parsing additional
1.29 crook 7430: characters from the input buffer.
7431: @item
7432: It treats the input buffer as a read-only region (and so must your code).
7433: @end itemize
7434:
7435: @noindent
7436: When the text interpreter is in compile state, its behaviour changes in
7437: these ways:
7438:
7439: @itemize @bullet
7440: @item
7441: If a parsed string is found in the dictionary, the text interpreter will
7442: perform the word's @dfn{compilation semantics}. In most cases, this
7443: simply means that the execution semantics of the word will be appended
7444: to the current definition.
1.27 crook 7445: @item
1.29 crook 7446: When a number is encountered, it is compiled into the current definition
7447: (as a literal) rather than being pushed onto a parameter stack.
7448: @item
7449: If an error occurs, @code{state} is modified to put the text interpreter
7450: back into interpret state.
7451: @item
7452: Each time a line is entered from the keyboard, Gforth prints
7453: ``@code{ compiled}'' rather than `` @code{ok}''.
7454: @end itemize
7455:
7456: @cindex text interpreter - input sources
7457: When the text interpreter is using an input device other than the
7458: keyboard, its behaviour changes in these ways:
7459:
7460: @itemize @bullet
7461: @item
7462: When the parse area is empty, the text interpreter attempts to refill
7463: the input buffer from the input source. When the input source is
1.71 anton 7464: exhausted, the input source is set back to the previous input source.
1.29 crook 7465: @item
7466: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7467: time the parse area is emptied.
7468: @item
7469: If an error occurs, the input source is set back to the user input
7470: device.
1.27 crook 7471: @end itemize
1.21 crook 7472:
1.49 anton 7473: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7474:
1.26 crook 7475: doc->in
1.27 crook 7476: doc-source
7477:
1.26 crook 7478: doc-tib
7479: doc-#tib
1.1 anton 7480:
1.44 crook 7481:
1.26 crook 7482: @menu
1.67 anton 7483: * Input Sources::
7484: * Number Conversion::
7485: * Interpret/Compile states::
7486: * Interpreter Directives::
1.26 crook 7487: @end menu
1.1 anton 7488:
1.29 crook 7489: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7490: @subsection Input Sources
7491: @cindex input sources
7492: @cindex text interpreter - input sources
7493:
1.44 crook 7494: By default, the text interpreter processes input from the user input
1.29 crook 7495: device (the keyboard) when Forth starts up. The text interpreter can
7496: process input from any of these sources:
7497:
7498: @itemize @bullet
7499: @item
7500: The user input device -- the keyboard.
7501: @item
7502: A file, using the words described in @ref{Forth source files}.
7503: @item
7504: A block, using the words described in @ref{Blocks}.
7505: @item
7506: A text string, using @code{evaluate}.
7507: @end itemize
7508:
7509: A program can identify the current input device from the values of
7510: @code{source-id} and @code{blk}.
7511:
1.44 crook 7512:
1.29 crook 7513: doc-source-id
7514: doc-blk
7515:
7516: doc-save-input
7517: doc-restore-input
7518:
7519: doc-evaluate
1.111 anton 7520: doc-query
1.1 anton 7521:
1.29 crook 7522:
1.44 crook 7523:
1.29 crook 7524: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7525: @subsection Number Conversion
7526: @cindex number conversion
7527: @cindex double-cell numbers, input format
7528: @cindex input format for double-cell numbers
7529: @cindex single-cell numbers, input format
7530: @cindex input format for single-cell numbers
7531: @cindex floating-point numbers, input format
7532: @cindex input format for floating-point numbers
1.1 anton 7533:
1.29 crook 7534: This section describes the rules that the text interpreter uses when it
7535: tries to convert a string into a number.
1.1 anton 7536:
1.26 crook 7537: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7538: number base@footnote{For example, 0-9 when the number base is decimal or
7539: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7540:
1.26 crook 7541: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7542:
1.29 crook 7543: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7544: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7545:
1.26 crook 7546: Let * represent any number of instances of the previous character
7547: (including none).
1.1 anton 7548:
1.26 crook 7549: Let any other character represent itself.
1.1 anton 7550:
1.29 crook 7551: @noindent
1.26 crook 7552: Now, the conversion rules are:
1.21 crook 7553:
1.26 crook 7554: @itemize @bullet
7555: @item
7556: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7557: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7558: @item
7559: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7560: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7561: arithmetic. Examples are -45 -5681 -0
7562: @item
7563: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7564: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7565: (all three of these represent the same number).
1.26 crook 7566: @item
7567: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7568: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7569: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7570: -34.65 (all three of these represent the same number).
1.26 crook 7571: @item
1.29 crook 7572: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7573: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7574: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7575: number) +12.E-4
1.26 crook 7576: @end itemize
1.1 anton 7577:
1.26 crook 7578: By default, the number base used for integer number conversion is given
1.35 anton 7579: by the contents of the variable @code{base}. Note that a lot of
7580: confusion can result from unexpected values of @code{base}. If you
7581: change @code{base} anywhere, make sure to save the old value and restore
7582: it afterwards. In general I recommend keeping @code{base} decimal, and
7583: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7584:
1.29 crook 7585: doc-dpl
1.26 crook 7586: doc-base
7587: doc-hex
7588: doc-decimal
1.1 anton 7589:
1.44 crook 7590:
1.26 crook 7591: @cindex '-prefix for character strings
7592: @cindex &-prefix for decimal numbers
7593: @cindex %-prefix for binary numbers
7594: @cindex $-prefix for hexadecimal numbers
1.35 anton 7595: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7596: prefix@footnote{Some Forth implementations provide a similar scheme by
7597: implementing @code{$} etc. as parsing words that process the subsequent
7598: number in the input stream and push it onto the stack. For example, see
7599: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7600: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7601: is required between the prefix and the number.} before the first digit
7602: of an (integer) number. Four prefixes are supported:
1.1 anton 7603:
1.26 crook 7604: @itemize @bullet
7605: @item
1.35 anton 7606: @code{&} -- decimal
1.26 crook 7607: @item
1.35 anton 7608: @code{%} -- binary
1.26 crook 7609: @item
1.35 anton 7610: @code{$} -- hexadecimal
1.26 crook 7611: @item
1.35 anton 7612: @code{'} -- base @code{max-char+1}
1.26 crook 7613: @end itemize
1.1 anton 7614:
1.26 crook 7615: Here are some examples, with the equivalent decimal number shown after
7616: in braces:
1.1 anton 7617:
1.26 crook 7618: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7619: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7620: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7621: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7622:
1.26 crook 7623: @cindex number conversion - traps for the unwary
1.29 crook 7624: @noindent
1.26 crook 7625: Number conversion has a number of traps for the unwary:
1.1 anton 7626:
1.26 crook 7627: @itemize @bullet
7628: @item
7629: You cannot determine the current number base using the code sequence
1.35 anton 7630: @code{base @@ .} -- the number base is always 10 in the current number
7631: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7632: @item
7633: If the number base is set to a value greater than 14 (for example,
7634: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7635: it to be intepreted as either a single-precision integer or a
7636: floating-point number (Gforth treats it as an integer). The ambiguity
7637: can be resolved by explicitly stating the sign of the mantissa and/or
7638: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7639: ambiguity arises; either representation will be treated as a
7640: floating-point number.
7641: @item
1.29 crook 7642: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7643: It is used to specify file types.
7644: @item
1.72 anton 7645: ANS Forth requires the @code{.} of a double-precision number to be the
7646: final character in the string. Gforth allows the @code{.} to be
7647: anywhere after the first digit.
1.26 crook 7648: @item
7649: The number conversion process does not check for overflow.
7650: @item
1.72 anton 7651: In an ANS Forth program @code{base} is required to be decimal when
7652: converting floating-point numbers. In Gforth, number conversion to
7653: floating-point numbers always uses base &10, irrespective of the value
7654: of @code{base}.
1.26 crook 7655: @end itemize
1.1 anton 7656:
1.49 anton 7657: You can read numbers into your programs with the words described in
7658: @ref{Input}.
1.1 anton 7659:
1.82 anton 7660: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7661: @subsection Interpret/Compile states
7662: @cindex Interpret/Compile states
1.1 anton 7663:
1.29 crook 7664: A standard program is not permitted to change @code{state}
7665: explicitly. However, it can change @code{state} implicitly, using the
7666: words @code{[} and @code{]}. When @code{[} is executed it switches
7667: @code{state} to interpret state, and therefore the text interpreter
7668: starts interpreting. When @code{]} is executed it switches @code{state}
7669: to compile state and therefore the text interpreter starts
1.44 crook 7670: compiling. The most common usage for these words is for switching into
7671: interpret state and back from within a colon definition; this technique
1.49 anton 7672: can be used to compile a literal (for an example, @pxref{Literals}) or
7673: for conditional compilation (for an example, @pxref{Interpreter
7674: Directives}).
1.44 crook 7675:
1.35 anton 7676:
7677: @c This is a bad example: It's non-standard, and it's not necessary.
7678: @c However, I can't think of a good example for switching into compile
7679: @c state when there is no current word (@code{state}-smart words are not a
7680: @c good reason). So maybe we should use an example for switching into
7681: @c interpret @code{state} in a colon def. - anton
1.44 crook 7682: @c nac-> I agree. I started out by putting in the example, then realised
7683: @c that it was non-ANS, so wrote more words around it. I hope this
7684: @c re-written version is acceptable to you. I do want to keep the example
7685: @c as it is helpful for showing what is and what is not portable, particularly
7686: @c where it outlaws a style in common use.
7687:
1.72 anton 7688: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7689: @c that, we can also show what's not. In any case, I have written a
7690: @c section Compiling Words which also deals with [ ].
1.35 anton 7691:
1.95 anton 7692: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7693:
1.95 anton 7694: @c @code{[} and @code{]} also give you the ability to switch into compile
7695: @c state and back, but we cannot think of any useful Standard application
7696: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7697:
7698: @c @example
7699: @c : AA ." this is A" ;
7700: @c : BB ." this is B" ;
7701: @c : CC ." this is C" ;
7702:
7703: @c create table ] aa bb cc [
7704:
7705: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7706: @c cells table + @@ execute ;
7707: @c @end example
7708:
7709: @c This example builds a jump table; @code{0 go} will display ``@code{this
7710: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7711: @c defining @code{table} like this:
7712:
7713: @c @example
7714: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7715: @c @end example
7716:
7717: @c The problem with this code is that the definition of @code{table} is not
7718: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7719: @c @i{may} work on systems where code space and data space co-incide, the
7720: @c Standard only allows data space to be assigned for a @code{CREATE}d
7721: @c word. In addition, the Standard only allows @code{@@} to access data
7722: @c space, whilst this example is using it to access code space. The only
7723: @c portable, Standard way to build this table is to build it in data space,
7724: @c like this:
7725:
7726: @c @example
7727: @c create table ' aa , ' bb , ' cc ,
7728: @c @end example
1.29 crook 7729:
1.95 anton 7730: @c doc-state
1.44 crook 7731:
1.29 crook 7732:
1.82 anton 7733: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7734: @subsection Interpreter Directives
7735: @cindex interpreter directives
1.72 anton 7736: @cindex conditional compilation
1.1 anton 7737:
1.29 crook 7738: These words are usually used in interpret state; typically to control
7739: which parts of a source file are processed by the text
1.26 crook 7740: interpreter. There are only a few ANS Forth Standard words, but Gforth
7741: supplements these with a rich set of immediate control structure words
7742: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7743: used in compile state (@pxref{Control Structures}). Typical usages:
7744:
7745: @example
1.72 anton 7746: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7747: .
7748: .
1.72 anton 7749: HAVE-ASSEMBLER [IF]
1.29 crook 7750: : ASSEMBLER-FEATURE
7751: ...
7752: ;
7753: [ENDIF]
7754: .
7755: .
7756: : SEE
7757: ... \ general-purpose SEE code
1.72 anton 7758: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7759: ... \ assembler-specific SEE code
7760: [ [ENDIF] ]
7761: ;
7762: @end example
1.1 anton 7763:
1.44 crook 7764:
1.26 crook 7765: doc-[IF]
7766: doc-[ELSE]
7767: doc-[THEN]
7768: doc-[ENDIF]
1.1 anton 7769:
1.26 crook 7770: doc-[IFDEF]
7771: doc-[IFUNDEF]
1.1 anton 7772:
1.26 crook 7773: doc-[?DO]
7774: doc-[DO]
7775: doc-[FOR]
7776: doc-[LOOP]
7777: doc-[+LOOP]
7778: doc-[NEXT]
1.1 anton 7779:
1.26 crook 7780: doc-[BEGIN]
7781: doc-[UNTIL]
7782: doc-[AGAIN]
7783: doc-[WHILE]
7784: doc-[REPEAT]
1.1 anton 7785:
1.27 crook 7786:
1.26 crook 7787: @c -------------------------------------------------------------
1.111 anton 7788: @node The Input Stream, Word Lists, The Text Interpreter, Words
7789: @section The Input Stream
7790: @cindex input stream
7791:
7792: @c !! integrate this better with the "Text Interpreter" section
7793: The text interpreter reads from the input stream, which can come from
7794: several sources (@pxref{Input Sources}). Some words, in particular
7795: defining words, but also words like @code{'}, read parameters from the
7796: input stream instead of from the stack.
7797:
7798: Such words are called parsing words, because they parse the input
7799: stream. Parsing words are hard to use in other words, because it is
7800: hard to pass program-generated parameters through the input stream.
7801: They also usually have an unintuitive combination of interpretation and
7802: compilation semantics when implemented naively, leading to various
7803: approaches that try to produce a more intuitive behaviour
7804: (@pxref{Combined words}).
7805:
7806: It should be obvious by now that parsing words are a bad idea. If you
7807: want to implement a parsing word for convenience, also provide a factor
7808: of the word that does not parse, but takes the parameters on the stack.
7809: To implement the parsing word on top if it, you can use the following
7810: words:
7811:
7812: @c anton: these belong in the input stream section
7813: doc-parse
7814: doc-parse-word
7815: doc-name
7816: doc-word
7817: doc-\"-parse
7818: doc-refill
7819:
7820: Conversely, if you have the bad luck (or lack of foresight) to have to
7821: deal with parsing words without having such factors, how do you pass a
7822: string that is not in the input stream to it?
7823:
7824: doc-execute-parsing
7825:
7826: If you want to run a parsing word on a file, the following word should
7827: help:
7828:
7829: doc-execute-parsing-file
7830:
7831: @c -------------------------------------------------------------
7832: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7833: @section Word Lists
7834: @cindex word lists
1.32 anton 7835: @cindex header space
1.1 anton 7836:
1.36 anton 7837: A wordlist is a list of named words; you can add new words and look up
7838: words by name (and you can remove words in a restricted way with
7839: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7840:
7841: @cindex search order stack
7842: The text interpreter searches the wordlists present in the search order
7843: (a stack of wordlists), from the top to the bottom. Within each
7844: wordlist, the search starts conceptually at the newest word; i.e., if
7845: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7846:
1.26 crook 7847: @cindex compilation word list
1.36 anton 7848: New words are added to the @dfn{compilation wordlist} (aka current
7849: wordlist).
1.1 anton 7850:
1.36 anton 7851: @cindex wid
7852: A word list is identified by a cell-sized word list identifier (@i{wid})
7853: in much the same way as a file is identified by a file handle. The
7854: numerical value of the wid has no (portable) meaning, and might change
7855: from session to session.
1.1 anton 7856:
1.29 crook 7857: The ANS Forth ``Search order'' word set is intended to provide a set of
7858: low-level tools that allow various different schemes to be
1.74 anton 7859: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7860: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7861: Forth.
1.1 anton 7862:
1.27 crook 7863: @comment TODO: locals section refers to here, saying that every word list (aka
7864: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7865: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7866:
1.45 crook 7867: @comment TODO: document markers, reveal, tables, mappedwordlist
7868:
7869: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7870: @comment word from the source files, rather than some alias.
1.44 crook 7871:
1.26 crook 7872: doc-forth-wordlist
7873: doc-definitions
7874: doc-get-current
7875: doc-set-current
7876: doc-get-order
1.45 crook 7877: doc---gforthman-set-order
1.26 crook 7878: doc-wordlist
1.30 anton 7879: doc-table
1.79 anton 7880: doc->order
1.36 anton 7881: doc-previous
1.26 crook 7882: doc-also
1.45 crook 7883: doc---gforthman-forth
1.26 crook 7884: doc-only
1.45 crook 7885: doc---gforthman-order
1.15 anton 7886:
1.26 crook 7887: doc-find
7888: doc-search-wordlist
1.15 anton 7889:
1.26 crook 7890: doc-words
7891: doc-vlist
1.44 crook 7892: @c doc-words-deferred
1.1 anton 7893:
1.74 anton 7894: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7895: doc-root
7896: doc-vocabulary
7897: doc-seal
7898: doc-vocs
7899: doc-current
7900: doc-context
1.1 anton 7901:
1.44 crook 7902:
1.26 crook 7903: @menu
1.75 anton 7904: * Vocabularies::
1.67 anton 7905: * Why use word lists?::
1.75 anton 7906: * Word list example::
1.26 crook 7907: @end menu
7908:
1.75 anton 7909: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7910: @subsection Vocabularies
7911: @cindex Vocabularies, detailed explanation
7912:
7913: Here is an example of creating and using a new wordlist using ANS
7914: Forth words:
7915:
7916: @example
7917: wordlist constant my-new-words-wordlist
7918: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7919:
7920: \ add it to the search order
7921: also my-new-words
7922:
7923: \ alternatively, add it to the search order and make it
7924: \ the compilation word list
7925: also my-new-words definitions
7926: \ type "order" to see the problem
7927: @end example
7928:
7929: The problem with this example is that @code{order} has no way to
7930: associate the name @code{my-new-words} with the wid of the word list (in
7931: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7932: that has no associated name). There is no Standard way of associating a
7933: name with a wid.
7934:
7935: In Gforth, this example can be re-coded using @code{vocabulary}, which
7936: associates a name with a wid:
7937:
7938: @example
7939: vocabulary my-new-words
7940:
7941: \ add it to the search order
7942: also my-new-words
7943:
7944: \ alternatively, add it to the search order and make it
7945: \ the compilation word list
7946: my-new-words definitions
7947: \ type "order" to see that the problem is solved
7948: @end example
7949:
7950:
7951: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7952: @subsection Why use word lists?
7953: @cindex word lists - why use them?
7954:
1.74 anton 7955: Here are some reasons why people use wordlists:
1.26 crook 7956:
7957: @itemize @bullet
1.74 anton 7958:
7959: @c anton: Gforth's hashing implementation makes the search speed
7960: @c independent from the number of words. But it is linear with the number
7961: @c of wordlists that have to be searched, so in effect using more wordlists
7962: @c actually slows down compilation.
7963:
7964: @c @item
7965: @c To improve compilation speed by reducing the number of header space
7966: @c entries that must be searched. This is achieved by creating a new
7967: @c word list that contains all of the definitions that are used in the
7968: @c definition of a Forth system but which would not usually be used by
7969: @c programs running on that system. That word list would be on the search
7970: @c list when the Forth system was compiled but would be removed from the
7971: @c search list for normal operation. This can be a useful technique for
7972: @c low-performance systems (for example, 8-bit processors in embedded
7973: @c systems) but is unlikely to be necessary in high-performance desktop
7974: @c systems.
7975:
1.26 crook 7976: @item
7977: To prevent a set of words from being used outside the context in which
7978: they are valid. Two classic examples of this are an integrated editor
7979: (all of the edit commands are defined in a separate word list; the
7980: search order is set to the editor word list when the editor is invoked;
7981: the old search order is restored when the editor is terminated) and an
7982: integrated assembler (the op-codes for the machine are defined in a
7983: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 7984:
7985: @item
7986: To organize the words of an application or library into a user-visible
7987: set (in @code{forth-wordlist} or some other common wordlist) and a set
7988: of helper words used just for the implementation (hidden in a separate
1.75 anton 7989: wordlist). This keeps @code{words}' output smaller, separates
7990: implementation and interface, and reduces the chance of name conflicts
7991: within the common wordlist.
1.74 anton 7992:
1.26 crook 7993: @item
7994: To prevent a name-space clash between multiple definitions with the same
7995: name. For example, when building a cross-compiler you might have a word
7996: @code{IF} that generates conditional code for your target system. By
7997: placing this definition in a different word list you can control whether
7998: the host system's @code{IF} or the target system's @code{IF} get used in
7999: any particular context by controlling the order of the word lists on the
8000: search order stack.
1.74 anton 8001:
1.26 crook 8002: @end itemize
1.1 anton 8003:
1.74 anton 8004: The downsides of using wordlists are:
8005:
8006: @itemize
8007:
8008: @item
8009: Debugging becomes more cumbersome.
8010:
8011: @item
8012: Name conflicts worked around with wordlists are still there, and you
8013: have to arrange the search order carefully to get the desired results;
8014: if you forget to do that, you get hard-to-find errors (as in any case
8015: where you read the code differently from the compiler; @code{see} can
1.75 anton 8016: help seeing which of several possible words the name resolves to in such
8017: cases). @code{See} displays just the name of the words, not what
8018: wordlist they belong to, so it might be misleading. Using unique names
8019: is a better approach to avoid name conflicts.
1.74 anton 8020:
8021: @item
8022: You have to explicitly undo any changes to the search order. In many
8023: cases it would be more convenient if this happened implicitly. Gforth
8024: currently does not provide such a feature, but it may do so in the
8025: future.
8026: @end itemize
8027:
8028:
1.75 anton 8029: @node Word list example, , Why use word lists?, Word Lists
8030: @subsection Word list example
8031: @cindex word lists - example
1.1 anton 8032:
1.74 anton 8033: The following example is from the
8034: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8035: garbage collector} and uses wordlists to separate public words from
8036: helper words:
8037:
8038: @example
8039: get-current ( wid )
8040: vocabulary garbage-collector also garbage-collector definitions
8041: ... \ define helper words
8042: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8043: ... \ define the public (i.e., API) words
8044: \ they can refer to the helper words
8045: previous \ restore original search order (helper words become invisible)
8046: @end example
8047:
1.26 crook 8048: @c -------------------------------------------------------------
8049: @node Environmental Queries, Files, Word Lists, Words
8050: @section Environmental Queries
8051: @cindex environmental queries
1.21 crook 8052:
1.26 crook 8053: ANS Forth introduced the idea of ``environmental queries'' as a way
8054: for a program running on a system to determine certain characteristics of the system.
8055: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8056:
1.32 anton 8057: The Standard requires that the header space used for environmental queries
8058: be distinct from the header space used for definitions.
1.21 crook 8059:
1.26 crook 8060: Typically, environmental queries are supported by creating a set of
1.29 crook 8061: definitions in a word list that is @i{only} used during environmental
1.26 crook 8062: queries; that is what Gforth does. There is no Standard way of adding
8063: definitions to the set of recognised environmental queries, but any
8064: implementation that supports the loading of optional word sets must have
8065: some mechanism for doing this (after loading the word set, the
8066: associated environmental query string must return @code{true}). In
8067: Gforth, the word list used to honour environmental queries can be
8068: manipulated just like any other word list.
1.21 crook 8069:
1.44 crook 8070:
1.26 crook 8071: doc-environment?
8072: doc-environment-wordlist
1.21 crook 8073:
1.26 crook 8074: doc-gforth
8075: doc-os-class
1.21 crook 8076:
1.44 crook 8077:
1.26 crook 8078: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8079: returning two items on the stack, querying it using @code{environment?}
8080: will return an additional item; the @code{true} flag that shows that the
8081: string was recognised.
1.21 crook 8082:
1.26 crook 8083: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8084:
1.26 crook 8085: Here are some examples of using environmental queries:
1.21 crook 8086:
1.26 crook 8087: @example
8088: s" address-unit-bits" environment? 0=
8089: [IF]
8090: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8091: [ELSE]
8092: drop \ ensure balanced stack effect
1.26 crook 8093: [THEN]
1.21 crook 8094:
1.75 anton 8095: \ this might occur in the prelude of a standard program that uses THROW
8096: s" exception" environment? [IF]
8097: 0= [IF]
8098: : throw abort" exception thrown" ;
8099: [THEN]
8100: [ELSE] \ we don't know, so make sure
8101: : throw abort" exception thrown" ;
8102: [THEN]
1.21 crook 8103:
1.26 crook 8104: s" gforth" environment? [IF] .( Gforth version ) TYPE
8105: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8106:
8107: \ a program using v*
8108: s" gforth" environment? [IF]
8109: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8110: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8111: >r swap 2swap swap 0e r> 0 ?DO
8112: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8113: LOOP
8114: 2drop 2drop ;
8115: [THEN]
8116: [ELSE] \
8117: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8118: ...
8119: [THEN]
1.26 crook 8120: @end example
1.21 crook 8121:
1.26 crook 8122: Here is an example of adding a definition to the environment word list:
1.21 crook 8123:
1.26 crook 8124: @example
8125: get-current environment-wordlist set-current
8126: true constant block
8127: true constant block-ext
8128: set-current
8129: @end example
1.21 crook 8130:
1.26 crook 8131: You can see what definitions are in the environment word list like this:
1.21 crook 8132:
1.26 crook 8133: @example
1.79 anton 8134: environment-wordlist >order words previous
1.26 crook 8135: @end example
1.21 crook 8136:
8137:
1.26 crook 8138: @c -------------------------------------------------------------
8139: @node Files, Blocks, Environmental Queries, Words
8140: @section Files
1.28 crook 8141: @cindex files
8142: @cindex I/O - file-handling
1.21 crook 8143:
1.26 crook 8144: Gforth provides facilities for accessing files that are stored in the
8145: host operating system's file-system. Files that are processed by Gforth
8146: can be divided into two categories:
1.21 crook 8147:
1.23 crook 8148: @itemize @bullet
8149: @item
1.29 crook 8150: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8151: @item
1.29 crook 8152: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8153: @end itemize
8154:
8155: @menu
1.48 anton 8156: * Forth source files::
8157: * General files::
8158: * Search Paths::
1.26 crook 8159: @end menu
8160:
8161: @c -------------------------------------------------------------
8162: @node Forth source files, General files, Files, Files
8163: @subsection Forth source files
8164: @cindex including files
8165: @cindex Forth source files
1.21 crook 8166:
1.26 crook 8167: The simplest way to interpret the contents of a file is to use one of
8168: these two formats:
1.21 crook 8169:
1.26 crook 8170: @example
8171: include mysource.fs
8172: s" mysource.fs" included
8173: @end example
1.21 crook 8174:
1.75 anton 8175: You usually want to include a file only if it is not included already
1.26 crook 8176: (by, say, another source file). In that case, you can use one of these
1.45 crook 8177: three formats:
1.21 crook 8178:
1.26 crook 8179: @example
8180: require mysource.fs
8181: needs mysource.fs
8182: s" mysource.fs" required
8183: @end example
1.21 crook 8184:
1.26 crook 8185: @cindex stack effect of included files
8186: @cindex including files, stack effect
1.45 crook 8187: It is good practice to write your source files such that interpreting them
8188: does not change the stack. Source files designed in this way can be used with
1.26 crook 8189: @code{required} and friends without complications. For example:
1.21 crook 8190:
1.26 crook 8191: @example
1.75 anton 8192: 1024 require foo.fs drop
1.26 crook 8193: @end example
1.21 crook 8194:
1.75 anton 8195: Here you want to pass the argument 1024 (e.g., a buffer size) to
8196: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8197: ), which allows its use with @code{require}. Of course with such
8198: parameters to required files, you have to ensure that the first
8199: @code{require} fits for all uses (i.e., @code{require} it early in the
8200: master load file).
1.44 crook 8201:
1.26 crook 8202: doc-include-file
8203: doc-included
1.28 crook 8204: doc-included?
1.26 crook 8205: doc-include
8206: doc-required
8207: doc-require
8208: doc-needs
1.75 anton 8209: @c doc-init-included-files @c internal
8210: doc-sourcefilename
8211: doc-sourceline#
1.44 crook 8212:
1.26 crook 8213: A definition in ANS Forth for @code{required} is provided in
8214: @file{compat/required.fs}.
1.21 crook 8215:
1.26 crook 8216: @c -------------------------------------------------------------
8217: @node General files, Search Paths, Forth source files, Files
8218: @subsection General files
8219: @cindex general files
8220: @cindex file-handling
1.21 crook 8221:
1.75 anton 8222: Files are opened/created by name and type. The following file access
8223: methods (FAMs) are recognised:
1.44 crook 8224:
1.75 anton 8225: @cindex fam (file access method)
1.26 crook 8226: doc-r/o
8227: doc-r/w
8228: doc-w/o
8229: doc-bin
1.1 anton 8230:
1.44 crook 8231:
1.26 crook 8232: When a file is opened/created, it returns a file identifier,
1.29 crook 8233: @i{wfileid} that is used for all other file commands. All file
8234: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8235: successful operation and an implementation-defined non-zero value in the
8236: case of an error.
1.21 crook 8237:
1.44 crook 8238:
1.26 crook 8239: doc-open-file
8240: doc-create-file
1.21 crook 8241:
1.26 crook 8242: doc-close-file
8243: doc-delete-file
8244: doc-rename-file
8245: doc-read-file
8246: doc-read-line
8247: doc-write-file
8248: doc-write-line
8249: doc-emit-file
8250: doc-flush-file
1.21 crook 8251:
1.26 crook 8252: doc-file-status
8253: doc-file-position
8254: doc-reposition-file
8255: doc-file-size
8256: doc-resize-file
1.21 crook 8257:
1.93 anton 8258: doc-slurp-file
8259: doc-slurp-fid
1.112 anton 8260: doc-stdin
8261: doc-stdout
8262: doc-stderr
1.44 crook 8263:
1.26 crook 8264: @c ---------------------------------------------------------
1.48 anton 8265: @node Search Paths, , General files, Files
1.26 crook 8266: @subsection Search Paths
8267: @cindex path for @code{included}
8268: @cindex file search path
8269: @cindex @code{include} search path
8270: @cindex search path for files
1.21 crook 8271:
1.26 crook 8272: If you specify an absolute filename (i.e., a filename starting with
8273: @file{/} or @file{~}, or with @file{:} in the second position (as in
8274: @samp{C:...})) for @code{included} and friends, that file is included
8275: just as you would expect.
1.21 crook 8276:
1.75 anton 8277: If the filename starts with @file{./}, this refers to the directory that
8278: the present file was @code{included} from. This allows files to include
8279: other files relative to their own position (irrespective of the current
8280: working directory or the absolute position). This feature is essential
8281: for libraries consisting of several files, where a file may include
8282: other files from the library. It corresponds to @code{#include "..."}
8283: in C. If the current input source is not a file, @file{.} refers to the
8284: directory of the innermost file being included, or, if there is no file
8285: being included, to the current working directory.
8286:
8287: For relative filenames (not starting with @file{./}), Gforth uses a
8288: search path similar to Forth's search order (@pxref{Word Lists}). It
8289: tries to find the given filename in the directories present in the path,
8290: and includes the first one it finds. There are separate search paths for
8291: Forth source files and general files. If the search path contains the
8292: directory @file{.}, this refers to the directory of the current file, or
8293: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8294:
1.26 crook 8295: Use @file{~+} to refer to the current working directory (as in the
8296: @code{bash}).
1.1 anton 8297:
1.75 anton 8298: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8299:
1.48 anton 8300: @menu
1.75 anton 8301: * Source Search Paths::
1.48 anton 8302: * General Search Paths::
8303: @end menu
8304:
1.26 crook 8305: @c ---------------------------------------------------------
1.75 anton 8306: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8307: @subsubsection Source Search Paths
8308: @cindex search path control, source files
1.5 anton 8309:
1.26 crook 8310: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8311: Gforth}). You can display it and change it using @code{fpath} in
8312: combination with the general path handling words.
1.5 anton 8313:
1.75 anton 8314: doc-fpath
8315: @c the functionality of the following words is easily available through
8316: @c fpath and the general path words. The may go away.
8317: @c doc-.fpath
8318: @c doc-fpath+
8319: @c doc-fpath=
8320: @c doc-open-fpath-file
1.44 crook 8321:
8322: @noindent
1.26 crook 8323: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8324:
1.26 crook 8325: @example
1.75 anton 8326: fpath path= /usr/lib/forth/|./
1.26 crook 8327: require timer.fs
8328: @end example
1.5 anton 8329:
1.75 anton 8330:
1.26 crook 8331: @c ---------------------------------------------------------
1.75 anton 8332: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8333: @subsubsection General Search Paths
1.75 anton 8334: @cindex search path control, source files
1.5 anton 8335:
1.26 crook 8336: Your application may need to search files in several directories, like
8337: @code{included} does. To facilitate this, Gforth allows you to define
8338: and use your own search paths, by providing generic equivalents of the
8339: Forth search path words:
1.5 anton 8340:
1.75 anton 8341: doc-open-path-file
8342: doc-path-allot
8343: doc-clear-path
8344: doc-also-path
1.26 crook 8345: doc-.path
8346: doc-path+
8347: doc-path=
1.5 anton 8348:
1.75 anton 8349: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8350:
1.75 anton 8351: Here's an example of creating an empty search path:
8352: @c
1.26 crook 8353: @example
1.75 anton 8354: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8355: @end example
1.5 anton 8356:
1.26 crook 8357: @c -------------------------------------------------------------
8358: @node Blocks, Other I/O, Files, Words
8359: @section Blocks
1.28 crook 8360: @cindex I/O - blocks
8361: @cindex blocks
8362:
8363: When you run Gforth on a modern desk-top computer, it runs under the
8364: control of an operating system which provides certain services. One of
8365: these services is @var{file services}, which allows Forth source code
8366: and data to be stored in files and read into Gforth (@pxref{Files}).
8367:
8368: Traditionally, Forth has been an important programming language on
8369: systems where it has interfaced directly to the underlying hardware with
8370: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8371: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8372:
8373: A block is a 1024-byte data area, which can be used to hold data or
8374: Forth source code. No structure is imposed on the contents of the
8375: block. A block is identified by its number; blocks are numbered
8376: contiguously from 1 to an implementation-defined maximum.
8377:
8378: A typical system that used blocks but no operating system might use a
8379: single floppy-disk drive for mass storage, with the disks formatted to
8380: provide 256-byte sectors. Blocks would be implemented by assigning the
8381: first four sectors of the disk to block 1, the second four sectors to
8382: block 2 and so on, up to the limit of the capacity of the disk. The disk
8383: would not contain any file system information, just the set of blocks.
8384:
1.29 crook 8385: @cindex blocks file
1.28 crook 8386: On systems that do provide file services, blocks are typically
1.29 crook 8387: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8388: file}. The size of the blocks file will be an exact multiple of 1024
8389: bytes, corresponding to the number of blocks it contains. This is the
8390: mechanism that Gforth uses.
8391:
1.29 crook 8392: @cindex @file{blocks.fb}
1.75 anton 8393: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8394: having specified a blocks file, Gforth defaults to the blocks file
8395: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8396: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8397:
1.29 crook 8398: @cindex block buffers
1.28 crook 8399: When you read and write blocks under program control, Gforth uses a
1.29 crook 8400: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8401: not used when you use @code{load} to interpret the contents of a block.
8402:
1.75 anton 8403: The behaviour of the block buffers is analagous to that of a cache.
8404: Each block buffer has three states:
1.28 crook 8405:
8406: @itemize @bullet
8407: @item
8408: Unassigned
8409: @item
8410: Assigned-clean
8411: @item
8412: Assigned-dirty
8413: @end itemize
8414:
1.29 crook 8415: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8416: block, the block (specified by its block number) must be assigned to a
8417: block buffer.
8418:
8419: The assignment of a block to a block buffer is performed by @code{block}
8420: or @code{buffer}. Use @code{block} when you wish to modify the existing
8421: contents of a block. Use @code{buffer} when you don't care about the
8422: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8423: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8424: with the particular block is already stored in a block buffer due to an
8425: earlier @code{block} command, @code{buffer} will return that block
8426: buffer and the existing contents of the block will be
8427: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8428: block buffer for the block.}.
1.28 crook 8429:
1.47 crook 8430: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8431: @code{buffer}, that block buffer becomes the @i{current block
8432: buffer}. Data may only be manipulated (read or written) within the
8433: current block buffer.
1.47 crook 8434:
8435: When the contents of the current block buffer has been modified it is
1.48 anton 8436: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8437: either abandon the changes (by doing nothing) or mark the block as
8438: changed (assigned-dirty), using @code{update}. Using @code{update} does
8439: not change the blocks file; it simply changes a block buffer's state to
8440: @i{assigned-dirty}. The block will be written implicitly when it's
8441: buffer is needed for another block, or explicitly by @code{flush} or
8442: @code{save-buffers}.
8443:
8444: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8445: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8446: @code{flush}.
1.28 crook 8447:
1.29 crook 8448: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8449: algorithm to assign a block buffer to a block. That means that any
8450: particular block can only be assigned to one specific block buffer,
1.29 crook 8451: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8452: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8453: the new block immediately. If it is @i{assigned-dirty} its current
8454: contents are written back to the blocks file on disk before it is
1.28 crook 8455: allocated to the new block.
8456:
8457: Although no structure is imposed on the contents of a block, it is
8458: traditional to display the contents as 16 lines each of 64 characters. A
8459: block provides a single, continuous stream of input (for example, it
8460: acts as a single parse area) -- there are no end-of-line characters
8461: within a block, and no end-of-file character at the end of a
8462: block. There are two consequences of this:
1.26 crook 8463:
1.28 crook 8464: @itemize @bullet
8465: @item
8466: The last character of one line wraps straight into the first character
8467: of the following line
8468: @item
8469: The word @code{\} -- comment to end of line -- requires special
8470: treatment; in the context of a block it causes all characters until the
8471: end of the current 64-character ``line'' to be ignored.
8472: @end itemize
8473:
8474: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8475: the current blocks file will be extended to the appropriate size and the
1.28 crook 8476: block buffer will be initialised with spaces.
8477:
1.47 crook 8478: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8479: for details) but doesn't encourage the use of blocks; the mechanism is
8480: only provided for backward compatibility -- ANS Forth requires blocks to
8481: be available when files are.
1.28 crook 8482:
8483: Common techniques that are used when working with blocks include:
8484:
8485: @itemize @bullet
8486: @item
8487: A screen editor that allows you to edit blocks without leaving the Forth
8488: environment.
8489: @item
8490: Shadow screens; where every code block has an associated block
8491: containing comments (for example: code in odd block numbers, comments in
8492: even block numbers). Typically, the block editor provides a convenient
8493: mechanism to toggle between code and comments.
8494: @item
8495: Load blocks; a single block (typically block 1) contains a number of
8496: @code{thru} commands which @code{load} the whole of the application.
8497: @end itemize
1.26 crook 8498:
1.29 crook 8499: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8500: integrated into a Forth programming environment.
1.26 crook 8501:
8502: @comment TODO what about errors on open-blocks?
1.44 crook 8503:
1.26 crook 8504: doc-open-blocks
8505: doc-use
1.75 anton 8506: doc-block-offset
1.26 crook 8507: doc-get-block-fid
8508: doc-block-position
1.28 crook 8509:
1.75 anton 8510: doc-list
1.28 crook 8511: doc-scr
8512:
1.45 crook 8513: doc---gforthman-block
1.28 crook 8514: doc-buffer
8515:
1.75 anton 8516: doc-empty-buffers
8517: doc-empty-buffer
1.26 crook 8518: doc-update
1.28 crook 8519: doc-updated?
1.26 crook 8520: doc-save-buffers
1.75 anton 8521: doc-save-buffer
1.26 crook 8522: doc-flush
1.28 crook 8523:
1.26 crook 8524: doc-load
8525: doc-thru
8526: doc-+load
8527: doc-+thru
1.45 crook 8528: doc---gforthman--->
1.26 crook 8529: doc-block-included
8530:
1.44 crook 8531:
1.26 crook 8532: @c -------------------------------------------------------------
1.126 pazsan 8533: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8534: @section Other I/O
1.28 crook 8535: @cindex I/O - keyboard and display
1.26 crook 8536:
8537: @menu
8538: * Simple numeric output:: Predefined formats
8539: * Formatted numeric output:: Formatted (pictured) output
8540: * String Formats:: How Forth stores strings in memory
1.67 anton 8541: * Displaying characters and strings:: Other stuff
1.26 crook 8542: * Input:: Input
1.112 anton 8543: * Pipes:: How to create your own pipes
1.26 crook 8544: @end menu
8545:
8546: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8547: @subsection Simple numeric output
1.28 crook 8548: @cindex numeric output - simple/free-format
1.5 anton 8549:
1.26 crook 8550: The simplest output functions are those that display numbers from the
8551: data or floating-point stacks. Floating-point output is always displayed
8552: using base 10. Numbers displayed from the data stack use the value stored
8553: in @code{base}.
1.5 anton 8554:
1.44 crook 8555:
1.26 crook 8556: doc-.
8557: doc-dec.
8558: doc-hex.
8559: doc-u.
8560: doc-.r
8561: doc-u.r
8562: doc-d.
8563: doc-ud.
8564: doc-d.r
8565: doc-ud.r
8566: doc-f.
8567: doc-fe.
8568: doc-fs.
1.111 anton 8569: doc-f.rdp
1.44 crook 8570:
1.26 crook 8571: Examples of printing the number 1234.5678E23 in the different floating-point output
8572: formats are shown below:
1.5 anton 8573:
8574: @example
1.26 crook 8575: f. 123456779999999000000000000.
8576: fe. 123.456779999999E24
8577: fs. 1.23456779999999E26
1.5 anton 8578: @end example
8579:
8580:
1.26 crook 8581: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8582: @subsection Formatted numeric output
1.28 crook 8583: @cindex formatted numeric output
1.26 crook 8584: @cindex pictured numeric output
1.28 crook 8585: @cindex numeric output - formatted
1.26 crook 8586:
1.29 crook 8587: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8588: output} for formatted printing of integers. In this technique, digits
8589: are extracted from the number (using the current output radix defined by
8590: @code{base}), converted to ASCII codes and appended to a string that is
8591: built in a scratch-pad area of memory (@pxref{core-idef,
8592: Implementation-defined options, Implementation-defined
8593: options}). Arbitrary characters can be appended to the string during the
8594: extraction process. The completed string is specified by an address
8595: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8596: under program control.
1.5 anton 8597:
1.75 anton 8598: All of the integer output words described in the previous section
8599: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8600: numeric output.
1.5 anton 8601:
1.47 crook 8602: Three important things to remember about pictured numeric output:
1.5 anton 8603:
1.26 crook 8604: @itemize @bullet
8605: @item
1.28 crook 8606: It always operates on double-precision numbers; to display a
1.49 anton 8607: single-precision number, convert it first (for ways of doing this
8608: @pxref{Double precision}).
1.26 crook 8609: @item
1.28 crook 8610: It always treats the double-precision number as though it were
8611: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8612: @item
8613: The string is built up from right to left; least significant digit first.
8614: @end itemize
1.5 anton 8615:
1.44 crook 8616:
1.26 crook 8617: doc-<#
1.47 crook 8618: doc-<<#
1.26 crook 8619: doc-#
8620: doc-#s
8621: doc-hold
8622: doc-sign
8623: doc-#>
1.47 crook 8624: doc-#>>
1.5 anton 8625:
1.26 crook 8626: doc-represent
1.111 anton 8627: doc-f>str-rdp
8628: doc-f>buf-rdp
1.5 anton 8629:
1.44 crook 8630:
8631: @noindent
1.26 crook 8632: Here are some examples of using pictured numeric output:
1.5 anton 8633:
8634: @example
1.26 crook 8635: : my-u. ( u -- )
8636: \ Simplest use of pns.. behaves like Standard u.
8637: 0 \ convert to unsigned double
1.75 anton 8638: <<# \ start conversion
1.26 crook 8639: #s \ convert all digits
8640: #> \ complete conversion
1.75 anton 8641: TYPE SPACE \ display, with trailing space
8642: #>> ; \ release hold area
1.5 anton 8643:
1.26 crook 8644: : cents-only ( u -- )
8645: 0 \ convert to unsigned double
1.75 anton 8646: <<# \ start conversion
1.26 crook 8647: # # \ convert two least-significant digits
8648: #> \ complete conversion, discard other digits
1.75 anton 8649: TYPE SPACE \ display, with trailing space
8650: #>> ; \ release hold area
1.5 anton 8651:
1.26 crook 8652: : dollars-and-cents ( u -- )
8653: 0 \ convert to unsigned double
1.75 anton 8654: <<# \ start conversion
1.26 crook 8655: # # \ convert two least-significant digits
8656: [char] . hold \ insert decimal point
8657: #s \ convert remaining digits
8658: [char] $ hold \ append currency symbol
8659: #> \ complete conversion
1.75 anton 8660: TYPE SPACE \ display, with trailing space
8661: #>> ; \ release hold area
1.5 anton 8662:
1.26 crook 8663: : my-. ( n -- )
8664: \ handling negatives.. behaves like Standard .
8665: s>d \ convert to signed double
8666: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8667: <<# \ start conversion
1.26 crook 8668: #s \ convert all digits
8669: rot sign \ get at sign byte, append "-" if needed
8670: #> \ complete conversion
1.75 anton 8671: TYPE SPACE \ display, with trailing space
8672: #>> ; \ release hold area
1.5 anton 8673:
1.26 crook 8674: : account. ( n -- )
1.75 anton 8675: \ accountants don't like minus signs, they use parentheses
1.26 crook 8676: \ for negative numbers
8677: s>d \ convert to signed double
8678: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8679: <<# \ start conversion
1.26 crook 8680: 2 pick \ get copy of sign byte
8681: 0< IF [char] ) hold THEN \ right-most character of output
8682: #s \ convert all digits
8683: rot \ get at sign byte
8684: 0< IF [char] ( hold THEN
8685: #> \ complete conversion
1.75 anton 8686: TYPE SPACE \ display, with trailing space
8687: #>> ; \ release hold area
8688:
1.5 anton 8689: @end example
8690:
1.26 crook 8691: Here are some examples of using these words:
1.5 anton 8692:
8693: @example
1.26 crook 8694: 1 my-u. 1
8695: hex -1 my-u. decimal FFFFFFFF
8696: 1 cents-only 01
8697: 1234 cents-only 34
8698: 2 dollars-and-cents $0.02
8699: 1234 dollars-and-cents $12.34
8700: 123 my-. 123
8701: -123 my. -123
8702: 123 account. 123
8703: -456 account. (456)
1.5 anton 8704: @end example
8705:
8706:
1.26 crook 8707: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8708: @subsection String Formats
1.27 crook 8709: @cindex strings - see character strings
8710: @cindex character strings - formats
1.28 crook 8711: @cindex I/O - see character strings
1.75 anton 8712: @cindex counted strings
8713:
8714: @c anton: this does not really belong here; maybe the memory section,
8715: @c or the principles chapter
1.26 crook 8716:
1.27 crook 8717: Forth commonly uses two different methods for representing character
8718: strings:
1.26 crook 8719:
8720: @itemize @bullet
8721: @item
8722: @cindex address of counted string
1.45 crook 8723: @cindex counted string
1.29 crook 8724: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8725: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8726: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8727: memory.
8728: @item
1.29 crook 8729: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8730: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8731: first byte of the string.
8732: @end itemize
8733:
8734: ANS Forth encourages the use of the second format when representing
1.75 anton 8735: strings.
1.26 crook 8736:
1.44 crook 8737:
1.26 crook 8738: doc-count
8739:
1.44 crook 8740:
1.49 anton 8741: For words that move, copy and search for strings see @ref{Memory
8742: Blocks}. For words that display characters and strings see
8743: @ref{Displaying characters and strings}.
1.26 crook 8744:
8745: @node Displaying characters and strings, Input, String Formats, Other I/O
8746: @subsection Displaying characters and strings
1.27 crook 8747: @cindex characters - compiling and displaying
8748: @cindex character strings - compiling and displaying
1.26 crook 8749:
8750: This section starts with a glossary of Forth words and ends with a set
8751: of examples.
8752:
1.44 crook 8753:
1.26 crook 8754: doc-bl
8755: doc-space
8756: doc-spaces
8757: doc-emit
8758: doc-toupper
8759: doc-."
8760: doc-.(
1.98 anton 8761: doc-.\"
1.26 crook 8762: doc-type
1.44 crook 8763: doc-typewhite
1.26 crook 8764: doc-cr
1.27 crook 8765: @cindex cursor control
1.26 crook 8766: doc-at-xy
8767: doc-page
8768: doc-s"
1.98 anton 8769: doc-s\"
1.26 crook 8770: doc-c"
8771: doc-char
8772: doc-[char]
8773:
1.44 crook 8774:
8775: @noindent
1.26 crook 8776: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8777:
8778: @example
1.26 crook 8779: .( text-1)
8780: : my-word
8781: ." text-2" cr
8782: .( text-3)
8783: ;
8784:
8785: ." text-4"
8786:
8787: : my-char
8788: [char] ALPHABET emit
8789: char emit
8790: ;
1.5 anton 8791: @end example
8792:
1.26 crook 8793: When you load this code into Gforth, the following output is generated:
1.5 anton 8794:
1.26 crook 8795: @example
1.30 anton 8796: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8797: @end example
1.5 anton 8798:
1.26 crook 8799: @itemize @bullet
8800: @item
8801: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8802: is an immediate word; it behaves in the same way whether it is used inside
8803: or outside a colon definition.
8804: @item
8805: Message @code{text-4} is displayed because of Gforth's added interpretation
8806: semantics for @code{."}.
8807: @item
1.29 crook 8808: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8809: performs the compilation semantics for @code{."} within the definition of
8810: @code{my-word}.
8811: @end itemize
1.5 anton 8812:
1.26 crook 8813: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8814:
1.26 crook 8815: @example
1.30 anton 8816: @kbd{my-word @key{RET}} text-2
1.26 crook 8817: ok
1.30 anton 8818: @kbd{my-char fred @key{RET}} Af ok
8819: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8820: @end example
1.5 anton 8821:
8822: @itemize @bullet
8823: @item
1.26 crook 8824: Message @code{text-2} is displayed because of the run-time behaviour of
8825: @code{."}.
8826: @item
8827: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8828: on the stack at run-time. @code{emit} always displays the character
8829: when @code{my-char} is executed.
8830: @item
8831: @code{char} parses a string at run-time and the second @code{emit} displays
8832: the first character of the string.
1.5 anton 8833: @item
1.26 crook 8834: If you type @code{see my-char} you can see that @code{[char]} discarded
8835: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8836: definition of @code{my-char}.
1.5 anton 8837: @end itemize
8838:
8839:
8840:
1.112 anton 8841: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8842: @subsection Input
8843: @cindex input
1.28 crook 8844: @cindex I/O - see input
8845: @cindex parsing a string
1.5 anton 8846:
1.49 anton 8847: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8848:
1.27 crook 8849: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8850: @comment then index them
1.27 crook 8851:
1.44 crook 8852:
1.27 crook 8853: doc-key
8854: doc-key?
1.45 crook 8855: doc-ekey
8856: doc-ekey?
8857: doc-ekey>char
1.26 crook 8858: doc->number
8859: doc->float
8860: doc-accept
1.109 anton 8861: doc-edit-line
1.27 crook 8862: doc-pad
8863: @comment obsolescent words..
8864: doc-convert
1.26 crook 8865: doc-expect
1.27 crook 8866: doc-span
1.5 anton 8867:
8868:
1.112 anton 8869: @node Pipes, , Input, Other I/O
8870: @subsection Pipes
8871: @cindex pipes, creating your own
8872:
8873: In addition to using Gforth in pipes created by other processes
8874: (@pxref{Gforth in pipes}), you can create your own pipe with
8875: @code{open-pipe}, and read from or write to it.
8876:
8877: doc-open-pipe
8878: doc-close-pipe
8879:
8880: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8881: you don't catch this exception, Gforth will catch it and exit, usually
8882: silently (@pxref{Gforth in pipes}). Since you probably do not want
8883: this, you should wrap a @code{catch} or @code{try} block around the code
8884: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8885: problem yourself, and then return to regular processing.
8886:
8887: doc-broken-pipe-error
8888:
8889:
1.121 anton 8890: @node OS command line arguments, Locals, Other I/O, Words
8891: @section OS command line arguments
8892: @cindex OS command line arguments
8893: @cindex command line arguments, OS
8894: @cindex arguments, OS command line
8895:
8896: The usual way to pass arguments to Gforth programs on the command line
8897: is via the @option{-e} option, e.g.
8898:
8899: @example
8900: gforth -e "123 456" foo.fs -e bye
8901: @end example
8902:
8903: However, you may want to interpret the command-line arguments directly.
8904: In that case, you can access the (image-specific) command-line arguments
1.123 anton 8905: through @code{next-arg}:
1.121 anton 8906:
1.123 anton 8907: doc-next-arg
1.121 anton 8908:
1.123 anton 8909: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 8910:
8911: @example
8912: : echo ( -- )
1.122 anton 8913: begin
1.123 anton 8914: next-arg 2dup 0 0 d<> while
8915: type space
8916: repeat
8917: 2drop ;
1.121 anton 8918:
8919: echo cr bye
8920: @end example
8921:
8922: This can be invoked with
8923:
8924: @example
8925: gforth echo.fs hello world
8926: @end example
1.123 anton 8927:
8928: and it will print
8929:
8930: @example
8931: hello world
8932: @end example
8933:
8934: The next lower level of dealing with the OS command line are the
8935: following words:
8936:
8937: doc-arg
8938: doc-shift-args
8939:
8940: Finally, at the lowest level Gforth provides the following words:
8941:
8942: doc-argc
8943: doc-argv
1.121 anton 8944:
1.78 anton 8945: @c -------------------------------------------------------------
1.126 pazsan 8946: @node Locals, Structures, OS command line arguments, Words
1.78 anton 8947: @section Locals
8948: @cindex locals
8949:
8950: Local variables can make Forth programming more enjoyable and Forth
8951: programs easier to read. Unfortunately, the locals of ANS Forth are
8952: laden with restrictions. Therefore, we provide not only the ANS Forth
8953: locals wordset, but also our own, more powerful locals wordset (we
8954: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 8955:
1.78 anton 8956: The ideas in this section have also been published in M. Anton Ertl,
8957: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8958: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 8959:
8960: @menu
1.78 anton 8961: * Gforth locals::
8962: * ANS Forth locals::
1.5 anton 8963: @end menu
8964:
1.78 anton 8965: @node Gforth locals, ANS Forth locals, Locals, Locals
8966: @subsection Gforth locals
8967: @cindex Gforth locals
8968: @cindex locals, Gforth style
1.5 anton 8969:
1.78 anton 8970: Locals can be defined with
1.44 crook 8971:
1.78 anton 8972: @example
8973: @{ local1 local2 ... -- comment @}
8974: @end example
8975: or
8976: @example
8977: @{ local1 local2 ... @}
8978: @end example
1.5 anton 8979:
1.78 anton 8980: E.g.,
8981: @example
8982: : max @{ n1 n2 -- n3 @}
8983: n1 n2 > if
8984: n1
8985: else
8986: n2
8987: endif ;
8988: @end example
1.44 crook 8989:
1.78 anton 8990: The similarity of locals definitions with stack comments is intended. A
8991: locals definition often replaces the stack comment of a word. The order
8992: of the locals corresponds to the order in a stack comment and everything
8993: after the @code{--} is really a comment.
1.77 anton 8994:
1.78 anton 8995: This similarity has one disadvantage: It is too easy to confuse locals
8996: declarations with stack comments, causing bugs and making them hard to
8997: find. However, this problem can be avoided by appropriate coding
8998: conventions: Do not use both notations in the same program. If you do,
8999: they should be distinguished using additional means, e.g. by position.
1.77 anton 9000:
1.78 anton 9001: @cindex types of locals
9002: @cindex locals types
9003: The name of the local may be preceded by a type specifier, e.g.,
9004: @code{F:} for a floating point value:
1.5 anton 9005:
1.78 anton 9006: @example
9007: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9008: \ complex multiplication
9009: Ar Br f* Ai Bi f* f-
9010: Ar Bi f* Ai Br f* f+ ;
9011: @end example
1.44 crook 9012:
1.78 anton 9013: @cindex flavours of locals
9014: @cindex locals flavours
9015: @cindex value-flavoured locals
9016: @cindex variable-flavoured locals
9017: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9018: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9019: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9020: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9021: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9022: produces its address (which becomes invalid when the variable's scope is
9023: left). E.g., the standard word @code{emit} can be defined in terms of
9024: @code{type} like this:
1.5 anton 9025:
1.78 anton 9026: @example
9027: : emit @{ C^ char* -- @}
9028: char* 1 type ;
9029: @end example
1.5 anton 9030:
1.78 anton 9031: @cindex default type of locals
9032: @cindex locals, default type
9033: A local without type specifier is a @code{W:} local. Both flavours of
9034: locals are initialized with values from the data or FP stack.
1.44 crook 9035:
1.78 anton 9036: Currently there is no way to define locals with user-defined data
9037: structures, but we are working on it.
1.5 anton 9038:
1.78 anton 9039: Gforth allows defining locals everywhere in a colon definition. This
9040: poses the following questions:
1.5 anton 9041:
1.78 anton 9042: @menu
9043: * Where are locals visible by name?::
9044: * How long do locals live?::
9045: * Locals programming style::
9046: * Locals implementation::
9047: @end menu
1.44 crook 9048:
1.78 anton 9049: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9050: @subsubsection Where are locals visible by name?
9051: @cindex locals visibility
9052: @cindex visibility of locals
9053: @cindex scope of locals
1.5 anton 9054:
1.78 anton 9055: Basically, the answer is that locals are visible where you would expect
9056: it in block-structured languages, and sometimes a little longer. If you
9057: want to restrict the scope of a local, enclose its definition in
9058: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9059:
9060:
1.78 anton 9061: doc-scope
9062: doc-endscope
1.5 anton 9063:
9064:
1.78 anton 9065: These words behave like control structure words, so you can use them
9066: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9067: arbitrary ways.
1.77 anton 9068:
1.78 anton 9069: If you want a more exact answer to the visibility question, here's the
9070: basic principle: A local is visible in all places that can only be
9071: reached through the definition of the local@footnote{In compiler
9072: construction terminology, all places dominated by the definition of the
9073: local.}. In other words, it is not visible in places that can be reached
9074: without going through the definition of the local. E.g., locals defined
9075: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9076: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9077: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9078:
1.78 anton 9079: The reasoning behind this solution is: We want to have the locals
9080: visible as long as it is meaningful. The user can always make the
9081: visibility shorter by using explicit scoping. In a place that can
9082: only be reached through the definition of a local, the meaning of a
9083: local name is clear. In other places it is not: How is the local
9084: initialized at the control flow path that does not contain the
9085: definition? Which local is meant, if the same name is defined twice in
9086: two independent control flow paths?
1.77 anton 9087:
1.78 anton 9088: This should be enough detail for nearly all users, so you can skip the
9089: rest of this section. If you really must know all the gory details and
9090: options, read on.
1.77 anton 9091:
1.78 anton 9092: In order to implement this rule, the compiler has to know which places
9093: are unreachable. It knows this automatically after @code{AHEAD},
9094: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9095: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9096: compiler that the control flow never reaches that place. If
9097: @code{UNREACHABLE} is not used where it could, the only consequence is
9098: that the visibility of some locals is more limited than the rule above
9099: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9100: lie to the compiler), buggy code will be produced.
1.77 anton 9101:
1.5 anton 9102:
1.78 anton 9103: doc-unreachable
1.5 anton 9104:
1.23 crook 9105:
1.78 anton 9106: Another problem with this rule is that at @code{BEGIN}, the compiler
9107: does not know which locals will be visible on the incoming
9108: back-edge. All problems discussed in the following are due to this
9109: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9110: loops as examples; the discussion also applies to @code{?DO} and other
9111: loops). Perhaps the most insidious example is:
1.26 crook 9112: @example
1.78 anton 9113: AHEAD
9114: BEGIN
9115: x
9116: [ 1 CS-ROLL ] THEN
9117: @{ x @}
9118: ...
9119: UNTIL
1.26 crook 9120: @end example
1.23 crook 9121:
1.78 anton 9122: This should be legal according to the visibility rule. The use of
9123: @code{x} can only be reached through the definition; but that appears
9124: textually below the use.
9125:
9126: From this example it is clear that the visibility rules cannot be fully
9127: implemented without major headaches. Our implementation treats common
9128: cases as advertised and the exceptions are treated in a safe way: The
9129: compiler makes a reasonable guess about the locals visible after a
9130: @code{BEGIN}; if it is too pessimistic, the
9131: user will get a spurious error about the local not being defined; if the
9132: compiler is too optimistic, it will notice this later and issue a
9133: warning. In the case above the compiler would complain about @code{x}
9134: being undefined at its use. You can see from the obscure examples in
9135: this section that it takes quite unusual control structures to get the
9136: compiler into trouble, and even then it will often do fine.
1.23 crook 9137:
1.78 anton 9138: If the @code{BEGIN} is reachable from above, the most optimistic guess
9139: is that all locals visible before the @code{BEGIN} will also be
9140: visible after the @code{BEGIN}. This guess is valid for all loops that
9141: are entered only through the @code{BEGIN}, in particular, for normal
9142: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9143: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9144: compiler. When the branch to the @code{BEGIN} is finally generated by
9145: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9146: warns the user if it was too optimistic:
1.26 crook 9147: @example
1.78 anton 9148: IF
9149: @{ x @}
9150: BEGIN
9151: \ x ?
9152: [ 1 cs-roll ] THEN
9153: ...
9154: UNTIL
1.26 crook 9155: @end example
1.23 crook 9156:
1.78 anton 9157: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9158: optimistically assumes that it lives until the @code{THEN}. It notices
9159: this difference when it compiles the @code{UNTIL} and issues a
9160: warning. The user can avoid the warning, and make sure that @code{x}
9161: is not used in the wrong area by using explicit scoping:
9162: @example
9163: IF
9164: SCOPE
9165: @{ x @}
9166: ENDSCOPE
9167: BEGIN
9168: [ 1 cs-roll ] THEN
9169: ...
9170: UNTIL
9171: @end example
1.23 crook 9172:
1.78 anton 9173: Since the guess is optimistic, there will be no spurious error messages
9174: about undefined locals.
1.44 crook 9175:
1.78 anton 9176: If the @code{BEGIN} is not reachable from above (e.g., after
9177: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9178: optimistic guess, as the locals visible after the @code{BEGIN} may be
9179: defined later. Therefore, the compiler assumes that no locals are
9180: visible after the @code{BEGIN}. However, the user can use
9181: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9182: visible at the BEGIN as at the point where the top control-flow stack
9183: item was created.
1.23 crook 9184:
1.44 crook 9185:
1.78 anton 9186: doc-assume-live
1.26 crook 9187:
1.23 crook 9188:
1.78 anton 9189: @noindent
9190: E.g.,
9191: @example
9192: @{ x @}
9193: AHEAD
9194: ASSUME-LIVE
9195: BEGIN
9196: x
9197: [ 1 CS-ROLL ] THEN
9198: ...
9199: UNTIL
9200: @end example
1.44 crook 9201:
1.78 anton 9202: Other cases where the locals are defined before the @code{BEGIN} can be
9203: handled by inserting an appropriate @code{CS-ROLL} before the
9204: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9205: behind the @code{ASSUME-LIVE}).
1.23 crook 9206:
1.78 anton 9207: Cases where locals are defined after the @code{BEGIN} (but should be
9208: visible immediately after the @code{BEGIN}) can only be handled by
9209: rearranging the loop. E.g., the ``most insidious'' example above can be
9210: arranged into:
9211: @example
9212: BEGIN
9213: @{ x @}
9214: ... 0=
9215: WHILE
9216: x
9217: REPEAT
9218: @end example
1.44 crook 9219:
1.78 anton 9220: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9221: @subsubsection How long do locals live?
9222: @cindex locals lifetime
9223: @cindex lifetime of locals
1.23 crook 9224:
1.78 anton 9225: The right answer for the lifetime question would be: A local lives at
9226: least as long as it can be accessed. For a value-flavoured local this
9227: means: until the end of its visibility. However, a variable-flavoured
9228: local could be accessed through its address far beyond its visibility
9229: scope. Ultimately, this would mean that such locals would have to be
9230: garbage collected. Since this entails un-Forth-like implementation
9231: complexities, I adopted the same cowardly solution as some other
9232: languages (e.g., C): The local lives only as long as it is visible;
9233: afterwards its address is invalid (and programs that access it
9234: afterwards are erroneous).
1.23 crook 9235:
1.78 anton 9236: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9237: @subsubsection Locals programming style
9238: @cindex locals programming style
9239: @cindex programming style, locals
1.23 crook 9240:
1.78 anton 9241: The freedom to define locals anywhere has the potential to change
9242: programming styles dramatically. In particular, the need to use the
9243: return stack for intermediate storage vanishes. Moreover, all stack
9244: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9245: determined arguments) can be eliminated: If the stack items are in the
9246: wrong order, just write a locals definition for all of them; then
9247: write the items in the order you want.
1.23 crook 9248:
1.78 anton 9249: This seems a little far-fetched and eliminating stack manipulations is
9250: unlikely to become a conscious programming objective. Still, the number
9251: of stack manipulations will be reduced dramatically if local variables
9252: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9253: a traditional implementation of @code{max}).
1.23 crook 9254:
1.78 anton 9255: This shows one potential benefit of locals: making Forth programs more
9256: readable. Of course, this benefit will only be realized if the
9257: programmers continue to honour the principle of factoring instead of
9258: using the added latitude to make the words longer.
1.23 crook 9259:
1.78 anton 9260: @cindex single-assignment style for locals
9261: Using @code{TO} can and should be avoided. Without @code{TO},
9262: every value-flavoured local has only a single assignment and many
9263: advantages of functional languages apply to Forth. I.e., programs are
9264: easier to analyse, to optimize and to read: It is clear from the
9265: definition what the local stands for, it does not turn into something
9266: different later.
1.23 crook 9267:
1.78 anton 9268: E.g., a definition using @code{TO} might look like this:
9269: @example
9270: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9271: u1 u2 min 0
9272: ?do
9273: addr1 c@@ addr2 c@@ -
9274: ?dup-if
9275: unloop exit
9276: then
9277: addr1 char+ TO addr1
9278: addr2 char+ TO addr2
9279: loop
9280: u1 u2 - ;
1.26 crook 9281: @end example
1.78 anton 9282: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9283: every loop iteration. @code{strcmp} is a typical example of the
9284: readability problems of using @code{TO}. When you start reading
9285: @code{strcmp}, you think that @code{addr1} refers to the start of the
9286: string. Only near the end of the loop you realize that it is something
9287: else.
1.23 crook 9288:
1.78 anton 9289: This can be avoided by defining two locals at the start of the loop that
9290: are initialized with the right value for the current iteration.
9291: @example
9292: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9293: addr1 addr2
9294: u1 u2 min 0
9295: ?do @{ s1 s2 @}
9296: s1 c@@ s2 c@@ -
9297: ?dup-if
9298: unloop exit
9299: then
9300: s1 char+ s2 char+
9301: loop
9302: 2drop
9303: u1 u2 - ;
9304: @end example
9305: Here it is clear from the start that @code{s1} has a different value
9306: in every loop iteration.
1.23 crook 9307:
1.78 anton 9308: @node Locals implementation, , Locals programming style, Gforth locals
9309: @subsubsection Locals implementation
9310: @cindex locals implementation
9311: @cindex implementation of locals
1.23 crook 9312:
1.78 anton 9313: @cindex locals stack
9314: Gforth uses an extra locals stack. The most compelling reason for
9315: this is that the return stack is not float-aligned; using an extra stack
9316: also eliminates the problems and restrictions of using the return stack
9317: as locals stack. Like the other stacks, the locals stack grows toward
9318: lower addresses. A few primitives allow an efficient implementation:
9319:
9320:
9321: doc-@local#
9322: doc-f@local#
9323: doc-laddr#
9324: doc-lp+!#
9325: doc-lp!
9326: doc->l
9327: doc-f>l
9328:
9329:
9330: In addition to these primitives, some specializations of these
9331: primitives for commonly occurring inline arguments are provided for
9332: efficiency reasons, e.g., @code{@@local0} as specialization of
9333: @code{@@local#} for the inline argument 0. The following compiling words
9334: compile the right specialized version, or the general version, as
9335: appropriate:
1.23 crook 9336:
1.5 anton 9337:
1.107 dvdkhlng 9338: @c doc-compile-@local
9339: @c doc-compile-f@local
1.78 anton 9340: doc-compile-lp+!
1.5 anton 9341:
9342:
1.78 anton 9343: Combinations of conditional branches and @code{lp+!#} like
9344: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9345: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9346:
1.78 anton 9347: A special area in the dictionary space is reserved for keeping the
9348: local variable names. @code{@{} switches the dictionary pointer to this
9349: area and @code{@}} switches it back and generates the locals
9350: initializing code. @code{W:} etc.@ are normal defining words. This
9351: special area is cleared at the start of every colon definition.
1.5 anton 9352:
1.78 anton 9353: @cindex word list for defining locals
9354: A special feature of Gforth's dictionary is used to implement the
9355: definition of locals without type specifiers: every word list (aka
9356: vocabulary) has its own methods for searching
9357: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9358: with a special search method: When it is searched for a word, it
9359: actually creates that word using @code{W:}. @code{@{} changes the search
9360: order to first search the word list containing @code{@}}, @code{W:} etc.,
9361: and then the word list for defining locals without type specifiers.
1.5 anton 9362:
1.78 anton 9363: The lifetime rules support a stack discipline within a colon
9364: definition: The lifetime of a local is either nested with other locals
9365: lifetimes or it does not overlap them.
1.23 crook 9366:
1.78 anton 9367: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9368: pointer manipulation is generated. Between control structure words
9369: locals definitions can push locals onto the locals stack. @code{AGAIN}
9370: is the simplest of the other three control flow words. It has to
9371: restore the locals stack depth of the corresponding @code{BEGIN}
9372: before branching. The code looks like this:
9373: @format
9374: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9375: @code{branch} <begin>
9376: @end format
1.26 crook 9377:
1.78 anton 9378: @code{UNTIL} is a little more complicated: If it branches back, it
9379: must adjust the stack just like @code{AGAIN}. But if it falls through,
9380: the locals stack must not be changed. The compiler generates the
9381: following code:
9382: @format
9383: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9384: @end format
9385: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9386:
1.78 anton 9387: @code{THEN} can produce somewhat inefficient code:
9388: @format
9389: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9390: <orig target>:
9391: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9392: @end format
9393: The second @code{lp+!#} adjusts the locals stack pointer from the
9394: level at the @i{orig} point to the level after the @code{THEN}. The
9395: first @code{lp+!#} adjusts the locals stack pointer from the current
9396: level to the level at the orig point, so the complete effect is an
9397: adjustment from the current level to the right level after the
9398: @code{THEN}.
1.26 crook 9399:
1.78 anton 9400: @cindex locals information on the control-flow stack
9401: @cindex control-flow stack items, locals information
9402: In a conventional Forth implementation a dest control-flow stack entry
9403: is just the target address and an orig entry is just the address to be
9404: patched. Our locals implementation adds a word list to every orig or dest
9405: item. It is the list of locals visible (or assumed visible) at the point
9406: described by the entry. Our implementation also adds a tag to identify
9407: the kind of entry, in particular to differentiate between live and dead
9408: (reachable and unreachable) orig entries.
1.26 crook 9409:
1.78 anton 9410: A few unusual operations have to be performed on locals word lists:
1.44 crook 9411:
1.5 anton 9412:
1.78 anton 9413: doc-common-list
9414: doc-sub-list?
9415: doc-list-size
1.52 anton 9416:
9417:
1.78 anton 9418: Several features of our locals word list implementation make these
9419: operations easy to implement: The locals word lists are organised as
9420: linked lists; the tails of these lists are shared, if the lists
9421: contain some of the same locals; and the address of a name is greater
9422: than the address of the names behind it in the list.
1.5 anton 9423:
1.78 anton 9424: Another important implementation detail is the variable
9425: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9426: determine if they can be reached directly or only through the branch
9427: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9428: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9429: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9430:
1.78 anton 9431: Counted loops are similar to other loops in most respects, but
9432: @code{LEAVE} requires special attention: It performs basically the same
9433: service as @code{AHEAD}, but it does not create a control-flow stack
9434: entry. Therefore the information has to be stored elsewhere;
9435: traditionally, the information was stored in the target fields of the
9436: branches created by the @code{LEAVE}s, by organizing these fields into a
9437: linked list. Unfortunately, this clever trick does not provide enough
9438: space for storing our extended control flow information. Therefore, we
9439: introduce another stack, the leave stack. It contains the control-flow
9440: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9441:
1.78 anton 9442: Local names are kept until the end of the colon definition, even if
9443: they are no longer visible in any control-flow path. In a few cases
9444: this may lead to increased space needs for the locals name area, but
9445: usually less than reclaiming this space would cost in code size.
1.5 anton 9446:
1.44 crook 9447:
1.78 anton 9448: @node ANS Forth locals, , Gforth locals, Locals
9449: @subsection ANS Forth locals
9450: @cindex locals, ANS Forth style
1.5 anton 9451:
1.78 anton 9452: The ANS Forth locals wordset does not define a syntax for locals, but
9453: words that make it possible to define various syntaxes. One of the
9454: possible syntaxes is a subset of the syntax we used in the Gforth locals
9455: wordset, i.e.:
1.29 crook 9456:
9457: @example
1.78 anton 9458: @{ local1 local2 ... -- comment @}
9459: @end example
9460: @noindent
9461: or
9462: @example
9463: @{ local1 local2 ... @}
1.29 crook 9464: @end example
9465:
1.78 anton 9466: The order of the locals corresponds to the order in a stack comment. The
9467: restrictions are:
1.5 anton 9468:
1.78 anton 9469: @itemize @bullet
9470: @item
9471: Locals can only be cell-sized values (no type specifiers are allowed).
9472: @item
9473: Locals can be defined only outside control structures.
9474: @item
9475: Locals can interfere with explicit usage of the return stack. For the
9476: exact (and long) rules, see the standard. If you don't use return stack
9477: accessing words in a definition using locals, you will be all right. The
9478: purpose of this rule is to make locals implementation on the return
9479: stack easier.
9480: @item
9481: The whole definition must be in one line.
9482: @end itemize
1.5 anton 9483:
1.78 anton 9484: Locals defined in ANS Forth behave like @code{VALUE}s
9485: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9486: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9487:
1.78 anton 9488: Since the syntax above is supported by Gforth directly, you need not do
9489: anything to use it. If you want to port a program using this syntax to
9490: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9491: syntax on the other system.
1.5 anton 9492:
1.78 anton 9493: Note that a syntax shown in the standard, section A.13 looks
9494: similar, but is quite different in having the order of locals
9495: reversed. Beware!
1.5 anton 9496:
1.78 anton 9497: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9498:
1.78 anton 9499: doc-(local)
1.5 anton 9500:
1.78 anton 9501: The ANS Forth locals extension wordset defines a syntax using
9502: @code{locals|}, but it is so awful that we strongly recommend not to use
9503: it. We have implemented this syntax to make porting to Gforth easy, but
9504: do not document it here. The problem with this syntax is that the locals
9505: are defined in an order reversed with respect to the standard stack
9506: comment notation, making programs harder to read, and easier to misread
9507: and miswrite. The only merit of this syntax is that it is easy to
9508: implement using the ANS Forth locals wordset.
1.53 anton 9509:
9510:
1.78 anton 9511: @c ----------------------------------------------------------
9512: @node Structures, Object-oriented Forth, Locals, Words
9513: @section Structures
9514: @cindex structures
9515: @cindex records
1.53 anton 9516:
1.78 anton 9517: This section presents the structure package that comes with Gforth. A
9518: version of the package implemented in ANS Forth is available in
9519: @file{compat/struct.fs}. This package was inspired by a posting on
9520: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9521: possibly John Hayes). A version of this section has been published in
9522: M. Anton Ertl,
9523: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9524: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9525: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9526:
1.78 anton 9527: @menu
9528: * Why explicit structure support?::
9529: * Structure Usage::
9530: * Structure Naming Convention::
9531: * Structure Implementation::
9532: * Structure Glossary::
9533: @end menu
1.55 anton 9534:
1.78 anton 9535: @node Why explicit structure support?, Structure Usage, Structures, Structures
9536: @subsection Why explicit structure support?
1.53 anton 9537:
1.78 anton 9538: @cindex address arithmetic for structures
9539: @cindex structures using address arithmetic
9540: If we want to use a structure containing several fields, we could simply
9541: reserve memory for it, and access the fields using address arithmetic
9542: (@pxref{Address arithmetic}). As an example, consider a structure with
9543: the following fields
1.57 anton 9544:
1.78 anton 9545: @table @code
9546: @item a
9547: is a float
9548: @item b
9549: is a cell
9550: @item c
9551: is a float
9552: @end table
1.57 anton 9553:
1.78 anton 9554: Given the (float-aligned) base address of the structure we get the
9555: address of the field
1.52 anton 9556:
1.78 anton 9557: @table @code
9558: @item a
9559: without doing anything further.
9560: @item b
9561: with @code{float+}
9562: @item c
9563: with @code{float+ cell+ faligned}
9564: @end table
1.52 anton 9565:
1.78 anton 9566: It is easy to see that this can become quite tiring.
1.52 anton 9567:
1.78 anton 9568: Moreover, it is not very readable, because seeing a
9569: @code{cell+} tells us neither which kind of structure is
9570: accessed nor what field is accessed; we have to somehow infer the kind
9571: of structure, and then look up in the documentation, which field of
9572: that structure corresponds to that offset.
1.53 anton 9573:
1.78 anton 9574: Finally, this kind of address arithmetic also causes maintenance
9575: troubles: If you add or delete a field somewhere in the middle of the
9576: structure, you have to find and change all computations for the fields
9577: afterwards.
1.52 anton 9578:
1.78 anton 9579: So, instead of using @code{cell+} and friends directly, how
9580: about storing the offsets in constants:
1.52 anton 9581:
1.78 anton 9582: @example
9583: 0 constant a-offset
9584: 0 float+ constant b-offset
9585: 0 float+ cell+ faligned c-offset
9586: @end example
1.64 pazsan 9587:
1.78 anton 9588: Now we can get the address of field @code{x} with @code{x-offset
9589: +}. This is much better in all respects. Of course, you still
9590: have to change all later offset definitions if you add a field. You can
9591: fix this by declaring the offsets in the following way:
1.57 anton 9592:
1.78 anton 9593: @example
9594: 0 constant a-offset
9595: a-offset float+ constant b-offset
9596: b-offset cell+ faligned constant c-offset
9597: @end example
1.57 anton 9598:
1.78 anton 9599: Since we always use the offsets with @code{+}, we could use a defining
9600: word @code{cfield} that includes the @code{+} in the action of the
9601: defined word:
1.64 pazsan 9602:
1.78 anton 9603: @example
9604: : cfield ( n "name" -- )
9605: create ,
9606: does> ( name execution: addr1 -- addr2 )
9607: @@ + ;
1.64 pazsan 9608:
1.78 anton 9609: 0 cfield a
9610: 0 a float+ cfield b
9611: 0 b cell+ faligned cfield c
9612: @end example
1.64 pazsan 9613:
1.78 anton 9614: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9615:
1.78 anton 9616: The structure field words now can be used quite nicely. However,
9617: their definition is still a bit cumbersome: We have to repeat the
9618: name, the information about size and alignment is distributed before
9619: and after the field definitions etc. The structure package presented
9620: here addresses these problems.
1.64 pazsan 9621:
1.78 anton 9622: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9623: @subsection Structure Usage
9624: @cindex structure usage
1.57 anton 9625:
1.78 anton 9626: @cindex @code{field} usage
9627: @cindex @code{struct} usage
9628: @cindex @code{end-struct} usage
9629: You can define a structure for a (data-less) linked list with:
1.57 anton 9630: @example
1.78 anton 9631: struct
9632: cell% field list-next
9633: end-struct list%
1.57 anton 9634: @end example
9635:
1.78 anton 9636: With the address of the list node on the stack, you can compute the
9637: address of the field that contains the address of the next node with
9638: @code{list-next}. E.g., you can determine the length of a list
9639: with:
1.57 anton 9640:
9641: @example
1.78 anton 9642: : list-length ( list -- n )
9643: \ "list" is a pointer to the first element of a linked list
9644: \ "n" is the length of the list
9645: 0 BEGIN ( list1 n1 )
9646: over
9647: WHILE ( list1 n1 )
9648: 1+ swap list-next @@ swap
9649: REPEAT
9650: nip ;
1.57 anton 9651: @end example
9652:
1.78 anton 9653: You can reserve memory for a list node in the dictionary with
9654: @code{list% %allot}, which leaves the address of the list node on the
9655: stack. For the equivalent allocation on the heap you can use @code{list%
9656: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9657: use @code{list% %allocate}). You can get the the size of a list
9658: node with @code{list% %size} and its alignment with @code{list%
9659: %alignment}.
9660:
9661: Note that in ANS Forth the body of a @code{create}d word is
9662: @code{aligned} but not necessarily @code{faligned};
9663: therefore, if you do a:
1.57 anton 9664:
9665: @example
1.78 anton 9666: create @emph{name} foo% %allot drop
1.57 anton 9667: @end example
9668:
1.78 anton 9669: @noindent
9670: then the memory alloted for @code{foo%} is guaranteed to start at the
9671: body of @code{@emph{name}} only if @code{foo%} contains only character,
9672: cell and double fields. Therefore, if your structure contains floats,
9673: better use
1.57 anton 9674:
9675: @example
1.78 anton 9676: foo% %allot constant @emph{name}
1.57 anton 9677: @end example
9678:
1.78 anton 9679: @cindex structures containing structures
9680: You can include a structure @code{foo%} as a field of
9681: another structure, like this:
1.65 anton 9682: @example
1.78 anton 9683: struct
9684: ...
9685: foo% field ...
9686: ...
9687: end-struct ...
1.65 anton 9688: @end example
1.52 anton 9689:
1.78 anton 9690: @cindex structure extension
9691: @cindex extended records
9692: Instead of starting with an empty structure, you can extend an
9693: existing structure. E.g., a plain linked list without data, as defined
9694: above, is hardly useful; You can extend it to a linked list of integers,
9695: like this:@footnote{This feature is also known as @emph{extended
9696: records}. It is the main innovation in the Oberon language; in other
9697: words, adding this feature to Modula-2 led Wirth to create a new
9698: language, write a new compiler etc. Adding this feature to Forth just
9699: required a few lines of code.}
1.52 anton 9700:
1.78 anton 9701: @example
9702: list%
9703: cell% field intlist-int
9704: end-struct intlist%
9705: @end example
1.55 anton 9706:
1.78 anton 9707: @code{intlist%} is a structure with two fields:
9708: @code{list-next} and @code{intlist-int}.
1.55 anton 9709:
1.78 anton 9710: @cindex structures containing arrays
9711: You can specify an array type containing @emph{n} elements of
9712: type @code{foo%} like this:
1.55 anton 9713:
9714: @example
1.78 anton 9715: foo% @emph{n} *
1.56 anton 9716: @end example
1.55 anton 9717:
1.78 anton 9718: You can use this array type in any place where you can use a normal
9719: type, e.g., when defining a @code{field}, or with
9720: @code{%allot}.
9721:
9722: @cindex first field optimization
9723: The first field is at the base address of a structure and the word for
9724: this field (e.g., @code{list-next}) actually does not change the address
9725: on the stack. You may be tempted to leave it away in the interest of
9726: run-time and space efficiency. This is not necessary, because the
9727: structure package optimizes this case: If you compile a first-field
9728: words, no code is generated. So, in the interest of readability and
9729: maintainability you should include the word for the field when accessing
9730: the field.
1.52 anton 9731:
9732:
1.78 anton 9733: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9734: @subsection Structure Naming Convention
9735: @cindex structure naming convention
1.52 anton 9736:
1.78 anton 9737: The field names that come to (my) mind are often quite generic, and,
9738: if used, would cause frequent name clashes. E.g., many structures
9739: probably contain a @code{counter} field. The structure names
9740: that come to (my) mind are often also the logical choice for the names
9741: of words that create such a structure.
1.52 anton 9742:
1.78 anton 9743: Therefore, I have adopted the following naming conventions:
1.52 anton 9744:
1.78 anton 9745: @itemize @bullet
9746: @cindex field naming convention
9747: @item
9748: The names of fields are of the form
9749: @code{@emph{struct}-@emph{field}}, where
9750: @code{@emph{struct}} is the basic name of the structure, and
9751: @code{@emph{field}} is the basic name of the field. You can
9752: think of field words as converting the (address of the)
9753: structure into the (address of the) field.
1.52 anton 9754:
1.78 anton 9755: @cindex structure naming convention
9756: @item
9757: The names of structures are of the form
9758: @code{@emph{struct}%}, where
9759: @code{@emph{struct}} is the basic name of the structure.
9760: @end itemize
1.52 anton 9761:
1.78 anton 9762: This naming convention does not work that well for fields of extended
9763: structures; e.g., the integer list structure has a field
9764: @code{intlist-int}, but has @code{list-next}, not
9765: @code{intlist-next}.
1.53 anton 9766:
1.78 anton 9767: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9768: @subsection Structure Implementation
9769: @cindex structure implementation
9770: @cindex implementation of structures
1.52 anton 9771:
1.78 anton 9772: The central idea in the implementation is to pass the data about the
9773: structure being built on the stack, not in some global
9774: variable. Everything else falls into place naturally once this design
9775: decision is made.
1.53 anton 9776:
1.78 anton 9777: The type description on the stack is of the form @emph{align
9778: size}. Keeping the size on the top-of-stack makes dealing with arrays
9779: very simple.
1.53 anton 9780:
1.78 anton 9781: @code{field} is a defining word that uses @code{Create}
9782: and @code{DOES>}. The body of the field contains the offset
9783: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9784:
9785: @example
1.78 anton 9786: @@ +
1.53 anton 9787: @end example
9788:
1.78 anton 9789: @noindent
9790: i.e., add the offset to the address, giving the stack effect
9791: @i{addr1 -- addr2} for a field.
9792:
9793: @cindex first field optimization, implementation
9794: This simple structure is slightly complicated by the optimization
9795: for fields with offset 0, which requires a different
9796: @code{DOES>}-part (because we cannot rely on there being
9797: something on the stack if such a field is invoked during
9798: compilation). Therefore, we put the different @code{DOES>}-parts
9799: in separate words, and decide which one to invoke based on the
9800: offset. For a zero offset, the field is basically a noop; it is
9801: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9802:
1.78 anton 9803: @node Structure Glossary, , Structure Implementation, Structures
9804: @subsection Structure Glossary
9805: @cindex structure glossary
1.53 anton 9806:
1.5 anton 9807:
1.78 anton 9808: doc-%align
9809: doc-%alignment
9810: doc-%alloc
9811: doc-%allocate
9812: doc-%allot
9813: doc-cell%
9814: doc-char%
9815: doc-dfloat%
9816: doc-double%
9817: doc-end-struct
9818: doc-field
9819: doc-float%
9820: doc-naligned
9821: doc-sfloat%
9822: doc-%size
9823: doc-struct
1.54 anton 9824:
9825:
1.26 crook 9826: @c -------------------------------------------------------------
1.78 anton 9827: @node Object-oriented Forth, Programming Tools, Structures, Words
9828: @section Object-oriented Forth
9829:
9830: Gforth comes with three packages for object-oriented programming:
9831: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9832: is preloaded, so you have to @code{include} them before use. The most
9833: important differences between these packages (and others) are discussed
9834: in @ref{Comparison with other object models}. All packages are written
9835: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9836:
1.78 anton 9837: @menu
9838: * Why object-oriented programming?::
9839: * Object-Oriented Terminology::
9840: * Objects::
9841: * OOF::
9842: * Mini-OOF::
9843: * Comparison with other object models::
9844: @end menu
1.5 anton 9845:
1.78 anton 9846: @c ----------------------------------------------------------------
9847: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9848: @subsection Why object-oriented programming?
9849: @cindex object-oriented programming motivation
9850: @cindex motivation for object-oriented programming
1.44 crook 9851:
1.78 anton 9852: Often we have to deal with several data structures (@emph{objects}),
9853: that have to be treated similarly in some respects, but differently in
9854: others. Graphical objects are the textbook example: circles, triangles,
9855: dinosaurs, icons, and others, and we may want to add more during program
9856: development. We want to apply some operations to any graphical object,
9857: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9858: has to do something different for every kind of object.
9859: @comment TODO add some other operations eg perimeter, area
9860: @comment and tie in to concrete examples later..
1.5 anton 9861:
1.78 anton 9862: We could implement @code{draw} as a big @code{CASE}
9863: control structure that executes the appropriate code depending on the
9864: kind of object to be drawn. This would be not be very elegant, and,
9865: moreover, we would have to change @code{draw} every time we add
9866: a new kind of graphical object (say, a spaceship).
1.44 crook 9867:
1.78 anton 9868: What we would rather do is: When defining spaceships, we would tell
9869: the system: ``Here's how you @code{draw} a spaceship; you figure
9870: out the rest''.
1.5 anton 9871:
1.78 anton 9872: This is the problem that all systems solve that (rightfully) call
9873: themselves object-oriented; the object-oriented packages presented here
9874: solve this problem (and not much else).
9875: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9876:
1.78 anton 9877: @c ------------------------------------------------------------------------
9878: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9879: @subsection Object-Oriented Terminology
9880: @cindex object-oriented terminology
9881: @cindex terminology for object-oriented programming
1.5 anton 9882:
1.78 anton 9883: This section is mainly for reference, so you don't have to understand
9884: all of it right away. The terminology is mainly Smalltalk-inspired. In
9885: short:
1.44 crook 9886:
1.78 anton 9887: @table @emph
9888: @cindex class
9889: @item class
9890: a data structure definition with some extras.
1.5 anton 9891:
1.78 anton 9892: @cindex object
9893: @item object
9894: an instance of the data structure described by the class definition.
1.5 anton 9895:
1.78 anton 9896: @cindex instance variables
9897: @item instance variables
9898: fields of the data structure.
1.5 anton 9899:
1.78 anton 9900: @cindex selector
9901: @cindex method selector
9902: @cindex virtual function
9903: @item selector
9904: (or @emph{method selector}) a word (e.g.,
9905: @code{draw}) that performs an operation on a variety of data
9906: structures (classes). A selector describes @emph{what} operation to
9907: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9908:
1.78 anton 9909: @cindex method
9910: @item method
9911: the concrete definition that performs the operation
9912: described by the selector for a specific class. A method specifies
9913: @emph{how} the operation is performed for a specific class.
1.5 anton 9914:
1.78 anton 9915: @cindex selector invocation
9916: @cindex message send
9917: @cindex invoking a selector
9918: @item selector invocation
9919: a call of a selector. One argument of the call (the TOS (top-of-stack))
9920: is used for determining which method is used. In Smalltalk terminology:
9921: a message (consisting of the selector and the other arguments) is sent
9922: to the object.
1.5 anton 9923:
1.78 anton 9924: @cindex receiving object
9925: @item receiving object
9926: the object used for determining the method executed by a selector
9927: invocation. In the @file{objects.fs} model, it is the object that is on
9928: the TOS when the selector is invoked. (@emph{Receiving} comes from
9929: the Smalltalk @emph{message} terminology.)
1.5 anton 9930:
1.78 anton 9931: @cindex child class
9932: @cindex parent class
9933: @cindex inheritance
9934: @item child class
9935: a class that has (@emph{inherits}) all properties (instance variables,
9936: selectors, methods) from a @emph{parent class}. In Smalltalk
9937: terminology: The subclass inherits from the superclass. In C++
9938: terminology: The derived class inherits from the base class.
1.5 anton 9939:
1.78 anton 9940: @end table
1.5 anton 9941:
1.78 anton 9942: @c If you wonder about the message sending terminology, it comes from
9943: @c a time when each object had it's own task and objects communicated via
9944: @c message passing; eventually the Smalltalk developers realized that
9945: @c they can do most things through simple (indirect) calls. They kept the
9946: @c terminology.
1.5 anton 9947:
1.78 anton 9948: @c --------------------------------------------------------------
9949: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9950: @subsection The @file{objects.fs} model
9951: @cindex objects
9952: @cindex object-oriented programming
1.26 crook 9953:
1.78 anton 9954: @cindex @file{objects.fs}
9955: @cindex @file{oof.fs}
1.26 crook 9956:
1.78 anton 9957: This section describes the @file{objects.fs} package. This material also
9958: has been published in M. Anton Ertl,
9959: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9960: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9961: 37--43.
9962: @c McKewan's and Zsoter's packages
1.26 crook 9963:
1.78 anton 9964: This section assumes that you have read @ref{Structures}.
1.5 anton 9965:
1.78 anton 9966: The techniques on which this model is based have been used to implement
9967: the parser generator, Gray, and have also been used in Gforth for
9968: implementing the various flavours of word lists (hashed or not,
9969: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 9970:
9971:
1.26 crook 9972: @menu
1.78 anton 9973: * Properties of the Objects model::
9974: * Basic Objects Usage::
9975: * The Objects base class::
9976: * Creating objects::
9977: * Object-Oriented Programming Style::
9978: * Class Binding::
9979: * Method conveniences::
9980: * Classes and Scoping::
9981: * Dividing classes::
9982: * Object Interfaces::
9983: * Objects Implementation::
9984: * Objects Glossary::
1.26 crook 9985: @end menu
1.5 anton 9986:
1.78 anton 9987: Marcel Hendrix provided helpful comments on this section.
1.5 anton 9988:
1.78 anton 9989: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
9990: @subsubsection Properties of the @file{objects.fs} model
9991: @cindex @file{objects.fs} properties
1.5 anton 9992:
1.78 anton 9993: @itemize @bullet
9994: @item
9995: It is straightforward to pass objects on the stack. Passing
9996: selectors on the stack is a little less convenient, but possible.
1.44 crook 9997:
1.78 anton 9998: @item
9999: Objects are just data structures in memory, and are referenced by their
10000: address. You can create words for objects with normal defining words
10001: like @code{constant}. Likewise, there is no difference between instance
10002: variables that contain objects and those that contain other data.
1.5 anton 10003:
1.78 anton 10004: @item
10005: Late binding is efficient and easy to use.
1.44 crook 10006:
1.78 anton 10007: @item
10008: It avoids parsing, and thus avoids problems with state-smartness
10009: and reduced extensibility; for convenience there are a few parsing
10010: words, but they have non-parsing counterparts. There are also a few
10011: defining words that parse. This is hard to avoid, because all standard
10012: defining words parse (except @code{:noname}); however, such
10013: words are not as bad as many other parsing words, because they are not
10014: state-smart.
1.5 anton 10015:
1.78 anton 10016: @item
10017: It does not try to incorporate everything. It does a few things and does
10018: them well (IMO). In particular, this model was not designed to support
10019: information hiding (although it has features that may help); you can use
10020: a separate package for achieving this.
1.5 anton 10021:
1.78 anton 10022: @item
10023: It is layered; you don't have to learn and use all features to use this
10024: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10025: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10026: are optional and independent of each other.
1.5 anton 10027:
1.78 anton 10028: @item
10029: An implementation in ANS Forth is available.
1.5 anton 10030:
1.78 anton 10031: @end itemize
1.5 anton 10032:
1.44 crook 10033:
1.78 anton 10034: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10035: @subsubsection Basic @file{objects.fs} Usage
10036: @cindex basic objects usage
10037: @cindex objects, basic usage
1.5 anton 10038:
1.78 anton 10039: You can define a class for graphical objects like this:
1.44 crook 10040:
1.78 anton 10041: @cindex @code{class} usage
10042: @cindex @code{end-class} usage
10043: @cindex @code{selector} usage
1.5 anton 10044: @example
1.78 anton 10045: object class \ "object" is the parent class
10046: selector draw ( x y graphical -- )
10047: end-class graphical
10048: @end example
10049:
10050: This code defines a class @code{graphical} with an
10051: operation @code{draw}. We can perform the operation
10052: @code{draw} on any @code{graphical} object, e.g.:
10053:
10054: @example
10055: 100 100 t-rex draw
1.26 crook 10056: @end example
1.5 anton 10057:
1.78 anton 10058: @noindent
10059: where @code{t-rex} is a word (say, a constant) that produces a
10060: graphical object.
10061:
10062: @comment TODO add a 2nd operation eg perimeter.. and use for
10063: @comment a concrete example
1.5 anton 10064:
1.78 anton 10065: @cindex abstract class
10066: How do we create a graphical object? With the present definitions,
10067: we cannot create a useful graphical object. The class
10068: @code{graphical} describes graphical objects in general, but not
10069: any concrete graphical object type (C++ users would call it an
10070: @emph{abstract class}); e.g., there is no method for the selector
10071: @code{draw} in the class @code{graphical}.
1.5 anton 10072:
1.78 anton 10073: For concrete graphical objects, we define child classes of the
10074: class @code{graphical}, e.g.:
1.5 anton 10075:
1.78 anton 10076: @cindex @code{overrides} usage
10077: @cindex @code{field} usage in class definition
1.26 crook 10078: @example
1.78 anton 10079: graphical class \ "graphical" is the parent class
10080: cell% field circle-radius
1.5 anton 10081:
1.78 anton 10082: :noname ( x y circle -- )
10083: circle-radius @@ draw-circle ;
10084: overrides draw
1.5 anton 10085:
1.78 anton 10086: :noname ( n-radius circle -- )
10087: circle-radius ! ;
10088: overrides construct
1.5 anton 10089:
1.78 anton 10090: end-class circle
10091: @end example
1.44 crook 10092:
1.78 anton 10093: Here we define a class @code{circle} as a child of @code{graphical},
10094: with field @code{circle-radius} (which behaves just like a field
10095: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10096: for the selectors @code{draw} and @code{construct} (@code{construct} is
10097: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10098:
1.78 anton 10099: Now we can create a circle on the heap (i.e.,
10100: @code{allocate}d memory) with:
1.44 crook 10101:
1.78 anton 10102: @cindex @code{heap-new} usage
1.5 anton 10103: @example
1.78 anton 10104: 50 circle heap-new constant my-circle
1.5 anton 10105: @end example
10106:
1.78 anton 10107: @noindent
10108: @code{heap-new} invokes @code{construct}, thus
10109: initializing the field @code{circle-radius} with 50. We can draw
10110: this new circle at (100,100) with:
1.5 anton 10111:
10112: @example
1.78 anton 10113: 100 100 my-circle draw
1.5 anton 10114: @end example
10115:
1.78 anton 10116: @cindex selector invocation, restrictions
10117: @cindex class definition, restrictions
10118: Note: You can only invoke a selector if the object on the TOS
10119: (the receiving object) belongs to the class where the selector was
10120: defined or one of its descendents; e.g., you can invoke
10121: @code{draw} only for objects belonging to @code{graphical}
10122: or its descendents (e.g., @code{circle}). Immediately before
10123: @code{end-class}, the search order has to be the same as
10124: immediately after @code{class}.
10125:
10126: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10127: @subsubsection The @file{object.fs} base class
10128: @cindex @code{object} class
10129:
10130: When you define a class, you have to specify a parent class. So how do
10131: you start defining classes? There is one class available from the start:
10132: @code{object}. It is ancestor for all classes and so is the
10133: only class that has no parent. It has two selectors: @code{construct}
10134: and @code{print}.
10135:
10136: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10137: @subsubsection Creating objects
10138: @cindex creating objects
10139: @cindex object creation
10140: @cindex object allocation options
10141:
10142: @cindex @code{heap-new} discussion
10143: @cindex @code{dict-new} discussion
10144: @cindex @code{construct} discussion
10145: You can create and initialize an object of a class on the heap with
10146: @code{heap-new} ( ... class -- object ) and in the dictionary
10147: (allocation with @code{allot}) with @code{dict-new} (
10148: ... class -- object ). Both words invoke @code{construct}, which
10149: consumes the stack items indicated by "..." above.
10150:
10151: @cindex @code{init-object} discussion
10152: @cindex @code{class-inst-size} discussion
10153: If you want to allocate memory for an object yourself, you can get its
10154: alignment and size with @code{class-inst-size 2@@} ( class --
10155: align size ). Once you have memory for an object, you can initialize
10156: it with @code{init-object} ( ... class object -- );
10157: @code{construct} does only a part of the necessary work.
10158:
10159: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10160: @subsubsection Object-Oriented Programming Style
10161: @cindex object-oriented programming style
10162: @cindex programming style, object-oriented
1.5 anton 10163:
1.78 anton 10164: This section is not exhaustive.
1.5 anton 10165:
1.78 anton 10166: @cindex stack effects of selectors
10167: @cindex selectors and stack effects
10168: In general, it is a good idea to ensure that all methods for the
10169: same selector have the same stack effect: when you invoke a selector,
10170: you often have no idea which method will be invoked, so, unless all
10171: methods have the same stack effect, you will not know the stack effect
10172: of the selector invocation.
1.5 anton 10173:
1.78 anton 10174: One exception to this rule is methods for the selector
10175: @code{construct}. We know which method is invoked, because we
10176: specify the class to be constructed at the same place. Actually, I
10177: defined @code{construct} as a selector only to give the users a
10178: convenient way to specify initialization. The way it is used, a
10179: mechanism different from selector invocation would be more natural
10180: (but probably would take more code and more space to explain).
1.5 anton 10181:
1.78 anton 10182: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10183: @subsubsection Class Binding
10184: @cindex class binding
10185: @cindex early binding
1.5 anton 10186:
1.78 anton 10187: @cindex late binding
10188: Normal selector invocations determine the method at run-time depending
10189: on the class of the receiving object. This run-time selection is called
10190: @i{late binding}.
1.5 anton 10191:
1.78 anton 10192: Sometimes it's preferable to invoke a different method. For example,
10193: you might want to use the simple method for @code{print}ing
10194: @code{object}s instead of the possibly long-winded @code{print} method
10195: of the receiver class. You can achieve this by replacing the invocation
10196: of @code{print} with:
1.5 anton 10197:
1.78 anton 10198: @cindex @code{[bind]} usage
1.5 anton 10199: @example
1.78 anton 10200: [bind] object print
1.5 anton 10201: @end example
10202:
1.78 anton 10203: @noindent
10204: in compiled code or:
10205:
10206: @cindex @code{bind} usage
1.5 anton 10207: @example
1.78 anton 10208: bind object print
1.5 anton 10209: @end example
10210:
1.78 anton 10211: @cindex class binding, alternative to
10212: @noindent
10213: in interpreted code. Alternatively, you can define the method with a
10214: name (e.g., @code{print-object}), and then invoke it through the
10215: name. Class binding is just a (often more convenient) way to achieve
10216: the same effect; it avoids name clutter and allows you to invoke
10217: methods directly without naming them first.
1.5 anton 10218:
1.78 anton 10219: @cindex superclass binding
10220: @cindex parent class binding
10221: A frequent use of class binding is this: When we define a method
10222: for a selector, we often want the method to do what the selector does
10223: in the parent class, and a little more. There is a special word for
10224: this purpose: @code{[parent]}; @code{[parent]
10225: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10226: selector}}, where @code{@emph{parent}} is the parent
10227: class of the current class. E.g., a method definition might look like:
1.44 crook 10228:
1.78 anton 10229: @cindex @code{[parent]} usage
10230: @example
10231: :noname
10232: dup [parent] foo \ do parent's foo on the receiving object
10233: ... \ do some more
10234: ; overrides foo
10235: @end example
1.6 pazsan 10236:
1.78 anton 10237: @cindex class binding as optimization
10238: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10239: March 1997), Andrew McKewan presents class binding as an optimization
10240: technique. I recommend not using it for this purpose unless you are in
10241: an emergency. Late binding is pretty fast with this model anyway, so the
10242: benefit of using class binding is small; the cost of using class binding
10243: where it is not appropriate is reduced maintainability.
1.44 crook 10244:
1.78 anton 10245: While we are at programming style questions: You should bind
10246: selectors only to ancestor classes of the receiving object. E.g., say,
10247: you know that the receiving object is of class @code{foo} or its
10248: descendents; then you should bind only to @code{foo} and its
10249: ancestors.
1.12 anton 10250:
1.78 anton 10251: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10252: @subsubsection Method conveniences
10253: @cindex method conveniences
1.44 crook 10254:
1.78 anton 10255: In a method you usually access the receiving object pretty often. If
10256: you define the method as a plain colon definition (e.g., with
10257: @code{:noname}), you may have to do a lot of stack
10258: gymnastics. To avoid this, you can define the method with @code{m:
10259: ... ;m}. E.g., you could define the method for
10260: @code{draw}ing a @code{circle} with
1.6 pazsan 10261:
1.78 anton 10262: @cindex @code{this} usage
10263: @cindex @code{m:} usage
10264: @cindex @code{;m} usage
10265: @example
10266: m: ( x y circle -- )
10267: ( x y ) this circle-radius @@ draw-circle ;m
10268: @end example
1.6 pazsan 10269:
1.78 anton 10270: @cindex @code{exit} in @code{m: ... ;m}
10271: @cindex @code{exitm} discussion
10272: @cindex @code{catch} in @code{m: ... ;m}
10273: When this method is executed, the receiver object is removed from the
10274: stack; you can access it with @code{this} (admittedly, in this
10275: example the use of @code{m: ... ;m} offers no advantage). Note
10276: that I specify the stack effect for the whole method (i.e. including
10277: the receiver object), not just for the code between @code{m:}
10278: and @code{;m}. You cannot use @code{exit} in
10279: @code{m:...;m}; instead, use
10280: @code{exitm}.@footnote{Moreover, for any word that calls
10281: @code{catch} and was defined before loading
10282: @code{objects.fs}, you have to redefine it like I redefined
10283: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10284:
1.78 anton 10285: @cindex @code{inst-var} usage
10286: You will frequently use sequences of the form @code{this
10287: @emph{field}} (in the example above: @code{this
10288: circle-radius}). If you use the field only in this way, you can
10289: define it with @code{inst-var} and eliminate the
10290: @code{this} before the field name. E.g., the @code{circle}
10291: class above could also be defined with:
1.6 pazsan 10292:
1.78 anton 10293: @example
10294: graphical class
10295: cell% inst-var radius
1.6 pazsan 10296:
1.78 anton 10297: m: ( x y circle -- )
10298: radius @@ draw-circle ;m
10299: overrides draw
1.6 pazsan 10300:
1.78 anton 10301: m: ( n-radius circle -- )
10302: radius ! ;m
10303: overrides construct
1.6 pazsan 10304:
1.78 anton 10305: end-class circle
10306: @end example
1.6 pazsan 10307:
1.78 anton 10308: @code{radius} can only be used in @code{circle} and its
10309: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10310:
1.78 anton 10311: @cindex @code{inst-value} usage
10312: You can also define fields with @code{inst-value}, which is
10313: to @code{inst-var} what @code{value} is to
10314: @code{variable}. You can change the value of such a field with
10315: @code{[to-inst]}. E.g., we could also define the class
10316: @code{circle} like this:
1.44 crook 10317:
1.78 anton 10318: @example
10319: graphical class
10320: inst-value radius
1.6 pazsan 10321:
1.78 anton 10322: m: ( x y circle -- )
10323: radius draw-circle ;m
10324: overrides draw
1.44 crook 10325:
1.78 anton 10326: m: ( n-radius circle -- )
10327: [to-inst] radius ;m
10328: overrides construct
1.6 pazsan 10329:
1.78 anton 10330: end-class circle
10331: @end example
1.6 pazsan 10332:
1.78 anton 10333: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10334:
1.78 anton 10335: @c Finally, you can define named methods with @code{:m}. One use of this
10336: @c feature is the definition of words that occur only in one class and are
10337: @c not intended to be overridden, but which still need method context
10338: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10339: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10340:
10341:
1.78 anton 10342: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10343: @subsubsection Classes and Scoping
10344: @cindex classes and scoping
10345: @cindex scoping and classes
1.6 pazsan 10346:
1.78 anton 10347: Inheritance is frequent, unlike structure extension. This exacerbates
10348: the problem with the field name convention (@pxref{Structure Naming
10349: Convention}): One always has to remember in which class the field was
10350: originally defined; changing a part of the class structure would require
10351: changes for renaming in otherwise unaffected code.
1.6 pazsan 10352:
1.78 anton 10353: @cindex @code{inst-var} visibility
10354: @cindex @code{inst-value} visibility
10355: To solve this problem, I added a scoping mechanism (which was not in my
10356: original charter): A field defined with @code{inst-var} (or
10357: @code{inst-value}) is visible only in the class where it is defined and in
10358: the descendent classes of this class. Using such fields only makes
10359: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10360:
1.78 anton 10361: This scoping mechanism allows us to use the unadorned field name,
10362: because name clashes with unrelated words become much less likely.
1.6 pazsan 10363:
1.78 anton 10364: @cindex @code{protected} discussion
10365: @cindex @code{private} discussion
10366: Once we have this mechanism, we can also use it for controlling the
10367: visibility of other words: All words defined after
10368: @code{protected} are visible only in the current class and its
10369: descendents. @code{public} restores the compilation
10370: (i.e. @code{current}) word list that was in effect before. If you
10371: have several @code{protected}s without an intervening
10372: @code{public} or @code{set-current}, @code{public}
10373: will restore the compilation word list in effect before the first of
10374: these @code{protected}s.
1.6 pazsan 10375:
1.78 anton 10376: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10377: @subsubsection Dividing classes
10378: @cindex Dividing classes
10379: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10380:
1.78 anton 10381: You may want to do the definition of methods separate from the
10382: definition of the class, its selectors, fields, and instance variables,
10383: i.e., separate the implementation from the definition. You can do this
10384: in the following way:
1.6 pazsan 10385:
1.78 anton 10386: @example
10387: graphical class
10388: inst-value radius
10389: end-class circle
1.6 pazsan 10390:
1.78 anton 10391: ... \ do some other stuff
1.6 pazsan 10392:
1.78 anton 10393: circle methods \ now we are ready
1.44 crook 10394:
1.78 anton 10395: m: ( x y circle -- )
10396: radius draw-circle ;m
10397: overrides draw
1.6 pazsan 10398:
1.78 anton 10399: m: ( n-radius circle -- )
10400: [to-inst] radius ;m
10401: overrides construct
1.44 crook 10402:
1.78 anton 10403: end-methods
10404: @end example
1.7 pazsan 10405:
1.78 anton 10406: You can use several @code{methods}...@code{end-methods} sections. The
10407: only things you can do to the class in these sections are: defining
10408: methods, and overriding the class's selectors. You must not define new
10409: selectors or fields.
1.7 pazsan 10410:
1.78 anton 10411: Note that you often have to override a selector before using it. In
10412: particular, you usually have to override @code{construct} with a new
10413: method before you can invoke @code{heap-new} and friends. E.g., you
10414: must not create a circle before the @code{overrides construct} sequence
10415: in the example above.
1.7 pazsan 10416:
1.78 anton 10417: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10418: @subsubsection Object Interfaces
10419: @cindex object interfaces
10420: @cindex interfaces for objects
1.7 pazsan 10421:
1.78 anton 10422: In this model you can only call selectors defined in the class of the
10423: receiving objects or in one of its ancestors. If you call a selector
10424: with a receiving object that is not in one of these classes, the
10425: result is undefined; if you are lucky, the program crashes
10426: immediately.
1.7 pazsan 10427:
1.78 anton 10428: @cindex selectors common to hardly-related classes
10429: Now consider the case when you want to have a selector (or several)
10430: available in two classes: You would have to add the selector to a
10431: common ancestor class, in the worst case to @code{object}. You
10432: may not want to do this, e.g., because someone else is responsible for
10433: this ancestor class.
1.7 pazsan 10434:
1.78 anton 10435: The solution for this problem is interfaces. An interface is a
10436: collection of selectors. If a class implements an interface, the
10437: selectors become available to the class and its descendents. A class
10438: can implement an unlimited number of interfaces. For the problem
10439: discussed above, we would define an interface for the selector(s), and
10440: both classes would implement the interface.
1.7 pazsan 10441:
1.78 anton 10442: As an example, consider an interface @code{storage} for
10443: writing objects to disk and getting them back, and a class
10444: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10445:
1.78 anton 10446: @cindex @code{interface} usage
10447: @cindex @code{end-interface} usage
10448: @cindex @code{implementation} usage
10449: @example
10450: interface
10451: selector write ( file object -- )
10452: selector read1 ( file object -- )
10453: end-interface storage
1.13 pazsan 10454:
1.78 anton 10455: bar class
10456: storage implementation
1.13 pazsan 10457:
1.78 anton 10458: ... overrides write
10459: ... overrides read1
10460: ...
10461: end-class foo
10462: @end example
1.13 pazsan 10463:
1.78 anton 10464: @noindent
10465: (I would add a word @code{read} @i{( file -- object )} that uses
10466: @code{read1} internally, but that's beyond the point illustrated
10467: here.)
1.13 pazsan 10468:
1.78 anton 10469: Note that you cannot use @code{protected} in an interface; and
10470: of course you cannot define fields.
1.13 pazsan 10471:
1.78 anton 10472: In the Neon model, all selectors are available for all classes;
10473: therefore it does not need interfaces. The price you pay in this model
10474: is slower late binding, and therefore, added complexity to avoid late
10475: binding.
1.13 pazsan 10476:
1.78 anton 10477: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10478: @subsubsection @file{objects.fs} Implementation
10479: @cindex @file{objects.fs} implementation
1.13 pazsan 10480:
1.78 anton 10481: @cindex @code{object-map} discussion
10482: An object is a piece of memory, like one of the data structures
10483: described with @code{struct...end-struct}. It has a field
10484: @code{object-map} that points to the method map for the object's
10485: class.
1.13 pazsan 10486:
1.78 anton 10487: @cindex method map
10488: @cindex virtual function table
10489: The @emph{method map}@footnote{This is Self terminology; in C++
10490: terminology: virtual function table.} is an array that contains the
10491: execution tokens (@i{xt}s) of the methods for the object's class. Each
10492: selector contains an offset into a method map.
1.13 pazsan 10493:
1.78 anton 10494: @cindex @code{selector} implementation, class
10495: @code{selector} is a defining word that uses
10496: @code{CREATE} and @code{DOES>}. The body of the
10497: selector contains the offset; the @code{DOES>} action for a
10498: class selector is, basically:
1.8 pazsan 10499:
10500: @example
1.78 anton 10501: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10502: @end example
10503:
1.78 anton 10504: Since @code{object-map} is the first field of the object, it
10505: does not generate any code. As you can see, calling a selector has a
10506: small, constant cost.
1.26 crook 10507:
1.78 anton 10508: @cindex @code{current-interface} discussion
10509: @cindex class implementation and representation
10510: A class is basically a @code{struct} combined with a method
10511: map. During the class definition the alignment and size of the class
10512: are passed on the stack, just as with @code{struct}s, so
10513: @code{field} can also be used for defining class
10514: fields. However, passing more items on the stack would be
10515: inconvenient, so @code{class} builds a data structure in memory,
10516: which is accessed through the variable
10517: @code{current-interface}. After its definition is complete, the
10518: class is represented on the stack by a pointer (e.g., as parameter for
10519: a child class definition).
1.26 crook 10520:
1.78 anton 10521: A new class starts off with the alignment and size of its parent,
10522: and a copy of the parent's method map. Defining new fields extends the
10523: size and alignment; likewise, defining new selectors extends the
10524: method map. @code{overrides} just stores a new @i{xt} in the method
10525: map at the offset given by the selector.
1.13 pazsan 10526:
1.78 anton 10527: @cindex class binding, implementation
10528: Class binding just gets the @i{xt} at the offset given by the selector
10529: from the class's method map and @code{compile,}s (in the case of
10530: @code{[bind]}) it.
1.13 pazsan 10531:
1.78 anton 10532: @cindex @code{this} implementation
10533: @cindex @code{catch} and @code{this}
10534: @cindex @code{this} and @code{catch}
10535: I implemented @code{this} as a @code{value}. At the
10536: start of an @code{m:...;m} method the old @code{this} is
10537: stored to the return stack and restored at the end; and the object on
10538: the TOS is stored @code{TO this}. This technique has one
10539: disadvantage: If the user does not leave the method via
10540: @code{;m}, but via @code{throw} or @code{exit},
10541: @code{this} is not restored (and @code{exit} may
10542: crash). To deal with the @code{throw} problem, I have redefined
10543: @code{catch} to save and restore @code{this}; the same
10544: should be done with any word that can catch an exception. As for
10545: @code{exit}, I simply forbid it (as a replacement, there is
10546: @code{exitm}).
1.13 pazsan 10547:
1.78 anton 10548: @cindex @code{inst-var} implementation
10549: @code{inst-var} is just the same as @code{field}, with
10550: a different @code{DOES>} action:
1.13 pazsan 10551: @example
1.78 anton 10552: @@ this +
1.8 pazsan 10553: @end example
1.78 anton 10554: Similar for @code{inst-value}.
1.8 pazsan 10555:
1.78 anton 10556: @cindex class scoping implementation
10557: Each class also has a word list that contains the words defined with
10558: @code{inst-var} and @code{inst-value}, and its protected
10559: words. It also has a pointer to its parent. @code{class} pushes
10560: the word lists of the class and all its ancestors onto the search order stack,
10561: and @code{end-class} drops them.
1.20 pazsan 10562:
1.78 anton 10563: @cindex interface implementation
10564: An interface is like a class without fields, parent and protected
10565: words; i.e., it just has a method map. If a class implements an
10566: interface, its method map contains a pointer to the method map of the
10567: interface. The positive offsets in the map are reserved for class
10568: methods, therefore interface map pointers have negative
10569: offsets. Interfaces have offsets that are unique throughout the
10570: system, unlike class selectors, whose offsets are only unique for the
10571: classes where the selector is available (invokable).
1.20 pazsan 10572:
1.78 anton 10573: This structure means that interface selectors have to perform one
10574: indirection more than class selectors to find their method. Their body
10575: contains the interface map pointer offset in the class method map, and
10576: the method offset in the interface method map. The
10577: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10578:
10579: @example
1.78 anton 10580: ( object selector-body )
10581: 2dup selector-interface @@ ( object selector-body object interface-offset )
10582: swap object-map @@ + @@ ( object selector-body map )
10583: swap selector-offset @@ + @@ execute
1.20 pazsan 10584: @end example
10585:
1.78 anton 10586: where @code{object-map} and @code{selector-offset} are
10587: first fields and generate no code.
1.20 pazsan 10588:
1.78 anton 10589: As a concrete example, consider the following code:
1.20 pazsan 10590:
10591: @example
1.78 anton 10592: interface
10593: selector if1sel1
10594: selector if1sel2
10595: end-interface if1
1.20 pazsan 10596:
1.78 anton 10597: object class
10598: if1 implementation
10599: selector cl1sel1
10600: cell% inst-var cl1iv1
1.20 pazsan 10601:
1.78 anton 10602: ' m1 overrides construct
10603: ' m2 overrides if1sel1
10604: ' m3 overrides if1sel2
10605: ' m4 overrides cl1sel2
10606: end-class cl1
1.20 pazsan 10607:
1.78 anton 10608: create obj1 object dict-new drop
10609: create obj2 cl1 dict-new drop
10610: @end example
1.20 pazsan 10611:
1.78 anton 10612: The data structure created by this code (including the data structure
10613: for @code{object}) is shown in the
10614: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10615: @comment TODO add this diagram..
1.20 pazsan 10616:
1.78 anton 10617: @node Objects Glossary, , Objects Implementation, Objects
10618: @subsubsection @file{objects.fs} Glossary
10619: @cindex @file{objects.fs} Glossary
1.20 pazsan 10620:
10621:
1.78 anton 10622: doc---objects-bind
10623: doc---objects-<bind>
10624: doc---objects-bind'
10625: doc---objects-[bind]
10626: doc---objects-class
10627: doc---objects-class->map
10628: doc---objects-class-inst-size
10629: doc---objects-class-override!
1.79 anton 10630: doc---objects-class-previous
10631: doc---objects-class>order
1.78 anton 10632: doc---objects-construct
10633: doc---objects-current'
10634: doc---objects-[current]
10635: doc---objects-current-interface
10636: doc---objects-dict-new
10637: doc---objects-end-class
10638: doc---objects-end-class-noname
10639: doc---objects-end-interface
10640: doc---objects-end-interface-noname
10641: doc---objects-end-methods
10642: doc---objects-exitm
10643: doc---objects-heap-new
10644: doc---objects-implementation
10645: doc---objects-init-object
10646: doc---objects-inst-value
10647: doc---objects-inst-var
10648: doc---objects-interface
10649: doc---objects-m:
10650: doc---objects-:m
10651: doc---objects-;m
10652: doc---objects-method
10653: doc---objects-methods
10654: doc---objects-object
10655: doc---objects-overrides
10656: doc---objects-[parent]
10657: doc---objects-print
10658: doc---objects-protected
10659: doc---objects-public
10660: doc---objects-selector
10661: doc---objects-this
10662: doc---objects-<to-inst>
10663: doc---objects-[to-inst]
10664: doc---objects-to-this
10665: doc---objects-xt-new
1.20 pazsan 10666:
10667:
1.78 anton 10668: @c -------------------------------------------------------------
10669: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10670: @subsection The @file{oof.fs} model
10671: @cindex oof
10672: @cindex object-oriented programming
1.20 pazsan 10673:
1.78 anton 10674: @cindex @file{objects.fs}
10675: @cindex @file{oof.fs}
1.20 pazsan 10676:
1.78 anton 10677: This section describes the @file{oof.fs} package.
1.20 pazsan 10678:
1.78 anton 10679: The package described in this section has been used in bigFORTH since 1991, and
10680: used for two large applications: a chromatographic system used to
10681: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10682:
1.78 anton 10683: You can find a description (in German) of @file{oof.fs} in @cite{Object
10684: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10685: 10(2), 1994.
1.20 pazsan 10686:
1.78 anton 10687: @menu
10688: * Properties of the OOF model::
10689: * Basic OOF Usage::
10690: * The OOF base class::
10691: * Class Declaration::
10692: * Class Implementation::
10693: @end menu
1.20 pazsan 10694:
1.78 anton 10695: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10696: @subsubsection Properties of the @file{oof.fs} model
10697: @cindex @file{oof.fs} properties
1.20 pazsan 10698:
1.78 anton 10699: @itemize @bullet
10700: @item
10701: This model combines object oriented programming with information
10702: hiding. It helps you writing large application, where scoping is
10703: necessary, because it provides class-oriented scoping.
1.20 pazsan 10704:
1.78 anton 10705: @item
10706: Named objects, object pointers, and object arrays can be created,
10707: selector invocation uses the ``object selector'' syntax. Selector invocation
10708: to objects and/or selectors on the stack is a bit less convenient, but
10709: possible.
1.44 crook 10710:
1.78 anton 10711: @item
10712: Selector invocation and instance variable usage of the active object is
10713: straightforward, since both make use of the active object.
1.44 crook 10714:
1.78 anton 10715: @item
10716: Late binding is efficient and easy to use.
1.20 pazsan 10717:
1.78 anton 10718: @item
10719: State-smart objects parse selectors. However, extensibility is provided
10720: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10721:
1.78 anton 10722: @item
10723: An implementation in ANS Forth is available.
1.20 pazsan 10724:
1.78 anton 10725: @end itemize
1.23 crook 10726:
10727:
1.78 anton 10728: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10729: @subsubsection Basic @file{oof.fs} Usage
10730: @cindex @file{oof.fs} usage
1.23 crook 10731:
1.78 anton 10732: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10733:
1.78 anton 10734: You can define a class for graphical objects like this:
1.23 crook 10735:
1.78 anton 10736: @cindex @code{class} usage
10737: @cindex @code{class;} usage
10738: @cindex @code{method} usage
10739: @example
10740: object class graphical \ "object" is the parent class
10741: method draw ( x y graphical -- )
10742: class;
10743: @end example
1.23 crook 10744:
1.78 anton 10745: This code defines a class @code{graphical} with an
10746: operation @code{draw}. We can perform the operation
10747: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10748:
1.78 anton 10749: @example
10750: 100 100 t-rex draw
10751: @end example
1.23 crook 10752:
1.78 anton 10753: @noindent
10754: where @code{t-rex} is an object or object pointer, created with e.g.
10755: @code{graphical : t-rex}.
1.23 crook 10756:
1.78 anton 10757: @cindex abstract class
10758: How do we create a graphical object? With the present definitions,
10759: we cannot create a useful graphical object. The class
10760: @code{graphical} describes graphical objects in general, but not
10761: any concrete graphical object type (C++ users would call it an
10762: @emph{abstract class}); e.g., there is no method for the selector
10763: @code{draw} in the class @code{graphical}.
1.23 crook 10764:
1.78 anton 10765: For concrete graphical objects, we define child classes of the
10766: class @code{graphical}, e.g.:
1.23 crook 10767:
1.78 anton 10768: @example
10769: graphical class circle \ "graphical" is the parent class
10770: cell var circle-radius
10771: how:
10772: : draw ( x y -- )
10773: circle-radius @@ draw-circle ;
1.23 crook 10774:
1.78 anton 10775: : init ( n-radius -- (
10776: circle-radius ! ;
10777: class;
10778: @end example
1.1 anton 10779:
1.78 anton 10780: Here we define a class @code{circle} as a child of @code{graphical},
10781: with a field @code{circle-radius}; it defines new methods for the
10782: selectors @code{draw} and @code{init} (@code{init} is defined in
10783: @code{object}, the parent class of @code{graphical}).
1.1 anton 10784:
1.78 anton 10785: Now we can create a circle in the dictionary with:
1.1 anton 10786:
1.78 anton 10787: @example
10788: 50 circle : my-circle
10789: @end example
1.21 crook 10790:
1.78 anton 10791: @noindent
10792: @code{:} invokes @code{init}, thus initializing the field
10793: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10794: with:
1.1 anton 10795:
1.78 anton 10796: @example
10797: 100 100 my-circle draw
10798: @end example
1.1 anton 10799:
1.78 anton 10800: @cindex selector invocation, restrictions
10801: @cindex class definition, restrictions
10802: Note: You can only invoke a selector if the receiving object belongs to
10803: the class where the selector was defined or one of its descendents;
10804: e.g., you can invoke @code{draw} only for objects belonging to
10805: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10806: mechanism will check if you try to invoke a selector that is not
10807: defined in this class hierarchy, so you'll get an error at compilation
10808: time.
1.1 anton 10809:
10810:
1.78 anton 10811: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10812: @subsubsection The @file{oof.fs} base class
10813: @cindex @file{oof.fs} base class
1.1 anton 10814:
1.78 anton 10815: When you define a class, you have to specify a parent class. So how do
10816: you start defining classes? There is one class available from the start:
10817: @code{object}. You have to use it as ancestor for all classes. It is the
10818: only class that has no parent. Classes are also objects, except that
10819: they don't have instance variables; class manipulation such as
10820: inheritance or changing definitions of a class is handled through
10821: selectors of the class @code{object}.
1.1 anton 10822:
1.78 anton 10823: @code{object} provides a number of selectors:
1.1 anton 10824:
1.78 anton 10825: @itemize @bullet
10826: @item
10827: @code{class} for subclassing, @code{definitions} to add definitions
10828: later on, and @code{class?} to get type informations (is the class a
10829: subclass of the class passed on the stack?).
1.1 anton 10830:
1.78 anton 10831: doc---object-class
10832: doc---object-definitions
10833: doc---object-class?
1.1 anton 10834:
10835:
1.26 crook 10836: @item
1.78 anton 10837: @code{init} and @code{dispose} as constructor and destructor of the
10838: object. @code{init} is invocated after the object's memory is allocated,
10839: while @code{dispose} also handles deallocation. Thus if you redefine
10840: @code{dispose}, you have to call the parent's dispose with @code{super
10841: dispose}, too.
10842:
10843: doc---object-init
10844: doc---object-dispose
10845:
1.1 anton 10846:
1.26 crook 10847: @item
1.78 anton 10848: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10849: @code{[]} to create named and unnamed objects and object arrays or
10850: object pointers.
10851:
10852: doc---object-new
10853: doc---object-new[]
10854: doc---object-:
10855: doc---object-ptr
10856: doc---object-asptr
10857: doc---object-[]
10858:
1.1 anton 10859:
1.26 crook 10860: @item
1.78 anton 10861: @code{::} and @code{super} for explicit scoping. You should use explicit
10862: scoping only for super classes or classes with the same set of instance
10863: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10864:
1.78 anton 10865: doc---object-::
10866: doc---object-super
1.21 crook 10867:
10868:
1.26 crook 10869: @item
1.78 anton 10870: @code{self} to get the address of the object
1.21 crook 10871:
1.78 anton 10872: doc---object-self
1.21 crook 10873:
10874:
1.78 anton 10875: @item
10876: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10877: pointers and instance defers.
1.21 crook 10878:
1.78 anton 10879: doc---object-bind
10880: doc---object-bound
10881: doc---object-link
10882: doc---object-is
1.21 crook 10883:
10884:
1.78 anton 10885: @item
10886: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10887: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10888:
1.78 anton 10889: doc---object-'
10890: doc---object-postpone
1.21 crook 10891:
10892:
1.78 anton 10893: @item
10894: @code{with} and @code{endwith} to select the active object from the
10895: stack, and enable its scope. Using @code{with} and @code{endwith}
10896: also allows you to create code using selector @code{postpone} without being
10897: trapped by the state-smart objects.
1.21 crook 10898:
1.78 anton 10899: doc---object-with
10900: doc---object-endwith
1.21 crook 10901:
10902:
1.78 anton 10903: @end itemize
1.21 crook 10904:
1.78 anton 10905: @node Class Declaration, Class Implementation, The OOF base class, OOF
10906: @subsubsection Class Declaration
10907: @cindex class declaration
1.21 crook 10908:
1.78 anton 10909: @itemize @bullet
10910: @item
10911: Instance variables
1.21 crook 10912:
1.78 anton 10913: doc---oof-var
1.21 crook 10914:
10915:
1.78 anton 10916: @item
10917: Object pointers
1.21 crook 10918:
1.78 anton 10919: doc---oof-ptr
10920: doc---oof-asptr
1.21 crook 10921:
10922:
1.78 anton 10923: @item
10924: Instance defers
1.21 crook 10925:
1.78 anton 10926: doc---oof-defer
1.21 crook 10927:
10928:
1.78 anton 10929: @item
10930: Method selectors
1.21 crook 10931:
1.78 anton 10932: doc---oof-early
10933: doc---oof-method
1.21 crook 10934:
10935:
1.78 anton 10936: @item
10937: Class-wide variables
1.21 crook 10938:
1.78 anton 10939: doc---oof-static
1.21 crook 10940:
10941:
1.78 anton 10942: @item
10943: End declaration
1.1 anton 10944:
1.78 anton 10945: doc---oof-how:
10946: doc---oof-class;
1.21 crook 10947:
10948:
1.78 anton 10949: @end itemize
1.21 crook 10950:
1.78 anton 10951: @c -------------------------------------------------------------
10952: @node Class Implementation, , Class Declaration, OOF
10953: @subsubsection Class Implementation
10954: @cindex class implementation
1.21 crook 10955:
1.78 anton 10956: @c -------------------------------------------------------------
10957: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10958: @subsection The @file{mini-oof.fs} model
10959: @cindex mini-oof
1.21 crook 10960:
1.78 anton 10961: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 10962: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 10963: and reduces to the bare minimum of features. This is based on a posting
10964: of Bernd Paysan in comp.lang.forth.
1.21 crook 10965:
1.78 anton 10966: @menu
10967: * Basic Mini-OOF Usage::
10968: * Mini-OOF Example::
10969: * Mini-OOF Implementation::
10970: @end menu
1.21 crook 10971:
1.78 anton 10972: @c -------------------------------------------------------------
10973: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10974: @subsubsection Basic @file{mini-oof.fs} Usage
10975: @cindex mini-oof usage
1.21 crook 10976:
1.78 anton 10977: There is a base class (@code{class}, which allocates one cell for the
10978: object pointer) plus seven other words: to define a method, a variable,
10979: a class; to end a class, to resolve binding, to allocate an object and
10980: to compile a class method.
10981: @comment TODO better description of the last one
1.26 crook 10982:
1.21 crook 10983:
1.78 anton 10984: doc-object
10985: doc-method
10986: doc-var
10987: doc-class
10988: doc-end-class
10989: doc-defines
10990: doc-new
10991: doc-::
1.21 crook 10992:
10993:
10994:
1.78 anton 10995: @c -------------------------------------------------------------
10996: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10997: @subsubsection Mini-OOF Example
10998: @cindex mini-oof example
1.1 anton 10999:
1.78 anton 11000: A short example shows how to use this package. This example, in slightly
11001: extended form, is supplied as @file{moof-exm.fs}
11002: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11003:
1.26 crook 11004: @example
1.78 anton 11005: object class
11006: method init
11007: method draw
11008: end-class graphical
1.26 crook 11009: @end example
1.20 pazsan 11010:
1.78 anton 11011: This code defines a class @code{graphical} with an
11012: operation @code{draw}. We can perform the operation
11013: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11014:
1.26 crook 11015: @example
1.78 anton 11016: 100 100 t-rex draw
1.26 crook 11017: @end example
1.12 anton 11018:
1.78 anton 11019: where @code{t-rex} is an object or object pointer, created with e.g.
11020: @code{graphical new Constant t-rex}.
1.12 anton 11021:
1.78 anton 11022: For concrete graphical objects, we define child classes of the
11023: class @code{graphical}, e.g.:
1.12 anton 11024:
1.26 crook 11025: @example
11026: graphical class
1.78 anton 11027: cell var circle-radius
11028: end-class circle \ "graphical" is the parent class
1.12 anton 11029:
1.78 anton 11030: :noname ( x y -- )
11031: circle-radius @@ draw-circle ; circle defines draw
11032: :noname ( r -- )
11033: circle-radius ! ; circle defines init
11034: @end example
1.12 anton 11035:
1.78 anton 11036: There is no implicit init method, so we have to define one. The creation
11037: code of the object now has to call init explicitely.
1.21 crook 11038:
1.78 anton 11039: @example
11040: circle new Constant my-circle
11041: 50 my-circle init
1.12 anton 11042: @end example
11043:
1.78 anton 11044: It is also possible to add a function to create named objects with
11045: automatic call of @code{init}, given that all objects have @code{init}
11046: on the same place:
1.38 anton 11047:
1.78 anton 11048: @example
11049: : new: ( .. o "name" -- )
11050: new dup Constant init ;
11051: 80 circle new: large-circle
11052: @end example
1.12 anton 11053:
1.78 anton 11054: We can draw this new circle at (100,100) with:
1.12 anton 11055:
1.78 anton 11056: @example
11057: 100 100 my-circle draw
11058: @end example
1.12 anton 11059:
1.78 anton 11060: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11061: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11062:
1.78 anton 11063: Object-oriented systems with late binding typically use a
11064: ``vtable''-approach: the first variable in each object is a pointer to a
11065: table, which contains the methods as function pointers. The vtable
11066: may also contain other information.
1.12 anton 11067:
1.79 anton 11068: So first, let's declare selectors:
1.37 anton 11069:
11070: @example
1.79 anton 11071: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11072: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11073: @end example
1.37 anton 11074:
1.79 anton 11075: During selector declaration, the number of selectors and instance
11076: variables is on the stack (in address units). @code{method} creates one
11077: selector and increments the selector number. To execute a selector, it
1.78 anton 11078: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11079: executes the method @i{xt} stored there. Each selector takes the object
11080: it is invoked with as top of stack parameter; it passes the parameters
11081: (including the object) unchanged to the appropriate method which should
1.78 anton 11082: consume that object.
1.37 anton 11083:
1.78 anton 11084: Now, we also have to declare instance variables
1.37 anton 11085:
1.78 anton 11086: @example
1.79 anton 11087: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11088: DOES> ( o -- addr ) @@ + ;
1.37 anton 11089: @end example
11090:
1.78 anton 11091: As before, a word is created with the current offset. Instance
11092: variables can have different sizes (cells, floats, doubles, chars), so
11093: all we do is take the size and add it to the offset. If your machine
11094: has alignment restrictions, put the proper @code{aligned} or
11095: @code{faligned} before the variable, to adjust the variable
11096: offset. That's why it is on the top of stack.
1.37 anton 11097:
1.78 anton 11098: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11099:
1.78 anton 11100: @example
11101: Create object 1 cells , 2 cells ,
1.79 anton 11102: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11103: @end example
1.12 anton 11104:
1.78 anton 11105: For inheritance, the vtable of the parent object has to be
11106: copied when a new, derived class is declared. This gives all the
11107: methods of the parent class, which can be overridden, though.
1.12 anton 11108:
1.78 anton 11109: @example
1.79 anton 11110: : end-class ( class selectors vars "name" -- )
1.78 anton 11111: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11112: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11113: @end example
1.12 anton 11114:
1.78 anton 11115: The first line creates the vtable, initialized with
11116: @code{noop}s. The second line is the inheritance mechanism, it
11117: copies the xts from the parent vtable.
1.12 anton 11118:
1.78 anton 11119: We still have no way to define new methods, let's do that now:
1.12 anton 11120:
1.26 crook 11121: @example
1.79 anton 11122: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11123: @end example
1.12 anton 11124:
1.78 anton 11125: To allocate a new object, we need a word, too:
1.12 anton 11126:
1.78 anton 11127: @example
11128: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11129: @end example
11130:
1.78 anton 11131: Sometimes derived classes want to access the method of the
11132: parent object. There are two ways to achieve this with Mini-OOF:
11133: first, you could use named words, and second, you could look up the
11134: vtable of the parent object.
1.12 anton 11135:
1.78 anton 11136: @example
11137: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11138: @end example
1.12 anton 11139:
11140:
1.78 anton 11141: Nothing can be more confusing than a good example, so here is
11142: one. First let's declare a text object (called
11143: @code{button}), that stores text and position:
1.12 anton 11144:
1.78 anton 11145: @example
11146: object class
11147: cell var text
11148: cell var len
11149: cell var x
11150: cell var y
11151: method init
11152: method draw
11153: end-class button
11154: @end example
1.12 anton 11155:
1.78 anton 11156: @noindent
11157: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11158:
1.26 crook 11159: @example
1.78 anton 11160: :noname ( o -- )
11161: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11162: button defines draw
11163: :noname ( addr u o -- )
11164: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11165: button defines init
1.26 crook 11166: @end example
1.12 anton 11167:
1.78 anton 11168: @noindent
11169: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11170: new data and no new selectors:
1.78 anton 11171:
11172: @example
11173: button class
11174: end-class bold-button
1.12 anton 11175:
1.78 anton 11176: : bold 27 emit ." [1m" ;
11177: : normal 27 emit ." [0m" ;
11178: @end example
1.1 anton 11179:
1.78 anton 11180: @noindent
11181: The class @code{bold-button} has a different draw method to
11182: @code{button}, but the new method is defined in terms of the draw method
11183: for @code{button}:
1.20 pazsan 11184:
1.78 anton 11185: @example
11186: :noname bold [ button :: draw ] normal ; bold-button defines draw
11187: @end example
1.21 crook 11188:
1.78 anton 11189: @noindent
1.79 anton 11190: Finally, create two objects and apply selectors:
1.21 crook 11191:
1.26 crook 11192: @example
1.78 anton 11193: button new Constant foo
11194: s" thin foo" foo init
11195: page
11196: foo draw
11197: bold-button new Constant bar
11198: s" fat bar" bar init
11199: 1 bar y !
11200: bar draw
1.26 crook 11201: @end example
1.21 crook 11202:
11203:
1.78 anton 11204: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11205: @subsection Comparison with other object models
11206: @cindex comparison of object models
11207: @cindex object models, comparison
11208:
11209: Many object-oriented Forth extensions have been proposed (@cite{A survey
11210: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11211: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11212: relation of the object models described here to two well-known and two
11213: closely-related (by the use of method maps) models. Andras Zsoter
11214: helped us with this section.
11215:
11216: @cindex Neon model
11217: The most popular model currently seems to be the Neon model (see
11218: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11219: 1997) by Andrew McKewan) but this model has a number of limitations
11220: @footnote{A longer version of this critique can be
11221: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11222: Dimensions, May 1997) by Anton Ertl.}:
11223:
11224: @itemize @bullet
11225: @item
11226: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11227: to pass objects on the stack.
1.21 crook 11228:
1.78 anton 11229: @item
11230: It requires that the selector parses the input stream (at
1.79 anton 11231: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11232: hard to find.
1.21 crook 11233:
1.78 anton 11234: @item
1.79 anton 11235: It allows using every selector on every object; this eliminates the
11236: need for interfaces, but makes it harder to create efficient
11237: implementations.
1.78 anton 11238: @end itemize
1.21 crook 11239:
1.78 anton 11240: @cindex Pountain's object-oriented model
11241: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11242: Press, London, 1987) by Dick Pountain. However, it is not really about
11243: object-oriented programming, because it hardly deals with late
11244: binding. Instead, it focuses on features like information hiding and
11245: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11246:
1.78 anton 11247: @cindex Zsoter's object-oriented model
1.79 anton 11248: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11249: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11250: describes a model that makes heavy use of an active object (like
11251: @code{this} in @file{objects.fs}): The active object is not only used
11252: for accessing all fields, but also specifies the receiving object of
11253: every selector invocation; you have to change the active object
11254: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11255: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11256: the method entry point is unnecessary with Zsoter's model, because the
11257: receiving object is the active object already. On the other hand, the
11258: explicit change is absolutely necessary in that model, because otherwise
11259: no one could ever change the active object. An ANS Forth implementation
11260: of this model is available through
11261: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11262:
1.78 anton 11263: @cindex @file{oof.fs}, differences to other models
11264: The @file{oof.fs} model combines information hiding and overloading
11265: resolution (by keeping names in various word lists) with object-oriented
11266: programming. It sets the active object implicitly on method entry, but
11267: also allows explicit changing (with @code{>o...o>} or with
11268: @code{with...endwith}). It uses parsing and state-smart objects and
11269: classes for resolving overloading and for early binding: the object or
11270: class parses the selector and determines the method from this. If the
11271: selector is not parsed by an object or class, it performs a call to the
11272: selector for the active object (late binding), like Zsoter's model.
11273: Fields are always accessed through the active object. The big
11274: disadvantage of this model is the parsing and the state-smartness, which
11275: reduces extensibility and increases the opportunities for subtle bugs;
11276: essentially, you are only safe if you never tick or @code{postpone} an
11277: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11278:
1.78 anton 11279: @cindex @file{mini-oof.fs}, differences to other models
11280: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11281: version of the @file{objects.fs} model, but syntactically it is a
11282: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11283:
11284:
1.78 anton 11285: @c -------------------------------------------------------------
11286: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11287: @section Programming Tools
11288: @cindex programming tools
1.21 crook 11289:
1.78 anton 11290: @c !! move this and assembler down below OO stuff.
1.21 crook 11291:
1.78 anton 11292: @menu
11293: * Examining::
11294: * Forgetting words::
11295: * Debugging:: Simple and quick.
11296: * Assertions:: Making your programs self-checking.
11297: * Singlestep Debugger:: Executing your program word by word.
11298: @end menu
1.21 crook 11299:
1.78 anton 11300: @node Examining, Forgetting words, Programming Tools, Programming Tools
11301: @subsection Examining data and code
11302: @cindex examining data and code
11303: @cindex data examination
11304: @cindex code examination
1.44 crook 11305:
1.78 anton 11306: The following words inspect the stack non-destructively:
1.21 crook 11307:
1.78 anton 11308: doc-.s
11309: doc-f.s
1.44 crook 11310:
1.78 anton 11311: There is a word @code{.r} but it does @i{not} display the return stack!
11312: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11313:
1.78 anton 11314: doc-depth
11315: doc-fdepth
11316: doc-clearstack
1.124 anton 11317: doc-clearstacks
1.21 crook 11318:
1.78 anton 11319: The following words inspect memory.
1.21 crook 11320:
1.78 anton 11321: doc-?
11322: doc-dump
1.21 crook 11323:
1.78 anton 11324: And finally, @code{see} allows to inspect code:
1.21 crook 11325:
1.78 anton 11326: doc-see
11327: doc-xt-see
1.111 anton 11328: doc-simple-see
11329: doc-simple-see-range
1.21 crook 11330:
1.78 anton 11331: @node Forgetting words, Debugging, Examining, Programming Tools
11332: @subsection Forgetting words
11333: @cindex words, forgetting
11334: @cindex forgeting words
1.21 crook 11335:
1.78 anton 11336: @c anton: other, maybe better places for this subsection: Defining Words;
11337: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11338:
1.78 anton 11339: Forth allows you to forget words (and everything that was alloted in the
11340: dictonary after them) in a LIFO manner.
1.21 crook 11341:
1.78 anton 11342: doc-marker
1.21 crook 11343:
1.78 anton 11344: The most common use of this feature is during progam development: when
11345: you change a source file, forget all the words it defined and load it
11346: again (since you also forget everything defined after the source file
11347: was loaded, you have to reload that, too). Note that effects like
11348: storing to variables and destroyed system words are not undone when you
11349: forget words. With a system like Gforth, that is fast enough at
11350: starting up and compiling, I find it more convenient to exit and restart
11351: Gforth, as this gives me a clean slate.
1.21 crook 11352:
1.78 anton 11353: Here's an example of using @code{marker} at the start of a source file
11354: that you are debugging; it ensures that you only ever have one copy of
11355: the file's definitions compiled at any time:
1.21 crook 11356:
1.78 anton 11357: @example
11358: [IFDEF] my-code
11359: my-code
11360: [ENDIF]
1.26 crook 11361:
1.78 anton 11362: marker my-code
11363: init-included-files
1.21 crook 11364:
1.78 anton 11365: \ .. definitions start here
11366: \ .
11367: \ .
11368: \ end
11369: @end example
1.21 crook 11370:
1.26 crook 11371:
1.78 anton 11372: @node Debugging, Assertions, Forgetting words, Programming Tools
11373: @subsection Debugging
11374: @cindex debugging
1.21 crook 11375:
1.78 anton 11376: Languages with a slow edit/compile/link/test development loop tend to
11377: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11378:
1.78 anton 11379: A much better (faster) way in fast-compiling languages is to add
11380: printing code at well-selected places, let the program run, look at
11381: the output, see where things went wrong, add more printing code, etc.,
11382: until the bug is found.
1.21 crook 11383:
1.78 anton 11384: The simple debugging aids provided in @file{debugs.fs}
11385: are meant to support this style of debugging.
1.21 crook 11386:
1.78 anton 11387: The word @code{~~} prints debugging information (by default the source
11388: location and the stack contents). It is easy to insert. If you use Emacs
11389: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11390: query-replace them with nothing). The deferred words
1.101 anton 11391: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11392: @code{~~}. The default source location output format works well with
11393: Emacs' compilation mode, so you can step through the program at the
11394: source level using @kbd{C-x `} (the advantage over a stepping debugger
11395: is that you can step in any direction and you know where the crash has
11396: happened or where the strange data has occurred).
1.21 crook 11397:
1.78 anton 11398: doc-~~
11399: doc-printdebugdata
1.101 anton 11400: doc-.debugline
1.21 crook 11401:
1.106 anton 11402: @cindex filenames in @code{~~} output
11403: @code{~~} (and assertions) will usually print the wrong file name if a
11404: marker is executed in the same file after their occurance. They will
11405: print @samp{*somewhere*} as file name if a marker is executed in the
11406: same file before their occurance.
11407:
11408:
1.78 anton 11409: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11410: @subsection Assertions
11411: @cindex assertions
1.21 crook 11412:
1.78 anton 11413: It is a good idea to make your programs self-checking, especially if you
11414: make an assumption that may become invalid during maintenance (for
11415: example, that a certain field of a data structure is never zero). Gforth
11416: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11417:
11418: @example
1.78 anton 11419: assert( @i{flag} )
1.26 crook 11420: @end example
11421:
1.78 anton 11422: The code between @code{assert(} and @code{)} should compute a flag, that
11423: should be true if everything is alright and false otherwise. It should
11424: not change anything else on the stack. The overall stack effect of the
11425: assertion is @code{( -- )}. E.g.
1.21 crook 11426:
1.26 crook 11427: @example
1.78 anton 11428: assert( 1 1 + 2 = ) \ what we learn in school
11429: assert( dup 0<> ) \ assert that the top of stack is not zero
11430: assert( false ) \ this code should not be reached
1.21 crook 11431: @end example
11432:
1.78 anton 11433: The need for assertions is different at different times. During
11434: debugging, we want more checking, in production we sometimes care more
11435: for speed. Therefore, assertions can be turned off, i.e., the assertion
11436: becomes a comment. Depending on the importance of an assertion and the
11437: time it takes to check it, you may want to turn off some assertions and
11438: keep others turned on. Gforth provides several levels of assertions for
11439: this purpose:
11440:
11441:
11442: doc-assert0(
11443: doc-assert1(
11444: doc-assert2(
11445: doc-assert3(
11446: doc-assert(
11447: doc-)
1.21 crook 11448:
11449:
1.78 anton 11450: The variable @code{assert-level} specifies the highest assertions that
11451: are turned on. I.e., at the default @code{assert-level} of one,
11452: @code{assert0(} and @code{assert1(} assertions perform checking, while
11453: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11454:
1.78 anton 11455: The value of @code{assert-level} is evaluated at compile-time, not at
11456: run-time. Therefore you cannot turn assertions on or off at run-time;
11457: you have to set the @code{assert-level} appropriately before compiling a
11458: piece of code. You can compile different pieces of code at different
11459: @code{assert-level}s (e.g., a trusted library at level 1 and
11460: newly-written code at level 3).
1.26 crook 11461:
11462:
1.78 anton 11463: doc-assert-level
1.26 crook 11464:
11465:
1.78 anton 11466: If an assertion fails, a message compatible with Emacs' compilation mode
11467: is produced and the execution is aborted (currently with @code{ABORT"}.
11468: If there is interest, we will introduce a special throw code. But if you
11469: intend to @code{catch} a specific condition, using @code{throw} is
11470: probably more appropriate than an assertion).
1.106 anton 11471:
11472: @cindex filenames in assertion output
11473: Assertions (and @code{~~}) will usually print the wrong file name if a
11474: marker is executed in the same file after their occurance. They will
11475: print @samp{*somewhere*} as file name if a marker is executed in the
11476: same file before their occurance.
1.44 crook 11477:
1.78 anton 11478: Definitions in ANS Forth for these assertion words are provided
11479: in @file{compat/assert.fs}.
1.26 crook 11480:
1.44 crook 11481:
1.78 anton 11482: @node Singlestep Debugger, , Assertions, Programming Tools
11483: @subsection Singlestep Debugger
11484: @cindex singlestep Debugger
11485: @cindex debugging Singlestep
1.44 crook 11486:
1.112 anton 11487: The singlestep debugger does not work in this release.
11488:
1.78 anton 11489: When you create a new word there's often the need to check whether it
11490: behaves correctly or not. You can do this by typing @code{dbg
11491: badword}. A debug session might look like this:
1.26 crook 11492:
1.78 anton 11493: @example
11494: : badword 0 DO i . LOOP ; ok
11495: 2 dbg badword
11496: : badword
11497: Scanning code...
1.44 crook 11498:
1.78 anton 11499: Nesting debugger ready!
1.44 crook 11500:
1.78 anton 11501: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11502: 400D4740 8049F68 DO -> [ 0 ]
11503: 400D4744 804A0C8 i -> [ 1 ] 00000
11504: 400D4748 400C5E60 . -> 0 [ 0 ]
11505: 400D474C 8049D0C LOOP -> [ 0 ]
11506: 400D4744 804A0C8 i -> [ 1 ] 00001
11507: 400D4748 400C5E60 . -> 1 [ 0 ]
11508: 400D474C 8049D0C LOOP -> [ 0 ]
11509: 400D4758 804B384 ; -> ok
11510: @end example
1.21 crook 11511:
1.78 anton 11512: Each line displayed is one step. You always have to hit return to
11513: execute the next word that is displayed. If you don't want to execute
11514: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11515: an overview what keys are available:
1.44 crook 11516:
1.78 anton 11517: @table @i
1.44 crook 11518:
1.78 anton 11519: @item @key{RET}
11520: Next; Execute the next word.
1.21 crook 11521:
1.78 anton 11522: @item n
11523: Nest; Single step through next word.
1.44 crook 11524:
1.78 anton 11525: @item u
11526: Unnest; Stop debugging and execute rest of word. If we got to this word
11527: with nest, continue debugging with the calling word.
1.44 crook 11528:
1.78 anton 11529: @item d
11530: Done; Stop debugging and execute rest.
1.21 crook 11531:
1.78 anton 11532: @item s
11533: Stop; Abort immediately.
1.44 crook 11534:
1.78 anton 11535: @end table
1.44 crook 11536:
1.78 anton 11537: Debugging large application with this mechanism is very difficult, because
11538: you have to nest very deeply into the program before the interesting part
11539: begins. This takes a lot of time.
1.26 crook 11540:
1.78 anton 11541: To do it more directly put a @code{BREAK:} command into your source code.
11542: When program execution reaches @code{BREAK:} the single step debugger is
11543: invoked and you have all the features described above.
1.44 crook 11544:
1.78 anton 11545: If you have more than one part to debug it is useful to know where the
11546: program has stopped at the moment. You can do this by the
11547: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11548: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11549:
1.26 crook 11550:
1.78 anton 11551: doc-dbg
11552: doc-break:
11553: doc-break"
1.44 crook 11554:
11555:
1.26 crook 11556:
1.78 anton 11557: @c -------------------------------------------------------------
11558: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11559: @section Assembler and Code Words
11560: @cindex assembler
11561: @cindex code words
1.44 crook 11562:
1.78 anton 11563: @menu
11564: * Code and ;code::
11565: * Common Assembler:: Assembler Syntax
11566: * Common Disassembler::
11567: * 386 Assembler:: Deviations and special cases
11568: * Alpha Assembler:: Deviations and special cases
11569: * MIPS assembler:: Deviations and special cases
11570: * Other assemblers:: How to write them
11571: @end menu
1.21 crook 11572:
1.78 anton 11573: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11574: @subsection @code{Code} and @code{;code}
1.26 crook 11575:
1.78 anton 11576: Gforth provides some words for defining primitives (words written in
11577: machine code), and for defining the machine-code equivalent of
11578: @code{DOES>}-based defining words. However, the machine-independent
11579: nature of Gforth poses a few problems: First of all, Gforth runs on
11580: several architectures, so it can provide no standard assembler. What's
11581: worse is that the register allocation not only depends on the processor,
11582: but also on the @code{gcc} version and options used.
1.44 crook 11583:
1.78 anton 11584: The words that Gforth offers encapsulate some system dependences (e.g.,
11585: the header structure), so a system-independent assembler may be used in
11586: Gforth. If you do not have an assembler, you can compile machine code
11587: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11588: because these words emit stuff in @i{data} space; it works because
11589: Gforth has unified code/data spaces. Assembler isn't likely to be
11590: portable anyway.}.
1.21 crook 11591:
1.44 crook 11592:
1.78 anton 11593: doc-assembler
11594: doc-init-asm
11595: doc-code
11596: doc-end-code
11597: doc-;code
11598: doc-flush-icache
1.44 crook 11599:
1.21 crook 11600:
1.78 anton 11601: If @code{flush-icache} does not work correctly, @code{code} words
11602: etc. will not work (reliably), either.
1.44 crook 11603:
1.78 anton 11604: The typical usage of these @code{code} words can be shown most easily by
11605: analogy to the equivalent high-level defining words:
1.44 crook 11606:
1.78 anton 11607: @example
11608: : foo code foo
11609: <high-level Forth words> <assembler>
11610: ; end-code
11611:
11612: : bar : bar
11613: <high-level Forth words> <high-level Forth words>
11614: CREATE CREATE
11615: <high-level Forth words> <high-level Forth words>
11616: DOES> ;code
11617: <high-level Forth words> <assembler>
11618: ; end-code
11619: @end example
1.21 crook 11620:
1.78 anton 11621: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11622:
1.78 anton 11623: @cindex registers of the inner interpreter
11624: In the assembly code you will want to refer to the inner interpreter's
11625: registers (e.g., the data stack pointer) and you may want to use other
11626: registers for temporary storage. Unfortunately, the register allocation
11627: is installation-dependent.
1.44 crook 11628:
1.78 anton 11629: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11630: (return stack pointer) may be in different places in @code{gforth} and
11631: @code{gforth-fast}, or different installations. This means that you
11632: cannot write a @code{NEXT} routine that works reliably on both versions
11633: or different installations; so for doing @code{NEXT}, I recommend
11634: jumping to @code{' noop >code-address}, which contains nothing but a
11635: @code{NEXT}.
1.21 crook 11636:
1.78 anton 11637: For general accesses to the inner interpreter's registers, the easiest
11638: solution is to use explicit register declarations (@pxref{Explicit Reg
11639: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11640: all of the inner interpreter's registers: You have to compile Gforth
11641: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11642: the appropriate declarations must be present in the @code{machine.h}
11643: file (see @code{mips.h} for an example; you can find a full list of all
11644: declarable register symbols with @code{grep register engine.c}). If you
11645: give explicit registers to all variables that are declared at the
11646: beginning of @code{engine()}, you should be able to use the other
11647: caller-saved registers for temporary storage. Alternatively, you can use
11648: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11649: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11650: reserve a register (however, this restriction on register allocation may
11651: slow Gforth significantly).
1.44 crook 11652:
1.78 anton 11653: If this solution is not viable (e.g., because @code{gcc} does not allow
11654: you to explicitly declare all the registers you need), you have to find
11655: out by looking at the code where the inner interpreter's registers
11656: reside and which registers can be used for temporary storage. You can
11657: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11658:
1.78 anton 11659: In any case, it is good practice to abstract your assembly code from the
11660: actual register allocation. E.g., if the data stack pointer resides in
11661: register @code{$17}, create an alias for this register called @code{sp},
11662: and use that in your assembly code.
1.21 crook 11663:
1.78 anton 11664: @cindex code words, portable
11665: Another option for implementing normal and defining words efficiently
11666: is to add the desired functionality to the source of Gforth. For normal
11667: words you just have to edit @file{primitives} (@pxref{Automatic
11668: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11669: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11670: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11671:
1.78 anton 11672: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11673: @subsection Common Assembler
1.44 crook 11674:
1.78 anton 11675: The assemblers in Gforth generally use a postfix syntax, i.e., the
11676: instruction name follows the operands.
1.21 crook 11677:
1.78 anton 11678: The operands are passed in the usual order (the same that is used in the
11679: manual of the architecture). Since they all are Forth words, they have
11680: to be separated by spaces; you can also use Forth words to compute the
11681: operands.
1.44 crook 11682:
1.78 anton 11683: The instruction names usually end with a @code{,}. This makes it easier
11684: to visually separate instructions if you put several of them on one
11685: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11686:
1.78 anton 11687: Registers are usually specified by number; e.g., (decimal) @code{11}
11688: specifies registers R11 and F11 on the Alpha architecture (which one,
11689: depends on the instruction). The usual names are also available, e.g.,
11690: @code{s2} for R11 on Alpha.
1.21 crook 11691:
1.78 anton 11692: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11693: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11694: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11695: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11696: conditions are specified in a way specific to each assembler.
1.1 anton 11697:
1.78 anton 11698: Note that the register assignments of the Gforth engine can change
11699: between Gforth versions, or even between different compilations of the
11700: same Gforth version (e.g., if you use a different GCC version). So if
11701: you want to refer to Gforth's registers (e.g., the stack pointer or
11702: TOS), I recommend defining your own words for refering to these
11703: registers, and using them later on; then you can easily adapt to a
11704: changed register assignment. The stability of the register assignment
11705: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11706:
1.100 anton 11707: The most common use of these registers is to dispatch to the next word
11708: (the @code{next} routine). A portable way to do this is to jump to
11709: @code{' noop >code-address} (of course, this is less efficient than
11710: integrating the @code{next} code and scheduling it well).
1.1 anton 11711:
1.96 anton 11712: Another difference between Gforth version is that the top of stack is
11713: kept in memory in @code{gforth} and, on most platforms, in a register in
11714: @code{gforth-fast}.
11715:
1.78 anton 11716: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11717: @subsection Common Disassembler
1.127 anton 11718: @cindex disassembler, general
11719: @cindex gdb disassembler
1.1 anton 11720:
1.78 anton 11721: You can disassemble a @code{code} word with @code{see}
11722: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11723:
1.127 anton 11724: doc-discode
1.44 crook 11725:
1.127 anton 11726: There are two kinds of disassembler for Gforth: The Forth disassembler
11727: (available on some CPUs) and the gdb disassembler (available on
11728: platforms with @command{gdb} and @command{mktemp}). If both are
11729: available, the Forth disassembler is used by default. If you prefer
11730: the gdb disassembler, say
11731:
11732: @example
11733: ' disasm-gdb is discode
11734: @end example
11735:
11736: If neither is available, @code{discode} performs @code{dump}.
11737:
11738: The Forth disassembler generally produces output that can be fed into the
1.78 anton 11739: assembler (i.e., same syntax, etc.). It also includes additional
11740: information in comments. In particular, the address of the instruction
11741: is given in a comment before the instruction.
1.1 anton 11742:
1.127 anton 11743: The gdb disassembler produces output in the same format as the gdb
11744: @code{disassemble} command (@pxref{Machine Code,,Source and machine
11745: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
11746: the 386 and AMD64 architectures).
11747:
1.78 anton 11748: @code{See} may display more or less than the actual code of the word,
11749: because the recognition of the end of the code is unreliable. You can
1.127 anton 11750: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 11751: the code word is not immediately followed by a named word. If you have
1.116 anton 11752: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11753: to ensure that the end is recognized.
1.21 crook 11754:
1.78 anton 11755: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11756: @subsection 386 Assembler
1.44 crook 11757:
1.78 anton 11758: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11759: available under GPL, and originally part of bigFORTH.
1.21 crook 11760:
1.78 anton 11761: The 386 disassembler included in Gforth was written by Andrew McKewan
11762: and is in the public domain.
1.21 crook 11763:
1.91 anton 11764: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11765:
1.78 anton 11766: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11767:
1.78 anton 11768: The assembler includes all instruction of the Athlon, i.e. 486 core
11769: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11770: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11771: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11772:
1.78 anton 11773: There are several prefixes to switch between different operation sizes,
11774: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11775: double-word accesses. Addressing modes can be switched with @code{.wa}
11776: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11777: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11778:
1.78 anton 11779: For floating point operations, the prefixes are @code{.fs} (IEEE
11780: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11781: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11782:
1.78 anton 11783: The MMX opcodes don't have size prefixes, they are spelled out like in
11784: the Intel assembler. Instead of move from and to memory, there are
11785: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11786:
1.78 anton 11787: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11788: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11789: e.g., @code{3 #}. Here are some examples of addressing modes in various
11790: syntaxes:
1.21 crook 11791:
1.26 crook 11792: @example
1.91 anton 11793: Gforth Intel (NASM) AT&T (gas) Name
11794: .w ax ax %ax register (16 bit)
11795: ax eax %eax register (32 bit)
11796: 3 # offset 3 $3 immediate
11797: 1000 #) byte ptr 1000 1000 displacement
11798: bx ) [ebx] (%ebx) base
11799: 100 di d) 100[edi] 100(%edi) base+displacement
11800: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11801: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11802: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11803: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11804: @end example
11805:
11806: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11807: @code{DI)} to enforce 32-bit displacement fields (useful for
11808: later patching).
1.21 crook 11809:
1.78 anton 11810: Some example of instructions are:
1.1 anton 11811:
11812: @example
1.78 anton 11813: ax bx mov \ move ebx,eax
11814: 3 # ax mov \ mov eax,3
11815: 100 di ) ax mov \ mov eax,100[edi]
11816: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11817: .w ax bx mov \ mov bx,ax
1.1 anton 11818: @end example
11819:
1.78 anton 11820: The following forms are supported for binary instructions:
1.1 anton 11821:
11822: @example
1.78 anton 11823: <reg> <reg> <inst>
11824: <n> # <reg> <inst>
11825: <mem> <reg> <inst>
11826: <reg> <mem> <inst>
1.1 anton 11827: @end example
11828:
1.78 anton 11829: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11830:
1.26 crook 11831: @example
1.78 anton 11832: <reg/mem> 1 # shl \ shortens to shift without immediate
11833: <reg/mem> 4 # shl
11834: <reg/mem> cl shl
1.26 crook 11835: @end example
1.1 anton 11836:
1.78 anton 11837: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11838: the byte version.
1.1 anton 11839:
1.78 anton 11840: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11841: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11842: pc < >= <= >}. (Note that most of these words shadow some Forth words
11843: when @code{assembler} is in front of @code{forth} in the search path,
11844: e.g., in @code{code} words). Currently the control structure words use
11845: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11846: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11847:
1.78 anton 11848: Here is an example of a @code{code} word (assumes that the stack pointer
11849: is in esi and the TOS is in ebx):
1.21 crook 11850:
1.26 crook 11851: @example
1.78 anton 11852: code my+ ( n1 n2 -- n )
11853: 4 si D) bx add
11854: 4 # si add
11855: Next
11856: end-code
1.26 crook 11857: @end example
1.21 crook 11858:
1.78 anton 11859: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11860: @subsection Alpha Assembler
1.21 crook 11861:
1.78 anton 11862: The Alpha assembler and disassembler were originally written by Bernd
11863: Thallner.
1.26 crook 11864:
1.78 anton 11865: The register names @code{a0}--@code{a5} are not available to avoid
11866: shadowing hex numbers.
1.2 jwilke 11867:
1.78 anton 11868: Immediate forms of arithmetic instructions are distinguished by a
11869: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11870: does not count as arithmetic instruction).
1.2 jwilke 11871:
1.78 anton 11872: You have to specify all operands to an instruction, even those that
11873: other assemblers consider optional, e.g., the destination register for
11874: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11875:
1.78 anton 11876: You can specify conditions for @code{if,} by removing the first @code{b}
11877: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11878:
1.26 crook 11879: @example
1.78 anton 11880: 11 fgt if, \ if F11>0e
11881: ...
11882: endif,
1.26 crook 11883: @end example
1.2 jwilke 11884:
1.78 anton 11885: @code{fbgt,} gives @code{fgt}.
11886:
11887: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11888: @subsection MIPS assembler
1.2 jwilke 11889:
1.78 anton 11890: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11891:
1.78 anton 11892: Currently the assembler and disassembler only cover the MIPS-I
11893: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11894:
1.78 anton 11895: The register names @code{$a0}--@code{$a3} are not available to avoid
11896: shadowing hex numbers.
1.2 jwilke 11897:
1.78 anton 11898: Because there is no way to distinguish registers from immediate values,
11899: you have to explicitly use the immediate forms of instructions, i.e.,
11900: @code{addiu,}, not just @code{addu,} (@command{as} does this
11901: implicitly).
1.2 jwilke 11902:
1.78 anton 11903: If the architecture manual specifies several formats for the instruction
11904: (e.g., for @code{jalr,}), you usually have to use the one with more
11905: arguments (i.e., two for @code{jalr,}). When in doubt, see
11906: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11907:
1.78 anton 11908: Branches and jumps in the MIPS architecture have a delay slot. You have
11909: to fill it yourself (the simplest way is to use @code{nop,}), the
11910: assembler does not do it for you (unlike @command{as}). Even
11911: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11912: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11913: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11914:
1.78 anton 11915: Note that you must not put branches, jumps, or @code{li,} into the delay
11916: slot: @code{li,} may expand to several instructions, and control flow
11917: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11918:
1.78 anton 11919: For branches the argument specifying the target is a relative address;
11920: You have to add the address of the delay slot to get the absolute
11921: address.
1.1 anton 11922:
1.78 anton 11923: The MIPS architecture also has load delay slots and restrictions on
11924: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11925: yourself to satisfy these restrictions, the assembler does not do it for
11926: you.
1.1 anton 11927:
1.78 anton 11928: You can specify the conditions for @code{if,} etc. by taking a
11929: conditional branch and leaving away the @code{b} at the start and the
11930: @code{,} at the end. E.g.,
1.1 anton 11931:
1.26 crook 11932: @example
1.78 anton 11933: 4 5 eq if,
11934: ... \ do something if $4 equals $5
11935: then,
1.26 crook 11936: @end example
1.1 anton 11937:
1.78 anton 11938: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11939: @subsection Other assemblers
11940:
11941: If you want to contribute another assembler/disassembler, please contact
1.103 anton 11942: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11943: an assembler already. If you are writing them from scratch, please use
11944: a similar syntax style as the one we use (i.e., postfix, commas at the
11945: end of the instruction names, @pxref{Common Assembler}); make the output
11946: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 11947: similar to the style we used.
11948:
11949: Hints on implementation: The most important part is to have a good test
11950: suite that contains all instructions. Once you have that, the rest is
11951: easy. For actual coding you can take a look at
11952: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11953: the assembler and disassembler, avoiding redundancy and some potential
11954: bugs. You can also look at that file (and @pxref{Advanced does> usage
11955: example}) to get ideas how to factor a disassembler.
11956:
11957: Start with the disassembler, because it's easier to reuse data from the
11958: disassembler for the assembler than the other way round.
1.1 anton 11959:
1.78 anton 11960: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11961: how simple it can be.
1.1 anton 11962:
1.78 anton 11963: @c -------------------------------------------------------------
11964: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11965: @section Threading Words
11966: @cindex threading words
1.1 anton 11967:
1.78 anton 11968: @cindex code address
11969: These words provide access to code addresses and other threading stuff
11970: in Gforth (and, possibly, other interpretive Forths). It more or less
11971: abstracts away the differences between direct and indirect threading
11972: (and, for direct threading, the machine dependences). However, at
11973: present this wordset is still incomplete. It is also pretty low-level;
11974: some day it will hopefully be made unnecessary by an internals wordset
11975: that abstracts implementation details away completely.
1.1 anton 11976:
1.78 anton 11977: The terminology used here stems from indirect threaded Forth systems; in
11978: such a system, the XT of a word is represented by the CFA (code field
11979: address) of a word; the CFA points to a cell that contains the code
11980: address. The code address is the address of some machine code that
11981: performs the run-time action of invoking the word (e.g., the
11982: @code{dovar:} routine pushes the address of the body of the word (a
11983: variable) on the stack
11984: ).
1.1 anton 11985:
1.78 anton 11986: @cindex code address
11987: @cindex code field address
11988: In an indirect threaded Forth, you can get the code address of @i{name}
11989: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11990: >code-address}, independent of the threading method.
1.1 anton 11991:
1.78 anton 11992: doc-threading-method
11993: doc->code-address
11994: doc-code-address!
1.1 anton 11995:
1.78 anton 11996: @cindex @code{does>}-handler
11997: @cindex @code{does>}-code
11998: For a word defined with @code{DOES>}, the code address usually points to
11999: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12000: routine (in Gforth on some platforms, it can also point to the dodoes
12001: routine itself). What you are typically interested in, though, is
12002: whether a word is a @code{DOES>}-defined word, and what Forth code it
12003: executes; @code{>does-code} tells you that.
1.1 anton 12004:
1.78 anton 12005: doc->does-code
1.1 anton 12006:
1.78 anton 12007: To create a @code{DOES>}-defined word with the following basic words,
12008: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12009: @code{/does-handler} aus behind you have to place your executable Forth
12010: code. Finally you have to create a word and modify its behaviour with
12011: @code{does-handler!}.
1.1 anton 12012:
1.78 anton 12013: doc-does-code!
12014: doc-does-handler!
12015: doc-/does-handler
1.1 anton 12016:
1.78 anton 12017: The code addresses produced by various defining words are produced by
12018: the following words:
1.1 anton 12019:
1.78 anton 12020: doc-docol:
12021: doc-docon:
12022: doc-dovar:
12023: doc-douser:
12024: doc-dodefer:
12025: doc-dofield:
1.1 anton 12026:
1.99 anton 12027: @cindex definer
12028: The following two words generalize @code{>code-address},
12029: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12030:
12031: doc->definer
12032: doc-definer!
12033:
1.26 crook 12034: @c -------------------------------------------------------------
1.78 anton 12035: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12036: @section Passing Commands to the Operating System
12037: @cindex operating system - passing commands
12038: @cindex shell commands
12039:
12040: Gforth allows you to pass an arbitrary string to the host operating
12041: system shell (if such a thing exists) for execution.
12042:
1.44 crook 12043:
1.21 crook 12044: doc-sh
12045: doc-system
12046: doc-$?
1.23 crook 12047: doc-getenv
1.21 crook 12048:
1.44 crook 12049:
1.26 crook 12050: @c -------------------------------------------------------------
1.47 crook 12051: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12052: @section Keeping track of Time
12053: @cindex time-related words
12054:
12055: doc-ms
12056: doc-time&date
1.79 anton 12057: doc-utime
12058: doc-cputime
1.47 crook 12059:
12060:
12061: @c -------------------------------------------------------------
12062: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12063: @section Miscellaneous Words
12064: @cindex miscellaneous words
12065:
1.29 crook 12066: @comment TODO find homes for these
12067:
1.26 crook 12068: These section lists the ANS Forth words that are not documented
1.21 crook 12069: elsewhere in this manual. Ultimately, they all need proper homes.
12070:
1.68 anton 12071: doc-quit
1.44 crook 12072:
1.26 crook 12073: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12074: (@pxref{ANS conformance}):
1.21 crook 12075:
12076: @code{EDITOR}
12077: @code{EMIT?}
12078: @code{FORGET}
12079:
1.24 anton 12080: @c ******************************************************************
12081: @node Error messages, Tools, Words, Top
12082: @chapter Error messages
12083: @cindex error messages
12084: @cindex backtrace
12085:
12086: A typical Gforth error message looks like this:
12087:
12088: @example
1.86 anton 12089: in file included from \evaluated string/:-1
1.24 anton 12090: in file included from ./yyy.fs:1
12091: ./xxx.fs:4: Invalid memory address
12092: bar
12093: ^^^
1.79 anton 12094: Backtrace:
1.25 anton 12095: $400E664C @@
12096: $400E6664 foo
1.24 anton 12097: @end example
12098:
12099: The message identifying the error is @code{Invalid memory address}. The
12100: error happened when text-interpreting line 4 of the file
12101: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12102: word on the line where the error happened, is pointed out (with
12103: @code{^^^}).
12104:
12105: The file containing the error was included in line 1 of @file{./yyy.fs},
12106: and @file{yyy.fs} was included from a non-file (in this case, by giving
12107: @file{yyy.fs} as command-line parameter to Gforth).
12108:
12109: At the end of the error message you find a return stack dump that can be
12110: interpreted as a backtrace (possibly empty). On top you find the top of
12111: the return stack when the @code{throw} happened, and at the bottom you
12112: find the return stack entry just above the return stack of the topmost
12113: text interpreter.
12114:
12115: To the right of most return stack entries you see a guess for the word
12116: that pushed that return stack entry as its return address. This gives a
12117: backtrace. In our case we see that @code{bar} called @code{foo}, and
12118: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12119: address} exception).
12120:
12121: Note that the backtrace is not perfect: We don't know which return stack
12122: entries are return addresses (so we may get false positives); and in
12123: some cases (e.g., for @code{abort"}) we cannot determine from the return
12124: address the word that pushed the return address, so for some return
12125: addresses you see no names in the return stack dump.
1.25 anton 12126:
12127: @cindex @code{catch} and backtraces
12128: The return stack dump represents the return stack at the time when a
12129: specific @code{throw} was executed. In programs that make use of
12130: @code{catch}, it is not necessarily clear which @code{throw} should be
12131: used for the return stack dump (e.g., consider one @code{throw} that
12132: indicates an error, which is caught, and during recovery another error
1.42 anton 12133: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12134: presents the return stack dump for the first @code{throw} after the last
12135: executed (not returned-to) @code{catch}; this works well in the usual
12136: case.
12137:
12138: @cindex @code{gforth-fast} and backtraces
12139: @cindex @code{gforth-fast}, difference from @code{gforth}
12140: @cindex backtraces with @code{gforth-fast}
12141: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12142: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12143: from primitives (e.g., invalid memory address, stack empty etc.);
12144: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12145: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12146: exception caused by a primitive in @code{gforth-fast}, you will
12147: typically see no return stack dump at all; however, if the exception is
12148: caught by @code{catch} (e.g., for restoring some state), and then
12149: @code{throw}n again, the return stack dump will be for the first such
12150: @code{throw}.
1.2 jwilke 12151:
1.5 anton 12152: @c ******************************************************************
1.24 anton 12153: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12154: @chapter Tools
12155:
12156: @menu
12157: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12158: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12159: @end menu
12160:
12161: See also @ref{Emacs and Gforth}.
12162:
1.126 pazsan 12163: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12164: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12165: @cindex @file{ans-report.fs}
12166: @cindex report the words used in your program
12167: @cindex words used in your program
12168:
12169: If you want to label a Forth program as ANS Forth Program, you must
12170: document which wordsets the program uses; for extension wordsets, it is
12171: helpful to list the words the program requires from these wordsets
12172: (because Forth systems are allowed to provide only some words of them).
12173:
12174: The @file{ans-report.fs} tool makes it easy for you to determine which
12175: words from which wordset and which non-ANS words your application
12176: uses. You simply have to include @file{ans-report.fs} before loading the
12177: program you want to check. After loading your program, you can get the
12178: report with @code{print-ans-report}. A typical use is to run this as
12179: batch job like this:
12180: @example
12181: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12182: @end example
12183:
12184: The output looks like this (for @file{compat/control.fs}):
12185: @example
12186: The program uses the following words
12187: from CORE :
12188: : POSTPONE THEN ; immediate ?dup IF 0=
12189: from BLOCK-EXT :
12190: \
12191: from FILE :
12192: (
12193: @end example
12194:
12195: @subsection Caveats
12196:
12197: Note that @file{ans-report.fs} just checks which words are used, not whether
12198: they are used in an ANS Forth conforming way!
12199:
12200: Some words are defined in several wordsets in the
12201: standard. @file{ans-report.fs} reports them for only one of the
12202: wordsets, and not necessarily the one you expect. It depends on usage
12203: which wordset is the right one to specify. E.g., if you only use the
12204: compilation semantics of @code{S"}, it is a Core word; if you also use
12205: its interpretation semantics, it is a File word.
1.124 anton 12206:
12207:
1.127 anton 12208: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12209: @section Stack depth changes during interpretation
12210: @cindex @file{depth-changes.fs}
12211: @cindex depth changes during interpretation
12212: @cindex stack depth changes during interpretation
12213: @cindex items on the stack after interpretation
12214:
12215: Sometimes you notice that, after loading a file, there are items left
12216: on the stack. The tool @file{depth-changes.fs} helps you find out
12217: quickly where in the file these stack items are coming from.
12218:
12219: The simplest way of using @file{depth-changes.fs} is to include it
12220: before the file(s) you want to check, e.g.:
12221:
12222: @example
12223: gforth depth-changes.fs my-file.fs
12224: @end example
12225:
12226: This will compare the stack depths of the data and FP stack at every
12227: empty line (in interpretation state) against these depths at the last
12228: empty line (in interpretation state). If the depths are not equal,
12229: the position in the file and the stack contents are printed with
12230: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12231: change has occured in the paragraph of non-empty lines before the
12232: indicated line. It is a good idea to leave an empty line at the end
12233: of the file, so the last paragraph is checked, too.
12234:
12235: Checking only at empty lines usually works well, but sometimes you
12236: have big blocks of non-empty lines (e.g., when building a big table),
12237: and you want to know where in this block the stack depth changed. You
12238: can check all interpreted lines with
12239:
12240: @example
12241: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12242: @end example
12243:
12244: This checks the stack depth at every end-of-line. So the depth change
12245: occured in the line reported by the @code{~~} (not in the line
12246: before).
12247:
12248: Note that, while this offers better accuracy in indicating where the
12249: stack depth changes, it will often report many intentional stack depth
12250: changes (e.g., when an interpreted computation stretches across
12251: several lines). You can suppress the checking of some lines by
12252: putting backslashes at the end of these lines (not followed by white
12253: space), and using
12254:
12255: @example
12256: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12257: @end example
1.1 anton 12258:
12259: @c ******************************************************************
1.65 anton 12260: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12261: @chapter ANS conformance
12262: @cindex ANS conformance of Gforth
12263:
12264: To the best of our knowledge, Gforth is an
12265:
12266: ANS Forth System
12267: @itemize @bullet
12268: @item providing the Core Extensions word set
12269: @item providing the Block word set
12270: @item providing the Block Extensions word set
12271: @item providing the Double-Number word set
12272: @item providing the Double-Number Extensions word set
12273: @item providing the Exception word set
12274: @item providing the Exception Extensions word set
12275: @item providing the Facility word set
1.40 anton 12276: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12277: @item providing the File Access word set
12278: @item providing the File Access Extensions word set
12279: @item providing the Floating-Point word set
12280: @item providing the Floating-Point Extensions word set
12281: @item providing the Locals word set
12282: @item providing the Locals Extensions word set
12283: @item providing the Memory-Allocation word set
12284: @item providing the Memory-Allocation Extensions word set (that one's easy)
12285: @item providing the Programming-Tools word set
12286: @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
12287: @item providing the Search-Order word set
12288: @item providing the Search-Order Extensions word set
12289: @item providing the String word set
12290: @item providing the String Extensions word set (another easy one)
12291: @end itemize
12292:
1.118 anton 12293: Gforth has the following environmental restrictions:
12294:
12295: @cindex environmental restrictions
12296: @itemize @bullet
12297: @item
12298: While processing the OS command line, if an exception is not caught,
12299: Gforth exits with a non-zero exit code instyead of performing QUIT.
12300:
12301: @item
12302: When an @code{throw} is performed after a @code{query}, Gforth does not
12303: allways restore the input source specification in effect at the
12304: corresponding catch.
12305:
12306: @end itemize
12307:
12308:
1.1 anton 12309: @cindex system documentation
12310: In addition, ANS Forth systems are required to document certain
12311: implementation choices. This chapter tries to meet these
12312: requirements. In many cases it gives a way to ask the system for the
12313: information instead of providing the information directly, in
12314: particular, if the information depends on the processor, the operating
12315: system or the installation options chosen, or if they are likely to
12316: change during the maintenance of Gforth.
12317:
12318: @comment The framework for the rest has been taken from pfe.
12319:
12320: @menu
12321: * The Core Words::
12322: * The optional Block word set::
12323: * The optional Double Number word set::
12324: * The optional Exception word set::
12325: * The optional Facility word set::
12326: * The optional File-Access word set::
12327: * The optional Floating-Point word set::
12328: * The optional Locals word set::
12329: * The optional Memory-Allocation word set::
12330: * The optional Programming-Tools word set::
12331: * The optional Search-Order word set::
12332: @end menu
12333:
12334:
12335: @c =====================================================================
12336: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12337: @comment node-name, next, previous, up
12338: @section The Core Words
12339: @c =====================================================================
12340: @cindex core words, system documentation
12341: @cindex system documentation, core words
12342:
12343: @menu
12344: * core-idef:: Implementation Defined Options
12345: * core-ambcond:: Ambiguous Conditions
12346: * core-other:: Other System Documentation
12347: @end menu
12348:
12349: @c ---------------------------------------------------------------------
12350: @node core-idef, core-ambcond, The Core Words, The Core Words
12351: @subsection Implementation Defined Options
12352: @c ---------------------------------------------------------------------
12353: @cindex core words, implementation-defined options
12354: @cindex implementation-defined options, core words
12355:
12356:
12357: @table @i
12358: @item (Cell) aligned addresses:
12359: @cindex cell-aligned addresses
12360: @cindex aligned addresses
12361: processor-dependent. Gforth's alignment words perform natural alignment
12362: (e.g., an address aligned for a datum of size 8 is divisible by
12363: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12364:
12365: @item @code{EMIT} and non-graphic characters:
12366: @cindex @code{EMIT} and non-graphic characters
12367: @cindex non-graphic characters and @code{EMIT}
12368: The character is output using the C library function (actually, macro)
12369: @code{putc}.
12370:
12371: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12372: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12373: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12374: @cindex @code{ACCEPT}, editing
12375: @cindex @code{EXPECT}, editing
12376: This is modeled on the GNU readline library (@pxref{Readline
12377: Interaction, , Command Line Editing, readline, The GNU Readline
12378: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12379: producing a full word completion every time you type it (instead of
1.28 crook 12380: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12381:
12382: @item character set:
12383: @cindex character set
12384: The character set of your computer and display device. Gforth is
12385: 8-bit-clean (but some other component in your system may make trouble).
12386:
12387: @item Character-aligned address requirements:
12388: @cindex character-aligned address requirements
12389: installation-dependent. Currently a character is represented by a C
12390: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12391: (Comments on that requested).
12392:
12393: @item character-set extensions and matching of names:
12394: @cindex character-set extensions and matching of names
1.26 crook 12395: @cindex case-sensitivity for name lookup
12396: @cindex name lookup, case-sensitivity
12397: @cindex locale and case-sensitivity
1.21 crook 12398: Any character except the ASCII NUL character can be used in a
1.1 anton 12399: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12400: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12401: function is probably influenced by the locale. E.g., the @code{C} locale
12402: does not know about accents and umlauts, so they are matched
12403: case-sensitively in that locale. For portability reasons it is best to
12404: write programs such that they work in the @code{C} locale. Then one can
12405: use libraries written by a Polish programmer (who might use words
12406: containing ISO Latin-2 encoded characters) and by a French programmer
12407: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12408: funny results for some of the words (which ones, depends on the font you
12409: are using)). Also, the locale you prefer may not be available in other
12410: operating systems. Hopefully, Unicode will solve these problems one day.
12411:
12412: @item conditions under which control characters match a space delimiter:
12413: @cindex space delimiters
12414: @cindex control characters as delimiters
1.117 anton 12415: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12416: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12417: are delimiters. @code{Parse}, on the other hand, treats space like other
12418: delimiters. @code{Parse-word}, which is used by the outer
1.1 anton 12419: interpreter (aka text interpreter) by default, treats all white-space
12420: characters as delimiters.
12421:
1.26 crook 12422: @item format of the control-flow stack:
12423: @cindex control-flow stack, format
12424: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12425: stack item in cells is given by the constant @code{cs-item-size}. At the
12426: time of this writing, an item consists of a (pointer to a) locals list
12427: (third), an address in the code (second), and a tag for identifying the
12428: item (TOS). The following tags are used: @code{defstart},
12429: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12430: @code{scopestart}.
12431:
12432: @item conversion of digits > 35
12433: @cindex digits > 35
12434: The characters @code{[\]^_'} are the digits with the decimal value
12435: 36@minus{}41. There is no way to input many of the larger digits.
12436:
12437: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12438: @cindex @code{EXPECT}, display after end of input
12439: @cindex @code{ACCEPT}, display after end of input
12440: The cursor is moved to the end of the entered string. If the input is
12441: terminated using the @kbd{Return} key, a space is typed.
12442:
12443: @item exception abort sequence of @code{ABORT"}:
12444: @cindex exception abort sequence of @code{ABORT"}
12445: @cindex @code{ABORT"}, exception abort sequence
12446: The error string is stored into the variable @code{"error} and a
12447: @code{-2 throw} is performed.
12448:
12449: @item input line terminator:
12450: @cindex input line terminator
12451: @cindex line terminator on input
1.26 crook 12452: @cindex newline character on input
1.1 anton 12453: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12454: lines. One of these characters is typically produced when you type the
12455: @kbd{Enter} or @kbd{Return} key.
12456:
12457: @item maximum size of a counted string:
12458: @cindex maximum size of a counted string
12459: @cindex counted string, maximum size
12460: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12461: on all platforms, but this may change.
1.1 anton 12462:
12463: @item maximum size of a parsed string:
12464: @cindex maximum size of a parsed string
12465: @cindex parsed string, maximum size
12466: Given by the constant @code{/line}. Currently 255 characters.
12467:
12468: @item maximum size of a definition name, in characters:
12469: @cindex maximum size of a definition name, in characters
12470: @cindex name, maximum length
1.113 anton 12471: MAXU/8
1.1 anton 12472:
12473: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12474: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12475: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12476: MAXU/8
1.1 anton 12477:
12478: @item method of selecting the user input device:
12479: @cindex user input device, method of selecting
12480: The user input device is the standard input. There is currently no way to
12481: change it from within Gforth. However, the input can typically be
12482: redirected in the command line that starts Gforth.
12483:
12484: @item method of selecting the user output device:
12485: @cindex user output device, method of selecting
12486: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12487: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12488: output when the user output device is a terminal, otherwise the output
12489: is buffered.
1.1 anton 12490:
12491: @item methods of dictionary compilation:
12492: What are we expected to document here?
12493:
12494: @item number of bits in one address unit:
12495: @cindex number of bits in one address unit
12496: @cindex address unit, size in bits
12497: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12498: platforms.
1.1 anton 12499:
12500: @item number representation and arithmetic:
12501: @cindex number representation and arithmetic
1.79 anton 12502: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12503:
12504: @item ranges for integer types:
12505: @cindex ranges for integer types
12506: @cindex integer types, ranges
12507: Installation-dependent. Make environmental queries for @code{MAX-N},
12508: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12509: unsigned (and positive) types is 0. The lower bound for signed types on
12510: two's complement and one's complement machines machines can be computed
12511: by adding 1 to the upper bound.
12512:
12513: @item read-only data space regions:
12514: @cindex read-only data space regions
12515: @cindex data-space, read-only regions
12516: The whole Forth data space is writable.
12517:
12518: @item size of buffer at @code{WORD}:
12519: @cindex size of buffer at @code{WORD}
12520: @cindex @code{WORD} buffer size
12521: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12522: shared with the pictured numeric output string. If overwriting
12523: @code{PAD} is acceptable, it is as large as the remaining dictionary
12524: space, although only as much can be sensibly used as fits in a counted
12525: string.
12526:
12527: @item size of one cell in address units:
12528: @cindex cell size
12529: @code{1 cells .}.
12530:
12531: @item size of one character in address units:
12532: @cindex char size
1.79 anton 12533: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12534:
12535: @item size of the keyboard terminal buffer:
12536: @cindex size of the keyboard terminal buffer
12537: @cindex terminal buffer, size
12538: Varies. You can determine the size at a specific time using @code{lp@@
12539: tib - .}. It is shared with the locals stack and TIBs of files that
12540: include the current file. You can change the amount of space for TIBs
12541: and locals stack at Gforth startup with the command line option
12542: @code{-l}.
12543:
12544: @item size of the pictured numeric output buffer:
12545: @cindex size of the pictured numeric output buffer
12546: @cindex pictured numeric output buffer, size
12547: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12548: shared with @code{WORD}.
12549:
12550: @item size of the scratch area returned by @code{PAD}:
12551: @cindex size of the scratch area returned by @code{PAD}
12552: @cindex @code{PAD} size
12553: The remainder of dictionary space. @code{unused pad here - - .}.
12554:
12555: @item system case-sensitivity characteristics:
12556: @cindex case-sensitivity characteristics
1.26 crook 12557: Dictionary searches are case-insensitive (except in
1.1 anton 12558: @code{TABLE}s). However, as explained above under @i{character-set
12559: extensions}, the matching for non-ASCII characters is determined by the
12560: locale you are using. In the default @code{C} locale all non-ASCII
12561: characters are matched case-sensitively.
12562:
12563: @item system prompt:
12564: @cindex system prompt
12565: @cindex prompt
12566: @code{ ok} in interpret state, @code{ compiled} in compile state.
12567:
12568: @item division rounding:
12569: @cindex division rounding
12570: installation dependent. @code{s" floored" environment? drop .}. We leave
12571: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12572: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12573:
12574: @item values of @code{STATE} when true:
12575: @cindex @code{STATE} values
12576: -1.
12577:
12578: @item values returned after arithmetic overflow:
12579: On two's complement machines, arithmetic is performed modulo
12580: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12581: arithmetic (with appropriate mapping for signed types). Division by zero
12582: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12583: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12584:
12585: @item whether the current definition can be found after @t{DOES>}:
12586: @cindex @t{DOES>}, visibility of current definition
12587: No.
12588:
12589: @end table
12590:
12591: @c ---------------------------------------------------------------------
12592: @node core-ambcond, core-other, core-idef, The Core Words
12593: @subsection Ambiguous conditions
12594: @c ---------------------------------------------------------------------
12595: @cindex core words, ambiguous conditions
12596: @cindex ambiguous conditions, core words
12597:
12598: @table @i
12599:
12600: @item a name is neither a word nor a number:
12601: @cindex name not found
1.26 crook 12602: @cindex undefined word
1.80 anton 12603: @code{-13 throw} (Undefined word).
1.1 anton 12604:
12605: @item a definition name exceeds the maximum length allowed:
1.26 crook 12606: @cindex word name too long
1.1 anton 12607: @code{-19 throw} (Word name too long)
12608:
12609: @item addressing a region not inside the various data spaces of the forth system:
12610: @cindex Invalid memory address
1.32 anton 12611: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12612: typically readable. Accessing other addresses gives results dependent on
12613: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12614: address).
12615:
12616: @item argument type incompatible with parameter:
1.26 crook 12617: @cindex argument type mismatch
1.1 anton 12618: This is usually not caught. Some words perform checks, e.g., the control
12619: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12620: mismatch).
12621:
12622: @item attempting to obtain the execution token of a word with undefined execution semantics:
12623: @cindex Interpreting a compile-only word, for @code{'} etc.
12624: @cindex execution token of words with undefined execution semantics
12625: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12626: get an execution token for @code{compile-only-error} (which performs a
12627: @code{-14 throw} when executed).
12628:
12629: @item dividing by zero:
12630: @cindex dividing by zero
12631: @cindex floating point unidentified fault, integer division
1.80 anton 12632: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12633: zero); on other systems, this typically results in a @code{-55 throw}
12634: (Floating-point unidentified fault).
1.1 anton 12635:
12636: @item insufficient data stack or return stack space:
12637: @cindex insufficient data stack or return stack space
12638: @cindex stack overflow
1.26 crook 12639: @cindex address alignment exception, stack overflow
1.1 anton 12640: @cindex Invalid memory address, stack overflow
12641: Depending on the operating system, the installation, and the invocation
12642: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12643: it is not checked. If it is checked, you typically get a @code{-3 throw}
12644: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12645: throw} (Invalid memory address) (depending on the platform and how you
12646: achieved the overflow) as soon as the overflow happens. If it is not
12647: checked, overflows typically result in mysterious illegal memory
12648: accesses, producing @code{-9 throw} (Invalid memory address) or
12649: @code{-23 throw} (Address alignment exception); they might also destroy
12650: the internal data structure of @code{ALLOCATE} and friends, resulting in
12651: various errors in these words.
1.1 anton 12652:
12653: @item insufficient space for loop control parameters:
12654: @cindex insufficient space for loop control parameters
1.80 anton 12655: Like other return stack overflows.
1.1 anton 12656:
12657: @item insufficient space in the dictionary:
12658: @cindex insufficient space in the dictionary
12659: @cindex dictionary overflow
1.12 anton 12660: If you try to allot (either directly with @code{allot}, or indirectly
12661: with @code{,}, @code{create} etc.) more memory than available in the
12662: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12663: to access memory beyond the end of the dictionary, the results are
12664: similar to stack overflows.
1.1 anton 12665:
12666: @item interpreting a word with undefined interpretation semantics:
12667: @cindex interpreting a word with undefined interpretation semantics
12668: @cindex Interpreting a compile-only word
12669: For some words, we have defined interpretation semantics. For the
12670: others: @code{-14 throw} (Interpreting a compile-only word).
12671:
12672: @item modifying the contents of the input buffer or a string literal:
12673: @cindex modifying the contents of the input buffer or a string literal
12674: These are located in writable memory and can be modified.
12675:
12676: @item overflow of the pictured numeric output string:
12677: @cindex overflow of the pictured numeric output string
12678: @cindex pictured numeric output string, overflow
1.24 anton 12679: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12680:
12681: @item parsed string overflow:
12682: @cindex parsed string overflow
12683: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12684:
12685: @item producing a result out of range:
12686: @cindex result out of range
12687: On two's complement machines, arithmetic is performed modulo
12688: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12689: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12690: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12691: throw} (floating point unidentified fault). @code{convert} and
12692: @code{>number} currently overflow silently.
1.1 anton 12693:
12694: @item reading from an empty data or return stack:
12695: @cindex stack empty
12696: @cindex stack underflow
1.24 anton 12697: @cindex return stack underflow
1.1 anton 12698: The data stack is checked by the outer (aka text) interpreter after
12699: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12700: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12701: depending on operating system, installation, and invocation. If they are
12702: caught by a check, they typically result in @code{-4 throw} (Stack
12703: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12704: (Invalid memory address), depending on the platform and which stack
12705: underflows and by how much. Note that even if the system uses checking
12706: (through the MMU), your program may have to underflow by a significant
12707: number of stack items to trigger the reaction (the reason for this is
12708: that the MMU, and therefore the checking, works with a page-size
12709: granularity). If there is no checking, the symptoms resulting from an
12710: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12711: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12712: (Invalid memory address) and Illegal Instruction (typically @code{-260
12713: throw}).
1.1 anton 12714:
12715: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12716: @cindex unexpected end of the input buffer
12717: @cindex zero-length string as a name
12718: @cindex Attempt to use zero-length string as a name
12719: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12720: use zero-length string as a name). Words like @code{'} probably will not
12721: find what they search. Note that it is possible to create zero-length
12722: names with @code{nextname} (should it not?).
12723:
12724: @item @code{>IN} greater than input buffer:
12725: @cindex @code{>IN} greater than input buffer
12726: The next invocation of a parsing word returns a string with length 0.
12727:
12728: @item @code{RECURSE} appears after @code{DOES>}:
12729: @cindex @code{RECURSE} appears after @code{DOES>}
12730: Compiles a recursive call to the defining word, not to the defined word.
12731:
12732: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12733: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12734: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12735: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12736: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12737: the end of the file was reached), its source-id may be
12738: reused. Therefore, restoring an input source specification referencing a
12739: closed file may lead to unpredictable results instead of a @code{-12
12740: THROW}.
12741:
12742: In the future, Gforth may be able to restore input source specifications
12743: from other than the current input source.
12744:
12745: @item data space containing definitions gets de-allocated:
12746: @cindex data space containing definitions gets de-allocated
12747: Deallocation with @code{allot} is not checked. This typically results in
12748: memory access faults or execution of illegal instructions.
12749:
12750: @item data space read/write with incorrect alignment:
12751: @cindex data space read/write with incorrect alignment
12752: @cindex alignment faults
1.26 crook 12753: @cindex address alignment exception
1.1 anton 12754: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12755: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12756: alignment turned on, incorrect alignment results in a @code{-9 throw}
12757: (Invalid memory address). There are reportedly some processors with
1.12 anton 12758: alignment restrictions that do not report violations.
1.1 anton 12759:
12760: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12761: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12762: Like other alignment errors.
12763:
12764: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12765: Like other stack underflows.
12766:
12767: @item loop control parameters not available:
12768: @cindex loop control parameters not available
12769: Not checked. The counted loop words simply assume that the top of return
12770: stack items are loop control parameters and behave accordingly.
12771:
12772: @item most recent definition does not have a name (@code{IMMEDIATE}):
12773: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12774: @cindex last word was headerless
12775: @code{abort" last word was headerless"}.
12776:
12777: @item name not defined by @code{VALUE} used by @code{TO}:
12778: @cindex name not defined by @code{VALUE} used by @code{TO}
12779: @cindex @code{TO} on non-@code{VALUE}s
12780: @cindex Invalid name argument, @code{TO}
12781: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12782: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12783:
12784: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12785: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12786: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12787: @code{-13 throw} (Undefined word)
12788:
12789: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12790: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12791: Gforth behaves as if they were of the same type. I.e., you can predict
12792: the behaviour by interpreting all parameters as, e.g., signed.
12793:
12794: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12795: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12796: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12797: compilation semantics of @code{TO}.
12798:
12799: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12800: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12801: @cindex @code{WORD}, string overflow
12802: Not checked. The string will be ok, but the count will, of course,
12803: contain only the least significant bits of the length.
12804:
12805: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12806: @cindex @code{LSHIFT}, large shift counts
12807: @cindex @code{RSHIFT}, large shift counts
12808: Processor-dependent. Typical behaviours are returning 0 and using only
12809: the low bits of the shift count.
12810:
12811: @item word not defined via @code{CREATE}:
12812: @cindex @code{>BODY} of non-@code{CREATE}d words
12813: @code{>BODY} produces the PFA of the word no matter how it was defined.
12814:
12815: @cindex @code{DOES>} of non-@code{CREATE}d words
12816: @code{DOES>} changes the execution semantics of the last defined word no
12817: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12818: @code{CREATE , DOES>}.
12819:
12820: @item words improperly used outside @code{<#} and @code{#>}:
12821: Not checked. As usual, you can expect memory faults.
12822:
12823: @end table
12824:
12825:
12826: @c ---------------------------------------------------------------------
12827: @node core-other, , core-ambcond, The Core Words
12828: @subsection Other system documentation
12829: @c ---------------------------------------------------------------------
12830: @cindex other system documentation, core words
12831: @cindex core words, other system documentation
12832:
12833: @table @i
12834: @item nonstandard words using @code{PAD}:
12835: @cindex @code{PAD} use by nonstandard words
12836: None.
12837:
12838: @item operator's terminal facilities available:
12839: @cindex operator's terminal facilities available
1.80 anton 12840: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12841: and you can give commands to Gforth interactively. The actual facilities
12842: available depend on how you invoke Gforth.
12843:
12844: @item program data space available:
12845: @cindex program data space available
12846: @cindex data space available
12847: @code{UNUSED .} gives the remaining dictionary space. The total
12848: dictionary space can be specified with the @code{-m} switch
12849: (@pxref{Invoking Gforth}) when Gforth starts up.
12850:
12851: @item return stack space available:
12852: @cindex return stack space available
12853: You can compute the total return stack space in cells with
12854: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12855: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12856:
12857: @item stack space available:
12858: @cindex stack space available
12859: You can compute the total data stack space in cells with
12860: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12861: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12862:
12863: @item system dictionary space required, in address units:
12864: @cindex system dictionary space required, in address units
12865: Type @code{here forthstart - .} after startup. At the time of this
12866: writing, this gives 80080 (bytes) on a 32-bit system.
12867: @end table
12868:
12869:
12870: @c =====================================================================
12871: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12872: @section The optional Block word set
12873: @c =====================================================================
12874: @cindex system documentation, block words
12875: @cindex block words, system documentation
12876:
12877: @menu
12878: * block-idef:: Implementation Defined Options
12879: * block-ambcond:: Ambiguous Conditions
12880: * block-other:: Other System Documentation
12881: @end menu
12882:
12883:
12884: @c ---------------------------------------------------------------------
12885: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12886: @subsection Implementation Defined Options
12887: @c ---------------------------------------------------------------------
12888: @cindex implementation-defined options, block words
12889: @cindex block words, implementation-defined options
12890:
12891: @table @i
12892: @item the format for display by @code{LIST}:
12893: @cindex @code{LIST} display format
12894: First the screen number is displayed, then 16 lines of 64 characters,
12895: each line preceded by the line number.
12896:
12897: @item the length of a line affected by @code{\}:
12898: @cindex length of a line affected by @code{\}
12899: @cindex @code{\}, line length in blocks
12900: 64 characters.
12901: @end table
12902:
12903:
12904: @c ---------------------------------------------------------------------
12905: @node block-ambcond, block-other, block-idef, The optional Block word set
12906: @subsection Ambiguous conditions
12907: @c ---------------------------------------------------------------------
12908: @cindex block words, ambiguous conditions
12909: @cindex ambiguous conditions, block words
12910:
12911: @table @i
12912: @item correct block read was not possible:
12913: @cindex block read not possible
12914: Typically results in a @code{throw} of some OS-derived value (between
12915: -512 and -2048). If the blocks file was just not long enough, blanks are
12916: supplied for the missing portion.
12917:
12918: @item I/O exception in block transfer:
12919: @cindex I/O exception in block transfer
12920: @cindex block transfer, I/O exception
12921: Typically results in a @code{throw} of some OS-derived value (between
12922: -512 and -2048).
12923:
12924: @item invalid block number:
12925: @cindex invalid block number
12926: @cindex block number invalid
12927: @code{-35 throw} (Invalid block number)
12928:
12929: @item a program directly alters the contents of @code{BLK}:
12930: @cindex @code{BLK}, altering @code{BLK}
12931: The input stream is switched to that other block, at the same
12932: position. If the storing to @code{BLK} happens when interpreting
12933: non-block input, the system will get quite confused when the block ends.
12934:
12935: @item no current block buffer for @code{UPDATE}:
12936: @cindex @code{UPDATE}, no current block buffer
12937: @code{UPDATE} has no effect.
12938:
12939: @end table
12940:
12941: @c ---------------------------------------------------------------------
12942: @node block-other, , block-ambcond, The optional Block word set
12943: @subsection Other system documentation
12944: @c ---------------------------------------------------------------------
12945: @cindex other system documentation, block words
12946: @cindex block words, other system documentation
12947:
12948: @table @i
12949: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12950: No restrictions (yet).
12951:
12952: @item the number of blocks available for source and data:
12953: depends on your disk space.
12954:
12955: @end table
12956:
12957:
12958: @c =====================================================================
12959: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12960: @section The optional Double Number word set
12961: @c =====================================================================
12962: @cindex system documentation, double words
12963: @cindex double words, system documentation
12964:
12965: @menu
12966: * double-ambcond:: Ambiguous Conditions
12967: @end menu
12968:
12969:
12970: @c ---------------------------------------------------------------------
12971: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12972: @subsection Ambiguous conditions
12973: @c ---------------------------------------------------------------------
12974: @cindex double words, ambiguous conditions
12975: @cindex ambiguous conditions, double words
12976:
12977: @table @i
1.29 crook 12978: @item @i{d} outside of range of @i{n} in @code{D>S}:
12979: @cindex @code{D>S}, @i{d} out of range of @i{n}
12980: The least significant cell of @i{d} is produced.
1.1 anton 12981:
12982: @end table
12983:
12984:
12985: @c =====================================================================
12986: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12987: @section The optional Exception word set
12988: @c =====================================================================
12989: @cindex system documentation, exception words
12990: @cindex exception words, system documentation
12991:
12992: @menu
12993: * exception-idef:: Implementation Defined Options
12994: @end menu
12995:
12996:
12997: @c ---------------------------------------------------------------------
12998: @node exception-idef, , The optional Exception word set, The optional Exception word set
12999: @subsection Implementation Defined Options
13000: @c ---------------------------------------------------------------------
13001: @cindex implementation-defined options, exception words
13002: @cindex exception words, implementation-defined options
13003:
13004: @table @i
13005: @item @code{THROW}-codes used in the system:
13006: @cindex @code{THROW}-codes used in the system
13007: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13008: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13009: codes -512@minus{}-2047 are used for OS errors (for file and memory
13010: allocation operations). The mapping from OS error numbers to throw codes
13011: is -512@minus{}@code{errno}. One side effect of this mapping is that
13012: undefined OS errors produce a message with a strange number; e.g.,
13013: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13014: @end table
13015:
13016: @c =====================================================================
13017: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13018: @section The optional Facility word set
13019: @c =====================================================================
13020: @cindex system documentation, facility words
13021: @cindex facility words, system documentation
13022:
13023: @menu
13024: * facility-idef:: Implementation Defined Options
13025: * facility-ambcond:: Ambiguous Conditions
13026: @end menu
13027:
13028:
13029: @c ---------------------------------------------------------------------
13030: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13031: @subsection Implementation Defined Options
13032: @c ---------------------------------------------------------------------
13033: @cindex implementation-defined options, facility words
13034: @cindex facility words, implementation-defined options
13035:
13036: @table @i
13037: @item encoding of keyboard events (@code{EKEY}):
13038: @cindex keyboard events, encoding in @code{EKEY}
13039: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13040: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13041: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13042: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13043: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13044: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13045:
1.1 anton 13046:
13047: @item duration of a system clock tick:
13048: @cindex duration of a system clock tick
13049: @cindex clock tick duration
13050: System dependent. With respect to @code{MS}, the time is specified in
13051: microseconds. How well the OS and the hardware implement this, is
13052: another question.
13053:
13054: @item repeatability to be expected from the execution of @code{MS}:
13055: @cindex repeatability to be expected from the execution of @code{MS}
13056: @cindex @code{MS}, repeatability to be expected
13057: System dependent. On Unix, a lot depends on load. If the system is
13058: lightly loaded, and the delay is short enough that Gforth does not get
13059: swapped out, the performance should be acceptable. Under MS-DOS and
13060: other single-tasking systems, it should be good.
13061:
13062: @end table
13063:
13064:
13065: @c ---------------------------------------------------------------------
13066: @node facility-ambcond, , facility-idef, The optional Facility word set
13067: @subsection Ambiguous conditions
13068: @c ---------------------------------------------------------------------
13069: @cindex facility words, ambiguous conditions
13070: @cindex ambiguous conditions, facility words
13071:
13072: @table @i
13073: @item @code{AT-XY} can't be performed on user output device:
13074: @cindex @code{AT-XY} can't be performed on user output device
13075: Largely terminal dependent. No range checks are done on the arguments.
13076: No errors are reported. You may see some garbage appearing, you may see
13077: simply nothing happen.
13078:
13079: @end table
13080:
13081:
13082: @c =====================================================================
13083: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13084: @section The optional File-Access word set
13085: @c =====================================================================
13086: @cindex system documentation, file words
13087: @cindex file words, system documentation
13088:
13089: @menu
13090: * file-idef:: Implementation Defined Options
13091: * file-ambcond:: Ambiguous Conditions
13092: @end menu
13093:
13094: @c ---------------------------------------------------------------------
13095: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13096: @subsection Implementation Defined Options
13097: @c ---------------------------------------------------------------------
13098: @cindex implementation-defined options, file words
13099: @cindex file words, implementation-defined options
13100:
13101: @table @i
13102: @item file access methods used:
13103: @cindex file access methods used
13104: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13105: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13106: @code{wb}): The file is cleared, if it exists, and created, if it does
13107: not (with both @code{open-file} and @code{create-file}). Under Unix
13108: @code{create-file} creates a file with 666 permissions modified by your
13109: umask.
13110:
13111: @item file exceptions:
13112: @cindex file exceptions
13113: The file words do not raise exceptions (except, perhaps, memory access
13114: faults when you pass illegal addresses or file-ids).
13115:
13116: @item file line terminator:
13117: @cindex file line terminator
13118: System-dependent. Gforth uses C's newline character as line
13119: terminator. What the actual character code(s) of this are is
13120: system-dependent.
13121:
13122: @item file name format:
13123: @cindex file name format
13124: System dependent. Gforth just uses the file name format of your OS.
13125:
13126: @item information returned by @code{FILE-STATUS}:
13127: @cindex @code{FILE-STATUS}, returned information
13128: @code{FILE-STATUS} returns the most powerful file access mode allowed
13129: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13130: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13131: along with the returned mode.
13132:
13133: @item input file state after an exception when including source:
13134: @cindex exception when including source
13135: All files that are left via the exception are closed.
13136:
1.29 crook 13137: @item @i{ior} values and meaning:
13138: @cindex @i{ior} values and meaning
1.68 anton 13139: @cindex @i{wior} values and meaning
1.29 crook 13140: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13141: intended as throw codes. They typically are in the range
13142: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13143: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13144:
13145: @item maximum depth of file input nesting:
13146: @cindex maximum depth of file input nesting
13147: @cindex file input nesting, maximum depth
13148: limited by the amount of return stack, locals/TIB stack, and the number
13149: of open files available. This should not give you troubles.
13150:
13151: @item maximum size of input line:
13152: @cindex maximum size of input line
13153: @cindex input line size, maximum
13154: @code{/line}. Currently 255.
13155:
13156: @item methods of mapping block ranges to files:
13157: @cindex mapping block ranges to files
13158: @cindex files containing blocks
13159: @cindex blocks in files
13160: By default, blocks are accessed in the file @file{blocks.fb} in the
13161: current working directory. The file can be switched with @code{USE}.
13162:
13163: @item number of string buffers provided by @code{S"}:
13164: @cindex @code{S"}, number of string buffers
13165: 1
13166:
13167: @item size of string buffer used by @code{S"}:
13168: @cindex @code{S"}, size of string buffer
13169: @code{/line}. currently 255.
13170:
13171: @end table
13172:
13173: @c ---------------------------------------------------------------------
13174: @node file-ambcond, , file-idef, The optional File-Access word set
13175: @subsection Ambiguous conditions
13176: @c ---------------------------------------------------------------------
13177: @cindex file words, ambiguous conditions
13178: @cindex ambiguous conditions, file words
13179:
13180: @table @i
13181: @item attempting to position a file outside its boundaries:
13182: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13183: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13184: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13185:
13186: @item attempting to read from file positions not yet written:
13187: @cindex reading from file positions not yet written
13188: End-of-file, i.e., zero characters are read and no error is reported.
13189:
1.29 crook 13190: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13191: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13192: An appropriate exception may be thrown, but a memory fault or other
13193: problem is more probable.
13194:
1.29 crook 13195: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13196: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13197: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13198: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13199: thrown.
13200:
13201: @item named file cannot be opened (@code{INCLUDED}):
13202: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13203: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13204:
13205: @item requesting an unmapped block number:
13206: @cindex unmapped block numbers
13207: There are no unmapped legal block numbers. On some operating systems,
13208: writing a block with a large number may overflow the file system and
13209: have an error message as consequence.
13210:
13211: @item using @code{source-id} when @code{blk} is non-zero:
13212: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13213: @code{source-id} performs its function. Typically it will give the id of
13214: the source which loaded the block. (Better ideas?)
13215:
13216: @end table
13217:
13218:
13219: @c =====================================================================
13220: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13221: @section The optional Floating-Point word set
13222: @c =====================================================================
13223: @cindex system documentation, floating-point words
13224: @cindex floating-point words, system documentation
13225:
13226: @menu
13227: * floating-idef:: Implementation Defined Options
13228: * floating-ambcond:: Ambiguous Conditions
13229: @end menu
13230:
13231:
13232: @c ---------------------------------------------------------------------
13233: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13234: @subsection Implementation Defined Options
13235: @c ---------------------------------------------------------------------
13236: @cindex implementation-defined options, floating-point words
13237: @cindex floating-point words, implementation-defined options
13238:
13239: @table @i
13240: @item format and range of floating point numbers:
13241: @cindex format and range of floating point numbers
13242: @cindex floating point numbers, format and range
13243: System-dependent; the @code{double} type of C.
13244:
1.29 crook 13245: @item results of @code{REPRESENT} when @i{float} is out of range:
13246: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13247: System dependent; @code{REPRESENT} is implemented using the C library
13248: function @code{ecvt()} and inherits its behaviour in this respect.
13249:
13250: @item rounding or truncation of floating-point numbers:
13251: @cindex rounding of floating-point numbers
13252: @cindex truncation of floating-point numbers
13253: @cindex floating-point numbers, rounding or truncation
13254: System dependent; the rounding behaviour is inherited from the hosting C
13255: compiler. IEEE-FP-based (i.e., most) systems by default round to
13256: nearest, and break ties by rounding to even (i.e., such that the last
13257: bit of the mantissa is 0).
13258:
13259: @item size of floating-point stack:
13260: @cindex floating-point stack size
13261: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13262: the floating-point stack (in floats). You can specify this on startup
13263: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13264:
13265: @item width of floating-point stack:
13266: @cindex floating-point stack width
13267: @code{1 floats}.
13268:
13269: @end table
13270:
13271:
13272: @c ---------------------------------------------------------------------
13273: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13274: @subsection Ambiguous conditions
13275: @c ---------------------------------------------------------------------
13276: @cindex floating-point words, ambiguous conditions
13277: @cindex ambiguous conditions, floating-point words
13278:
13279: @table @i
13280: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13281: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13282: System-dependent. Typically results in a @code{-23 THROW} like other
13283: alignment violations.
13284:
13285: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13286: @cindex @code{f@@} used with an address that is not float aligned
13287: @cindex @code{f!} used with an address that is not float aligned
13288: System-dependent. Typically results in a @code{-23 THROW} like other
13289: alignment violations.
13290:
13291: @item floating-point result out of range:
13292: @cindex floating-point result out of range
1.80 anton 13293: System-dependent. Can result in a @code{-43 throw} (floating point
13294: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13295: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13296: unidentified fault), or can produce a special value representing, e.g.,
13297: Infinity.
13298:
13299: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13300: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13301: System-dependent. Typically results in an alignment fault like other
13302: alignment violations.
13303:
1.35 anton 13304: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13305: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13306: The floating-point number is converted into decimal nonetheless.
13307:
13308: @item Both arguments are equal to zero (@code{FATAN2}):
13309: @cindex @code{FATAN2}, both arguments are equal to zero
13310: System-dependent. @code{FATAN2} is implemented using the C library
13311: function @code{atan2()}.
13312:
1.29 crook 13313: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13314: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13315: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13316: because of small errors and the tan will be a very large (or very small)
13317: but finite number.
13318:
1.29 crook 13319: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13320: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13321: The result is rounded to the nearest float.
13322:
13323: @item dividing by zero:
13324: @cindex dividing by zero, floating-point
13325: @cindex floating-point dividing by zero
13326: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13327: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13328: (floating point divide by zero) or @code{-55 throw} (Floating-point
13329: unidentified fault).
1.1 anton 13330:
13331: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13332: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13333: System dependent. On IEEE-FP based systems the number is converted into
13334: an infinity.
13335:
1.29 crook 13336: @item @i{float}<1 (@code{FACOSH}):
13337: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13338: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13339: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13340:
1.29 crook 13341: @item @i{float}=<-1 (@code{FLNP1}):
13342: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13343: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13344: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13345: negative infinity for @i{float}=-1).
1.1 anton 13346:
1.29 crook 13347: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13348: @cindex @code{FLN}, @i{float}=<0
13349: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13350: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13351: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13352: negative infinity for @i{float}=0).
1.1 anton 13353:
1.29 crook 13354: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13355: @cindex @code{FASINH}, @i{float}<0
13356: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13357: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13358: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13359: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13360: C library?).
1.1 anton 13361:
1.29 crook 13362: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13363: @cindex @code{FACOS}, |@i{float}|>1
13364: @cindex @code{FASIN}, |@i{float}|>1
13365: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13366: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13367: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13368:
1.29 crook 13369: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13370: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13371: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13372: Platform-dependent; typically, some double number is produced and no
13373: error is reported.
1.1 anton 13374:
13375: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13376: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13377: @code{Precision} characters of the numeric output area are used. If
13378: @code{precision} is too high, these words will smash the data or code
13379: close to @code{here}.
1.1 anton 13380: @end table
13381:
13382: @c =====================================================================
13383: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13384: @section The optional Locals word set
13385: @c =====================================================================
13386: @cindex system documentation, locals words
13387: @cindex locals words, system documentation
13388:
13389: @menu
13390: * locals-idef:: Implementation Defined Options
13391: * locals-ambcond:: Ambiguous Conditions
13392: @end menu
13393:
13394:
13395: @c ---------------------------------------------------------------------
13396: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13397: @subsection Implementation Defined Options
13398: @c ---------------------------------------------------------------------
13399: @cindex implementation-defined options, locals words
13400: @cindex locals words, implementation-defined options
13401:
13402: @table @i
13403: @item maximum number of locals in a definition:
13404: @cindex maximum number of locals in a definition
13405: @cindex locals, maximum number in a definition
13406: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13407: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13408: characters. The number of locals in a definition is bounded by the size
13409: of locals-buffer, which contains the names of the locals.
13410:
13411: @end table
13412:
13413:
13414: @c ---------------------------------------------------------------------
13415: @node locals-ambcond, , locals-idef, The optional Locals word set
13416: @subsection Ambiguous conditions
13417: @c ---------------------------------------------------------------------
13418: @cindex locals words, ambiguous conditions
13419: @cindex ambiguous conditions, locals words
13420:
13421: @table @i
13422: @item executing a named local in interpretation state:
13423: @cindex local in interpretation state
13424: @cindex Interpreting a compile-only word, for a local
13425: Locals have no interpretation semantics. If you try to perform the
13426: interpretation semantics, you will get a @code{-14 throw} somewhere
13427: (Interpreting a compile-only word). If you perform the compilation
13428: semantics, the locals access will be compiled (irrespective of state).
13429:
1.29 crook 13430: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13431: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13432: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13433: @cindex Invalid name argument, @code{TO}
13434: @code{-32 throw} (Invalid name argument)
13435:
13436: @end table
13437:
13438:
13439: @c =====================================================================
13440: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13441: @section The optional Memory-Allocation word set
13442: @c =====================================================================
13443: @cindex system documentation, memory-allocation words
13444: @cindex memory-allocation words, system documentation
13445:
13446: @menu
13447: * memory-idef:: Implementation Defined Options
13448: @end menu
13449:
13450:
13451: @c ---------------------------------------------------------------------
13452: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13453: @subsection Implementation Defined Options
13454: @c ---------------------------------------------------------------------
13455: @cindex implementation-defined options, memory-allocation words
13456: @cindex memory-allocation words, implementation-defined options
13457:
13458: @table @i
1.29 crook 13459: @item values and meaning of @i{ior}:
13460: @cindex @i{ior} values and meaning
13461: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13462: intended as throw codes. They typically are in the range
13463: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13464: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13465:
13466: @end table
13467:
13468: @c =====================================================================
13469: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13470: @section The optional Programming-Tools word set
13471: @c =====================================================================
13472: @cindex system documentation, programming-tools words
13473: @cindex programming-tools words, system documentation
13474:
13475: @menu
13476: * programming-idef:: Implementation Defined Options
13477: * programming-ambcond:: Ambiguous Conditions
13478: @end menu
13479:
13480:
13481: @c ---------------------------------------------------------------------
13482: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13483: @subsection Implementation Defined Options
13484: @c ---------------------------------------------------------------------
13485: @cindex implementation-defined options, programming-tools words
13486: @cindex programming-tools words, implementation-defined options
13487:
13488: @table @i
13489: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13490: @cindex @code{;CODE} ending sequence
13491: @cindex @code{CODE} ending sequence
13492: @code{END-CODE}
13493:
13494: @item manner of processing input following @code{;CODE} and @code{CODE}:
13495: @cindex @code{;CODE}, processing input
13496: @cindex @code{CODE}, processing input
13497: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13498: the input is processed by the text interpreter, (starting) in interpret
13499: state.
13500:
13501: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13502: @cindex @code{ASSEMBLER}, search order capability
13503: The ANS Forth search order word set.
13504:
13505: @item source and format of display by @code{SEE}:
13506: @cindex @code{SEE}, source and format of output
1.80 anton 13507: The source for @code{see} is the executable code used by the inner
1.1 anton 13508: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13509: (and on some platforms, assembly code for primitives) as well as
13510: possible.
1.1 anton 13511:
13512: @end table
13513:
13514: @c ---------------------------------------------------------------------
13515: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13516: @subsection Ambiguous conditions
13517: @c ---------------------------------------------------------------------
13518: @cindex programming-tools words, ambiguous conditions
13519: @cindex ambiguous conditions, programming-tools words
13520:
13521: @table @i
13522:
1.21 crook 13523: @item deleting the compilation word list (@code{FORGET}):
13524: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13525: Not implemented (yet).
13526:
1.29 crook 13527: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13528: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13529: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13530: @cindex control-flow stack underflow
13531: This typically results in an @code{abort"} with a descriptive error
13532: message (may change into a @code{-22 throw} (Control structure mismatch)
13533: in the future). You may also get a memory access error. If you are
13534: unlucky, this ambiguous condition is not caught.
13535:
1.29 crook 13536: @item @i{name} can't be found (@code{FORGET}):
13537: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13538: Not implemented (yet).
13539:
1.29 crook 13540: @item @i{name} not defined via @code{CREATE}:
13541: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13542: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13543: the execution semantics of the last defined word no matter how it was
13544: defined.
13545:
13546: @item @code{POSTPONE} applied to @code{[IF]}:
13547: @cindex @code{POSTPONE} applied to @code{[IF]}
13548: @cindex @code{[IF]} and @code{POSTPONE}
13549: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13550: equivalent to @code{[IF]}.
13551:
13552: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13553: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13554: Continue in the same state of conditional compilation in the next outer
13555: input source. Currently there is no warning to the user about this.
13556:
13557: @item removing a needed definition (@code{FORGET}):
13558: @cindex @code{FORGET}, removing a needed definition
13559: Not implemented (yet).
13560:
13561: @end table
13562:
13563:
13564: @c =====================================================================
13565: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13566: @section The optional Search-Order word set
13567: @c =====================================================================
13568: @cindex system documentation, search-order words
13569: @cindex search-order words, system documentation
13570:
13571: @menu
13572: * search-idef:: Implementation Defined Options
13573: * search-ambcond:: Ambiguous Conditions
13574: @end menu
13575:
13576:
13577: @c ---------------------------------------------------------------------
13578: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13579: @subsection Implementation Defined Options
13580: @c ---------------------------------------------------------------------
13581: @cindex implementation-defined options, search-order words
13582: @cindex search-order words, implementation-defined options
13583:
13584: @table @i
13585: @item maximum number of word lists in search order:
13586: @cindex maximum number of word lists in search order
13587: @cindex search order, maximum depth
13588: @code{s" wordlists" environment? drop .}. Currently 16.
13589:
13590: @item minimum search order:
13591: @cindex minimum search order
13592: @cindex search order, minimum
13593: @code{root root}.
13594:
13595: @end table
13596:
13597: @c ---------------------------------------------------------------------
13598: @node search-ambcond, , search-idef, The optional Search-Order word set
13599: @subsection Ambiguous conditions
13600: @c ---------------------------------------------------------------------
13601: @cindex search-order words, ambiguous conditions
13602: @cindex ambiguous conditions, search-order words
13603:
13604: @table @i
1.21 crook 13605: @item changing the compilation word list (during compilation):
13606: @cindex changing the compilation word list (during compilation)
13607: @cindex compilation word list, change before definition ends
13608: The word is entered into the word list that was the compilation word list
1.1 anton 13609: at the start of the definition. Any changes to the name field (e.g.,
13610: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13611: are applied to the latest defined word (as reported by @code{latest} or
13612: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13613:
13614: @item search order empty (@code{previous}):
13615: @cindex @code{previous}, search order empty
1.26 crook 13616: @cindex vocstack empty, @code{previous}
1.1 anton 13617: @code{abort" Vocstack empty"}.
13618:
13619: @item too many word lists in search order (@code{also}):
13620: @cindex @code{also}, too many word lists in search order
1.26 crook 13621: @cindex vocstack full, @code{also}
1.1 anton 13622: @code{abort" Vocstack full"}.
13623:
13624: @end table
13625:
13626: @c ***************************************************************
1.65 anton 13627: @node Standard vs Extensions, Model, ANS conformance, Top
13628: @chapter Should I use Gforth extensions?
13629: @cindex Gforth extensions
13630:
13631: As you read through the rest of this manual, you will see documentation
13632: for @i{Standard} words, and documentation for some appealing Gforth
13633: @i{extensions}. You might ask yourself the question: @i{``Should I
13634: restrict myself to the standard, or should I use the extensions?''}
13635:
13636: The answer depends on the goals you have for the program you are working
13637: on:
13638:
13639: @itemize @bullet
13640:
13641: @item Is it just for yourself or do you want to share it with others?
13642:
13643: @item
13644: If you want to share it, do the others all use Gforth?
13645:
13646: @item
13647: If it is just for yourself, do you want to restrict yourself to Gforth?
13648:
13649: @end itemize
13650:
13651: If restricting the program to Gforth is ok, then there is no reason not
13652: to use extensions. It is still a good idea to keep to the standard
13653: where it is easy, in case you want to reuse these parts in another
13654: program that you want to be portable.
13655:
13656: If you want to be able to port the program to other Forth systems, there
13657: are the following points to consider:
13658:
13659: @itemize @bullet
13660:
13661: @item
13662: Most Forth systems that are being maintained support the ANS Forth
13663: standard. So if your program complies with the standard, it will be
13664: portable among many systems.
13665:
13666: @item
13667: A number of the Gforth extensions can be implemented in ANS Forth using
13668: public-domain files provided in the @file{compat/} directory. These are
13669: mentioned in the text in passing. There is no reason not to use these
13670: extensions, your program will still be ANS Forth compliant; just include
13671: the appropriate compat files with your program.
13672:
13673: @item
13674: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13675: analyse your program and determine what non-Standard words it relies
13676: upon. However, it does not check whether you use standard words in a
13677: non-standard way.
13678:
13679: @item
13680: Some techniques are not standardized by ANS Forth, and are hard or
13681: impossible to implement in a standard way, but can be implemented in
13682: most Forth systems easily, and usually in similar ways (e.g., accessing
13683: word headers). Forth has a rich historical precedent for programmers
13684: taking advantage of implementation-dependent features of their tools
13685: (for example, relying on a knowledge of the dictionary
13686: structure). Sometimes these techniques are necessary to extract every
13687: last bit of performance from the hardware, sometimes they are just a
13688: programming shorthand.
13689:
13690: @item
13691: Does using a Gforth extension save more work than the porting this part
13692: to other Forth systems (if any) will cost?
13693:
13694: @item
13695: Is the additional functionality worth the reduction in portability and
13696: the additional porting problems?
13697:
13698: @end itemize
13699:
13700: In order to perform these consideratios, you need to know what's
13701: standard and what's not. This manual generally states if something is
1.81 anton 13702: non-standard, but the authoritative source is the
13703: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13704: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13705: into the thought processes of the technical committee.
13706:
13707: Note also that portability between Forth systems is not the only
13708: portability issue; there is also the issue of portability between
13709: different platforms (processor/OS combinations).
13710:
13711: @c ***************************************************************
13712: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13713: @chapter Model
13714:
13715: This chapter has yet to be written. It will contain information, on
13716: which internal structures you can rely.
13717:
13718: @c ***************************************************************
13719: @node Integrating Gforth, Emacs and Gforth, Model, Top
13720: @chapter Integrating Gforth into C programs
13721:
13722: This is not yet implemented.
13723:
13724: Several people like to use Forth as scripting language for applications
13725: that are otherwise written in C, C++, or some other language.
13726:
13727: The Forth system ATLAST provides facilities for embedding it into
13728: applications; unfortunately it has several disadvantages: most
13729: importantly, it is not based on ANS Forth, and it is apparently dead
13730: (i.e., not developed further and not supported). The facilities
1.21 crook 13731: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13732: making the switch should not be hard.
13733:
13734: We also tried to design the interface such that it can easily be
13735: implemented by other Forth systems, so that we may one day arrive at a
13736: standardized interface. Such a standard interface would allow you to
13737: replace the Forth system without having to rewrite C code.
13738:
13739: You embed the Gforth interpreter by linking with the library
13740: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13741: global symbols in this library that belong to the interface, have the
13742: prefix @code{forth_}. (Global symbols that are used internally have the
13743: prefix @code{gforth_}).
13744:
13745: You can include the declarations of Forth types and the functions and
13746: variables of the interface with @code{#include <forth.h>}.
13747:
13748: Types.
13749:
13750: Variables.
13751:
13752: Data and FP Stack pointer. Area sizes.
13753:
13754: functions.
13755:
13756: forth_init(imagefile)
13757: forth_evaluate(string) exceptions?
13758: forth_goto(address) (or forth_execute(xt)?)
13759: forth_continue() (a corountining mechanism)
13760:
13761: Adding primitives.
13762:
13763: No checking.
13764:
13765: Signals?
13766:
13767: Accessing the Stacks
13768:
1.26 crook 13769: @c ******************************************************************
1.1 anton 13770: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13771: @chapter Emacs and Gforth
13772: @cindex Emacs and Gforth
13773:
13774: @cindex @file{gforth.el}
13775: @cindex @file{forth.el}
13776: @cindex Rydqvist, Goran
1.107 dvdkhlng 13777: @cindex Kuehling, David
1.1 anton 13778: @cindex comment editing commands
13779: @cindex @code{\}, editing with Emacs
13780: @cindex debug tracer editing commands
13781: @cindex @code{~~}, removal with Emacs
13782: @cindex Forth mode in Emacs
1.107 dvdkhlng 13783:
1.1 anton 13784: Gforth comes with @file{gforth.el}, an improved version of
13785: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13786: improvements are:
13787:
13788: @itemize @bullet
13789: @item
1.107 dvdkhlng 13790: A better handling of indentation.
13791: @item
13792: A custom hilighting engine for Forth-code.
1.26 crook 13793: @item
13794: Comment paragraph filling (@kbd{M-q})
13795: @item
13796: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13797: @item
13798: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13799: @item
13800: Support of the @code{info-lookup} feature for looking up the
13801: documentation of a word.
1.107 dvdkhlng 13802: @item
13803: Support for reading and writing blocks files.
1.26 crook 13804: @end itemize
13805:
1.107 dvdkhlng 13806: To get a basic description of these features, enter Forth mode and
13807: type @kbd{C-h m}.
1.1 anton 13808:
13809: @cindex source location of error or debugging output in Emacs
13810: @cindex error output, finding the source location in Emacs
13811: @cindex debugging output, finding the source location in Emacs
13812: In addition, Gforth supports Emacs quite well: The source code locations
13813: given in error messages, debugging output (from @code{~~}) and failed
13814: assertion messages are in the right format for Emacs' compilation mode
13815: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13816: Manual}) so the source location corresponding to an error or other
13817: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13818: @kbd{C-c C-c} for the error under the cursor).
13819:
1.107 dvdkhlng 13820: @cindex viewing the documentation of a word in Emacs
13821: @cindex context-sensitive help
13822: Moreover, for words documented in this manual, you can look up the
13823: glossary entry quickly by using @kbd{C-h TAB}
13824: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13825: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13826: later and does not work for words containing @code{:}.
13827:
13828: @menu
13829: * Installing gforth.el:: Making Emacs aware of Forth.
13830: * Emacs Tags:: Viewing the source of a word in Emacs.
13831: * Hilighting:: Making Forth code look prettier.
13832: * Auto-Indentation:: Customizing auto-indentation.
13833: * Blocks Files:: Reading and writing blocks files.
13834: @end menu
13835:
13836: @c ----------------------------------
1.109 anton 13837: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13838: @section Installing gforth.el
13839: @cindex @file{.emacs}
13840: @cindex @file{gforth.el}, installation
13841: To make the features from @file{gforth.el} available in Emacs, add
13842: the following lines to your @file{.emacs} file:
13843:
13844: @example
13845: (autoload 'forth-mode "gforth.el")
13846: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13847: auto-mode-alist))
13848: (autoload 'forth-block-mode "gforth.el")
13849: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13850: auto-mode-alist))
13851: (add-hook 'forth-mode-hook (function (lambda ()
13852: ;; customize variables here:
13853: (setq forth-indent-level 4)
13854: (setq forth-minor-indent-level 2)
13855: (setq forth-hilight-level 3)
13856: ;;; ...
13857: )))
13858: @end example
13859:
13860: @c ----------------------------------
13861: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13862: @section Emacs Tags
1.1 anton 13863: @cindex @file{TAGS} file
13864: @cindex @file{etags.fs}
13865: @cindex viewing the source of a word in Emacs
1.43 anton 13866: @cindex @code{require}, placement in files
13867: @cindex @code{include}, placement in files
1.107 dvdkhlng 13868: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13869: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13870: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13871: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13872: several tags files at the same time (e.g., one for the Gforth sources
13873: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13874: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13875: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13876: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13877: with @file{etags.fs}, you should avoid putting definitions both before
13878: and after @code{require} etc., otherwise you will see the same file
13879: visited several times by commands like @code{tags-search}.
1.1 anton 13880:
1.107 dvdkhlng 13881: @c ----------------------------------
13882: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13883: @section Hilighting
13884: @cindex hilighting Forth code in Emacs
13885: @cindex highlighting Forth code in Emacs
13886: @file{gforth.el} comes with a custom source hilighting engine. When
13887: you open a file in @code{forth-mode}, it will be completely parsed,
13888: assigning faces to keywords, comments, strings etc. While you edit
13889: the file, modified regions get parsed and updated on-the-fly.
13890:
13891: Use the variable `forth-hilight-level' to change the level of
13892: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13893: you set the hilighting level to 0, the parser will still work in the
13894: background, collecting information about whether regions of text are
13895: ``compiled'' or ``interpreted''. Those information are required for
13896: auto-indentation to work properly. Set `forth-disable-parser' to
13897: non-nil if your computer is too slow to handle parsing. This will
13898: have an impact on the smartness of the auto-indentation engine,
13899: though.
13900:
13901: Sometimes Forth sources define new features that should be hilighted,
13902: new control structures, defining-words etc. You can use the variable
13903: `forth-custom-words' to make @code{forth-mode} hilight additional
13904: words and constructs. See the docstring of `forth-words' for details
13905: (in Emacs, type @kbd{C-h v forth-words}).
13906:
13907: `forth-custom-words' is meant to be customized in your
13908: @file{.emacs} file. To customize hilighing in a file-specific manner,
13909: set `forth-local-words' in a local-variables section at the end of
13910: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13911:
13912: Example:
13913: @example
13914: 0 [IF]
13915: Local Variables:
13916: forth-local-words:
13917: ((("t:") definition-starter (font-lock-keyword-face . 1)
13918: "[ \t\n]" t name (font-lock-function-name-face . 3))
13919: ((";t") definition-ender (font-lock-keyword-face . 1)))
13920: End:
13921: [THEN]
13922: @end example
13923:
13924: @c ----------------------------------
13925: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13926: @section Auto-Indentation
13927: @cindex auto-indentation of Forth code in Emacs
13928: @cindex indentation of Forth code in Emacs
13929: @code{forth-mode} automatically tries to indent lines in a smart way,
13930: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13931:
13932: Simple customization can be achieved by setting
13933: `forth-indent-level' and `forth-minor-indent-level' in your
13934: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13935: per default by multiples of 4 columns. To use the more traditional
13936: 3-column indentation, add the following lines to your @file{.emacs}:
13937:
13938: @example
13939: (add-hook 'forth-mode-hook (function (lambda ()
13940: ;; customize variables here:
13941: (setq forth-indent-level 3)
13942: (setq forth-minor-indent-level 1)
13943: )))
13944: @end example
13945:
13946: If you want indentation to recognize non-default words, customize it
13947: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
13948: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13949: v forth-indent-words}).
13950:
13951: To customize indentation in a file-specific manner, set
13952: `forth-local-indent-words' in a local-variables section at the end of
13953: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13954: Emacs Manual}).
13955:
13956: Example:
13957: @example
13958: 0 [IF]
13959: Local Variables:
13960: forth-local-indent-words:
13961: ((("t:") (0 . 2) (0 . 2))
13962: ((";t") (-2 . 0) (0 . -2)))
13963: End:
13964: [THEN]
13965: @end example
13966:
13967: @c ----------------------------------
1.109 anton 13968: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 13969: @section Blocks Files
13970: @cindex blocks files, use with Emacs
13971: @code{forth-mode} Autodetects blocks files by checking whether the
13972: length of the first line exceeds 1023 characters. It then tries to
13973: convert the file into normal text format. When you save the file, it
13974: will be written to disk as normal stream-source file.
13975:
13976: If you want to write blocks files, use @code{forth-blocks-mode}. It
13977: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 13978:
1.107 dvdkhlng 13979: @itemize @bullet
13980: @item
13981: Files are written to disk in blocks file format.
13982: @item
13983: Screen numbers are displayed in the mode line (enumerated beginning
13984: with the value of `forth-block-base')
13985: @item
13986: Warnings are displayed when lines exceed 64 characters.
13987: @item
13988: The beginning of the currently edited block is marked with an
13989: overlay-arrow.
13990: @end itemize
1.41 anton 13991:
1.107 dvdkhlng 13992: There are some restrictions you should be aware of. When you open a
13993: blocks file that contains tabulator or newline characters, these
13994: characters will be translated into spaces when the file is written
13995: back to disk. If tabs or newlines are encountered during blocks file
13996: reading, an error is output to the echo area. So have a look at the
13997: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 13998:
1.107 dvdkhlng 13999: Please consult the docstring of @code{forth-blocks-mode} for more
14000: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14001:
1.26 crook 14002: @c ******************************************************************
1.1 anton 14003: @node Image Files, Engine, Emacs and Gforth, Top
14004: @chapter Image Files
1.26 crook 14005: @cindex image file
14006: @cindex @file{.fi} files
1.1 anton 14007: @cindex precompiled Forth code
14008: @cindex dictionary in persistent form
14009: @cindex persistent form of dictionary
14010:
14011: An image file is a file containing an image of the Forth dictionary,
14012: i.e., compiled Forth code and data residing in the dictionary. By
14013: convention, we use the extension @code{.fi} for image files.
14014:
14015: @menu
1.18 anton 14016: * Image Licensing Issues:: Distribution terms for images.
14017: * Image File Background:: Why have image files?
1.67 anton 14018: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14019: * Data-Relocatable Image Files:: are better.
1.67 anton 14020: * Fully Relocatable Image Files:: better yet.
1.18 anton 14021: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14022: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14023: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14024: @end menu
14025:
1.18 anton 14026: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14027: @section Image Licensing Issues
14028: @cindex license for images
14029: @cindex image license
14030:
14031: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14032: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14033: original image; i.e., according to copyright law it is a derived work of
14034: the original image.
14035:
14036: Since Gforth is distributed under the GNU GPL, the newly created image
14037: falls under the GNU GPL, too. In particular, this means that if you
14038: distribute the image, you have to make all of the sources for the image
1.113 anton 14039: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14040: GNU General Public License (Section 3)}.
14041:
14042: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14043: contains only code compiled from the sources you gave it; if none of
14044: these sources is under the GPL, the terms discussed above do not apply
14045: to the image. However, if your image needs an engine (a gforth binary)
14046: that is under the GPL, you should make sure that you distribute both in
14047: a way that is at most a @emph{mere aggregation}, if you don't want the
14048: terms of the GPL to apply to the image.
14049:
14050: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14051: @section Image File Background
14052: @cindex image file background
14053:
1.80 anton 14054: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14055: definitions written in Forth. Since the Forth compiler itself belongs to
14056: those definitions, it is not possible to start the system with the
1.80 anton 14057: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14058: code as an image file in nearly executable form. When Gforth starts up,
14059: a C routine loads the image file into memory, optionally relocates the
14060: addresses, then sets up the memory (stacks etc.) according to
14061: information in the image file, and (finally) starts executing Forth
14062: code.
1.1 anton 14063:
14064: The image file variants represent different compromises between the
14065: goals of making it easy to generate image files and making them
14066: portable.
14067:
14068: @cindex relocation at run-time
1.26 crook 14069: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14070: run-time. This avoids many of the complications discussed below (image
14071: files are data relocatable without further ado), but costs performance
14072: (one addition per memory access).
14073:
14074: @cindex relocation at load-time
1.26 crook 14075: By contrast, the Gforth loader performs relocation at image load time. The
14076: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14077: appropriate code-field addresses (or code addresses in the case of
14078: direct threading).
14079:
14080: There are three kinds of image files, with different degrees of
14081: relocatability: non-relocatable, data-relocatable, and fully relocatable
14082: image files.
14083:
14084: @cindex image file loader
14085: @cindex relocating loader
14086: @cindex loader for image files
14087: These image file variants have several restrictions in common; they are
14088: caused by the design of the image file loader:
14089:
14090: @itemize @bullet
14091: @item
14092: There is only one segment; in particular, this means, that an image file
14093: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14094: them). The contents of the stacks are not represented, either.
1.1 anton 14095:
14096: @item
14097: The only kinds of relocation supported are: adding the same offset to
14098: all cells that represent data addresses; and replacing special tokens
14099: with code addresses or with pieces of machine code.
14100:
14101: If any complex computations involving addresses are performed, the
14102: results cannot be represented in the image file. Several applications that
14103: use such computations come to mind:
14104: @itemize @minus
14105: @item
14106: Hashing addresses (or data structures which contain addresses) for table
14107: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14108: purpose, you will have no problem, because the hash tables are
14109: recomputed automatically when the system is started. If you use your own
14110: hash tables, you will have to do something similar.
14111:
14112: @item
14113: There's a cute implementation of doubly-linked lists that uses
14114: @code{XOR}ed addresses. You could represent such lists as singly-linked
14115: in the image file, and restore the doubly-linked representation on
14116: startup.@footnote{In my opinion, though, you should think thrice before
14117: using a doubly-linked list (whatever implementation).}
14118:
14119: @item
14120: The code addresses of run-time routines like @code{docol:} cannot be
14121: represented in the image file (because their tokens would be replaced by
14122: machine code in direct threaded implementations). As a workaround,
14123: compute these addresses at run-time with @code{>code-address} from the
14124: executions tokens of appropriate words (see the definitions of
1.80 anton 14125: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14126:
14127: @item
14128: On many architectures addresses are represented in machine code in some
14129: shifted or mangled form. You cannot put @code{CODE} words that contain
14130: absolute addresses in this form in a relocatable image file. Workarounds
14131: are representing the address in some relative form (e.g., relative to
14132: the CFA, which is present in some register), or loading the address from
14133: a place where it is stored in a non-mangled form.
14134: @end itemize
14135: @end itemize
14136:
14137: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14138: @section Non-Relocatable Image Files
14139: @cindex non-relocatable image files
1.26 crook 14140: @cindex image file, non-relocatable
1.1 anton 14141:
14142: These files are simple memory dumps of the dictionary. They are specific
14143: to the executable (i.e., @file{gforth} file) they were created
14144: with. What's worse, they are specific to the place on which the
14145: dictionary resided when the image was created. Now, there is no
14146: guarantee that the dictionary will reside at the same place the next
14147: time you start Gforth, so there's no guarantee that a non-relocatable
14148: image will work the next time (Gforth will complain instead of crashing,
14149: though).
14150:
14151: You can create a non-relocatable image file with
14152:
1.44 crook 14153:
1.1 anton 14154: doc-savesystem
14155:
1.44 crook 14156:
1.1 anton 14157: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14158: @section Data-Relocatable Image Files
14159: @cindex data-relocatable image files
1.26 crook 14160: @cindex image file, data-relocatable
1.1 anton 14161:
14162: These files contain relocatable data addresses, but fixed code addresses
14163: (instead of tokens). They are specific to the executable (i.e.,
14164: @file{gforth} file) they were created with. For direct threading on some
14165: architectures (e.g., the i386), data-relocatable images do not work. You
14166: get a data-relocatable image, if you use @file{gforthmi} with a
14167: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14168: Relocatable Image Files}).
14169:
14170: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14171: @section Fully Relocatable Image Files
14172: @cindex fully relocatable image files
1.26 crook 14173: @cindex image file, fully relocatable
1.1 anton 14174:
14175: @cindex @file{kern*.fi}, relocatability
14176: @cindex @file{gforth.fi}, relocatability
14177: These image files have relocatable data addresses, and tokens for code
14178: addresses. They can be used with different binaries (e.g., with and
14179: without debugging) on the same machine, and even across machines with
14180: the same data formats (byte order, cell size, floating point
14181: format). However, they are usually specific to the version of Gforth
14182: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14183: are fully relocatable.
14184:
14185: There are two ways to create a fully relocatable image file:
14186:
14187: @menu
1.29 crook 14188: * gforthmi:: The normal way
1.1 anton 14189: * cross.fs:: The hard way
14190: @end menu
14191:
14192: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14193: @subsection @file{gforthmi}
14194: @cindex @file{comp-i.fs}
14195: @cindex @file{gforthmi}
14196:
14197: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14198: image @i{file} that contains everything you would load by invoking
14199: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14200: @example
1.29 crook 14201: gforthmi @i{file} @i{options}
1.1 anton 14202: @end example
14203:
14204: E.g., if you want to create an image @file{asm.fi} that has the file
14205: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14206: like this:
14207:
14208: @example
14209: gforthmi asm.fi asm.fs
14210: @end example
14211:
1.27 crook 14212: @file{gforthmi} is implemented as a sh script and works like this: It
14213: produces two non-relocatable images for different addresses and then
14214: compares them. Its output reflects this: first you see the output (if
1.62 crook 14215: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14216: files, then you see the output of the comparing program: It displays the
14217: offset used for data addresses and the offset used for code addresses;
1.1 anton 14218: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14219: image files, it displays a line like this:
1.1 anton 14220:
14221: @example
14222: 78DC BFFFFA50 BFFFFA40
14223: @end example
14224:
14225: This means that at offset $78dc from @code{forthstart}, one input image
14226: contains $bffffa50, and the other contains $bffffa40. Since these cells
14227: cannot be represented correctly in the output image, you should examine
14228: these places in the dictionary and verify that these cells are dead
14229: (i.e., not read before they are written).
1.39 anton 14230:
14231: @cindex --application, @code{gforthmi} option
14232: If you insert the option @code{--application} in front of the image file
14233: name, you will get an image that uses the @code{--appl-image} option
14234: instead of the @code{--image-file} option (@pxref{Invoking
14235: Gforth}). When you execute such an image on Unix (by typing the image
14236: name as command), the Gforth engine will pass all options to the image
14237: instead of trying to interpret them as engine options.
1.1 anton 14238:
1.27 crook 14239: If you type @file{gforthmi} with no arguments, it prints some usage
14240: instructions.
14241:
1.1 anton 14242: @cindex @code{savesystem} during @file{gforthmi}
14243: @cindex @code{bye} during @file{gforthmi}
14244: @cindex doubly indirect threaded code
1.44 crook 14245: @cindex environment variables
14246: @cindex @code{GFORTHD} -- environment variable
14247: @cindex @code{GFORTH} -- environment variable
1.1 anton 14248: @cindex @code{gforth-ditc}
1.29 crook 14249: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14250: words @code{savesystem} and @code{bye} must be visible. A special doubly
14251: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14252: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14253: this executable through the environment variable @code{GFORTHD}
14254: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14255: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14256: data-relocatable image (because there is no code address offset). The
14257: normal @file{gforth} executable is used for creating the relocatable
14258: image; you can pass the exact filename of this executable through the
14259: environment variable @code{GFORTH}.
1.1 anton 14260:
14261: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14262: @subsection @file{cross.fs}
14263: @cindex @file{cross.fs}
14264: @cindex cross-compiler
14265: @cindex metacompiler
1.47 crook 14266: @cindex target compiler
1.1 anton 14267:
14268: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14269: programming language (@pxref{Cross Compiler}).
1.1 anton 14270:
1.47 crook 14271: @code{cross} allows you to create image files for machines with
1.1 anton 14272: different data sizes and data formats than the one used for generating
14273: the image file. You can also use it to create an application image that
14274: does not contain a Forth compiler. These features are bought with
14275: restrictions and inconveniences in programming. E.g., addresses have to
14276: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14277: order to make the code relocatable.
14278:
14279:
14280: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14281: @section Stack and Dictionary Sizes
14282: @cindex image file, stack and dictionary sizes
14283: @cindex dictionary size default
14284: @cindex stack size default
14285:
14286: If you invoke Gforth with a command line flag for the size
14287: (@pxref{Invoking Gforth}), the size you specify is stored in the
14288: dictionary. If you save the dictionary with @code{savesystem} or create
14289: an image with @file{gforthmi}, this size will become the default
14290: for the resulting image file. E.g., the following will create a
1.21 crook 14291: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14292:
14293: @example
14294: gforthmi gforth.fi -m 1M
14295: @end example
14296:
14297: In other words, if you want to set the default size for the dictionary
14298: and the stacks of an image, just invoke @file{gforthmi} with the
14299: appropriate options when creating the image.
14300:
14301: @cindex stack size, cache-friendly
14302: Note: For cache-friendly behaviour (i.e., good performance), you should
14303: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14304: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14305: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14306:
14307: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14308: @section Running Image Files
14309: @cindex running image files
14310: @cindex invoking image files
14311: @cindex image file invocation
14312:
14313: @cindex -i, invoke image file
14314: @cindex --image file, invoke image file
1.29 crook 14315: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14316: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14317: @example
1.29 crook 14318: gforth -i @i{image}
1.1 anton 14319: @end example
14320:
14321: @cindex executable image file
1.26 crook 14322: @cindex image file, executable
1.1 anton 14323: If your operating system supports starting scripts with a line of the
14324: form @code{#! ...}, you just have to type the image file name to start
14325: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14326: just a convention). I.e., to run Gforth with the image file @i{image},
14327: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14328: This works because every @code{.fi} file starts with a line of this
14329: format:
14330:
14331: @example
14332: #! /usr/local/bin/gforth-0.4.0 -i
14333: @end example
14334:
14335: The file and pathname for the Gforth engine specified on this line is
14336: the specific Gforth executable that it was built against; i.e. the value
14337: of the environment variable @code{GFORTH} at the time that
14338: @file{gforthmi} was executed.
1.1 anton 14339:
1.27 crook 14340: You can make use of the same shell capability to make a Forth source
14341: file into an executable. For example, if you place this text in a file:
1.26 crook 14342:
14343: @example
14344: #! /usr/local/bin/gforth
14345:
14346: ." Hello, world" CR
14347: bye
14348: @end example
14349:
14350: @noindent
1.27 crook 14351: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14352: directly from the command line. The sequence @code{#!} is used in two
14353: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14354: system@footnote{The Unix kernel actually recognises two types of files:
14355: executable files and files of data, where the data is processed by an
14356: interpreter that is specified on the ``interpreter line'' -- the first
14357: line of the file, starting with the sequence #!. There may be a small
14358: limit (e.g., 32) on the number of characters that may be specified on
14359: the interpreter line.} secondly it is treated as a comment character by
14360: Gforth. Because of the second usage, a space is required between
1.80 anton 14361: @code{#!} and the path to the executable (moreover, some Unixes
14362: require the sequence @code{#! /}).
1.27 crook 14363:
14364: The disadvantage of this latter technique, compared with using
1.80 anton 14365: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14366: compiled on-the-fly, each time the program is invoked.
1.26 crook 14367:
1.1 anton 14368: doc-#!
14369:
1.44 crook 14370:
1.1 anton 14371: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14372: @section Modifying the Startup Sequence
14373: @cindex startup sequence for image file
14374: @cindex image file initialization sequence
14375: @cindex initialization sequence of image file
14376:
1.120 anton 14377: You can add your own initialization to the startup sequence of an image
14378: through the deferred word @code{'cold}. @code{'cold} is invoked just
14379: before the image-specific command line processing (i.e., loading files
14380: and evaluating (@code{-e}) strings) starts.
1.1 anton 14381:
14382: A sequence for adding your initialization usually looks like this:
14383:
14384: @example
14385: :noname
14386: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14387: ... \ your stuff
14388: ; IS 'cold
14389: @end example
14390:
14391: @cindex turnkey image files
1.26 crook 14392: @cindex image file, turnkey applications
1.1 anton 14393: You can make a turnkey image by letting @code{'cold} execute a word
14394: (your turnkey application) that never returns; instead, it exits Gforth
14395: via @code{bye} or @code{throw}.
14396:
1.121 anton 14397: You can access the (image-specific) command-line arguments through
14398: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14399: arguments}).
1.1 anton 14400:
1.26 crook 14401: If @code{'cold} exits normally, Gforth processes the command-line
14402: arguments as files to be loaded and strings to be evaluated. Therefore,
14403: @code{'cold} should remove the arguments it has used in this case.
14404:
14405: doc-'cold
1.44 crook 14406:
1.1 anton 14407: @c ******************************************************************
1.113 anton 14408: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14409: @chapter Engine
14410: @cindex engine
14411: @cindex virtual machine
14412:
1.26 crook 14413: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14414: may be helpful for finding your way in the Gforth sources.
14415:
1.109 anton 14416: The ideas in this section have also been published in the following
14417: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14418: Forth-Tagung '93; M. Anton Ertl,
14419: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14420: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14421: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14422: Threaded code variations and optimizations (extended version)}},
14423: Forth-Tagung '02.
1.1 anton 14424:
14425: @menu
14426: * Portability::
14427: * Threading::
14428: * Primitives::
14429: * Performance::
14430: @end menu
14431:
14432: @node Portability, Threading, Engine, Engine
14433: @section Portability
14434: @cindex engine portability
14435:
1.26 crook 14436: An important goal of the Gforth Project is availability across a wide
14437: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14438: achieved this goal by manually coding the engine in assembly language
14439: for several then-popular processors. This approach is very
14440: labor-intensive and the results are short-lived due to progress in
14441: computer architecture.
1.1 anton 14442:
14443: @cindex C, using C for the engine
14444: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14445: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14446: particularly popular for UNIX-based Forths due to the large variety of
14447: architectures of UNIX machines. Unfortunately an implementation in C
14448: does not mix well with the goals of efficiency and with using
14449: traditional techniques: Indirect or direct threading cannot be expressed
14450: in C, and switch threading, the fastest technique available in C, is
14451: significantly slower. Another problem with C is that it is very
14452: cumbersome to express double integer arithmetic.
14453:
14454: @cindex GNU C for the engine
14455: @cindex long long
14456: Fortunately, there is a portable language that does not have these
14457: limitations: GNU C, the version of C processed by the GNU C compiler
14458: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14459: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14460: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14461: threading possible, its @code{long long} type (@pxref{Long Long, ,
14462: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14463: double numbers on many systems. GNU C is freely available on all
1.1 anton 14464: important (and many unimportant) UNIX machines, VMS, 80386s running
14465: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14466: on all these machines.
14467:
14468: Writing in a portable language has the reputation of producing code that
14469: is slower than assembly. For our Forth engine we repeatedly looked at
14470: the code produced by the compiler and eliminated most compiler-induced
14471: inefficiencies by appropriate changes in the source code.
14472:
14473: @cindex explicit register declarations
14474: @cindex --enable-force-reg, configuration flag
14475: @cindex -DFORCE_REG
14476: However, register allocation cannot be portably influenced by the
14477: programmer, leading to some inefficiencies on register-starved
14478: machines. We use explicit register declarations (@pxref{Explicit Reg
14479: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14480: improve the speed on some machines. They are turned on by using the
14481: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14482: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14483: machine, but also on the compiler version: On some machines some
14484: compiler versions produce incorrect code when certain explicit register
14485: declarations are used. So by default @code{-DFORCE_REG} is not used.
14486:
14487: @node Threading, Primitives, Portability, Engine
14488: @section Threading
14489: @cindex inner interpreter implementation
14490: @cindex threaded code implementation
14491:
14492: @cindex labels as values
14493: GNU C's labels as values extension (available since @code{gcc-2.0},
14494: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14495: makes it possible to take the address of @i{label} by writing
14496: @code{&&@i{label}}. This address can then be used in a statement like
14497: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14498: @code{goto x}.
14499:
1.26 crook 14500: @cindex @code{NEXT}, indirect threaded
1.1 anton 14501: @cindex indirect threaded inner interpreter
14502: @cindex inner interpreter, indirect threaded
1.26 crook 14503: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14504: @example
14505: cfa = *ip++;
14506: ca = *cfa;
14507: goto *ca;
14508: @end example
14509: @cindex instruction pointer
14510: For those unfamiliar with the names: @code{ip} is the Forth instruction
14511: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14512: execution token and points to the code field of the next word to be
14513: executed; The @code{ca} (code address) fetched from there points to some
14514: executable code, e.g., a primitive or the colon definition handler
14515: @code{docol}.
14516:
1.26 crook 14517: @cindex @code{NEXT}, direct threaded
1.1 anton 14518: @cindex direct threaded inner interpreter
14519: @cindex inner interpreter, direct threaded
14520: Direct threading is even simpler:
14521: @example
14522: ca = *ip++;
14523: goto *ca;
14524: @end example
14525:
14526: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14527: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14528:
14529: @menu
14530: * Scheduling::
14531: * Direct or Indirect Threaded?::
1.109 anton 14532: * Dynamic Superinstructions::
1.1 anton 14533: * DOES>::
14534: @end menu
14535:
14536: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14537: @subsection Scheduling
14538: @cindex inner interpreter optimization
14539:
14540: There is a little complication: Pipelined and superscalar processors,
14541: i.e., RISC and some modern CISC machines can process independent
14542: instructions while waiting for the results of an instruction. The
14543: compiler usually reorders (schedules) the instructions in a way that
14544: achieves good usage of these delay slots. However, on our first tries
14545: the compiler did not do well on scheduling primitives. E.g., for
14546: @code{+} implemented as
14547: @example
14548: n=sp[0]+sp[1];
14549: sp++;
14550: sp[0]=n;
14551: NEXT;
14552: @end example
1.81 anton 14553: the @code{NEXT} comes strictly after the other code, i.e., there is
14554: nearly no scheduling. After a little thought the problem becomes clear:
14555: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14556: addresses (and the version of @code{gcc} we used would not know it even
14557: if it was possible), so it could not move the load of the cfa above the
14558: store to the TOS. Indeed the pointers could be the same, if code on or
14559: very near the top of stack were executed. In the interest of speed we
14560: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14561: in scheduling: @code{NEXT} is divided into several parts:
14562: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14563: like:
1.1 anton 14564: @example
1.81 anton 14565: NEXT_P0;
1.1 anton 14566: n=sp[0]+sp[1];
14567: sp++;
14568: NEXT_P1;
14569: sp[0]=n;
14570: NEXT_P2;
14571: @end example
14572:
1.81 anton 14573: There are various schemes that distribute the different operations of
14574: NEXT between these parts in several ways; in general, different schemes
14575: perform best on different processors. We use a scheme for most
14576: architectures that performs well for most processors of this
1.109 anton 14577: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14578: the scheme on installation time.
14579:
1.1 anton 14580:
1.109 anton 14581: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14582: @subsection Direct or Indirect Threaded?
14583: @cindex threading, direct or indirect?
14584:
1.109 anton 14585: Threaded forth code consists of references to primitives (simple machine
14586: code routines like @code{+}) and to non-primitives (e.g., colon
14587: definitions, variables, constants); for a specific class of
14588: non-primitives (e.g., variables) there is one code routine (e.g.,
14589: @code{dovar}), but each variable needs a separate reference to its data.
14590:
14591: Traditionally Forth has been implemented as indirect threaded code,
14592: because this allows to use only one cell to reference a non-primitive
14593: (basically you point to the data, and find the code address there).
14594:
14595: @cindex primitive-centric threaded code
14596: However, threaded code in Gforth (since 0.6.0) uses two cells for
14597: non-primitives, one for the code address, and one for the data address;
14598: the data pointer is an immediate argument for the virtual machine
14599: instruction represented by the code address. We call this
14600: @emph{primitive-centric} threaded code, because all code addresses point
14601: to simple primitives. E.g., for a variable, the code address is for
14602: @code{lit} (also used for integer literals like @code{99}).
14603:
14604: Primitive-centric threaded code allows us to use (faster) direct
14605: threading as dispatch method, completely portably (direct threaded code
14606: in Gforth before 0.6.0 required architecture-specific code). It also
14607: eliminates the performance problems related to I-cache consistency that
14608: 386 implementations have with direct threaded code, and allows
14609: additional optimizations.
14610:
14611: @cindex hybrid direct/indirect threaded code
14612: There is a catch, however: the @var{xt} parameter of @code{execute} can
14613: occupy only one cell, so how do we pass non-primitives with their code
14614: @emph{and} data addresses to them? Our answer is to use indirect
14615: threaded dispatch for @code{execute} and other words that use a
14616: single-cell xt. So, normal threaded code in colon definitions uses
14617: direct threading, and @code{execute} and similar words, which dispatch
14618: to xts on the data stack, use indirect threaded code. We call this
14619: @emph{hybrid direct/indirect} threaded code.
14620:
14621: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14622: @cindex gforth engine
14623: @cindex gforth-fast engine
14624: The engines @command{gforth} and @command{gforth-fast} use hybrid
14625: direct/indirect threaded code. This means that with these engines you
14626: cannot use @code{,} to compile an xt. Instead, you have to use
14627: @code{compile,}.
14628:
14629: @cindex gforth-itc engine
1.115 anton 14630: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14631: This engine uses plain old indirect threaded code. It still compiles in
14632: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14633: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14634: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14635: and execute @code{' , is compile,}. Your program can check if it is
14636: running on a hybrid direct/indirect threaded engine or a pure indirect
14637: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14638:
14639:
14640: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14641: @subsection Dynamic Superinstructions
14642: @cindex Dynamic superinstructions with replication
14643: @cindex Superinstructions
14644: @cindex Replication
14645:
14646: The engines @command{gforth} and @command{gforth-fast} use another
14647: optimization: Dynamic superinstructions with replication. As an
14648: example, consider the following colon definition:
14649:
14650: @example
14651: : squared ( n1 -- n2 )
14652: dup * ;
14653: @end example
14654:
14655: Gforth compiles this into the threaded code sequence
14656:
14657: @example
14658: dup
14659: *
14660: ;s
14661: @end example
14662:
14663: In normal direct threaded code there is a code address occupying one
14664: cell for each of these primitives. Each code address points to a
14665: machine code routine, and the interpreter jumps to this machine code in
14666: order to execute the primitive. The routines for these three
14667: primitives are (in @command{gforth-fast} on the 386):
14668:
14669: @example
14670: Code dup
14671: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14672: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14673: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14674: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14675: end-code
14676: Code *
14677: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14678: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14679: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14680: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14681: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14682: end-code
14683: Code ;s
14684: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14685: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14686: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14687: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14688: end-code
14689: @end example
14690:
14691: With dynamic superinstructions and replication the compiler does not
14692: just lay down the threaded code, but also copies the machine code
14693: fragments, usually without the jump at the end.
14694:
14695: @example
14696: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14697: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14698: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14699: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14700: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14701: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14702: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14703: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14704: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14705: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14706: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14707: @end example
14708:
14709: Only when a threaded-code control-flow change happens (e.g., in
14710: @code{;s}), the jump is appended. This optimization eliminates many of
14711: these jumps and makes the rest much more predictable. The speedup
14712: depends on the processor and the application; on the Athlon and Pentium
14713: III this optimization typically produces a speedup by a factor of 2.
14714:
14715: The code addresses in the direct-threaded code are set to point to the
14716: appropriate points in the copied machine code, in this example like
14717: this:
1.1 anton 14718:
1.109 anton 14719: @example
14720: primitive code address
14721: dup $4057D27D
14722: * $4057D286
14723: ;s $4057D292
14724: @end example
14725:
14726: Thus there can be threaded-code jumps to any place in this piece of
14727: code. This also simplifies decompilation quite a bit.
14728:
14729: @cindex --no-dynamic command-line option
14730: @cindex --no-super command-line option
14731: You can disable this optimization with @option{--no-dynamic}. You can
14732: use the copying without eliminating the jumps (i.e., dynamic
14733: replication, but without superinstructions) with @option{--no-super};
14734: this gives the branch prediction benefit alone; the effect on
1.110 anton 14735: performance depends on the CPU; on the Athlon and Pentium III the
14736: speedup is a little less than for dynamic superinstructions with
14737: replication.
14738:
14739: @cindex patching threaded code
14740: One use of these options is if you want to patch the threaded code.
14741: With superinstructions, many of the dispatch jumps are eliminated, so
14742: patching often has no effect. These options preserve all the dispatch
14743: jumps.
1.109 anton 14744:
14745: @cindex --dynamic command-line option
1.110 anton 14746: On some machines dynamic superinstructions are disabled by default,
14747: because it is unsafe on these machines. However, if you feel
14748: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14749:
14750: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14751: @subsection DOES>
14752: @cindex @code{DOES>} implementation
14753:
1.26 crook 14754: @cindex @code{dodoes} routine
14755: @cindex @code{DOES>}-code
1.1 anton 14756: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14757: the chunk of code executed by every word defined by a
1.109 anton 14758: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14759: this is only needed if the xt of the word is @code{execute}d. The main
14760: problem here is: How to find the Forth code to be executed, i.e. the
14761: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14762: solutions:
1.1 anton 14763:
1.21 crook 14764: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14765: @code{DOES>}-code address is stored in the cell after the code address
14766: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14767: illegal in the Forth-79 and all later standards, because in fig-Forth
14768: this address lies in the body (which is illegal in these
14769: standards). However, by making the code field larger for all words this
14770: solution becomes legal again. We use this approach. Leaving a cell
14771: unused in most words is a bit wasteful, but on the machines we are
14772: targeting this is hardly a problem.
14773:
1.1 anton 14774:
14775: @node Primitives, Performance, Threading, Engine
14776: @section Primitives
14777: @cindex primitives, implementation
14778: @cindex virtual machine instructions, implementation
14779:
14780: @menu
14781: * Automatic Generation::
14782: * TOS Optimization::
14783: * Produced code::
14784: @end menu
14785:
14786: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14787: @subsection Automatic Generation
14788: @cindex primitives, automatic generation
14789:
14790: @cindex @file{prims2x.fs}
1.109 anton 14791:
1.1 anton 14792: Since the primitives are implemented in a portable language, there is no
14793: longer any need to minimize the number of primitives. On the contrary,
14794: having many primitives has an advantage: speed. In order to reduce the
14795: number of errors in primitives and to make programming them easier, we
1.109 anton 14796: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14797: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14798: generates most (and sometimes all) of the C code for a primitive from
14799: the stack effect notation. The source for a primitive has the following
14800: form:
1.1 anton 14801:
14802: @cindex primitive source format
14803: @format
1.58 anton 14804: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14805: [@code{""}@i{glossary entry}@code{""}]
14806: @i{C code}
1.1 anton 14807: [@code{:}
1.29 crook 14808: @i{Forth code}]
1.1 anton 14809: @end format
14810:
14811: The items in brackets are optional. The category and glossary fields
14812: are there for generating the documentation, the Forth code is there
14813: for manual implementations on machines without GNU C. E.g., the source
14814: for the primitive @code{+} is:
14815: @example
1.58 anton 14816: + ( n1 n2 -- n ) core plus
1.1 anton 14817: n = n1+n2;
14818: @end example
14819:
14820: This looks like a specification, but in fact @code{n = n1+n2} is C
14821: code. Our primitive generation tool extracts a lot of information from
14822: the stack effect notations@footnote{We use a one-stack notation, even
14823: though we have separate data and floating-point stacks; The separate
14824: notation can be generated easily from the unified notation.}: The number
14825: of items popped from and pushed on the stack, their type, and by what
14826: name they are referred to in the C code. It then generates a C code
14827: prelude and postlude for each primitive. The final C code for @code{+}
14828: looks like this:
14829:
14830: @example
1.46 pazsan 14831: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14832: /* */ /* documentation */
1.81 anton 14833: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14834: @{
14835: DEF_CA /* definition of variable ca (indirect threading) */
14836: Cell n1; /* definitions of variables */
14837: Cell n2;
14838: Cell n;
1.81 anton 14839: NEXT_P0; /* NEXT part 0 */
1.1 anton 14840: n1 = (Cell) sp[1]; /* input */
14841: n2 = (Cell) TOS;
14842: sp += 1; /* stack adjustment */
14843: @{
14844: n = n1+n2; /* C code taken from the source */
14845: @}
14846: NEXT_P1; /* NEXT part 1 */
14847: TOS = (Cell)n; /* output */
14848: NEXT_P2; /* NEXT part 2 */
14849: @}
14850: @end example
14851:
14852: This looks long and inefficient, but the GNU C compiler optimizes quite
14853: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14854: HP RISC machines: Defining the @code{n}s does not produce any code, and
14855: using them as intermediate storage also adds no cost.
14856:
1.26 crook 14857: There are also other optimizations that are not illustrated by this
14858: example: assignments between simple variables are usually for free (copy
1.1 anton 14859: propagation). If one of the stack items is not used by the primitive
14860: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14861: (dead code elimination). On the other hand, there are some things that
14862: the compiler does not do, therefore they are performed by
14863: @file{prims2x.fs}: The compiler does not optimize code away that stores
14864: a stack item to the place where it just came from (e.g., @code{over}).
14865:
14866: While programming a primitive is usually easy, there are a few cases
14867: where the programmer has to take the actions of the generator into
14868: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14869: fall through to @code{NEXT}.
1.109 anton 14870:
14871: For more information
1.1 anton 14872:
14873: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14874: @subsection TOS Optimization
14875: @cindex TOS optimization for primitives
14876: @cindex primitives, keeping the TOS in a register
14877:
14878: An important optimization for stack machine emulators, e.g., Forth
14879: engines, is keeping one or more of the top stack items in
1.29 crook 14880: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14881: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14882: @itemize @bullet
14883: @item
1.29 crook 14884: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14885: due to fewer loads from and stores to the stack.
1.29 crook 14886: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14887: @i{y<n}, due to additional moves between registers.
1.1 anton 14888: @end itemize
14889:
14890: @cindex -DUSE_TOS
14891: @cindex -DUSE_NO_TOS
14892: In particular, keeping one item in a register is never a disadvantage,
14893: if there are enough registers. Keeping two items in registers is a
14894: disadvantage for frequent words like @code{?branch}, constants,
14895: variables, literals and @code{i}. Therefore our generator only produces
14896: code that keeps zero or one items in registers. The generated C code
14897: covers both cases; the selection between these alternatives is made at
14898: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14899: code for @code{+} is just a simple variable name in the one-item case,
14900: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14901: GNU C compiler tries to keep simple variables like @code{TOS} in
14902: registers, and it usually succeeds, if there are enough registers.
14903:
14904: @cindex -DUSE_FTOS
14905: @cindex -DUSE_NO_FTOS
14906: The primitive generator performs the TOS optimization for the
14907: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14908: operations the benefit of this optimization is even larger:
14909: floating-point operations take quite long on most processors, but can be
14910: performed in parallel with other operations as long as their results are
14911: not used. If the FP-TOS is kept in a register, this works. If
14912: it is kept on the stack, i.e., in memory, the store into memory has to
14913: wait for the result of the floating-point operation, lengthening the
14914: execution time of the primitive considerably.
14915:
14916: The TOS optimization makes the automatic generation of primitives a
14917: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14918: @code{TOS} is not sufficient. There are some special cases to
14919: consider:
14920: @itemize @bullet
14921: @item In the case of @code{dup ( w -- w w )} the generator must not
14922: eliminate the store to the original location of the item on the stack,
14923: if the TOS optimization is turned on.
14924: @item Primitives with stack effects of the form @code{--}
1.29 crook 14925: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14926: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14927: must load the TOS from the stack at the end. But for the null stack
14928: effect @code{--} no stores or loads should be generated.
14929: @end itemize
14930:
14931: @node Produced code, , TOS Optimization, Primitives
14932: @subsection Produced code
14933: @cindex primitives, assembly code listing
14934:
14935: @cindex @file{engine.s}
14936: To see what assembly code is produced for the primitives on your machine
14937: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 14938: look at the resulting file @file{engine.s}. Alternatively, you can also
14939: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 14940:
14941: @node Performance, , Primitives, Engine
14942: @section Performance
14943: @cindex performance of some Forth interpreters
14944: @cindex engine performance
14945: @cindex benchmarking Forth systems
14946: @cindex Gforth performance
14947:
14948: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 14949: impossible to write a significantly faster threaded-code engine.
1.1 anton 14950:
14951: On register-starved machines like the 386 architecture processors
14952: improvements are possible, because @code{gcc} does not utilize the
14953: registers as well as a human, even with explicit register declarations;
14954: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14955: and hand-tuned it for the 486; this system is 1.19 times faster on the
14956: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14957: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14958: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14959: registers fit in real registers (and we can even afford to use the TOS
14960: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 14961: earlier results. And dynamic superinstructions provide another speedup
14962: (but only around a factor 1.2 on the 486).
1.1 anton 14963:
14964: @cindex Win32Forth performance
14965: @cindex NT Forth performance
14966: @cindex eforth performance
14967: @cindex ThisForth performance
14968: @cindex PFE performance
14969: @cindex TILE performance
1.81 anton 14970: The potential advantage of assembly language implementations is not
1.112 anton 14971: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 14972: (direct threaded, compiled with @code{gcc-2.95.1} and
14973: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14974: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14975: (with and without peephole (aka pinhole) optimization of the threaded
14976: code); all these systems were written in assembly language. We also
14977: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14978: with @code{gcc-2.6.3} with the default configuration for Linux:
14979: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14980: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14981: employs peephole optimization of the threaded code) and TILE (compiled
14982: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14983: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14984: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14985: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14986: then extended it to run the benchmarks, added the peephole optimizer,
14987: ran the benchmarks and reported the results.
1.40 anton 14988:
1.1 anton 14989: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14990: matrix multiplication come from the Stanford integer benchmarks and have
14991: been translated into Forth by Martin Fraeman; we used the versions
14992: included in the TILE Forth package, but with bigger data set sizes; and
14993: a recursive Fibonacci number computation for benchmarking calling
14994: performance. The following table shows the time taken for the benchmarks
14995: scaled by the time taken by Gforth (in other words, it shows the speedup
14996: factor that Gforth achieved over the other systems).
14997:
14998: @example
1.112 anton 14999: relative Win32- NT eforth This-
15000: time Gforth Forth Forth eforth +opt PFE Forth TILE
15001: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15002: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15003: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15004: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15005: @end example
15006:
1.26 crook 15007: You may be quite surprised by the good performance of Gforth when
15008: compared with systems written in assembly language. One important reason
15009: for the disappointing performance of these other systems is probably
15010: that they are not written optimally for the 486 (e.g., they use the
15011: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15012: but costly method for relocating the Forth image: like @code{cforth}, it
15013: computes the actual addresses at run time, resulting in two address
15014: computations per @code{NEXT} (@pxref{Image File Background}).
15015:
1.1 anton 15016: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15017: explained with the self-imposed restriction of the latter systems to
15018: standard C, which makes efficient threading impossible (however, the
1.4 anton 15019: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15020: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15021: Moreover, current C compilers have a hard time optimizing other aspects
15022: of the ThisForth and the TILE source.
15023:
1.26 crook 15024: The performance of Gforth on 386 architecture processors varies widely
15025: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15026: allocate any of the virtual machine registers into real machine
15027: registers by itself and would not work correctly with explicit register
1.112 anton 15028: declarations, giving a significantly slower engine (on a 486DX2/66
15029: running the Sieve) than the one measured above.
1.1 anton 15030:
1.26 crook 15031: Note that there have been several releases of Win32Forth since the
15032: release presented here, so the results presented above may have little
1.40 anton 15033: predictive value for the performance of Win32Forth today (results for
15034: the current release on an i486DX2/66 are welcome).
1.1 anton 15035:
15036: @cindex @file{Benchres}
1.66 anton 15037: In
15038: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15039: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15040: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15041: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15042: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15043: than the version used here. You can find a newer version of these
15044: measurements at
1.47 crook 15045: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15046: find numbers for Gforth on various machines in @file{Benchres}.
15047:
1.26 crook 15048: @c ******************************************************************
1.113 anton 15049: @c @node Binding to System Library, Cross Compiler, Engine, Top
15050: @c @chapter Binding to System Library
1.13 pazsan 15051:
1.113 anton 15052: @c ****************************************************************
15053: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15054: @chapter Cross Compiler
1.47 crook 15055: @cindex @file{cross.fs}
15056: @cindex cross-compiler
15057: @cindex metacompiler
15058: @cindex target compiler
1.13 pazsan 15059:
1.46 pazsan 15060: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15061: mostly written in Forth, including crucial parts like the outer
15062: interpreter and compiler, it needs compiled Forth code to get
15063: started. The cross compiler allows to create new images for other
15064: architectures, even running under another Forth system.
1.13 pazsan 15065:
15066: @menu
1.67 anton 15067: * Using the Cross Compiler::
15068: * How the Cross Compiler Works::
1.13 pazsan 15069: @end menu
15070:
1.21 crook 15071: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15072: @section Using the Cross Compiler
1.46 pazsan 15073:
15074: The cross compiler uses a language that resembles Forth, but isn't. The
15075: main difference is that you can execute Forth code after definition,
15076: while you usually can't execute the code compiled by cross, because the
15077: code you are compiling is typically for a different computer than the
15078: one you are compiling on.
15079:
1.81 anton 15080: @c anton: This chapter is somewhat different from waht I would expect: I
15081: @c would expect an explanation of the cross language and how to create an
15082: @c application image with it. The section explains some aspects of
15083: @c creating a Gforth kernel.
15084:
1.46 pazsan 15085: The Makefile is already set up to allow you to create kernels for new
15086: architectures with a simple make command. The generic kernels using the
15087: GCC compiled virtual machine are created in the normal build process
15088: with @code{make}. To create a embedded Gforth executable for e.g. the
15089: 8086 processor (running on a DOS machine), type
15090:
15091: @example
15092: make kernl-8086.fi
15093: @end example
15094:
15095: This will use the machine description from the @file{arch/8086}
15096: directory to create a new kernel. A machine file may look like that:
15097:
15098: @example
15099: \ Parameter for target systems 06oct92py
15100:
15101: 4 Constant cell \ cell size in bytes
15102: 2 Constant cell<< \ cell shift to bytes
15103: 5 Constant cell>bit \ cell shift to bits
15104: 8 Constant bits/char \ bits per character
15105: 8 Constant bits/byte \ bits per byte [default: 8]
15106: 8 Constant float \ bytes per float
15107: 8 Constant /maxalign \ maximum alignment in bytes
15108: false Constant bigendian \ byte order
15109: ( true=big, false=little )
15110:
15111: include machpc.fs \ feature list
15112: @end example
15113:
15114: This part is obligatory for the cross compiler itself, the feature list
15115: is used by the kernel to conditionally compile some features in and out,
15116: depending on whether the target supports these features.
15117:
15118: There are some optional features, if you define your own primitives,
15119: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15120: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15121: @code{prims-include} includes primitives, and @code{>boot} prepares for
15122: booting.
15123:
15124: @example
15125: : asm-include ." Include assembler" cr
15126: s" arch/8086/asm.fs" included ;
15127:
15128: : prims-include ." Include primitives" cr
15129: s" arch/8086/prim.fs" included ;
15130:
15131: : >boot ." Prepare booting" cr
15132: s" ' boot >body into-forth 1+ !" evaluate ;
15133: @end example
15134:
15135: These words are used as sort of macro during the cross compilation in
1.81 anton 15136: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15137: be possible --- but more complicated --- to write a new kernel project
15138: file, too.
15139:
15140: @file{kernel/main.fs} expects the machine description file name on the
15141: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15142: @code{mach-file} leaves a counted string on the stack, or
15143: @code{machine-file} leaves an address, count pair of the filename on the
15144: stack.
15145:
15146: The feature list is typically controlled using @code{SetValue}, generic
15147: files that are used by several projects can use @code{DefaultValue}
15148: instead. Both functions work like @code{Value}, when the value isn't
15149: defined, but @code{SetValue} works like @code{to} if the value is
15150: defined, and @code{DefaultValue} doesn't set anything, if the value is
15151: defined.
15152:
15153: @example
15154: \ generic mach file for pc gforth 03sep97jaw
15155:
15156: true DefaultValue NIL \ relocating
15157:
15158: >ENVIRON
15159:
15160: true DefaultValue file \ controls the presence of the
15161: \ file access wordset
15162: true DefaultValue OS \ flag to indicate a operating system
15163:
15164: true DefaultValue prims \ true: primitives are c-code
15165:
15166: true DefaultValue floating \ floating point wordset is present
15167:
15168: true DefaultValue glocals \ gforth locals are present
15169: \ will be loaded
15170: true DefaultValue dcomps \ double number comparisons
15171:
15172: true DefaultValue hash \ hashing primitives are loaded/present
15173:
15174: true DefaultValue xconds \ used together with glocals,
15175: \ special conditionals supporting gforths'
15176: \ local variables
15177: true DefaultValue header \ save a header information
15178:
15179: true DefaultValue backtrace \ enables backtrace code
15180:
15181: false DefaultValue ec
15182: false DefaultValue crlf
15183:
15184: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15185:
15186: &16 KB DefaultValue stack-size
15187: &15 KB &512 + DefaultValue fstack-size
15188: &15 KB DefaultValue rstack-size
15189: &14 KB &512 + DefaultValue lstack-size
15190: @end example
1.13 pazsan 15191:
1.48 anton 15192: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15193: @section How the Cross Compiler Works
1.13 pazsan 15194:
15195: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15196: @appendix Bugs
1.1 anton 15197: @cindex bug reporting
15198:
1.21 crook 15199: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15200:
1.103 anton 15201: If you find a bug, please submit a bug report through
15202: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15203:
15204: @itemize @bullet
15205: @item
1.81 anton 15206: A program (or a sequence of keyboard commands) that reproduces the bug.
15207: @item
15208: A description of what you think constitutes the buggy behaviour.
15209: @item
1.21 crook 15210: The Gforth version used (it is announced at the start of an
15211: interactive Gforth session).
15212: @item
15213: The machine and operating system (on Unix
15214: systems @code{uname -a} will report this information).
15215: @item
1.81 anton 15216: The installation options (you can find the configure options at the
15217: start of @file{config.status}) and configuration (@code{configure}
15218: output or @file{config.cache}).
1.21 crook 15219: @item
15220: A complete list of changes (if any) you (or your installer) have made to the
15221: Gforth sources.
15222: @end itemize
1.1 anton 15223:
15224: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15225: to Report Bugs, gcc.info, GNU C Manual}.
15226:
15227:
1.21 crook 15228: @node Origin, Forth-related information, Bugs, Top
15229: @appendix Authors and Ancestors of Gforth
1.1 anton 15230:
15231: @section Authors and Contributors
15232: @cindex authors of Gforth
15233: @cindex contributors to Gforth
15234:
15235: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15236: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15237: lot to the manual. Assemblers and disassemblers were contributed by
15238: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15239: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15240: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15241: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15242: support for calling C libraries. Helpful comments also came from Paul
15243: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15244: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15245: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15246: Gforth-0.2.1 there were also helpful comments from many others; thank
15247: you all, sorry for not listing you here (but digging through my mailbox
15248: to extract your names is on my to-do list).
1.1 anton 15249:
15250: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15251: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15252: was developed across the Internet, and its authors did not meet
1.20 pazsan 15253: physically for the first 4 years of development.
1.1 anton 15254:
15255: @section Pedigree
1.26 crook 15256: @cindex pedigree of Gforth
1.1 anton 15257:
1.81 anton 15258: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15259: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15260:
1.20 pazsan 15261: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15262: 32 bit native code version of VolksForth for the Atari ST, written
15263: mostly by Dietrich Weineck.
15264:
1.81 anton 15265: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15266: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15267: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15268:
15269: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15270: Forth-83 standard. !! Pedigree? When?
15271:
15272: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15273: 1979. Robert Selzer and Bill Ragsdale developed the original
15274: implementation of fig-Forth for the 6502 based on microForth.
15275:
15276: The principal architect of microForth was Dean Sanderson. microForth was
15277: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15278: the 1802, and subsequently implemented on the 8080, the 6800 and the
15279: Z80.
15280:
15281: All earlier Forth systems were custom-made, usually by Charles Moore,
15282: who discovered (as he puts it) Forth during the late 60s. The first full
15283: Forth existed in 1971.
15284:
1.81 anton 15285: A part of the information in this section comes from
15286: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15287: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15288: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15289: SIGPLAN Notices 28(3), 1993. You can find more historical and
15290: genealogical information about Forth there.
1.1 anton 15291:
1.81 anton 15292: @c ------------------------------------------------------------------
1.113 anton 15293: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15294: @appendix Other Forth-related information
15295: @cindex Forth-related information
15296:
1.81 anton 15297: @c anton: I threw most of this stuff out, because it can be found through
15298: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15299:
15300: @cindex comp.lang.forth
15301: @cindex frequently asked questions
1.81 anton 15302: There is an active news group (comp.lang.forth) discussing Forth
15303: (including Gforth) and Forth-related issues. Its
15304: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15305: (frequently asked questions and their answers) contains a lot of
15306: information on Forth. You should read it before posting to
15307: comp.lang.forth.
1.21 crook 15308:
1.81 anton 15309: The ANS Forth standard is most usable in its
15310: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15311:
1.113 anton 15312: @c ---------------------------------------------------
15313: @node Licenses, Word Index, Forth-related information, Top
15314: @appendix Licenses
15315:
15316: @menu
15317: * GNU Free Documentation License:: License for copying this manual.
15318: * Copying:: GPL (for copying this software).
15319: @end menu
15320:
15321: @include fdl.texi
15322:
15323: @include gpl.texi
15324:
15325:
15326:
1.81 anton 15327: @c ------------------------------------------------------------------
1.113 anton 15328: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15329: @unnumbered Word Index
15330:
1.26 crook 15331: This index is a list of Forth words that have ``glossary'' entries
15332: within this manual. Each word is listed with its stack effect and
15333: wordset.
1.1 anton 15334:
15335: @printindex fn
15336:
1.81 anton 15337: @c anton: the name index seems superfluous given the word and concept indices.
15338:
15339: @c @node Name Index, Concept Index, Word Index, Top
15340: @c @unnumbered Name Index
1.41 anton 15341:
1.81 anton 15342: @c This index is a list of Forth words that have ``glossary'' entries
15343: @c within this manual.
1.41 anton 15344:
1.81 anton 15345: @c @printindex ky
1.41 anton 15346:
1.113 anton 15347: @c -------------------------------------------------------
1.81 anton 15348: @node Concept Index, , Word Index, Top
1.1 anton 15349: @unnumbered Concept and Word Index
15350:
1.26 crook 15351: Not all entries listed in this index are present verbatim in the
15352: text. This index also duplicates, in abbreviated form, all of the words
15353: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15354:
15355: @printindex cp
15356:
15357: @bye
1.81 anton 15358:
15359:
1.1 anton 15360:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>