Annotation of gforth/doc/gforth.ds, revision 1.117
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
59: This manual is for Gforth
60: (version @value{VERSION}, @value{UPDATED}),
61: a fast and portable implementation of the ANS Forth language
1.29 crook 62:
1.113 anton 63: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003 Free Software Foundation, Inc.
1.29 crook 64:
1.113 anton 65: @quotation
66: Permission is granted to copy, distribute and/or modify this document
67: under the terms of the GNU Free Documentation License, Version 1.1 or
68: any later version published by the Free Software Foundation; with no
69: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
70: and with the Back-Cover Texts as in (a) below. A copy of the
71: license is included in the section entitled ``GNU Free Documentation
72: License.''
73:
74: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
75: this GNU Manual, like GNU software. Copies published by the Free
76: Software Foundation raise funds for GNU development.''
77: @end quotation
78: @end copying
1.10 anton 79:
1.113 anton 80: @dircategory Software development
81: @direntry
82: * Gforth: (gforth). A fast interpreter for the Forth language.
83: @end direntry
84: @c The Texinfo manual also recommends doing this, but for Gforth it may
85: @c not make much sense
86: @c @dircategory Individual utilities
87: @c @direntry
88: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
89: @c @end direntry
1.1 anton 90:
91: @titlepage
1.113 anton 92: @title Gforth
93: @subtitle for version @value{VERSION}, @value{UPDATED}
94: @author Neal Crook
95: @author Anton Ertl
1.114 anton 96: @author David Kuehling
1.113 anton 97: @author Bernd Paysan
98: @author Jens Wilke
1.1 anton 99: @page
100: @vskip 0pt plus 1filll
1.113 anton 101: @insertcopying
102: @end titlepage
1.1 anton 103:
1.113 anton 104: @contents
1.1 anton 105:
1.113 anton 106: @ifnottex
107: @node Top, Goals, (dir), (dir)
108: @top Gforth
1.1 anton 109:
1.113 anton 110: @insertcopying
1.49 anton 111: @end ifnottex
1.1 anton 112:
113: @menu
1.26 crook 114: * Goals:: About the Gforth Project
1.29 crook 115: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 116: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 117: * Introduction:: An introduction to ANS Forth
1.1 anton 118: * Words:: Forth words available in Gforth
1.24 anton 119: * Error messages:: How to interpret them
1.1 anton 120: * Tools:: Programming tools
121: * ANS conformance:: Implementation-defined options etc.
1.65 anton 122: * Standard vs Extensions:: Should I use extensions?
1.1 anton 123: * Model:: The abstract machine of Gforth
124: * Integrating Gforth:: Forth as scripting language for applications
125: * Emacs and Gforth:: The Gforth Mode
126: * Image Files:: @code{.fi} files contain compiled code
127: * Engine:: The inner interpreter and the primitives
1.13 pazsan 128: * Cross Compiler:: The Cross Compiler
1.1 anton 129: * Bugs:: How to report them
130: * Origin:: Authors and ancestors of Gforth
1.21 crook 131: * Forth-related information:: Books and places to look on the WWW
1.113 anton 132: * Licenses::
1.1 anton 133: * Word Index:: An item for each Forth word
134: * Concept Index:: A menu covering many topics
1.12 anton 135:
1.91 anton 136: @detailmenu
137: --- The Detailed Node Listing ---
1.12 anton 138:
1.29 crook 139: Gforth Environment
140:
1.32 anton 141: * Invoking Gforth:: Getting in
142: * Leaving Gforth:: Getting out
143: * Command-line editing::
1.48 anton 144: * Environment variables:: that affect how Gforth starts up
1.32 anton 145: * Gforth Files:: What gets installed and where
1.112 anton 146: * Gforth in pipes::
1.48 anton 147: * Startup speed:: When 35ms is not fast enough ...
148:
149: Forth Tutorial
150:
151: * Starting Gforth Tutorial::
152: * Syntax Tutorial::
153: * Crash Course Tutorial::
154: * Stack Tutorial::
155: * Arithmetics Tutorial::
156: * Stack Manipulation Tutorial::
157: * Using files for Forth code Tutorial::
158: * Comments Tutorial::
159: * Colon Definitions Tutorial::
160: * Decompilation Tutorial::
161: * Stack-Effect Comments Tutorial::
162: * Types Tutorial::
163: * Factoring Tutorial::
164: * Designing the stack effect Tutorial::
165: * Local Variables Tutorial::
166: * Conditional execution Tutorial::
167: * Flags and Comparisons Tutorial::
168: * General Loops Tutorial::
169: * Counted loops Tutorial::
170: * Recursion Tutorial::
171: * Leaving definitions or loops Tutorial::
172: * Return Stack Tutorial::
173: * Memory Tutorial::
174: * Characters and Strings Tutorial::
175: * Alignment Tutorial::
1.87 anton 176: * Files Tutorial::
1.48 anton 177: * Interpretation and Compilation Semantics and Immediacy Tutorial::
178: * Execution Tokens Tutorial::
179: * Exceptions Tutorial::
180: * Defining Words Tutorial::
181: * Arrays and Records Tutorial::
182: * POSTPONE Tutorial::
183: * Literal Tutorial::
184: * Advanced macros Tutorial::
185: * Compilation Tokens Tutorial::
186: * Wordlists and Search Order Tutorial::
1.29 crook 187:
1.24 anton 188: An Introduction to ANS Forth
189:
1.67 anton 190: * Introducing the Text Interpreter::
191: * Stacks and Postfix notation::
192: * Your first definition::
193: * How does that work?::
194: * Forth is written in Forth::
195: * Review - elements of a Forth system::
196: * Where to go next::
197: * Exercises::
1.24 anton 198:
1.12 anton 199: Forth Words
200:
201: * Notation::
1.65 anton 202: * Case insensitivity::
203: * Comments::
204: * Boolean Flags::
1.12 anton 205: * Arithmetic::
206: * Stack Manipulation::
207: * Memory::
208: * Control Structures::
209: * Defining Words::
1.65 anton 210: * Interpretation and Compilation Semantics::
1.47 crook 211: * Tokens for Words::
1.81 anton 212: * Compiling words::
1.65 anton 213: * The Text Interpreter::
1.111 anton 214: * The Input Stream::
1.65 anton 215: * Word Lists::
216: * Environmental Queries::
1.12 anton 217: * Files::
218: * Blocks::
219: * Other I/O::
1.78 anton 220: * Locals::
221: * Structures::
222: * Object-oriented Forth::
1.12 anton 223: * Programming Tools::
224: * Assembler and Code Words::
225: * Threading Words::
1.65 anton 226: * Passing Commands to the OS::
227: * Keeping track of Time::
228: * Miscellaneous Words::
1.12 anton 229:
230: Arithmetic
231:
232: * Single precision::
1.67 anton 233: * Double precision:: Double-cell integer arithmetic
1.12 anton 234: * Bitwise operations::
1.67 anton 235: * Numeric comparison::
1.32 anton 236: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 237: * Floating Point::
238:
239: Stack Manipulation
240:
241: * Data stack::
242: * Floating point stack::
243: * Return stack::
244: * Locals stack::
245: * Stack pointer manipulation::
246:
247: Memory
248:
1.32 anton 249: * Memory model::
250: * Dictionary allocation::
251: * Heap Allocation::
252: * Memory Access::
253: * Address arithmetic::
254: * Memory Blocks::
1.12 anton 255:
256: Control Structures
257:
1.41 anton 258: * Selection:: IF ... ELSE ... ENDIF
259: * Simple Loops:: BEGIN ...
1.32 anton 260: * Counted Loops:: DO
1.67 anton 261: * Arbitrary control structures::
262: * Calls and returns::
1.12 anton 263: * Exception Handling::
264:
265: Defining Words
266:
1.67 anton 267: * CREATE::
1.44 crook 268: * Variables:: Variables and user variables
1.67 anton 269: * Constants::
1.44 crook 270: * Values:: Initialised variables
1.67 anton 271: * Colon Definitions::
1.44 crook 272: * Anonymous Definitions:: Definitions without names
1.71 anton 273: * Supplying names:: Passing definition names as strings
1.67 anton 274: * User-defined Defining Words::
1.44 crook 275: * Deferred words:: Allow forward references
1.67 anton 276: * Aliases::
1.47 crook 277:
1.63 anton 278: User-defined Defining Words
279:
280: * CREATE..DOES> applications::
281: * CREATE..DOES> details::
282: * Advanced does> usage example::
1.91 anton 283: * @code{Const-does>}::
1.63 anton 284:
1.47 crook 285: Interpretation and Compilation Semantics
286:
1.67 anton 287: * Combined words::
1.12 anton 288:
1.71 anton 289: Tokens for Words
290:
291: * Execution token:: represents execution/interpretation semantics
292: * Compilation token:: represents compilation semantics
293: * Name token:: represents named words
294:
1.82 anton 295: Compiling words
296:
297: * Literals:: Compiling data values
298: * Macros:: Compiling words
299:
1.21 crook 300: The Text Interpreter
301:
1.67 anton 302: * Input Sources::
303: * Number Conversion::
304: * Interpret/Compile states::
305: * Interpreter Directives::
1.21 crook 306:
1.26 crook 307: Word Lists
308:
1.75 anton 309: * Vocabularies::
1.67 anton 310: * Why use word lists?::
1.75 anton 311: * Word list example::
1.26 crook 312:
313: Files
314:
1.48 anton 315: * Forth source files::
316: * General files::
317: * Search Paths::
318:
319: Search Paths
320:
1.75 anton 321: * Source Search Paths::
1.26 crook 322: * General Search Paths::
323:
324: Other I/O
325:
1.32 anton 326: * Simple numeric output:: Predefined formats
327: * Formatted numeric output:: Formatted (pictured) output
328: * String Formats:: How Forth stores strings in memory
1.67 anton 329: * Displaying characters and strings:: Other stuff
1.32 anton 330: * Input:: Input
1.112 anton 331: * Pipes:: How to create your own pipes
1.26 crook 332:
333: Locals
334:
335: * Gforth locals::
336: * ANS Forth locals::
337:
338: Gforth locals
339:
340: * Where are locals visible by name?::
341: * How long do locals live?::
1.78 anton 342: * Locals programming style::
343: * Locals implementation::
1.26 crook 344:
1.12 anton 345: Structures
346:
347: * Why explicit structure support?::
348: * Structure Usage::
349: * Structure Naming Convention::
350: * Structure Implementation::
351: * Structure Glossary::
352:
353: Object-oriented Forth
354:
1.48 anton 355: * Why object-oriented programming?::
356: * Object-Oriented Terminology::
357: * Objects::
358: * OOF::
359: * Mini-OOF::
1.23 crook 360: * Comparison with other object models::
1.12 anton 361:
1.24 anton 362: The @file{objects.fs} model
1.12 anton 363:
364: * Properties of the Objects model::
365: * Basic Objects Usage::
1.41 anton 366: * The Objects base class::
1.12 anton 367: * Creating objects::
368: * Object-Oriented Programming Style::
369: * Class Binding::
370: * Method conveniences::
371: * Classes and Scoping::
1.41 anton 372: * Dividing classes::
1.12 anton 373: * Object Interfaces::
374: * Objects Implementation::
375: * Objects Glossary::
376:
1.24 anton 377: The @file{oof.fs} model
1.12 anton 378:
1.67 anton 379: * Properties of the OOF model::
380: * Basic OOF Usage::
381: * The OOF base class::
382: * Class Declaration::
383: * Class Implementation::
1.12 anton 384:
1.24 anton 385: The @file{mini-oof.fs} model
1.23 crook 386:
1.48 anton 387: * Basic Mini-OOF Usage::
388: * Mini-OOF Example::
389: * Mini-OOF Implementation::
1.23 crook 390:
1.78 anton 391: Programming Tools
392:
393: * Examining::
394: * Forgetting words::
395: * Debugging:: Simple and quick.
396: * Assertions:: Making your programs self-checking.
397: * Singlestep Debugger:: Executing your program word by word.
398:
399: Assembler and Code Words
400:
401: * Code and ;code::
402: * Common Assembler:: Assembler Syntax
403: * Common Disassembler::
404: * 386 Assembler:: Deviations and special cases
405: * Alpha Assembler:: Deviations and special cases
406: * MIPS assembler:: Deviations and special cases
407: * Other assemblers:: How to write them
408:
1.12 anton 409: Tools
410:
411: * ANS Report:: Report the words used, sorted by wordset.
412:
413: ANS conformance
414:
415: * The Core Words::
416: * The optional Block word set::
417: * The optional Double Number word set::
418: * The optional Exception word set::
419: * The optional Facility word set::
420: * The optional File-Access word set::
421: * The optional Floating-Point word set::
422: * The optional Locals word set::
423: * The optional Memory-Allocation word set::
424: * The optional Programming-Tools word set::
425: * The optional Search-Order word set::
426:
427: The Core Words
428:
429: * core-idef:: Implementation Defined Options
430: * core-ambcond:: Ambiguous Conditions
431: * core-other:: Other System Documentation
432:
433: The optional Block word set
434:
435: * block-idef:: Implementation Defined Options
436: * block-ambcond:: Ambiguous Conditions
437: * block-other:: Other System Documentation
438:
439: The optional Double Number word set
440:
441: * double-ambcond:: Ambiguous Conditions
442:
443: The optional Exception word set
444:
445: * exception-idef:: Implementation Defined Options
446:
447: The optional Facility word set
448:
449: * facility-idef:: Implementation Defined Options
450: * facility-ambcond:: Ambiguous Conditions
451:
452: The optional File-Access word set
453:
454: * file-idef:: Implementation Defined Options
455: * file-ambcond:: Ambiguous Conditions
456:
457: The optional Floating-Point word set
458:
459: * floating-idef:: Implementation Defined Options
460: * floating-ambcond:: Ambiguous Conditions
461:
462: The optional Locals word set
463:
464: * locals-idef:: Implementation Defined Options
465: * locals-ambcond:: Ambiguous Conditions
466:
467: The optional Memory-Allocation word set
468:
469: * memory-idef:: Implementation Defined Options
470:
471: The optional Programming-Tools word set
472:
473: * programming-idef:: Implementation Defined Options
474: * programming-ambcond:: Ambiguous Conditions
475:
476: The optional Search-Order word set
477:
478: * search-idef:: Implementation Defined Options
479: * search-ambcond:: Ambiguous Conditions
480:
1.109 anton 481: Emacs and Gforth
482:
483: * Installing gforth.el:: Making Emacs aware of Forth.
484: * Emacs Tags:: Viewing the source of a word in Emacs.
485: * Hilighting:: Making Forth code look prettier.
486: * Auto-Indentation:: Customizing auto-indentation.
487: * Blocks Files:: Reading and writing blocks files.
488:
1.12 anton 489: Image Files
490:
1.24 anton 491: * Image Licensing Issues:: Distribution terms for images.
492: * Image File Background:: Why have image files?
1.67 anton 493: * Non-Relocatable Image Files:: don't always work.
1.24 anton 494: * Data-Relocatable Image Files:: are better.
1.67 anton 495: * Fully Relocatable Image Files:: better yet.
1.24 anton 496: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 497: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 498: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 499:
500: Fully Relocatable Image Files
501:
1.27 crook 502: * gforthmi:: The normal way
1.12 anton 503: * cross.fs:: The hard way
504:
505: Engine
506:
507: * Portability::
508: * Threading::
509: * Primitives::
510: * Performance::
511:
512: Threading
513:
514: * Scheduling::
515: * Direct or Indirect Threaded?::
1.109 anton 516: * Dynamic Superinstructions::
1.12 anton 517: * DOES>::
518:
519: Primitives
520:
521: * Automatic Generation::
522: * TOS Optimization::
523: * Produced code::
1.13 pazsan 524:
525: Cross Compiler
526:
1.67 anton 527: * Using the Cross Compiler::
528: * How the Cross Compiler Works::
1.13 pazsan 529:
1.113 anton 530: Licenses
531:
532: * GNU Free Documentation License:: License for copying this manual.
533: * Copying:: GPL (for copying this software).
534:
1.24 anton 535: @end detailmenu
1.1 anton 536: @end menu
537:
1.113 anton 538: @c ----------------------------------------------------------
1.1 anton 539: @iftex
540: @unnumbered Preface
541: @cindex Preface
1.21 crook 542: This manual documents Gforth. Some introductory material is provided for
543: readers who are unfamiliar with Forth or who are migrating to Gforth
544: from other Forth compilers. However, this manual is primarily a
545: reference manual.
1.1 anton 546: @end iftex
547:
1.28 crook 548: @comment TODO much more blurb here.
1.26 crook 549:
550: @c ******************************************************************
1.113 anton 551: @node Goals, Gforth Environment, Top, Top
1.26 crook 552: @comment node-name, next, previous, up
553: @chapter Goals of Gforth
554: @cindex goals of the Gforth project
555: The goal of the Gforth Project is to develop a standard model for
556: ANS Forth. This can be split into several subgoals:
557:
558: @itemize @bullet
559: @item
560: Gforth should conform to the ANS Forth Standard.
561: @item
562: It should be a model, i.e. it should define all the
563: implementation-dependent things.
564: @item
565: It should become standard, i.e. widely accepted and used. This goal
566: is the most difficult one.
567: @end itemize
568:
569: To achieve these goals Gforth should be
570: @itemize @bullet
571: @item
572: Similar to previous models (fig-Forth, F83)
573: @item
574: Powerful. It should provide for all the things that are considered
575: necessary today and even some that are not yet considered necessary.
576: @item
577: Efficient. It should not get the reputation of being exceptionally
578: slow.
579: @item
580: Free.
581: @item
582: Available on many machines/easy to port.
583: @end itemize
584:
585: Have we achieved these goals? Gforth conforms to the ANS Forth
586: standard. It may be considered a model, but we have not yet documented
587: which parts of the model are stable and which parts we are likely to
588: change. It certainly has not yet become a de facto standard, but it
589: appears to be quite popular. It has some similarities to and some
590: differences from previous models. It has some powerful features, but not
591: yet everything that we envisioned. We certainly have achieved our
1.65 anton 592: execution speed goals (@pxref{Performance})@footnote{However, in 1998
593: the bar was raised when the major commercial Forth vendors switched to
594: native code compilers.}. It is free and available on many machines.
1.29 crook 595:
1.26 crook 596: @c ******************************************************************
1.48 anton 597: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 598: @chapter Gforth Environment
599: @cindex Gforth environment
1.21 crook 600:
1.45 crook 601: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 602: material in this chapter.
1.21 crook 603:
604: @menu
1.29 crook 605: * Invoking Gforth:: Getting in
606: * Leaving Gforth:: Getting out
607: * Command-line editing::
1.48 anton 608: * Environment variables:: that affect how Gforth starts up
1.29 crook 609: * Gforth Files:: What gets installed and where
1.112 anton 610: * Gforth in pipes::
1.48 anton 611: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 612: @end menu
613:
1.49 anton 614: For related information about the creation of images see @ref{Image Files}.
1.29 crook 615:
1.21 crook 616: @comment ----------------------------------------------
1.48 anton 617: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 618: @section Invoking Gforth
619: @cindex invoking Gforth
620: @cindex running Gforth
621: @cindex command-line options
622: @cindex options on the command line
623: @cindex flags on the command line
1.21 crook 624:
1.30 anton 625: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 626: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 627: will usually just say @code{gforth} -- this automatically loads the
628: default image file @file{gforth.fi}. In many other cases the default
629: Gforth image will be invoked like this:
1.21 crook 630: @example
1.30 anton 631: gforth [file | -e forth-code] ...
1.21 crook 632: @end example
1.29 crook 633: @noindent
634: This interprets the contents of the files and the Forth code in the order they
635: are given.
1.21 crook 636:
1.109 anton 637: In addition to the @command{gforth} engine, there is also an engine
638: called @command{gforth-fast}, which is faster, but gives less
639: informative error messages (@pxref{Error messages}) and may catch some
640: stack underflows later or not at all. You should use it for debugged,
641: performance-critical programs.
642:
643: Moreover, there is an engine called @command{gforth-itc}, which is
644: useful in some backwards-compatibility situations (@pxref{Direct or
645: Indirect Threaded?}).
1.30 anton 646:
1.29 crook 647: In general, the command line looks like this:
1.21 crook 648:
649: @example
1.30 anton 650: gforth[-fast] [engine options] [image options]
1.21 crook 651: @end example
652:
1.30 anton 653: The engine options must come before the rest of the command
1.29 crook 654: line. They are:
1.26 crook 655:
1.29 crook 656: @table @code
657: @cindex -i, command-line option
658: @cindex --image-file, command-line option
659: @item --image-file @i{file}
660: @itemx -i @i{file}
661: Loads the Forth image @i{file} instead of the default
662: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 663:
1.39 anton 664: @cindex --appl-image, command-line option
665: @item --appl-image @i{file}
666: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 667: to the image (instead of processing them as engine options). This is
668: useful for building executable application images on Unix, built with
1.39 anton 669: @code{gforthmi --application ...}.
670:
1.29 crook 671: @cindex --path, command-line option
672: @cindex -p, command-line option
673: @item --path @i{path}
674: @itemx -p @i{path}
675: Uses @i{path} for searching the image file and Forth source code files
676: instead of the default in the environment variable @code{GFORTHPATH} or
677: the path specified at installation time (e.g.,
678: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
679: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 680:
1.29 crook 681: @cindex --dictionary-size, command-line option
682: @cindex -m, command-line option
683: @cindex @i{size} parameters for command-line options
684: @cindex size of the dictionary and the stacks
685: @item --dictionary-size @i{size}
686: @itemx -m @i{size}
687: Allocate @i{size} space for the Forth dictionary space instead of
688: using the default specified in the image (typically 256K). The
689: @i{size} specification for this and subsequent options consists of
690: an integer and a unit (e.g.,
691: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
692: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
693: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
694: @code{e} is used.
1.21 crook 695:
1.29 crook 696: @cindex --data-stack-size, command-line option
697: @cindex -d, command-line option
698: @item --data-stack-size @i{size}
699: @itemx -d @i{size}
700: Allocate @i{size} space for the data stack instead of using the
701: default specified in the image (typically 16K).
1.21 crook 702:
1.29 crook 703: @cindex --return-stack-size, command-line option
704: @cindex -r, command-line option
705: @item --return-stack-size @i{size}
706: @itemx -r @i{size}
707: Allocate @i{size} space for the return stack instead of using the
708: default specified in the image (typically 15K).
1.21 crook 709:
1.29 crook 710: @cindex --fp-stack-size, command-line option
711: @cindex -f, command-line option
712: @item --fp-stack-size @i{size}
713: @itemx -f @i{size}
714: Allocate @i{size} space for the floating point stack instead of
715: using the default specified in the image (typically 15.5K). In this case
716: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 717:
1.48 anton 718: @cindex --locals-stack-size, command-line option
719: @cindex -l, command-line option
720: @item --locals-stack-size @i{size}
721: @itemx -l @i{size}
722: Allocate @i{size} space for the locals stack instead of using the
723: default specified in the image (typically 14.5K).
724:
725: @cindex -h, command-line option
726: @cindex --help, command-line option
727: @item --help
728: @itemx -h
729: Print a message about the command-line options
730:
731: @cindex -v, command-line option
732: @cindex --version, command-line option
733: @item --version
734: @itemx -v
735: Print version and exit
736:
737: @cindex --debug, command-line option
738: @item --debug
739: Print some information useful for debugging on startup.
740:
741: @cindex --offset-image, command-line option
742: @item --offset-image
743: Start the dictionary at a slightly different position than would be used
744: otherwise (useful for creating data-relocatable images,
745: @pxref{Data-Relocatable Image Files}).
746:
747: @cindex --no-offset-im, command-line option
748: @item --no-offset-im
749: Start the dictionary at the normal position.
750:
751: @cindex --clear-dictionary, command-line option
752: @item --clear-dictionary
753: Initialize all bytes in the dictionary to 0 before loading the image
754: (@pxref{Data-Relocatable Image Files}).
755:
756: @cindex --die-on-signal, command-line-option
757: @item --die-on-signal
758: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
759: or the segmentation violation SIGSEGV) by translating it into a Forth
760: @code{THROW}. With this option, Gforth exits if it receives such a
761: signal. This option is useful when the engine and/or the image might be
762: severely broken (such that it causes another signal before recovering
763: from the first); this option avoids endless loops in such cases.
1.109 anton 764:
765: @item --no-dynamic
766: @item --dynamic
767: Disable or enable dynamic superinstructions with replication
768: (@pxref{Dynamic Superinstructions}).
769:
770: @item --no-super
1.110 anton 771: Disable dynamic superinstructions, use just dynamic replication; this is
772: useful if you want to patch threaded code (@pxref{Dynamic
773: Superinstructions}).
1.109 anton 774:
1.48 anton 775: @end table
776:
777: @cindex loading files at startup
778: @cindex executing code on startup
779: @cindex batch processing with Gforth
780: As explained above, the image-specific command-line arguments for the
781: default image @file{gforth.fi} consist of a sequence of filenames and
782: @code{-e @var{forth-code}} options that are interpreted in the sequence
783: in which they are given. The @code{-e @var{forth-code}} or
784: @code{--evaluate @var{forth-code}} option evaluates the Forth
785: code. This option takes only one argument; if you want to evaluate more
786: Forth words, you have to quote them or use @code{-e} several times. To exit
787: after processing the command line (instead of entering interactive mode)
788: append @code{-e bye} to the command line.
789:
790: @cindex versions, invoking other versions of Gforth
791: If you have several versions of Gforth installed, @code{gforth} will
792: invoke the version that was installed last. @code{gforth-@i{version}}
793: invokes a specific version. If your environment contains the variable
794: @code{GFORTHPATH}, you may want to override it by using the
795: @code{--path} option.
796:
797: Not yet implemented:
798: On startup the system first executes the system initialization file
799: (unless the option @code{--no-init-file} is given; note that the system
800: resulting from using this option may not be ANS Forth conformant). Then
801: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 802: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 803: then in @file{~}, then in the normal path (see above).
804:
805:
806:
807: @comment ----------------------------------------------
808: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
809: @section Leaving Gforth
810: @cindex Gforth - leaving
811: @cindex leaving Gforth
812:
813: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
814: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
815: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 816: data are discarded. For ways of saving the state of the system before
817: leaving Gforth see @ref{Image Files}.
1.48 anton 818:
819: doc-bye
820:
821:
822: @comment ----------------------------------------------
1.65 anton 823: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 824: @section Command-line editing
825: @cindex command-line editing
826:
827: Gforth maintains a history file that records every line that you type to
828: the text interpreter. This file is preserved between sessions, and is
829: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
830: repeatedly you can recall successively older commands from this (or
831: previous) session(s). The full list of command-line editing facilities is:
832:
833: @itemize @bullet
834: @item
835: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
836: commands from the history buffer.
837: @item
838: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
839: from the history buffer.
840: @item
841: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
842: @item
843: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
844: @item
845: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
846: closing up the line.
847: @item
848: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
849: @item
850: @kbd{Ctrl-a} to move the cursor to the start of the line.
851: @item
852: @kbd{Ctrl-e} to move the cursor to the end of the line.
853: @item
854: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
855: line.
856: @item
857: @key{TAB} to step through all possible full-word completions of the word
858: currently being typed.
859: @item
1.65 anton 860: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
861: using @code{bye}).
862: @item
863: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
864: character under the cursor.
1.48 anton 865: @end itemize
866:
867: When editing, displayable characters are inserted to the left of the
868: cursor position; the line is always in ``insert'' (as opposed to
869: ``overstrike'') mode.
870:
871: @cindex history file
872: @cindex @file{.gforth-history}
873: On Unix systems, the history file is @file{~/.gforth-history} by
874: default@footnote{i.e. it is stored in the user's home directory.}. You
875: can find out the name and location of your history file using:
876:
877: @example
878: history-file type \ Unix-class systems
879:
880: history-file type \ Other systems
881: history-dir type
882: @end example
883:
884: If you enter long definitions by hand, you can use a text editor to
885: paste them out of the history file into a Forth source file for reuse at
886: a later time.
887:
888: Gforth never trims the size of the history file, so you should do this
889: periodically, if necessary.
890:
891: @comment this is all defined in history.fs
892: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
893: @comment chosen?
894:
895:
896: @comment ----------------------------------------------
1.65 anton 897: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 898: @section Environment variables
899: @cindex environment variables
900:
901: Gforth uses these environment variables:
902:
903: @itemize @bullet
904: @item
905: @cindex @code{GFORTHHIST} -- environment variable
906: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
907: open/create the history file, @file{.gforth-history}. Default:
908: @code{$HOME}.
909:
910: @item
911: @cindex @code{GFORTHPATH} -- environment variable
912: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
913: for Forth source-code files.
914:
915: @item
916: @cindex @code{GFORTH} -- environment variable
1.49 anton 917: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 918:
919: @item
920: @cindex @code{GFORTHD} -- environment variable
1.62 crook 921: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 922:
923: @item
924: @cindex @code{TMP}, @code{TEMP} - environment variable
925: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
926: location for the history file.
927: @end itemize
928:
929: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
930: @comment mentioning these.
931:
932: All the Gforth environment variables default to sensible values if they
933: are not set.
934:
935:
936: @comment ----------------------------------------------
1.112 anton 937: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 938: @section Gforth files
939: @cindex Gforth files
940:
941: When you install Gforth on a Unix system, it installs files in these
942: locations by default:
943:
944: @itemize @bullet
945: @item
946: @file{/usr/local/bin/gforth}
947: @item
948: @file{/usr/local/bin/gforthmi}
949: @item
950: @file{/usr/local/man/man1/gforth.1} - man page.
951: @item
952: @file{/usr/local/info} - the Info version of this manual.
953: @item
954: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
955: @item
956: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
957: @item
958: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
959: @item
960: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
961: @end itemize
962:
963: You can select different places for installation by using
964: @code{configure} options (listed with @code{configure --help}).
965:
966: @comment ----------------------------------------------
1.112 anton 967: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
968: @section Gforth in pipes
969: @cindex pipes, Gforth as part of
970:
971: Gforth can be used in pipes created elsewhere (described here). It can
972: also create pipes on its own (@pxref{Pipes}).
973:
974: @cindex input from pipes
975: If you pipe into Gforth, your program should read with @code{read-file}
976: or @code{read-line} from @code{stdin} (@pxref{General files}).
977: @code{Key} does not recognize the end of input. Words like
978: @code{accept} echo the input and are therefore usually not useful for
979: reading from a pipe. You have to invoke the Forth program with an OS
980: command-line option, as you have no chance to use the Forth command line
981: (the text interpreter would try to interpret the pipe input).
982:
983: @cindex output in pipes
984: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
985:
986: @cindex silent exiting from Gforth
987: When you write to a pipe that has been closed at the other end, Gforth
988: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
989: into the exception @code{broken-pipe-error}. If your application does
990: not catch that exception, the system catches it and exits, usually
991: silently (unless you were working on the Forth command line; then it
992: prints an error message and exits). This is usually the desired
993: behaviour.
994:
995: If you do not like this behaviour, you have to catch the exception
996: yourself, and react to it.
997:
998: Here's an example of an invocation of Gforth that is usable in a pipe:
999:
1000: @example
1001: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1002: type repeat ; foo bye"
1003: @end example
1004:
1005: This example just copies the input verbatim to the output. A very
1006: simple pipe containing this example looks like this:
1007:
1008: @example
1009: cat startup.fs |
1010: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1011: type repeat ; foo bye"|
1012: head
1013: @end example
1014:
1015: @cindex stderr and pipes
1016: Pipes involving Gforth's @code{stderr} output do not work.
1017:
1018: @comment ----------------------------------------------
1019: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1020: @section Startup speed
1021: @cindex Startup speed
1022: @cindex speed, startup
1023:
1024: If Gforth is used for CGI scripts or in shell scripts, its startup
1025: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1026: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1027: system time.
1028:
1029: If startup speed is a problem, you may consider the following ways to
1030: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1031: (for example, by using Fast-CGI).
1.48 anton 1032:
1.112 anton 1033: An easy step that influences Gforth startup speed is the use of the
1034: @option{--no-dynamic} option; this decreases image loading speed, but
1035: increases compile-time and run-time.
1036:
1037: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1038: building it with @code{XLDFLAGS=-static}. This requires more memory for
1039: the code and will therefore slow down the first invocation, but
1040: subsequent invocations avoid the dynamic linking overhead. Another
1041: disadvantage is that Gforth won't profit from library upgrades. As a
1042: result, @code{gforth-static -e bye} takes about 17.1ms user and
1043: 8.2ms system time.
1044:
1045: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1046: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1047: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1048: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1049: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1050: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1051: address for the dictionary, for whatever reason; so you better provide a
1052: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1053: bye} takes about 15.3ms user and 7.5ms system time.
1054:
1055: The final step is to disable dictionary hashing in Gforth. Gforth
1056: builds the hash table on startup, which takes much of the startup
1057: overhead. You can do this by commenting out the @code{include hash.fs}
1058: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1059: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1060: The disadvantages are that functionality like @code{table} and
1061: @code{ekey} is missing and that text interpretation (e.g., compiling)
1062: now takes much longer. So, you should only use this method if there is
1063: no significant text interpretation to perform (the script should be
1.62 crook 1064: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1065: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1066:
1067: @c ******************************************************************
1068: @node Tutorial, Introduction, Gforth Environment, Top
1069: @chapter Forth Tutorial
1070: @cindex Tutorial
1071: @cindex Forth Tutorial
1072:
1.67 anton 1073: @c Topics from nac's Introduction that could be mentioned:
1074: @c press <ret> after each line
1075: @c Prompt
1076: @c numbers vs. words in dictionary on text interpretation
1077: @c what happens on redefinition
1078: @c parsing words (in particular, defining words)
1079:
1.83 anton 1080: The difference of this chapter from the Introduction
1081: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1082: be used while sitting in front of a computer, and covers much more
1083: material, but does not explain how the Forth system works.
1084:
1.62 crook 1085: This tutorial can be used with any ANS-compliant Forth; any
1086: Gforth-specific features are marked as such and you can skip them if you
1087: work with another Forth. This tutorial does not explain all features of
1088: Forth, just enough to get you started and give you some ideas about the
1089: facilities available in Forth. Read the rest of the manual and the
1090: standard when you are through this.
1.48 anton 1091:
1092: The intended way to use this tutorial is that you work through it while
1093: sitting in front of the console, take a look at the examples and predict
1094: what they will do, then try them out; if the outcome is not as expected,
1095: find out why (e.g., by trying out variations of the example), so you
1096: understand what's going on. There are also some assignments that you
1097: should solve.
1098:
1099: This tutorial assumes that you have programmed before and know what,
1100: e.g., a loop is.
1101:
1102: @c !! explain compat library
1103:
1104: @menu
1105: * Starting Gforth Tutorial::
1106: * Syntax Tutorial::
1107: * Crash Course Tutorial::
1108: * Stack Tutorial::
1109: * Arithmetics Tutorial::
1110: * Stack Manipulation Tutorial::
1111: * Using files for Forth code Tutorial::
1112: * Comments Tutorial::
1113: * Colon Definitions Tutorial::
1114: * Decompilation Tutorial::
1115: * Stack-Effect Comments Tutorial::
1116: * Types Tutorial::
1117: * Factoring Tutorial::
1118: * Designing the stack effect Tutorial::
1119: * Local Variables Tutorial::
1120: * Conditional execution Tutorial::
1121: * Flags and Comparisons Tutorial::
1122: * General Loops Tutorial::
1123: * Counted loops Tutorial::
1124: * Recursion Tutorial::
1125: * Leaving definitions or loops Tutorial::
1126: * Return Stack Tutorial::
1127: * Memory Tutorial::
1128: * Characters and Strings Tutorial::
1129: * Alignment Tutorial::
1.87 anton 1130: * Files Tutorial::
1.48 anton 1131: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1132: * Execution Tokens Tutorial::
1133: * Exceptions Tutorial::
1134: * Defining Words Tutorial::
1135: * Arrays and Records Tutorial::
1136: * POSTPONE Tutorial::
1137: * Literal Tutorial::
1138: * Advanced macros Tutorial::
1139: * Compilation Tokens Tutorial::
1140: * Wordlists and Search Order Tutorial::
1141: @end menu
1142:
1143: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1144: @section Starting Gforth
1.66 anton 1145: @cindex starting Gforth tutorial
1.48 anton 1146: You can start Gforth by typing its name:
1147:
1148: @example
1149: gforth
1150: @end example
1151:
1152: That puts you into interactive mode; you can leave Gforth by typing
1153: @code{bye}. While in Gforth, you can edit the command line and access
1154: the command line history with cursor keys, similar to bash.
1155:
1156:
1157: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1158: @section Syntax
1.66 anton 1159: @cindex syntax tutorial
1.48 anton 1160:
1161: A @dfn{word} is a sequence of arbitrary characters (expcept white
1162: space). Words are separated by white space. E.g., each of the
1163: following lines contains exactly one word:
1164:
1165: @example
1166: word
1167: !@@#$%^&*()
1168: 1234567890
1169: 5!a
1170: @end example
1171:
1172: A frequent beginner's error is to leave away necessary white space,
1173: resulting in an error like @samp{Undefined word}; so if you see such an
1174: error, check if you have put spaces wherever necessary.
1175:
1176: @example
1177: ." hello, world" \ correct
1178: ."hello, world" \ gives an "Undefined word" error
1179: @end example
1180:
1.65 anton 1181: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1182: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1183: your system is case-sensitive, you may have to type all the examples
1184: given here in upper case.
1185:
1186:
1187: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1188: @section Crash Course
1189:
1190: Type
1191:
1192: @example
1193: 0 0 !
1194: here execute
1195: ' catch >body 20 erase abort
1196: ' (quit) >body 20 erase
1197: @end example
1198:
1199: The last two examples are guaranteed to destroy parts of Gforth (and
1200: most other systems), so you better leave Gforth afterwards (if it has
1201: not finished by itself). On some systems you may have to kill gforth
1202: from outside (e.g., in Unix with @code{kill}).
1203:
1204: Now that you know how to produce crashes (and that there's not much to
1205: them), let's learn how to produce meaningful programs.
1206:
1207:
1208: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1209: @section Stack
1.66 anton 1210: @cindex stack tutorial
1.48 anton 1211:
1212: The most obvious feature of Forth is the stack. When you type in a
1213: number, it is pushed on the stack. You can display the content of the
1214: stack with @code{.s}.
1215:
1216: @example
1217: 1 2 .s
1218: 3 .s
1219: @end example
1220:
1221: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1222: appear in @code{.s} output as they appeared in the input.
1223:
1224: You can print the top of stack element with @code{.}.
1225:
1226: @example
1227: 1 2 3 . . .
1228: @end example
1229:
1230: In general, words consume their stack arguments (@code{.s} is an
1231: exception).
1232:
1233: @assignment
1234: What does the stack contain after @code{5 6 7 .}?
1235: @endassignment
1236:
1237:
1238: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1239: @section Arithmetics
1.66 anton 1240: @cindex arithmetics tutorial
1.48 anton 1241:
1242: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1243: operate on the top two stack items:
1244:
1245: @example
1.67 anton 1246: 2 2 .s
1247: + .s
1248: .
1.48 anton 1249: 2 1 - .
1250: 7 3 mod .
1251: @end example
1252:
1253: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1254: as in the corresponding infix expression (this is generally the case in
1255: Forth).
1256:
1257: Parentheses are superfluous (and not available), because the order of
1258: the words unambiguously determines the order of evaluation and the
1259: operands:
1260:
1261: @example
1262: 3 4 + 5 * .
1263: 3 4 5 * + .
1264: @end example
1265:
1266: @assignment
1267: What are the infix expressions corresponding to the Forth code above?
1268: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1269: known as Postfix or RPN (Reverse Polish Notation).}.
1270: @endassignment
1271:
1272: To change the sign, use @code{negate}:
1273:
1274: @example
1275: 2 negate .
1276: @end example
1277:
1278: @assignment
1279: Convert -(-3)*4-5 to Forth.
1280: @endassignment
1281:
1282: @code{/mod} performs both @code{/} and @code{mod}.
1283:
1284: @example
1285: 7 3 /mod . .
1286: @end example
1287:
1.66 anton 1288: Reference: @ref{Arithmetic}.
1289:
1290:
1.48 anton 1291: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1292: @section Stack Manipulation
1.66 anton 1293: @cindex stack manipulation tutorial
1.48 anton 1294:
1295: Stack manipulation words rearrange the data on the stack.
1296:
1297: @example
1298: 1 .s drop .s
1299: 1 .s dup .s drop drop .s
1300: 1 2 .s over .s drop drop drop
1301: 1 2 .s swap .s drop drop
1302: 1 2 3 .s rot .s drop drop drop
1303: @end example
1304:
1305: These are the most important stack manipulation words. There are also
1306: variants that manipulate twice as many stack items:
1307:
1308: @example
1309: 1 2 3 4 .s 2swap .s 2drop 2drop
1310: @end example
1311:
1312: Two more stack manipulation words are:
1313:
1314: @example
1315: 1 2 .s nip .s drop
1316: 1 2 .s tuck .s 2drop drop
1317: @end example
1318:
1319: @assignment
1320: Replace @code{nip} and @code{tuck} with combinations of other stack
1321: manipulation words.
1322:
1323: @example
1324: Given: How do you get:
1325: 1 2 3 3 2 1
1326: 1 2 3 1 2 3 2
1327: 1 2 3 1 2 3 3
1328: 1 2 3 1 3 3
1329: 1 2 3 2 1 3
1330: 1 2 3 4 4 3 2 1
1331: 1 2 3 1 2 3 1 2 3
1332: 1 2 3 4 1 2 3 4 1 2
1333: 1 2 3
1334: 1 2 3 1 2 3 4
1335: 1 2 3 1 3
1336: @end example
1337: @endassignment
1338:
1339: @example
1340: 5 dup * .
1341: @end example
1342:
1343: @assignment
1344: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1345: Write a piece of Forth code that expects two numbers on the stack
1346: (@var{a} and @var{b}, with @var{b} on top) and computes
1347: @code{(a-b)(a+1)}.
1348: @endassignment
1349:
1.66 anton 1350: Reference: @ref{Stack Manipulation}.
1351:
1352:
1.48 anton 1353: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1354: @section Using files for Forth code
1.66 anton 1355: @cindex loading Forth code, tutorial
1356: @cindex files containing Forth code, tutorial
1.48 anton 1357:
1358: While working at the Forth command line is convenient for one-line
1359: examples and short one-off code, you probably want to store your source
1360: code in files for convenient editing and persistence. You can use your
1361: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1362: Gforth}) to create @var{file.fs} and use
1.48 anton 1363:
1364: @example
1.102 anton 1365: s" @var{file.fs}" included
1.48 anton 1366: @end example
1367:
1368: to load it into your Forth system. The file name extension I use for
1369: Forth files is @samp{.fs}.
1370:
1371: You can easily start Gforth with some files loaded like this:
1372:
1373: @example
1.102 anton 1374: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1375: @end example
1376:
1377: If an error occurs during loading these files, Gforth terminates,
1378: whereas an error during @code{INCLUDED} within Gforth usually gives you
1379: a Gforth command line. Starting the Forth system every time gives you a
1380: clean start every time, without interference from the results of earlier
1381: tries.
1382:
1383: I often put all the tests in a file, then load the code and run the
1384: tests with
1385:
1386: @example
1.102 anton 1387: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1388: @end example
1389:
1390: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1391: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1392: restart this command without ado.
1393:
1394: The advantage of this approach is that the tests can be repeated easily
1395: every time the program ist changed, making it easy to catch bugs
1396: introduced by the change.
1397:
1.66 anton 1398: Reference: @ref{Forth source files}.
1399:
1.48 anton 1400:
1401: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1402: @section Comments
1.66 anton 1403: @cindex comments tutorial
1.48 anton 1404:
1405: @example
1406: \ That's a comment; it ends at the end of the line
1407: ( Another comment; it ends here: ) .s
1408: @end example
1409:
1410: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1411: separated with white space from the following text.
1412:
1413: @example
1414: \This gives an "Undefined word" error
1415: @end example
1416:
1417: The first @code{)} ends a comment started with @code{(}, so you cannot
1418: nest @code{(}-comments; and you cannot comment out text containing a
1419: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1420: avoid @code{)} in word names.}.
1421:
1422: I use @code{\}-comments for descriptive text and for commenting out code
1423: of one or more line; I use @code{(}-comments for describing the stack
1424: effect, the stack contents, or for commenting out sub-line pieces of
1425: code.
1426:
1427: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1428: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1429: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1430: with @kbd{M-q}.
1431:
1.66 anton 1432: Reference: @ref{Comments}.
1433:
1.48 anton 1434:
1435: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1436: @section Colon Definitions
1.66 anton 1437: @cindex colon definitions, tutorial
1438: @cindex definitions, tutorial
1439: @cindex procedures, tutorial
1440: @cindex functions, tutorial
1.48 anton 1441:
1442: are similar to procedures and functions in other programming languages.
1443:
1444: @example
1445: : squared ( n -- n^2 )
1446: dup * ;
1447: 5 squared .
1448: 7 squared .
1449: @end example
1450:
1451: @code{:} starts the colon definition; its name is @code{squared}. The
1452: following comment describes its stack effect. The words @code{dup *}
1453: are not executed, but compiled into the definition. @code{;} ends the
1454: colon definition.
1455:
1456: The newly-defined word can be used like any other word, including using
1457: it in other definitions:
1458:
1459: @example
1460: : cubed ( n -- n^3 )
1461: dup squared * ;
1462: -5 cubed .
1463: : fourth-power ( n -- n^4 )
1464: squared squared ;
1465: 3 fourth-power .
1466: @end example
1467:
1468: @assignment
1469: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1470: @code{/mod} in terms of other Forth words, and check if they work (hint:
1471: test your tests on the originals first). Don't let the
1472: @samp{redefined}-Messages spook you, they are just warnings.
1473: @endassignment
1474:
1.66 anton 1475: Reference: @ref{Colon Definitions}.
1476:
1.48 anton 1477:
1478: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1479: @section Decompilation
1.66 anton 1480: @cindex decompilation tutorial
1481: @cindex see tutorial
1.48 anton 1482:
1483: You can decompile colon definitions with @code{see}:
1484:
1485: @example
1486: see squared
1487: see cubed
1488: @end example
1489:
1490: In Gforth @code{see} shows you a reconstruction of the source code from
1491: the executable code. Informations that were present in the source, but
1492: not in the executable code, are lost (e.g., comments).
1493:
1.65 anton 1494: You can also decompile the predefined words:
1495:
1496: @example
1497: see .
1498: see +
1499: @end example
1500:
1501:
1.48 anton 1502: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1503: @section Stack-Effect Comments
1.66 anton 1504: @cindex stack-effect comments, tutorial
1505: @cindex --, tutorial
1.48 anton 1506: By convention the comment after the name of a definition describes the
1507: stack effect: The part in from of the @samp{--} describes the state of
1508: the stack before the execution of the definition, i.e., the parameters
1509: that are passed into the colon definition; the part behind the @samp{--}
1510: is the state of the stack after the execution of the definition, i.e.,
1511: the results of the definition. The stack comment only shows the top
1512: stack items that the definition accesses and/or changes.
1513:
1514: You should put a correct stack effect on every definition, even if it is
1515: just @code{( -- )}. You should also add some descriptive comment to
1516: more complicated words (I usually do this in the lines following
1517: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 ! anton 1518: you have to work through every definition before you can understand
1.48 anton 1519: any).
1520:
1521: @assignment
1522: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1523: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1524: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1525: are done, you can compare your stack effects to those in this manual
1.48 anton 1526: (@pxref{Word Index}).
1527: @endassignment
1528:
1529: Sometimes programmers put comments at various places in colon
1530: definitions that describe the contents of the stack at that place (stack
1531: comments); i.e., they are like the first part of a stack-effect
1532: comment. E.g.,
1533:
1534: @example
1535: : cubed ( n -- n^3 )
1536: dup squared ( n n^2 ) * ;
1537: @end example
1538:
1539: In this case the stack comment is pretty superfluous, because the word
1540: is simple enough. If you think it would be a good idea to add such a
1541: comment to increase readability, you should also consider factoring the
1542: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1543: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1544: however, if you decide not to refactor it, then having such a comment is
1545: better than not having it.
1546:
1547: The names of the stack items in stack-effect and stack comments in the
1548: standard, in this manual, and in many programs specify the type through
1549: a type prefix, similar to Fortran and Hungarian notation. The most
1550: frequent prefixes are:
1551:
1552: @table @code
1553: @item n
1554: signed integer
1555: @item u
1556: unsigned integer
1557: @item c
1558: character
1559: @item f
1560: Boolean flags, i.e. @code{false} or @code{true}.
1561: @item a-addr,a-
1562: Cell-aligned address
1563: @item c-addr,c-
1564: Char-aligned address (note that a Char may have two bytes in Windows NT)
1565: @item xt
1566: Execution token, same size as Cell
1567: @item w,x
1568: Cell, can contain an integer or an address. It usually takes 32, 64 or
1569: 16 bits (depending on your platform and Forth system). A cell is more
1570: commonly known as machine word, but the term @emph{word} already means
1571: something different in Forth.
1572: @item d
1573: signed double-cell integer
1574: @item ud
1575: unsigned double-cell integer
1576: @item r
1577: Float (on the FP stack)
1578: @end table
1579:
1580: You can find a more complete list in @ref{Notation}.
1581:
1582: @assignment
1583: Write stack-effect comments for all definitions you have written up to
1584: now.
1585: @endassignment
1586:
1587:
1588: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1589: @section Types
1.66 anton 1590: @cindex types tutorial
1.48 anton 1591:
1592: In Forth the names of the operations are not overloaded; so similar
1593: operations on different types need different names; e.g., @code{+} adds
1594: integers, and you have to use @code{f+} to add floating-point numbers.
1595: The following prefixes are often used for related operations on
1596: different types:
1597:
1598: @table @code
1599: @item (none)
1600: signed integer
1601: @item u
1602: unsigned integer
1603: @item c
1604: character
1605: @item d
1606: signed double-cell integer
1607: @item ud, du
1608: unsigned double-cell integer
1609: @item 2
1610: two cells (not-necessarily double-cell numbers)
1611: @item m, um
1612: mixed single-cell and double-cell operations
1613: @item f
1614: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1615: and @samp{r} represents FP numbers).
1.48 anton 1616: @end table
1617:
1618: If there are no differences between the signed and the unsigned variant
1619: (e.g., for @code{+}), there is only the prefix-less variant.
1620:
1621: Forth does not perform type checking, neither at compile time, nor at
1622: run time. If you use the wrong oeration, the data are interpreted
1623: incorrectly:
1624:
1625: @example
1626: -1 u.
1627: @end example
1628:
1629: If you have only experience with type-checked languages until now, and
1630: have heard how important type-checking is, don't panic! In my
1631: experience (and that of other Forthers), type errors in Forth code are
1632: usually easy to find (once you get used to it), the increased vigilance
1633: of the programmer tends to catch some harder errors in addition to most
1634: type errors, and you never have to work around the type system, so in
1635: most situations the lack of type-checking seems to be a win (projects to
1636: add type checking to Forth have not caught on).
1637:
1638:
1639: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1640: @section Factoring
1.66 anton 1641: @cindex factoring tutorial
1.48 anton 1642:
1643: If you try to write longer definitions, you will soon find it hard to
1644: keep track of the stack contents. Therefore, good Forth programmers
1645: tend to write only short definitions (e.g., three lines). The art of
1646: finding meaningful short definitions is known as factoring (as in
1647: factoring polynomials).
1648:
1649: Well-factored programs offer additional advantages: smaller, more
1650: general words, are easier to test and debug and can be reused more and
1651: better than larger, specialized words.
1652:
1653: So, if you run into difficulties with stack management, when writing
1654: code, try to define meaningful factors for the word, and define the word
1655: in terms of those. Even if a factor contains only two words, it is
1656: often helpful.
1657:
1.65 anton 1658: Good factoring is not easy, and it takes some practice to get the knack
1659: for it; but even experienced Forth programmers often don't find the
1660: right solution right away, but only when rewriting the program. So, if
1661: you don't come up with a good solution immediately, keep trying, don't
1662: despair.
1.48 anton 1663:
1664: @c example !!
1665:
1666:
1667: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1668: @section Designing the stack effect
1.66 anton 1669: @cindex Stack effect design, tutorial
1670: @cindex design of stack effects, tutorial
1.48 anton 1671:
1672: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1673: function; and since there is only one result, you don't have to deal with
1.48 anton 1674: the order of results, either.
1675:
1.117 ! anton 1676: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1677: parameter and result order of a definition is important and should be
1678: designed well. The general guideline is to design the stack effect such
1679: that the word is simple to use in most cases, even if that complicates
1680: the implementation of the word. Some concrete rules are:
1681:
1682: @itemize @bullet
1683:
1684: @item
1685: Words consume all of their parameters (e.g., @code{.}).
1686:
1687: @item
1688: If there is a convention on the order of parameters (e.g., from
1689: mathematics or another programming language), stick with it (e.g.,
1690: @code{-}).
1691:
1692: @item
1693: If one parameter usually requires only a short computation (e.g., it is
1694: a constant), pass it on the top of the stack. Conversely, parameters
1695: that usually require a long sequence of code to compute should be passed
1696: as the bottom (i.e., first) parameter. This makes the code easier to
1697: read, because reader does not need to keep track of the bottom item
1698: through a long sequence of code (or, alternatively, through stack
1.49 anton 1699: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1700: address on top of the stack because it is usually simpler to compute
1701: than the stored value (often the address is just a variable).
1702:
1703: @item
1704: Similarly, results that are usually consumed quickly should be returned
1705: on the top of stack, whereas a result that is often used in long
1706: computations should be passed as bottom result. E.g., the file words
1707: like @code{open-file} return the error code on the top of stack, because
1708: it is usually consumed quickly by @code{throw}; moreover, the error code
1709: has to be checked before doing anything with the other results.
1710:
1711: @end itemize
1712:
1713: These rules are just general guidelines, don't lose sight of the overall
1714: goal to make the words easy to use. E.g., if the convention rule
1715: conflicts with the computation-length rule, you might decide in favour
1716: of the convention if the word will be used rarely, and in favour of the
1717: computation-length rule if the word will be used frequently (because
1718: with frequent use the cost of breaking the computation-length rule would
1719: be quite high, and frequent use makes it easier to remember an
1720: unconventional order).
1721:
1722: @c example !! structure package
1723:
1.65 anton 1724:
1.48 anton 1725: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1726: @section Local Variables
1.66 anton 1727: @cindex local variables, tutorial
1.48 anton 1728:
1729: You can define local variables (@emph{locals}) in a colon definition:
1730:
1731: @example
1732: : swap @{ a b -- b a @}
1733: b a ;
1734: 1 2 swap .s 2drop
1735: @end example
1736:
1737: (If your Forth system does not support this syntax, include
1738: @file{compat/anslocals.fs} first).
1739:
1740: In this example @code{@{ a b -- b a @}} is the locals definition; it
1741: takes two cells from the stack, puts the top of stack in @code{b} and
1742: the next stack element in @code{a}. @code{--} starts a comment ending
1743: with @code{@}}. After the locals definition, using the name of the
1744: local will push its value on the stack. You can leave the comment
1745: part (@code{-- b a}) away:
1746:
1747: @example
1748: : swap ( x1 x2 -- x2 x1 )
1749: @{ a b @} b a ;
1750: @end example
1751:
1752: In Gforth you can have several locals definitions, anywhere in a colon
1753: definition; in contrast, in a standard program you can have only one
1754: locals definition per colon definition, and that locals definition must
1755: be outside any controll structure.
1756:
1757: With locals you can write slightly longer definitions without running
1758: into stack trouble. However, I recommend trying to write colon
1759: definitions without locals for exercise purposes to help you gain the
1760: essential factoring skills.
1761:
1762: @assignment
1763: Rewrite your definitions until now with locals
1764: @endassignment
1765:
1.66 anton 1766: Reference: @ref{Locals}.
1767:
1.48 anton 1768:
1769: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1770: @section Conditional execution
1.66 anton 1771: @cindex conditionals, tutorial
1772: @cindex if, tutorial
1.48 anton 1773:
1774: In Forth you can use control structures only inside colon definitions.
1775: An @code{if}-structure looks like this:
1776:
1777: @example
1778: : abs ( n1 -- +n2 )
1779: dup 0 < if
1780: negate
1781: endif ;
1782: 5 abs .
1783: -5 abs .
1784: @end example
1785:
1786: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1787: the following code is performed, otherwise execution continues after the
1.51 pazsan 1788: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1789: elements and prioduces a flag:
1790:
1791: @example
1792: 1 2 < .
1793: 2 1 < .
1794: 1 1 < .
1795: @end example
1796:
1797: Actually the standard name for @code{endif} is @code{then}. This
1798: tutorial presents the examples using @code{endif}, because this is often
1799: less confusing for people familiar with other programming languages
1800: where @code{then} has a different meaning. If your system does not have
1801: @code{endif}, define it with
1802:
1803: @example
1804: : endif postpone then ; immediate
1805: @end example
1806:
1807: You can optionally use an @code{else}-part:
1808:
1809: @example
1810: : min ( n1 n2 -- n )
1811: 2dup < if
1812: drop
1813: else
1814: nip
1815: endif ;
1816: 2 3 min .
1817: 3 2 min .
1818: @end example
1819:
1820: @assignment
1821: Write @code{min} without @code{else}-part (hint: what's the definition
1822: of @code{nip}?).
1823: @endassignment
1824:
1.66 anton 1825: Reference: @ref{Selection}.
1826:
1.48 anton 1827:
1828: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1829: @section Flags and Comparisons
1.66 anton 1830: @cindex flags tutorial
1831: @cindex comparison tutorial
1.48 anton 1832:
1833: In a false-flag all bits are clear (0 when interpreted as integer). In
1834: a canonical true-flag all bits are set (-1 as a twos-complement signed
1835: integer); in many contexts (e.g., @code{if}) any non-zero value is
1836: treated as true flag.
1837:
1838: @example
1839: false .
1840: true .
1841: true hex u. decimal
1842: @end example
1843:
1844: Comparison words produce canonical flags:
1845:
1846: @example
1847: 1 1 = .
1848: 1 0= .
1849: 0 1 < .
1850: 0 0 < .
1851: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1852: -1 1 < .
1853: @end example
1854:
1.66 anton 1855: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1856: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1857: these combinations are standard (for details see the standard,
1858: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1859:
1860: You can use @code{and or xor invert} can be used as operations on
1861: canonical flags. Actually they are bitwise operations:
1862:
1863: @example
1864: 1 2 and .
1865: 1 2 or .
1866: 1 3 xor .
1867: 1 invert .
1868: @end example
1869:
1870: You can convert a zero/non-zero flag into a canonical flag with
1871: @code{0<>} (and complement it on the way with @code{0=}).
1872:
1873: @example
1874: 1 0= .
1875: 1 0<> .
1876: @end example
1877:
1.65 anton 1878: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1879: operation of the Boolean operations to avoid @code{if}s:
1880:
1881: @example
1882: : foo ( n1 -- n2 )
1883: 0= if
1884: 14
1885: else
1886: 0
1887: endif ;
1888: 0 foo .
1889: 1 foo .
1890:
1891: : foo ( n1 -- n2 )
1892: 0= 14 and ;
1893: 0 foo .
1894: 1 foo .
1895: @end example
1896:
1897: @assignment
1898: Write @code{min} without @code{if}.
1899: @endassignment
1900:
1.66 anton 1901: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1902: @ref{Bitwise operations}.
1903:
1.48 anton 1904:
1905: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1906: @section General Loops
1.66 anton 1907: @cindex loops, indefinite, tutorial
1.48 anton 1908:
1909: The endless loop is the most simple one:
1910:
1911: @example
1912: : endless ( -- )
1913: 0 begin
1914: dup . 1+
1915: again ;
1916: endless
1917: @end example
1918:
1919: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
1920: does nothing at run-time, @code{again} jumps back to @code{begin}.
1921:
1922: A loop with one exit at any place looks like this:
1923:
1924: @example
1925: : log2 ( +n1 -- n2 )
1926: \ logarithmus dualis of n1>0, rounded down to the next integer
1927: assert( dup 0> )
1928: 2/ 0 begin
1929: over 0> while
1930: 1+ swap 2/ swap
1931: repeat
1932: nip ;
1933: 7 log2 .
1934: 8 log2 .
1935: @end example
1936:
1937: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 1938: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 1939: continues behind the @code{while}. @code{Repeat} jumps back to
1940: @code{begin}, just like @code{again}.
1941:
1942: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 1943: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 1944: one bit (arithmetic shift right):
1945:
1946: @example
1947: -5 2 / .
1948: -5 2/ .
1949: @end example
1950:
1951: @code{assert(} is no standard word, but you can get it on systems other
1952: then Gforth by including @file{compat/assert.fs}. You can see what it
1953: does by trying
1954:
1955: @example
1956: 0 log2 .
1957: @end example
1958:
1959: Here's a loop with an exit at the end:
1960:
1961: @example
1962: : log2 ( +n1 -- n2 )
1963: \ logarithmus dualis of n1>0, rounded down to the next integer
1964: assert( dup 0 > )
1965: -1 begin
1966: 1+ swap 2/ swap
1967: over 0 <=
1968: until
1969: nip ;
1970: @end example
1971:
1972: @code{Until} consumes a flag; if it is non-zero, execution continues at
1973: the @code{begin}, otherwise after the @code{until}.
1974:
1975: @assignment
1976: Write a definition for computing the greatest common divisor.
1977: @endassignment
1978:
1.66 anton 1979: Reference: @ref{Simple Loops}.
1980:
1.48 anton 1981:
1982: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
1983: @section Counted loops
1.66 anton 1984: @cindex loops, counted, tutorial
1.48 anton 1985:
1986: @example
1987: : ^ ( n1 u -- n )
1988: \ n = the uth power of u1
1989: 1 swap 0 u+do
1990: over *
1991: loop
1992: nip ;
1993: 3 2 ^ .
1994: 4 3 ^ .
1995: @end example
1996:
1997: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
1998: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
1999: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2000: times (or not at all, if @code{u3-u4<0}).
2001:
2002: You can see the stack effect design rules at work in the stack effect of
2003: the loop start words: Since the start value of the loop is more
2004: frequently constant than the end value, the start value is passed on
2005: the top-of-stack.
2006:
2007: You can access the counter of a counted loop with @code{i}:
2008:
2009: @example
2010: : fac ( u -- u! )
2011: 1 swap 1+ 1 u+do
2012: i *
2013: loop ;
2014: 5 fac .
2015: 7 fac .
2016: @end example
2017:
2018: There is also @code{+do}, which expects signed numbers (important for
2019: deciding whether to enter the loop).
2020:
2021: @assignment
2022: Write a definition for computing the nth Fibonacci number.
2023: @endassignment
2024:
1.65 anton 2025: You can also use increments other than 1:
2026:
2027: @example
2028: : up2 ( n1 n2 -- )
2029: +do
2030: i .
2031: 2 +loop ;
2032: 10 0 up2
2033:
2034: : down2 ( n1 n2 -- )
2035: -do
2036: i .
2037: 2 -loop ;
2038: 0 10 down2
2039: @end example
1.48 anton 2040:
1.66 anton 2041: Reference: @ref{Counted Loops}.
2042:
1.48 anton 2043:
2044: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2045: @section Recursion
1.66 anton 2046: @cindex recursion tutorial
1.48 anton 2047:
2048: Usually the name of a definition is not visible in the definition; but
2049: earlier definitions are usually visible:
2050:
2051: @example
2052: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2053: : / ( n1 n2 -- n )
2054: dup 0= if
2055: -10 throw \ report division by zero
2056: endif
2057: / \ old version
2058: ;
2059: 1 0 /
2060: @end example
2061:
2062: For recursive definitions you can use @code{recursive} (non-standard) or
2063: @code{recurse}:
2064:
2065: @example
2066: : fac1 ( n -- n! ) recursive
2067: dup 0> if
2068: dup 1- fac1 *
2069: else
2070: drop 1
2071: endif ;
2072: 7 fac1 .
2073:
2074: : fac2 ( n -- n! )
2075: dup 0> if
2076: dup 1- recurse *
2077: else
2078: drop 1
2079: endif ;
2080: 8 fac2 .
2081: @end example
2082:
2083: @assignment
2084: Write a recursive definition for computing the nth Fibonacci number.
2085: @endassignment
2086:
1.66 anton 2087: Reference (including indirect recursion): @xref{Calls and returns}.
2088:
1.48 anton 2089:
2090: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2091: @section Leaving definitions or loops
1.66 anton 2092: @cindex leaving definitions, tutorial
2093: @cindex leaving loops, tutorial
1.48 anton 2094:
2095: @code{EXIT} exits the current definition right away. For every counted
2096: loop that is left in this way, an @code{UNLOOP} has to be performed
2097: before the @code{EXIT}:
2098:
2099: @c !! real examples
2100: @example
2101: : ...
2102: ... u+do
2103: ... if
2104: ... unloop exit
2105: endif
2106: ...
2107: loop
2108: ... ;
2109: @end example
2110:
2111: @code{LEAVE} leaves the innermost counted loop right away:
2112:
2113: @example
2114: : ...
2115: ... u+do
2116: ... if
2117: ... leave
2118: endif
2119: ...
2120: loop
2121: ... ;
2122: @end example
2123:
1.65 anton 2124: @c !! example
1.48 anton 2125:
1.66 anton 2126: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2127:
2128:
1.48 anton 2129: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2130: @section Return Stack
1.66 anton 2131: @cindex return stack tutorial
1.48 anton 2132:
2133: In addition to the data stack Forth also has a second stack, the return
2134: stack; most Forth systems store the return addresses of procedure calls
2135: there (thus its name). Programmers can also use this stack:
2136:
2137: @example
2138: : foo ( n1 n2 -- )
2139: .s
2140: >r .s
1.50 anton 2141: r@@ .
1.48 anton 2142: >r .s
1.50 anton 2143: r@@ .
1.48 anton 2144: r> .
1.50 anton 2145: r@@ .
1.48 anton 2146: r> . ;
2147: 1 2 foo
2148: @end example
2149:
2150: @code{>r} takes an element from the data stack and pushes it onto the
2151: return stack; conversely, @code{r>} moves an elementm from the return to
2152: the data stack; @code{r@@} pushes a copy of the top of the return stack
2153: on the return stack.
2154:
2155: Forth programmers usually use the return stack for storing data
2156: temporarily, if using the data stack alone would be too complex, and
2157: factoring and locals are not an option:
2158:
2159: @example
2160: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2161: rot >r rot r> ;
2162: @end example
2163:
2164: The return address of the definition and the loop control parameters of
2165: counted loops usually reside on the return stack, so you have to take
2166: all items, that you have pushed on the return stack in a colon
2167: definition or counted loop, from the return stack before the definition
2168: or loop ends. You cannot access items that you pushed on the return
2169: stack outside some definition or loop within the definition of loop.
2170:
2171: If you miscount the return stack items, this usually ends in a crash:
2172:
2173: @example
2174: : crash ( n -- )
2175: >r ;
2176: 5 crash
2177: @end example
2178:
2179: You cannot mix using locals and using the return stack (according to the
2180: standard; Gforth has no problem). However, they solve the same
2181: problems, so this shouldn't be an issue.
2182:
2183: @assignment
2184: Can you rewrite any of the definitions you wrote until now in a better
2185: way using the return stack?
2186: @endassignment
2187:
1.66 anton 2188: Reference: @ref{Return stack}.
2189:
1.48 anton 2190:
2191: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2192: @section Memory
1.66 anton 2193: @cindex memory access/allocation tutorial
1.48 anton 2194:
2195: You can create a global variable @code{v} with
2196:
2197: @example
2198: variable v ( -- addr )
2199: @end example
2200:
2201: @code{v} pushes the address of a cell in memory on the stack. This cell
2202: was reserved by @code{variable}. You can use @code{!} (store) to store
2203: values into this cell and @code{@@} (fetch) to load the value from the
2204: stack into memory:
2205:
2206: @example
2207: v .
2208: 5 v ! .s
1.50 anton 2209: v @@ .
1.48 anton 2210: @end example
2211:
1.65 anton 2212: You can see a raw dump of memory with @code{dump}:
2213:
2214: @example
2215: v 1 cells .s dump
2216: @end example
2217:
2218: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2219: generally, address units (aus)) that @code{n1 cells} occupy. You can
2220: also reserve more memory:
1.48 anton 2221:
2222: @example
2223: create v2 20 cells allot
1.65 anton 2224: v2 20 cells dump
1.48 anton 2225: @end example
2226:
1.65 anton 2227: creates a word @code{v2} and reserves 20 uninitialized cells; the
2228: address pushed by @code{v2} points to the start of these 20 cells. You
2229: can use address arithmetic to access these cells:
1.48 anton 2230:
2231: @example
2232: 3 v2 5 cells + !
1.65 anton 2233: v2 20 cells dump
1.48 anton 2234: @end example
2235:
2236: You can reserve and initialize memory with @code{,}:
2237:
2238: @example
2239: create v3
2240: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2241: v3 @@ .
2242: v3 cell+ @@ .
2243: v3 2 cells + @@ .
1.65 anton 2244: v3 5 cells dump
1.48 anton 2245: @end example
2246:
2247: @assignment
2248: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2249: @code{u} cells, with the first of these cells at @code{addr}, the next
2250: one at @code{addr cell+} etc.
2251: @endassignment
2252:
2253: You can also reserve memory without creating a new word:
2254:
2255: @example
1.60 anton 2256: here 10 cells allot .
2257: here .
1.48 anton 2258: @end example
2259:
2260: @code{Here} pushes the start address of the memory area. You should
2261: store it somewhere, or you will have a hard time finding the memory area
2262: again.
2263:
2264: @code{Allot} manages dictionary memory. The dictionary memory contains
2265: the system's data structures for words etc. on Gforth and most other
2266: Forth systems. It is managed like a stack: You can free the memory that
2267: you have just @code{allot}ed with
2268:
2269: @example
2270: -10 cells allot
1.60 anton 2271: here .
1.48 anton 2272: @end example
2273:
2274: Note that you cannot do this if you have created a new word in the
2275: meantime (because then your @code{allot}ed memory is no longer on the
2276: top of the dictionary ``stack'').
2277:
2278: Alternatively, you can use @code{allocate} and @code{free} which allow
2279: freeing memory in any order:
2280:
2281: @example
2282: 10 cells allocate throw .s
2283: 20 cells allocate throw .s
2284: swap
2285: free throw
2286: free throw
2287: @end example
2288:
2289: The @code{throw}s deal with errors (e.g., out of memory).
2290:
1.65 anton 2291: And there is also a
2292: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2293: garbage collector}, which eliminates the need to @code{free} memory
2294: explicitly.
1.48 anton 2295:
1.66 anton 2296: Reference: @ref{Memory}.
2297:
1.48 anton 2298:
2299: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2300: @section Characters and Strings
1.66 anton 2301: @cindex strings tutorial
2302: @cindex characters tutorial
1.48 anton 2303:
2304: On the stack characters take up a cell, like numbers. In memory they
2305: have their own size (one 8-bit byte on most systems), and therefore
2306: require their own words for memory access:
2307:
2308: @example
2309: create v4
2310: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2311: v4 4 chars + c@@ .
1.65 anton 2312: v4 5 chars dump
1.48 anton 2313: @end example
2314:
2315: The preferred representation of strings on the stack is @code{addr
2316: u-count}, where @code{addr} is the address of the first character and
2317: @code{u-count} is the number of characters in the string.
2318:
2319: @example
2320: v4 5 type
2321: @end example
2322:
2323: You get a string constant with
2324:
2325: @example
2326: s" hello, world" .s
2327: type
2328: @end example
2329:
2330: Make sure you have a space between @code{s"} and the string; @code{s"}
2331: is a normal Forth word and must be delimited with white space (try what
2332: happens when you remove the space).
2333:
2334: However, this interpretive use of @code{s"} is quite restricted: the
2335: string exists only until the next call of @code{s"} (some Forth systems
2336: keep more than one of these strings, but usually they still have a
1.62 crook 2337: limited lifetime).
1.48 anton 2338:
2339: @example
2340: s" hello," s" world" .s
2341: type
2342: type
2343: @end example
2344:
1.62 crook 2345: You can also use @code{s"} in a definition, and the resulting
2346: strings then live forever (well, for as long as the definition):
1.48 anton 2347:
2348: @example
2349: : foo s" hello," s" world" ;
2350: foo .s
2351: type
2352: type
2353: @end example
2354:
2355: @assignment
2356: @code{Emit ( c -- )} types @code{c} as character (not a number).
2357: Implement @code{type ( addr u -- )}.
2358: @endassignment
2359:
1.66 anton 2360: Reference: @ref{Memory Blocks}.
2361:
2362:
1.84 pazsan 2363: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2364: @section Alignment
1.66 anton 2365: @cindex alignment tutorial
2366: @cindex memory alignment tutorial
1.48 anton 2367:
2368: On many processors cells have to be aligned in memory, if you want to
2369: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2370: not require alignment, access to aligned cells is faster).
1.48 anton 2371:
2372: @code{Create} aligns @code{here} (i.e., the place where the next
2373: allocation will occur, and that the @code{create}d word points to).
2374: Likewise, the memory produced by @code{allocate} starts at an aligned
2375: address. Adding a number of @code{cells} to an aligned address produces
2376: another aligned address.
2377:
2378: However, address arithmetic involving @code{char+} and @code{chars} can
2379: create an address that is not cell-aligned. @code{Aligned ( addr --
2380: a-addr )} produces the next aligned address:
2381:
2382: @example
1.50 anton 2383: v3 char+ aligned .s @@ .
2384: v3 char+ .s @@ .
1.48 anton 2385: @end example
2386:
2387: Similarly, @code{align} advances @code{here} to the next aligned
2388: address:
2389:
2390: @example
2391: create v5 97 c,
2392: here .
2393: align here .
2394: 1000 ,
2395: @end example
2396:
2397: Note that you should use aligned addresses even if your processor does
2398: not require them, if you want your program to be portable.
2399:
1.66 anton 2400: Reference: @ref{Address arithmetic}.
2401:
1.48 anton 2402:
1.84 pazsan 2403: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2404: @section Files
2405: @cindex files tutorial
2406:
2407: This section gives a short introduction into how to use files inside
2408: Forth. It's broken up into five easy steps:
2409:
2410: @enumerate 1
2411: @item Opened an ASCII text file for input
2412: @item Opened a file for output
2413: @item Read input file until string matched (or some other condition matched)
2414: @item Wrote some lines from input ( modified or not) to output
2415: @item Closed the files.
2416: @end enumerate
2417:
2418: @subsection Open file for input
2419:
2420: @example
2421: s" foo.in" r/o open-file throw Value fd-in
2422: @end example
2423:
2424: @subsection Create file for output
2425:
2426: @example
2427: s" foo.out" w/o create-file throw Value fd-out
2428: @end example
2429:
2430: The available file modes are r/o for read-only access, r/w for
2431: read-write access, and w/o for write-only access. You could open both
2432: files with r/w, too, if you like. All file words return error codes; for
2433: most applications, it's best to pass there error codes with @code{throw}
2434: to the outer error handler.
2435:
2436: If you want words for opening and assigning, define them as follows:
2437:
2438: @example
2439: 0 Value fd-in
2440: 0 Value fd-out
2441: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2442: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2443: @end example
2444:
2445: Usage example:
2446:
2447: @example
2448: s" foo.in" open-input
2449: s" foo.out" open-output
2450: @end example
2451:
2452: @subsection Scan file for a particular line
2453:
2454: @example
2455: 256 Constant max-line
2456: Create line-buffer max-line 2 + allot
2457:
2458: : scan-file ( addr u -- )
2459: begin
2460: line-buffer max-line fd-in read-line throw
2461: while
2462: >r 2dup line-buffer r> compare 0=
2463: until
2464: else
2465: drop
2466: then
2467: 2drop ;
2468: @end example
2469:
2470: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2471: the buffer at addr, and returns the number of bytes read, a flag that is
2472: false when the end of file is reached, and an error code.
1.84 pazsan 2473:
2474: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2475: returns zero if both strings are equal. It returns a positive number if
2476: the first string is lexically greater, a negative if the second string
2477: is lexically greater.
2478:
2479: We haven't seen this loop here; it has two exits. Since the @code{while}
2480: exits with the number of bytes read on the stack, we have to clean up
2481: that separately; that's after the @code{else}.
2482:
2483: Usage example:
2484:
2485: @example
2486: s" The text I search is here" scan-file
2487: @end example
2488:
2489: @subsection Copy input to output
2490:
2491: @example
2492: : copy-file ( -- )
2493: begin
2494: line-buffer max-line fd-in read-line throw
2495: while
2496: line-buffer swap fd-out write-file throw
2497: repeat ;
2498: @end example
2499:
2500: @subsection Close files
2501:
2502: @example
2503: fd-in close-file throw
2504: fd-out close-file throw
2505: @end example
2506:
2507: Likewise, you can put that into definitions, too:
2508:
2509: @example
2510: : close-input ( -- ) fd-in close-file throw ;
2511: : close-output ( -- ) fd-out close-file throw ;
2512: @end example
2513:
2514: @assignment
2515: How could you modify @code{copy-file} so that it copies until a second line is
2516: matched? Can you write a program that extracts a section of a text file,
2517: given the line that starts and the line that terminates that section?
2518: @endassignment
2519:
2520: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2521: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2522: @cindex semantics tutorial
2523: @cindex interpretation semantics tutorial
2524: @cindex compilation semantics tutorial
2525: @cindex immediate, tutorial
1.48 anton 2526:
2527: When a word is compiled, it behaves differently from being interpreted.
2528: E.g., consider @code{+}:
2529:
2530: @example
2531: 1 2 + .
2532: : foo + ;
2533: @end example
2534:
2535: These two behaviours are known as compilation and interpretation
2536: semantics. For normal words (e.g., @code{+}), the compilation semantics
2537: is to append the interpretation semantics to the currently defined word
2538: (@code{foo} in the example above). I.e., when @code{foo} is executed
2539: later, the interpretation semantics of @code{+} (i.e., adding two
2540: numbers) will be performed.
2541:
2542: However, there are words with non-default compilation semantics, e.g.,
2543: the control-flow words like @code{if}. You can use @code{immediate} to
2544: change the compilation semantics of the last defined word to be equal to
2545: the interpretation semantics:
2546:
2547: @example
2548: : [FOO] ( -- )
2549: 5 . ; immediate
2550:
2551: [FOO]
2552: : bar ( -- )
2553: [FOO] ;
2554: bar
2555: see bar
2556: @end example
2557:
2558: Two conventions to mark words with non-default compilation semnatics are
2559: names with brackets (more frequently used) and to write them all in
2560: upper case (less frequently used).
2561:
2562: In Gforth (and many other systems) you can also remove the
2563: interpretation semantics with @code{compile-only} (the compilation
2564: semantics is derived from the original interpretation semantics):
2565:
2566: @example
2567: : flip ( -- )
2568: 6 . ; compile-only \ but not immediate
2569: flip
2570:
2571: : flop ( -- )
2572: flip ;
2573: flop
2574: @end example
2575:
2576: In this example the interpretation semantics of @code{flop} is equal to
2577: the original interpretation semantics of @code{flip}.
2578:
2579: The text interpreter has two states: in interpret state, it performs the
2580: interpretation semantics of words it encounters; in compile state, it
2581: performs the compilation semantics of these words.
2582:
2583: Among other things, @code{:} switches into compile state, and @code{;}
2584: switches back to interpret state. They contain the factors @code{]}
2585: (switch to compile state) and @code{[} (switch to interpret state), that
2586: do nothing but switch the state.
2587:
2588: @example
2589: : xxx ( -- )
2590: [ 5 . ]
2591: ;
2592:
2593: xxx
2594: see xxx
2595: @end example
2596:
2597: These brackets are also the source of the naming convention mentioned
2598: above.
2599:
1.66 anton 2600: Reference: @ref{Interpretation and Compilation Semantics}.
2601:
1.48 anton 2602:
2603: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2604: @section Execution Tokens
1.66 anton 2605: @cindex execution tokens tutorial
2606: @cindex XT tutorial
1.48 anton 2607:
2608: @code{' word} gives you the execution token (XT) of a word. The XT is a
2609: cell representing the interpretation semantics of a word. You can
2610: execute this semantics with @code{execute}:
2611:
2612: @example
2613: ' + .s
2614: 1 2 rot execute .
2615: @end example
2616:
2617: The XT is similar to a function pointer in C. However, parameter
2618: passing through the stack makes it a little more flexible:
2619:
2620: @example
2621: : map-array ( ... addr u xt -- ... )
1.50 anton 2622: \ executes xt ( ... x -- ... ) for every element of the array starting
2623: \ at addr and containing u elements
1.48 anton 2624: @{ xt @}
2625: cells over + swap ?do
1.50 anton 2626: i @@ xt execute
1.48 anton 2627: 1 cells +loop ;
2628:
2629: create a 3 , 4 , 2 , -1 , 4 ,
2630: a 5 ' . map-array .s
2631: 0 a 5 ' + map-array .
2632: s" max-n" environment? drop .s
2633: a 5 ' min map-array .
2634: @end example
2635:
2636: You can use map-array with the XTs of words that consume one element
2637: more than they produce. In theory you can also use it with other XTs,
2638: but the stack effect then depends on the size of the array, which is
2639: hard to understand.
2640:
1.51 pazsan 2641: Since XTs are cell-sized, you can store them in memory and manipulate
2642: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2643: word with @code{compile,}:
2644:
2645: @example
2646: : foo1 ( n1 n2 -- n )
2647: [ ' + compile, ] ;
2648: see foo
2649: @end example
2650:
2651: This is non-standard, because @code{compile,} has no compilation
2652: semantics in the standard, but it works in good Forth systems. For the
2653: broken ones, use
2654:
2655: @example
2656: : [compile,] compile, ; immediate
2657:
2658: : foo1 ( n1 n2 -- n )
2659: [ ' + ] [compile,] ;
2660: see foo
2661: @end example
2662:
2663: @code{'} is a word with default compilation semantics; it parses the
2664: next word when its interpretation semantics are executed, not during
2665: compilation:
2666:
2667: @example
2668: : foo ( -- xt )
2669: ' ;
2670: see foo
2671: : bar ( ... "word" -- ... )
2672: ' execute ;
2673: see bar
1.60 anton 2674: 1 2 bar + .
1.48 anton 2675: @end example
2676:
2677: You often want to parse a word during compilation and compile its XT so
2678: it will be pushed on the stack at run-time. @code{[']} does this:
2679:
2680: @example
2681: : xt-+ ( -- xt )
2682: ['] + ;
2683: see xt-+
2684: 1 2 xt-+ execute .
2685: @end example
2686:
2687: Many programmers tend to see @code{'} and the word it parses as one
2688: unit, and expect it to behave like @code{[']} when compiled, and are
2689: confused by the actual behaviour. If you are, just remember that the
2690: Forth system just takes @code{'} as one unit and has no idea that it is
2691: a parsing word (attempts to convenience programmers in this issue have
2692: usually resulted in even worse pitfalls, see
1.66 anton 2693: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2694: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2695:
2696: Note that the state of the interpreter does not come into play when
1.51 pazsan 2697: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2698: compile state, it still gives you the interpretation semantics. And
2699: whatever that state is, @code{execute} performs the semantics
1.66 anton 2700: represented by the XT (i.e., for XTs produced with @code{'} the
2701: interpretation semantics).
2702:
2703: Reference: @ref{Tokens for Words}.
1.48 anton 2704:
2705:
2706: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2707: @section Exceptions
1.66 anton 2708: @cindex exceptions tutorial
1.48 anton 2709:
2710: @code{throw ( n -- )} causes an exception unless n is zero.
2711:
2712: @example
2713: 100 throw .s
2714: 0 throw .s
2715: @end example
2716:
2717: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2718: it catches exceptions and pushes the number of the exception on the
2719: stack (or 0, if the xt executed without exception). If there was an
2720: exception, the stacks have the same depth as when entering @code{catch}:
2721:
2722: @example
2723: .s
2724: 3 0 ' / catch .s
2725: 3 2 ' / catch .s
2726: @end example
2727:
2728: @assignment
2729: Try the same with @code{execute} instead of @code{catch}.
2730: @endassignment
2731:
2732: @code{Throw} always jumps to the dynamically next enclosing
2733: @code{catch}, even if it has to leave several call levels to achieve
2734: this:
2735:
2736: @example
2737: : foo 100 throw ;
2738: : foo1 foo ." after foo" ;
1.51 pazsan 2739: : bar ['] foo1 catch ;
1.60 anton 2740: bar .
1.48 anton 2741: @end example
2742:
2743: It is often important to restore a value upon leaving a definition, even
2744: if the definition is left through an exception. You can ensure this
2745: like this:
2746:
2747: @example
2748: : ...
2749: save-x
1.51 pazsan 2750: ['] word-changing-x catch ( ... n )
1.48 anton 2751: restore-x
2752: ( ... n ) throw ;
2753: @end example
2754:
1.55 anton 2755: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2756: @code{try ... recover ... endtry}. If the code between @code{try} and
2757: @code{recover} has an exception, the stack depths are restored, the
2758: exception number is pushed on the stack, and the code between
2759: @code{recover} and @code{endtry} is performed. E.g., the definition for
2760: @code{catch} is
2761:
2762: @example
2763: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2764: try
2765: execute 0
2766: recover
2767: nip
2768: endtry ;
2769: @end example
2770:
2771: The equivalent to the restoration code above is
2772:
2773: @example
2774: : ...
2775: save-x
2776: try
1.92 anton 2777: word-changing-x 0
2778: recover endtry
1.48 anton 2779: restore-x
2780: throw ;
2781: @end example
2782:
1.92 anton 2783: This works if @code{word-changing-x} does not change the stack depth,
2784: otherwise you should add some code between @code{recover} and
2785: @code{endtry} to balance the stack.
1.48 anton 2786:
1.66 anton 2787: Reference: @ref{Exception Handling}.
2788:
1.48 anton 2789:
2790: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2791: @section Defining Words
1.66 anton 2792: @cindex defining words tutorial
2793: @cindex does> tutorial
2794: @cindex create...does> tutorial
2795:
2796: @c before semantics?
1.48 anton 2797:
2798: @code{:}, @code{create}, and @code{variable} are definition words: They
2799: define other words. @code{Constant} is another definition word:
2800:
2801: @example
2802: 5 constant foo
2803: foo .
2804: @end example
2805:
2806: You can also use the prefixes @code{2} (double-cell) and @code{f}
2807: (floating point) with @code{variable} and @code{constant}.
2808:
2809: You can also define your own defining words. E.g.:
2810:
2811: @example
2812: : variable ( "name" -- )
2813: create 0 , ;
2814: @end example
2815:
2816: You can also define defining words that create words that do something
2817: other than just producing their address:
2818:
2819: @example
2820: : constant ( n "name" -- )
2821: create ,
2822: does> ( -- n )
1.50 anton 2823: ( addr ) @@ ;
1.48 anton 2824:
2825: 5 constant foo
2826: foo .
2827: @end example
2828:
2829: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2830: @code{does>} replaces @code{;}, but it also does something else: It
2831: changes the last defined word such that it pushes the address of the
2832: body of the word and then performs the code after the @code{does>}
2833: whenever it is called.
2834:
2835: In the example above, @code{constant} uses @code{,} to store 5 into the
2836: body of @code{foo}. When @code{foo} executes, it pushes the address of
2837: the body onto the stack, then (in the code after the @code{does>})
2838: fetches the 5 from there.
2839:
2840: The stack comment near the @code{does>} reflects the stack effect of the
2841: defined word, not the stack effect of the code after the @code{does>}
2842: (the difference is that the code expects the address of the body that
2843: the stack comment does not show).
2844:
2845: You can use these definition words to do factoring in cases that involve
2846: (other) definition words. E.g., a field offset is always added to an
2847: address. Instead of defining
2848:
2849: @example
2850: 2 cells constant offset-field1
2851: @end example
2852:
2853: and using this like
2854:
2855: @example
2856: ( addr ) offset-field1 +
2857: @end example
2858:
2859: you can define a definition word
2860:
2861: @example
2862: : simple-field ( n "name" -- )
2863: create ,
2864: does> ( n1 -- n1+n )
1.50 anton 2865: ( addr ) @@ + ;
1.48 anton 2866: @end example
1.21 crook 2867:
1.48 anton 2868: Definition and use of field offsets now look like this:
1.21 crook 2869:
1.48 anton 2870: @example
2871: 2 cells simple-field field1
1.60 anton 2872: create mystruct 4 cells allot
2873: mystruct .s field1 .s drop
1.48 anton 2874: @end example
1.21 crook 2875:
1.48 anton 2876: If you want to do something with the word without performing the code
2877: after the @code{does>}, you can access the body of a @code{create}d word
2878: with @code{>body ( xt -- addr )}:
1.21 crook 2879:
1.48 anton 2880: @example
2881: : value ( n "name" -- )
2882: create ,
2883: does> ( -- n1 )
1.50 anton 2884: @@ ;
1.48 anton 2885: : to ( n "name" -- )
2886: ' >body ! ;
1.21 crook 2887:
1.48 anton 2888: 5 value foo
2889: foo .
2890: 7 to foo
2891: foo .
2892: @end example
1.21 crook 2893:
1.48 anton 2894: @assignment
2895: Define @code{defer ( "name" -- )}, which creates a word that stores an
2896: XT (at the start the XT of @code{abort}), and upon execution
2897: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2898: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2899: recursion is one application of @code{defer}.
2900: @endassignment
1.29 crook 2901:
1.66 anton 2902: Reference: @ref{User-defined Defining Words}.
2903:
2904:
1.48 anton 2905: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2906: @section Arrays and Records
1.66 anton 2907: @cindex arrays tutorial
2908: @cindex records tutorial
2909: @cindex structs tutorial
1.29 crook 2910:
1.48 anton 2911: Forth has no standard words for defining data structures such as arrays
2912: and records (structs in C terminology), but you can build them yourself
2913: based on address arithmetic. You can also define words for defining
2914: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 2915:
1.48 anton 2916: One of the first projects a Forth newcomer sets out upon when learning
2917: about defining words is an array defining word (possibly for
2918: n-dimensional arrays). Go ahead and do it, I did it, too; you will
2919: learn something from it. However, don't be disappointed when you later
2920: learn that you have little use for these words (inappropriate use would
2921: be even worse). I have not yet found a set of useful array words yet;
2922: the needs are just too diverse, and named, global arrays (the result of
2923: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 2924: consider how to pass them as parameters). Another such project is a set
2925: of words to help dealing with strings.
1.29 crook 2926:
1.48 anton 2927: On the other hand, there is a useful set of record words, and it has
2928: been defined in @file{compat/struct.fs}; these words are predefined in
2929: Gforth. They are explained in depth elsewhere in this manual (see
2930: @pxref{Structures}). The @code{simple-field} example above is
2931: simplified variant of fields in this package.
1.21 crook 2932:
2933:
1.48 anton 2934: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
2935: @section @code{POSTPONE}
1.66 anton 2936: @cindex postpone tutorial
1.21 crook 2937:
1.48 anton 2938: You can compile the compilation semantics (instead of compiling the
2939: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 2940:
1.48 anton 2941: @example
2942: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 2943: POSTPONE + ; immediate
1.48 anton 2944: : foo ( n1 n2 -- n )
2945: MY-+ ;
2946: 1 2 foo .
2947: see foo
2948: @end example
1.21 crook 2949:
1.48 anton 2950: During the definition of @code{foo} the text interpreter performs the
2951: compilation semantics of @code{MY-+}, which performs the compilation
2952: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
2953:
2954: This example also displays separate stack comments for the compilation
2955: semantics and for the stack effect of the compiled code. For words with
2956: default compilation semantics these stack effects are usually not
2957: displayed; the stack effect of the compilation semantics is always
2958: @code{( -- )} for these words, the stack effect for the compiled code is
2959: the stack effect of the interpretation semantics.
2960:
2961: Note that the state of the interpreter does not come into play when
2962: performing the compilation semantics in this way. You can also perform
2963: it interpretively, e.g.:
2964:
2965: @example
2966: : foo2 ( n1 n2 -- n )
2967: [ MY-+ ] ;
2968: 1 2 foo .
2969: see foo
2970: @end example
1.21 crook 2971:
1.48 anton 2972: However, there are some broken Forth systems where this does not always
1.62 crook 2973: work, and therefore this practice was been declared non-standard in
1.48 anton 2974: 1999.
2975: @c !! repair.fs
2976:
2977: Here is another example for using @code{POSTPONE}:
1.44 crook 2978:
1.48 anton 2979: @example
2980: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
2981: POSTPONE negate POSTPONE + ; immediate compile-only
2982: : bar ( n1 n2 -- n )
2983: MY-- ;
2984: 2 1 bar .
2985: see bar
2986: @end example
1.21 crook 2987:
1.48 anton 2988: You can define @code{ENDIF} in this way:
1.21 crook 2989:
1.48 anton 2990: @example
2991: : ENDIF ( Compilation: orig -- )
2992: POSTPONE then ; immediate
2993: @end example
1.21 crook 2994:
1.48 anton 2995: @assignment
2996: Write @code{MY-2DUP} that has compilation semantics equivalent to
2997: @code{2dup}, but compiles @code{over over}.
2998: @endassignment
1.29 crook 2999:
1.66 anton 3000: @c !! @xref{Macros} for reference
3001:
3002:
1.48 anton 3003: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3004: @section @code{Literal}
1.66 anton 3005: @cindex literal tutorial
1.29 crook 3006:
1.48 anton 3007: You cannot @code{POSTPONE} numbers:
1.21 crook 3008:
1.48 anton 3009: @example
3010: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3011: @end example
3012:
1.48 anton 3013: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3014:
1.48 anton 3015: @example
3016: : [FOO] ( compilation: --; run-time: -- n )
3017: 500 POSTPONE literal ; immediate
1.29 crook 3018:
1.60 anton 3019: : flip [FOO] ;
1.48 anton 3020: flip .
3021: see flip
3022: @end example
1.29 crook 3023:
1.48 anton 3024: @code{LITERAL} consumes a number at compile-time (when it's compilation
3025: semantics are executed) and pushes it at run-time (when the code it
3026: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3027: number computed at compile time into the current word:
1.29 crook 3028:
1.48 anton 3029: @example
3030: : bar ( -- n )
3031: [ 2 2 + ] literal ;
3032: see bar
3033: @end example
1.29 crook 3034:
1.48 anton 3035: @assignment
3036: Write @code{]L} which allows writing the example above as @code{: bar (
3037: -- n ) [ 2 2 + ]L ;}
3038: @endassignment
3039:
1.66 anton 3040: @c !! @xref{Macros} for reference
3041:
1.48 anton 3042:
3043: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3044: @section Advanced macros
1.66 anton 3045: @cindex macros, advanced tutorial
3046: @cindex run-time code generation, tutorial
1.48 anton 3047:
1.66 anton 3048: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3049: Execution Tokens}. It frequently performs @code{execute}, a relatively
3050: expensive operation in some Forth implementations. You can use
1.48 anton 3051: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3052: and produce a word that contains the word to be performed directly:
3053:
3054: @c use ]] ... [[
3055: @example
3056: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3057: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3058: \ array beginning at addr and containing u elements
3059: @{ xt @}
3060: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3061: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3062: 1 cells POSTPONE literal POSTPONE +loop ;
3063:
3064: : sum-array ( addr u -- n )
3065: 0 rot rot [ ' + compile-map-array ] ;
3066: see sum-array
3067: a 5 sum-array .
3068: @end example
3069:
3070: You can use the full power of Forth for generating the code; here's an
3071: example where the code is generated in a loop:
3072:
3073: @example
3074: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3075: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3076: POSTPONE tuck POSTPONE @@
1.48 anton 3077: POSTPONE literal POSTPONE * POSTPONE +
3078: POSTPONE swap POSTPONE cell+ ;
3079:
3080: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3081: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3082: 0 postpone literal postpone swap
3083: [ ' compile-vmul-step compile-map-array ]
3084: postpone drop ;
3085: see compile-vmul
3086:
3087: : a-vmul ( addr -- n )
1.51 pazsan 3088: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3089: [ a 5 compile-vmul ] ;
3090: see a-vmul
3091: a a-vmul .
3092: @end example
3093:
3094: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3095: also use @code{map-array} instead (try it now!).
1.48 anton 3096:
3097: You can use this technique for efficient multiplication of large
3098: matrices. In matrix multiplication, you multiply every line of one
3099: matrix with every column of the other matrix. You can generate the code
3100: for one line once, and use it for every column. The only downside of
3101: this technique is that it is cumbersome to recover the memory consumed
3102: by the generated code when you are done (and in more complicated cases
3103: it is not possible portably).
3104:
1.66 anton 3105: @c !! @xref{Macros} for reference
3106:
3107:
1.48 anton 3108: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3109: @section Compilation Tokens
1.66 anton 3110: @cindex compilation tokens, tutorial
3111: @cindex CT, tutorial
1.48 anton 3112:
3113: This section is Gforth-specific. You can skip it.
3114:
3115: @code{' word compile,} compiles the interpretation semantics. For words
3116: with default compilation semantics this is the same as performing the
3117: compilation semantics. To represent the compilation semantics of other
3118: words (e.g., words like @code{if} that have no interpretation
3119: semantics), Gforth has the concept of a compilation token (CT,
3120: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3121: You can perform the compilation semantics represented by a CT with
3122: @code{execute}:
1.29 crook 3123:
1.48 anton 3124: @example
3125: : foo2 ( n1 n2 -- n )
3126: [ comp' + execute ] ;
3127: see foo
3128: @end example
1.29 crook 3129:
1.48 anton 3130: You can compile the compilation semantics represented by a CT with
3131: @code{postpone,}:
1.30 anton 3132:
1.48 anton 3133: @example
3134: : foo3 ( -- )
3135: [ comp' + postpone, ] ;
3136: see foo3
3137: @end example
1.30 anton 3138:
1.51 pazsan 3139: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3140: @code{comp'} is particularly useful for words that have no
3141: interpretation semantics:
1.29 crook 3142:
1.30 anton 3143: @example
1.48 anton 3144: ' if
1.60 anton 3145: comp' if .s 2drop
1.30 anton 3146: @end example
3147:
1.66 anton 3148: Reference: @ref{Tokens for Words}.
3149:
1.29 crook 3150:
1.48 anton 3151: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3152: @section Wordlists and Search Order
1.66 anton 3153: @cindex wordlists tutorial
3154: @cindex search order, tutorial
1.48 anton 3155:
3156: The dictionary is not just a memory area that allows you to allocate
3157: memory with @code{allot}, it also contains the Forth words, arranged in
3158: several wordlists. When searching for a word in a wordlist,
3159: conceptually you start searching at the youngest and proceed towards
3160: older words (in reality most systems nowadays use hash-tables); i.e., if
3161: you define a word with the same name as an older word, the new word
3162: shadows the older word.
3163:
3164: Which wordlists are searched in which order is determined by the search
3165: order. You can display the search order with @code{order}. It displays
3166: first the search order, starting with the wordlist searched first, then
3167: it displays the wordlist that will contain newly defined words.
1.21 crook 3168:
1.48 anton 3169: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3170:
1.48 anton 3171: @example
3172: wordlist constant mywords
3173: @end example
1.21 crook 3174:
1.48 anton 3175: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3176: defined words (the @emph{current} wordlist):
1.21 crook 3177:
1.48 anton 3178: @example
3179: mywords set-current
3180: order
3181: @end example
1.26 crook 3182:
1.48 anton 3183: Gforth does not display a name for the wordlist in @code{mywords}
3184: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3185:
1.48 anton 3186: You can get the current wordlist with @code{get-current ( -- wid)}. If
3187: you want to put something into a specific wordlist without overall
3188: effect on the current wordlist, this typically looks like this:
1.21 crook 3189:
1.48 anton 3190: @example
3191: get-current mywords set-current ( wid )
3192: create someword
3193: ( wid ) set-current
3194: @end example
1.21 crook 3195:
1.48 anton 3196: You can write the search order with @code{set-order ( wid1 .. widn n --
3197: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3198: searched wordlist is topmost.
1.21 crook 3199:
1.48 anton 3200: @example
3201: get-order mywords swap 1+ set-order
3202: order
3203: @end example
1.21 crook 3204:
1.48 anton 3205: Yes, the order of wordlists in the output of @code{order} is reversed
3206: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3207:
1.48 anton 3208: @assignment
3209: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3210: wordlist to the search order. Define @code{previous ( -- )}, which
3211: removes the first searched wordlist from the search order. Experiment
3212: with boundary conditions (you will see some crashes or situations that
3213: are hard or impossible to leave).
3214: @endassignment
1.21 crook 3215:
1.48 anton 3216: The search order is a powerful foundation for providing features similar
3217: to Modula-2 modules and C++ namespaces. However, trying to modularize
3218: programs in this way has disadvantages for debugging and reuse/factoring
3219: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3220: though). These disadvantages are not so clear in other
1.82 anton 3221: languages/programming environments, because these languages are not so
1.48 anton 3222: strong in debugging and reuse.
1.21 crook 3223:
1.66 anton 3224: @c !! example
3225:
3226: Reference: @ref{Word Lists}.
1.21 crook 3227:
1.29 crook 3228: @c ******************************************************************
1.48 anton 3229: @node Introduction, Words, Tutorial, Top
1.29 crook 3230: @comment node-name, next, previous, up
3231: @chapter An Introduction to ANS Forth
3232: @cindex Forth - an introduction
1.21 crook 3233:
1.83 anton 3234: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3235: that it is slower-paced in its examples, but uses them to dive deep into
3236: explaining Forth internals (not covered by the Tutorial). Apart from
3237: that, this chapter covers far less material. It is suitable for reading
3238: without using a computer.
3239:
1.29 crook 3240: The primary purpose of this manual is to document Gforth. However, since
3241: Forth is not a widely-known language and there is a lack of up-to-date
3242: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3243: material. For other sources of Forth-related
3244: information, see @ref{Forth-related information}.
1.21 crook 3245:
1.29 crook 3246: The examples in this section should work on any ANS Forth; the
3247: output shown was produced using Gforth. Each example attempts to
3248: reproduce the exact output that Gforth produces. If you try out the
3249: examples (and you should), what you should type is shown @kbd{like this}
3250: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3251: that, where the example shows @key{RET} it means that you should
1.29 crook 3252: press the ``carriage return'' key. Unfortunately, some output formats for
3253: this manual cannot show the difference between @kbd{this} and
3254: @code{this} which will make trying out the examples harder (but not
3255: impossible).
1.21 crook 3256:
1.29 crook 3257: Forth is an unusual language. It provides an interactive development
3258: environment which includes both an interpreter and compiler. Forth
3259: programming style encourages you to break a problem down into many
3260: @cindex factoring
3261: small fragments (@dfn{factoring}), and then to develop and test each
3262: fragment interactively. Forth advocates assert that breaking the
3263: edit-compile-test cycle used by conventional programming languages can
3264: lead to great productivity improvements.
1.21 crook 3265:
1.29 crook 3266: @menu
1.67 anton 3267: * Introducing the Text Interpreter::
3268: * Stacks and Postfix notation::
3269: * Your first definition::
3270: * How does that work?::
3271: * Forth is written in Forth::
3272: * Review - elements of a Forth system::
3273: * Where to go next::
3274: * Exercises::
1.29 crook 3275: @end menu
1.21 crook 3276:
1.29 crook 3277: @comment ----------------------------------------------
3278: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3279: @section Introducing the Text Interpreter
3280: @cindex text interpreter
3281: @cindex outer interpreter
1.21 crook 3282:
1.30 anton 3283: @c IMO this is too detailed and the pace is too slow for
3284: @c an introduction. If you know German, take a look at
3285: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3286: @c to see how I do it - anton
3287:
1.44 crook 3288: @c nac-> Where I have accepted your comments 100% and modified the text
3289: @c accordingly, I have deleted your comments. Elsewhere I have added a
3290: @c response like this to attempt to rationalise what I have done. Of
3291: @c course, this is a very clumsy mechanism for something that would be
3292: @c done far more efficiently over a beer. Please delete any dialogue
3293: @c you consider closed.
3294:
1.29 crook 3295: When you invoke the Forth image, you will see a startup banner printed
3296: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3297: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3298: its command line interpreter, which is called the @dfn{Text Interpreter}
3299: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3300: about the text interpreter as you read through this chapter, for more
3301: detail @pxref{The Text Interpreter}).
1.21 crook 3302:
1.29 crook 3303: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3304: input. Type a number and press the @key{RET} key:
1.21 crook 3305:
1.26 crook 3306: @example
1.30 anton 3307: @kbd{45@key{RET}} ok
1.26 crook 3308: @end example
1.21 crook 3309:
1.29 crook 3310: Rather than give you a prompt to invite you to input something, the text
3311: interpreter prints a status message @i{after} it has processed a line
3312: of input. The status message in this case (``@code{ ok}'' followed by
3313: carriage-return) indicates that the text interpreter was able to process
3314: all of your input successfully. Now type something illegal:
3315:
3316: @example
1.30 anton 3317: @kbd{qwer341@key{RET}}
1.29 crook 3318: :1: Undefined word
3319: qwer341
3320: ^^^^^^^
3321: $400D2BA8 Bounce
3322: $400DBDA8 no.extensions
3323: @end example
1.23 crook 3324:
1.29 crook 3325: The exact text, other than the ``Undefined word'' may differ slightly on
3326: your system, but the effect is the same; when the text interpreter
3327: detects an error, it discards any remaining text on a line, resets
1.49 anton 3328: certain internal state and prints an error message. For a detailed description of error messages see @ref{Error
3329: messages}.
1.23 crook 3330:
1.29 crook 3331: The text interpreter waits for you to press carriage-return, and then
3332: processes your input line. Starting at the beginning of the line, it
3333: breaks the line into groups of characters separated by spaces. For each
3334: group of characters in turn, it makes two attempts to do something:
1.23 crook 3335:
1.29 crook 3336: @itemize @bullet
3337: @item
1.44 crook 3338: @cindex name dictionary
1.29 crook 3339: It tries to treat it as a command. It does this by searching a @dfn{name
3340: dictionary}. If the group of characters matches an entry in the name
3341: dictionary, the name dictionary provides the text interpreter with
3342: information that allows the text interpreter perform some actions. In
3343: Forth jargon, we say that the group
3344: @cindex word
3345: @cindex definition
3346: @cindex execution token
3347: @cindex xt
3348: of characters names a @dfn{word}, that the dictionary search returns an
3349: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3350: word, and that the text interpreter executes the xt. Often, the terms
3351: @dfn{word} and @dfn{definition} are used interchangeably.
3352: @item
3353: If the text interpreter fails to find a match in the name dictionary, it
3354: tries to treat the group of characters as a number in the current number
3355: base (when you start up Forth, the current number base is base 10). If
3356: the group of characters legitimately represents a number, the text
3357: interpreter pushes the number onto a stack (we'll learn more about that
3358: in the next section).
3359: @end itemize
1.23 crook 3360:
1.29 crook 3361: If the text interpreter is unable to do either of these things with any
3362: group of characters, it discards the group of characters and the rest of
3363: the line, then prints an error message. If the text interpreter reaches
3364: the end of the line without error, it prints the status message ``@code{ ok}''
3365: followed by carriage-return.
1.21 crook 3366:
1.29 crook 3367: This is the simplest command we can give to the text interpreter:
1.23 crook 3368:
3369: @example
1.30 anton 3370: @key{RET} ok
1.23 crook 3371: @end example
1.21 crook 3372:
1.29 crook 3373: The text interpreter did everything we asked it to do (nothing) without
3374: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3375: command:
1.21 crook 3376:
1.23 crook 3377: @example
1.30 anton 3378: @kbd{12 dup fred dup@key{RET}}
1.29 crook 3379: :1: Undefined word
3380: 12 dup fred dup
3381: ^^^^
3382: $400D2BA8 Bounce
3383: $400DBDA8 no.extensions
1.23 crook 3384: @end example
1.21 crook 3385:
1.29 crook 3386: When you press the carriage-return key, the text interpreter starts to
3387: work its way along the line:
1.21 crook 3388:
1.29 crook 3389: @itemize @bullet
3390: @item
3391: When it gets to the space after the @code{2}, it takes the group of
3392: characters @code{12} and looks them up in the name
3393: dictionary@footnote{We can't tell if it found them or not, but assume
3394: for now that it did not}. There is no match for this group of characters
3395: in the name dictionary, so it tries to treat them as a number. It is
3396: able to do this successfully, so it puts the number, 12, ``on the stack''
3397: (whatever that means).
3398: @item
3399: The text interpreter resumes scanning the line and gets the next group
3400: of characters, @code{dup}. It looks it up in the name dictionary and
3401: (you'll have to take my word for this) finds it, and executes the word
3402: @code{dup} (whatever that means).
3403: @item
3404: Once again, the text interpreter resumes scanning the line and gets the
3405: group of characters @code{fred}. It looks them up in the name
3406: dictionary, but can't find them. It tries to treat them as a number, but
3407: they don't represent any legal number.
3408: @end itemize
1.21 crook 3409:
1.29 crook 3410: At this point, the text interpreter gives up and prints an error
3411: message. The error message shows exactly how far the text interpreter
3412: got in processing the line. In particular, it shows that the text
3413: interpreter made no attempt to do anything with the final character
3414: group, @code{dup}, even though we have good reason to believe that the
3415: text interpreter would have no problem looking that word up and
3416: executing it a second time.
1.21 crook 3417:
3418:
1.29 crook 3419: @comment ----------------------------------------------
3420: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3421: @section Stacks, postfix notation and parameter passing
3422: @cindex text interpreter
3423: @cindex outer interpreter
1.21 crook 3424:
1.29 crook 3425: In procedural programming languages (like C and Pascal), the
3426: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3427: functions or procedures are called with @dfn{explicit parameters}. For
3428: example, in C we might write:
1.21 crook 3429:
1.23 crook 3430: @example
1.29 crook 3431: total = total + new_volume(length,height,depth);
1.23 crook 3432: @end example
1.21 crook 3433:
1.23 crook 3434: @noindent
1.29 crook 3435: where new_volume is a function-call to another piece of code, and total,
3436: length, height and depth are all variables. length, height and depth are
3437: parameters to the function-call.
1.21 crook 3438:
1.29 crook 3439: In Forth, the equivalent of the function or procedure is the
3440: @dfn{definition} and parameters are implicitly passed between
3441: definitions using a shared stack that is visible to the
3442: programmer. Although Forth does support variables, the existence of the
3443: stack means that they are used far less often than in most other
3444: programming languages. When the text interpreter encounters a number, it
3445: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3446: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3447: used for any operation is implied unambiguously by the operation being
3448: performed. The stack used for all integer operations is called the @dfn{data
3449: stack} and, since this is the stack used most commonly, references to
3450: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3451:
1.29 crook 3452: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3453:
1.23 crook 3454: @example
1.30 anton 3455: @kbd{1 2 3@key{RET}} ok
1.23 crook 3456: @end example
1.21 crook 3457:
1.29 crook 3458: Then this instructs the text interpreter to placed three numbers on the
3459: (data) stack. An analogy for the behaviour of the stack is to take a
3460: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3461: the table. The 3 was the last card onto the pile (``last-in'') and if
3462: you take a card off the pile then, unless you're prepared to fiddle a
3463: bit, the card that you take off will be the 3 (``first-out''). The
3464: number that will be first-out of the stack is called the @dfn{top of
3465: stack}, which
3466: @cindex TOS definition
3467: is often abbreviated to @dfn{TOS}.
1.21 crook 3468:
1.29 crook 3469: To understand how parameters are passed in Forth, consider the
3470: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3471: be surprised to learn that this definition performs addition. More
3472: precisely, it adds two number together and produces a result. Where does
3473: it get the two numbers from? It takes the top two numbers off the
3474: stack. Where does it place the result? On the stack. You can act-out the
3475: behaviour of @code{+} with your playing cards like this:
1.21 crook 3476:
3477: @itemize @bullet
3478: @item
1.29 crook 3479: Pick up two cards from the stack on the table
1.21 crook 3480: @item
1.29 crook 3481: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3482: numbers''
1.21 crook 3483: @item
1.29 crook 3484: Decide that the answer is 5
1.21 crook 3485: @item
1.29 crook 3486: Shuffle the two cards back into the pack and find a 5
1.21 crook 3487: @item
1.29 crook 3488: Put a 5 on the remaining ace that's on the table.
1.21 crook 3489: @end itemize
3490:
1.29 crook 3491: If you don't have a pack of cards handy but you do have Forth running,
3492: you can use the definition @code{.s} to show the current state of the stack,
3493: without affecting the stack. Type:
1.21 crook 3494:
3495: @example
1.30 anton 3496: @kbd{clearstack 1 2 3@key{RET}} ok
3497: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3498: @end example
3499:
1.29 crook 3500: The text interpreter looks up the word @code{clearstack} and executes
3501: it; it tidies up the stack and removes any entries that may have been
3502: left on it by earlier examples. The text interpreter pushes each of the
3503: three numbers in turn onto the stack. Finally, the text interpreter
3504: looks up the word @code{.s} and executes it. The effect of executing
3505: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3506: followed by a list of all the items on the stack; the item on the far
3507: right-hand side is the TOS.
1.21 crook 3508:
1.29 crook 3509: You can now type:
1.21 crook 3510:
1.29 crook 3511: @example
1.30 anton 3512: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3513: @end example
1.21 crook 3514:
1.29 crook 3515: @noindent
3516: which is correct; there are now 2 items on the stack and the result of
3517: the addition is 5.
1.23 crook 3518:
1.29 crook 3519: If you're playing with cards, try doing a second addition: pick up the
3520: two cards, work out that their sum is 6, shuffle them into the pack,
3521: look for a 6 and place that on the table. You now have just one item on
3522: the stack. What happens if you try to do a third addition? Pick up the
3523: first card, pick up the second card -- ah! There is no second card. This
3524: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3525: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3526: Underflow or an Invalid Memory Address error).
1.23 crook 3527:
1.29 crook 3528: The opposite situation to a stack underflow is a @dfn{stack overflow},
3529: which simply accepts that there is a finite amount of storage space
3530: reserved for the stack. To stretch the playing card analogy, if you had
3531: enough packs of cards and you piled the cards up on the table, you would
3532: eventually be unable to add another card; you'd hit the ceiling. Gforth
3533: allows you to set the maximum size of the stacks. In general, the only
3534: time that you will get a stack overflow is because a definition has a
3535: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3536:
1.29 crook 3537: There's one final use for the playing card analogy. If you model your
3538: stack using a pack of playing cards, the maximum number of items on
3539: your stack will be 52 (I assume you didn't use the Joker). The maximum
3540: @i{value} of any item on the stack is 13 (the King). In fact, the only
3541: possible numbers are positive integer numbers 1 through 13; you can't
3542: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3543: think about some of the cards, you can accommodate different
3544: numbers. For example, you could think of the Jack as representing 0,
3545: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3546: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3547: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3548:
1.29 crook 3549: In that analogy, the limit was the amount of information that a single
3550: stack entry could hold, and Forth has a similar limit. In Forth, the
3551: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3552: implementation dependent and affects the maximum value that a stack
3553: entry can hold. A Standard Forth provides a cell size of at least
3554: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3555:
1.29 crook 3556: Forth does not do any type checking for you, so you are free to
3557: manipulate and combine stack items in any way you wish. A convenient way
3558: of treating stack items is as 2's complement signed integers, and that
3559: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3560:
1.29 crook 3561: @example
1.30 anton 3562: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3563: @end example
1.21 crook 3564:
1.29 crook 3565: If you use numbers and definitions like @code{+} in order to turn Forth
3566: into a great big pocket calculator, you will realise that it's rather
3567: different from a normal calculator. Rather than typing 2 + 3 = you had
3568: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3569: result). The terminology used to describe this difference is to say that
3570: your calculator uses @dfn{Infix Notation} (parameters and operators are
3571: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3572: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3573:
1.29 crook 3574: Whilst postfix notation might look confusing to begin with, it has
3575: several important advantages:
1.21 crook 3576:
1.23 crook 3577: @itemize @bullet
3578: @item
1.29 crook 3579: it is unambiguous
1.23 crook 3580: @item
1.29 crook 3581: it is more concise
1.23 crook 3582: @item
1.29 crook 3583: it fits naturally with a stack-based system
1.23 crook 3584: @end itemize
1.21 crook 3585:
1.29 crook 3586: To examine these claims in more detail, consider these sums:
1.21 crook 3587:
1.29 crook 3588: @example
3589: 6 + 5 * 4 =
3590: 4 * 5 + 6 =
3591: @end example
1.21 crook 3592:
1.29 crook 3593: If you're just learning maths or your maths is very rusty, you will
3594: probably come up with the answer 44 for the first and 26 for the
3595: second. If you are a bit of a whizz at maths you will remember the
3596: @i{convention} that multiplication takes precendence over addition, and
3597: you'd come up with the answer 26 both times. To explain the answer 26
3598: to someone who got the answer 44, you'd probably rewrite the first sum
3599: like this:
1.21 crook 3600:
1.29 crook 3601: @example
3602: 6 + (5 * 4) =
3603: @end example
1.21 crook 3604:
1.29 crook 3605: If what you really wanted was to perform the addition before the
3606: multiplication, you would have to use parentheses to force it.
1.21 crook 3607:
1.29 crook 3608: If you did the first two sums on a pocket calculator you would probably
3609: get the right answers, unless you were very cautious and entered them using
3610: these keystroke sequences:
1.21 crook 3611:
1.29 crook 3612: 6 + 5 = * 4 =
3613: 4 * 5 = + 6 =
1.21 crook 3614:
1.29 crook 3615: Postfix notation is unambiguous because the order that the operators
3616: are applied is always explicit; that also means that parentheses are
3617: never required. The operators are @i{active} (the act of quoting the
3618: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3619:
1.29 crook 3620: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3621: equivalent ways:
1.26 crook 3622:
3623: @example
1.29 crook 3624: 6 5 4 * + or:
3625: 5 4 * 6 +
1.26 crook 3626: @end example
1.23 crook 3627:
1.29 crook 3628: An important thing that you should notice about this notation is that
3629: the @i{order} of the numbers does not change; if you want to subtract
3630: 2 from 10 you type @code{10 2 -}.
1.1 anton 3631:
1.29 crook 3632: The reason that Forth uses postfix notation is very simple to explain: it
3633: makes the implementation extremely simple, and it follows naturally from
3634: using the stack as a mechanism for passing parameters. Another way of
3635: thinking about this is to realise that all Forth definitions are
3636: @i{active}; they execute as they are encountered by the text
3637: interpreter. The result of this is that the syntax of Forth is trivially
3638: simple.
1.1 anton 3639:
3640:
3641:
1.29 crook 3642: @comment ----------------------------------------------
3643: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3644: @section Your first Forth definition
3645: @cindex first definition
1.1 anton 3646:
1.29 crook 3647: Until now, the examples we've seen have been trivial; we've just been
3648: using Forth as a bigger-than-pocket calculator. Also, each calculation
3649: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3650: again@footnote{That's not quite true. If you press the up-arrow key on
3651: your keyboard you should be able to scroll back to any earlier command,
3652: edit it and re-enter it.} In this section we'll see how to add new
3653: words to Forth's vocabulary.
1.1 anton 3654:
1.29 crook 3655: The easiest way to create a new word is to use a @dfn{colon
3656: definition}. We'll define a few and try them out before worrying too
3657: much about how they work. Try typing in these examples; be careful to
3658: copy the spaces accurately:
1.1 anton 3659:
1.29 crook 3660: @example
3661: : add-two 2 + . ;
3662: : greet ." Hello and welcome" ;
3663: : demo 5 add-two ;
3664: @end example
1.1 anton 3665:
1.29 crook 3666: @noindent
3667: Now try them out:
1.1 anton 3668:
1.29 crook 3669: @example
1.30 anton 3670: @kbd{greet@key{RET}} Hello and welcome ok
3671: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3672: @kbd{4 add-two@key{RET}} 6 ok
3673: @kbd{demo@key{RET}} 7 ok
3674: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3675: @end example
1.1 anton 3676:
1.29 crook 3677: The first new thing that we've introduced here is the pair of words
3678: @code{:} and @code{;}. These are used to start and terminate a new
3679: definition, respectively. The first word after the @code{:} is the name
3680: for the new definition.
1.1 anton 3681:
1.29 crook 3682: As you can see from the examples, a definition is built up of words that
3683: have already been defined; Forth makes no distinction between
3684: definitions that existed when you started the system up, and those that
3685: you define yourself.
1.1 anton 3686:
1.29 crook 3687: The examples also introduce the words @code{.} (dot), @code{."}
3688: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3689: the stack and displays it. It's like @code{.s} except that it only
3690: displays the top item of the stack and it is destructive; after it has
3691: executed, the number is no longer on the stack. There is always one
3692: space printed after the number, and no spaces before it. Dot-quote
3693: defines a string (a sequence of characters) that will be printed when
3694: the word is executed. The string can contain any printable characters
3695: except @code{"}. A @code{"} has a special function; it is not a Forth
3696: word but it acts as a delimiter (the way that delimiters work is
3697: described in the next section). Finally, @code{dup} duplicates the value
3698: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3699:
1.29 crook 3700: We already know that the text interpreter searches through the
3701: dictionary to locate names. If you've followed the examples earlier, you
3702: will already have a definition called @code{add-two}. Lets try modifying
3703: it by typing in a new definition:
1.1 anton 3704:
1.29 crook 3705: @example
1.30 anton 3706: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3707: @end example
1.5 anton 3708:
1.29 crook 3709: Forth recognised that we were defining a word that already exists, and
3710: printed a message to warn us of that fact. Let's try out the new
3711: definition:
1.5 anton 3712:
1.29 crook 3713: @example
1.30 anton 3714: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3715: @end example
1.1 anton 3716:
1.29 crook 3717: @noindent
3718: All that we've actually done here, though, is to create a new
3719: definition, with a particular name. The fact that there was already a
3720: definition with the same name did not make any difference to the way
3721: that the new definition was created (except that Forth printed a warning
3722: message). The old definition of add-two still exists (try @code{demo}
3723: again to see that this is true). Any new definition will use the new
3724: definition of @code{add-two}, but old definitions continue to use the
3725: version that already existed at the time that they were @code{compiled}.
1.1 anton 3726:
1.29 crook 3727: Before you go on to the next section, try defining and redefining some
3728: words of your own.
1.1 anton 3729:
1.29 crook 3730: @comment ----------------------------------------------
3731: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3732: @section How does that work?
3733: @cindex parsing words
1.1 anton 3734:
1.30 anton 3735: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3736:
3737: @c Is it a good idea to talk about the interpretation semantics of a
3738: @c number? We don't have an xt to go along with it. - anton
3739:
3740: @c Now that I have eliminated execution semantics, I wonder if it would not
3741: @c be better to keep them (or add run-time semantics), to make it easier to
3742: @c explain what compilation semantics usually does. - anton
3743:
1.44 crook 3744: @c nac-> I removed the term ``default compilation sematics'' from the
3745: @c introductory chapter. Removing ``execution semantics'' was making
3746: @c everything simpler to explain, then I think the use of this term made
3747: @c everything more complex again. I replaced it with ``default
3748: @c semantics'' (which is used elsewhere in the manual) by which I mean
3749: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3750: @c flag set''.
3751:
3752: @c anton: I have eliminated default semantics (except in one place where it
3753: @c means "default interpretation and compilation semantics"), because it
3754: @c makes no sense in the presence of combined words. I reverted to
3755: @c "execution semantics" where necessary.
3756:
3757: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3758: @c section (and, unusually for me, I think I even made it shorter!). See
3759: @c what you think -- I know I have not addressed your primary concern
3760: @c that it is too heavy-going for an introduction. From what I understood
3761: @c of your course notes it looks as though they might be a good framework.
3762: @c Things that I've tried to capture here are some things that came as a
3763: @c great revelation here when I first understood them. Also, I like the
3764: @c fact that a very simple code example shows up almost all of the issues
3765: @c that you need to understand to see how Forth works. That's unique and
3766: @c worthwhile to emphasise.
3767:
1.83 anton 3768: @c anton: I think it's a good idea to present the details, especially those
3769: @c that you found to be a revelation, and probably the tutorial tries to be
3770: @c too superficial and does not get some of the things across that make
3771: @c Forth special. I do believe that most of the time these things should
3772: @c be discussed at the end of a section or in separate sections instead of
3773: @c in the middle of a section (e.g., the stuff you added in "User-defined
3774: @c defining words" leads in a completely different direction from the rest
3775: @c of the section).
3776:
1.29 crook 3777: Now we're going to take another look at the definition of @code{add-two}
3778: from the previous section. From our knowledge of the way that the text
3779: interpreter works, we would have expected this result when we tried to
3780: define @code{add-two}:
1.21 crook 3781:
1.29 crook 3782: @example
1.44 crook 3783: @kbd{: add-two 2 + . ;@key{RET}}
1.29 crook 3784: ^^^^^^^
3785: Error: Undefined word
3786: @end example
1.28 crook 3787:
1.29 crook 3788: The reason that this didn't happen is bound up in the way that @code{:}
3789: works. The word @code{:} does two special things. The first special
3790: thing that it does prevents the text interpreter from ever seeing the
3791: characters @code{add-two}. The text interpreter uses a variable called
3792: @cindex modifying >IN
1.44 crook 3793: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3794: input line. When it encounters the word @code{:} it behaves in exactly
3795: the same way as it does for any other word; it looks it up in the name
3796: dictionary, finds its xt and executes it. When @code{:} executes, it
3797: looks at the input buffer, finds the word @code{add-two} and advances the
3798: value of @code{>IN} to point past it. It then does some other stuff
3799: associated with creating the new definition (including creating an entry
3800: for @code{add-two} in the name dictionary). When the execution of @code{:}
3801: completes, control returns to the text interpreter, which is oblivious
3802: to the fact that it has been tricked into ignoring part of the input
3803: line.
1.21 crook 3804:
1.29 crook 3805: @cindex parsing words
3806: Words like @code{:} -- words that advance the value of @code{>IN} and so
3807: prevent the text interpreter from acting on the whole of the input line
3808: -- are called @dfn{parsing words}.
1.21 crook 3809:
1.29 crook 3810: @cindex @code{state} - effect on the text interpreter
3811: @cindex text interpreter - effect of state
3812: The second special thing that @code{:} does is change the value of a
3813: variable called @code{state}, which affects the way that the text
3814: interpreter behaves. When Gforth starts up, @code{state} has the value
3815: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3816: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3817: the text interpreter is said to be @dfn{compiling}.
3818:
3819: In this example, the text interpreter is compiling when it processes the
3820: string ``@code{2 + . ;}''. It still breaks the string down into
3821: character sequences in the same way. However, instead of pushing the
3822: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3823: into the definition of @code{add-two} that will make the number @code{2} get
3824: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3825: the behaviours of @code{+} and @code{.} are also compiled into the
3826: definition.
3827:
3828: One category of words don't get compiled. These so-called @dfn{immediate
3829: words} get executed (performed @i{now}) regardless of whether the text
3830: interpreter is interpreting or compiling. The word @code{;} is an
3831: immediate word. Rather than being compiled into the definition, it
3832: executes. Its effect is to terminate the current definition, which
3833: includes changing the value of @code{state} back to 0.
3834:
3835: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3836: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3837: definition.
1.28 crook 3838:
1.30 anton 3839: In Forth, every word or number can be described in terms of two
1.29 crook 3840: properties:
1.28 crook 3841:
3842: @itemize @bullet
3843: @item
1.29 crook 3844: @cindex interpretation semantics
1.44 crook 3845: Its @dfn{interpretation semantics} describe how it will behave when the
3846: text interpreter encounters it in @dfn{interpret} state. The
3847: interpretation semantics of a word are represented by an @dfn{execution
3848: token}.
1.28 crook 3849: @item
1.29 crook 3850: @cindex compilation semantics
1.44 crook 3851: Its @dfn{compilation semantics} describe how it will behave when the
3852: text interpreter encounters it in @dfn{compile} state. The compilation
3853: semantics of a word are represented in an implementation-dependent way;
3854: Gforth uses a @dfn{compilation token}.
1.29 crook 3855: @end itemize
3856:
3857: @noindent
3858: Numbers are always treated in a fixed way:
3859:
3860: @itemize @bullet
1.28 crook 3861: @item
1.44 crook 3862: When the number is @dfn{interpreted}, its behaviour is to push the
3863: number onto the stack.
1.28 crook 3864: @item
1.30 anton 3865: When the number is @dfn{compiled}, a piece of code is appended to the
3866: current definition that pushes the number when it runs. (In other words,
3867: the compilation semantics of a number are to postpone its interpretation
3868: semantics until the run-time of the definition that it is being compiled
3869: into.)
1.29 crook 3870: @end itemize
3871:
1.44 crook 3872: Words don't behave in such a regular way, but most have @i{default
3873: semantics} which means that they behave like this:
1.29 crook 3874:
3875: @itemize @bullet
1.28 crook 3876: @item
1.30 anton 3877: The @dfn{interpretation semantics} of the word are to do something useful.
3878: @item
1.29 crook 3879: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3880: @dfn{interpretation semantics} to the current definition (so that its
3881: run-time behaviour is to do something useful).
1.28 crook 3882: @end itemize
3883:
1.30 anton 3884: @cindex immediate words
1.44 crook 3885: The actual behaviour of any particular word can be controlled by using
3886: the words @code{immediate} and @code{compile-only} when the word is
3887: defined. These words set flags in the name dictionary entry of the most
3888: recently defined word, and these flags are retrieved by the text
3889: interpreter when it finds the word in the name dictionary.
3890:
3891: A word that is marked as @dfn{immediate} has compilation semantics that
3892: are identical to its interpretation semantics. In other words, it
3893: behaves like this:
1.29 crook 3894:
3895: @itemize @bullet
3896: @item
1.30 anton 3897: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3898: @item
1.30 anton 3899: The @dfn{compilation semantics} of the word are to do something useful
3900: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3901: @end itemize
1.28 crook 3902:
1.44 crook 3903: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3904: performing the interpretation semantics of the word directly; an attempt
3905: to do so will generate an error. It is never necessary to use
3906: @code{compile-only} (and it is not even part of ANS Forth, though it is
3907: provided by many implementations) but it is good etiquette to apply it
3908: to a word that will not behave correctly (and might have unexpected
3909: side-effects) in interpret state. For example, it is only legal to use
3910: the conditional word @code{IF} within a definition. If you forget this
3911: and try to use it elsewhere, the fact that (in Gforth) it is marked as
3912: @code{compile-only} allows the text interpreter to generate a helpful
3913: error message rather than subjecting you to the consequences of your
3914: folly.
3915:
1.29 crook 3916: This example shows the difference between an immediate and a
3917: non-immediate word:
1.28 crook 3918:
1.29 crook 3919: @example
3920: : show-state state @@ . ;
3921: : show-state-now show-state ; immediate
3922: : word1 show-state ;
3923: : word2 show-state-now ;
1.28 crook 3924: @end example
1.23 crook 3925:
1.29 crook 3926: The word @code{immediate} after the definition of @code{show-state-now}
3927: makes that word an immediate word. These definitions introduce a new
3928: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
3929: variable, and leaves it on the stack. Therefore, the behaviour of
3930: @code{show-state} is to print a number that represents the current value
3931: of @code{state}.
1.28 crook 3932:
1.29 crook 3933: When you execute @code{word1}, it prints the number 0, indicating that
3934: the system is interpreting. When the text interpreter compiled the
3935: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 3936: compilation semantics are to append its interpretation semantics to the
1.29 crook 3937: current definition. When you execute @code{word1}, it performs the
1.30 anton 3938: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 3939: (and therefore @code{show-state}) are executed, the system is
3940: interpreting.
1.28 crook 3941:
1.30 anton 3942: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 3943: you should have seen the number -1 printed, followed by ``@code{
3944: ok}''. When the text interpreter compiled the definition of
3945: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 3946: whose compilation semantics are therefore to perform its interpretation
1.29 crook 3947: semantics. It is executed straight away (even before the text
3948: interpreter has moved on to process another group of characters; the
3949: @code{;} in this example). The effect of executing it are to display the
3950: value of @code{state} @i{at the time that the definition of}
3951: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
3952: system is compiling at this time. If you execute @code{word2} it does
3953: nothing at all.
1.28 crook 3954:
1.29 crook 3955: @cindex @code{."}, how it works
3956: Before leaving the subject of immediate words, consider the behaviour of
3957: @code{."} in the definition of @code{greet}, in the previous
3958: section. This word is both a parsing word and an immediate word. Notice
3959: that there is a space between @code{."} and the start of the text
3960: @code{Hello and welcome}, but that there is no space between the last
3961: letter of @code{welcome} and the @code{"} character. The reason for this
3962: is that @code{."} is a Forth word; it must have a space after it so that
3963: the text interpreter can identify it. The @code{"} is not a Forth word;
3964: it is a @dfn{delimiter}. The examples earlier show that, when the string
3965: is displayed, there is neither a space before the @code{H} nor after the
3966: @code{e}. Since @code{."} is an immediate word, it executes at the time
3967: that @code{greet} is defined. When it executes, its behaviour is to
3968: search forward in the input line looking for the delimiter. When it
3969: finds the delimiter, it updates @code{>IN} to point past the
3970: delimiter. It also compiles some magic code into the definition of
3971: @code{greet}; the xt of a run-time routine that prints a text string. It
3972: compiles the string @code{Hello and welcome} into memory so that it is
3973: available to be printed later. When the text interpreter gains control,
3974: the next word it finds in the input stream is @code{;} and so it
3975: terminates the definition of @code{greet}.
1.28 crook 3976:
3977:
3978: @comment ----------------------------------------------
1.29 crook 3979: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
3980: @section Forth is written in Forth
3981: @cindex structure of Forth programs
3982:
3983: When you start up a Forth compiler, a large number of definitions
3984: already exist. In Forth, you develop a new application using bottom-up
3985: programming techniques to create new definitions that are defined in
3986: terms of existing definitions. As you create each definition you can
3987: test and debug it interactively.
3988:
3989: If you have tried out the examples in this section, you will probably
3990: have typed them in by hand; when you leave Gforth, your definitions will
3991: be lost. You can avoid this by using a text editor to enter Forth source
3992: code into a file, and then loading code from the file using
1.49 anton 3993: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 3994: processed by the text interpreter, just as though you had typed it in by
3995: hand@footnote{Actually, there are some subtle differences -- see
3996: @ref{The Text Interpreter}.}.
3997:
3998: Gforth also supports the traditional Forth alternative to using text
1.49 anton 3999: files for program entry (@pxref{Blocks}).
1.28 crook 4000:
1.29 crook 4001: In common with many, if not most, Forth compilers, most of Gforth is
4002: actually written in Forth. All of the @file{.fs} files in the
4003: installation directory@footnote{For example,
1.30 anton 4004: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4005: study to see examples of Forth programming.
1.28 crook 4006:
1.29 crook 4007: Gforth maintains a history file that records every line that you type to
4008: the text interpreter. This file is preserved between sessions, and is
4009: used to provide a command-line recall facility. If you enter long
4010: definitions by hand, you can use a text editor to paste them out of the
4011: history file into a Forth source file for reuse at a later time
1.49 anton 4012: (for more information @pxref{Command-line editing}).
1.28 crook 4013:
4014:
4015: @comment ----------------------------------------------
1.29 crook 4016: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4017: @section Review - elements of a Forth system
4018: @cindex elements of a Forth system
1.28 crook 4019:
1.29 crook 4020: To summarise this chapter:
1.28 crook 4021:
4022: @itemize @bullet
4023: @item
1.29 crook 4024: Forth programs use @dfn{factoring} to break a problem down into small
4025: fragments called @dfn{words} or @dfn{definitions}.
4026: @item
4027: Forth program development is an interactive process.
4028: @item
4029: The main command loop that accepts input, and controls both
4030: interpretation and compilation, is called the @dfn{text interpreter}
4031: (also known as the @dfn{outer interpreter}).
4032: @item
4033: Forth has a very simple syntax, consisting of words and numbers
4034: separated by spaces or carriage-return characters. Any additional syntax
4035: is imposed by @dfn{parsing words}.
4036: @item
4037: Forth uses a stack to pass parameters between words. As a result, it
4038: uses postfix notation.
4039: @item
4040: To use a word that has previously been defined, the text interpreter
4041: searches for the word in the @dfn{name dictionary}.
4042: @item
1.30 anton 4043: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4044: @item
1.29 crook 4045: The text interpreter uses the value of @code{state} to select between
4046: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4047: semantics} of a word that it encounters.
1.28 crook 4048: @item
1.30 anton 4049: The relationship between the @dfn{interpretation semantics} and
4050: @dfn{compilation semantics} for a word
1.29 crook 4051: depend upon the way in which the word was defined (for example, whether
4052: it is an @dfn{immediate} word).
1.28 crook 4053: @item
1.29 crook 4054: Forth definitions can be implemented in Forth (called @dfn{high-level
4055: definitions}) or in some other way (usually a lower-level language and
4056: as a result often called @dfn{low-level definitions}, @dfn{code
4057: definitions} or @dfn{primitives}).
1.28 crook 4058: @item
1.29 crook 4059: Many Forth systems are implemented mainly in Forth.
1.28 crook 4060: @end itemize
4061:
4062:
1.29 crook 4063: @comment ----------------------------------------------
1.48 anton 4064: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4065: @section Where To Go Next
4066: @cindex where to go next
1.28 crook 4067:
1.29 crook 4068: Amazing as it may seem, if you have read (and understood) this far, you
4069: know almost all the fundamentals about the inner workings of a Forth
4070: system. You certainly know enough to be able to read and understand the
4071: rest of this manual and the ANS Forth document, to learn more about the
4072: facilities that Forth in general and Gforth in particular provide. Even
4073: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4074: However, that's not a good idea just yet... better to try writing some
1.29 crook 4075: programs in Gforth.
1.28 crook 4076:
1.29 crook 4077: Forth has such a rich vocabulary that it can be hard to know where to
4078: start in learning it. This section suggests a few sets of words that are
4079: enough to write small but useful programs. Use the word index in this
4080: document to learn more about each word, then try it out and try to write
4081: small definitions using it. Start by experimenting with these words:
1.28 crook 4082:
4083: @itemize @bullet
4084: @item
1.29 crook 4085: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4086: @item
4087: Comparison: @code{MIN MAX =}
4088: @item
4089: Logic: @code{AND OR XOR NOT}
4090: @item
4091: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4092: @item
1.29 crook 4093: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4094: @item
1.29 crook 4095: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4096: @item
1.29 crook 4097: Defining words: @code{: ; CREATE}
1.28 crook 4098: @item
1.29 crook 4099: Memory allocation words: @code{ALLOT ,}
1.28 crook 4100: @item
1.29 crook 4101: Tools: @code{SEE WORDS .S MARKER}
4102: @end itemize
4103:
4104: When you have mastered those, go on to:
4105:
4106: @itemize @bullet
1.28 crook 4107: @item
1.29 crook 4108: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4109: @item
1.29 crook 4110: Memory access: @code{@@ !}
1.28 crook 4111: @end itemize
1.23 crook 4112:
1.29 crook 4113: When you have mastered these, there's nothing for it but to read through
4114: the whole of this manual and find out what you've missed.
4115:
4116: @comment ----------------------------------------------
1.48 anton 4117: @node Exercises, , Where to go next, Introduction
1.29 crook 4118: @section Exercises
4119: @cindex exercises
4120:
4121: TODO: provide a set of programming excercises linked into the stuff done
4122: already and into other sections of the manual. Provide solutions to all
4123: the exercises in a .fs file in the distribution.
4124:
4125: @c Get some inspiration from Starting Forth and Kelly&Spies.
4126:
4127: @c excercises:
4128: @c 1. take inches and convert to feet and inches.
4129: @c 2. take temperature and convert from fahrenheight to celcius;
4130: @c may need to care about symmetric vs floored??
4131: @c 3. take input line and do character substitution
4132: @c to encipher or decipher
4133: @c 4. as above but work on a file for in and out
4134: @c 5. take input line and convert to pig-latin
4135: @c
4136: @c thing of sets of things to exercise then come up with
4137: @c problems that need those things.
4138:
4139:
1.26 crook 4140: @c ******************************************************************
1.29 crook 4141: @node Words, Error messages, Introduction, Top
1.1 anton 4142: @chapter Forth Words
1.26 crook 4143: @cindex words
1.1 anton 4144:
4145: @menu
4146: * Notation::
1.65 anton 4147: * Case insensitivity::
4148: * Comments::
4149: * Boolean Flags::
1.1 anton 4150: * Arithmetic::
4151: * Stack Manipulation::
1.5 anton 4152: * Memory::
1.1 anton 4153: * Control Structures::
4154: * Defining Words::
1.65 anton 4155: * Interpretation and Compilation Semantics::
1.47 crook 4156: * Tokens for Words::
1.81 anton 4157: * Compiling words::
1.65 anton 4158: * The Text Interpreter::
1.111 anton 4159: * The Input Stream::
1.65 anton 4160: * Word Lists::
4161: * Environmental Queries::
1.12 anton 4162: * Files::
4163: * Blocks::
4164: * Other I/O::
1.78 anton 4165: * Locals::
4166: * Structures::
4167: * Object-oriented Forth::
1.12 anton 4168: * Programming Tools::
4169: * Assembler and Code Words::
4170: * Threading Words::
1.65 anton 4171: * Passing Commands to the OS::
4172: * Keeping track of Time::
4173: * Miscellaneous Words::
1.1 anton 4174: @end menu
4175:
1.65 anton 4176: @node Notation, Case insensitivity, Words, Words
1.1 anton 4177: @section Notation
4178: @cindex notation of glossary entries
4179: @cindex format of glossary entries
4180: @cindex glossary notation format
4181: @cindex word glossary entry format
4182:
4183: The Forth words are described in this section in the glossary notation
1.67 anton 4184: that has become a de-facto standard for Forth texts:
1.1 anton 4185:
4186: @format
1.29 crook 4187: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4188: @end format
1.29 crook 4189: @i{Description}
1.1 anton 4190:
4191: @table @var
4192: @item word
1.28 crook 4193: The name of the word.
1.1 anton 4194:
4195: @item Stack effect
4196: @cindex stack effect
1.29 crook 4197: The stack effect is written in the notation @code{@i{before} --
4198: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4199: stack entries before and after the execution of the word. The rest of
4200: the stack is not touched by the word. The top of stack is rightmost,
4201: i.e., a stack sequence is written as it is typed in. Note that Gforth
4202: uses a separate floating point stack, but a unified stack
1.29 crook 4203: notation. Also, return stack effects are not shown in @i{stack
4204: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4205: the type and/or the function of the item. See below for a discussion of
4206: the types.
4207:
4208: All words have two stack effects: A compile-time stack effect and a
4209: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4210: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4211: this standard behaviour, or the word does other unusual things at
4212: compile time, both stack effects are shown; otherwise only the run-time
4213: stack effect is shown.
4214:
4215: @cindex pronounciation of words
4216: @item pronunciation
4217: How the word is pronounced.
4218:
4219: @cindex wordset
1.67 anton 4220: @cindex environment wordset
1.1 anton 4221: @item wordset
1.21 crook 4222: The ANS Forth standard is divided into several word sets. A standard
4223: system need not support all of them. Therefore, in theory, the fewer
4224: word sets your program uses the more portable it will be. However, we
4225: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4226: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4227: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4228: describes words that will work in future releases of Gforth;
4229: @code{gforth-internal} words are more volatile. Environmental query
4230: strings are also displayed like words; you can recognize them by the
1.21 crook 4231: @code{environment} in the word set field.
1.1 anton 4232:
4233: @item Description
4234: A description of the behaviour of the word.
4235: @end table
4236:
4237: @cindex types of stack items
4238: @cindex stack item types
4239: The type of a stack item is specified by the character(s) the name
4240: starts with:
4241:
4242: @table @code
4243: @item f
4244: @cindex @code{f}, stack item type
4245: Boolean flags, i.e. @code{false} or @code{true}.
4246: @item c
4247: @cindex @code{c}, stack item type
4248: Char
4249: @item w
4250: @cindex @code{w}, stack item type
4251: Cell, can contain an integer or an address
4252: @item n
4253: @cindex @code{n}, stack item type
4254: signed integer
4255: @item u
4256: @cindex @code{u}, stack item type
4257: unsigned integer
4258: @item d
4259: @cindex @code{d}, stack item type
4260: double sized signed integer
4261: @item ud
4262: @cindex @code{ud}, stack item type
4263: double sized unsigned integer
4264: @item r
4265: @cindex @code{r}, stack item type
4266: Float (on the FP stack)
1.21 crook 4267: @item a-
1.1 anton 4268: @cindex @code{a_}, stack item type
4269: Cell-aligned address
1.21 crook 4270: @item c-
1.1 anton 4271: @cindex @code{c_}, stack item type
4272: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4273: @item f-
1.1 anton 4274: @cindex @code{f_}, stack item type
4275: Float-aligned address
1.21 crook 4276: @item df-
1.1 anton 4277: @cindex @code{df_}, stack item type
4278: Address aligned for IEEE double precision float
1.21 crook 4279: @item sf-
1.1 anton 4280: @cindex @code{sf_}, stack item type
4281: Address aligned for IEEE single precision float
4282: @item xt
4283: @cindex @code{xt}, stack item type
4284: Execution token, same size as Cell
4285: @item wid
4286: @cindex @code{wid}, stack item type
1.21 crook 4287: Word list ID, same size as Cell
1.68 anton 4288: @item ior, wior
4289: @cindex ior type description
4290: @cindex wior type description
4291: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4292: @item f83name
4293: @cindex @code{f83name}, stack item type
4294: Pointer to a name structure
4295: @item "
4296: @cindex @code{"}, stack item type
1.12 anton 4297: string in the input stream (not on the stack). The terminating character
4298: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4299: quotes.
4300: @end table
4301:
1.65 anton 4302: @comment ----------------------------------------------
4303: @node Case insensitivity, Comments, Notation, Words
4304: @section Case insensitivity
4305: @cindex case sensitivity
4306: @cindex upper and lower case
4307:
4308: Gforth is case-insensitive; you can enter definitions and invoke
4309: Standard words using upper, lower or mixed case (however,
4310: @pxref{core-idef, Implementation-defined options, Implementation-defined
4311: options}).
4312:
4313: ANS Forth only @i{requires} implementations to recognise Standard words
4314: when they are typed entirely in upper case. Therefore, a Standard
4315: program must use upper case for all Standard words. You can use whatever
4316: case you like for words that you define, but in a Standard program you
4317: have to use the words in the same case that you defined them.
4318:
4319: Gforth supports case sensitivity through @code{table}s (case-sensitive
4320: wordlists, @pxref{Word Lists}).
4321:
4322: Two people have asked how to convert Gforth to be case-sensitive; while
4323: we think this is a bad idea, you can change all wordlists into tables
4324: like this:
4325:
4326: @example
4327: ' table-find forth-wordlist wordlist-map @ !
4328: @end example
4329:
4330: Note that you now have to type the predefined words in the same case
4331: that we defined them, which are varying. You may want to convert them
4332: to your favourite case before doing this operation (I won't explain how,
4333: because if you are even contemplating doing this, you'd better have
4334: enough knowledge of Forth systems to know this already).
4335:
4336: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4337: @section Comments
1.26 crook 4338: @cindex comments
1.21 crook 4339:
1.29 crook 4340: Forth supports two styles of comment; the traditional @i{in-line} comment,
4341: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4342:
1.44 crook 4343:
1.23 crook 4344: doc-(
1.21 crook 4345: doc-\
1.23 crook 4346: doc-\G
1.21 crook 4347:
1.44 crook 4348:
1.21 crook 4349: @node Boolean Flags, Arithmetic, Comments, Words
4350: @section Boolean Flags
1.26 crook 4351: @cindex Boolean flags
1.21 crook 4352:
4353: A Boolean flag is cell-sized. A cell with all bits clear represents the
4354: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4355: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4356: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4357: @c on and off to Memory?
4358: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4359:
1.21 crook 4360: doc-true
4361: doc-false
1.29 crook 4362: doc-on
4363: doc-off
1.21 crook 4364:
1.44 crook 4365:
1.21 crook 4366: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4367: @section Arithmetic
4368: @cindex arithmetic words
4369:
4370: @cindex division with potentially negative operands
4371: Forth arithmetic is not checked, i.e., you will not hear about integer
4372: overflow on addition or multiplication, you may hear about division by
4373: zero if you are lucky. The operator is written after the operands, but
4374: the operands are still in the original order. I.e., the infix @code{2-1}
4375: corresponds to @code{2 1 -}. Forth offers a variety of division
4376: operators. If you perform division with potentially negative operands,
4377: you do not want to use @code{/} or @code{/mod} with its undefined
4378: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4379: former, @pxref{Mixed precision}).
1.26 crook 4380: @comment TODO discuss the different division forms and the std approach
1.1 anton 4381:
4382: @menu
4383: * Single precision::
1.67 anton 4384: * Double precision:: Double-cell integer arithmetic
1.1 anton 4385: * Bitwise operations::
1.67 anton 4386: * Numeric comparison::
1.29 crook 4387: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4388: * Floating Point::
4389: @end menu
4390:
1.67 anton 4391: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4392: @subsection Single precision
4393: @cindex single precision arithmetic words
4394:
1.67 anton 4395: @c !! cell undefined
4396:
4397: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4398: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4399: treat them. For the rules used by the text interpreter for recognising
4400: single-precision integers see @ref{Number Conversion}.
1.21 crook 4401:
1.67 anton 4402: These words are all defined for signed operands, but some of them also
4403: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4404: @code{*}.
1.44 crook 4405:
1.1 anton 4406: doc-+
1.21 crook 4407: doc-1+
1.1 anton 4408: doc--
1.21 crook 4409: doc-1-
1.1 anton 4410: doc-*
4411: doc-/
4412: doc-mod
4413: doc-/mod
4414: doc-negate
4415: doc-abs
4416: doc-min
4417: doc-max
1.27 crook 4418: doc-floored
1.1 anton 4419:
1.44 crook 4420:
1.67 anton 4421: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4422: @subsection Double precision
4423: @cindex double precision arithmetic words
4424:
1.49 anton 4425: For the rules used by the text interpreter for
4426: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4427:
4428: A double precision number is represented by a cell pair, with the most
1.67 anton 4429: significant cell at the TOS. It is trivial to convert an unsigned single
4430: to a double: simply push a @code{0} onto the TOS. Since numbers are
4431: represented by Gforth using 2's complement arithmetic, converting a
4432: signed single to a (signed) double requires sign-extension across the
4433: most significant cell. This can be achieved using @code{s>d}. The moral
4434: of the story is that you cannot convert a number without knowing whether
4435: it represents an unsigned or a signed number.
1.21 crook 4436:
1.67 anton 4437: These words are all defined for signed operands, but some of them also
4438: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4439:
1.21 crook 4440: doc-s>d
1.67 anton 4441: doc-d>s
1.21 crook 4442: doc-d+
4443: doc-d-
4444: doc-dnegate
4445: doc-dabs
4446: doc-dmin
4447: doc-dmax
4448:
1.44 crook 4449:
1.67 anton 4450: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4451: @subsection Bitwise operations
4452: @cindex bitwise operation words
4453:
4454:
4455: doc-and
4456: doc-or
4457: doc-xor
4458: doc-invert
4459: doc-lshift
4460: doc-rshift
4461: doc-2*
4462: doc-d2*
4463: doc-2/
4464: doc-d2/
4465:
4466:
4467: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4468: @subsection Numeric comparison
4469: @cindex numeric comparison words
4470:
1.67 anton 4471: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4472: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4473:
1.28 crook 4474: doc-<
4475: doc-<=
4476: doc-<>
4477: doc-=
4478: doc->
4479: doc->=
4480:
1.21 crook 4481: doc-0<
1.23 crook 4482: doc-0<=
1.21 crook 4483: doc-0<>
4484: doc-0=
1.23 crook 4485: doc-0>
4486: doc-0>=
1.28 crook 4487:
4488: doc-u<
4489: doc-u<=
1.44 crook 4490: @c u<> and u= exist but are the same as <> and =
1.31 anton 4491: @c doc-u<>
4492: @c doc-u=
1.28 crook 4493: doc-u>
4494: doc-u>=
4495:
4496: doc-within
4497:
4498: doc-d<
4499: doc-d<=
4500: doc-d<>
4501: doc-d=
4502: doc-d>
4503: doc-d>=
1.23 crook 4504:
1.21 crook 4505: doc-d0<
1.23 crook 4506: doc-d0<=
4507: doc-d0<>
1.21 crook 4508: doc-d0=
1.23 crook 4509: doc-d0>
4510: doc-d0>=
4511:
1.21 crook 4512: doc-du<
1.28 crook 4513: doc-du<=
1.44 crook 4514: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4515: @c doc-du<>
4516: @c doc-du=
1.28 crook 4517: doc-du>
4518: doc-du>=
1.1 anton 4519:
1.44 crook 4520:
1.21 crook 4521: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4522: @subsection Mixed precision
4523: @cindex mixed precision arithmetic words
4524:
1.44 crook 4525:
1.1 anton 4526: doc-m+
4527: doc-*/
4528: doc-*/mod
4529: doc-m*
4530: doc-um*
4531: doc-m*/
4532: doc-um/mod
4533: doc-fm/mod
4534: doc-sm/rem
4535:
1.44 crook 4536:
1.21 crook 4537: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4538: @subsection Floating Point
4539: @cindex floating point arithmetic words
4540:
1.49 anton 4541: For the rules used by the text interpreter for
4542: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4543:
1.67 anton 4544: Gforth has a separate floating point stack, but the documentation uses
4545: the unified notation.@footnote{It's easy to generate the separate
4546: notation from that by just separating the floating-point numbers out:
4547: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4548: r3 )}.}
1.1 anton 4549:
4550: @cindex floating-point arithmetic, pitfalls
4551: Floating point numbers have a number of unpleasant surprises for the
4552: unwary (e.g., floating point addition is not associative) and even a few
4553: for the wary. You should not use them unless you know what you are doing
4554: or you don't care that the results you get are totally bogus. If you
4555: want to learn about the problems of floating point numbers (and how to
1.66 anton 4556: avoid them), you might start with @cite{David Goldberg,
4557: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4558: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4559: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4560:
1.44 crook 4561:
1.21 crook 4562: doc-d>f
4563: doc-f>d
1.1 anton 4564: doc-f+
4565: doc-f-
4566: doc-f*
4567: doc-f/
4568: doc-fnegate
4569: doc-fabs
4570: doc-fmax
4571: doc-fmin
4572: doc-floor
4573: doc-fround
4574: doc-f**
4575: doc-fsqrt
4576: doc-fexp
4577: doc-fexpm1
4578: doc-fln
4579: doc-flnp1
4580: doc-flog
4581: doc-falog
1.32 anton 4582: doc-f2*
4583: doc-f2/
4584: doc-1/f
4585: doc-precision
4586: doc-set-precision
4587:
4588: @cindex angles in trigonometric operations
4589: @cindex trigonometric operations
4590: Angles in floating point operations are given in radians (a full circle
4591: has 2 pi radians).
4592:
1.1 anton 4593: doc-fsin
4594: doc-fcos
4595: doc-fsincos
4596: doc-ftan
4597: doc-fasin
4598: doc-facos
4599: doc-fatan
4600: doc-fatan2
4601: doc-fsinh
4602: doc-fcosh
4603: doc-ftanh
4604: doc-fasinh
4605: doc-facosh
4606: doc-fatanh
1.21 crook 4607: doc-pi
1.28 crook 4608:
1.32 anton 4609: @cindex equality of floats
4610: @cindex floating-point comparisons
1.31 anton 4611: One particular problem with floating-point arithmetic is that comparison
4612: for equality often fails when you would expect it to succeed. For this
4613: reason approximate equality is often preferred (but you still have to
1.67 anton 4614: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4615: differently from what you might expect. The comparison words are:
1.31 anton 4616:
4617: doc-f~rel
4618: doc-f~abs
1.68 anton 4619: doc-f~
1.31 anton 4620: doc-f=
4621: doc-f<>
4622:
4623: doc-f<
4624: doc-f<=
4625: doc-f>
4626: doc-f>=
4627:
1.21 crook 4628: doc-f0<
1.28 crook 4629: doc-f0<=
4630: doc-f0<>
1.21 crook 4631: doc-f0=
1.28 crook 4632: doc-f0>
4633: doc-f0>=
4634:
1.1 anton 4635:
4636: @node Stack Manipulation, Memory, Arithmetic, Words
4637: @section Stack Manipulation
4638: @cindex stack manipulation words
4639:
4640: @cindex floating-point stack in the standard
1.21 crook 4641: Gforth maintains a number of separate stacks:
4642:
1.29 crook 4643: @cindex data stack
4644: @cindex parameter stack
1.21 crook 4645: @itemize @bullet
4646: @item
1.29 crook 4647: A data stack (also known as the @dfn{parameter stack}) -- for
4648: characters, cells, addresses, and double cells.
1.21 crook 4649:
1.29 crook 4650: @cindex floating-point stack
1.21 crook 4651: @item
1.44 crook 4652: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4653:
1.29 crook 4654: @cindex return stack
1.21 crook 4655: @item
1.44 crook 4656: A return stack -- for holding the return addresses of colon
1.32 anton 4657: definitions and other (non-FP) data.
1.21 crook 4658:
1.29 crook 4659: @cindex locals stack
1.21 crook 4660: @item
1.44 crook 4661: A locals stack -- for holding local variables.
1.21 crook 4662: @end itemize
4663:
1.1 anton 4664: @menu
4665: * Data stack::
4666: * Floating point stack::
4667: * Return stack::
4668: * Locals stack::
4669: * Stack pointer manipulation::
4670: @end menu
4671:
4672: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4673: @subsection Data stack
4674: @cindex data stack manipulation words
4675: @cindex stack manipulations words, data stack
4676:
1.44 crook 4677:
1.1 anton 4678: doc-drop
4679: doc-nip
4680: doc-dup
4681: doc-over
4682: doc-tuck
4683: doc-swap
1.21 crook 4684: doc-pick
1.1 anton 4685: doc-rot
4686: doc--rot
4687: doc-?dup
4688: doc-roll
4689: doc-2drop
4690: doc-2nip
4691: doc-2dup
4692: doc-2over
4693: doc-2tuck
4694: doc-2swap
4695: doc-2rot
4696:
1.44 crook 4697:
1.1 anton 4698: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4699: @subsection Floating point stack
4700: @cindex floating-point stack manipulation words
4701: @cindex stack manipulation words, floating-point stack
4702:
1.32 anton 4703: Whilst every sane Forth has a separate floating-point stack, it is not
4704: strictly required; an ANS Forth system could theoretically keep
4705: floating-point numbers on the data stack. As an additional difficulty,
4706: you don't know how many cells a floating-point number takes. It is
4707: reportedly possible to write words in a way that they work also for a
4708: unified stack model, but we do not recommend trying it. Instead, just
4709: say that your program has an environmental dependency on a separate
4710: floating-point stack.
4711:
4712: doc-floating-stack
4713:
1.1 anton 4714: doc-fdrop
4715: doc-fnip
4716: doc-fdup
4717: doc-fover
4718: doc-ftuck
4719: doc-fswap
1.21 crook 4720: doc-fpick
1.1 anton 4721: doc-frot
4722:
1.44 crook 4723:
1.1 anton 4724: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4725: @subsection Return stack
4726: @cindex return stack manipulation words
4727: @cindex stack manipulation words, return stack
4728:
1.32 anton 4729: @cindex return stack and locals
4730: @cindex locals and return stack
4731: A Forth system is allowed to keep local variables on the
4732: return stack. This is reasonable, as local variables usually eliminate
4733: the need to use the return stack explicitly. So, if you want to produce
4734: a standard compliant program and you are using local variables in a
4735: word, forget about return stack manipulations in that word (refer to the
4736: standard document for the exact rules).
4737:
1.1 anton 4738: doc->r
4739: doc-r>
4740: doc-r@
4741: doc-rdrop
4742: doc-2>r
4743: doc-2r>
4744: doc-2r@
4745: doc-2rdrop
4746:
1.44 crook 4747:
1.1 anton 4748: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4749: @subsection Locals stack
4750:
1.78 anton 4751: Gforth uses an extra locals stack. It is described, along with the
4752: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4753:
1.1 anton 4754: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4755: @subsection Stack pointer manipulation
4756: @cindex stack pointer manipulation words
4757:
1.44 crook 4758: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4759: doc-sp0
1.1 anton 4760: doc-sp@
4761: doc-sp!
1.21 crook 4762: doc-fp0
1.1 anton 4763: doc-fp@
4764: doc-fp!
1.21 crook 4765: doc-rp0
1.1 anton 4766: doc-rp@
4767: doc-rp!
1.21 crook 4768: doc-lp0
1.1 anton 4769: doc-lp@
4770: doc-lp!
4771:
1.44 crook 4772:
1.1 anton 4773: @node Memory, Control Structures, Stack Manipulation, Words
4774: @section Memory
1.26 crook 4775: @cindex memory words
1.1 anton 4776:
1.32 anton 4777: @menu
4778: * Memory model::
4779: * Dictionary allocation::
4780: * Heap Allocation::
4781: * Memory Access::
4782: * Address arithmetic::
4783: * Memory Blocks::
4784: @end menu
4785:
1.67 anton 4786: In addition to the standard Forth memory allocation words, there is also
4787: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4788: garbage collector}.
4789:
1.32 anton 4790: @node Memory model, Dictionary allocation, Memory, Memory
4791: @subsection ANS Forth and Gforth memory models
4792:
4793: @c The ANS Forth description is a mess (e.g., is the heap part of
4794: @c the dictionary?), so let's not stick to closely with it.
4795:
1.67 anton 4796: ANS Forth considers a Forth system as consisting of several address
4797: spaces, of which only @dfn{data space} is managed and accessible with
4798: the memory words. Memory not necessarily in data space includes the
4799: stacks, the code (called code space) and the headers (called name
4800: space). In Gforth everything is in data space, but the code for the
4801: primitives is usually read-only.
1.32 anton 4802:
4803: Data space is divided into a number of areas: The (data space portion of
4804: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4805: refer to the search data structure embodied in word lists and headers,
4806: because it is used for looking up names, just as you would in a
4807: conventional dictionary.}, the heap, and a number of system-allocated
4808: buffers.
4809:
1.68 anton 4810: @cindex address arithmetic restrictions, ANS vs. Gforth
4811: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4812: In ANS Forth data space is also divided into contiguous regions. You
4813: can only use address arithmetic within a contiguous region, not between
4814: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4815: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4816: allocation}).
4817:
4818: Gforth provides one big address space, and address arithmetic can be
4819: performed between any addresses. However, in the dictionary headers or
4820: code are interleaved with data, so almost the only contiguous data space
4821: regions there are those described by ANS Forth as contiguous; but you
4822: can be sure that the dictionary is allocated towards increasing
4823: addresses even between contiguous regions. The memory order of
4824: allocations in the heap is platform-dependent (and possibly different
4825: from one run to the next).
4826:
1.27 crook 4827:
1.32 anton 4828: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4829: @subsection Dictionary allocation
1.27 crook 4830: @cindex reserving data space
4831: @cindex data space - reserving some
4832:
1.32 anton 4833: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4834: you want to deallocate X, you also deallocate everything
4835: allocated after X.
4836:
1.68 anton 4837: @cindex contiguous regions in dictionary allocation
1.32 anton 4838: The allocations using the words below are contiguous and grow the region
4839: towards increasing addresses. Other words that allocate dictionary
4840: memory of any kind (i.e., defining words including @code{:noname}) end
4841: the contiguous region and start a new one.
4842:
4843: In ANS Forth only @code{create}d words are guaranteed to produce an
4844: address that is the start of the following contiguous region. In
4845: particular, the cell allocated by @code{variable} is not guaranteed to
4846: be contiguous with following @code{allot}ed memory.
4847:
4848: You can deallocate memory by using @code{allot} with a negative argument
4849: (with some restrictions, see @code{allot}). For larger deallocations use
4850: @code{marker}.
1.27 crook 4851:
1.29 crook 4852:
1.27 crook 4853: doc-here
4854: doc-unused
4855: doc-allot
4856: doc-c,
1.29 crook 4857: doc-f,
1.27 crook 4858: doc-,
4859: doc-2,
4860:
1.32 anton 4861: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4862: course you should allocate memory in an aligned way, too. I.e., before
4863: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4864: The words below align @code{here} if it is not already. Basically it is
4865: only already aligned for a type, if the last allocation was a multiple
4866: of the size of this type and if @code{here} was aligned for this type
4867: before.
4868:
4869: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4870: ANS Forth (@code{maxalign}ed in Gforth).
4871:
4872: doc-align
4873: doc-falign
4874: doc-sfalign
4875: doc-dfalign
4876: doc-maxalign
4877: doc-cfalign
4878:
4879:
4880: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4881: @subsection Heap allocation
4882: @cindex heap allocation
4883: @cindex dynamic allocation of memory
4884: @cindex memory-allocation word set
4885:
1.68 anton 4886: @cindex contiguous regions and heap allocation
1.32 anton 4887: Heap allocation supports deallocation of allocated memory in any
4888: order. Dictionary allocation is not affected by it (i.e., it does not
4889: end a contiguous region). In Gforth, these words are implemented using
4890: the standard C library calls malloc(), free() and resize().
4891:
1.68 anton 4892: The memory region produced by one invocation of @code{allocate} or
4893: @code{resize} is internally contiguous. There is no contiguity between
4894: such a region and any other region (including others allocated from the
4895: heap).
4896:
1.32 anton 4897: doc-allocate
4898: doc-free
4899: doc-resize
4900:
1.27 crook 4901:
1.32 anton 4902: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4903: @subsection Memory Access
4904: @cindex memory access words
4905:
4906: doc-@
4907: doc-!
4908: doc-+!
4909: doc-c@
4910: doc-c!
4911: doc-2@
4912: doc-2!
4913: doc-f@
4914: doc-f!
4915: doc-sf@
4916: doc-sf!
4917: doc-df@
4918: doc-df!
4919:
1.68 anton 4920:
1.32 anton 4921: @node Address arithmetic, Memory Blocks, Memory Access, Memory
4922: @subsection Address arithmetic
1.1 anton 4923: @cindex address arithmetic words
4924:
1.67 anton 4925: Address arithmetic is the foundation on which you can build data
4926: structures like arrays, records (@pxref{Structures}) and objects
4927: (@pxref{Object-oriented Forth}).
1.32 anton 4928:
1.68 anton 4929: @cindex address unit
4930: @cindex au (address unit)
1.1 anton 4931: ANS Forth does not specify the sizes of the data types. Instead, it
4932: offers a number of words for computing sizes and doing address
1.29 crook 4933: arithmetic. Address arithmetic is performed in terms of address units
4934: (aus); on most systems the address unit is one byte. Note that a
4935: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 4936: platforms where it is a noop, it compiles to nothing).
1.1 anton 4937:
1.67 anton 4938: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
4939: you have the address of a cell, perform @code{1 cells +}, and you will
4940: have the address of the next cell.
4941:
1.68 anton 4942: @cindex contiguous regions and address arithmetic
1.67 anton 4943: In ANS Forth you can perform address arithmetic only within a contiguous
4944: region, i.e., if you have an address into one region, you can only add
4945: and subtract such that the result is still within the region; you can
4946: only subtract or compare addresses from within the same contiguous
4947: region. Reasons: several contiguous regions can be arranged in memory
4948: in any way; on segmented systems addresses may have unusual
4949: representations, such that address arithmetic only works within a
4950: region. Gforth provides a few more guarantees (linear address space,
4951: dictionary grows upwards), but in general I have found it easy to stay
4952: within contiguous regions (exception: computing and comparing to the
4953: address just beyond the end of an array).
4954:
1.1 anton 4955: @cindex alignment of addresses for types
4956: ANS Forth also defines words for aligning addresses for specific
4957: types. Many computers require that accesses to specific data types
4958: must only occur at specific addresses; e.g., that cells may only be
4959: accessed at addresses divisible by 4. Even if a machine allows unaligned
4960: accesses, it can usually perform aligned accesses faster.
4961:
4962: For the performance-conscious: alignment operations are usually only
4963: necessary during the definition of a data structure, not during the
4964: (more frequent) accesses to it.
4965:
4966: ANS Forth defines no words for character-aligning addresses. This is not
4967: an oversight, but reflects the fact that addresses that are not
4968: char-aligned have no use in the standard and therefore will not be
4969: created.
4970:
4971: @cindex @code{CREATE} and alignment
1.29 crook 4972: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 4973: are cell-aligned; in addition, Gforth guarantees that these addresses
4974: are aligned for all purposes.
4975:
1.26 crook 4976: Note that the ANS Forth word @code{char} has nothing to do with address
4977: arithmetic.
1.1 anton 4978:
1.44 crook 4979:
1.1 anton 4980: doc-chars
4981: doc-char+
4982: doc-cells
4983: doc-cell+
4984: doc-cell
4985: doc-aligned
4986: doc-floats
4987: doc-float+
4988: doc-float
4989: doc-faligned
4990: doc-sfloats
4991: doc-sfloat+
4992: doc-sfaligned
4993: doc-dfloats
4994: doc-dfloat+
4995: doc-dfaligned
4996: doc-maxaligned
4997: doc-cfaligned
4998: doc-address-unit-bits
4999:
1.44 crook 5000:
1.32 anton 5001: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5002: @subsection Memory Blocks
5003: @cindex memory block words
1.27 crook 5004: @cindex character strings - moving and copying
5005:
1.49 anton 5006: Memory blocks often represent character strings; For ways of storing
5007: character strings in memory see @ref{String Formats}. For other
5008: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5009:
1.67 anton 5010: A few of these words work on address unit blocks. In that case, you
5011: usually have to insert @code{CHARS} before the word when working on
5012: character strings. Most words work on character blocks, and expect a
5013: char-aligned address.
5014:
5015: When copying characters between overlapping memory regions, use
5016: @code{chars move} or choose carefully between @code{cmove} and
5017: @code{cmove>}.
1.44 crook 5018:
1.1 anton 5019: doc-move
5020: doc-erase
5021: doc-cmove
5022: doc-cmove>
5023: doc-fill
5024: doc-blank
1.21 crook 5025: doc-compare
1.111 anton 5026: doc-str=
5027: doc-str<
5028: doc-string-prefix?
1.21 crook 5029: doc-search
1.27 crook 5030: doc--trailing
5031: doc-/string
1.82 anton 5032: doc-bounds
1.44 crook 5033:
1.111 anton 5034:
1.27 crook 5035: @comment TODO examples
5036:
1.1 anton 5037:
1.26 crook 5038: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5039: @section Control Structures
5040: @cindex control structures
5041:
1.33 anton 5042: Control structures in Forth cannot be used interpretively, only in a
5043: colon definition@footnote{To be precise, they have no interpretation
5044: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5045: not like this limitation, but have not seen a satisfying way around it
5046: yet, although many schemes have been proposed.
1.1 anton 5047:
5048: @menu
1.33 anton 5049: * Selection:: IF ... ELSE ... ENDIF
5050: * Simple Loops:: BEGIN ...
1.29 crook 5051: * Counted Loops:: DO
1.67 anton 5052: * Arbitrary control structures::
5053: * Calls and returns::
1.1 anton 5054: * Exception Handling::
5055: @end menu
5056:
5057: @node Selection, Simple Loops, Control Structures, Control Structures
5058: @subsection Selection
5059: @cindex selection control structures
5060: @cindex control structures for selection
5061:
5062: @cindex @code{IF} control structure
5063: @example
1.29 crook 5064: @i{flag}
1.1 anton 5065: IF
1.29 crook 5066: @i{code}
1.1 anton 5067: ENDIF
5068: @end example
1.21 crook 5069: @noindent
1.33 anton 5070:
1.44 crook 5071: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5072: with any bit set represents truth) @i{code} is executed.
1.33 anton 5073:
1.1 anton 5074: @example
1.29 crook 5075: @i{flag}
1.1 anton 5076: IF
1.29 crook 5077: @i{code1}
1.1 anton 5078: ELSE
1.29 crook 5079: @i{code2}
1.1 anton 5080: ENDIF
5081: @end example
5082:
1.44 crook 5083: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5084: executed.
1.33 anton 5085:
1.1 anton 5086: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5087: standard, and @code{ENDIF} is not, although it is quite popular. We
5088: recommend using @code{ENDIF}, because it is less confusing for people
5089: who also know other languages (and is not prone to reinforcing negative
5090: prejudices against Forth in these people). Adding @code{ENDIF} to a
5091: system that only supplies @code{THEN} is simple:
5092: @example
1.82 anton 5093: : ENDIF POSTPONE then ; immediate
1.1 anton 5094: @end example
5095:
5096: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5097: (adv.)} has the following meanings:
5098: @quotation
5099: ... 2b: following next after in order ... 3d: as a necessary consequence
5100: (if you were there, then you saw them).
5101: @end quotation
5102: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5103: and many other programming languages has the meaning 3d.]
5104:
1.21 crook 5105: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5106: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5107: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5108: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5109: @file{compat/control.fs}.
5110:
5111: @cindex @code{CASE} control structure
5112: @example
1.29 crook 5113: @i{n}
1.1 anton 5114: CASE
1.29 crook 5115: @i{n1} OF @i{code1} ENDOF
5116: @i{n2} OF @i{code2} ENDOF
1.1 anton 5117: @dots{}
1.68 anton 5118: ( n ) @i{default-code} ( n )
1.1 anton 5119: ENDCASE
5120: @end example
5121:
1.68 anton 5122: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5123: @i{ni} matches, the optional @i{default-code} is executed. The optional
5124: default case can be added by simply writing the code after the last
5125: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5126: not consume it.
1.1 anton 5127:
1.69 anton 5128: @progstyle
5129: To keep the code understandable, you should ensure that on all paths
5130: through a selection construct the stack is changed in the same way
5131: (wrt. number and types of stack items consumed and pushed).
5132:
1.1 anton 5133: @node Simple Loops, Counted Loops, Selection, Control Structures
5134: @subsection Simple Loops
5135: @cindex simple loops
5136: @cindex loops without count
5137:
5138: @cindex @code{WHILE} loop
5139: @example
5140: BEGIN
1.29 crook 5141: @i{code1}
5142: @i{flag}
1.1 anton 5143: WHILE
1.29 crook 5144: @i{code2}
1.1 anton 5145: REPEAT
5146: @end example
5147:
1.29 crook 5148: @i{code1} is executed and @i{flag} is computed. If it is true,
5149: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5150: false, execution continues after the @code{REPEAT}.
5151:
5152: @cindex @code{UNTIL} loop
5153: @example
5154: BEGIN
1.29 crook 5155: @i{code}
5156: @i{flag}
1.1 anton 5157: UNTIL
5158: @end example
5159:
1.29 crook 5160: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5161:
1.69 anton 5162: @progstyle
5163: To keep the code understandable, a complete iteration of the loop should
5164: not change the number and types of the items on the stacks.
5165:
1.1 anton 5166: @cindex endless loop
5167: @cindex loops, endless
5168: @example
5169: BEGIN
1.29 crook 5170: @i{code}
1.1 anton 5171: AGAIN
5172: @end example
5173:
5174: This is an endless loop.
5175:
5176: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5177: @subsection Counted Loops
5178: @cindex counted loops
5179: @cindex loops, counted
5180: @cindex @code{DO} loops
5181:
5182: The basic counted loop is:
5183: @example
1.29 crook 5184: @i{limit} @i{start}
1.1 anton 5185: ?DO
1.29 crook 5186: @i{body}
1.1 anton 5187: LOOP
5188: @end example
5189:
1.29 crook 5190: This performs one iteration for every integer, starting from @i{start}
5191: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5192: accessed with @code{i}. For example, the loop:
1.1 anton 5193: @example
5194: 10 0 ?DO
5195: i .
5196: LOOP
5197: @end example
1.21 crook 5198: @noindent
5199: prints @code{0 1 2 3 4 5 6 7 8 9}
5200:
1.1 anton 5201: The index of the innermost loop can be accessed with @code{i}, the index
5202: of the next loop with @code{j}, and the index of the third loop with
5203: @code{k}.
5204:
1.44 crook 5205:
1.1 anton 5206: doc-i
5207: doc-j
5208: doc-k
5209:
1.44 crook 5210:
1.1 anton 5211: The loop control data are kept on the return stack, so there are some
1.21 crook 5212: restrictions on mixing return stack accesses and counted loop words. In
5213: particuler, if you put values on the return stack outside the loop, you
5214: cannot read them inside the loop@footnote{well, not in a way that is
5215: portable.}. If you put values on the return stack within a loop, you
5216: have to remove them before the end of the loop and before accessing the
5217: index of the loop.
1.1 anton 5218:
5219: There are several variations on the counted loop:
5220:
1.21 crook 5221: @itemize @bullet
5222: @item
5223: @code{LEAVE} leaves the innermost counted loop immediately; execution
5224: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5225:
5226: @example
5227: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5228: @end example
5229: prints @code{0 1 2 3}
5230:
1.1 anton 5231:
1.21 crook 5232: @item
5233: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5234: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5235: return stack so @code{EXIT} can get to its return address. For example:
5236:
5237: @example
5238: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5239: @end example
5240: prints @code{0 1 2 3}
5241:
5242:
5243: @item
1.29 crook 5244: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5245: (and @code{LOOP} iterates until they become equal by wrap-around
5246: arithmetic). This behaviour is usually not what you want. Therefore,
5247: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5248: @code{?DO}), which do not enter the loop if @i{start} is greater than
5249: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5250: unsigned loop parameters.
5251:
1.21 crook 5252: @item
5253: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5254: the loop, independent of the loop parameters. Do not use @code{DO}, even
5255: if you know that the loop is entered in any case. Such knowledge tends
5256: to become invalid during maintenance of a program, and then the
5257: @code{DO} will make trouble.
5258:
5259: @item
1.29 crook 5260: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5261: index by @i{n} instead of by 1. The loop is terminated when the border
5262: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5263:
1.21 crook 5264: @example
5265: 4 0 +DO i . 2 +LOOP
5266: @end example
5267: @noindent
5268: prints @code{0 2}
5269:
5270: @example
5271: 4 1 +DO i . 2 +LOOP
5272: @end example
5273: @noindent
5274: prints @code{1 3}
1.1 anton 5275:
1.68 anton 5276: @item
1.1 anton 5277: @cindex negative increment for counted loops
5278: @cindex counted loops with negative increment
1.29 crook 5279: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5280:
1.21 crook 5281: @example
5282: -1 0 ?DO i . -1 +LOOP
5283: @end example
5284: @noindent
5285: prints @code{0 -1}
1.1 anton 5286:
1.21 crook 5287: @example
5288: 0 0 ?DO i . -1 +LOOP
5289: @end example
5290: prints nothing.
1.1 anton 5291:
1.29 crook 5292: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5293: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5294: index by @i{u} each iteration. The loop is terminated when the border
5295: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5296: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5297:
1.21 crook 5298: @example
5299: -2 0 -DO i . 1 -LOOP
5300: @end example
5301: @noindent
5302: prints @code{0 -1}
1.1 anton 5303:
1.21 crook 5304: @example
5305: -1 0 -DO i . 1 -LOOP
5306: @end example
5307: @noindent
5308: prints @code{0}
5309:
5310: @example
5311: 0 0 -DO i . 1 -LOOP
5312: @end example
5313: @noindent
5314: prints nothing.
1.1 anton 5315:
1.21 crook 5316: @end itemize
1.1 anton 5317:
5318: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5319: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5320: for these words that uses only standard words is provided in
5321: @file{compat/loops.fs}.
1.1 anton 5322:
5323:
5324: @cindex @code{FOR} loops
1.26 crook 5325: Another counted loop is:
1.1 anton 5326: @example
1.29 crook 5327: @i{n}
1.1 anton 5328: FOR
1.29 crook 5329: @i{body}
1.1 anton 5330: NEXT
5331: @end example
5332: This is the preferred loop of native code compiler writers who are too
1.26 crook 5333: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5334: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5335: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5336: Forth systems may behave differently, even if they support @code{FOR}
5337: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5338:
5339: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5340: @subsection Arbitrary control structures
5341: @cindex control structures, user-defined
5342:
5343: @cindex control-flow stack
5344: ANS Forth permits and supports using control structures in a non-nested
5345: way. Information about incomplete control structures is stored on the
5346: control-flow stack. This stack may be implemented on the Forth data
5347: stack, and this is what we have done in Gforth.
5348:
5349: @cindex @code{orig}, control-flow stack item
5350: @cindex @code{dest}, control-flow stack item
5351: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5352: entry represents a backward branch target. A few words are the basis for
5353: building any control structure possible (except control structures that
5354: need storage, like calls, coroutines, and backtracking).
5355:
1.44 crook 5356:
1.1 anton 5357: doc-if
5358: doc-ahead
5359: doc-then
5360: doc-begin
5361: doc-until
5362: doc-again
5363: doc-cs-pick
5364: doc-cs-roll
5365:
1.44 crook 5366:
1.21 crook 5367: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5368: manipulate the control-flow stack in a portable way. Without them, you
5369: would need to know how many stack items are occupied by a control-flow
5370: entry (many systems use one cell. In Gforth they currently take three,
5371: but this may change in the future).
5372:
1.1 anton 5373: Some standard control structure words are built from these words:
5374:
1.44 crook 5375:
1.1 anton 5376: doc-else
5377: doc-while
5378: doc-repeat
5379:
1.44 crook 5380:
5381: @noindent
1.1 anton 5382: Gforth adds some more control-structure words:
5383:
1.44 crook 5384:
1.1 anton 5385: doc-endif
5386: doc-?dup-if
5387: doc-?dup-0=-if
5388:
1.44 crook 5389:
5390: @noindent
1.1 anton 5391: Counted loop words constitute a separate group of words:
5392:
1.44 crook 5393:
1.1 anton 5394: doc-?do
5395: doc-+do
5396: doc-u+do
5397: doc--do
5398: doc-u-do
5399: doc-do
5400: doc-for
5401: doc-loop
5402: doc-+loop
5403: doc--loop
5404: doc-next
5405: doc-leave
5406: doc-?leave
5407: doc-unloop
5408: doc-done
5409:
1.44 crook 5410:
1.21 crook 5411: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5412: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5413: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5414: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5415: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5416: resolved (by using one of the loop-ending words or @code{DONE}).
5417:
1.44 crook 5418: @noindent
1.26 crook 5419: Another group of control structure words are:
1.1 anton 5420:
1.44 crook 5421:
1.1 anton 5422: doc-case
5423: doc-endcase
5424: doc-of
5425: doc-endof
5426:
1.44 crook 5427:
1.21 crook 5428: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5429: @code{CS-ROLL}.
1.1 anton 5430:
5431: @subsubsection Programming Style
1.47 crook 5432: @cindex control structures programming style
5433: @cindex programming style, arbitrary control structures
1.1 anton 5434:
5435: In order to ensure readability we recommend that you do not create
5436: arbitrary control structures directly, but define new control structure
5437: words for the control structure you want and use these words in your
1.26 crook 5438: program. For example, instead of writing:
1.1 anton 5439:
5440: @example
1.26 crook 5441: BEGIN
1.1 anton 5442: ...
1.26 crook 5443: IF [ 1 CS-ROLL ]
1.1 anton 5444: ...
1.26 crook 5445: AGAIN THEN
1.1 anton 5446: @end example
5447:
1.21 crook 5448: @noindent
1.1 anton 5449: we recommend defining control structure words, e.g.,
5450:
5451: @example
1.26 crook 5452: : WHILE ( DEST -- ORIG DEST )
5453: POSTPONE IF
5454: 1 CS-ROLL ; immediate
5455:
5456: : REPEAT ( orig dest -- )
5457: POSTPONE AGAIN
5458: POSTPONE THEN ; immediate
1.1 anton 5459: @end example
5460:
1.21 crook 5461: @noindent
1.1 anton 5462: and then using these to create the control structure:
5463:
5464: @example
1.26 crook 5465: BEGIN
1.1 anton 5466: ...
1.26 crook 5467: WHILE
1.1 anton 5468: ...
1.26 crook 5469: REPEAT
1.1 anton 5470: @end example
5471:
5472: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5473: @code{WHILE} are predefined, so in this example it would not be
5474: necessary to define them.
5475:
5476: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5477: @subsection Calls and returns
5478: @cindex calling a definition
5479: @cindex returning from a definition
5480:
1.3 anton 5481: @cindex recursive definitions
5482: A definition can be called simply be writing the name of the definition
1.26 crook 5483: to be called. Normally a definition is invisible during its own
1.3 anton 5484: definition. If you want to write a directly recursive definition, you
1.26 crook 5485: can use @code{recursive} to make the current definition visible, or
5486: @code{recurse} to call the current definition directly.
1.3 anton 5487:
1.44 crook 5488:
1.3 anton 5489: doc-recursive
5490: doc-recurse
5491:
1.44 crook 5492:
1.21 crook 5493: @comment TODO add example of the two recursion methods
1.12 anton 5494: @quotation
5495: @progstyle
5496: I prefer using @code{recursive} to @code{recurse}, because calling the
5497: definition by name is more descriptive (if the name is well-chosen) than
5498: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5499: implementation, it is much better to read (and think) ``now sort the
5500: partitions'' than to read ``now do a recursive call''.
5501: @end quotation
1.3 anton 5502:
1.29 crook 5503: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5504:
5505: @example
1.28 crook 5506: Defer foo
1.3 anton 5507:
5508: : bar ( ... -- ... )
5509: ... foo ... ;
5510:
5511: :noname ( ... -- ... )
5512: ... bar ... ;
5513: IS foo
5514: @end example
5515:
1.44 crook 5516: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5517:
1.26 crook 5518: The current definition returns control to the calling definition when
1.33 anton 5519: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5520:
5521: doc-exit
5522: doc-;s
5523:
1.44 crook 5524:
1.1 anton 5525: @node Exception Handling, , Calls and returns, Control Structures
5526: @subsection Exception Handling
1.26 crook 5527: @cindex exceptions
1.1 anton 5528:
1.68 anton 5529: @c quit is a very bad idea for error handling,
5530: @c because it does not translate into a THROW
5531: @c it also does not belong into this chapter
5532:
5533: If a word detects an error condition that it cannot handle, it can
5534: @code{throw} an exception. In the simplest case, this will terminate
5535: your program, and report an appropriate error.
1.21 crook 5536:
1.68 anton 5537: doc-throw
1.1 anton 5538:
1.69 anton 5539: @code{Throw} consumes a cell-sized error number on the stack. There are
5540: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5541: Gforth (and most other systems) you can use the iors produced by various
5542: words as error numbers (e.g., a typical use of @code{allocate} is
5543: @code{allocate throw}). Gforth also provides the word @code{exception}
5544: to define your own error numbers (with decent error reporting); an ANS
5545: Forth version of this word (but without the error messages) is available
5546: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5547: numbers (anything outside the range -4095..0), but won't get nice error
5548: messages, only numbers. For example, try:
5549:
5550: @example
1.69 anton 5551: -10 throw \ ANS defined
5552: -267 throw \ system defined
5553: s" my error" exception throw \ user defined
5554: 7 throw \ arbitrary number
1.68 anton 5555: @end example
5556:
5557: doc---exception-exception
1.1 anton 5558:
1.69 anton 5559: A common idiom to @code{THROW} a specific error if a flag is true is
5560: this:
5561:
5562: @example
5563: @code{( flag ) 0<> @i{errno} and throw}
5564: @end example
5565:
5566: Your program can provide exception handlers to catch exceptions. An
5567: exception handler can be used to correct the problem, or to clean up
5568: some data structures and just throw the exception to the next exception
5569: handler. Note that @code{throw} jumps to the dynamically innermost
5570: exception handler. The system's exception handler is outermost, and just
5571: prints an error and restarts command-line interpretation (or, in batch
5572: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5573:
1.68 anton 5574: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5575:
1.68 anton 5576: doc-catch
5577:
5578: The most common use of exception handlers is to clean up the state when
5579: an error happens. E.g.,
1.1 anton 5580:
1.26 crook 5581: @example
1.68 anton 5582: base @ >r hex \ actually the hex should be inside foo, or we h
5583: ['] foo catch ( nerror|0 )
5584: r> base !
1.69 anton 5585: ( nerror|0 ) throw \ pass it on
1.26 crook 5586: @end example
1.1 anton 5587:
1.69 anton 5588: A use of @code{catch} for handling the error @code{myerror} might look
5589: like this:
1.44 crook 5590:
1.68 anton 5591: @example
1.69 anton 5592: ['] foo catch
5593: CASE
5594: myerror OF ... ( do something about it ) ENDOF
5595: dup throw \ default: pass other errors on, do nothing on non-errors
5596: ENDCASE
1.68 anton 5597: @end example
1.44 crook 5598:
1.68 anton 5599: Having to wrap the code into a separate word is often cumbersome,
5600: therefore Gforth provides an alternative syntax:
1.1 anton 5601:
5602: @example
1.69 anton 5603: TRY
1.68 anton 5604: @i{code1}
1.69 anton 5605: RECOVER \ optional
1.68 anton 5606: @i{code2} \ optional
1.69 anton 5607: ENDTRY
1.1 anton 5608: @end example
5609:
1.68 anton 5610: This performs @i{Code1}. If @i{code1} completes normally, execution
5611: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5612: reset to the state during @code{try}, the throw value is pushed on the
5613: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5614: through the @code{endtry} into the following code.
1.26 crook 5615:
1.68 anton 5616: doc-try
5617: doc-recover
5618: doc-endtry
1.26 crook 5619:
1.69 anton 5620: The cleanup example from above in this syntax:
1.26 crook 5621:
1.68 anton 5622: @example
1.69 anton 5623: base @ >r TRY
1.68 anton 5624: hex foo \ now the hex is placed correctly
1.69 anton 5625: 0 \ value for throw
1.92 anton 5626: RECOVER ENDTRY
1.68 anton 5627: r> base ! throw
1.1 anton 5628: @end example
5629:
1.69 anton 5630: And here's the error handling example:
1.1 anton 5631:
1.68 anton 5632: @example
1.69 anton 5633: TRY
1.68 anton 5634: foo
1.69 anton 5635: RECOVER
5636: CASE
5637: myerror OF ... ( do something about it ) ENDOF
5638: throw \ pass other errors on
5639: ENDCASE
5640: ENDTRY
1.68 anton 5641: @end example
1.1 anton 5642:
1.69 anton 5643: @progstyle
5644: As usual, you should ensure that the stack depth is statically known at
5645: the end: either after the @code{throw} for passing on errors, or after
5646: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5647: selection construct for handling the error).
5648:
1.68 anton 5649: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5650: and you can provide an error message. @code{Abort} just produces an
5651: ``Aborted'' error.
1.1 anton 5652:
1.68 anton 5653: The problem with these words is that exception handlers cannot
5654: differentiate between different @code{abort"}s; they just look like
5655: @code{-2 throw} to them (the error message cannot be accessed by
5656: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5657: exception handlers.
1.44 crook 5658:
1.68 anton 5659: doc-abort"
1.26 crook 5660: doc-abort
1.29 crook 5661:
5662:
1.44 crook 5663:
1.29 crook 5664: @c -------------------------------------------------------------
1.47 crook 5665: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5666: @section Defining Words
5667: @cindex defining words
5668:
1.47 crook 5669: Defining words are used to extend Forth by creating new entries in the dictionary.
5670:
1.29 crook 5671: @menu
1.67 anton 5672: * CREATE::
1.44 crook 5673: * Variables:: Variables and user variables
1.67 anton 5674: * Constants::
1.44 crook 5675: * Values:: Initialised variables
1.67 anton 5676: * Colon Definitions::
1.44 crook 5677: * Anonymous Definitions:: Definitions without names
1.69 anton 5678: * Supplying names:: Passing definition names as strings
1.67 anton 5679: * User-defined Defining Words::
1.44 crook 5680: * Deferred words:: Allow forward references
1.67 anton 5681: * Aliases::
1.29 crook 5682: @end menu
5683:
1.44 crook 5684: @node CREATE, Variables, Defining Words, Defining Words
5685: @subsection @code{CREATE}
1.29 crook 5686: @cindex simple defining words
5687: @cindex defining words, simple
5688:
5689: Defining words are used to create new entries in the dictionary. The
5690: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5691: this:
5692:
5693: @example
5694: CREATE new-word1
5695: @end example
5696:
1.69 anton 5697: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5698: input stream (@code{new-word1} in our example). It generates a
5699: dictionary entry for @code{new-word1}. When @code{new-word1} is
5700: executed, all that it does is leave an address on the stack. The address
5701: represents the value of the data space pointer (@code{HERE}) at the time
5702: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5703: associating a name with the address of a region of memory.
1.29 crook 5704:
1.34 anton 5705: doc-create
5706:
1.69 anton 5707: Note that in ANS Forth guarantees only for @code{create} that its body
5708: is in dictionary data space (i.e., where @code{here}, @code{allot}
5709: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5710: @code{create}d words can be modified with @code{does>}
5711: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5712: can only be applied to @code{create}d words.
5713:
1.29 crook 5714: By extending this example to reserve some memory in data space, we end
1.69 anton 5715: up with something like a @i{variable}. Here are two different ways to do
5716: it:
1.29 crook 5717:
5718: @example
5719: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5720: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5721: @end example
5722:
5723: The variable can be examined and modified using @code{@@} (``fetch'') and
5724: @code{!} (``store'') like this:
5725:
5726: @example
5727: new-word2 @@ . \ get address, fetch from it and display
5728: 1234 new-word2 ! \ new value, get address, store to it
5729: @end example
5730:
1.44 crook 5731: @cindex arrays
5732: A similar mechanism can be used to create arrays. For example, an
5733: 80-character text input buffer:
1.29 crook 5734:
5735: @example
1.44 crook 5736: CREATE text-buf 80 chars allot
5737:
5738: text-buf 0 chars c@@ \ the 1st character (offset 0)
5739: text-buf 3 chars c@@ \ the 4th character (offset 3)
5740: @end example
1.29 crook 5741:
1.44 crook 5742: You can build arbitrarily complex data structures by allocating
1.49 anton 5743: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5744: learn about some Gforth tools that make it easier,
1.49 anton 5745: @xref{Structures}.
1.44 crook 5746:
5747:
5748: @node Variables, Constants, CREATE, Defining Words
5749: @subsection Variables
5750: @cindex variables
5751:
5752: The previous section showed how a sequence of commands could be used to
5753: generate a variable. As a final refinement, the whole code sequence can
5754: be wrapped up in a defining word (pre-empting the subject of the next
5755: section), making it easier to create new variables:
5756:
5757: @example
5758: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5759: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5760:
5761: myvariableX foo \ variable foo starts off with an unknown value
5762: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5763:
5764: 45 3 * foo ! \ set foo to 135
5765: 1234 joe ! \ set joe to 1234
5766: 3 joe +! \ increment joe by 3.. to 1237
5767: @end example
5768:
5769: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5770: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5771: guarantee that a @code{Variable} is initialised when it is created
5772: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5773: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5774: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5775: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5776: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5777: store a boolean, you can use @code{on} and @code{off} to toggle its
5778: state.
1.29 crook 5779:
1.34 anton 5780: doc-variable
5781: doc-2variable
5782: doc-fvariable
5783:
1.29 crook 5784: @cindex user variables
5785: @cindex user space
5786: The defining word @code{User} behaves in the same way as @code{Variable}.
5787: The difference is that it reserves space in @i{user (data) space} rather
5788: than normal data space. In a Forth system that has a multi-tasker, each
5789: task has its own set of user variables.
5790:
1.34 anton 5791: doc-user
1.67 anton 5792: @c doc-udp
5793: @c doc-uallot
1.34 anton 5794:
1.29 crook 5795: @comment TODO is that stuff about user variables strictly correct? Is it
5796: @comment just terminal tasks that have user variables?
5797: @comment should document tasker.fs (with some examples) elsewhere
5798: @comment in this manual, then expand on user space and user variables.
5799:
1.44 crook 5800: @node Constants, Values, Variables, Defining Words
5801: @subsection Constants
5802: @cindex constants
5803:
5804: @code{Constant} allows you to declare a fixed value and refer to it by
5805: name. For example:
1.29 crook 5806:
5807: @example
5808: 12 Constant INCHES-PER-FOOT
5809: 3E+08 fconstant SPEED-O-LIGHT
5810: @end example
5811:
5812: A @code{Variable} can be both read and written, so its run-time
5813: behaviour is to supply an address through which its current value can be
5814: manipulated. In contrast, the value of a @code{Constant} cannot be
5815: changed once it has been declared@footnote{Well, often it can be -- but
5816: not in a Standard, portable way. It's safer to use a @code{Value} (read
5817: on).} so it's not necessary to supply the address -- it is more
5818: efficient to return the value of the constant directly. That's exactly
5819: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5820: the top of the stack (You can find one
5821: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5822:
1.69 anton 5823: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5824: double and floating-point constants, respectively.
5825:
1.34 anton 5826: doc-constant
5827: doc-2constant
5828: doc-fconstant
5829:
5830: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5831: @c nac-> How could that not be true in an ANS Forth? You can't define a
5832: @c constant, use it and then delete the definition of the constant..
1.69 anton 5833:
5834: @c anton->An ANS Forth system can compile a constant to a literal; On
5835: @c decompilation you would see only the number, just as if it had been used
5836: @c in the first place. The word will stay, of course, but it will only be
5837: @c used by the text interpreter (no run-time duties, except when it is
5838: @c POSTPONEd or somesuch).
5839:
5840: @c nac:
1.44 crook 5841: @c I agree that it's rather deep, but IMO it is an important difference
5842: @c relative to other programming languages.. often it's annoying: it
5843: @c certainly changes my programming style relative to C.
5844:
1.69 anton 5845: @c anton: In what way?
5846:
1.29 crook 5847: Constants in Forth behave differently from their equivalents in other
5848: programming languages. In other languages, a constant (such as an EQU in
5849: assembler or a #define in C) only exists at compile-time; in the
5850: executable program the constant has been translated into an absolute
5851: number and, unless you are using a symbolic debugger, it's impossible to
5852: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5853: an entry in the header space and remains there after the code that uses
5854: it has been defined. In fact, it must remain in the dictionary since it
5855: has run-time duties to perform. For example:
1.29 crook 5856:
5857: @example
5858: 12 Constant INCHES-PER-FOOT
5859: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5860: @end example
5861:
5862: @cindex in-lining of constants
5863: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5864: associated with the constant @code{INCHES-PER-FOOT}. If you use
5865: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5866: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5867: attempt to optimise constants by in-lining them where they are used. You
5868: can force Gforth to in-line a constant like this:
5869:
5870: @example
5871: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5872: @end example
5873:
5874: If you use @code{see} to decompile @i{this} version of
5875: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5876: longer present. To understand how this works, read
5877: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5878:
5879: In-lining constants in this way might improve execution time
5880: fractionally, and can ensure that a constant is now only referenced at
5881: compile-time. However, the definition of the constant still remains in
5882: the dictionary. Some Forth compilers provide a mechanism for controlling
5883: a second dictionary for holding transient words such that this second
5884: dictionary can be deleted later in order to recover memory
5885: space. However, there is no standard way of doing this.
5886:
5887:
1.44 crook 5888: @node Values, Colon Definitions, Constants, Defining Words
5889: @subsection Values
5890: @cindex values
1.34 anton 5891:
1.69 anton 5892: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5893: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5894: (not in ANS Forth) you can access (and change) a @code{value} also with
5895: @code{>body}.
5896:
5897: Here are some
5898: examples:
1.29 crook 5899:
5900: @example
1.69 anton 5901: 12 Value APPLES \ Define APPLES with an initial value of 12
5902: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
5903: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
5904: APPLES \ puts 35 on the top of the stack.
1.29 crook 5905: @end example
5906:
1.44 crook 5907: doc-value
5908: doc-to
1.29 crook 5909:
1.35 anton 5910:
1.69 anton 5911:
1.44 crook 5912: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
5913: @subsection Colon Definitions
5914: @cindex colon definitions
1.35 anton 5915:
5916: @example
1.44 crook 5917: : name ( ... -- ... )
5918: word1 word2 word3 ;
1.29 crook 5919: @end example
5920:
1.44 crook 5921: @noindent
5922: Creates a word called @code{name} that, upon execution, executes
5923: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 5924:
1.49 anton 5925: The explanation above is somewhat superficial. For simple examples of
5926: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 5927: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 5928: Compilation Semantics}.
1.29 crook 5929:
1.44 crook 5930: doc-:
5931: doc-;
1.1 anton 5932:
1.34 anton 5933:
1.69 anton 5934: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 5935: @subsection Anonymous Definitions
5936: @cindex colon definitions
5937: @cindex defining words without name
1.34 anton 5938:
1.44 crook 5939: Sometimes you want to define an @dfn{anonymous word}; a word without a
5940: name. You can do this with:
1.1 anton 5941:
1.44 crook 5942: doc-:noname
1.1 anton 5943:
1.44 crook 5944: This leaves the execution token for the word on the stack after the
5945: closing @code{;}. Here's an example in which a deferred word is
5946: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 5947:
1.29 crook 5948: @example
1.44 crook 5949: Defer deferred
5950: :noname ( ... -- ... )
5951: ... ;
5952: IS deferred
1.29 crook 5953: @end example
1.26 crook 5954:
1.44 crook 5955: @noindent
5956: Gforth provides an alternative way of doing this, using two separate
5957: words:
1.27 crook 5958:
1.44 crook 5959: doc-noname
5960: @cindex execution token of last defined word
1.116 anton 5961: doc-latestxt
1.1 anton 5962:
1.44 crook 5963: @noindent
5964: The previous example can be rewritten using @code{noname} and
1.116 anton 5965: @code{latestxt}:
1.1 anton 5966:
1.26 crook 5967: @example
1.44 crook 5968: Defer deferred
5969: noname : ( ... -- ... )
5970: ... ;
1.116 anton 5971: latestxt IS deferred
1.26 crook 5972: @end example
1.1 anton 5973:
1.29 crook 5974: @noindent
1.44 crook 5975: @code{noname} works with any defining word, not just @code{:}.
5976:
1.116 anton 5977: @code{latestxt} also works when the last word was not defined as
1.71 anton 5978: @code{noname}. It does not work for combined words, though. It also has
5979: the useful property that is is valid as soon as the header for a
5980: definition has been built. Thus:
1.44 crook 5981:
5982: @example
1.116 anton 5983: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 5984: @end example
1.1 anton 5985:
1.44 crook 5986: @noindent
5987: prints 3 numbers; the last two are the same.
1.26 crook 5988:
1.69 anton 5989: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
5990: @subsection Supplying the name of a defined word
5991: @cindex names for defined words
5992: @cindex defining words, name given in a string
5993:
5994: By default, a defining word takes the name for the defined word from the
5995: input stream. Sometimes you want to supply the name from a string. You
5996: can do this with:
5997:
5998: doc-nextname
5999:
6000: For example:
6001:
6002: @example
6003: s" foo" nextname create
6004: @end example
6005:
6006: @noindent
6007: is equivalent to:
6008:
6009: @example
6010: create foo
6011: @end example
6012:
6013: @noindent
6014: @code{nextname} works with any defining word.
6015:
1.1 anton 6016:
1.69 anton 6017: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6018: @subsection User-defined Defining Words
6019: @cindex user-defined defining words
6020: @cindex defining words, user-defined
1.1 anton 6021:
1.29 crook 6022: You can create a new defining word by wrapping defining-time code around
6023: an existing defining word and putting the sequence in a colon
1.69 anton 6024: definition.
6025:
6026: @c anton: This example is very complex and leads in a quite different
6027: @c direction from the CREATE-DOES> stuff that follows. It should probably
6028: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6029: @c subsection of Defining Words)
6030:
6031: For example, suppose that you have a word @code{stats} that
1.29 crook 6032: gathers statistics about colon definitions given the @i{xt} of the
6033: definition, and you want every colon definition in your application to
6034: make a call to @code{stats}. You can define and use a new version of
6035: @code{:} like this:
6036:
6037: @example
6038: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6039: ... ; \ other code
6040:
1.116 anton 6041: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6042:
6043: my: foo + - ;
6044: @end example
6045:
6046: When @code{foo} is defined using @code{my:} these steps occur:
6047:
6048: @itemize @bullet
6049: @item
6050: @code{my:} is executed.
6051: @item
6052: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6053: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6054: the input stream for a name, builds a dictionary header for the name
6055: @code{foo} and switches @code{state} from interpret to compile.
6056: @item
1.116 anton 6057: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6058: being defined -- @code{foo} -- onto the stack.
6059: @item
6060: The code that was produced by @code{postpone literal} is executed; this
6061: causes the value on the stack to be compiled as a literal in the code
6062: area of @code{foo}.
6063: @item
6064: The code @code{['] stats} compiles a literal into the definition of
6065: @code{my:}. When @code{compile,} is executed, that literal -- the
6066: execution token for @code{stats} -- is layed down in the code area of
6067: @code{foo} , following the literal@footnote{Strictly speaking, the
6068: mechanism that @code{compile,} uses to convert an @i{xt} into something
6069: in the code area is implementation-dependent. A threaded implementation
6070: might spit out the execution token directly whilst another
6071: implementation might spit out a native code sequence.}.
6072: @item
6073: At this point, the execution of @code{my:} is complete, and control
6074: returns to the text interpreter. The text interpreter is in compile
6075: state, so subsequent text @code{+ -} is compiled into the definition of
6076: @code{foo} and the @code{;} terminates the definition as always.
6077: @end itemize
6078:
6079: You can use @code{see} to decompile a word that was defined using
6080: @code{my:} and see how it is different from a normal @code{:}
6081: definition. For example:
6082:
6083: @example
6084: : bar + - ; \ like foo but using : rather than my:
6085: see bar
6086: : bar
6087: + - ;
6088: see foo
6089: : foo
6090: 107645672 stats + - ;
6091:
6092: \ use ' stats . to show that 107645672 is the xt for stats
6093: @end example
6094:
6095: You can use techniques like this to make new defining words in terms of
6096: @i{any} existing defining word.
1.1 anton 6097:
6098:
1.29 crook 6099: @cindex defining defining words
1.26 crook 6100: @cindex @code{CREATE} ... @code{DOES>}
6101: If you want the words defined with your defining words to behave
6102: differently from words defined with standard defining words, you can
6103: write your defining word like this:
1.1 anton 6104:
6105: @example
1.26 crook 6106: : def-word ( "name" -- )
1.29 crook 6107: CREATE @i{code1}
1.26 crook 6108: DOES> ( ... -- ... )
1.29 crook 6109: @i{code2} ;
1.26 crook 6110:
6111: def-word name
1.1 anton 6112: @end example
6113:
1.29 crook 6114: @cindex child words
6115: This fragment defines a @dfn{defining word} @code{def-word} and then
6116: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6117: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6118: is not executed at this time. The word @code{name} is sometimes called a
6119: @dfn{child} of @code{def-word}.
6120:
6121: When you execute @code{name}, the address of the body of @code{name} is
6122: put on the data stack and @i{code2} is executed (the address of the body
6123: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6124: @code{CREATE}, i.e., the address a @code{create}d word returns by
6125: default).
6126:
6127: @c anton:
6128: @c www.dictionary.com says:
6129: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6130: @c several generations of absence, usually caused by the chance
6131: @c recombination of genes. 2.An individual or a part that exhibits
6132: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6133: @c of previous behavior after a period of absence.
6134: @c
6135: @c Doesn't seem to fit.
1.29 crook 6136:
1.69 anton 6137: @c @cindex atavism in child words
1.33 anton 6138: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6139: similarly; they all have a common run-time behaviour determined by
6140: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6141: body of the child word. The structure of the data is common to all
6142: children of @code{def-word}, but the data values are specific -- and
6143: private -- to each child word. When a child word is executed, the
6144: address of its private data area is passed as a parameter on TOS to be
6145: used and manipulated@footnote{It is legitimate both to read and write to
6146: this data area.} by @i{code2}.
1.29 crook 6147:
6148: The two fragments of code that make up the defining words act (are
6149: executed) at two completely separate times:
1.1 anton 6150:
1.29 crook 6151: @itemize @bullet
6152: @item
6153: At @i{define time}, the defining word executes @i{code1} to generate a
6154: child word
6155: @item
6156: At @i{child execution time}, when a child word is invoked, @i{code2}
6157: is executed, using parameters (data) that are private and specific to
6158: the child word.
6159: @end itemize
6160:
1.44 crook 6161: Another way of understanding the behaviour of @code{def-word} and
6162: @code{name} is to say that, if you make the following definitions:
1.33 anton 6163: @example
6164: : def-word1 ( "name" -- )
6165: CREATE @i{code1} ;
6166:
6167: : action1 ( ... -- ... )
6168: @i{code2} ;
6169:
6170: def-word1 name1
6171: @end example
6172:
1.44 crook 6173: @noindent
6174: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6175:
1.29 crook 6176: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6177:
1.1 anton 6178: @example
1.29 crook 6179: : CONSTANT ( w "name" -- )
6180: CREATE ,
1.26 crook 6181: DOES> ( -- w )
6182: @@ ;
1.1 anton 6183: @end example
6184:
1.29 crook 6185: @comment There is a beautiful description of how this works and what
6186: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6187: @comment commentary on the Counting Fruits problem.
6188:
6189: When you create a constant with @code{5 CONSTANT five}, a set of
6190: define-time actions take place; first a new word @code{five} is created,
6191: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6192: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6193: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6194: no code of its own; it simply contains a data field and a pointer to the
6195: code that follows @code{DOES>} in its defining word. That makes words
6196: created in this way very compact.
6197:
6198: The final example in this section is intended to remind you that space
6199: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6200: both read and written by a Standard program@footnote{Exercise: use this
6201: example as a starting point for your own implementation of @code{Value}
6202: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6203: @code{[']}.}:
6204:
6205: @example
6206: : foo ( "name" -- )
6207: CREATE -1 ,
6208: DOES> ( -- )
1.33 anton 6209: @@ . ;
1.29 crook 6210:
6211: foo first-word
6212: foo second-word
6213:
6214: 123 ' first-word >BODY !
6215: @end example
6216:
6217: If @code{first-word} had been a @code{CREATE}d word, we could simply
6218: have executed it to get the address of its data field. However, since it
6219: was defined to have @code{DOES>} actions, its execution semantics are to
6220: perform those @code{DOES>} actions. To get the address of its data field
6221: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6222: translate the xt into the address of the data field. When you execute
6223: @code{first-word}, it will display @code{123}. When you execute
6224: @code{second-word} it will display @code{-1}.
1.26 crook 6225:
6226: @cindex stack effect of @code{DOES>}-parts
6227: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6228: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6229: the stack effect of the defined words, not the stack effect of the
6230: following code (the following code expects the address of the body on
6231: the top of stack, which is not reflected in the stack comment). This is
6232: the convention that I use and recommend (it clashes a bit with using
6233: locals declarations for stack effect specification, though).
1.1 anton 6234:
1.53 anton 6235: @menu
6236: * CREATE..DOES> applications::
6237: * CREATE..DOES> details::
1.63 anton 6238: * Advanced does> usage example::
1.91 anton 6239: * @code{Const-does>}::
1.53 anton 6240: @end menu
6241:
6242: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6243: @subsubsection Applications of @code{CREATE..DOES>}
6244: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6245:
1.26 crook 6246: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6247:
1.26 crook 6248: @cindex factoring similar colon definitions
6249: When you see a sequence of code occurring several times, and you can
6250: identify a meaning, you will factor it out as a colon definition. When
6251: you see similar colon definitions, you can factor them using
6252: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6253: that look very similar:
1.1 anton 6254: @example
1.26 crook 6255: : ori, ( reg-target reg-source n -- )
6256: 0 asm-reg-reg-imm ;
6257: : andi, ( reg-target reg-source n -- )
6258: 1 asm-reg-reg-imm ;
1.1 anton 6259: @end example
6260:
1.26 crook 6261: @noindent
6262: This could be factored with:
6263: @example
6264: : reg-reg-imm ( op-code -- )
6265: CREATE ,
6266: DOES> ( reg-target reg-source n -- )
6267: @@ asm-reg-reg-imm ;
6268:
6269: 0 reg-reg-imm ori,
6270: 1 reg-reg-imm andi,
6271: @end example
1.1 anton 6272:
1.26 crook 6273: @cindex currying
6274: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6275: supply a part of the parameters for a word (known as @dfn{currying} in
6276: the functional language community). E.g., @code{+} needs two
6277: parameters. Creating versions of @code{+} with one parameter fixed can
6278: be done like this:
1.82 anton 6279:
1.1 anton 6280: @example
1.82 anton 6281: : curry+ ( n1 "name" -- )
1.26 crook 6282: CREATE ,
6283: DOES> ( n2 -- n1+n2 )
6284: @@ + ;
6285:
6286: 3 curry+ 3+
6287: -2 curry+ 2-
1.1 anton 6288: @end example
6289:
1.91 anton 6290:
1.63 anton 6291: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6292: @subsubsection The gory details of @code{CREATE..DOES>}
6293: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6294:
1.26 crook 6295: doc-does>
1.1 anton 6296:
1.26 crook 6297: @cindex @code{DOES>} in a separate definition
6298: This means that you need not use @code{CREATE} and @code{DOES>} in the
6299: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6300: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6301: @example
6302: : does1
6303: DOES> ( ... -- ... )
1.44 crook 6304: ... ;
6305:
6306: : does2
6307: DOES> ( ... -- ... )
6308: ... ;
6309:
6310: : def-word ( ... -- ... )
6311: create ...
6312: IF
6313: does1
6314: ELSE
6315: does2
6316: ENDIF ;
6317: @end example
6318:
6319: In this example, the selection of whether to use @code{does1} or
1.69 anton 6320: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6321: @code{CREATE}d.
6322:
6323: @cindex @code{DOES>} in interpretation state
6324: In a standard program you can apply a @code{DOES>}-part only if the last
6325: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6326: will override the behaviour of the last word defined in any case. In a
6327: standard program, you can use @code{DOES>} only in a colon
6328: definition. In Gforth, you can also use it in interpretation state, in a
6329: kind of one-shot mode; for example:
6330: @example
6331: CREATE name ( ... -- ... )
6332: @i{initialization}
6333: DOES>
6334: @i{code} ;
6335: @end example
6336:
6337: @noindent
6338: is equivalent to the standard:
6339: @example
6340: :noname
6341: DOES>
6342: @i{code} ;
6343: CREATE name EXECUTE ( ... -- ... )
6344: @i{initialization}
6345: @end example
6346:
1.53 anton 6347: doc->body
6348:
1.91 anton 6349: @node Advanced does> usage example, @code{Const-does>}, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6350: @subsubsection Advanced does> usage example
6351:
6352: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6353: for disassembling instructions, that follow a very repetetive scheme:
6354:
6355: @example
6356: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6357: @var{entry-num} cells @var{table} + !
6358: @end example
6359:
6360: Of course, this inspires the idea to factor out the commonalities to
6361: allow a definition like
6362:
6363: @example
6364: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6365: @end example
6366:
6367: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6368: correlated. Moreover, before I wrote the disassembler, there already
6369: existed code that defines instructions like this:
1.63 anton 6370:
6371: @example
6372: @var{entry-num} @var{inst-format} @var{inst-name}
6373: @end example
6374:
6375: This code comes from the assembler and resides in
6376: @file{arch/mips/insts.fs}.
6377:
6378: So I had to define the @var{inst-format} words that performed the scheme
6379: above when executed. At first I chose to use run-time code-generation:
6380:
6381: @example
6382: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6383: :noname Postpone @var{disasm-operands}
6384: name Postpone sliteral Postpone type Postpone ;
6385: swap cells @var{table} + ! ;
6386: @end example
6387:
6388: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6389:
1.63 anton 6390: An alternative would have been to write this using
6391: @code{create}/@code{does>}:
6392:
6393: @example
6394: : @var{inst-format} ( entry-num "name" -- )
6395: here name string, ( entry-num c-addr ) \ parse and save "name"
6396: noname create , ( entry-num )
1.116 anton 6397: latestxt swap cells @var{table} + !
1.63 anton 6398: does> ( addr w -- )
6399: \ disassemble instruction w at addr
6400: @@ >r
6401: @var{disasm-operands}
6402: r> count type ;
6403: @end example
6404:
6405: Somehow the first solution is simpler, mainly because it's simpler to
6406: shift a string from definition-time to use-time with @code{sliteral}
6407: than with @code{string,} and friends.
6408:
6409: I wrote a lot of words following this scheme and soon thought about
6410: factoring out the commonalities among them. Note that this uses a
6411: two-level defining word, i.e., a word that defines ordinary defining
6412: words.
6413:
6414: This time a solution involving @code{postpone} and friends seemed more
6415: difficult (try it as an exercise), so I decided to use a
6416: @code{create}/@code{does>} word; since I was already at it, I also used
6417: @code{create}/@code{does>} for the lower level (try using
6418: @code{postpone} etc. as an exercise), resulting in the following
6419: definition:
6420:
6421: @example
6422: : define-format ( disasm-xt table-xt -- )
6423: \ define an instruction format that uses disasm-xt for
6424: \ disassembling and enters the defined instructions into table
6425: \ table-xt
6426: create 2,
6427: does> ( u "inst" -- )
6428: \ defines an anonymous word for disassembling instruction inst,
6429: \ and enters it as u-th entry into table-xt
6430: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6431: noname create 2, \ define anonymous word
1.116 anton 6432: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6433: does> ( addr w -- )
6434: \ disassemble instruction w at addr
6435: 2@@ >r ( addr w disasm-xt R: c-addr )
6436: execute ( R: c-addr ) \ disassemble operands
6437: r> count type ; \ print name
6438: @end example
6439:
6440: Note that the tables here (in contrast to above) do the @code{cells +}
6441: by themselves (that's why you have to pass an xt). This word is used in
6442: the following way:
6443:
6444: @example
6445: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6446: @end example
6447:
1.71 anton 6448: As shown above, the defined instruction format is then used like this:
6449:
6450: @example
6451: @var{entry-num} @var{inst-format} @var{inst-name}
6452: @end example
6453:
1.63 anton 6454: In terms of currying, this kind of two-level defining word provides the
6455: parameters in three stages: first @var{disasm-operands} and @var{table},
6456: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6457: the instruction to be disassembled.
6458:
6459: Of course this did not quite fit all the instruction format names used
6460: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6461: the parameters into the right form.
6462:
6463: If you have trouble following this section, don't worry. First, this is
6464: involved and takes time (and probably some playing around) to
6465: understand; second, this is the first two-level
6466: @code{create}/@code{does>} word I have written in seventeen years of
6467: Forth; and if I did not have @file{insts.fs} to start with, I may well
6468: have elected to use just a one-level defining word (with some repeating
6469: of parameters when using the defining word). So it is not necessary to
6470: understand this, but it may improve your understanding of Forth.
1.44 crook 6471:
6472:
1.91 anton 6473: @node @code{Const-does>}, , Advanced does> usage example, User-defined Defining Words
6474: @subsubsection @code{Const-does>}
6475:
6476: A frequent use of @code{create}...@code{does>} is for transferring some
6477: values from definition-time to run-time. Gforth supports this use with
6478:
6479: doc-const-does>
6480:
6481: A typical use of this word is:
6482:
6483: @example
6484: : curry+ ( n1 "name" -- )
6485: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6486: + ;
6487:
6488: 3 curry+ 3+
6489: @end example
6490:
6491: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6492: definition to run-time.
6493:
6494: The advantages of using @code{const-does>} are:
6495:
6496: @itemize
6497:
6498: @item
6499: You don't have to deal with storing and retrieving the values, i.e.,
6500: your program becomes more writable and readable.
6501:
6502: @item
6503: When using @code{does>}, you have to introduce a @code{@@} that cannot
6504: be optimized away (because you could change the data using
6505: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6506:
6507: @end itemize
6508:
6509: An ANS Forth implementation of @code{const-does>} is available in
6510: @file{compat/const-does.fs}.
6511:
6512:
1.44 crook 6513: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6514: @subsection Deferred words
6515: @cindex deferred words
6516:
6517: The defining word @code{Defer} allows you to define a word by name
6518: without defining its behaviour; the definition of its behaviour is
6519: deferred. Here are two situation where this can be useful:
6520:
6521: @itemize @bullet
6522: @item
6523: Where you want to allow the behaviour of a word to be altered later, and
6524: for all precompiled references to the word to change when its behaviour
6525: is changed.
6526: @item
6527: For mutual recursion; @xref{Calls and returns}.
6528: @end itemize
6529:
6530: In the following example, @code{foo} always invokes the version of
6531: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6532: always invokes the version that prints ``@code{Hello}''. There is no way
6533: of getting @code{foo} to use the later version without re-ordering the
6534: source code and recompiling it.
6535:
6536: @example
6537: : greet ." Good morning" ;
6538: : foo ... greet ... ;
6539: : greet ." Hello" ;
6540: : bar ... greet ... ;
6541: @end example
6542:
6543: This problem can be solved by defining @code{greet} as a @code{Defer}red
6544: word. The behaviour of a @code{Defer}red word can be defined and
6545: redefined at any time by using @code{IS} to associate the xt of a
6546: previously-defined word with it. The previous example becomes:
6547:
6548: @example
1.69 anton 6549: Defer greet ( -- )
1.44 crook 6550: : foo ... greet ... ;
6551: : bar ... greet ... ;
1.69 anton 6552: : greet1 ( -- ) ." Good morning" ;
6553: : greet2 ( -- ) ." Hello" ;
1.44 crook 6554: ' greet2 <IS> greet \ make greet behave like greet2
6555: @end example
6556:
1.69 anton 6557: @progstyle
6558: You should write a stack comment for every deferred word, and put only
6559: XTs into deferred words that conform to this stack effect. Otherwise
6560: it's too difficult to use the deferred word.
6561:
1.44 crook 6562: A deferred word can be used to improve the statistics-gathering example
6563: from @ref{User-defined Defining Words}; rather than edit the
6564: application's source code to change every @code{:} to a @code{my:}, do
6565: this:
6566:
6567: @example
6568: : real: : ; \ retain access to the original
6569: defer : \ redefine as a deferred word
1.69 anton 6570: ' my: <IS> : \ use special version of :
1.44 crook 6571: \
6572: \ load application here
6573: \
1.69 anton 6574: ' real: <IS> : \ go back to the original
1.44 crook 6575: @end example
6576:
6577:
6578: One thing to note is that @code{<IS>} consumes its name when it is
6579: executed. If you want to specify the name at compile time, use
6580: @code{[IS]}:
6581:
6582: @example
6583: : set-greet ( xt -- )
6584: [IS] greet ;
6585:
6586: ' greet1 set-greet
6587: @end example
6588:
1.69 anton 6589: A deferred word can only inherit execution semantics from the xt
6590: (because that is all that an xt can represent -- for more discussion of
6591: this @pxref{Tokens for Words}); by default it will have default
6592: interpretation and compilation semantics deriving from this execution
6593: semantics. However, you can change the interpretation and compilation
6594: semantics of the deferred word in the usual ways:
1.44 crook 6595:
6596: @example
6597: : bar .... ; compile-only
6598: Defer fred immediate
6599: Defer jim
6600:
6601: ' bar <IS> jim \ jim has default semantics
6602: ' bar <IS> fred \ fred is immediate
6603: @end example
6604:
6605: doc-defer
6606: doc-<is>
6607: doc-[is]
6608: doc-is
6609: @comment TODO document these: what's defers [is]
6610: doc-what's
6611: doc-defers
6612:
6613: @c Use @code{words-deferred} to see a list of deferred words.
6614:
6615: Definitions in ANS Forth for @code{defer}, @code{<is>} and @code{[is]}
6616: are provided in @file{compat/defer.fs}.
6617:
6618:
1.69 anton 6619: @node Aliases, , Deferred words, Defining Words
1.44 crook 6620: @subsection Aliases
6621: @cindex aliases
1.1 anton 6622:
1.44 crook 6623: The defining word @code{Alias} allows you to define a word by name that
6624: has the same behaviour as some other word. Here are two situation where
6625: this can be useful:
1.1 anton 6626:
1.44 crook 6627: @itemize @bullet
6628: @item
6629: When you want access to a word's definition from a different word list
6630: (for an example of this, see the definition of the @code{Root} word list
6631: in the Gforth source).
6632: @item
6633: When you want to create a synonym; a definition that can be known by
6634: either of two names (for example, @code{THEN} and @code{ENDIF} are
6635: aliases).
6636: @end itemize
1.1 anton 6637:
1.69 anton 6638: Like deferred words, an alias has default compilation and interpretation
6639: semantics at the beginning (not the modifications of the other word),
6640: but you can change them in the usual ways (@code{immediate},
6641: @code{compile-only}). For example:
1.1 anton 6642:
6643: @example
1.44 crook 6644: : foo ... ; immediate
6645:
6646: ' foo Alias bar \ bar is not an immediate word
6647: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6648: @end example
6649:
1.44 crook 6650: Words that are aliases have the same xt, different headers in the
6651: dictionary, and consequently different name tokens (@pxref{Tokens for
6652: Words}) and possibly different immediate flags. An alias can only have
6653: default or immediate compilation semantics; you can define aliases for
6654: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6655:
1.44 crook 6656: doc-alias
1.1 anton 6657:
6658:
1.47 crook 6659: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6660: @section Interpretation and Compilation Semantics
1.26 crook 6661: @cindex semantics, interpretation and compilation
1.1 anton 6662:
1.71 anton 6663: @c !! state and ' are used without explanation
6664: @c example for immediate/compile-only? or is the tutorial enough
6665:
1.26 crook 6666: @cindex interpretation semantics
1.71 anton 6667: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6668: interpreter does when it encounters the word in interpret state. It also
6669: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6670: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6671: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6672: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6673:
1.26 crook 6674: @cindex compilation semantics
1.71 anton 6675: The @dfn{compilation semantics} of a (named) word are what the text
6676: interpreter does when it encounters the word in compile state. It also
6677: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6678: compiles@footnote{In standard terminology, ``appends to the current
6679: definition''.} the compilation semantics of @i{word}.
1.1 anton 6680:
1.26 crook 6681: @cindex execution semantics
6682: The standard also talks about @dfn{execution semantics}. They are used
6683: only for defining the interpretation and compilation semantics of many
6684: words. By default, the interpretation semantics of a word are to
6685: @code{execute} its execution semantics, and the compilation semantics of
6686: a word are to @code{compile,} its execution semantics.@footnote{In
6687: standard terminology: The default interpretation semantics are its
6688: execution semantics; the default compilation semantics are to append its
6689: execution semantics to the execution semantics of the current
6690: definition.}
6691:
1.71 anton 6692: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6693: the text interpreter, ticked, or @code{postpone}d, so they have no
6694: interpretation or compilation semantics. Their behaviour is represented
6695: by their XT (@pxref{Tokens for Words}), and we call it execution
6696: semantics, too.
6697:
1.26 crook 6698: @comment TODO expand, make it co-operate with new sections on text interpreter.
6699:
6700: @cindex immediate words
6701: @cindex compile-only words
6702: You can change the semantics of the most-recently defined word:
6703:
1.44 crook 6704:
1.26 crook 6705: doc-immediate
6706: doc-compile-only
6707: doc-restrict
6708:
1.82 anton 6709: By convention, words with non-default compilation semantics (e.g.,
6710: immediate words) often have names surrounded with brackets (e.g.,
6711: @code{[']}, @pxref{Execution token}).
1.44 crook 6712:
1.26 crook 6713: Note that ticking (@code{'}) a compile-only word gives an error
6714: (``Interpreting a compile-only word'').
1.1 anton 6715:
1.47 crook 6716: @menu
1.67 anton 6717: * Combined words::
1.47 crook 6718: @end menu
1.44 crook 6719:
1.71 anton 6720:
1.48 anton 6721: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6722: @subsection Combined Words
6723: @cindex combined words
6724:
6725: Gforth allows you to define @dfn{combined words} -- words that have an
6726: arbitrary combination of interpretation and compilation semantics.
6727:
1.26 crook 6728: doc-interpret/compile:
1.1 anton 6729:
1.26 crook 6730: This feature was introduced for implementing @code{TO} and @code{S"}. I
6731: recommend that you do not define such words, as cute as they may be:
6732: they make it hard to get at both parts of the word in some contexts.
6733: E.g., assume you want to get an execution token for the compilation
6734: part. Instead, define two words, one that embodies the interpretation
6735: part, and one that embodies the compilation part. Once you have done
6736: that, you can define a combined word with @code{interpret/compile:} for
6737: the convenience of your users.
1.1 anton 6738:
1.26 crook 6739: You might try to use this feature to provide an optimizing
6740: implementation of the default compilation semantics of a word. For
6741: example, by defining:
1.1 anton 6742: @example
1.26 crook 6743: :noname
6744: foo bar ;
6745: :noname
6746: POSTPONE foo POSTPONE bar ;
1.29 crook 6747: interpret/compile: opti-foobar
1.1 anton 6748: @end example
1.26 crook 6749:
1.23 crook 6750: @noindent
1.26 crook 6751: as an optimizing version of:
6752:
1.1 anton 6753: @example
1.26 crook 6754: : foobar
6755: foo bar ;
1.1 anton 6756: @end example
6757:
1.26 crook 6758: Unfortunately, this does not work correctly with @code{[compile]},
6759: because @code{[compile]} assumes that the compilation semantics of all
6760: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6761: opti-foobar} would compile compilation semantics, whereas
6762: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6763:
1.26 crook 6764: @cindex state-smart words (are a bad idea)
1.82 anton 6765: @anchor{state-smartness}
1.29 crook 6766: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6767: by @code{interpret/compile:} (words are state-smart if they check
6768: @code{STATE} during execution). E.g., they would try to code
6769: @code{foobar} like this:
1.1 anton 6770:
1.26 crook 6771: @example
6772: : foobar
6773: STATE @@
6774: IF ( compilation state )
6775: POSTPONE foo POSTPONE bar
6776: ELSE
6777: foo bar
6778: ENDIF ; immediate
6779: @end example
1.1 anton 6780:
1.26 crook 6781: Although this works if @code{foobar} is only processed by the text
6782: interpreter, it does not work in other contexts (like @code{'} or
6783: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6784: for a state-smart word, not for the interpretation semantics of the
6785: original @code{foobar}; when you execute this execution token (directly
6786: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6787: state, the result will not be what you expected (i.e., it will not
6788: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6789: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6790: M. Anton Ertl,
6791: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6792: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6793:
1.26 crook 6794: @cindex defining words with arbitrary semantics combinations
6795: It is also possible to write defining words that define words with
6796: arbitrary combinations of interpretation and compilation semantics. In
6797: general, they look like this:
1.1 anton 6798:
1.26 crook 6799: @example
6800: : def-word
6801: create-interpret/compile
1.29 crook 6802: @i{code1}
1.26 crook 6803: interpretation>
1.29 crook 6804: @i{code2}
1.26 crook 6805: <interpretation
6806: compilation>
1.29 crook 6807: @i{code3}
1.26 crook 6808: <compilation ;
6809: @end example
1.1 anton 6810:
1.29 crook 6811: For a @i{word} defined with @code{def-word}, the interpretation
6812: semantics are to push the address of the body of @i{word} and perform
6813: @i{code2}, and the compilation semantics are to push the address of
6814: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6815: can also be defined like this (except that the defined constants don't
6816: behave correctly when @code{[compile]}d):
1.1 anton 6817:
1.26 crook 6818: @example
6819: : constant ( n "name" -- )
6820: create-interpret/compile
6821: ,
6822: interpretation> ( -- n )
6823: @@
6824: <interpretation
6825: compilation> ( compilation. -- ; run-time. -- n )
6826: @@ postpone literal
6827: <compilation ;
6828: @end example
1.1 anton 6829:
1.44 crook 6830:
1.26 crook 6831: doc-create-interpret/compile
6832: doc-interpretation>
6833: doc-<interpretation
6834: doc-compilation>
6835: doc-<compilation
1.1 anton 6836:
1.44 crook 6837:
1.29 crook 6838: Words defined with @code{interpret/compile:} and
1.26 crook 6839: @code{create-interpret/compile} have an extended header structure that
6840: differs from other words; however, unless you try to access them with
6841: plain address arithmetic, you should not notice this. Words for
6842: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6843: @code{'} @i{word} @code{>body} also gives you the body of a word created
6844: with @code{create-interpret/compile}.
1.1 anton 6845:
1.44 crook 6846:
1.47 crook 6847: @c -------------------------------------------------------------
1.81 anton 6848: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6849: @section Tokens for Words
6850: @cindex tokens for words
6851:
6852: This section describes the creation and use of tokens that represent
6853: words.
6854:
1.71 anton 6855: @menu
6856: * Execution token:: represents execution/interpretation semantics
6857: * Compilation token:: represents compilation semantics
6858: * Name token:: represents named words
6859: @end menu
1.47 crook 6860:
1.71 anton 6861: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6862: @subsection Execution token
1.47 crook 6863:
6864: @cindex xt
6865: @cindex execution token
1.71 anton 6866: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6867: You can use @code{execute} to invoke this behaviour.
1.47 crook 6868:
1.71 anton 6869: @cindex tick (')
6870: You can use @code{'} to get an execution token that represents the
6871: interpretation semantics of a named word:
1.47 crook 6872:
6873: @example
1.97 anton 6874: 5 ' . ( n xt )
6875: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6876: @end example
1.47 crook 6877:
1.71 anton 6878: doc-'
6879:
6880: @code{'} parses at run-time; there is also a word @code{[']} that parses
6881: when it is compiled, and compiles the resulting XT:
6882:
6883: @example
6884: : foo ['] . execute ;
6885: 5 foo
6886: : bar ' execute ; \ by contrast,
6887: 5 bar . \ ' parses "." when bar executes
6888: @end example
6889:
6890: doc-[']
6891:
6892: If you want the execution token of @i{word}, write @code{['] @i{word}}
6893: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6894: @code{'} and @code{[']} behave somewhat unusually by complaining about
6895: compile-only words (because these words have no interpretation
6896: semantics). You might get what you want by using @code{COMP' @i{word}
6897: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
6898: token}).
6899:
1.116 anton 6900: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 6901: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
6902: for the only behaviour the word has (the execution semantics). For
1.116 anton 6903: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 6904: would produce if the word was defined anonymously.
6905:
6906: @example
6907: :noname ." hello" ;
6908: execute
1.47 crook 6909: @end example
6910:
1.71 anton 6911: An XT occupies one cell and can be manipulated like any other cell.
6912:
1.47 crook 6913: @cindex code field address
6914: @cindex CFA
1.71 anton 6915: In ANS Forth the XT is just an abstract data type (i.e., defined by the
6916: operations that produce or consume it). For old hands: In Gforth, the
6917: XT is implemented as a code field address (CFA).
6918:
6919: doc-execute
6920: doc-perform
6921:
6922: @node Compilation token, Name token, Execution token, Tokens for Words
6923: @subsection Compilation token
1.47 crook 6924:
6925: @cindex compilation token
1.71 anton 6926: @cindex CT (compilation token)
6927: Gforth represents the compilation semantics of a named word by a
1.47 crook 6928: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
6929: @i{xt} is an execution token. The compilation semantics represented by
6930: the compilation token can be performed with @code{execute}, which
6931: consumes the whole compilation token, with an additional stack effect
6932: determined by the represented compilation semantics.
6933:
6934: At present, the @i{w} part of a compilation token is an execution token,
6935: and the @i{xt} part represents either @code{execute} or
6936: @code{compile,}@footnote{Depending upon the compilation semantics of the
6937: word. If the word has default compilation semantics, the @i{xt} will
6938: represent @code{compile,}. Otherwise (e.g., for immediate words), the
6939: @i{xt} will represent @code{execute}.}. However, don't rely on that
6940: knowledge, unless necessary; future versions of Gforth may introduce
6941: unusual compilation tokens (e.g., a compilation token that represents
6942: the compilation semantics of a literal).
6943:
1.71 anton 6944: You can perform the compilation semantics represented by the compilation
6945: token with @code{execute}. You can compile the compilation semantics
6946: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
6947: equivalent to @code{postpone @i{word}}.
6948:
6949: doc-[comp']
6950: doc-comp'
6951: doc-postpone,
6952:
6953: @node Name token, , Compilation token, Tokens for Words
6954: @subsection Name token
1.47 crook 6955:
6956: @cindex name token
1.116 anton 6957: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
6958: token is an abstract data type that occurs as argument or result of the
6959: words below.
6960:
6961: @c !! put this elswhere?
1.47 crook 6962: @cindex name field address
6963: @cindex NFA
1.116 anton 6964: The closest thing to the nt in older Forth systems is the name field
6965: address (NFA), but there are significant differences: in older Forth
6966: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
6967: LFA, NFA, CFA, PFA) and there were words for getting from one to the
6968: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
6969: is a link field in the structure identified by the name token, but
6970: searching usually uses a hash table external to these structures; the
6971: name in Gforth has a cell-wide count-and-flags field, and the nt is not
6972: implemented as the address of that count field.
1.47 crook 6973:
6974: doc-find-name
1.116 anton 6975: doc-latest
6976: doc->name
1.47 crook 6977: doc-name>int
6978: doc-name?int
6979: doc-name>comp
6980: doc-name>string
1.109 anton 6981: doc-id.
6982: doc-.name
6983: doc-.id
1.47 crook 6984:
1.81 anton 6985: @c ----------------------------------------------------------
6986: @node Compiling words, The Text Interpreter, Tokens for Words, Words
6987: @section Compiling words
6988: @cindex compiling words
6989: @cindex macros
6990:
6991: In contrast to most other languages, Forth has no strict boundary
1.82 anton 6992: between compilation and run-time. E.g., you can run arbitrary code
6993: between defining words (or for computing data used by defining words
6994: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
6995: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
6996: running arbitrary code while compiling a colon definition (exception:
6997: you must not allot dictionary space).
6998:
6999: @menu
7000: * Literals:: Compiling data values
7001: * Macros:: Compiling words
7002: @end menu
7003:
7004: @node Literals, Macros, Compiling words, Compiling words
7005: @subsection Literals
7006: @cindex Literals
7007:
7008: The simplest and most frequent example is to compute a literal during
7009: compilation. E.g., the following definition prints an array of strings,
7010: one string per line:
7011:
7012: @example
7013: : .strings ( addr u -- ) \ gforth
7014: 2* cells bounds U+DO
7015: cr i 2@@ type
7016: 2 cells +LOOP ;
7017: @end example
1.81 anton 7018:
1.82 anton 7019: With a simple-minded compiler like Gforth's, this computes @code{2
7020: cells} on every loop iteration. You can compute this value once and for
7021: all at compile time and compile it into the definition like this:
7022:
7023: @example
7024: : .strings ( addr u -- ) \ gforth
7025: 2* cells bounds U+DO
7026: cr i 2@@ type
7027: [ 2 cells ] literal +LOOP ;
7028: @end example
7029:
7030: @code{[} switches the text interpreter to interpret state (you will get
7031: an @code{ok} prompt if you type this example interactively and insert a
7032: newline between @code{[} and @code{]}), so it performs the
7033: interpretation semantics of @code{2 cells}; this computes a number.
7034: @code{]} switches the text interpreter back into compile state. It then
7035: performs @code{Literal}'s compilation semantics, which are to compile
7036: this number into the current word. You can decompile the word with
7037: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7038:
1.82 anton 7039: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7040: *} in this way.
1.81 anton 7041:
1.82 anton 7042: doc-[
7043: doc-]
1.81 anton 7044: doc-literal
7045: doc-]L
1.82 anton 7046:
7047: There are also words for compiling other data types than single cells as
7048: literals:
7049:
1.81 anton 7050: doc-2literal
7051: doc-fliteral
1.82 anton 7052: doc-sliteral
7053:
7054: @cindex colon-sys, passing data across @code{:}
7055: @cindex @code{:}, passing data across
7056: You might be tempted to pass data from outside a colon definition to the
7057: inside on the data stack. This does not work, because @code{:} puhes a
7058: colon-sys, making stuff below unaccessible. E.g., this does not work:
7059:
7060: @example
7061: 5 : foo literal ; \ error: "unstructured"
7062: @end example
7063:
7064: Instead, you have to pass the value in some other way, e.g., through a
7065: variable:
7066:
7067: @example
7068: variable temp
7069: 5 temp !
7070: : foo [ temp @@ ] literal ;
7071: @end example
7072:
7073:
7074: @node Macros, , Literals, Compiling words
7075: @subsection Macros
7076: @cindex Macros
7077: @cindex compiling compilation semantics
7078:
7079: @code{Literal} and friends compile data values into the current
7080: definition. You can also write words that compile other words into the
7081: current definition. E.g.,
7082:
7083: @example
7084: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7085: POSTPONE + ;
7086:
7087: : foo ( n1 n2 -- n )
7088: [ compile-+ ] ;
7089: 1 2 foo .
7090: @end example
7091:
7092: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7093: What happens in this example? @code{Postpone} compiles the compilation
7094: semantics of @code{+} into @code{compile-+}; later the text interpreter
7095: executes @code{compile-+} and thus the compilation semantics of +, which
7096: compile (the execution semantics of) @code{+} into
7097: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7098: should only be executed in compile state, so this example is not
7099: guaranteed to work on all standard systems, but on any decent system it
7100: will work.}
7101:
7102: doc-postpone
7103: doc-[compile]
7104:
7105: Compiling words like @code{compile-+} are usually immediate (or similar)
7106: so you do not have to switch to interpret state to execute them;
7107: mopifying the last example accordingly produces:
7108:
7109: @example
7110: : [compile-+] ( compilation: --; interpretation: -- )
7111: \ compiled code: ( n1 n2 -- n )
7112: POSTPONE + ; immediate
7113:
7114: : foo ( n1 n2 -- n )
7115: [compile-+] ;
7116: 1 2 foo .
7117: @end example
7118:
7119: Immediate compiling words are similar to macros in other languages (in
7120: particular, Lisp). The important differences to macros in, e.g., C are:
7121:
7122: @itemize @bullet
7123:
7124: @item
7125: You use the same language for defining and processing macros, not a
7126: separate preprocessing language and processor.
7127:
7128: @item
7129: Consequently, the full power of Forth is available in macro definitions.
7130: E.g., you can perform arbitrarily complex computations, or generate
7131: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7132: Tutorial}). This power is very useful when writing a parser generators
7133: or other code-generating software.
7134:
7135: @item
7136: Macros defined using @code{postpone} etc. deal with the language at a
7137: higher level than strings; name binding happens at macro definition
7138: time, so you can avoid the pitfalls of name collisions that can happen
7139: in C macros. Of course, Forth is a liberal language and also allows to
7140: shoot yourself in the foot with text-interpreted macros like
7141:
7142: @example
7143: : [compile-+] s" +" evaluate ; immediate
7144: @end example
7145:
7146: Apart from binding the name at macro use time, using @code{evaluate}
7147: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7148: @end itemize
7149:
7150: You may want the macro to compile a number into a word. The word to do
7151: it is @code{literal}, but you have to @code{postpone} it, so its
7152: compilation semantics take effect when the macro is executed, not when
7153: it is compiled:
7154:
7155: @example
7156: : [compile-5] ( -- ) \ compiled code: ( -- n )
7157: 5 POSTPONE literal ; immediate
7158:
7159: : foo [compile-5] ;
7160: foo .
7161: @end example
7162:
7163: You may want to pass parameters to a macro, that the macro should
7164: compile into the current definition. If the parameter is a number, then
7165: you can use @code{postpone literal} (similar for other values).
7166:
7167: If you want to pass a word that is to be compiled, the usual way is to
7168: pass an execution token and @code{compile,} it:
7169:
7170: @example
7171: : twice1 ( xt -- ) \ compiled code: ... -- ...
7172: dup compile, compile, ;
7173:
7174: : 2+ ( n1 -- n2 )
7175: [ ' 1+ twice1 ] ;
7176: @end example
7177:
7178: doc-compile,
7179:
7180: An alternative available in Gforth, that allows you to pass compile-only
7181: words as parameters is to use the compilation token (@pxref{Compilation
7182: token}). The same example in this technique:
7183:
7184: @example
7185: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7186: 2dup 2>r execute 2r> execute ;
7187:
7188: : 2+ ( n1 -- n2 )
7189: [ comp' 1+ twice ] ;
7190: @end example
7191:
7192: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7193: works even if the executed compilation semantics has an effect on the
7194: data stack.
7195:
7196: You can also define complete definitions with these words; this provides
7197: an alternative to using @code{does>} (@pxref{User-defined Defining
7198: Words}). E.g., instead of
7199:
7200: @example
7201: : curry+ ( n1 "name" -- )
7202: CREATE ,
7203: DOES> ( n2 -- n1+n2 )
7204: @@ + ;
7205: @end example
7206:
7207: you could define
7208:
7209: @example
7210: : curry+ ( n1 "name" -- )
7211: \ name execution: ( n2 -- n1+n2 )
7212: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7213:
1.82 anton 7214: -3 curry+ 3-
7215: see 3-
7216: @end example
1.81 anton 7217:
1.82 anton 7218: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7219: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7220:
1.82 anton 7221: This way of writing defining words is sometimes more, sometimes less
7222: convenient than using @code{does>} (@pxref{Advanced does> usage
7223: example}). One advantage of this method is that it can be optimized
7224: better, because the compiler knows that the value compiled with
7225: @code{literal} is fixed, whereas the data associated with a
7226: @code{create}d word can be changed.
1.47 crook 7227:
1.26 crook 7228: @c ----------------------------------------------------------
1.111 anton 7229: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7230: @section The Text Interpreter
7231: @cindex interpreter - outer
7232: @cindex text interpreter
7233: @cindex outer interpreter
1.1 anton 7234:
1.34 anton 7235: @c Should we really describe all these ugly details? IMO the text
7236: @c interpreter should be much cleaner, but that may not be possible within
7237: @c ANS Forth. - anton
1.44 crook 7238: @c nac-> I wanted to explain how it works to show how you can exploit
7239: @c it in your own programs. When I was writing a cross-compiler, figuring out
7240: @c some of these gory details was very helpful to me. None of the textbooks
7241: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7242: @c seems to positively avoid going into too much detail for some of
7243: @c the internals.
1.34 anton 7244:
1.71 anton 7245: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7246: @c it is; for the ugly details, I would prefer another place. I wonder
7247: @c whether we should have a chapter before "Words" that describes some
7248: @c basic concepts referred to in words, and a chapter after "Words" that
7249: @c describes implementation details.
7250:
1.29 crook 7251: The text interpreter@footnote{This is an expanded version of the
7252: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7253: that processes input from the current input device. It is also called
7254: the outer interpreter, in contrast to the inner interpreter
7255: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7256: implementations.
1.27 crook 7257:
1.29 crook 7258: @cindex interpret state
7259: @cindex compile state
7260: The text interpreter operates in one of two states: @dfn{interpret
7261: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7262: aptly-named variable @code{state}.
1.29 crook 7263:
7264: This section starts by describing how the text interpreter behaves when
7265: it is in interpret state, processing input from the user input device --
7266: the keyboard. This is the mode that a Forth system is in after it starts
7267: up.
7268:
7269: @cindex input buffer
7270: @cindex terminal input buffer
7271: The text interpreter works from an area of memory called the @dfn{input
7272: buffer}@footnote{When the text interpreter is processing input from the
7273: keyboard, this area of memory is called the @dfn{terminal input buffer}
7274: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7275: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7276: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7277: leading spaces (called @dfn{delimiters}) then parses a string (a
7278: sequence of non-space characters) until it reaches either a space
7279: character or the end of the buffer. Having parsed a string, it makes two
7280: attempts to process it:
1.27 crook 7281:
1.29 crook 7282: @cindex dictionary
1.27 crook 7283: @itemize @bullet
7284: @item
1.29 crook 7285: It looks for the string in a @dfn{dictionary} of definitions. If the
7286: string is found, the string names a @dfn{definition} (also known as a
7287: @dfn{word}) and the dictionary search returns information that allows
7288: the text interpreter to perform the word's @dfn{interpretation
7289: semantics}. In most cases, this simply means that the word will be
7290: executed.
1.27 crook 7291: @item
7292: If the string is not found in the dictionary, the text interpreter
1.29 crook 7293: attempts to treat it as a number, using the rules described in
7294: @ref{Number Conversion}. If the string represents a legal number in the
7295: current radix, the number is pushed onto a parameter stack (the data
7296: stack for integers, the floating-point stack for floating-point
7297: numbers).
7298: @end itemize
7299:
7300: If both attempts fail, or if the word is found in the dictionary but has
7301: no interpretation semantics@footnote{This happens if the word was
7302: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7303: remainder of the input buffer, issues an error message and waits for
7304: more input. If one of the attempts succeeds, the text interpreter
7305: repeats the parsing process until the whole of the input buffer has been
7306: processed, at which point it prints the status message ``@code{ ok}''
7307: and waits for more input.
7308:
1.71 anton 7309: @c anton: this should be in the input stream subsection (or below it)
7310:
1.29 crook 7311: @cindex parse area
7312: The text interpreter keeps track of its position in the input buffer by
7313: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7314: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7315: of the input buffer. The region from offset @code{>IN @@} to the end of
7316: the input buffer is called the @dfn{parse area}@footnote{In other words,
7317: the text interpreter processes the contents of the input buffer by
7318: parsing strings from the parse area until the parse area is empty.}.
7319: This example shows how @code{>IN} changes as the text interpreter parses
7320: the input buffer:
7321:
7322: @example
7323: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7324: CR ." ->" TYPE ." <-" ; IMMEDIATE
7325:
7326: 1 2 3 remaining + remaining .
7327:
7328: : foo 1 2 3 remaining SWAP remaining ;
7329: @end example
7330:
7331: @noindent
7332: The result is:
7333:
7334: @example
7335: ->+ remaining .<-
7336: ->.<-5 ok
7337:
7338: ->SWAP remaining ;-<
7339: ->;<- ok
7340: @end example
7341:
7342: @cindex parsing words
7343: The value of @code{>IN} can also be modified by a word in the input
7344: buffer that is executed by the text interpreter. This means that a word
7345: can ``trick'' the text interpreter into either skipping a section of the
7346: input buffer@footnote{This is how parsing words work.} or into parsing a
7347: section twice. For example:
1.27 crook 7348:
1.29 crook 7349: @example
1.71 anton 7350: : lat ." <<foo>>" ;
7351: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7352: @end example
7353:
7354: @noindent
7355: When @code{flat} is executed, this output is produced@footnote{Exercise
7356: for the reader: what would happen if the @code{3} were replaced with
7357: @code{4}?}:
7358:
7359: @example
1.71 anton 7360: <<bar>><<foo>>
1.29 crook 7361: @end example
7362:
1.71 anton 7363: This technique can be used to work around some of the interoperability
7364: problems of parsing words. Of course, it's better to avoid parsing
7365: words where possible.
7366:
1.29 crook 7367: @noindent
7368: Two important notes about the behaviour of the text interpreter:
1.27 crook 7369:
7370: @itemize @bullet
7371: @item
7372: It processes each input string to completion before parsing additional
1.29 crook 7373: characters from the input buffer.
7374: @item
7375: It treats the input buffer as a read-only region (and so must your code).
7376: @end itemize
7377:
7378: @noindent
7379: When the text interpreter is in compile state, its behaviour changes in
7380: these ways:
7381:
7382: @itemize @bullet
7383: @item
7384: If a parsed string is found in the dictionary, the text interpreter will
7385: perform the word's @dfn{compilation semantics}. In most cases, this
7386: simply means that the execution semantics of the word will be appended
7387: to the current definition.
1.27 crook 7388: @item
1.29 crook 7389: When a number is encountered, it is compiled into the current definition
7390: (as a literal) rather than being pushed onto a parameter stack.
7391: @item
7392: If an error occurs, @code{state} is modified to put the text interpreter
7393: back into interpret state.
7394: @item
7395: Each time a line is entered from the keyboard, Gforth prints
7396: ``@code{ compiled}'' rather than `` @code{ok}''.
7397: @end itemize
7398:
7399: @cindex text interpreter - input sources
7400: When the text interpreter is using an input device other than the
7401: keyboard, its behaviour changes in these ways:
7402:
7403: @itemize @bullet
7404: @item
7405: When the parse area is empty, the text interpreter attempts to refill
7406: the input buffer from the input source. When the input source is
1.71 anton 7407: exhausted, the input source is set back to the previous input source.
1.29 crook 7408: @item
7409: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7410: time the parse area is emptied.
7411: @item
7412: If an error occurs, the input source is set back to the user input
7413: device.
1.27 crook 7414: @end itemize
1.21 crook 7415:
1.49 anton 7416: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7417:
1.26 crook 7418: doc->in
1.27 crook 7419: doc-source
7420:
1.26 crook 7421: doc-tib
7422: doc-#tib
1.1 anton 7423:
1.44 crook 7424:
1.26 crook 7425: @menu
1.67 anton 7426: * Input Sources::
7427: * Number Conversion::
7428: * Interpret/Compile states::
7429: * Interpreter Directives::
1.26 crook 7430: @end menu
1.1 anton 7431:
1.29 crook 7432: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7433: @subsection Input Sources
7434: @cindex input sources
7435: @cindex text interpreter - input sources
7436:
1.44 crook 7437: By default, the text interpreter processes input from the user input
1.29 crook 7438: device (the keyboard) when Forth starts up. The text interpreter can
7439: process input from any of these sources:
7440:
7441: @itemize @bullet
7442: @item
7443: The user input device -- the keyboard.
7444: @item
7445: A file, using the words described in @ref{Forth source files}.
7446: @item
7447: A block, using the words described in @ref{Blocks}.
7448: @item
7449: A text string, using @code{evaluate}.
7450: @end itemize
7451:
7452: A program can identify the current input device from the values of
7453: @code{source-id} and @code{blk}.
7454:
1.44 crook 7455:
1.29 crook 7456: doc-source-id
7457: doc-blk
7458:
7459: doc-save-input
7460: doc-restore-input
7461:
7462: doc-evaluate
1.111 anton 7463: doc-query
1.1 anton 7464:
1.29 crook 7465:
1.44 crook 7466:
1.29 crook 7467: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7468: @subsection Number Conversion
7469: @cindex number conversion
7470: @cindex double-cell numbers, input format
7471: @cindex input format for double-cell numbers
7472: @cindex single-cell numbers, input format
7473: @cindex input format for single-cell numbers
7474: @cindex floating-point numbers, input format
7475: @cindex input format for floating-point numbers
1.1 anton 7476:
1.29 crook 7477: This section describes the rules that the text interpreter uses when it
7478: tries to convert a string into a number.
1.1 anton 7479:
1.26 crook 7480: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7481: number base@footnote{For example, 0-9 when the number base is decimal or
7482: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7483:
1.26 crook 7484: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7485:
1.29 crook 7486: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7487: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7488:
1.26 crook 7489: Let * represent any number of instances of the previous character
7490: (including none).
1.1 anton 7491:
1.26 crook 7492: Let any other character represent itself.
1.1 anton 7493:
1.29 crook 7494: @noindent
1.26 crook 7495: Now, the conversion rules are:
1.21 crook 7496:
1.26 crook 7497: @itemize @bullet
7498: @item
7499: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7500: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7501: @item
7502: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7503: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7504: arithmetic. Examples are -45 -5681 -0
7505: @item
7506: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7507: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7508: (all three of these represent the same number).
1.26 crook 7509: @item
7510: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7511: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7512: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7513: -34.65 (all three of these represent the same number).
1.26 crook 7514: @item
1.29 crook 7515: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7516: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7517: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7518: number) +12.E-4
1.26 crook 7519: @end itemize
1.1 anton 7520:
1.26 crook 7521: By default, the number base used for integer number conversion is given
1.35 anton 7522: by the contents of the variable @code{base}. Note that a lot of
7523: confusion can result from unexpected values of @code{base}. If you
7524: change @code{base} anywhere, make sure to save the old value and restore
7525: it afterwards. In general I recommend keeping @code{base} decimal, and
7526: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7527:
1.29 crook 7528: doc-dpl
1.26 crook 7529: doc-base
7530: doc-hex
7531: doc-decimal
1.1 anton 7532:
1.44 crook 7533:
1.26 crook 7534: @cindex '-prefix for character strings
7535: @cindex &-prefix for decimal numbers
7536: @cindex %-prefix for binary numbers
7537: @cindex $-prefix for hexadecimal numbers
1.35 anton 7538: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7539: prefix@footnote{Some Forth implementations provide a similar scheme by
7540: implementing @code{$} etc. as parsing words that process the subsequent
7541: number in the input stream and push it onto the stack. For example, see
7542: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7543: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7544: is required between the prefix and the number.} before the first digit
7545: of an (integer) number. Four prefixes are supported:
1.1 anton 7546:
1.26 crook 7547: @itemize @bullet
7548: @item
1.35 anton 7549: @code{&} -- decimal
1.26 crook 7550: @item
1.35 anton 7551: @code{%} -- binary
1.26 crook 7552: @item
1.35 anton 7553: @code{$} -- hexadecimal
1.26 crook 7554: @item
1.35 anton 7555: @code{'} -- base @code{max-char+1}
1.26 crook 7556: @end itemize
1.1 anton 7557:
1.26 crook 7558: Here are some examples, with the equivalent decimal number shown after
7559: in braces:
1.1 anton 7560:
1.26 crook 7561: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
7562: 'AB (16706; ascii A is 65, ascii B is 66, number is 65*256 + 66),
7563: 'ab (24930; ascii a is 97, ascii B is 98, number is 97*256 + 98),
7564: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7565:
1.26 crook 7566: @cindex number conversion - traps for the unwary
1.29 crook 7567: @noindent
1.26 crook 7568: Number conversion has a number of traps for the unwary:
1.1 anton 7569:
1.26 crook 7570: @itemize @bullet
7571: @item
7572: You cannot determine the current number base using the code sequence
1.35 anton 7573: @code{base @@ .} -- the number base is always 10 in the current number
7574: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7575: @item
7576: If the number base is set to a value greater than 14 (for example,
7577: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7578: it to be intepreted as either a single-precision integer or a
7579: floating-point number (Gforth treats it as an integer). The ambiguity
7580: can be resolved by explicitly stating the sign of the mantissa and/or
7581: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7582: ambiguity arises; either representation will be treated as a
7583: floating-point number.
7584: @item
1.29 crook 7585: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7586: It is used to specify file types.
7587: @item
1.72 anton 7588: ANS Forth requires the @code{.} of a double-precision number to be the
7589: final character in the string. Gforth allows the @code{.} to be
7590: anywhere after the first digit.
1.26 crook 7591: @item
7592: The number conversion process does not check for overflow.
7593: @item
1.72 anton 7594: In an ANS Forth program @code{base} is required to be decimal when
7595: converting floating-point numbers. In Gforth, number conversion to
7596: floating-point numbers always uses base &10, irrespective of the value
7597: of @code{base}.
1.26 crook 7598: @end itemize
1.1 anton 7599:
1.49 anton 7600: You can read numbers into your programs with the words described in
7601: @ref{Input}.
1.1 anton 7602:
1.82 anton 7603: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7604: @subsection Interpret/Compile states
7605: @cindex Interpret/Compile states
1.1 anton 7606:
1.29 crook 7607: A standard program is not permitted to change @code{state}
7608: explicitly. However, it can change @code{state} implicitly, using the
7609: words @code{[} and @code{]}. When @code{[} is executed it switches
7610: @code{state} to interpret state, and therefore the text interpreter
7611: starts interpreting. When @code{]} is executed it switches @code{state}
7612: to compile state and therefore the text interpreter starts
1.44 crook 7613: compiling. The most common usage for these words is for switching into
7614: interpret state and back from within a colon definition; this technique
1.49 anton 7615: can be used to compile a literal (for an example, @pxref{Literals}) or
7616: for conditional compilation (for an example, @pxref{Interpreter
7617: Directives}).
1.44 crook 7618:
1.35 anton 7619:
7620: @c This is a bad example: It's non-standard, and it's not necessary.
7621: @c However, I can't think of a good example for switching into compile
7622: @c state when there is no current word (@code{state}-smart words are not a
7623: @c good reason). So maybe we should use an example for switching into
7624: @c interpret @code{state} in a colon def. - anton
1.44 crook 7625: @c nac-> I agree. I started out by putting in the example, then realised
7626: @c that it was non-ANS, so wrote more words around it. I hope this
7627: @c re-written version is acceptable to you. I do want to keep the example
7628: @c as it is helpful for showing what is and what is not portable, particularly
7629: @c where it outlaws a style in common use.
7630:
1.72 anton 7631: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7632: @c that, we can also show what's not. In any case, I have written a
7633: @c section Compiling Words which also deals with [ ].
1.35 anton 7634:
1.95 anton 7635: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7636:
1.95 anton 7637: @c @code{[} and @code{]} also give you the ability to switch into compile
7638: @c state and back, but we cannot think of any useful Standard application
7639: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7640:
7641: @c @example
7642: @c : AA ." this is A" ;
7643: @c : BB ." this is B" ;
7644: @c : CC ." this is C" ;
7645:
7646: @c create table ] aa bb cc [
7647:
7648: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7649: @c cells table + @@ execute ;
7650: @c @end example
7651:
7652: @c This example builds a jump table; @code{0 go} will display ``@code{this
7653: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7654: @c defining @code{table} like this:
7655:
7656: @c @example
7657: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7658: @c @end example
7659:
7660: @c The problem with this code is that the definition of @code{table} is not
7661: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7662: @c @i{may} work on systems where code space and data space co-incide, the
7663: @c Standard only allows data space to be assigned for a @code{CREATE}d
7664: @c word. In addition, the Standard only allows @code{@@} to access data
7665: @c space, whilst this example is using it to access code space. The only
7666: @c portable, Standard way to build this table is to build it in data space,
7667: @c like this:
7668:
7669: @c @example
7670: @c create table ' aa , ' bb , ' cc ,
7671: @c @end example
1.29 crook 7672:
1.95 anton 7673: @c doc-state
1.44 crook 7674:
1.29 crook 7675:
1.82 anton 7676: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7677: @subsection Interpreter Directives
7678: @cindex interpreter directives
1.72 anton 7679: @cindex conditional compilation
1.1 anton 7680:
1.29 crook 7681: These words are usually used in interpret state; typically to control
7682: which parts of a source file are processed by the text
1.26 crook 7683: interpreter. There are only a few ANS Forth Standard words, but Gforth
7684: supplements these with a rich set of immediate control structure words
7685: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7686: used in compile state (@pxref{Control Structures}). Typical usages:
7687:
7688: @example
1.72 anton 7689: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7690: .
7691: .
1.72 anton 7692: HAVE-ASSEMBLER [IF]
1.29 crook 7693: : ASSEMBLER-FEATURE
7694: ...
7695: ;
7696: [ENDIF]
7697: .
7698: .
7699: : SEE
7700: ... \ general-purpose SEE code
1.72 anton 7701: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7702: ... \ assembler-specific SEE code
7703: [ [ENDIF] ]
7704: ;
7705: @end example
1.1 anton 7706:
1.44 crook 7707:
1.26 crook 7708: doc-[IF]
7709: doc-[ELSE]
7710: doc-[THEN]
7711: doc-[ENDIF]
1.1 anton 7712:
1.26 crook 7713: doc-[IFDEF]
7714: doc-[IFUNDEF]
1.1 anton 7715:
1.26 crook 7716: doc-[?DO]
7717: doc-[DO]
7718: doc-[FOR]
7719: doc-[LOOP]
7720: doc-[+LOOP]
7721: doc-[NEXT]
1.1 anton 7722:
1.26 crook 7723: doc-[BEGIN]
7724: doc-[UNTIL]
7725: doc-[AGAIN]
7726: doc-[WHILE]
7727: doc-[REPEAT]
1.1 anton 7728:
1.27 crook 7729:
1.26 crook 7730: @c -------------------------------------------------------------
1.111 anton 7731: @node The Input Stream, Word Lists, The Text Interpreter, Words
7732: @section The Input Stream
7733: @cindex input stream
7734:
7735: @c !! integrate this better with the "Text Interpreter" section
7736: The text interpreter reads from the input stream, which can come from
7737: several sources (@pxref{Input Sources}). Some words, in particular
7738: defining words, but also words like @code{'}, read parameters from the
7739: input stream instead of from the stack.
7740:
7741: Such words are called parsing words, because they parse the input
7742: stream. Parsing words are hard to use in other words, because it is
7743: hard to pass program-generated parameters through the input stream.
7744: They also usually have an unintuitive combination of interpretation and
7745: compilation semantics when implemented naively, leading to various
7746: approaches that try to produce a more intuitive behaviour
7747: (@pxref{Combined words}).
7748:
7749: It should be obvious by now that parsing words are a bad idea. If you
7750: want to implement a parsing word for convenience, also provide a factor
7751: of the word that does not parse, but takes the parameters on the stack.
7752: To implement the parsing word on top if it, you can use the following
7753: words:
7754:
7755: @c anton: these belong in the input stream section
7756: doc-parse
7757: doc-parse-word
7758: doc-name
7759: doc-word
7760: doc-\"-parse
7761: doc-refill
7762:
7763: Conversely, if you have the bad luck (or lack of foresight) to have to
7764: deal with parsing words without having such factors, how do you pass a
7765: string that is not in the input stream to it?
7766:
7767: doc-execute-parsing
7768:
7769: If you want to run a parsing word on a file, the following word should
7770: help:
7771:
7772: doc-execute-parsing-file
7773:
7774: @c -------------------------------------------------------------
7775: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7776: @section Word Lists
7777: @cindex word lists
1.32 anton 7778: @cindex header space
1.1 anton 7779:
1.36 anton 7780: A wordlist is a list of named words; you can add new words and look up
7781: words by name (and you can remove words in a restricted way with
7782: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7783:
7784: @cindex search order stack
7785: The text interpreter searches the wordlists present in the search order
7786: (a stack of wordlists), from the top to the bottom. Within each
7787: wordlist, the search starts conceptually at the newest word; i.e., if
7788: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7789:
1.26 crook 7790: @cindex compilation word list
1.36 anton 7791: New words are added to the @dfn{compilation wordlist} (aka current
7792: wordlist).
1.1 anton 7793:
1.36 anton 7794: @cindex wid
7795: A word list is identified by a cell-sized word list identifier (@i{wid})
7796: in much the same way as a file is identified by a file handle. The
7797: numerical value of the wid has no (portable) meaning, and might change
7798: from session to session.
1.1 anton 7799:
1.29 crook 7800: The ANS Forth ``Search order'' word set is intended to provide a set of
7801: low-level tools that allow various different schemes to be
1.74 anton 7802: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7803: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7804: Forth.
1.1 anton 7805:
1.27 crook 7806: @comment TODO: locals section refers to here, saying that every word list (aka
7807: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7808: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7809:
1.45 crook 7810: @comment TODO: document markers, reveal, tables, mappedwordlist
7811:
7812: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7813: @comment word from the source files, rather than some alias.
1.44 crook 7814:
1.26 crook 7815: doc-forth-wordlist
7816: doc-definitions
7817: doc-get-current
7818: doc-set-current
7819: doc-get-order
1.45 crook 7820: doc---gforthman-set-order
1.26 crook 7821: doc-wordlist
1.30 anton 7822: doc-table
1.79 anton 7823: doc->order
1.36 anton 7824: doc-previous
1.26 crook 7825: doc-also
1.45 crook 7826: doc---gforthman-forth
1.26 crook 7827: doc-only
1.45 crook 7828: doc---gforthman-order
1.15 anton 7829:
1.26 crook 7830: doc-find
7831: doc-search-wordlist
1.15 anton 7832:
1.26 crook 7833: doc-words
7834: doc-vlist
1.44 crook 7835: @c doc-words-deferred
1.1 anton 7836:
1.74 anton 7837: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7838: doc-root
7839: doc-vocabulary
7840: doc-seal
7841: doc-vocs
7842: doc-current
7843: doc-context
1.1 anton 7844:
1.44 crook 7845:
1.26 crook 7846: @menu
1.75 anton 7847: * Vocabularies::
1.67 anton 7848: * Why use word lists?::
1.75 anton 7849: * Word list example::
1.26 crook 7850: @end menu
7851:
1.75 anton 7852: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7853: @subsection Vocabularies
7854: @cindex Vocabularies, detailed explanation
7855:
7856: Here is an example of creating and using a new wordlist using ANS
7857: Forth words:
7858:
7859: @example
7860: wordlist constant my-new-words-wordlist
7861: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7862:
7863: \ add it to the search order
7864: also my-new-words
7865:
7866: \ alternatively, add it to the search order and make it
7867: \ the compilation word list
7868: also my-new-words definitions
7869: \ type "order" to see the problem
7870: @end example
7871:
7872: The problem with this example is that @code{order} has no way to
7873: associate the name @code{my-new-words} with the wid of the word list (in
7874: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7875: that has no associated name). There is no Standard way of associating a
7876: name with a wid.
7877:
7878: In Gforth, this example can be re-coded using @code{vocabulary}, which
7879: associates a name with a wid:
7880:
7881: @example
7882: vocabulary my-new-words
7883:
7884: \ add it to the search order
7885: also my-new-words
7886:
7887: \ alternatively, add it to the search order and make it
7888: \ the compilation word list
7889: my-new-words definitions
7890: \ type "order" to see that the problem is solved
7891: @end example
7892:
7893:
7894: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 7895: @subsection Why use word lists?
7896: @cindex word lists - why use them?
7897:
1.74 anton 7898: Here are some reasons why people use wordlists:
1.26 crook 7899:
7900: @itemize @bullet
1.74 anton 7901:
7902: @c anton: Gforth's hashing implementation makes the search speed
7903: @c independent from the number of words. But it is linear with the number
7904: @c of wordlists that have to be searched, so in effect using more wordlists
7905: @c actually slows down compilation.
7906:
7907: @c @item
7908: @c To improve compilation speed by reducing the number of header space
7909: @c entries that must be searched. This is achieved by creating a new
7910: @c word list that contains all of the definitions that are used in the
7911: @c definition of a Forth system but which would not usually be used by
7912: @c programs running on that system. That word list would be on the search
7913: @c list when the Forth system was compiled but would be removed from the
7914: @c search list for normal operation. This can be a useful technique for
7915: @c low-performance systems (for example, 8-bit processors in embedded
7916: @c systems) but is unlikely to be necessary in high-performance desktop
7917: @c systems.
7918:
1.26 crook 7919: @item
7920: To prevent a set of words from being used outside the context in which
7921: they are valid. Two classic examples of this are an integrated editor
7922: (all of the edit commands are defined in a separate word list; the
7923: search order is set to the editor word list when the editor is invoked;
7924: the old search order is restored when the editor is terminated) and an
7925: integrated assembler (the op-codes for the machine are defined in a
7926: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 7927:
7928: @item
7929: To organize the words of an application or library into a user-visible
7930: set (in @code{forth-wordlist} or some other common wordlist) and a set
7931: of helper words used just for the implementation (hidden in a separate
1.75 anton 7932: wordlist). This keeps @code{words}' output smaller, separates
7933: implementation and interface, and reduces the chance of name conflicts
7934: within the common wordlist.
1.74 anton 7935:
1.26 crook 7936: @item
7937: To prevent a name-space clash between multiple definitions with the same
7938: name. For example, when building a cross-compiler you might have a word
7939: @code{IF} that generates conditional code for your target system. By
7940: placing this definition in a different word list you can control whether
7941: the host system's @code{IF} or the target system's @code{IF} get used in
7942: any particular context by controlling the order of the word lists on the
7943: search order stack.
1.74 anton 7944:
1.26 crook 7945: @end itemize
1.1 anton 7946:
1.74 anton 7947: The downsides of using wordlists are:
7948:
7949: @itemize
7950:
7951: @item
7952: Debugging becomes more cumbersome.
7953:
7954: @item
7955: Name conflicts worked around with wordlists are still there, and you
7956: have to arrange the search order carefully to get the desired results;
7957: if you forget to do that, you get hard-to-find errors (as in any case
7958: where you read the code differently from the compiler; @code{see} can
1.75 anton 7959: help seeing which of several possible words the name resolves to in such
7960: cases). @code{See} displays just the name of the words, not what
7961: wordlist they belong to, so it might be misleading. Using unique names
7962: is a better approach to avoid name conflicts.
1.74 anton 7963:
7964: @item
7965: You have to explicitly undo any changes to the search order. In many
7966: cases it would be more convenient if this happened implicitly. Gforth
7967: currently does not provide such a feature, but it may do so in the
7968: future.
7969: @end itemize
7970:
7971:
1.75 anton 7972: @node Word list example, , Why use word lists?, Word Lists
7973: @subsection Word list example
7974: @cindex word lists - example
1.1 anton 7975:
1.74 anton 7976: The following example is from the
7977: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
7978: garbage collector} and uses wordlists to separate public words from
7979: helper words:
7980:
7981: @example
7982: get-current ( wid )
7983: vocabulary garbage-collector also garbage-collector definitions
7984: ... \ define helper words
7985: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
7986: ... \ define the public (i.e., API) words
7987: \ they can refer to the helper words
7988: previous \ restore original search order (helper words become invisible)
7989: @end example
7990:
1.26 crook 7991: @c -------------------------------------------------------------
7992: @node Environmental Queries, Files, Word Lists, Words
7993: @section Environmental Queries
7994: @cindex environmental queries
1.21 crook 7995:
1.26 crook 7996: ANS Forth introduced the idea of ``environmental queries'' as a way
7997: for a program running on a system to determine certain characteristics of the system.
7998: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 7999:
1.32 anton 8000: The Standard requires that the header space used for environmental queries
8001: be distinct from the header space used for definitions.
1.21 crook 8002:
1.26 crook 8003: Typically, environmental queries are supported by creating a set of
1.29 crook 8004: definitions in a word list that is @i{only} used during environmental
1.26 crook 8005: queries; that is what Gforth does. There is no Standard way of adding
8006: definitions to the set of recognised environmental queries, but any
8007: implementation that supports the loading of optional word sets must have
8008: some mechanism for doing this (after loading the word set, the
8009: associated environmental query string must return @code{true}). In
8010: Gforth, the word list used to honour environmental queries can be
8011: manipulated just like any other word list.
1.21 crook 8012:
1.44 crook 8013:
1.26 crook 8014: doc-environment?
8015: doc-environment-wordlist
1.21 crook 8016:
1.26 crook 8017: doc-gforth
8018: doc-os-class
1.21 crook 8019:
1.44 crook 8020:
1.26 crook 8021: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8022: returning two items on the stack, querying it using @code{environment?}
8023: will return an additional item; the @code{true} flag that shows that the
8024: string was recognised.
1.21 crook 8025:
1.26 crook 8026: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8027:
1.26 crook 8028: Here are some examples of using environmental queries:
1.21 crook 8029:
1.26 crook 8030: @example
8031: s" address-unit-bits" environment? 0=
8032: [IF]
8033: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8034: [ELSE]
8035: drop \ ensure balanced stack effect
1.26 crook 8036: [THEN]
1.21 crook 8037:
1.75 anton 8038: \ this might occur in the prelude of a standard program that uses THROW
8039: s" exception" environment? [IF]
8040: 0= [IF]
8041: : throw abort" exception thrown" ;
8042: [THEN]
8043: [ELSE] \ we don't know, so make sure
8044: : throw abort" exception thrown" ;
8045: [THEN]
1.21 crook 8046:
1.26 crook 8047: s" gforth" environment? [IF] .( Gforth version ) TYPE
8048: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8049:
8050: \ a program using v*
8051: s" gforth" environment? [IF]
8052: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8053: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8054: >r swap 2swap swap 0e r> 0 ?DO
8055: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8056: LOOP
8057: 2drop 2drop ;
8058: [THEN]
8059: [ELSE] \
8060: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8061: ...
8062: [THEN]
1.26 crook 8063: @end example
1.21 crook 8064:
1.26 crook 8065: Here is an example of adding a definition to the environment word list:
1.21 crook 8066:
1.26 crook 8067: @example
8068: get-current environment-wordlist set-current
8069: true constant block
8070: true constant block-ext
8071: set-current
8072: @end example
1.21 crook 8073:
1.26 crook 8074: You can see what definitions are in the environment word list like this:
1.21 crook 8075:
1.26 crook 8076: @example
1.79 anton 8077: environment-wordlist >order words previous
1.26 crook 8078: @end example
1.21 crook 8079:
8080:
1.26 crook 8081: @c -------------------------------------------------------------
8082: @node Files, Blocks, Environmental Queries, Words
8083: @section Files
1.28 crook 8084: @cindex files
8085: @cindex I/O - file-handling
1.21 crook 8086:
1.26 crook 8087: Gforth provides facilities for accessing files that are stored in the
8088: host operating system's file-system. Files that are processed by Gforth
8089: can be divided into two categories:
1.21 crook 8090:
1.23 crook 8091: @itemize @bullet
8092: @item
1.29 crook 8093: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8094: @item
1.29 crook 8095: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8096: @end itemize
8097:
8098: @menu
1.48 anton 8099: * Forth source files::
8100: * General files::
8101: * Search Paths::
1.26 crook 8102: @end menu
8103:
8104: @c -------------------------------------------------------------
8105: @node Forth source files, General files, Files, Files
8106: @subsection Forth source files
8107: @cindex including files
8108: @cindex Forth source files
1.21 crook 8109:
1.26 crook 8110: The simplest way to interpret the contents of a file is to use one of
8111: these two formats:
1.21 crook 8112:
1.26 crook 8113: @example
8114: include mysource.fs
8115: s" mysource.fs" included
8116: @end example
1.21 crook 8117:
1.75 anton 8118: You usually want to include a file only if it is not included already
1.26 crook 8119: (by, say, another source file). In that case, you can use one of these
1.45 crook 8120: three formats:
1.21 crook 8121:
1.26 crook 8122: @example
8123: require mysource.fs
8124: needs mysource.fs
8125: s" mysource.fs" required
8126: @end example
1.21 crook 8127:
1.26 crook 8128: @cindex stack effect of included files
8129: @cindex including files, stack effect
1.45 crook 8130: It is good practice to write your source files such that interpreting them
8131: does not change the stack. Source files designed in this way can be used with
1.26 crook 8132: @code{required} and friends without complications. For example:
1.21 crook 8133:
1.26 crook 8134: @example
1.75 anton 8135: 1024 require foo.fs drop
1.26 crook 8136: @end example
1.21 crook 8137:
1.75 anton 8138: Here you want to pass the argument 1024 (e.g., a buffer size) to
8139: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8140: ), which allows its use with @code{require}. Of course with such
8141: parameters to required files, you have to ensure that the first
8142: @code{require} fits for all uses (i.e., @code{require} it early in the
8143: master load file).
1.44 crook 8144:
1.26 crook 8145: doc-include-file
8146: doc-included
1.28 crook 8147: doc-included?
1.26 crook 8148: doc-include
8149: doc-required
8150: doc-require
8151: doc-needs
1.75 anton 8152: @c doc-init-included-files @c internal
8153: doc-sourcefilename
8154: doc-sourceline#
1.44 crook 8155:
1.26 crook 8156: A definition in ANS Forth for @code{required} is provided in
8157: @file{compat/required.fs}.
1.21 crook 8158:
1.26 crook 8159: @c -------------------------------------------------------------
8160: @node General files, Search Paths, Forth source files, Files
8161: @subsection General files
8162: @cindex general files
8163: @cindex file-handling
1.21 crook 8164:
1.75 anton 8165: Files are opened/created by name and type. The following file access
8166: methods (FAMs) are recognised:
1.44 crook 8167:
1.75 anton 8168: @cindex fam (file access method)
1.26 crook 8169: doc-r/o
8170: doc-r/w
8171: doc-w/o
8172: doc-bin
1.1 anton 8173:
1.44 crook 8174:
1.26 crook 8175: When a file is opened/created, it returns a file identifier,
1.29 crook 8176: @i{wfileid} that is used for all other file commands. All file
8177: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8178: successful operation and an implementation-defined non-zero value in the
8179: case of an error.
1.21 crook 8180:
1.44 crook 8181:
1.26 crook 8182: doc-open-file
8183: doc-create-file
1.21 crook 8184:
1.26 crook 8185: doc-close-file
8186: doc-delete-file
8187: doc-rename-file
8188: doc-read-file
8189: doc-read-line
8190: doc-write-file
8191: doc-write-line
8192: doc-emit-file
8193: doc-flush-file
1.21 crook 8194:
1.26 crook 8195: doc-file-status
8196: doc-file-position
8197: doc-reposition-file
8198: doc-file-size
8199: doc-resize-file
1.21 crook 8200:
1.93 anton 8201: doc-slurp-file
8202: doc-slurp-fid
1.112 anton 8203: doc-stdin
8204: doc-stdout
8205: doc-stderr
1.44 crook 8206:
1.26 crook 8207: @c ---------------------------------------------------------
1.48 anton 8208: @node Search Paths, , General files, Files
1.26 crook 8209: @subsection Search Paths
8210: @cindex path for @code{included}
8211: @cindex file search path
8212: @cindex @code{include} search path
8213: @cindex search path for files
1.21 crook 8214:
1.26 crook 8215: If you specify an absolute filename (i.e., a filename starting with
8216: @file{/} or @file{~}, or with @file{:} in the second position (as in
8217: @samp{C:...})) for @code{included} and friends, that file is included
8218: just as you would expect.
1.21 crook 8219:
1.75 anton 8220: If the filename starts with @file{./}, this refers to the directory that
8221: the present file was @code{included} from. This allows files to include
8222: other files relative to their own position (irrespective of the current
8223: working directory or the absolute position). This feature is essential
8224: for libraries consisting of several files, where a file may include
8225: other files from the library. It corresponds to @code{#include "..."}
8226: in C. If the current input source is not a file, @file{.} refers to the
8227: directory of the innermost file being included, or, if there is no file
8228: being included, to the current working directory.
8229:
8230: For relative filenames (not starting with @file{./}), Gforth uses a
8231: search path similar to Forth's search order (@pxref{Word Lists}). It
8232: tries to find the given filename in the directories present in the path,
8233: and includes the first one it finds. There are separate search paths for
8234: Forth source files and general files. If the search path contains the
8235: directory @file{.}, this refers to the directory of the current file, or
8236: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8237:
1.26 crook 8238: Use @file{~+} to refer to the current working directory (as in the
8239: @code{bash}).
1.1 anton 8240:
1.75 anton 8241: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8242:
1.48 anton 8243: @menu
1.75 anton 8244: * Source Search Paths::
1.48 anton 8245: * General Search Paths::
8246: @end menu
8247:
1.26 crook 8248: @c ---------------------------------------------------------
1.75 anton 8249: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8250: @subsubsection Source Search Paths
8251: @cindex search path control, source files
1.5 anton 8252:
1.26 crook 8253: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8254: Gforth}). You can display it and change it using @code{fpath} in
8255: combination with the general path handling words.
1.5 anton 8256:
1.75 anton 8257: doc-fpath
8258: @c the functionality of the following words is easily available through
8259: @c fpath and the general path words. The may go away.
8260: @c doc-.fpath
8261: @c doc-fpath+
8262: @c doc-fpath=
8263: @c doc-open-fpath-file
1.44 crook 8264:
8265: @noindent
1.26 crook 8266: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8267:
1.26 crook 8268: @example
1.75 anton 8269: fpath path= /usr/lib/forth/|./
1.26 crook 8270: require timer.fs
8271: @end example
1.5 anton 8272:
1.75 anton 8273:
1.26 crook 8274: @c ---------------------------------------------------------
1.75 anton 8275: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8276: @subsubsection General Search Paths
1.75 anton 8277: @cindex search path control, source files
1.5 anton 8278:
1.26 crook 8279: Your application may need to search files in several directories, like
8280: @code{included} does. To facilitate this, Gforth allows you to define
8281: and use your own search paths, by providing generic equivalents of the
8282: Forth search path words:
1.5 anton 8283:
1.75 anton 8284: doc-open-path-file
8285: doc-path-allot
8286: doc-clear-path
8287: doc-also-path
1.26 crook 8288: doc-.path
8289: doc-path+
8290: doc-path=
1.5 anton 8291:
1.75 anton 8292: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8293:
1.75 anton 8294: Here's an example of creating an empty search path:
8295: @c
1.26 crook 8296: @example
1.75 anton 8297: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8298: @end example
1.5 anton 8299:
1.26 crook 8300: @c -------------------------------------------------------------
8301: @node Blocks, Other I/O, Files, Words
8302: @section Blocks
1.28 crook 8303: @cindex I/O - blocks
8304: @cindex blocks
8305:
8306: When you run Gforth on a modern desk-top computer, it runs under the
8307: control of an operating system which provides certain services. One of
8308: these services is @var{file services}, which allows Forth source code
8309: and data to be stored in files and read into Gforth (@pxref{Files}).
8310:
8311: Traditionally, Forth has been an important programming language on
8312: systems where it has interfaced directly to the underlying hardware with
8313: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8314: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8315:
8316: A block is a 1024-byte data area, which can be used to hold data or
8317: Forth source code. No structure is imposed on the contents of the
8318: block. A block is identified by its number; blocks are numbered
8319: contiguously from 1 to an implementation-defined maximum.
8320:
8321: A typical system that used blocks but no operating system might use a
8322: single floppy-disk drive for mass storage, with the disks formatted to
8323: provide 256-byte sectors. Blocks would be implemented by assigning the
8324: first four sectors of the disk to block 1, the second four sectors to
8325: block 2 and so on, up to the limit of the capacity of the disk. The disk
8326: would not contain any file system information, just the set of blocks.
8327:
1.29 crook 8328: @cindex blocks file
1.28 crook 8329: On systems that do provide file services, blocks are typically
1.29 crook 8330: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8331: file}. The size of the blocks file will be an exact multiple of 1024
8332: bytes, corresponding to the number of blocks it contains. This is the
8333: mechanism that Gforth uses.
8334:
1.29 crook 8335: @cindex @file{blocks.fb}
1.75 anton 8336: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8337: having specified a blocks file, Gforth defaults to the blocks file
8338: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8339: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8340:
1.29 crook 8341: @cindex block buffers
1.28 crook 8342: When you read and write blocks under program control, Gforth uses a
1.29 crook 8343: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8344: not used when you use @code{load} to interpret the contents of a block.
8345:
1.75 anton 8346: The behaviour of the block buffers is analagous to that of a cache.
8347: Each block buffer has three states:
1.28 crook 8348:
8349: @itemize @bullet
8350: @item
8351: Unassigned
8352: @item
8353: Assigned-clean
8354: @item
8355: Assigned-dirty
8356: @end itemize
8357:
1.29 crook 8358: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8359: block, the block (specified by its block number) must be assigned to a
8360: block buffer.
8361:
8362: The assignment of a block to a block buffer is performed by @code{block}
8363: or @code{buffer}. Use @code{block} when you wish to modify the existing
8364: contents of a block. Use @code{buffer} when you don't care about the
8365: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8366: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8367: with the particular block is already stored in a block buffer due to an
8368: earlier @code{block} command, @code{buffer} will return that block
8369: buffer and the existing contents of the block will be
8370: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8371: block buffer for the block.}.
1.28 crook 8372:
1.47 crook 8373: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8374: @code{buffer}, that block buffer becomes the @i{current block
8375: buffer}. Data may only be manipulated (read or written) within the
8376: current block buffer.
1.47 crook 8377:
8378: When the contents of the current block buffer has been modified it is
1.48 anton 8379: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8380: either abandon the changes (by doing nothing) or mark the block as
8381: changed (assigned-dirty), using @code{update}. Using @code{update} does
8382: not change the blocks file; it simply changes a block buffer's state to
8383: @i{assigned-dirty}. The block will be written implicitly when it's
8384: buffer is needed for another block, or explicitly by @code{flush} or
8385: @code{save-buffers}.
8386:
8387: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8388: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8389: @code{flush}.
1.28 crook 8390:
1.29 crook 8391: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8392: algorithm to assign a block buffer to a block. That means that any
8393: particular block can only be assigned to one specific block buffer,
1.29 crook 8394: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8395: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8396: the new block immediately. If it is @i{assigned-dirty} its current
8397: contents are written back to the blocks file on disk before it is
1.28 crook 8398: allocated to the new block.
8399:
8400: Although no structure is imposed on the contents of a block, it is
8401: traditional to display the contents as 16 lines each of 64 characters. A
8402: block provides a single, continuous stream of input (for example, it
8403: acts as a single parse area) -- there are no end-of-line characters
8404: within a block, and no end-of-file character at the end of a
8405: block. There are two consequences of this:
1.26 crook 8406:
1.28 crook 8407: @itemize @bullet
8408: @item
8409: The last character of one line wraps straight into the first character
8410: of the following line
8411: @item
8412: The word @code{\} -- comment to end of line -- requires special
8413: treatment; in the context of a block it causes all characters until the
8414: end of the current 64-character ``line'' to be ignored.
8415: @end itemize
8416:
8417: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8418: the current blocks file will be extended to the appropriate size and the
1.28 crook 8419: block buffer will be initialised with spaces.
8420:
1.47 crook 8421: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8422: for details) but doesn't encourage the use of blocks; the mechanism is
8423: only provided for backward compatibility -- ANS Forth requires blocks to
8424: be available when files are.
1.28 crook 8425:
8426: Common techniques that are used when working with blocks include:
8427:
8428: @itemize @bullet
8429: @item
8430: A screen editor that allows you to edit blocks without leaving the Forth
8431: environment.
8432: @item
8433: Shadow screens; where every code block has an associated block
8434: containing comments (for example: code in odd block numbers, comments in
8435: even block numbers). Typically, the block editor provides a convenient
8436: mechanism to toggle between code and comments.
8437: @item
8438: Load blocks; a single block (typically block 1) contains a number of
8439: @code{thru} commands which @code{load} the whole of the application.
8440: @end itemize
1.26 crook 8441:
1.29 crook 8442: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8443: integrated into a Forth programming environment.
1.26 crook 8444:
8445: @comment TODO what about errors on open-blocks?
1.44 crook 8446:
1.26 crook 8447: doc-open-blocks
8448: doc-use
1.75 anton 8449: doc-block-offset
1.26 crook 8450: doc-get-block-fid
8451: doc-block-position
1.28 crook 8452:
1.75 anton 8453: doc-list
1.28 crook 8454: doc-scr
8455:
1.45 crook 8456: doc---gforthman-block
1.28 crook 8457: doc-buffer
8458:
1.75 anton 8459: doc-empty-buffers
8460: doc-empty-buffer
1.26 crook 8461: doc-update
1.28 crook 8462: doc-updated?
1.26 crook 8463: doc-save-buffers
1.75 anton 8464: doc-save-buffer
1.26 crook 8465: doc-flush
1.28 crook 8466:
1.26 crook 8467: doc-load
8468: doc-thru
8469: doc-+load
8470: doc-+thru
1.45 crook 8471: doc---gforthman--->
1.26 crook 8472: doc-block-included
8473:
1.44 crook 8474:
1.26 crook 8475: @c -------------------------------------------------------------
1.78 anton 8476: @node Other I/O, Locals, Blocks, Words
1.26 crook 8477: @section Other I/O
1.28 crook 8478: @cindex I/O - keyboard and display
1.26 crook 8479:
8480: @menu
8481: * Simple numeric output:: Predefined formats
8482: * Formatted numeric output:: Formatted (pictured) output
8483: * String Formats:: How Forth stores strings in memory
1.67 anton 8484: * Displaying characters and strings:: Other stuff
1.26 crook 8485: * Input:: Input
1.112 anton 8486: * Pipes:: How to create your own pipes
1.26 crook 8487: @end menu
8488:
8489: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8490: @subsection Simple numeric output
1.28 crook 8491: @cindex numeric output - simple/free-format
1.5 anton 8492:
1.26 crook 8493: The simplest output functions are those that display numbers from the
8494: data or floating-point stacks. Floating-point output is always displayed
8495: using base 10. Numbers displayed from the data stack use the value stored
8496: in @code{base}.
1.5 anton 8497:
1.44 crook 8498:
1.26 crook 8499: doc-.
8500: doc-dec.
8501: doc-hex.
8502: doc-u.
8503: doc-.r
8504: doc-u.r
8505: doc-d.
8506: doc-ud.
8507: doc-d.r
8508: doc-ud.r
8509: doc-f.
8510: doc-fe.
8511: doc-fs.
1.111 anton 8512: doc-f.rdp
1.44 crook 8513:
1.26 crook 8514: Examples of printing the number 1234.5678E23 in the different floating-point output
8515: formats are shown below:
1.5 anton 8516:
8517: @example
1.26 crook 8518: f. 123456779999999000000000000.
8519: fe. 123.456779999999E24
8520: fs. 1.23456779999999E26
1.5 anton 8521: @end example
8522:
8523:
1.26 crook 8524: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8525: @subsection Formatted numeric output
1.28 crook 8526: @cindex formatted numeric output
1.26 crook 8527: @cindex pictured numeric output
1.28 crook 8528: @cindex numeric output - formatted
1.26 crook 8529:
1.29 crook 8530: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8531: output} for formatted printing of integers. In this technique, digits
8532: are extracted from the number (using the current output radix defined by
8533: @code{base}), converted to ASCII codes and appended to a string that is
8534: built in a scratch-pad area of memory (@pxref{core-idef,
8535: Implementation-defined options, Implementation-defined
8536: options}). Arbitrary characters can be appended to the string during the
8537: extraction process. The completed string is specified by an address
8538: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8539: under program control.
1.5 anton 8540:
1.75 anton 8541: All of the integer output words described in the previous section
8542: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8543: numeric output.
1.5 anton 8544:
1.47 crook 8545: Three important things to remember about pictured numeric output:
1.5 anton 8546:
1.26 crook 8547: @itemize @bullet
8548: @item
1.28 crook 8549: It always operates on double-precision numbers; to display a
1.49 anton 8550: single-precision number, convert it first (for ways of doing this
8551: @pxref{Double precision}).
1.26 crook 8552: @item
1.28 crook 8553: It always treats the double-precision number as though it were
8554: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8555: @item
8556: The string is built up from right to left; least significant digit first.
8557: @end itemize
1.5 anton 8558:
1.44 crook 8559:
1.26 crook 8560: doc-<#
1.47 crook 8561: doc-<<#
1.26 crook 8562: doc-#
8563: doc-#s
8564: doc-hold
8565: doc-sign
8566: doc-#>
1.47 crook 8567: doc-#>>
1.5 anton 8568:
1.26 crook 8569: doc-represent
1.111 anton 8570: doc-f>str-rdp
8571: doc-f>buf-rdp
1.5 anton 8572:
1.44 crook 8573:
8574: @noindent
1.26 crook 8575: Here are some examples of using pictured numeric output:
1.5 anton 8576:
8577: @example
1.26 crook 8578: : my-u. ( u -- )
8579: \ Simplest use of pns.. behaves like Standard u.
8580: 0 \ convert to unsigned double
1.75 anton 8581: <<# \ start conversion
1.26 crook 8582: #s \ convert all digits
8583: #> \ complete conversion
1.75 anton 8584: TYPE SPACE \ display, with trailing space
8585: #>> ; \ release hold area
1.5 anton 8586:
1.26 crook 8587: : cents-only ( u -- )
8588: 0 \ convert to unsigned double
1.75 anton 8589: <<# \ start conversion
1.26 crook 8590: # # \ convert two least-significant digits
8591: #> \ complete conversion, discard other digits
1.75 anton 8592: TYPE SPACE \ display, with trailing space
8593: #>> ; \ release hold area
1.5 anton 8594:
1.26 crook 8595: : dollars-and-cents ( u -- )
8596: 0 \ convert to unsigned double
1.75 anton 8597: <<# \ start conversion
1.26 crook 8598: # # \ convert two least-significant digits
8599: [char] . hold \ insert decimal point
8600: #s \ convert remaining digits
8601: [char] $ hold \ append currency symbol
8602: #> \ complete conversion
1.75 anton 8603: TYPE SPACE \ display, with trailing space
8604: #>> ; \ release hold area
1.5 anton 8605:
1.26 crook 8606: : my-. ( n -- )
8607: \ handling negatives.. behaves like Standard .
8608: s>d \ convert to signed double
8609: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8610: <<# \ start conversion
1.26 crook 8611: #s \ convert all digits
8612: rot sign \ get at sign byte, append "-" if needed
8613: #> \ complete conversion
1.75 anton 8614: TYPE SPACE \ display, with trailing space
8615: #>> ; \ release hold area
1.5 anton 8616:
1.26 crook 8617: : account. ( n -- )
1.75 anton 8618: \ accountants don't like minus signs, they use parentheses
1.26 crook 8619: \ for negative numbers
8620: s>d \ convert to signed double
8621: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8622: <<# \ start conversion
1.26 crook 8623: 2 pick \ get copy of sign byte
8624: 0< IF [char] ) hold THEN \ right-most character of output
8625: #s \ convert all digits
8626: rot \ get at sign byte
8627: 0< IF [char] ( hold THEN
8628: #> \ complete conversion
1.75 anton 8629: TYPE SPACE \ display, with trailing space
8630: #>> ; \ release hold area
8631:
1.5 anton 8632: @end example
8633:
1.26 crook 8634: Here are some examples of using these words:
1.5 anton 8635:
8636: @example
1.26 crook 8637: 1 my-u. 1
8638: hex -1 my-u. decimal FFFFFFFF
8639: 1 cents-only 01
8640: 1234 cents-only 34
8641: 2 dollars-and-cents $0.02
8642: 1234 dollars-and-cents $12.34
8643: 123 my-. 123
8644: -123 my. -123
8645: 123 account. 123
8646: -456 account. (456)
1.5 anton 8647: @end example
8648:
8649:
1.26 crook 8650: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8651: @subsection String Formats
1.27 crook 8652: @cindex strings - see character strings
8653: @cindex character strings - formats
1.28 crook 8654: @cindex I/O - see character strings
1.75 anton 8655: @cindex counted strings
8656:
8657: @c anton: this does not really belong here; maybe the memory section,
8658: @c or the principles chapter
1.26 crook 8659:
1.27 crook 8660: Forth commonly uses two different methods for representing character
8661: strings:
1.26 crook 8662:
8663: @itemize @bullet
8664: @item
8665: @cindex address of counted string
1.45 crook 8666: @cindex counted string
1.29 crook 8667: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8668: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8669: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8670: memory.
8671: @item
1.29 crook 8672: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8673: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8674: first byte of the string.
8675: @end itemize
8676:
8677: ANS Forth encourages the use of the second format when representing
1.75 anton 8678: strings.
1.26 crook 8679:
1.44 crook 8680:
1.26 crook 8681: doc-count
8682:
1.44 crook 8683:
1.49 anton 8684: For words that move, copy and search for strings see @ref{Memory
8685: Blocks}. For words that display characters and strings see
8686: @ref{Displaying characters and strings}.
1.26 crook 8687:
8688: @node Displaying characters and strings, Input, String Formats, Other I/O
8689: @subsection Displaying characters and strings
1.27 crook 8690: @cindex characters - compiling and displaying
8691: @cindex character strings - compiling and displaying
1.26 crook 8692:
8693: This section starts with a glossary of Forth words and ends with a set
8694: of examples.
8695:
1.44 crook 8696:
1.26 crook 8697: doc-bl
8698: doc-space
8699: doc-spaces
8700: doc-emit
8701: doc-toupper
8702: doc-."
8703: doc-.(
1.98 anton 8704: doc-.\"
1.26 crook 8705: doc-type
1.44 crook 8706: doc-typewhite
1.26 crook 8707: doc-cr
1.27 crook 8708: @cindex cursor control
1.26 crook 8709: doc-at-xy
8710: doc-page
8711: doc-s"
1.98 anton 8712: doc-s\"
1.26 crook 8713: doc-c"
8714: doc-char
8715: doc-[char]
8716:
1.44 crook 8717:
8718: @noindent
1.26 crook 8719: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8720:
8721: @example
1.26 crook 8722: .( text-1)
8723: : my-word
8724: ." text-2" cr
8725: .( text-3)
8726: ;
8727:
8728: ." text-4"
8729:
8730: : my-char
8731: [char] ALPHABET emit
8732: char emit
8733: ;
1.5 anton 8734: @end example
8735:
1.26 crook 8736: When you load this code into Gforth, the following output is generated:
1.5 anton 8737:
1.26 crook 8738: @example
1.30 anton 8739: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8740: @end example
1.5 anton 8741:
1.26 crook 8742: @itemize @bullet
8743: @item
8744: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8745: is an immediate word; it behaves in the same way whether it is used inside
8746: or outside a colon definition.
8747: @item
8748: Message @code{text-4} is displayed because of Gforth's added interpretation
8749: semantics for @code{."}.
8750: @item
1.29 crook 8751: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8752: performs the compilation semantics for @code{."} within the definition of
8753: @code{my-word}.
8754: @end itemize
1.5 anton 8755:
1.26 crook 8756: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8757:
1.26 crook 8758: @example
1.30 anton 8759: @kbd{my-word @key{RET}} text-2
1.26 crook 8760: ok
1.30 anton 8761: @kbd{my-char fred @key{RET}} Af ok
8762: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8763: @end example
1.5 anton 8764:
8765: @itemize @bullet
8766: @item
1.26 crook 8767: Message @code{text-2} is displayed because of the run-time behaviour of
8768: @code{."}.
8769: @item
8770: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8771: on the stack at run-time. @code{emit} always displays the character
8772: when @code{my-char} is executed.
8773: @item
8774: @code{char} parses a string at run-time and the second @code{emit} displays
8775: the first character of the string.
1.5 anton 8776: @item
1.26 crook 8777: If you type @code{see my-char} you can see that @code{[char]} discarded
8778: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8779: definition of @code{my-char}.
1.5 anton 8780: @end itemize
8781:
8782:
8783:
1.112 anton 8784: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8785: @subsection Input
8786: @cindex input
1.28 crook 8787: @cindex I/O - see input
8788: @cindex parsing a string
1.5 anton 8789:
1.49 anton 8790: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8791:
1.27 crook 8792: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8793: @comment then index them
1.27 crook 8794:
1.44 crook 8795:
1.27 crook 8796: doc-key
8797: doc-key?
1.45 crook 8798: doc-ekey
8799: doc-ekey?
8800: doc-ekey>char
1.26 crook 8801: doc->number
8802: doc->float
8803: doc-accept
1.109 anton 8804: doc-edit-line
1.27 crook 8805: doc-pad
8806: @comment obsolescent words..
8807: doc-convert
1.26 crook 8808: doc-expect
1.27 crook 8809: doc-span
1.5 anton 8810:
8811:
1.112 anton 8812: @node Pipes, , Input, Other I/O
8813: @subsection Pipes
8814: @cindex pipes, creating your own
8815:
8816: In addition to using Gforth in pipes created by other processes
8817: (@pxref{Gforth in pipes}), you can create your own pipe with
8818: @code{open-pipe}, and read from or write to it.
8819:
8820: doc-open-pipe
8821: doc-close-pipe
8822:
8823: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8824: you don't catch this exception, Gforth will catch it and exit, usually
8825: silently (@pxref{Gforth in pipes}). Since you probably do not want
8826: this, you should wrap a @code{catch} or @code{try} block around the code
8827: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
8828: problem yourself, and then return to regular processing.
8829:
8830: doc-broken-pipe-error
8831:
8832:
1.78 anton 8833: @c -------------------------------------------------------------
8834: @node Locals, Structures, Other I/O, Words
8835: @section Locals
8836: @cindex locals
8837:
8838: Local variables can make Forth programming more enjoyable and Forth
8839: programs easier to read. Unfortunately, the locals of ANS Forth are
8840: laden with restrictions. Therefore, we provide not only the ANS Forth
8841: locals wordset, but also our own, more powerful locals wordset (we
8842: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 8843:
1.78 anton 8844: The ideas in this section have also been published in M. Anton Ertl,
8845: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
8846: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 8847:
8848: @menu
1.78 anton 8849: * Gforth locals::
8850: * ANS Forth locals::
1.5 anton 8851: @end menu
8852:
1.78 anton 8853: @node Gforth locals, ANS Forth locals, Locals, Locals
8854: @subsection Gforth locals
8855: @cindex Gforth locals
8856: @cindex locals, Gforth style
1.5 anton 8857:
1.78 anton 8858: Locals can be defined with
1.44 crook 8859:
1.78 anton 8860: @example
8861: @{ local1 local2 ... -- comment @}
8862: @end example
8863: or
8864: @example
8865: @{ local1 local2 ... @}
8866: @end example
1.5 anton 8867:
1.78 anton 8868: E.g.,
8869: @example
8870: : max @{ n1 n2 -- n3 @}
8871: n1 n2 > if
8872: n1
8873: else
8874: n2
8875: endif ;
8876: @end example
1.44 crook 8877:
1.78 anton 8878: The similarity of locals definitions with stack comments is intended. A
8879: locals definition often replaces the stack comment of a word. The order
8880: of the locals corresponds to the order in a stack comment and everything
8881: after the @code{--} is really a comment.
1.77 anton 8882:
1.78 anton 8883: This similarity has one disadvantage: It is too easy to confuse locals
8884: declarations with stack comments, causing bugs and making them hard to
8885: find. However, this problem can be avoided by appropriate coding
8886: conventions: Do not use both notations in the same program. If you do,
8887: they should be distinguished using additional means, e.g. by position.
1.77 anton 8888:
1.78 anton 8889: @cindex types of locals
8890: @cindex locals types
8891: The name of the local may be preceded by a type specifier, e.g.,
8892: @code{F:} for a floating point value:
1.5 anton 8893:
1.78 anton 8894: @example
8895: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
8896: \ complex multiplication
8897: Ar Br f* Ai Bi f* f-
8898: Ar Bi f* Ai Br f* f+ ;
8899: @end example
1.44 crook 8900:
1.78 anton 8901: @cindex flavours of locals
8902: @cindex locals flavours
8903: @cindex value-flavoured locals
8904: @cindex variable-flavoured locals
8905: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
8906: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
8907: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
8908: with @code{W:}, @code{D:} etc.) produces its value and can be changed
8909: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
8910: produces its address (which becomes invalid when the variable's scope is
8911: left). E.g., the standard word @code{emit} can be defined in terms of
8912: @code{type} like this:
1.5 anton 8913:
1.78 anton 8914: @example
8915: : emit @{ C^ char* -- @}
8916: char* 1 type ;
8917: @end example
1.5 anton 8918:
1.78 anton 8919: @cindex default type of locals
8920: @cindex locals, default type
8921: A local without type specifier is a @code{W:} local. Both flavours of
8922: locals are initialized with values from the data or FP stack.
1.44 crook 8923:
1.78 anton 8924: Currently there is no way to define locals with user-defined data
8925: structures, but we are working on it.
1.5 anton 8926:
1.78 anton 8927: Gforth allows defining locals everywhere in a colon definition. This
8928: poses the following questions:
1.5 anton 8929:
1.78 anton 8930: @menu
8931: * Where are locals visible by name?::
8932: * How long do locals live?::
8933: * Locals programming style::
8934: * Locals implementation::
8935: @end menu
1.44 crook 8936:
1.78 anton 8937: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
8938: @subsubsection Where are locals visible by name?
8939: @cindex locals visibility
8940: @cindex visibility of locals
8941: @cindex scope of locals
1.5 anton 8942:
1.78 anton 8943: Basically, the answer is that locals are visible where you would expect
8944: it in block-structured languages, and sometimes a little longer. If you
8945: want to restrict the scope of a local, enclose its definition in
8946: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 8947:
8948:
1.78 anton 8949: doc-scope
8950: doc-endscope
1.5 anton 8951:
8952:
1.78 anton 8953: These words behave like control structure words, so you can use them
8954: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
8955: arbitrary ways.
1.77 anton 8956:
1.78 anton 8957: If you want a more exact answer to the visibility question, here's the
8958: basic principle: A local is visible in all places that can only be
8959: reached through the definition of the local@footnote{In compiler
8960: construction terminology, all places dominated by the definition of the
8961: local.}. In other words, it is not visible in places that can be reached
8962: without going through the definition of the local. E.g., locals defined
8963: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
8964: defined in @code{BEGIN}...@code{UNTIL} are visible after the
8965: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 8966:
1.78 anton 8967: The reasoning behind this solution is: We want to have the locals
8968: visible as long as it is meaningful. The user can always make the
8969: visibility shorter by using explicit scoping. In a place that can
8970: only be reached through the definition of a local, the meaning of a
8971: local name is clear. In other places it is not: How is the local
8972: initialized at the control flow path that does not contain the
8973: definition? Which local is meant, if the same name is defined twice in
8974: two independent control flow paths?
1.77 anton 8975:
1.78 anton 8976: This should be enough detail for nearly all users, so you can skip the
8977: rest of this section. If you really must know all the gory details and
8978: options, read on.
1.77 anton 8979:
1.78 anton 8980: In order to implement this rule, the compiler has to know which places
8981: are unreachable. It knows this automatically after @code{AHEAD},
8982: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
8983: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
8984: compiler that the control flow never reaches that place. If
8985: @code{UNREACHABLE} is not used where it could, the only consequence is
8986: that the visibility of some locals is more limited than the rule above
8987: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
8988: lie to the compiler), buggy code will be produced.
1.77 anton 8989:
1.5 anton 8990:
1.78 anton 8991: doc-unreachable
1.5 anton 8992:
1.23 crook 8993:
1.78 anton 8994: Another problem with this rule is that at @code{BEGIN}, the compiler
8995: does not know which locals will be visible on the incoming
8996: back-edge. All problems discussed in the following are due to this
8997: ignorance of the compiler (we discuss the problems using @code{BEGIN}
8998: loops as examples; the discussion also applies to @code{?DO} and other
8999: loops). Perhaps the most insidious example is:
1.26 crook 9000: @example
1.78 anton 9001: AHEAD
9002: BEGIN
9003: x
9004: [ 1 CS-ROLL ] THEN
9005: @{ x @}
9006: ...
9007: UNTIL
1.26 crook 9008: @end example
1.23 crook 9009:
1.78 anton 9010: This should be legal according to the visibility rule. The use of
9011: @code{x} can only be reached through the definition; but that appears
9012: textually below the use.
9013:
9014: From this example it is clear that the visibility rules cannot be fully
9015: implemented without major headaches. Our implementation treats common
9016: cases as advertised and the exceptions are treated in a safe way: The
9017: compiler makes a reasonable guess about the locals visible after a
9018: @code{BEGIN}; if it is too pessimistic, the
9019: user will get a spurious error about the local not being defined; if the
9020: compiler is too optimistic, it will notice this later and issue a
9021: warning. In the case above the compiler would complain about @code{x}
9022: being undefined at its use. You can see from the obscure examples in
9023: this section that it takes quite unusual control structures to get the
9024: compiler into trouble, and even then it will often do fine.
1.23 crook 9025:
1.78 anton 9026: If the @code{BEGIN} is reachable from above, the most optimistic guess
9027: is that all locals visible before the @code{BEGIN} will also be
9028: visible after the @code{BEGIN}. This guess is valid for all loops that
9029: are entered only through the @code{BEGIN}, in particular, for normal
9030: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9031: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9032: compiler. When the branch to the @code{BEGIN} is finally generated by
9033: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9034: warns the user if it was too optimistic:
1.26 crook 9035: @example
1.78 anton 9036: IF
9037: @{ x @}
9038: BEGIN
9039: \ x ?
9040: [ 1 cs-roll ] THEN
9041: ...
9042: UNTIL
1.26 crook 9043: @end example
1.23 crook 9044:
1.78 anton 9045: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9046: optimistically assumes that it lives until the @code{THEN}. It notices
9047: this difference when it compiles the @code{UNTIL} and issues a
9048: warning. The user can avoid the warning, and make sure that @code{x}
9049: is not used in the wrong area by using explicit scoping:
9050: @example
9051: IF
9052: SCOPE
9053: @{ x @}
9054: ENDSCOPE
9055: BEGIN
9056: [ 1 cs-roll ] THEN
9057: ...
9058: UNTIL
9059: @end example
1.23 crook 9060:
1.78 anton 9061: Since the guess is optimistic, there will be no spurious error messages
9062: about undefined locals.
1.44 crook 9063:
1.78 anton 9064: If the @code{BEGIN} is not reachable from above (e.g., after
9065: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9066: optimistic guess, as the locals visible after the @code{BEGIN} may be
9067: defined later. Therefore, the compiler assumes that no locals are
9068: visible after the @code{BEGIN}. However, the user can use
9069: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9070: visible at the BEGIN as at the point where the top control-flow stack
9071: item was created.
1.23 crook 9072:
1.44 crook 9073:
1.78 anton 9074: doc-assume-live
1.26 crook 9075:
1.23 crook 9076:
1.78 anton 9077: @noindent
9078: E.g.,
9079: @example
9080: @{ x @}
9081: AHEAD
9082: ASSUME-LIVE
9083: BEGIN
9084: x
9085: [ 1 CS-ROLL ] THEN
9086: ...
9087: UNTIL
9088: @end example
1.44 crook 9089:
1.78 anton 9090: Other cases where the locals are defined before the @code{BEGIN} can be
9091: handled by inserting an appropriate @code{CS-ROLL} before the
9092: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9093: behind the @code{ASSUME-LIVE}).
1.23 crook 9094:
1.78 anton 9095: Cases where locals are defined after the @code{BEGIN} (but should be
9096: visible immediately after the @code{BEGIN}) can only be handled by
9097: rearranging the loop. E.g., the ``most insidious'' example above can be
9098: arranged into:
9099: @example
9100: BEGIN
9101: @{ x @}
9102: ... 0=
9103: WHILE
9104: x
9105: REPEAT
9106: @end example
1.44 crook 9107:
1.78 anton 9108: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9109: @subsubsection How long do locals live?
9110: @cindex locals lifetime
9111: @cindex lifetime of locals
1.23 crook 9112:
1.78 anton 9113: The right answer for the lifetime question would be: A local lives at
9114: least as long as it can be accessed. For a value-flavoured local this
9115: means: until the end of its visibility. However, a variable-flavoured
9116: local could be accessed through its address far beyond its visibility
9117: scope. Ultimately, this would mean that such locals would have to be
9118: garbage collected. Since this entails un-Forth-like implementation
9119: complexities, I adopted the same cowardly solution as some other
9120: languages (e.g., C): The local lives only as long as it is visible;
9121: afterwards its address is invalid (and programs that access it
9122: afterwards are erroneous).
1.23 crook 9123:
1.78 anton 9124: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9125: @subsubsection Locals programming style
9126: @cindex locals programming style
9127: @cindex programming style, locals
1.23 crook 9128:
1.78 anton 9129: The freedom to define locals anywhere has the potential to change
9130: programming styles dramatically. In particular, the need to use the
9131: return stack for intermediate storage vanishes. Moreover, all stack
9132: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9133: determined arguments) can be eliminated: If the stack items are in the
9134: wrong order, just write a locals definition for all of them; then
9135: write the items in the order you want.
1.23 crook 9136:
1.78 anton 9137: This seems a little far-fetched and eliminating stack manipulations is
9138: unlikely to become a conscious programming objective. Still, the number
9139: of stack manipulations will be reduced dramatically if local variables
9140: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9141: a traditional implementation of @code{max}).
1.23 crook 9142:
1.78 anton 9143: This shows one potential benefit of locals: making Forth programs more
9144: readable. Of course, this benefit will only be realized if the
9145: programmers continue to honour the principle of factoring instead of
9146: using the added latitude to make the words longer.
1.23 crook 9147:
1.78 anton 9148: @cindex single-assignment style for locals
9149: Using @code{TO} can and should be avoided. Without @code{TO},
9150: every value-flavoured local has only a single assignment and many
9151: advantages of functional languages apply to Forth. I.e., programs are
9152: easier to analyse, to optimize and to read: It is clear from the
9153: definition what the local stands for, it does not turn into something
9154: different later.
1.23 crook 9155:
1.78 anton 9156: E.g., a definition using @code{TO} might look like this:
9157: @example
9158: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9159: u1 u2 min 0
9160: ?do
9161: addr1 c@@ addr2 c@@ -
9162: ?dup-if
9163: unloop exit
9164: then
9165: addr1 char+ TO addr1
9166: addr2 char+ TO addr2
9167: loop
9168: u1 u2 - ;
1.26 crook 9169: @end example
1.78 anton 9170: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9171: every loop iteration. @code{strcmp} is a typical example of the
9172: readability problems of using @code{TO}. When you start reading
9173: @code{strcmp}, you think that @code{addr1} refers to the start of the
9174: string. Only near the end of the loop you realize that it is something
9175: else.
1.23 crook 9176:
1.78 anton 9177: This can be avoided by defining two locals at the start of the loop that
9178: are initialized with the right value for the current iteration.
9179: @example
9180: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9181: addr1 addr2
9182: u1 u2 min 0
9183: ?do @{ s1 s2 @}
9184: s1 c@@ s2 c@@ -
9185: ?dup-if
9186: unloop exit
9187: then
9188: s1 char+ s2 char+
9189: loop
9190: 2drop
9191: u1 u2 - ;
9192: @end example
9193: Here it is clear from the start that @code{s1} has a different value
9194: in every loop iteration.
1.23 crook 9195:
1.78 anton 9196: @node Locals implementation, , Locals programming style, Gforth locals
9197: @subsubsection Locals implementation
9198: @cindex locals implementation
9199: @cindex implementation of locals
1.23 crook 9200:
1.78 anton 9201: @cindex locals stack
9202: Gforth uses an extra locals stack. The most compelling reason for
9203: this is that the return stack is not float-aligned; using an extra stack
9204: also eliminates the problems and restrictions of using the return stack
9205: as locals stack. Like the other stacks, the locals stack grows toward
9206: lower addresses. A few primitives allow an efficient implementation:
9207:
9208:
9209: doc-@local#
9210: doc-f@local#
9211: doc-laddr#
9212: doc-lp+!#
9213: doc-lp!
9214: doc->l
9215: doc-f>l
9216:
9217:
9218: In addition to these primitives, some specializations of these
9219: primitives for commonly occurring inline arguments are provided for
9220: efficiency reasons, e.g., @code{@@local0} as specialization of
9221: @code{@@local#} for the inline argument 0. The following compiling words
9222: compile the right specialized version, or the general version, as
9223: appropriate:
1.23 crook 9224:
1.5 anton 9225:
1.107 dvdkhlng 9226: @c doc-compile-@local
9227: @c doc-compile-f@local
1.78 anton 9228: doc-compile-lp+!
1.5 anton 9229:
9230:
1.78 anton 9231: Combinations of conditional branches and @code{lp+!#} like
9232: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9233: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9234:
1.78 anton 9235: A special area in the dictionary space is reserved for keeping the
9236: local variable names. @code{@{} switches the dictionary pointer to this
9237: area and @code{@}} switches it back and generates the locals
9238: initializing code. @code{W:} etc.@ are normal defining words. This
9239: special area is cleared at the start of every colon definition.
1.5 anton 9240:
1.78 anton 9241: @cindex word list for defining locals
9242: A special feature of Gforth's dictionary is used to implement the
9243: definition of locals without type specifiers: every word list (aka
9244: vocabulary) has its own methods for searching
9245: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9246: with a special search method: When it is searched for a word, it
9247: actually creates that word using @code{W:}. @code{@{} changes the search
9248: order to first search the word list containing @code{@}}, @code{W:} etc.,
9249: and then the word list for defining locals without type specifiers.
1.5 anton 9250:
1.78 anton 9251: The lifetime rules support a stack discipline within a colon
9252: definition: The lifetime of a local is either nested with other locals
9253: lifetimes or it does not overlap them.
1.23 crook 9254:
1.78 anton 9255: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9256: pointer manipulation is generated. Between control structure words
9257: locals definitions can push locals onto the locals stack. @code{AGAIN}
9258: is the simplest of the other three control flow words. It has to
9259: restore the locals stack depth of the corresponding @code{BEGIN}
9260: before branching. The code looks like this:
9261: @format
9262: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9263: @code{branch} <begin>
9264: @end format
1.26 crook 9265:
1.78 anton 9266: @code{UNTIL} is a little more complicated: If it branches back, it
9267: must adjust the stack just like @code{AGAIN}. But if it falls through,
9268: the locals stack must not be changed. The compiler generates the
9269: following code:
9270: @format
9271: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9272: @end format
9273: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9274:
1.78 anton 9275: @code{THEN} can produce somewhat inefficient code:
9276: @format
9277: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9278: <orig target>:
9279: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9280: @end format
9281: The second @code{lp+!#} adjusts the locals stack pointer from the
9282: level at the @i{orig} point to the level after the @code{THEN}. The
9283: first @code{lp+!#} adjusts the locals stack pointer from the current
9284: level to the level at the orig point, so the complete effect is an
9285: adjustment from the current level to the right level after the
9286: @code{THEN}.
1.26 crook 9287:
1.78 anton 9288: @cindex locals information on the control-flow stack
9289: @cindex control-flow stack items, locals information
9290: In a conventional Forth implementation a dest control-flow stack entry
9291: is just the target address and an orig entry is just the address to be
9292: patched. Our locals implementation adds a word list to every orig or dest
9293: item. It is the list of locals visible (or assumed visible) at the point
9294: described by the entry. Our implementation also adds a tag to identify
9295: the kind of entry, in particular to differentiate between live and dead
9296: (reachable and unreachable) orig entries.
1.26 crook 9297:
1.78 anton 9298: A few unusual operations have to be performed on locals word lists:
1.44 crook 9299:
1.5 anton 9300:
1.78 anton 9301: doc-common-list
9302: doc-sub-list?
9303: doc-list-size
1.52 anton 9304:
9305:
1.78 anton 9306: Several features of our locals word list implementation make these
9307: operations easy to implement: The locals word lists are organised as
9308: linked lists; the tails of these lists are shared, if the lists
9309: contain some of the same locals; and the address of a name is greater
9310: than the address of the names behind it in the list.
1.5 anton 9311:
1.78 anton 9312: Another important implementation detail is the variable
9313: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9314: determine if they can be reached directly or only through the branch
9315: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9316: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9317: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9318:
1.78 anton 9319: Counted loops are similar to other loops in most respects, but
9320: @code{LEAVE} requires special attention: It performs basically the same
9321: service as @code{AHEAD}, but it does not create a control-flow stack
9322: entry. Therefore the information has to be stored elsewhere;
9323: traditionally, the information was stored in the target fields of the
9324: branches created by the @code{LEAVE}s, by organizing these fields into a
9325: linked list. Unfortunately, this clever trick does not provide enough
9326: space for storing our extended control flow information. Therefore, we
9327: introduce another stack, the leave stack. It contains the control-flow
9328: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9329:
1.78 anton 9330: Local names are kept until the end of the colon definition, even if
9331: they are no longer visible in any control-flow path. In a few cases
9332: this may lead to increased space needs for the locals name area, but
9333: usually less than reclaiming this space would cost in code size.
1.5 anton 9334:
1.44 crook 9335:
1.78 anton 9336: @node ANS Forth locals, , Gforth locals, Locals
9337: @subsection ANS Forth locals
9338: @cindex locals, ANS Forth style
1.5 anton 9339:
1.78 anton 9340: The ANS Forth locals wordset does not define a syntax for locals, but
9341: words that make it possible to define various syntaxes. One of the
9342: possible syntaxes is a subset of the syntax we used in the Gforth locals
9343: wordset, i.e.:
1.29 crook 9344:
9345: @example
1.78 anton 9346: @{ local1 local2 ... -- comment @}
9347: @end example
9348: @noindent
9349: or
9350: @example
9351: @{ local1 local2 ... @}
1.29 crook 9352: @end example
9353:
1.78 anton 9354: The order of the locals corresponds to the order in a stack comment. The
9355: restrictions are:
1.5 anton 9356:
1.78 anton 9357: @itemize @bullet
9358: @item
9359: Locals can only be cell-sized values (no type specifiers are allowed).
9360: @item
9361: Locals can be defined only outside control structures.
9362: @item
9363: Locals can interfere with explicit usage of the return stack. For the
9364: exact (and long) rules, see the standard. If you don't use return stack
9365: accessing words in a definition using locals, you will be all right. The
9366: purpose of this rule is to make locals implementation on the return
9367: stack easier.
9368: @item
9369: The whole definition must be in one line.
9370: @end itemize
1.5 anton 9371:
1.78 anton 9372: Locals defined in ANS Forth behave like @code{VALUE}s
9373: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9374: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9375:
1.78 anton 9376: Since the syntax above is supported by Gforth directly, you need not do
9377: anything to use it. If you want to port a program using this syntax to
9378: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9379: syntax on the other system.
1.5 anton 9380:
1.78 anton 9381: Note that a syntax shown in the standard, section A.13 looks
9382: similar, but is quite different in having the order of locals
9383: reversed. Beware!
1.5 anton 9384:
1.78 anton 9385: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9386:
1.78 anton 9387: doc-(local)
1.5 anton 9388:
1.78 anton 9389: The ANS Forth locals extension wordset defines a syntax using
9390: @code{locals|}, but it is so awful that we strongly recommend not to use
9391: it. We have implemented this syntax to make porting to Gforth easy, but
9392: do not document it here. The problem with this syntax is that the locals
9393: are defined in an order reversed with respect to the standard stack
9394: comment notation, making programs harder to read, and easier to misread
9395: and miswrite. The only merit of this syntax is that it is easy to
9396: implement using the ANS Forth locals wordset.
1.53 anton 9397:
9398:
1.78 anton 9399: @c ----------------------------------------------------------
9400: @node Structures, Object-oriented Forth, Locals, Words
9401: @section Structures
9402: @cindex structures
9403: @cindex records
1.53 anton 9404:
1.78 anton 9405: This section presents the structure package that comes with Gforth. A
9406: version of the package implemented in ANS Forth is available in
9407: @file{compat/struct.fs}. This package was inspired by a posting on
9408: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9409: possibly John Hayes). A version of this section has been published in
9410: M. Anton Ertl,
9411: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9412: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9413: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9414:
1.78 anton 9415: @menu
9416: * Why explicit structure support?::
9417: * Structure Usage::
9418: * Structure Naming Convention::
9419: * Structure Implementation::
9420: * Structure Glossary::
9421: @end menu
1.55 anton 9422:
1.78 anton 9423: @node Why explicit structure support?, Structure Usage, Structures, Structures
9424: @subsection Why explicit structure support?
1.53 anton 9425:
1.78 anton 9426: @cindex address arithmetic for structures
9427: @cindex structures using address arithmetic
9428: If we want to use a structure containing several fields, we could simply
9429: reserve memory for it, and access the fields using address arithmetic
9430: (@pxref{Address arithmetic}). As an example, consider a structure with
9431: the following fields
1.57 anton 9432:
1.78 anton 9433: @table @code
9434: @item a
9435: is a float
9436: @item b
9437: is a cell
9438: @item c
9439: is a float
9440: @end table
1.57 anton 9441:
1.78 anton 9442: Given the (float-aligned) base address of the structure we get the
9443: address of the field
1.52 anton 9444:
1.78 anton 9445: @table @code
9446: @item a
9447: without doing anything further.
9448: @item b
9449: with @code{float+}
9450: @item c
9451: with @code{float+ cell+ faligned}
9452: @end table
1.52 anton 9453:
1.78 anton 9454: It is easy to see that this can become quite tiring.
1.52 anton 9455:
1.78 anton 9456: Moreover, it is not very readable, because seeing a
9457: @code{cell+} tells us neither which kind of structure is
9458: accessed nor what field is accessed; we have to somehow infer the kind
9459: of structure, and then look up in the documentation, which field of
9460: that structure corresponds to that offset.
1.53 anton 9461:
1.78 anton 9462: Finally, this kind of address arithmetic also causes maintenance
9463: troubles: If you add or delete a field somewhere in the middle of the
9464: structure, you have to find and change all computations for the fields
9465: afterwards.
1.52 anton 9466:
1.78 anton 9467: So, instead of using @code{cell+} and friends directly, how
9468: about storing the offsets in constants:
1.52 anton 9469:
1.78 anton 9470: @example
9471: 0 constant a-offset
9472: 0 float+ constant b-offset
9473: 0 float+ cell+ faligned c-offset
9474: @end example
1.64 pazsan 9475:
1.78 anton 9476: Now we can get the address of field @code{x} with @code{x-offset
9477: +}. This is much better in all respects. Of course, you still
9478: have to change all later offset definitions if you add a field. You can
9479: fix this by declaring the offsets in the following way:
1.57 anton 9480:
1.78 anton 9481: @example
9482: 0 constant a-offset
9483: a-offset float+ constant b-offset
9484: b-offset cell+ faligned constant c-offset
9485: @end example
1.57 anton 9486:
1.78 anton 9487: Since we always use the offsets with @code{+}, we could use a defining
9488: word @code{cfield} that includes the @code{+} in the action of the
9489: defined word:
1.64 pazsan 9490:
1.78 anton 9491: @example
9492: : cfield ( n "name" -- )
9493: create ,
9494: does> ( name execution: addr1 -- addr2 )
9495: @@ + ;
1.64 pazsan 9496:
1.78 anton 9497: 0 cfield a
9498: 0 a float+ cfield b
9499: 0 b cell+ faligned cfield c
9500: @end example
1.64 pazsan 9501:
1.78 anton 9502: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9503:
1.78 anton 9504: The structure field words now can be used quite nicely. However,
9505: their definition is still a bit cumbersome: We have to repeat the
9506: name, the information about size and alignment is distributed before
9507: and after the field definitions etc. The structure package presented
9508: here addresses these problems.
1.64 pazsan 9509:
1.78 anton 9510: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9511: @subsection Structure Usage
9512: @cindex structure usage
1.57 anton 9513:
1.78 anton 9514: @cindex @code{field} usage
9515: @cindex @code{struct} usage
9516: @cindex @code{end-struct} usage
9517: You can define a structure for a (data-less) linked list with:
1.57 anton 9518: @example
1.78 anton 9519: struct
9520: cell% field list-next
9521: end-struct list%
1.57 anton 9522: @end example
9523:
1.78 anton 9524: With the address of the list node on the stack, you can compute the
9525: address of the field that contains the address of the next node with
9526: @code{list-next}. E.g., you can determine the length of a list
9527: with:
1.57 anton 9528:
9529: @example
1.78 anton 9530: : list-length ( list -- n )
9531: \ "list" is a pointer to the first element of a linked list
9532: \ "n" is the length of the list
9533: 0 BEGIN ( list1 n1 )
9534: over
9535: WHILE ( list1 n1 )
9536: 1+ swap list-next @@ swap
9537: REPEAT
9538: nip ;
1.57 anton 9539: @end example
9540:
1.78 anton 9541: You can reserve memory for a list node in the dictionary with
9542: @code{list% %allot}, which leaves the address of the list node on the
9543: stack. For the equivalent allocation on the heap you can use @code{list%
9544: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9545: use @code{list% %allocate}). You can get the the size of a list
9546: node with @code{list% %size} and its alignment with @code{list%
9547: %alignment}.
9548:
9549: Note that in ANS Forth the body of a @code{create}d word is
9550: @code{aligned} but not necessarily @code{faligned};
9551: therefore, if you do a:
1.57 anton 9552:
9553: @example
1.78 anton 9554: create @emph{name} foo% %allot drop
1.57 anton 9555: @end example
9556:
1.78 anton 9557: @noindent
9558: then the memory alloted for @code{foo%} is guaranteed to start at the
9559: body of @code{@emph{name}} only if @code{foo%} contains only character,
9560: cell and double fields. Therefore, if your structure contains floats,
9561: better use
1.57 anton 9562:
9563: @example
1.78 anton 9564: foo% %allot constant @emph{name}
1.57 anton 9565: @end example
9566:
1.78 anton 9567: @cindex structures containing structures
9568: You can include a structure @code{foo%} as a field of
9569: another structure, like this:
1.65 anton 9570: @example
1.78 anton 9571: struct
9572: ...
9573: foo% field ...
9574: ...
9575: end-struct ...
1.65 anton 9576: @end example
1.52 anton 9577:
1.78 anton 9578: @cindex structure extension
9579: @cindex extended records
9580: Instead of starting with an empty structure, you can extend an
9581: existing structure. E.g., a plain linked list without data, as defined
9582: above, is hardly useful; You can extend it to a linked list of integers,
9583: like this:@footnote{This feature is also known as @emph{extended
9584: records}. It is the main innovation in the Oberon language; in other
9585: words, adding this feature to Modula-2 led Wirth to create a new
9586: language, write a new compiler etc. Adding this feature to Forth just
9587: required a few lines of code.}
1.52 anton 9588:
1.78 anton 9589: @example
9590: list%
9591: cell% field intlist-int
9592: end-struct intlist%
9593: @end example
1.55 anton 9594:
1.78 anton 9595: @code{intlist%} is a structure with two fields:
9596: @code{list-next} and @code{intlist-int}.
1.55 anton 9597:
1.78 anton 9598: @cindex structures containing arrays
9599: You can specify an array type containing @emph{n} elements of
9600: type @code{foo%} like this:
1.55 anton 9601:
9602: @example
1.78 anton 9603: foo% @emph{n} *
1.56 anton 9604: @end example
1.55 anton 9605:
1.78 anton 9606: You can use this array type in any place where you can use a normal
9607: type, e.g., when defining a @code{field}, or with
9608: @code{%allot}.
9609:
9610: @cindex first field optimization
9611: The first field is at the base address of a structure and the word for
9612: this field (e.g., @code{list-next}) actually does not change the address
9613: on the stack. You may be tempted to leave it away in the interest of
9614: run-time and space efficiency. This is not necessary, because the
9615: structure package optimizes this case: If you compile a first-field
9616: words, no code is generated. So, in the interest of readability and
9617: maintainability you should include the word for the field when accessing
9618: the field.
1.52 anton 9619:
9620:
1.78 anton 9621: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9622: @subsection Structure Naming Convention
9623: @cindex structure naming convention
1.52 anton 9624:
1.78 anton 9625: The field names that come to (my) mind are often quite generic, and,
9626: if used, would cause frequent name clashes. E.g., many structures
9627: probably contain a @code{counter} field. The structure names
9628: that come to (my) mind are often also the logical choice for the names
9629: of words that create such a structure.
1.52 anton 9630:
1.78 anton 9631: Therefore, I have adopted the following naming conventions:
1.52 anton 9632:
1.78 anton 9633: @itemize @bullet
9634: @cindex field naming convention
9635: @item
9636: The names of fields are of the form
9637: @code{@emph{struct}-@emph{field}}, where
9638: @code{@emph{struct}} is the basic name of the structure, and
9639: @code{@emph{field}} is the basic name of the field. You can
9640: think of field words as converting the (address of the)
9641: structure into the (address of the) field.
1.52 anton 9642:
1.78 anton 9643: @cindex structure naming convention
9644: @item
9645: The names of structures are of the form
9646: @code{@emph{struct}%}, where
9647: @code{@emph{struct}} is the basic name of the structure.
9648: @end itemize
1.52 anton 9649:
1.78 anton 9650: This naming convention does not work that well for fields of extended
9651: structures; e.g., the integer list structure has a field
9652: @code{intlist-int}, but has @code{list-next}, not
9653: @code{intlist-next}.
1.53 anton 9654:
1.78 anton 9655: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9656: @subsection Structure Implementation
9657: @cindex structure implementation
9658: @cindex implementation of structures
1.52 anton 9659:
1.78 anton 9660: The central idea in the implementation is to pass the data about the
9661: structure being built on the stack, not in some global
9662: variable. Everything else falls into place naturally once this design
9663: decision is made.
1.53 anton 9664:
1.78 anton 9665: The type description on the stack is of the form @emph{align
9666: size}. Keeping the size on the top-of-stack makes dealing with arrays
9667: very simple.
1.53 anton 9668:
1.78 anton 9669: @code{field} is a defining word that uses @code{Create}
9670: and @code{DOES>}. The body of the field contains the offset
9671: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9672:
9673: @example
1.78 anton 9674: @@ +
1.53 anton 9675: @end example
9676:
1.78 anton 9677: @noindent
9678: i.e., add the offset to the address, giving the stack effect
9679: @i{addr1 -- addr2} for a field.
9680:
9681: @cindex first field optimization, implementation
9682: This simple structure is slightly complicated by the optimization
9683: for fields with offset 0, which requires a different
9684: @code{DOES>}-part (because we cannot rely on there being
9685: something on the stack if such a field is invoked during
9686: compilation). Therefore, we put the different @code{DOES>}-parts
9687: in separate words, and decide which one to invoke based on the
9688: offset. For a zero offset, the field is basically a noop; it is
9689: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9690:
1.78 anton 9691: @node Structure Glossary, , Structure Implementation, Structures
9692: @subsection Structure Glossary
9693: @cindex structure glossary
1.53 anton 9694:
1.5 anton 9695:
1.78 anton 9696: doc-%align
9697: doc-%alignment
9698: doc-%alloc
9699: doc-%allocate
9700: doc-%allot
9701: doc-cell%
9702: doc-char%
9703: doc-dfloat%
9704: doc-double%
9705: doc-end-struct
9706: doc-field
9707: doc-float%
9708: doc-naligned
9709: doc-sfloat%
9710: doc-%size
9711: doc-struct
1.54 anton 9712:
9713:
1.26 crook 9714: @c -------------------------------------------------------------
1.78 anton 9715: @node Object-oriented Forth, Programming Tools, Structures, Words
9716: @section Object-oriented Forth
9717:
9718: Gforth comes with three packages for object-oriented programming:
9719: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9720: is preloaded, so you have to @code{include} them before use. The most
9721: important differences between these packages (and others) are discussed
9722: in @ref{Comparison with other object models}. All packages are written
9723: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9724:
1.78 anton 9725: @menu
9726: * Why object-oriented programming?::
9727: * Object-Oriented Terminology::
9728: * Objects::
9729: * OOF::
9730: * Mini-OOF::
9731: * Comparison with other object models::
9732: @end menu
1.5 anton 9733:
1.78 anton 9734: @c ----------------------------------------------------------------
9735: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9736: @subsection Why object-oriented programming?
9737: @cindex object-oriented programming motivation
9738: @cindex motivation for object-oriented programming
1.44 crook 9739:
1.78 anton 9740: Often we have to deal with several data structures (@emph{objects}),
9741: that have to be treated similarly in some respects, but differently in
9742: others. Graphical objects are the textbook example: circles, triangles,
9743: dinosaurs, icons, and others, and we may want to add more during program
9744: development. We want to apply some operations to any graphical object,
9745: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9746: has to do something different for every kind of object.
9747: @comment TODO add some other operations eg perimeter, area
9748: @comment and tie in to concrete examples later..
1.5 anton 9749:
1.78 anton 9750: We could implement @code{draw} as a big @code{CASE}
9751: control structure that executes the appropriate code depending on the
9752: kind of object to be drawn. This would be not be very elegant, and,
9753: moreover, we would have to change @code{draw} every time we add
9754: a new kind of graphical object (say, a spaceship).
1.44 crook 9755:
1.78 anton 9756: What we would rather do is: When defining spaceships, we would tell
9757: the system: ``Here's how you @code{draw} a spaceship; you figure
9758: out the rest''.
1.5 anton 9759:
1.78 anton 9760: This is the problem that all systems solve that (rightfully) call
9761: themselves object-oriented; the object-oriented packages presented here
9762: solve this problem (and not much else).
9763: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9764:
1.78 anton 9765: @c ------------------------------------------------------------------------
9766: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
9767: @subsection Object-Oriented Terminology
9768: @cindex object-oriented terminology
9769: @cindex terminology for object-oriented programming
1.5 anton 9770:
1.78 anton 9771: This section is mainly for reference, so you don't have to understand
9772: all of it right away. The terminology is mainly Smalltalk-inspired. In
9773: short:
1.44 crook 9774:
1.78 anton 9775: @table @emph
9776: @cindex class
9777: @item class
9778: a data structure definition with some extras.
1.5 anton 9779:
1.78 anton 9780: @cindex object
9781: @item object
9782: an instance of the data structure described by the class definition.
1.5 anton 9783:
1.78 anton 9784: @cindex instance variables
9785: @item instance variables
9786: fields of the data structure.
1.5 anton 9787:
1.78 anton 9788: @cindex selector
9789: @cindex method selector
9790: @cindex virtual function
9791: @item selector
9792: (or @emph{method selector}) a word (e.g.,
9793: @code{draw}) that performs an operation on a variety of data
9794: structures (classes). A selector describes @emph{what} operation to
9795: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 9796:
1.78 anton 9797: @cindex method
9798: @item method
9799: the concrete definition that performs the operation
9800: described by the selector for a specific class. A method specifies
9801: @emph{how} the operation is performed for a specific class.
1.5 anton 9802:
1.78 anton 9803: @cindex selector invocation
9804: @cindex message send
9805: @cindex invoking a selector
9806: @item selector invocation
9807: a call of a selector. One argument of the call (the TOS (top-of-stack))
9808: is used for determining which method is used. In Smalltalk terminology:
9809: a message (consisting of the selector and the other arguments) is sent
9810: to the object.
1.5 anton 9811:
1.78 anton 9812: @cindex receiving object
9813: @item receiving object
9814: the object used for determining the method executed by a selector
9815: invocation. In the @file{objects.fs} model, it is the object that is on
9816: the TOS when the selector is invoked. (@emph{Receiving} comes from
9817: the Smalltalk @emph{message} terminology.)
1.5 anton 9818:
1.78 anton 9819: @cindex child class
9820: @cindex parent class
9821: @cindex inheritance
9822: @item child class
9823: a class that has (@emph{inherits}) all properties (instance variables,
9824: selectors, methods) from a @emph{parent class}. In Smalltalk
9825: terminology: The subclass inherits from the superclass. In C++
9826: terminology: The derived class inherits from the base class.
1.5 anton 9827:
1.78 anton 9828: @end table
1.5 anton 9829:
1.78 anton 9830: @c If you wonder about the message sending terminology, it comes from
9831: @c a time when each object had it's own task and objects communicated via
9832: @c message passing; eventually the Smalltalk developers realized that
9833: @c they can do most things through simple (indirect) calls. They kept the
9834: @c terminology.
1.5 anton 9835:
1.78 anton 9836: @c --------------------------------------------------------------
9837: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
9838: @subsection The @file{objects.fs} model
9839: @cindex objects
9840: @cindex object-oriented programming
1.26 crook 9841:
1.78 anton 9842: @cindex @file{objects.fs}
9843: @cindex @file{oof.fs}
1.26 crook 9844:
1.78 anton 9845: This section describes the @file{objects.fs} package. This material also
9846: has been published in M. Anton Ertl,
9847: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
9848: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
9849: 37--43.
9850: @c McKewan's and Zsoter's packages
1.26 crook 9851:
1.78 anton 9852: This section assumes that you have read @ref{Structures}.
1.5 anton 9853:
1.78 anton 9854: The techniques on which this model is based have been used to implement
9855: the parser generator, Gray, and have also been used in Gforth for
9856: implementing the various flavours of word lists (hashed or not,
9857: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 9858:
9859:
1.26 crook 9860: @menu
1.78 anton 9861: * Properties of the Objects model::
9862: * Basic Objects Usage::
9863: * The Objects base class::
9864: * Creating objects::
9865: * Object-Oriented Programming Style::
9866: * Class Binding::
9867: * Method conveniences::
9868: * Classes and Scoping::
9869: * Dividing classes::
9870: * Object Interfaces::
9871: * Objects Implementation::
9872: * Objects Glossary::
1.26 crook 9873: @end menu
1.5 anton 9874:
1.78 anton 9875: Marcel Hendrix provided helpful comments on this section.
1.5 anton 9876:
1.78 anton 9877: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
9878: @subsubsection Properties of the @file{objects.fs} model
9879: @cindex @file{objects.fs} properties
1.5 anton 9880:
1.78 anton 9881: @itemize @bullet
9882: @item
9883: It is straightforward to pass objects on the stack. Passing
9884: selectors on the stack is a little less convenient, but possible.
1.44 crook 9885:
1.78 anton 9886: @item
9887: Objects are just data structures in memory, and are referenced by their
9888: address. You can create words for objects with normal defining words
9889: like @code{constant}. Likewise, there is no difference between instance
9890: variables that contain objects and those that contain other data.
1.5 anton 9891:
1.78 anton 9892: @item
9893: Late binding is efficient and easy to use.
1.44 crook 9894:
1.78 anton 9895: @item
9896: It avoids parsing, and thus avoids problems with state-smartness
9897: and reduced extensibility; for convenience there are a few parsing
9898: words, but they have non-parsing counterparts. There are also a few
9899: defining words that parse. This is hard to avoid, because all standard
9900: defining words parse (except @code{:noname}); however, such
9901: words are not as bad as many other parsing words, because they are not
9902: state-smart.
1.5 anton 9903:
1.78 anton 9904: @item
9905: It does not try to incorporate everything. It does a few things and does
9906: them well (IMO). In particular, this model was not designed to support
9907: information hiding (although it has features that may help); you can use
9908: a separate package for achieving this.
1.5 anton 9909:
1.78 anton 9910: @item
9911: It is layered; you don't have to learn and use all features to use this
9912: model. Only a few features are necessary (@pxref{Basic Objects Usage},
9913: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
9914: are optional and independent of each other.
1.5 anton 9915:
1.78 anton 9916: @item
9917: An implementation in ANS Forth is available.
1.5 anton 9918:
1.78 anton 9919: @end itemize
1.5 anton 9920:
1.44 crook 9921:
1.78 anton 9922: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
9923: @subsubsection Basic @file{objects.fs} Usage
9924: @cindex basic objects usage
9925: @cindex objects, basic usage
1.5 anton 9926:
1.78 anton 9927: You can define a class for graphical objects like this:
1.44 crook 9928:
1.78 anton 9929: @cindex @code{class} usage
9930: @cindex @code{end-class} usage
9931: @cindex @code{selector} usage
1.5 anton 9932: @example
1.78 anton 9933: object class \ "object" is the parent class
9934: selector draw ( x y graphical -- )
9935: end-class graphical
9936: @end example
9937:
9938: This code defines a class @code{graphical} with an
9939: operation @code{draw}. We can perform the operation
9940: @code{draw} on any @code{graphical} object, e.g.:
9941:
9942: @example
9943: 100 100 t-rex draw
1.26 crook 9944: @end example
1.5 anton 9945:
1.78 anton 9946: @noindent
9947: where @code{t-rex} is a word (say, a constant) that produces a
9948: graphical object.
9949:
9950: @comment TODO add a 2nd operation eg perimeter.. and use for
9951: @comment a concrete example
1.5 anton 9952:
1.78 anton 9953: @cindex abstract class
9954: How do we create a graphical object? With the present definitions,
9955: we cannot create a useful graphical object. The class
9956: @code{graphical} describes graphical objects in general, but not
9957: any concrete graphical object type (C++ users would call it an
9958: @emph{abstract class}); e.g., there is no method for the selector
9959: @code{draw} in the class @code{graphical}.
1.5 anton 9960:
1.78 anton 9961: For concrete graphical objects, we define child classes of the
9962: class @code{graphical}, e.g.:
1.5 anton 9963:
1.78 anton 9964: @cindex @code{overrides} usage
9965: @cindex @code{field} usage in class definition
1.26 crook 9966: @example
1.78 anton 9967: graphical class \ "graphical" is the parent class
9968: cell% field circle-radius
1.5 anton 9969:
1.78 anton 9970: :noname ( x y circle -- )
9971: circle-radius @@ draw-circle ;
9972: overrides draw
1.5 anton 9973:
1.78 anton 9974: :noname ( n-radius circle -- )
9975: circle-radius ! ;
9976: overrides construct
1.5 anton 9977:
1.78 anton 9978: end-class circle
9979: @end example
1.44 crook 9980:
1.78 anton 9981: Here we define a class @code{circle} as a child of @code{graphical},
9982: with field @code{circle-radius} (which behaves just like a field
9983: (@pxref{Structures}); it defines (using @code{overrides}) new methods
9984: for the selectors @code{draw} and @code{construct} (@code{construct} is
9985: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 9986:
1.78 anton 9987: Now we can create a circle on the heap (i.e.,
9988: @code{allocate}d memory) with:
1.44 crook 9989:
1.78 anton 9990: @cindex @code{heap-new} usage
1.5 anton 9991: @example
1.78 anton 9992: 50 circle heap-new constant my-circle
1.5 anton 9993: @end example
9994:
1.78 anton 9995: @noindent
9996: @code{heap-new} invokes @code{construct}, thus
9997: initializing the field @code{circle-radius} with 50. We can draw
9998: this new circle at (100,100) with:
1.5 anton 9999:
10000: @example
1.78 anton 10001: 100 100 my-circle draw
1.5 anton 10002: @end example
10003:
1.78 anton 10004: @cindex selector invocation, restrictions
10005: @cindex class definition, restrictions
10006: Note: You can only invoke a selector if the object on the TOS
10007: (the receiving object) belongs to the class where the selector was
10008: defined or one of its descendents; e.g., you can invoke
10009: @code{draw} only for objects belonging to @code{graphical}
10010: or its descendents (e.g., @code{circle}). Immediately before
10011: @code{end-class}, the search order has to be the same as
10012: immediately after @code{class}.
10013:
10014: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10015: @subsubsection The @file{object.fs} base class
10016: @cindex @code{object} class
10017:
10018: When you define a class, you have to specify a parent class. So how do
10019: you start defining classes? There is one class available from the start:
10020: @code{object}. It is ancestor for all classes and so is the
10021: only class that has no parent. It has two selectors: @code{construct}
10022: and @code{print}.
10023:
10024: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10025: @subsubsection Creating objects
10026: @cindex creating objects
10027: @cindex object creation
10028: @cindex object allocation options
10029:
10030: @cindex @code{heap-new} discussion
10031: @cindex @code{dict-new} discussion
10032: @cindex @code{construct} discussion
10033: You can create and initialize an object of a class on the heap with
10034: @code{heap-new} ( ... class -- object ) and in the dictionary
10035: (allocation with @code{allot}) with @code{dict-new} (
10036: ... class -- object ). Both words invoke @code{construct}, which
10037: consumes the stack items indicated by "..." above.
10038:
10039: @cindex @code{init-object} discussion
10040: @cindex @code{class-inst-size} discussion
10041: If you want to allocate memory for an object yourself, you can get its
10042: alignment and size with @code{class-inst-size 2@@} ( class --
10043: align size ). Once you have memory for an object, you can initialize
10044: it with @code{init-object} ( ... class object -- );
10045: @code{construct} does only a part of the necessary work.
10046:
10047: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10048: @subsubsection Object-Oriented Programming Style
10049: @cindex object-oriented programming style
10050: @cindex programming style, object-oriented
1.5 anton 10051:
1.78 anton 10052: This section is not exhaustive.
1.5 anton 10053:
1.78 anton 10054: @cindex stack effects of selectors
10055: @cindex selectors and stack effects
10056: In general, it is a good idea to ensure that all methods for the
10057: same selector have the same stack effect: when you invoke a selector,
10058: you often have no idea which method will be invoked, so, unless all
10059: methods have the same stack effect, you will not know the stack effect
10060: of the selector invocation.
1.5 anton 10061:
1.78 anton 10062: One exception to this rule is methods for the selector
10063: @code{construct}. We know which method is invoked, because we
10064: specify the class to be constructed at the same place. Actually, I
10065: defined @code{construct} as a selector only to give the users a
10066: convenient way to specify initialization. The way it is used, a
10067: mechanism different from selector invocation would be more natural
10068: (but probably would take more code and more space to explain).
1.5 anton 10069:
1.78 anton 10070: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10071: @subsubsection Class Binding
10072: @cindex class binding
10073: @cindex early binding
1.5 anton 10074:
1.78 anton 10075: @cindex late binding
10076: Normal selector invocations determine the method at run-time depending
10077: on the class of the receiving object. This run-time selection is called
10078: @i{late binding}.
1.5 anton 10079:
1.78 anton 10080: Sometimes it's preferable to invoke a different method. For example,
10081: you might want to use the simple method for @code{print}ing
10082: @code{object}s instead of the possibly long-winded @code{print} method
10083: of the receiver class. You can achieve this by replacing the invocation
10084: of @code{print} with:
1.5 anton 10085:
1.78 anton 10086: @cindex @code{[bind]} usage
1.5 anton 10087: @example
1.78 anton 10088: [bind] object print
1.5 anton 10089: @end example
10090:
1.78 anton 10091: @noindent
10092: in compiled code or:
10093:
10094: @cindex @code{bind} usage
1.5 anton 10095: @example
1.78 anton 10096: bind object print
1.5 anton 10097: @end example
10098:
1.78 anton 10099: @cindex class binding, alternative to
10100: @noindent
10101: in interpreted code. Alternatively, you can define the method with a
10102: name (e.g., @code{print-object}), and then invoke it through the
10103: name. Class binding is just a (often more convenient) way to achieve
10104: the same effect; it avoids name clutter and allows you to invoke
10105: methods directly without naming them first.
1.5 anton 10106:
1.78 anton 10107: @cindex superclass binding
10108: @cindex parent class binding
10109: A frequent use of class binding is this: When we define a method
10110: for a selector, we often want the method to do what the selector does
10111: in the parent class, and a little more. There is a special word for
10112: this purpose: @code{[parent]}; @code{[parent]
10113: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10114: selector}}, where @code{@emph{parent}} is the parent
10115: class of the current class. E.g., a method definition might look like:
1.44 crook 10116:
1.78 anton 10117: @cindex @code{[parent]} usage
10118: @example
10119: :noname
10120: dup [parent] foo \ do parent's foo on the receiving object
10121: ... \ do some more
10122: ; overrides foo
10123: @end example
1.6 pazsan 10124:
1.78 anton 10125: @cindex class binding as optimization
10126: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10127: March 1997), Andrew McKewan presents class binding as an optimization
10128: technique. I recommend not using it for this purpose unless you are in
10129: an emergency. Late binding is pretty fast with this model anyway, so the
10130: benefit of using class binding is small; the cost of using class binding
10131: where it is not appropriate is reduced maintainability.
1.44 crook 10132:
1.78 anton 10133: While we are at programming style questions: You should bind
10134: selectors only to ancestor classes of the receiving object. E.g., say,
10135: you know that the receiving object is of class @code{foo} or its
10136: descendents; then you should bind only to @code{foo} and its
10137: ancestors.
1.12 anton 10138:
1.78 anton 10139: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10140: @subsubsection Method conveniences
10141: @cindex method conveniences
1.44 crook 10142:
1.78 anton 10143: In a method you usually access the receiving object pretty often. If
10144: you define the method as a plain colon definition (e.g., with
10145: @code{:noname}), you may have to do a lot of stack
10146: gymnastics. To avoid this, you can define the method with @code{m:
10147: ... ;m}. E.g., you could define the method for
10148: @code{draw}ing a @code{circle} with
1.6 pazsan 10149:
1.78 anton 10150: @cindex @code{this} usage
10151: @cindex @code{m:} usage
10152: @cindex @code{;m} usage
10153: @example
10154: m: ( x y circle -- )
10155: ( x y ) this circle-radius @@ draw-circle ;m
10156: @end example
1.6 pazsan 10157:
1.78 anton 10158: @cindex @code{exit} in @code{m: ... ;m}
10159: @cindex @code{exitm} discussion
10160: @cindex @code{catch} in @code{m: ... ;m}
10161: When this method is executed, the receiver object is removed from the
10162: stack; you can access it with @code{this} (admittedly, in this
10163: example the use of @code{m: ... ;m} offers no advantage). Note
10164: that I specify the stack effect for the whole method (i.e. including
10165: the receiver object), not just for the code between @code{m:}
10166: and @code{;m}. You cannot use @code{exit} in
10167: @code{m:...;m}; instead, use
10168: @code{exitm}.@footnote{Moreover, for any word that calls
10169: @code{catch} and was defined before loading
10170: @code{objects.fs}, you have to redefine it like I redefined
10171: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10172:
1.78 anton 10173: @cindex @code{inst-var} usage
10174: You will frequently use sequences of the form @code{this
10175: @emph{field}} (in the example above: @code{this
10176: circle-radius}). If you use the field only in this way, you can
10177: define it with @code{inst-var} and eliminate the
10178: @code{this} before the field name. E.g., the @code{circle}
10179: class above could also be defined with:
1.6 pazsan 10180:
1.78 anton 10181: @example
10182: graphical class
10183: cell% inst-var radius
1.6 pazsan 10184:
1.78 anton 10185: m: ( x y circle -- )
10186: radius @@ draw-circle ;m
10187: overrides draw
1.6 pazsan 10188:
1.78 anton 10189: m: ( n-radius circle -- )
10190: radius ! ;m
10191: overrides construct
1.6 pazsan 10192:
1.78 anton 10193: end-class circle
10194: @end example
1.6 pazsan 10195:
1.78 anton 10196: @code{radius} can only be used in @code{circle} and its
10197: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10198:
1.78 anton 10199: @cindex @code{inst-value} usage
10200: You can also define fields with @code{inst-value}, which is
10201: to @code{inst-var} what @code{value} is to
10202: @code{variable}. You can change the value of such a field with
10203: @code{[to-inst]}. E.g., we could also define the class
10204: @code{circle} like this:
1.44 crook 10205:
1.78 anton 10206: @example
10207: graphical class
10208: inst-value radius
1.6 pazsan 10209:
1.78 anton 10210: m: ( x y circle -- )
10211: radius draw-circle ;m
10212: overrides draw
1.44 crook 10213:
1.78 anton 10214: m: ( n-radius circle -- )
10215: [to-inst] radius ;m
10216: overrides construct
1.6 pazsan 10217:
1.78 anton 10218: end-class circle
10219: @end example
1.6 pazsan 10220:
1.78 anton 10221: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10222:
1.78 anton 10223: @c Finally, you can define named methods with @code{:m}. One use of this
10224: @c feature is the definition of words that occur only in one class and are
10225: @c not intended to be overridden, but which still need method context
10226: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10227: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10228:
10229:
1.78 anton 10230: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10231: @subsubsection Classes and Scoping
10232: @cindex classes and scoping
10233: @cindex scoping and classes
1.6 pazsan 10234:
1.78 anton 10235: Inheritance is frequent, unlike structure extension. This exacerbates
10236: the problem with the field name convention (@pxref{Structure Naming
10237: Convention}): One always has to remember in which class the field was
10238: originally defined; changing a part of the class structure would require
10239: changes for renaming in otherwise unaffected code.
1.6 pazsan 10240:
1.78 anton 10241: @cindex @code{inst-var} visibility
10242: @cindex @code{inst-value} visibility
10243: To solve this problem, I added a scoping mechanism (which was not in my
10244: original charter): A field defined with @code{inst-var} (or
10245: @code{inst-value}) is visible only in the class where it is defined and in
10246: the descendent classes of this class. Using such fields only makes
10247: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10248:
1.78 anton 10249: This scoping mechanism allows us to use the unadorned field name,
10250: because name clashes with unrelated words become much less likely.
1.6 pazsan 10251:
1.78 anton 10252: @cindex @code{protected} discussion
10253: @cindex @code{private} discussion
10254: Once we have this mechanism, we can also use it for controlling the
10255: visibility of other words: All words defined after
10256: @code{protected} are visible only in the current class and its
10257: descendents. @code{public} restores the compilation
10258: (i.e. @code{current}) word list that was in effect before. If you
10259: have several @code{protected}s without an intervening
10260: @code{public} or @code{set-current}, @code{public}
10261: will restore the compilation word list in effect before the first of
10262: these @code{protected}s.
1.6 pazsan 10263:
1.78 anton 10264: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10265: @subsubsection Dividing classes
10266: @cindex Dividing classes
10267: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10268:
1.78 anton 10269: You may want to do the definition of methods separate from the
10270: definition of the class, its selectors, fields, and instance variables,
10271: i.e., separate the implementation from the definition. You can do this
10272: in the following way:
1.6 pazsan 10273:
1.78 anton 10274: @example
10275: graphical class
10276: inst-value radius
10277: end-class circle
1.6 pazsan 10278:
1.78 anton 10279: ... \ do some other stuff
1.6 pazsan 10280:
1.78 anton 10281: circle methods \ now we are ready
1.44 crook 10282:
1.78 anton 10283: m: ( x y circle -- )
10284: radius draw-circle ;m
10285: overrides draw
1.6 pazsan 10286:
1.78 anton 10287: m: ( n-radius circle -- )
10288: [to-inst] radius ;m
10289: overrides construct
1.44 crook 10290:
1.78 anton 10291: end-methods
10292: @end example
1.7 pazsan 10293:
1.78 anton 10294: You can use several @code{methods}...@code{end-methods} sections. The
10295: only things you can do to the class in these sections are: defining
10296: methods, and overriding the class's selectors. You must not define new
10297: selectors or fields.
1.7 pazsan 10298:
1.78 anton 10299: Note that you often have to override a selector before using it. In
10300: particular, you usually have to override @code{construct} with a new
10301: method before you can invoke @code{heap-new} and friends. E.g., you
10302: must not create a circle before the @code{overrides construct} sequence
10303: in the example above.
1.7 pazsan 10304:
1.78 anton 10305: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10306: @subsubsection Object Interfaces
10307: @cindex object interfaces
10308: @cindex interfaces for objects
1.7 pazsan 10309:
1.78 anton 10310: In this model you can only call selectors defined in the class of the
10311: receiving objects or in one of its ancestors. If you call a selector
10312: with a receiving object that is not in one of these classes, the
10313: result is undefined; if you are lucky, the program crashes
10314: immediately.
1.7 pazsan 10315:
1.78 anton 10316: @cindex selectors common to hardly-related classes
10317: Now consider the case when you want to have a selector (or several)
10318: available in two classes: You would have to add the selector to a
10319: common ancestor class, in the worst case to @code{object}. You
10320: may not want to do this, e.g., because someone else is responsible for
10321: this ancestor class.
1.7 pazsan 10322:
1.78 anton 10323: The solution for this problem is interfaces. An interface is a
10324: collection of selectors. If a class implements an interface, the
10325: selectors become available to the class and its descendents. A class
10326: can implement an unlimited number of interfaces. For the problem
10327: discussed above, we would define an interface for the selector(s), and
10328: both classes would implement the interface.
1.7 pazsan 10329:
1.78 anton 10330: As an example, consider an interface @code{storage} for
10331: writing objects to disk and getting them back, and a class
10332: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10333:
1.78 anton 10334: @cindex @code{interface} usage
10335: @cindex @code{end-interface} usage
10336: @cindex @code{implementation} usage
10337: @example
10338: interface
10339: selector write ( file object -- )
10340: selector read1 ( file object -- )
10341: end-interface storage
1.13 pazsan 10342:
1.78 anton 10343: bar class
10344: storage implementation
1.13 pazsan 10345:
1.78 anton 10346: ... overrides write
10347: ... overrides read1
10348: ...
10349: end-class foo
10350: @end example
1.13 pazsan 10351:
1.78 anton 10352: @noindent
10353: (I would add a word @code{read} @i{( file -- object )} that uses
10354: @code{read1} internally, but that's beyond the point illustrated
10355: here.)
1.13 pazsan 10356:
1.78 anton 10357: Note that you cannot use @code{protected} in an interface; and
10358: of course you cannot define fields.
1.13 pazsan 10359:
1.78 anton 10360: In the Neon model, all selectors are available for all classes;
10361: therefore it does not need interfaces. The price you pay in this model
10362: is slower late binding, and therefore, added complexity to avoid late
10363: binding.
1.13 pazsan 10364:
1.78 anton 10365: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10366: @subsubsection @file{objects.fs} Implementation
10367: @cindex @file{objects.fs} implementation
1.13 pazsan 10368:
1.78 anton 10369: @cindex @code{object-map} discussion
10370: An object is a piece of memory, like one of the data structures
10371: described with @code{struct...end-struct}. It has a field
10372: @code{object-map} that points to the method map for the object's
10373: class.
1.13 pazsan 10374:
1.78 anton 10375: @cindex method map
10376: @cindex virtual function table
10377: The @emph{method map}@footnote{This is Self terminology; in C++
10378: terminology: virtual function table.} is an array that contains the
10379: execution tokens (@i{xt}s) of the methods for the object's class. Each
10380: selector contains an offset into a method map.
1.13 pazsan 10381:
1.78 anton 10382: @cindex @code{selector} implementation, class
10383: @code{selector} is a defining word that uses
10384: @code{CREATE} and @code{DOES>}. The body of the
10385: selector contains the offset; the @code{DOES>} action for a
10386: class selector is, basically:
1.8 pazsan 10387:
10388: @example
1.78 anton 10389: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10390: @end example
10391:
1.78 anton 10392: Since @code{object-map} is the first field of the object, it
10393: does not generate any code. As you can see, calling a selector has a
10394: small, constant cost.
1.26 crook 10395:
1.78 anton 10396: @cindex @code{current-interface} discussion
10397: @cindex class implementation and representation
10398: A class is basically a @code{struct} combined with a method
10399: map. During the class definition the alignment and size of the class
10400: are passed on the stack, just as with @code{struct}s, so
10401: @code{field} can also be used for defining class
10402: fields. However, passing more items on the stack would be
10403: inconvenient, so @code{class} builds a data structure in memory,
10404: which is accessed through the variable
10405: @code{current-interface}. After its definition is complete, the
10406: class is represented on the stack by a pointer (e.g., as parameter for
10407: a child class definition).
1.26 crook 10408:
1.78 anton 10409: A new class starts off with the alignment and size of its parent,
10410: and a copy of the parent's method map. Defining new fields extends the
10411: size and alignment; likewise, defining new selectors extends the
10412: method map. @code{overrides} just stores a new @i{xt} in the method
10413: map at the offset given by the selector.
1.13 pazsan 10414:
1.78 anton 10415: @cindex class binding, implementation
10416: Class binding just gets the @i{xt} at the offset given by the selector
10417: from the class's method map and @code{compile,}s (in the case of
10418: @code{[bind]}) it.
1.13 pazsan 10419:
1.78 anton 10420: @cindex @code{this} implementation
10421: @cindex @code{catch} and @code{this}
10422: @cindex @code{this} and @code{catch}
10423: I implemented @code{this} as a @code{value}. At the
10424: start of an @code{m:...;m} method the old @code{this} is
10425: stored to the return stack and restored at the end; and the object on
10426: the TOS is stored @code{TO this}. This technique has one
10427: disadvantage: If the user does not leave the method via
10428: @code{;m}, but via @code{throw} or @code{exit},
10429: @code{this} is not restored (and @code{exit} may
10430: crash). To deal with the @code{throw} problem, I have redefined
10431: @code{catch} to save and restore @code{this}; the same
10432: should be done with any word that can catch an exception. As for
10433: @code{exit}, I simply forbid it (as a replacement, there is
10434: @code{exitm}).
1.13 pazsan 10435:
1.78 anton 10436: @cindex @code{inst-var} implementation
10437: @code{inst-var} is just the same as @code{field}, with
10438: a different @code{DOES>} action:
1.13 pazsan 10439: @example
1.78 anton 10440: @@ this +
1.8 pazsan 10441: @end example
1.78 anton 10442: Similar for @code{inst-value}.
1.8 pazsan 10443:
1.78 anton 10444: @cindex class scoping implementation
10445: Each class also has a word list that contains the words defined with
10446: @code{inst-var} and @code{inst-value}, and its protected
10447: words. It also has a pointer to its parent. @code{class} pushes
10448: the word lists of the class and all its ancestors onto the search order stack,
10449: and @code{end-class} drops them.
1.20 pazsan 10450:
1.78 anton 10451: @cindex interface implementation
10452: An interface is like a class without fields, parent and protected
10453: words; i.e., it just has a method map. If a class implements an
10454: interface, its method map contains a pointer to the method map of the
10455: interface. The positive offsets in the map are reserved for class
10456: methods, therefore interface map pointers have negative
10457: offsets. Interfaces have offsets that are unique throughout the
10458: system, unlike class selectors, whose offsets are only unique for the
10459: classes where the selector is available (invokable).
1.20 pazsan 10460:
1.78 anton 10461: This structure means that interface selectors have to perform one
10462: indirection more than class selectors to find their method. Their body
10463: contains the interface map pointer offset in the class method map, and
10464: the method offset in the interface method map. The
10465: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10466:
10467: @example
1.78 anton 10468: ( object selector-body )
10469: 2dup selector-interface @@ ( object selector-body object interface-offset )
10470: swap object-map @@ + @@ ( object selector-body map )
10471: swap selector-offset @@ + @@ execute
1.20 pazsan 10472: @end example
10473:
1.78 anton 10474: where @code{object-map} and @code{selector-offset} are
10475: first fields and generate no code.
1.20 pazsan 10476:
1.78 anton 10477: As a concrete example, consider the following code:
1.20 pazsan 10478:
10479: @example
1.78 anton 10480: interface
10481: selector if1sel1
10482: selector if1sel2
10483: end-interface if1
1.20 pazsan 10484:
1.78 anton 10485: object class
10486: if1 implementation
10487: selector cl1sel1
10488: cell% inst-var cl1iv1
1.20 pazsan 10489:
1.78 anton 10490: ' m1 overrides construct
10491: ' m2 overrides if1sel1
10492: ' m3 overrides if1sel2
10493: ' m4 overrides cl1sel2
10494: end-class cl1
1.20 pazsan 10495:
1.78 anton 10496: create obj1 object dict-new drop
10497: create obj2 cl1 dict-new drop
10498: @end example
1.20 pazsan 10499:
1.78 anton 10500: The data structure created by this code (including the data structure
10501: for @code{object}) is shown in the
10502: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10503: @comment TODO add this diagram..
1.20 pazsan 10504:
1.78 anton 10505: @node Objects Glossary, , Objects Implementation, Objects
10506: @subsubsection @file{objects.fs} Glossary
10507: @cindex @file{objects.fs} Glossary
1.20 pazsan 10508:
10509:
1.78 anton 10510: doc---objects-bind
10511: doc---objects-<bind>
10512: doc---objects-bind'
10513: doc---objects-[bind]
10514: doc---objects-class
10515: doc---objects-class->map
10516: doc---objects-class-inst-size
10517: doc---objects-class-override!
1.79 anton 10518: doc---objects-class-previous
10519: doc---objects-class>order
1.78 anton 10520: doc---objects-construct
10521: doc---objects-current'
10522: doc---objects-[current]
10523: doc---objects-current-interface
10524: doc---objects-dict-new
10525: doc---objects-end-class
10526: doc---objects-end-class-noname
10527: doc---objects-end-interface
10528: doc---objects-end-interface-noname
10529: doc---objects-end-methods
10530: doc---objects-exitm
10531: doc---objects-heap-new
10532: doc---objects-implementation
10533: doc---objects-init-object
10534: doc---objects-inst-value
10535: doc---objects-inst-var
10536: doc---objects-interface
10537: doc---objects-m:
10538: doc---objects-:m
10539: doc---objects-;m
10540: doc---objects-method
10541: doc---objects-methods
10542: doc---objects-object
10543: doc---objects-overrides
10544: doc---objects-[parent]
10545: doc---objects-print
10546: doc---objects-protected
10547: doc---objects-public
10548: doc---objects-selector
10549: doc---objects-this
10550: doc---objects-<to-inst>
10551: doc---objects-[to-inst]
10552: doc---objects-to-this
10553: doc---objects-xt-new
1.20 pazsan 10554:
10555:
1.78 anton 10556: @c -------------------------------------------------------------
10557: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10558: @subsection The @file{oof.fs} model
10559: @cindex oof
10560: @cindex object-oriented programming
1.20 pazsan 10561:
1.78 anton 10562: @cindex @file{objects.fs}
10563: @cindex @file{oof.fs}
1.20 pazsan 10564:
1.78 anton 10565: This section describes the @file{oof.fs} package.
1.20 pazsan 10566:
1.78 anton 10567: The package described in this section has been used in bigFORTH since 1991, and
10568: used for two large applications: a chromatographic system used to
10569: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10570:
1.78 anton 10571: You can find a description (in German) of @file{oof.fs} in @cite{Object
10572: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10573: 10(2), 1994.
1.20 pazsan 10574:
1.78 anton 10575: @menu
10576: * Properties of the OOF model::
10577: * Basic OOF Usage::
10578: * The OOF base class::
10579: * Class Declaration::
10580: * Class Implementation::
10581: @end menu
1.20 pazsan 10582:
1.78 anton 10583: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10584: @subsubsection Properties of the @file{oof.fs} model
10585: @cindex @file{oof.fs} properties
1.20 pazsan 10586:
1.78 anton 10587: @itemize @bullet
10588: @item
10589: This model combines object oriented programming with information
10590: hiding. It helps you writing large application, where scoping is
10591: necessary, because it provides class-oriented scoping.
1.20 pazsan 10592:
1.78 anton 10593: @item
10594: Named objects, object pointers, and object arrays can be created,
10595: selector invocation uses the ``object selector'' syntax. Selector invocation
10596: to objects and/or selectors on the stack is a bit less convenient, but
10597: possible.
1.44 crook 10598:
1.78 anton 10599: @item
10600: Selector invocation and instance variable usage of the active object is
10601: straightforward, since both make use of the active object.
1.44 crook 10602:
1.78 anton 10603: @item
10604: Late binding is efficient and easy to use.
1.20 pazsan 10605:
1.78 anton 10606: @item
10607: State-smart objects parse selectors. However, extensibility is provided
10608: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10609:
1.78 anton 10610: @item
10611: An implementation in ANS Forth is available.
1.20 pazsan 10612:
1.78 anton 10613: @end itemize
1.23 crook 10614:
10615:
1.78 anton 10616: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10617: @subsubsection Basic @file{oof.fs} Usage
10618: @cindex @file{oof.fs} usage
1.23 crook 10619:
1.78 anton 10620: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10621:
1.78 anton 10622: You can define a class for graphical objects like this:
1.23 crook 10623:
1.78 anton 10624: @cindex @code{class} usage
10625: @cindex @code{class;} usage
10626: @cindex @code{method} usage
10627: @example
10628: object class graphical \ "object" is the parent class
10629: method draw ( x y graphical -- )
10630: class;
10631: @end example
1.23 crook 10632:
1.78 anton 10633: This code defines a class @code{graphical} with an
10634: operation @code{draw}. We can perform the operation
10635: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10636:
1.78 anton 10637: @example
10638: 100 100 t-rex draw
10639: @end example
1.23 crook 10640:
1.78 anton 10641: @noindent
10642: where @code{t-rex} is an object or object pointer, created with e.g.
10643: @code{graphical : t-rex}.
1.23 crook 10644:
1.78 anton 10645: @cindex abstract class
10646: How do we create a graphical object? With the present definitions,
10647: we cannot create a useful graphical object. The class
10648: @code{graphical} describes graphical objects in general, but not
10649: any concrete graphical object type (C++ users would call it an
10650: @emph{abstract class}); e.g., there is no method for the selector
10651: @code{draw} in the class @code{graphical}.
1.23 crook 10652:
1.78 anton 10653: For concrete graphical objects, we define child classes of the
10654: class @code{graphical}, e.g.:
1.23 crook 10655:
1.78 anton 10656: @example
10657: graphical class circle \ "graphical" is the parent class
10658: cell var circle-radius
10659: how:
10660: : draw ( x y -- )
10661: circle-radius @@ draw-circle ;
1.23 crook 10662:
1.78 anton 10663: : init ( n-radius -- (
10664: circle-radius ! ;
10665: class;
10666: @end example
1.1 anton 10667:
1.78 anton 10668: Here we define a class @code{circle} as a child of @code{graphical},
10669: with a field @code{circle-radius}; it defines new methods for the
10670: selectors @code{draw} and @code{init} (@code{init} is defined in
10671: @code{object}, the parent class of @code{graphical}).
1.1 anton 10672:
1.78 anton 10673: Now we can create a circle in the dictionary with:
1.1 anton 10674:
1.78 anton 10675: @example
10676: 50 circle : my-circle
10677: @end example
1.21 crook 10678:
1.78 anton 10679: @noindent
10680: @code{:} invokes @code{init}, thus initializing the field
10681: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10682: with:
1.1 anton 10683:
1.78 anton 10684: @example
10685: 100 100 my-circle draw
10686: @end example
1.1 anton 10687:
1.78 anton 10688: @cindex selector invocation, restrictions
10689: @cindex class definition, restrictions
10690: Note: You can only invoke a selector if the receiving object belongs to
10691: the class where the selector was defined or one of its descendents;
10692: e.g., you can invoke @code{draw} only for objects belonging to
10693: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10694: mechanism will check if you try to invoke a selector that is not
10695: defined in this class hierarchy, so you'll get an error at compilation
10696: time.
1.1 anton 10697:
10698:
1.78 anton 10699: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10700: @subsubsection The @file{oof.fs} base class
10701: @cindex @file{oof.fs} base class
1.1 anton 10702:
1.78 anton 10703: When you define a class, you have to specify a parent class. So how do
10704: you start defining classes? There is one class available from the start:
10705: @code{object}. You have to use it as ancestor for all classes. It is the
10706: only class that has no parent. Classes are also objects, except that
10707: they don't have instance variables; class manipulation such as
10708: inheritance or changing definitions of a class is handled through
10709: selectors of the class @code{object}.
1.1 anton 10710:
1.78 anton 10711: @code{object} provides a number of selectors:
1.1 anton 10712:
1.78 anton 10713: @itemize @bullet
10714: @item
10715: @code{class} for subclassing, @code{definitions} to add definitions
10716: later on, and @code{class?} to get type informations (is the class a
10717: subclass of the class passed on the stack?).
1.1 anton 10718:
1.78 anton 10719: doc---object-class
10720: doc---object-definitions
10721: doc---object-class?
1.1 anton 10722:
10723:
1.26 crook 10724: @item
1.78 anton 10725: @code{init} and @code{dispose} as constructor and destructor of the
10726: object. @code{init} is invocated after the object's memory is allocated,
10727: while @code{dispose} also handles deallocation. Thus if you redefine
10728: @code{dispose}, you have to call the parent's dispose with @code{super
10729: dispose}, too.
10730:
10731: doc---object-init
10732: doc---object-dispose
10733:
1.1 anton 10734:
1.26 crook 10735: @item
1.78 anton 10736: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10737: @code{[]} to create named and unnamed objects and object arrays or
10738: object pointers.
10739:
10740: doc---object-new
10741: doc---object-new[]
10742: doc---object-:
10743: doc---object-ptr
10744: doc---object-asptr
10745: doc---object-[]
10746:
1.1 anton 10747:
1.26 crook 10748: @item
1.78 anton 10749: @code{::} and @code{super} for explicit scoping. You should use explicit
10750: scoping only for super classes or classes with the same set of instance
10751: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10752:
1.78 anton 10753: doc---object-::
10754: doc---object-super
1.21 crook 10755:
10756:
1.26 crook 10757: @item
1.78 anton 10758: @code{self} to get the address of the object
1.21 crook 10759:
1.78 anton 10760: doc---object-self
1.21 crook 10761:
10762:
1.78 anton 10763: @item
10764: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10765: pointers and instance defers.
1.21 crook 10766:
1.78 anton 10767: doc---object-bind
10768: doc---object-bound
10769: doc---object-link
10770: doc---object-is
1.21 crook 10771:
10772:
1.78 anton 10773: @item
10774: @code{'} to obtain selector tokens, @code{send} to invocate selectors
10775: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 10776:
1.78 anton 10777: doc---object-'
10778: doc---object-postpone
1.21 crook 10779:
10780:
1.78 anton 10781: @item
10782: @code{with} and @code{endwith} to select the active object from the
10783: stack, and enable its scope. Using @code{with} and @code{endwith}
10784: also allows you to create code using selector @code{postpone} without being
10785: trapped by the state-smart objects.
1.21 crook 10786:
1.78 anton 10787: doc---object-with
10788: doc---object-endwith
1.21 crook 10789:
10790:
1.78 anton 10791: @end itemize
1.21 crook 10792:
1.78 anton 10793: @node Class Declaration, Class Implementation, The OOF base class, OOF
10794: @subsubsection Class Declaration
10795: @cindex class declaration
1.21 crook 10796:
1.78 anton 10797: @itemize @bullet
10798: @item
10799: Instance variables
1.21 crook 10800:
1.78 anton 10801: doc---oof-var
1.21 crook 10802:
10803:
1.78 anton 10804: @item
10805: Object pointers
1.21 crook 10806:
1.78 anton 10807: doc---oof-ptr
10808: doc---oof-asptr
1.21 crook 10809:
10810:
1.78 anton 10811: @item
10812: Instance defers
1.21 crook 10813:
1.78 anton 10814: doc---oof-defer
1.21 crook 10815:
10816:
1.78 anton 10817: @item
10818: Method selectors
1.21 crook 10819:
1.78 anton 10820: doc---oof-early
10821: doc---oof-method
1.21 crook 10822:
10823:
1.78 anton 10824: @item
10825: Class-wide variables
1.21 crook 10826:
1.78 anton 10827: doc---oof-static
1.21 crook 10828:
10829:
1.78 anton 10830: @item
10831: End declaration
1.1 anton 10832:
1.78 anton 10833: doc---oof-how:
10834: doc---oof-class;
1.21 crook 10835:
10836:
1.78 anton 10837: @end itemize
1.21 crook 10838:
1.78 anton 10839: @c -------------------------------------------------------------
10840: @node Class Implementation, , Class Declaration, OOF
10841: @subsubsection Class Implementation
10842: @cindex class implementation
1.21 crook 10843:
1.78 anton 10844: @c -------------------------------------------------------------
10845: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
10846: @subsection The @file{mini-oof.fs} model
10847: @cindex mini-oof
1.21 crook 10848:
1.78 anton 10849: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 10850: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 10851: and reduces to the bare minimum of features. This is based on a posting
10852: of Bernd Paysan in comp.lang.forth.
1.21 crook 10853:
1.78 anton 10854: @menu
10855: * Basic Mini-OOF Usage::
10856: * Mini-OOF Example::
10857: * Mini-OOF Implementation::
10858: @end menu
1.21 crook 10859:
1.78 anton 10860: @c -------------------------------------------------------------
10861: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
10862: @subsubsection Basic @file{mini-oof.fs} Usage
10863: @cindex mini-oof usage
1.21 crook 10864:
1.78 anton 10865: There is a base class (@code{class}, which allocates one cell for the
10866: object pointer) plus seven other words: to define a method, a variable,
10867: a class; to end a class, to resolve binding, to allocate an object and
10868: to compile a class method.
10869: @comment TODO better description of the last one
1.26 crook 10870:
1.21 crook 10871:
1.78 anton 10872: doc-object
10873: doc-method
10874: doc-var
10875: doc-class
10876: doc-end-class
10877: doc-defines
10878: doc-new
10879: doc-::
1.21 crook 10880:
10881:
10882:
1.78 anton 10883: @c -------------------------------------------------------------
10884: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
10885: @subsubsection Mini-OOF Example
10886: @cindex mini-oof example
1.1 anton 10887:
1.78 anton 10888: A short example shows how to use this package. This example, in slightly
10889: extended form, is supplied as @file{moof-exm.fs}
10890: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 10891:
1.26 crook 10892: @example
1.78 anton 10893: object class
10894: method init
10895: method draw
10896: end-class graphical
1.26 crook 10897: @end example
1.20 pazsan 10898:
1.78 anton 10899: This code defines a class @code{graphical} with an
10900: operation @code{draw}. We can perform the operation
10901: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 10902:
1.26 crook 10903: @example
1.78 anton 10904: 100 100 t-rex draw
1.26 crook 10905: @end example
1.12 anton 10906:
1.78 anton 10907: where @code{t-rex} is an object or object pointer, created with e.g.
10908: @code{graphical new Constant t-rex}.
1.12 anton 10909:
1.78 anton 10910: For concrete graphical objects, we define child classes of the
10911: class @code{graphical}, e.g.:
1.12 anton 10912:
1.26 crook 10913: @example
10914: graphical class
1.78 anton 10915: cell var circle-radius
10916: end-class circle \ "graphical" is the parent class
1.12 anton 10917:
1.78 anton 10918: :noname ( x y -- )
10919: circle-radius @@ draw-circle ; circle defines draw
10920: :noname ( r -- )
10921: circle-radius ! ; circle defines init
10922: @end example
1.12 anton 10923:
1.78 anton 10924: There is no implicit init method, so we have to define one. The creation
10925: code of the object now has to call init explicitely.
1.21 crook 10926:
1.78 anton 10927: @example
10928: circle new Constant my-circle
10929: 50 my-circle init
1.12 anton 10930: @end example
10931:
1.78 anton 10932: It is also possible to add a function to create named objects with
10933: automatic call of @code{init}, given that all objects have @code{init}
10934: on the same place:
1.38 anton 10935:
1.78 anton 10936: @example
10937: : new: ( .. o "name" -- )
10938: new dup Constant init ;
10939: 80 circle new: large-circle
10940: @end example
1.12 anton 10941:
1.78 anton 10942: We can draw this new circle at (100,100) with:
1.12 anton 10943:
1.78 anton 10944: @example
10945: 100 100 my-circle draw
10946: @end example
1.12 anton 10947:
1.78 anton 10948: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
10949: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 10950:
1.78 anton 10951: Object-oriented systems with late binding typically use a
10952: ``vtable''-approach: the first variable in each object is a pointer to a
10953: table, which contains the methods as function pointers. The vtable
10954: may also contain other information.
1.12 anton 10955:
1.79 anton 10956: So first, let's declare selectors:
1.37 anton 10957:
10958: @example
1.79 anton 10959: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 10960: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
10961: @end example
1.37 anton 10962:
1.79 anton 10963: During selector declaration, the number of selectors and instance
10964: variables is on the stack (in address units). @code{method} creates one
10965: selector and increments the selector number. To execute a selector, it
1.78 anton 10966: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 10967: executes the method @i{xt} stored there. Each selector takes the object
10968: it is invoked with as top of stack parameter; it passes the parameters
10969: (including the object) unchanged to the appropriate method which should
1.78 anton 10970: consume that object.
1.37 anton 10971:
1.78 anton 10972: Now, we also have to declare instance variables
1.37 anton 10973:
1.78 anton 10974: @example
1.79 anton 10975: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 10976: DOES> ( o -- addr ) @@ + ;
1.37 anton 10977: @end example
10978:
1.78 anton 10979: As before, a word is created with the current offset. Instance
10980: variables can have different sizes (cells, floats, doubles, chars), so
10981: all we do is take the size and add it to the offset. If your machine
10982: has alignment restrictions, put the proper @code{aligned} or
10983: @code{faligned} before the variable, to adjust the variable
10984: offset. That's why it is on the top of stack.
1.37 anton 10985:
1.78 anton 10986: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 10987:
1.78 anton 10988: @example
10989: Create object 1 cells , 2 cells ,
1.79 anton 10990: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 10991: @end example
1.12 anton 10992:
1.78 anton 10993: For inheritance, the vtable of the parent object has to be
10994: copied when a new, derived class is declared. This gives all the
10995: methods of the parent class, which can be overridden, though.
1.12 anton 10996:
1.78 anton 10997: @example
1.79 anton 10998: : end-class ( class selectors vars "name" -- )
1.78 anton 10999: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11000: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11001: @end example
1.12 anton 11002:
1.78 anton 11003: The first line creates the vtable, initialized with
11004: @code{noop}s. The second line is the inheritance mechanism, it
11005: copies the xts from the parent vtable.
1.12 anton 11006:
1.78 anton 11007: We still have no way to define new methods, let's do that now:
1.12 anton 11008:
1.26 crook 11009: @example
1.79 anton 11010: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11011: @end example
1.12 anton 11012:
1.78 anton 11013: To allocate a new object, we need a word, too:
1.12 anton 11014:
1.78 anton 11015: @example
11016: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11017: @end example
11018:
1.78 anton 11019: Sometimes derived classes want to access the method of the
11020: parent object. There are two ways to achieve this with Mini-OOF:
11021: first, you could use named words, and second, you could look up the
11022: vtable of the parent object.
1.12 anton 11023:
1.78 anton 11024: @example
11025: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11026: @end example
1.12 anton 11027:
11028:
1.78 anton 11029: Nothing can be more confusing than a good example, so here is
11030: one. First let's declare a text object (called
11031: @code{button}), that stores text and position:
1.12 anton 11032:
1.78 anton 11033: @example
11034: object class
11035: cell var text
11036: cell var len
11037: cell var x
11038: cell var y
11039: method init
11040: method draw
11041: end-class button
11042: @end example
1.12 anton 11043:
1.78 anton 11044: @noindent
11045: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11046:
1.26 crook 11047: @example
1.78 anton 11048: :noname ( o -- )
11049: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11050: button defines draw
11051: :noname ( addr u o -- )
11052: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11053: button defines init
1.26 crook 11054: @end example
1.12 anton 11055:
1.78 anton 11056: @noindent
11057: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11058: new data and no new selectors:
1.78 anton 11059:
11060: @example
11061: button class
11062: end-class bold-button
1.12 anton 11063:
1.78 anton 11064: : bold 27 emit ." [1m" ;
11065: : normal 27 emit ." [0m" ;
11066: @end example
1.1 anton 11067:
1.78 anton 11068: @noindent
11069: The class @code{bold-button} has a different draw method to
11070: @code{button}, but the new method is defined in terms of the draw method
11071: for @code{button}:
1.20 pazsan 11072:
1.78 anton 11073: @example
11074: :noname bold [ button :: draw ] normal ; bold-button defines draw
11075: @end example
1.21 crook 11076:
1.78 anton 11077: @noindent
1.79 anton 11078: Finally, create two objects and apply selectors:
1.21 crook 11079:
1.26 crook 11080: @example
1.78 anton 11081: button new Constant foo
11082: s" thin foo" foo init
11083: page
11084: foo draw
11085: bold-button new Constant bar
11086: s" fat bar" bar init
11087: 1 bar y !
11088: bar draw
1.26 crook 11089: @end example
1.21 crook 11090:
11091:
1.78 anton 11092: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11093: @subsection Comparison with other object models
11094: @cindex comparison of object models
11095: @cindex object models, comparison
11096:
11097: Many object-oriented Forth extensions have been proposed (@cite{A survey
11098: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11099: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11100: relation of the object models described here to two well-known and two
11101: closely-related (by the use of method maps) models. Andras Zsoter
11102: helped us with this section.
11103:
11104: @cindex Neon model
11105: The most popular model currently seems to be the Neon model (see
11106: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11107: 1997) by Andrew McKewan) but this model has a number of limitations
11108: @footnote{A longer version of this critique can be
11109: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11110: Dimensions, May 1997) by Anton Ertl.}:
11111:
11112: @itemize @bullet
11113: @item
11114: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11115: to pass objects on the stack.
1.21 crook 11116:
1.78 anton 11117: @item
11118: It requires that the selector parses the input stream (at
1.79 anton 11119: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11120: hard to find.
1.21 crook 11121:
1.78 anton 11122: @item
1.79 anton 11123: It allows using every selector on every object; this eliminates the
11124: need for interfaces, but makes it harder to create efficient
11125: implementations.
1.78 anton 11126: @end itemize
1.21 crook 11127:
1.78 anton 11128: @cindex Pountain's object-oriented model
11129: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11130: Press, London, 1987) by Dick Pountain. However, it is not really about
11131: object-oriented programming, because it hardly deals with late
11132: binding. Instead, it focuses on features like information hiding and
11133: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11134:
1.78 anton 11135: @cindex Zsoter's object-oriented model
1.79 anton 11136: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11137: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11138: describes a model that makes heavy use of an active object (like
11139: @code{this} in @file{objects.fs}): The active object is not only used
11140: for accessing all fields, but also specifies the receiving object of
11141: every selector invocation; you have to change the active object
11142: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11143: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11144: the method entry point is unnecessary with Zsoter's model, because the
11145: receiving object is the active object already. On the other hand, the
11146: explicit change is absolutely necessary in that model, because otherwise
11147: no one could ever change the active object. An ANS Forth implementation
11148: of this model is available through
11149: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11150:
1.78 anton 11151: @cindex @file{oof.fs}, differences to other models
11152: The @file{oof.fs} model combines information hiding and overloading
11153: resolution (by keeping names in various word lists) with object-oriented
11154: programming. It sets the active object implicitly on method entry, but
11155: also allows explicit changing (with @code{>o...o>} or with
11156: @code{with...endwith}). It uses parsing and state-smart objects and
11157: classes for resolving overloading and for early binding: the object or
11158: class parses the selector and determines the method from this. If the
11159: selector is not parsed by an object or class, it performs a call to the
11160: selector for the active object (late binding), like Zsoter's model.
11161: Fields are always accessed through the active object. The big
11162: disadvantage of this model is the parsing and the state-smartness, which
11163: reduces extensibility and increases the opportunities for subtle bugs;
11164: essentially, you are only safe if you never tick or @code{postpone} an
11165: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11166:
1.78 anton 11167: @cindex @file{mini-oof.fs}, differences to other models
11168: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11169: version of the @file{objects.fs} model, but syntactically it is a
11170: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11171:
11172:
1.78 anton 11173: @c -------------------------------------------------------------
11174: @node Programming Tools, Assembler and Code Words, Object-oriented Forth, Words
11175: @section Programming Tools
11176: @cindex programming tools
1.21 crook 11177:
1.78 anton 11178: @c !! move this and assembler down below OO stuff.
1.21 crook 11179:
1.78 anton 11180: @menu
11181: * Examining::
11182: * Forgetting words::
11183: * Debugging:: Simple and quick.
11184: * Assertions:: Making your programs self-checking.
11185: * Singlestep Debugger:: Executing your program word by word.
11186: @end menu
1.21 crook 11187:
1.78 anton 11188: @node Examining, Forgetting words, Programming Tools, Programming Tools
11189: @subsection Examining data and code
11190: @cindex examining data and code
11191: @cindex data examination
11192: @cindex code examination
1.44 crook 11193:
1.78 anton 11194: The following words inspect the stack non-destructively:
1.21 crook 11195:
1.78 anton 11196: doc-.s
11197: doc-f.s
1.44 crook 11198:
1.78 anton 11199: There is a word @code{.r} but it does @i{not} display the return stack!
11200: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11201:
1.78 anton 11202: doc-depth
11203: doc-fdepth
11204: doc-clearstack
1.21 crook 11205:
1.78 anton 11206: The following words inspect memory.
1.21 crook 11207:
1.78 anton 11208: doc-?
11209: doc-dump
1.21 crook 11210:
1.78 anton 11211: And finally, @code{see} allows to inspect code:
1.21 crook 11212:
1.78 anton 11213: doc-see
11214: doc-xt-see
1.111 anton 11215: doc-simple-see
11216: doc-simple-see-range
1.21 crook 11217:
1.78 anton 11218: @node Forgetting words, Debugging, Examining, Programming Tools
11219: @subsection Forgetting words
11220: @cindex words, forgetting
11221: @cindex forgeting words
1.21 crook 11222:
1.78 anton 11223: @c anton: other, maybe better places for this subsection: Defining Words;
11224: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11225:
1.78 anton 11226: Forth allows you to forget words (and everything that was alloted in the
11227: dictonary after them) in a LIFO manner.
1.21 crook 11228:
1.78 anton 11229: doc-marker
1.21 crook 11230:
1.78 anton 11231: The most common use of this feature is during progam development: when
11232: you change a source file, forget all the words it defined and load it
11233: again (since you also forget everything defined after the source file
11234: was loaded, you have to reload that, too). Note that effects like
11235: storing to variables and destroyed system words are not undone when you
11236: forget words. With a system like Gforth, that is fast enough at
11237: starting up and compiling, I find it more convenient to exit and restart
11238: Gforth, as this gives me a clean slate.
1.21 crook 11239:
1.78 anton 11240: Here's an example of using @code{marker} at the start of a source file
11241: that you are debugging; it ensures that you only ever have one copy of
11242: the file's definitions compiled at any time:
1.21 crook 11243:
1.78 anton 11244: @example
11245: [IFDEF] my-code
11246: my-code
11247: [ENDIF]
1.26 crook 11248:
1.78 anton 11249: marker my-code
11250: init-included-files
1.21 crook 11251:
1.78 anton 11252: \ .. definitions start here
11253: \ .
11254: \ .
11255: \ end
11256: @end example
1.21 crook 11257:
1.26 crook 11258:
1.78 anton 11259: @node Debugging, Assertions, Forgetting words, Programming Tools
11260: @subsection Debugging
11261: @cindex debugging
1.21 crook 11262:
1.78 anton 11263: Languages with a slow edit/compile/link/test development loop tend to
11264: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11265:
1.78 anton 11266: A much better (faster) way in fast-compiling languages is to add
11267: printing code at well-selected places, let the program run, look at
11268: the output, see where things went wrong, add more printing code, etc.,
11269: until the bug is found.
1.21 crook 11270:
1.78 anton 11271: The simple debugging aids provided in @file{debugs.fs}
11272: are meant to support this style of debugging.
1.21 crook 11273:
1.78 anton 11274: The word @code{~~} prints debugging information (by default the source
11275: location and the stack contents). It is easy to insert. If you use Emacs
11276: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11277: query-replace them with nothing). The deferred words
1.101 anton 11278: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11279: @code{~~}. The default source location output format works well with
11280: Emacs' compilation mode, so you can step through the program at the
11281: source level using @kbd{C-x `} (the advantage over a stepping debugger
11282: is that you can step in any direction and you know where the crash has
11283: happened or where the strange data has occurred).
1.21 crook 11284:
1.78 anton 11285: doc-~~
11286: doc-printdebugdata
1.101 anton 11287: doc-.debugline
1.21 crook 11288:
1.106 anton 11289: @cindex filenames in @code{~~} output
11290: @code{~~} (and assertions) will usually print the wrong file name if a
11291: marker is executed in the same file after their occurance. They will
11292: print @samp{*somewhere*} as file name if a marker is executed in the
11293: same file before their occurance.
11294:
11295:
1.78 anton 11296: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11297: @subsection Assertions
11298: @cindex assertions
1.21 crook 11299:
1.78 anton 11300: It is a good idea to make your programs self-checking, especially if you
11301: make an assumption that may become invalid during maintenance (for
11302: example, that a certain field of a data structure is never zero). Gforth
11303: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11304:
11305: @example
1.78 anton 11306: assert( @i{flag} )
1.26 crook 11307: @end example
11308:
1.78 anton 11309: The code between @code{assert(} and @code{)} should compute a flag, that
11310: should be true if everything is alright and false otherwise. It should
11311: not change anything else on the stack. The overall stack effect of the
11312: assertion is @code{( -- )}. E.g.
1.21 crook 11313:
1.26 crook 11314: @example
1.78 anton 11315: assert( 1 1 + 2 = ) \ what we learn in school
11316: assert( dup 0<> ) \ assert that the top of stack is not zero
11317: assert( false ) \ this code should not be reached
1.21 crook 11318: @end example
11319:
1.78 anton 11320: The need for assertions is different at different times. During
11321: debugging, we want more checking, in production we sometimes care more
11322: for speed. Therefore, assertions can be turned off, i.e., the assertion
11323: becomes a comment. Depending on the importance of an assertion and the
11324: time it takes to check it, you may want to turn off some assertions and
11325: keep others turned on. Gforth provides several levels of assertions for
11326: this purpose:
11327:
11328:
11329: doc-assert0(
11330: doc-assert1(
11331: doc-assert2(
11332: doc-assert3(
11333: doc-assert(
11334: doc-)
1.21 crook 11335:
11336:
1.78 anton 11337: The variable @code{assert-level} specifies the highest assertions that
11338: are turned on. I.e., at the default @code{assert-level} of one,
11339: @code{assert0(} and @code{assert1(} assertions perform checking, while
11340: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11341:
1.78 anton 11342: The value of @code{assert-level} is evaluated at compile-time, not at
11343: run-time. Therefore you cannot turn assertions on or off at run-time;
11344: you have to set the @code{assert-level} appropriately before compiling a
11345: piece of code. You can compile different pieces of code at different
11346: @code{assert-level}s (e.g., a trusted library at level 1 and
11347: newly-written code at level 3).
1.26 crook 11348:
11349:
1.78 anton 11350: doc-assert-level
1.26 crook 11351:
11352:
1.78 anton 11353: If an assertion fails, a message compatible with Emacs' compilation mode
11354: is produced and the execution is aborted (currently with @code{ABORT"}.
11355: If there is interest, we will introduce a special throw code. But if you
11356: intend to @code{catch} a specific condition, using @code{throw} is
11357: probably more appropriate than an assertion).
1.106 anton 11358:
11359: @cindex filenames in assertion output
11360: Assertions (and @code{~~}) will usually print the wrong file name if a
11361: marker is executed in the same file after their occurance. They will
11362: print @samp{*somewhere*} as file name if a marker is executed in the
11363: same file before their occurance.
1.44 crook 11364:
1.78 anton 11365: Definitions in ANS Forth for these assertion words are provided
11366: in @file{compat/assert.fs}.
1.26 crook 11367:
1.44 crook 11368:
1.78 anton 11369: @node Singlestep Debugger, , Assertions, Programming Tools
11370: @subsection Singlestep Debugger
11371: @cindex singlestep Debugger
11372: @cindex debugging Singlestep
1.44 crook 11373:
1.112 anton 11374: The singlestep debugger does not work in this release.
11375:
1.78 anton 11376: When you create a new word there's often the need to check whether it
11377: behaves correctly or not. You can do this by typing @code{dbg
11378: badword}. A debug session might look like this:
1.26 crook 11379:
1.78 anton 11380: @example
11381: : badword 0 DO i . LOOP ; ok
11382: 2 dbg badword
11383: : badword
11384: Scanning code...
1.44 crook 11385:
1.78 anton 11386: Nesting debugger ready!
1.44 crook 11387:
1.78 anton 11388: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11389: 400D4740 8049F68 DO -> [ 0 ]
11390: 400D4744 804A0C8 i -> [ 1 ] 00000
11391: 400D4748 400C5E60 . -> 0 [ 0 ]
11392: 400D474C 8049D0C LOOP -> [ 0 ]
11393: 400D4744 804A0C8 i -> [ 1 ] 00001
11394: 400D4748 400C5E60 . -> 1 [ 0 ]
11395: 400D474C 8049D0C LOOP -> [ 0 ]
11396: 400D4758 804B384 ; -> ok
11397: @end example
1.21 crook 11398:
1.78 anton 11399: Each line displayed is one step. You always have to hit return to
11400: execute the next word that is displayed. If you don't want to execute
11401: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11402: an overview what keys are available:
1.44 crook 11403:
1.78 anton 11404: @table @i
1.44 crook 11405:
1.78 anton 11406: @item @key{RET}
11407: Next; Execute the next word.
1.21 crook 11408:
1.78 anton 11409: @item n
11410: Nest; Single step through next word.
1.44 crook 11411:
1.78 anton 11412: @item u
11413: Unnest; Stop debugging and execute rest of word. If we got to this word
11414: with nest, continue debugging with the calling word.
1.44 crook 11415:
1.78 anton 11416: @item d
11417: Done; Stop debugging and execute rest.
1.21 crook 11418:
1.78 anton 11419: @item s
11420: Stop; Abort immediately.
1.44 crook 11421:
1.78 anton 11422: @end table
1.44 crook 11423:
1.78 anton 11424: Debugging large application with this mechanism is very difficult, because
11425: you have to nest very deeply into the program before the interesting part
11426: begins. This takes a lot of time.
1.26 crook 11427:
1.78 anton 11428: To do it more directly put a @code{BREAK:} command into your source code.
11429: When program execution reaches @code{BREAK:} the single step debugger is
11430: invoked and you have all the features described above.
1.44 crook 11431:
1.78 anton 11432: If you have more than one part to debug it is useful to know where the
11433: program has stopped at the moment. You can do this by the
11434: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11435: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11436:
1.26 crook 11437:
1.78 anton 11438: doc-dbg
11439: doc-break:
11440: doc-break"
1.44 crook 11441:
11442:
1.26 crook 11443:
1.78 anton 11444: @c -------------------------------------------------------------
11445: @node Assembler and Code Words, Threading Words, Programming Tools, Words
11446: @section Assembler and Code Words
11447: @cindex assembler
11448: @cindex code words
1.44 crook 11449:
1.78 anton 11450: @menu
11451: * Code and ;code::
11452: * Common Assembler:: Assembler Syntax
11453: * Common Disassembler::
11454: * 386 Assembler:: Deviations and special cases
11455: * Alpha Assembler:: Deviations and special cases
11456: * MIPS assembler:: Deviations and special cases
11457: * Other assemblers:: How to write them
11458: @end menu
1.21 crook 11459:
1.78 anton 11460: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11461: @subsection @code{Code} and @code{;code}
1.26 crook 11462:
1.78 anton 11463: Gforth provides some words for defining primitives (words written in
11464: machine code), and for defining the machine-code equivalent of
11465: @code{DOES>}-based defining words. However, the machine-independent
11466: nature of Gforth poses a few problems: First of all, Gforth runs on
11467: several architectures, so it can provide no standard assembler. What's
11468: worse is that the register allocation not only depends on the processor,
11469: but also on the @code{gcc} version and options used.
1.44 crook 11470:
1.78 anton 11471: The words that Gforth offers encapsulate some system dependences (e.g.,
11472: the header structure), so a system-independent assembler may be used in
11473: Gforth. If you do not have an assembler, you can compile machine code
11474: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11475: because these words emit stuff in @i{data} space; it works because
11476: Gforth has unified code/data spaces. Assembler isn't likely to be
11477: portable anyway.}.
1.21 crook 11478:
1.44 crook 11479:
1.78 anton 11480: doc-assembler
11481: doc-init-asm
11482: doc-code
11483: doc-end-code
11484: doc-;code
11485: doc-flush-icache
1.44 crook 11486:
1.21 crook 11487:
1.78 anton 11488: If @code{flush-icache} does not work correctly, @code{code} words
11489: etc. will not work (reliably), either.
1.44 crook 11490:
1.78 anton 11491: The typical usage of these @code{code} words can be shown most easily by
11492: analogy to the equivalent high-level defining words:
1.44 crook 11493:
1.78 anton 11494: @example
11495: : foo code foo
11496: <high-level Forth words> <assembler>
11497: ; end-code
11498:
11499: : bar : bar
11500: <high-level Forth words> <high-level Forth words>
11501: CREATE CREATE
11502: <high-level Forth words> <high-level Forth words>
11503: DOES> ;code
11504: <high-level Forth words> <assembler>
11505: ; end-code
11506: @end example
1.21 crook 11507:
1.78 anton 11508: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11509:
1.78 anton 11510: @cindex registers of the inner interpreter
11511: In the assembly code you will want to refer to the inner interpreter's
11512: registers (e.g., the data stack pointer) and you may want to use other
11513: registers for temporary storage. Unfortunately, the register allocation
11514: is installation-dependent.
1.44 crook 11515:
1.78 anton 11516: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11517: (return stack pointer) may be in different places in @code{gforth} and
11518: @code{gforth-fast}, or different installations. This means that you
11519: cannot write a @code{NEXT} routine that works reliably on both versions
11520: or different installations; so for doing @code{NEXT}, I recommend
11521: jumping to @code{' noop >code-address}, which contains nothing but a
11522: @code{NEXT}.
1.21 crook 11523:
1.78 anton 11524: For general accesses to the inner interpreter's registers, the easiest
11525: solution is to use explicit register declarations (@pxref{Explicit Reg
11526: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11527: all of the inner interpreter's registers: You have to compile Gforth
11528: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11529: the appropriate declarations must be present in the @code{machine.h}
11530: file (see @code{mips.h} for an example; you can find a full list of all
11531: declarable register symbols with @code{grep register engine.c}). If you
11532: give explicit registers to all variables that are declared at the
11533: beginning of @code{engine()}, you should be able to use the other
11534: caller-saved registers for temporary storage. Alternatively, you can use
11535: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11536: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11537: reserve a register (however, this restriction on register allocation may
11538: slow Gforth significantly).
1.44 crook 11539:
1.78 anton 11540: If this solution is not viable (e.g., because @code{gcc} does not allow
11541: you to explicitly declare all the registers you need), you have to find
11542: out by looking at the code where the inner interpreter's registers
11543: reside and which registers can be used for temporary storage. You can
11544: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11545:
1.78 anton 11546: In any case, it is good practice to abstract your assembly code from the
11547: actual register allocation. E.g., if the data stack pointer resides in
11548: register @code{$17}, create an alias for this register called @code{sp},
11549: and use that in your assembly code.
1.21 crook 11550:
1.78 anton 11551: @cindex code words, portable
11552: Another option for implementing normal and defining words efficiently
11553: is to add the desired functionality to the source of Gforth. For normal
11554: words you just have to edit @file{primitives} (@pxref{Automatic
11555: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11556: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11557: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11558:
1.78 anton 11559: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11560: @subsection Common Assembler
1.44 crook 11561:
1.78 anton 11562: The assemblers in Gforth generally use a postfix syntax, i.e., the
11563: instruction name follows the operands.
1.21 crook 11564:
1.78 anton 11565: The operands are passed in the usual order (the same that is used in the
11566: manual of the architecture). Since they all are Forth words, they have
11567: to be separated by spaces; you can also use Forth words to compute the
11568: operands.
1.44 crook 11569:
1.78 anton 11570: The instruction names usually end with a @code{,}. This makes it easier
11571: to visually separate instructions if you put several of them on one
11572: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11573:
1.78 anton 11574: Registers are usually specified by number; e.g., (decimal) @code{11}
11575: specifies registers R11 and F11 on the Alpha architecture (which one,
11576: depends on the instruction). The usual names are also available, e.g.,
11577: @code{s2} for R11 on Alpha.
1.21 crook 11578:
1.78 anton 11579: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
11580: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
11581: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
11582: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
11583: conditions are specified in a way specific to each assembler.
1.1 anton 11584:
1.78 anton 11585: Note that the register assignments of the Gforth engine can change
11586: between Gforth versions, or even between different compilations of the
11587: same Gforth version (e.g., if you use a different GCC version). So if
11588: you want to refer to Gforth's registers (e.g., the stack pointer or
11589: TOS), I recommend defining your own words for refering to these
11590: registers, and using them later on; then you can easily adapt to a
11591: changed register assignment. The stability of the register assignment
11592: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 11593:
1.100 anton 11594: The most common use of these registers is to dispatch to the next word
11595: (the @code{next} routine). A portable way to do this is to jump to
11596: @code{' noop >code-address} (of course, this is less efficient than
11597: integrating the @code{next} code and scheduling it well).
1.1 anton 11598:
1.96 anton 11599: Another difference between Gforth version is that the top of stack is
11600: kept in memory in @code{gforth} and, on most platforms, in a register in
11601: @code{gforth-fast}.
11602:
1.78 anton 11603: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
11604: @subsection Common Disassembler
1.1 anton 11605:
1.78 anton 11606: You can disassemble a @code{code} word with @code{see}
11607: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 11608:
1.78 anton 11609: doc-disasm
1.44 crook 11610:
1.78 anton 11611: The disassembler generally produces output that can be fed into the
11612: assembler (i.e., same syntax, etc.). It also includes additional
11613: information in comments. In particular, the address of the instruction
11614: is given in a comment before the instruction.
1.1 anton 11615:
1.78 anton 11616: @code{See} may display more or less than the actual code of the word,
11617: because the recognition of the end of the code is unreliable. You can
11618: use @code{disasm} if it did not display enough. It may display more, if
11619: the code word is not immediately followed by a named word. If you have
1.116 anton 11620: something else there, you can follow the word with @code{align latest ,}
1.78 anton 11621: to ensure that the end is recognized.
1.21 crook 11622:
1.78 anton 11623: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
11624: @subsection 386 Assembler
1.44 crook 11625:
1.78 anton 11626: The 386 assembler included in Gforth was written by Bernd Paysan, it's
11627: available under GPL, and originally part of bigFORTH.
1.21 crook 11628:
1.78 anton 11629: The 386 disassembler included in Gforth was written by Andrew McKewan
11630: and is in the public domain.
1.21 crook 11631:
1.91 anton 11632: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 11633:
1.78 anton 11634: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 11635:
1.78 anton 11636: The assembler includes all instruction of the Athlon, i.e. 486 core
11637: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
11638: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
11639: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 11640:
1.78 anton 11641: There are several prefixes to switch between different operation sizes,
11642: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
11643: double-word accesses. Addressing modes can be switched with @code{.wa}
11644: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
11645: need a prefix for byte register names (@code{AL} et al).
1.1 anton 11646:
1.78 anton 11647: For floating point operations, the prefixes are @code{.fs} (IEEE
11648: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
11649: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 11650:
1.78 anton 11651: The MMX opcodes don't have size prefixes, they are spelled out like in
11652: the Intel assembler. Instead of move from and to memory, there are
11653: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 11654:
1.78 anton 11655: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
11656: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 11657: e.g., @code{3 #}. Here are some examples of addressing modes in various
11658: syntaxes:
1.21 crook 11659:
1.26 crook 11660: @example
1.91 anton 11661: Gforth Intel (NASM) AT&T (gas) Name
11662: .w ax ax %ax register (16 bit)
11663: ax eax %eax register (32 bit)
11664: 3 # offset 3 $3 immediate
11665: 1000 #) byte ptr 1000 1000 displacement
11666: bx ) [ebx] (%ebx) base
11667: 100 di d) 100[edi] 100(%edi) base+displacement
11668: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
11669: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
11670: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
11671: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
11672: @end example
11673:
11674: You can use @code{L)} and @code{LI)} instead of @code{D)} and
11675: @code{DI)} to enforce 32-bit displacement fields (useful for
11676: later patching).
1.21 crook 11677:
1.78 anton 11678: Some example of instructions are:
1.1 anton 11679:
11680: @example
1.78 anton 11681: ax bx mov \ move ebx,eax
11682: 3 # ax mov \ mov eax,3
11683: 100 di ) ax mov \ mov eax,100[edi]
11684: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
11685: .w ax bx mov \ mov bx,ax
1.1 anton 11686: @end example
11687:
1.78 anton 11688: The following forms are supported for binary instructions:
1.1 anton 11689:
11690: @example
1.78 anton 11691: <reg> <reg> <inst>
11692: <n> # <reg> <inst>
11693: <mem> <reg> <inst>
11694: <reg> <mem> <inst>
1.1 anton 11695: @end example
11696:
1.78 anton 11697: Immediate to memory is not supported. The shift/rotate syntax is:
1.1 anton 11698:
1.26 crook 11699: @example
1.78 anton 11700: <reg/mem> 1 # shl \ shortens to shift without immediate
11701: <reg/mem> 4 # shl
11702: <reg/mem> cl shl
1.26 crook 11703: @end example
1.1 anton 11704:
1.78 anton 11705: Precede string instructions (@code{movs} etc.) with @code{.b} to get
11706: the byte version.
1.1 anton 11707:
1.78 anton 11708: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
11709: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
11710: pc < >= <= >}. (Note that most of these words shadow some Forth words
11711: when @code{assembler} is in front of @code{forth} in the search path,
11712: e.g., in @code{code} words). Currently the control structure words use
11713: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
11714: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 11715:
1.78 anton 11716: Here is an example of a @code{code} word (assumes that the stack pointer
11717: is in esi and the TOS is in ebx):
1.21 crook 11718:
1.26 crook 11719: @example
1.78 anton 11720: code my+ ( n1 n2 -- n )
11721: 4 si D) bx add
11722: 4 # si add
11723: Next
11724: end-code
1.26 crook 11725: @end example
1.21 crook 11726:
1.78 anton 11727: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
11728: @subsection Alpha Assembler
1.21 crook 11729:
1.78 anton 11730: The Alpha assembler and disassembler were originally written by Bernd
11731: Thallner.
1.26 crook 11732:
1.78 anton 11733: The register names @code{a0}--@code{a5} are not available to avoid
11734: shadowing hex numbers.
1.2 jwilke 11735:
1.78 anton 11736: Immediate forms of arithmetic instructions are distinguished by a
11737: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
11738: does not count as arithmetic instruction).
1.2 jwilke 11739:
1.78 anton 11740: You have to specify all operands to an instruction, even those that
11741: other assemblers consider optional, e.g., the destination register for
11742: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 11743:
1.78 anton 11744: You can specify conditions for @code{if,} by removing the first @code{b}
11745: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 11746:
1.26 crook 11747: @example
1.78 anton 11748: 11 fgt if, \ if F11>0e
11749: ...
11750: endif,
1.26 crook 11751: @end example
1.2 jwilke 11752:
1.78 anton 11753: @code{fbgt,} gives @code{fgt}.
11754:
11755: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
11756: @subsection MIPS assembler
1.2 jwilke 11757:
1.78 anton 11758: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 11759:
1.78 anton 11760: Currently the assembler and disassembler only cover the MIPS-I
11761: architecture (R3000), and don't support FP instructions.
1.2 jwilke 11762:
1.78 anton 11763: The register names @code{$a0}--@code{$a3} are not available to avoid
11764: shadowing hex numbers.
1.2 jwilke 11765:
1.78 anton 11766: Because there is no way to distinguish registers from immediate values,
11767: you have to explicitly use the immediate forms of instructions, i.e.,
11768: @code{addiu,}, not just @code{addu,} (@command{as} does this
11769: implicitly).
1.2 jwilke 11770:
1.78 anton 11771: If the architecture manual specifies several formats for the instruction
11772: (e.g., for @code{jalr,}), you usually have to use the one with more
11773: arguments (i.e., two for @code{jalr,}). When in doubt, see
11774: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 11775:
1.78 anton 11776: Branches and jumps in the MIPS architecture have a delay slot. You have
11777: to fill it yourself (the simplest way is to use @code{nop,}), the
11778: assembler does not do it for you (unlike @command{as}). Even
11779: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
11780: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
11781: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 11782:
1.78 anton 11783: Note that you must not put branches, jumps, or @code{li,} into the delay
11784: slot: @code{li,} may expand to several instructions, and control flow
11785: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 11786:
1.78 anton 11787: For branches the argument specifying the target is a relative address;
11788: You have to add the address of the delay slot to get the absolute
11789: address.
1.1 anton 11790:
1.78 anton 11791: The MIPS architecture also has load delay slots and restrictions on
11792: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
11793: yourself to satisfy these restrictions, the assembler does not do it for
11794: you.
1.1 anton 11795:
1.78 anton 11796: You can specify the conditions for @code{if,} etc. by taking a
11797: conditional branch and leaving away the @code{b} at the start and the
11798: @code{,} at the end. E.g.,
1.1 anton 11799:
1.26 crook 11800: @example
1.78 anton 11801: 4 5 eq if,
11802: ... \ do something if $4 equals $5
11803: then,
1.26 crook 11804: @end example
1.1 anton 11805:
1.78 anton 11806: @node Other assemblers, , MIPS assembler, Assembler and Code Words
11807: @subsection Other assemblers
11808:
11809: If you want to contribute another assembler/disassembler, please contact
1.103 anton 11810: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
11811: an assembler already. If you are writing them from scratch, please use
11812: a similar syntax style as the one we use (i.e., postfix, commas at the
11813: end of the instruction names, @pxref{Common Assembler}); make the output
11814: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 11815: similar to the style we used.
11816:
11817: Hints on implementation: The most important part is to have a good test
11818: suite that contains all instructions. Once you have that, the rest is
11819: easy. For actual coding you can take a look at
11820: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
11821: the assembler and disassembler, avoiding redundancy and some potential
11822: bugs. You can also look at that file (and @pxref{Advanced does> usage
11823: example}) to get ideas how to factor a disassembler.
11824:
11825: Start with the disassembler, because it's easier to reuse data from the
11826: disassembler for the assembler than the other way round.
1.1 anton 11827:
1.78 anton 11828: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
11829: how simple it can be.
1.1 anton 11830:
1.78 anton 11831: @c -------------------------------------------------------------
11832: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
11833: @section Threading Words
11834: @cindex threading words
1.1 anton 11835:
1.78 anton 11836: @cindex code address
11837: These words provide access to code addresses and other threading stuff
11838: in Gforth (and, possibly, other interpretive Forths). It more or less
11839: abstracts away the differences between direct and indirect threading
11840: (and, for direct threading, the machine dependences). However, at
11841: present this wordset is still incomplete. It is also pretty low-level;
11842: some day it will hopefully be made unnecessary by an internals wordset
11843: that abstracts implementation details away completely.
1.1 anton 11844:
1.78 anton 11845: The terminology used here stems from indirect threaded Forth systems; in
11846: such a system, the XT of a word is represented by the CFA (code field
11847: address) of a word; the CFA points to a cell that contains the code
11848: address. The code address is the address of some machine code that
11849: performs the run-time action of invoking the word (e.g., the
11850: @code{dovar:} routine pushes the address of the body of the word (a
11851: variable) on the stack
11852: ).
1.1 anton 11853:
1.78 anton 11854: @cindex code address
11855: @cindex code field address
11856: In an indirect threaded Forth, you can get the code address of @i{name}
11857: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
11858: >code-address}, independent of the threading method.
1.1 anton 11859:
1.78 anton 11860: doc-threading-method
11861: doc->code-address
11862: doc-code-address!
1.1 anton 11863:
1.78 anton 11864: @cindex @code{does>}-handler
11865: @cindex @code{does>}-code
11866: For a word defined with @code{DOES>}, the code address usually points to
11867: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
11868: routine (in Gforth on some platforms, it can also point to the dodoes
11869: routine itself). What you are typically interested in, though, is
11870: whether a word is a @code{DOES>}-defined word, and what Forth code it
11871: executes; @code{>does-code} tells you that.
1.1 anton 11872:
1.78 anton 11873: doc->does-code
1.1 anton 11874:
1.78 anton 11875: To create a @code{DOES>}-defined word with the following basic words,
11876: you have to set up a @code{DOES>}-handler with @code{does-handler!};
11877: @code{/does-handler} aus behind you have to place your executable Forth
11878: code. Finally you have to create a word and modify its behaviour with
11879: @code{does-handler!}.
1.1 anton 11880:
1.78 anton 11881: doc-does-code!
11882: doc-does-handler!
11883: doc-/does-handler
1.1 anton 11884:
1.78 anton 11885: The code addresses produced by various defining words are produced by
11886: the following words:
1.1 anton 11887:
1.78 anton 11888: doc-docol:
11889: doc-docon:
11890: doc-dovar:
11891: doc-douser:
11892: doc-dodefer:
11893: doc-dofield:
1.1 anton 11894:
1.99 anton 11895: @cindex definer
11896: The following two words generalize @code{>code-address},
11897: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
11898:
11899: doc->definer
11900: doc-definer!
11901:
1.26 crook 11902: @c -------------------------------------------------------------
1.78 anton 11903: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 11904: @section Passing Commands to the Operating System
11905: @cindex operating system - passing commands
11906: @cindex shell commands
11907:
11908: Gforth allows you to pass an arbitrary string to the host operating
11909: system shell (if such a thing exists) for execution.
11910:
1.44 crook 11911:
1.21 crook 11912: doc-sh
11913: doc-system
11914: doc-$?
1.23 crook 11915: doc-getenv
1.21 crook 11916:
1.44 crook 11917:
1.26 crook 11918: @c -------------------------------------------------------------
1.47 crook 11919: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
11920: @section Keeping track of Time
11921: @cindex time-related words
11922:
11923: doc-ms
11924: doc-time&date
1.79 anton 11925: doc-utime
11926: doc-cputime
1.47 crook 11927:
11928:
11929: @c -------------------------------------------------------------
11930: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 11931: @section Miscellaneous Words
11932: @cindex miscellaneous words
11933:
1.29 crook 11934: @comment TODO find homes for these
11935:
1.26 crook 11936: These section lists the ANS Forth words that are not documented
1.21 crook 11937: elsewhere in this manual. Ultimately, they all need proper homes.
11938:
1.68 anton 11939: doc-quit
1.44 crook 11940:
1.26 crook 11941: The following ANS Forth words are not currently supported by Gforth
1.27 crook 11942: (@pxref{ANS conformance}):
1.21 crook 11943:
11944: @code{EDITOR}
11945: @code{EMIT?}
11946: @code{FORGET}
11947:
1.24 anton 11948: @c ******************************************************************
11949: @node Error messages, Tools, Words, Top
11950: @chapter Error messages
11951: @cindex error messages
11952: @cindex backtrace
11953:
11954: A typical Gforth error message looks like this:
11955:
11956: @example
1.86 anton 11957: in file included from \evaluated string/:-1
1.24 anton 11958: in file included from ./yyy.fs:1
11959: ./xxx.fs:4: Invalid memory address
11960: bar
11961: ^^^
1.79 anton 11962: Backtrace:
1.25 anton 11963: $400E664C @@
11964: $400E6664 foo
1.24 anton 11965: @end example
11966:
11967: The message identifying the error is @code{Invalid memory address}. The
11968: error happened when text-interpreting line 4 of the file
11969: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
11970: word on the line where the error happened, is pointed out (with
11971: @code{^^^}).
11972:
11973: The file containing the error was included in line 1 of @file{./yyy.fs},
11974: and @file{yyy.fs} was included from a non-file (in this case, by giving
11975: @file{yyy.fs} as command-line parameter to Gforth).
11976:
11977: At the end of the error message you find a return stack dump that can be
11978: interpreted as a backtrace (possibly empty). On top you find the top of
11979: the return stack when the @code{throw} happened, and at the bottom you
11980: find the return stack entry just above the return stack of the topmost
11981: text interpreter.
11982:
11983: To the right of most return stack entries you see a guess for the word
11984: that pushed that return stack entry as its return address. This gives a
11985: backtrace. In our case we see that @code{bar} called @code{foo}, and
11986: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
11987: address} exception).
11988:
11989: Note that the backtrace is not perfect: We don't know which return stack
11990: entries are return addresses (so we may get false positives); and in
11991: some cases (e.g., for @code{abort"}) we cannot determine from the return
11992: address the word that pushed the return address, so for some return
11993: addresses you see no names in the return stack dump.
1.25 anton 11994:
11995: @cindex @code{catch} and backtraces
11996: The return stack dump represents the return stack at the time when a
11997: specific @code{throw} was executed. In programs that make use of
11998: @code{catch}, it is not necessarily clear which @code{throw} should be
11999: used for the return stack dump (e.g., consider one @code{throw} that
12000: indicates an error, which is caught, and during recovery another error
1.42 anton 12001: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12002: presents the return stack dump for the first @code{throw} after the last
12003: executed (not returned-to) @code{catch}; this works well in the usual
12004: case.
12005:
12006: @cindex @code{gforth-fast} and backtraces
12007: @cindex @code{gforth-fast}, difference from @code{gforth}
12008: @cindex backtraces with @code{gforth-fast}
12009: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12010: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12011: from primitives (e.g., invalid memory address, stack empty etc.);
12012: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12013: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12014: exception caused by a primitive in @code{gforth-fast}, you will
12015: typically see no return stack dump at all; however, if the exception is
12016: caught by @code{catch} (e.g., for restoring some state), and then
12017: @code{throw}n again, the return stack dump will be for the first such
12018: @code{throw}.
1.2 jwilke 12019:
1.5 anton 12020: @c ******************************************************************
1.24 anton 12021: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12022: @chapter Tools
12023:
12024: @menu
12025: * ANS Report:: Report the words used, sorted by wordset.
12026: @end menu
12027:
12028: See also @ref{Emacs and Gforth}.
12029:
12030: @node ANS Report, , Tools, Tools
12031: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12032: @cindex @file{ans-report.fs}
12033: @cindex report the words used in your program
12034: @cindex words used in your program
12035:
12036: If you want to label a Forth program as ANS Forth Program, you must
12037: document which wordsets the program uses; for extension wordsets, it is
12038: helpful to list the words the program requires from these wordsets
12039: (because Forth systems are allowed to provide only some words of them).
12040:
12041: The @file{ans-report.fs} tool makes it easy for you to determine which
12042: words from which wordset and which non-ANS words your application
12043: uses. You simply have to include @file{ans-report.fs} before loading the
12044: program you want to check. After loading your program, you can get the
12045: report with @code{print-ans-report}. A typical use is to run this as
12046: batch job like this:
12047: @example
12048: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12049: @end example
12050:
12051: The output looks like this (for @file{compat/control.fs}):
12052: @example
12053: The program uses the following words
12054: from CORE :
12055: : POSTPONE THEN ; immediate ?dup IF 0=
12056: from BLOCK-EXT :
12057: \
12058: from FILE :
12059: (
12060: @end example
12061:
12062: @subsection Caveats
12063:
12064: Note that @file{ans-report.fs} just checks which words are used, not whether
12065: they are used in an ANS Forth conforming way!
12066:
12067: Some words are defined in several wordsets in the
12068: standard. @file{ans-report.fs} reports them for only one of the
12069: wordsets, and not necessarily the one you expect. It depends on usage
12070: which wordset is the right one to specify. E.g., if you only use the
12071: compilation semantics of @code{S"}, it is a Core word; if you also use
12072: its interpretation semantics, it is a File word.
12073:
12074: @c ******************************************************************
1.65 anton 12075: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12076: @chapter ANS conformance
12077: @cindex ANS conformance of Gforth
12078:
12079: To the best of our knowledge, Gforth is an
12080:
12081: ANS Forth System
12082: @itemize @bullet
12083: @item providing the Core Extensions word set
12084: @item providing the Block word set
12085: @item providing the Block Extensions word set
12086: @item providing the Double-Number word set
12087: @item providing the Double-Number Extensions word set
12088: @item providing the Exception word set
12089: @item providing the Exception Extensions word set
12090: @item providing the Facility word set
1.40 anton 12091: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12092: @item providing the File Access word set
12093: @item providing the File Access Extensions word set
12094: @item providing the Floating-Point word set
12095: @item providing the Floating-Point Extensions word set
12096: @item providing the Locals word set
12097: @item providing the Locals Extensions word set
12098: @item providing the Memory-Allocation word set
12099: @item providing the Memory-Allocation Extensions word set (that one's easy)
12100: @item providing the Programming-Tools word set
12101: @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
12102: @item providing the Search-Order word set
12103: @item providing the Search-Order Extensions word set
12104: @item providing the String word set
12105: @item providing the String Extensions word set (another easy one)
12106: @end itemize
12107:
12108: @cindex system documentation
12109: In addition, ANS Forth systems are required to document certain
12110: implementation choices. This chapter tries to meet these
12111: requirements. In many cases it gives a way to ask the system for the
12112: information instead of providing the information directly, in
12113: particular, if the information depends on the processor, the operating
12114: system or the installation options chosen, or if they are likely to
12115: change during the maintenance of Gforth.
12116:
12117: @comment The framework for the rest has been taken from pfe.
12118:
12119: @menu
12120: * The Core Words::
12121: * The optional Block word set::
12122: * The optional Double Number word set::
12123: * The optional Exception word set::
12124: * The optional Facility word set::
12125: * The optional File-Access word set::
12126: * The optional Floating-Point word set::
12127: * The optional Locals word set::
12128: * The optional Memory-Allocation word set::
12129: * The optional Programming-Tools word set::
12130: * The optional Search-Order word set::
12131: @end menu
12132:
12133:
12134: @c =====================================================================
12135: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12136: @comment node-name, next, previous, up
12137: @section The Core Words
12138: @c =====================================================================
12139: @cindex core words, system documentation
12140: @cindex system documentation, core words
12141:
12142: @menu
12143: * core-idef:: Implementation Defined Options
12144: * core-ambcond:: Ambiguous Conditions
12145: * core-other:: Other System Documentation
12146: @end menu
12147:
12148: @c ---------------------------------------------------------------------
12149: @node core-idef, core-ambcond, The Core Words, The Core Words
12150: @subsection Implementation Defined Options
12151: @c ---------------------------------------------------------------------
12152: @cindex core words, implementation-defined options
12153: @cindex implementation-defined options, core words
12154:
12155:
12156: @table @i
12157: @item (Cell) aligned addresses:
12158: @cindex cell-aligned addresses
12159: @cindex aligned addresses
12160: processor-dependent. Gforth's alignment words perform natural alignment
12161: (e.g., an address aligned for a datum of size 8 is divisible by
12162: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12163:
12164: @item @code{EMIT} and non-graphic characters:
12165: @cindex @code{EMIT} and non-graphic characters
12166: @cindex non-graphic characters and @code{EMIT}
12167: The character is output using the C library function (actually, macro)
12168: @code{putc}.
12169:
12170: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12171: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12172: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12173: @cindex @code{ACCEPT}, editing
12174: @cindex @code{EXPECT}, editing
12175: This is modeled on the GNU readline library (@pxref{Readline
12176: Interaction, , Command Line Editing, readline, The GNU Readline
12177: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12178: producing a full word completion every time you type it (instead of
1.28 crook 12179: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12180:
12181: @item character set:
12182: @cindex character set
12183: The character set of your computer and display device. Gforth is
12184: 8-bit-clean (but some other component in your system may make trouble).
12185:
12186: @item Character-aligned address requirements:
12187: @cindex character-aligned address requirements
12188: installation-dependent. Currently a character is represented by a C
12189: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12190: (Comments on that requested).
12191:
12192: @item character-set extensions and matching of names:
12193: @cindex character-set extensions and matching of names
1.26 crook 12194: @cindex case-sensitivity for name lookup
12195: @cindex name lookup, case-sensitivity
12196: @cindex locale and case-sensitivity
1.21 crook 12197: Any character except the ASCII NUL character can be used in a
1.1 anton 12198: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12199: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12200: function is probably influenced by the locale. E.g., the @code{C} locale
12201: does not know about accents and umlauts, so they are matched
12202: case-sensitively in that locale. For portability reasons it is best to
12203: write programs such that they work in the @code{C} locale. Then one can
12204: use libraries written by a Polish programmer (who might use words
12205: containing ISO Latin-2 encoded characters) and by a French programmer
12206: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12207: funny results for some of the words (which ones, depends on the font you
12208: are using)). Also, the locale you prefer may not be available in other
12209: operating systems. Hopefully, Unicode will solve these problems one day.
12210:
12211: @item conditions under which control characters match a space delimiter:
12212: @cindex space delimiters
12213: @cindex control characters as delimiters
1.117 ! anton 12214: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12215: white-space characters (as identified by the C macro @code{isspace()})
1.117 ! anton 12216: are delimiters. @code{Parse}, on the other hand, treats space like other
! 12217: delimiters. @code{Parse-word}, which is used by the outer
1.1 anton 12218: interpreter (aka text interpreter) by default, treats all white-space
12219: characters as delimiters.
12220:
1.26 crook 12221: @item format of the control-flow stack:
12222: @cindex control-flow stack, format
12223: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12224: stack item in cells is given by the constant @code{cs-item-size}. At the
12225: time of this writing, an item consists of a (pointer to a) locals list
12226: (third), an address in the code (second), and a tag for identifying the
12227: item (TOS). The following tags are used: @code{defstart},
12228: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12229: @code{scopestart}.
12230:
12231: @item conversion of digits > 35
12232: @cindex digits > 35
12233: The characters @code{[\]^_'} are the digits with the decimal value
12234: 36@minus{}41. There is no way to input many of the larger digits.
12235:
12236: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12237: @cindex @code{EXPECT}, display after end of input
12238: @cindex @code{ACCEPT}, display after end of input
12239: The cursor is moved to the end of the entered string. If the input is
12240: terminated using the @kbd{Return} key, a space is typed.
12241:
12242: @item exception abort sequence of @code{ABORT"}:
12243: @cindex exception abort sequence of @code{ABORT"}
12244: @cindex @code{ABORT"}, exception abort sequence
12245: The error string is stored into the variable @code{"error} and a
12246: @code{-2 throw} is performed.
12247:
12248: @item input line terminator:
12249: @cindex input line terminator
12250: @cindex line terminator on input
1.26 crook 12251: @cindex newline character on input
1.1 anton 12252: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12253: lines. One of these characters is typically produced when you type the
12254: @kbd{Enter} or @kbd{Return} key.
12255:
12256: @item maximum size of a counted string:
12257: @cindex maximum size of a counted string
12258: @cindex counted string, maximum size
12259: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12260: on all platforms, but this may change.
1.1 anton 12261:
12262: @item maximum size of a parsed string:
12263: @cindex maximum size of a parsed string
12264: @cindex parsed string, maximum size
12265: Given by the constant @code{/line}. Currently 255 characters.
12266:
12267: @item maximum size of a definition name, in characters:
12268: @cindex maximum size of a definition name, in characters
12269: @cindex name, maximum length
1.113 anton 12270: MAXU/8
1.1 anton 12271:
12272: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12273: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12274: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12275: MAXU/8
1.1 anton 12276:
12277: @item method of selecting the user input device:
12278: @cindex user input device, method of selecting
12279: The user input device is the standard input. There is currently no way to
12280: change it from within Gforth. However, the input can typically be
12281: redirected in the command line that starts Gforth.
12282:
12283: @item method of selecting the user output device:
12284: @cindex user output device, method of selecting
12285: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12286: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12287: output when the user output device is a terminal, otherwise the output
12288: is buffered.
1.1 anton 12289:
12290: @item methods of dictionary compilation:
12291: What are we expected to document here?
12292:
12293: @item number of bits in one address unit:
12294: @cindex number of bits in one address unit
12295: @cindex address unit, size in bits
12296: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12297: platforms.
1.1 anton 12298:
12299: @item number representation and arithmetic:
12300: @cindex number representation and arithmetic
1.79 anton 12301: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12302:
12303: @item ranges for integer types:
12304: @cindex ranges for integer types
12305: @cindex integer types, ranges
12306: Installation-dependent. Make environmental queries for @code{MAX-N},
12307: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12308: unsigned (and positive) types is 0. The lower bound for signed types on
12309: two's complement and one's complement machines machines can be computed
12310: by adding 1 to the upper bound.
12311:
12312: @item read-only data space regions:
12313: @cindex read-only data space regions
12314: @cindex data-space, read-only regions
12315: The whole Forth data space is writable.
12316:
12317: @item size of buffer at @code{WORD}:
12318: @cindex size of buffer at @code{WORD}
12319: @cindex @code{WORD} buffer size
12320: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12321: shared with the pictured numeric output string. If overwriting
12322: @code{PAD} is acceptable, it is as large as the remaining dictionary
12323: space, although only as much can be sensibly used as fits in a counted
12324: string.
12325:
12326: @item size of one cell in address units:
12327: @cindex cell size
12328: @code{1 cells .}.
12329:
12330: @item size of one character in address units:
12331: @cindex char size
1.79 anton 12332: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12333:
12334: @item size of the keyboard terminal buffer:
12335: @cindex size of the keyboard terminal buffer
12336: @cindex terminal buffer, size
12337: Varies. You can determine the size at a specific time using @code{lp@@
12338: tib - .}. It is shared with the locals stack and TIBs of files that
12339: include the current file. You can change the amount of space for TIBs
12340: and locals stack at Gforth startup with the command line option
12341: @code{-l}.
12342:
12343: @item size of the pictured numeric output buffer:
12344: @cindex size of the pictured numeric output buffer
12345: @cindex pictured numeric output buffer, size
12346: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12347: shared with @code{WORD}.
12348:
12349: @item size of the scratch area returned by @code{PAD}:
12350: @cindex size of the scratch area returned by @code{PAD}
12351: @cindex @code{PAD} size
12352: The remainder of dictionary space. @code{unused pad here - - .}.
12353:
12354: @item system case-sensitivity characteristics:
12355: @cindex case-sensitivity characteristics
1.26 crook 12356: Dictionary searches are case-insensitive (except in
1.1 anton 12357: @code{TABLE}s). However, as explained above under @i{character-set
12358: extensions}, the matching for non-ASCII characters is determined by the
12359: locale you are using. In the default @code{C} locale all non-ASCII
12360: characters are matched case-sensitively.
12361:
12362: @item system prompt:
12363: @cindex system prompt
12364: @cindex prompt
12365: @code{ ok} in interpret state, @code{ compiled} in compile state.
12366:
12367: @item division rounding:
12368: @cindex division rounding
12369: installation dependent. @code{s" floored" environment? drop .}. We leave
12370: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12371: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12372:
12373: @item values of @code{STATE} when true:
12374: @cindex @code{STATE} values
12375: -1.
12376:
12377: @item values returned after arithmetic overflow:
12378: On two's complement machines, arithmetic is performed modulo
12379: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12380: arithmetic (with appropriate mapping for signed types). Division by zero
12381: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12382: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12383:
12384: @item whether the current definition can be found after @t{DOES>}:
12385: @cindex @t{DOES>}, visibility of current definition
12386: No.
12387:
12388: @end table
12389:
12390: @c ---------------------------------------------------------------------
12391: @node core-ambcond, core-other, core-idef, The Core Words
12392: @subsection Ambiguous conditions
12393: @c ---------------------------------------------------------------------
12394: @cindex core words, ambiguous conditions
12395: @cindex ambiguous conditions, core words
12396:
12397: @table @i
12398:
12399: @item a name is neither a word nor a number:
12400: @cindex name not found
1.26 crook 12401: @cindex undefined word
1.80 anton 12402: @code{-13 throw} (Undefined word).
1.1 anton 12403:
12404: @item a definition name exceeds the maximum length allowed:
1.26 crook 12405: @cindex word name too long
1.1 anton 12406: @code{-19 throw} (Word name too long)
12407:
12408: @item addressing a region not inside the various data spaces of the forth system:
12409: @cindex Invalid memory address
1.32 anton 12410: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12411: typically readable. Accessing other addresses gives results dependent on
12412: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12413: address).
12414:
12415: @item argument type incompatible with parameter:
1.26 crook 12416: @cindex argument type mismatch
1.1 anton 12417: This is usually not caught. Some words perform checks, e.g., the control
12418: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12419: mismatch).
12420:
12421: @item attempting to obtain the execution token of a word with undefined execution semantics:
12422: @cindex Interpreting a compile-only word, for @code{'} etc.
12423: @cindex execution token of words with undefined execution semantics
12424: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12425: get an execution token for @code{compile-only-error} (which performs a
12426: @code{-14 throw} when executed).
12427:
12428: @item dividing by zero:
12429: @cindex dividing by zero
12430: @cindex floating point unidentified fault, integer division
1.80 anton 12431: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12432: zero); on other systems, this typically results in a @code{-55 throw}
12433: (Floating-point unidentified fault).
1.1 anton 12434:
12435: @item insufficient data stack or return stack space:
12436: @cindex insufficient data stack or return stack space
12437: @cindex stack overflow
1.26 crook 12438: @cindex address alignment exception, stack overflow
1.1 anton 12439: @cindex Invalid memory address, stack overflow
12440: Depending on the operating system, the installation, and the invocation
12441: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12442: it is not checked. If it is checked, you typically get a @code{-3 throw}
12443: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12444: throw} (Invalid memory address) (depending on the platform and how you
12445: achieved the overflow) as soon as the overflow happens. If it is not
12446: checked, overflows typically result in mysterious illegal memory
12447: accesses, producing @code{-9 throw} (Invalid memory address) or
12448: @code{-23 throw} (Address alignment exception); they might also destroy
12449: the internal data structure of @code{ALLOCATE} and friends, resulting in
12450: various errors in these words.
1.1 anton 12451:
12452: @item insufficient space for loop control parameters:
12453: @cindex insufficient space for loop control parameters
1.80 anton 12454: Like other return stack overflows.
1.1 anton 12455:
12456: @item insufficient space in the dictionary:
12457: @cindex insufficient space in the dictionary
12458: @cindex dictionary overflow
1.12 anton 12459: If you try to allot (either directly with @code{allot}, or indirectly
12460: with @code{,}, @code{create} etc.) more memory than available in the
12461: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12462: to access memory beyond the end of the dictionary, the results are
12463: similar to stack overflows.
1.1 anton 12464:
12465: @item interpreting a word with undefined interpretation semantics:
12466: @cindex interpreting a word with undefined interpretation semantics
12467: @cindex Interpreting a compile-only word
12468: For some words, we have defined interpretation semantics. For the
12469: others: @code{-14 throw} (Interpreting a compile-only word).
12470:
12471: @item modifying the contents of the input buffer or a string literal:
12472: @cindex modifying the contents of the input buffer or a string literal
12473: These are located in writable memory and can be modified.
12474:
12475: @item overflow of the pictured numeric output string:
12476: @cindex overflow of the pictured numeric output string
12477: @cindex pictured numeric output string, overflow
1.24 anton 12478: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12479:
12480: @item parsed string overflow:
12481: @cindex parsed string overflow
12482: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12483:
12484: @item producing a result out of range:
12485: @cindex result out of range
12486: On two's complement machines, arithmetic is performed modulo
12487: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12488: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12489: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12490: throw} (floating point unidentified fault). @code{convert} and
12491: @code{>number} currently overflow silently.
1.1 anton 12492:
12493: @item reading from an empty data or return stack:
12494: @cindex stack empty
12495: @cindex stack underflow
1.24 anton 12496: @cindex return stack underflow
1.1 anton 12497: The data stack is checked by the outer (aka text) interpreter after
12498: every word executed. If it has underflowed, a @code{-4 throw} (Stack
12499: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 12500: depending on operating system, installation, and invocation. If they are
12501: caught by a check, they typically result in @code{-4 throw} (Stack
12502: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
12503: (Invalid memory address), depending on the platform and which stack
12504: underflows and by how much. Note that even if the system uses checking
12505: (through the MMU), your program may have to underflow by a significant
12506: number of stack items to trigger the reaction (the reason for this is
12507: that the MMU, and therefore the checking, works with a page-size
12508: granularity). If there is no checking, the symptoms resulting from an
12509: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 12510: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 12511: (Invalid memory address) and Illegal Instruction (typically @code{-260
12512: throw}).
1.1 anton 12513:
12514: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
12515: @cindex unexpected end of the input buffer
12516: @cindex zero-length string as a name
12517: @cindex Attempt to use zero-length string as a name
12518: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
12519: use zero-length string as a name). Words like @code{'} probably will not
12520: find what they search. Note that it is possible to create zero-length
12521: names with @code{nextname} (should it not?).
12522:
12523: @item @code{>IN} greater than input buffer:
12524: @cindex @code{>IN} greater than input buffer
12525: The next invocation of a parsing word returns a string with length 0.
12526:
12527: @item @code{RECURSE} appears after @code{DOES>}:
12528: @cindex @code{RECURSE} appears after @code{DOES>}
12529: Compiles a recursive call to the defining word, not to the defined word.
12530:
12531: @item argument input source different than current input source for @code{RESTORE-INPUT}:
12532: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 12533: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 12534: @cindex @code{RESTORE-INPUT}, Argument type mismatch
12535: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
12536: the end of the file was reached), its source-id may be
12537: reused. Therefore, restoring an input source specification referencing a
12538: closed file may lead to unpredictable results instead of a @code{-12
12539: THROW}.
12540:
12541: In the future, Gforth may be able to restore input source specifications
12542: from other than the current input source.
12543:
12544: @item data space containing definitions gets de-allocated:
12545: @cindex data space containing definitions gets de-allocated
12546: Deallocation with @code{allot} is not checked. This typically results in
12547: memory access faults or execution of illegal instructions.
12548:
12549: @item data space read/write with incorrect alignment:
12550: @cindex data space read/write with incorrect alignment
12551: @cindex alignment faults
1.26 crook 12552: @cindex address alignment exception
1.1 anton 12553: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 12554: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 12555: alignment turned on, incorrect alignment results in a @code{-9 throw}
12556: (Invalid memory address). There are reportedly some processors with
1.12 anton 12557: alignment restrictions that do not report violations.
1.1 anton 12558:
12559: @item data space pointer not properly aligned, @code{,}, @code{C,}:
12560: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
12561: Like other alignment errors.
12562:
12563: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
12564: Like other stack underflows.
12565:
12566: @item loop control parameters not available:
12567: @cindex loop control parameters not available
12568: Not checked. The counted loop words simply assume that the top of return
12569: stack items are loop control parameters and behave accordingly.
12570:
12571: @item most recent definition does not have a name (@code{IMMEDIATE}):
12572: @cindex most recent definition does not have a name (@code{IMMEDIATE})
12573: @cindex last word was headerless
12574: @code{abort" last word was headerless"}.
12575:
12576: @item name not defined by @code{VALUE} used by @code{TO}:
12577: @cindex name not defined by @code{VALUE} used by @code{TO}
12578: @cindex @code{TO} on non-@code{VALUE}s
12579: @cindex Invalid name argument, @code{TO}
12580: @code{-32 throw} (Invalid name argument) (unless name is a local or was
12581: defined by @code{CONSTANT}; in the latter case it just changes the constant).
12582:
12583: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
12584: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 12585: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 12586: @code{-13 throw} (Undefined word)
12587:
12588: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
12589: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
12590: Gforth behaves as if they were of the same type. I.e., you can predict
12591: the behaviour by interpreting all parameters as, e.g., signed.
12592:
12593: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
12594: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
12595: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
12596: compilation semantics of @code{TO}.
12597:
12598: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 12599: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 12600: @cindex @code{WORD}, string overflow
12601: Not checked. The string will be ok, but the count will, of course,
12602: contain only the least significant bits of the length.
12603:
12604: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
12605: @cindex @code{LSHIFT}, large shift counts
12606: @cindex @code{RSHIFT}, large shift counts
12607: Processor-dependent. Typical behaviours are returning 0 and using only
12608: the low bits of the shift count.
12609:
12610: @item word not defined via @code{CREATE}:
12611: @cindex @code{>BODY} of non-@code{CREATE}d words
12612: @code{>BODY} produces the PFA of the word no matter how it was defined.
12613:
12614: @cindex @code{DOES>} of non-@code{CREATE}d words
12615: @code{DOES>} changes the execution semantics of the last defined word no
12616: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
12617: @code{CREATE , DOES>}.
12618:
12619: @item words improperly used outside @code{<#} and @code{#>}:
12620: Not checked. As usual, you can expect memory faults.
12621:
12622: @end table
12623:
12624:
12625: @c ---------------------------------------------------------------------
12626: @node core-other, , core-ambcond, The Core Words
12627: @subsection Other system documentation
12628: @c ---------------------------------------------------------------------
12629: @cindex other system documentation, core words
12630: @cindex core words, other system documentation
12631:
12632: @table @i
12633: @item nonstandard words using @code{PAD}:
12634: @cindex @code{PAD} use by nonstandard words
12635: None.
12636:
12637: @item operator's terminal facilities available:
12638: @cindex operator's terminal facilities available
1.80 anton 12639: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 12640: and you can give commands to Gforth interactively. The actual facilities
12641: available depend on how you invoke Gforth.
12642:
12643: @item program data space available:
12644: @cindex program data space available
12645: @cindex data space available
12646: @code{UNUSED .} gives the remaining dictionary space. The total
12647: dictionary space can be specified with the @code{-m} switch
12648: (@pxref{Invoking Gforth}) when Gforth starts up.
12649:
12650: @item return stack space available:
12651: @cindex return stack space available
12652: You can compute the total return stack space in cells with
12653: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
12654: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
12655:
12656: @item stack space available:
12657: @cindex stack space available
12658: You can compute the total data stack space in cells with
12659: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
12660: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
12661:
12662: @item system dictionary space required, in address units:
12663: @cindex system dictionary space required, in address units
12664: Type @code{here forthstart - .} after startup. At the time of this
12665: writing, this gives 80080 (bytes) on a 32-bit system.
12666: @end table
12667:
12668:
12669: @c =====================================================================
12670: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
12671: @section The optional Block word set
12672: @c =====================================================================
12673: @cindex system documentation, block words
12674: @cindex block words, system documentation
12675:
12676: @menu
12677: * block-idef:: Implementation Defined Options
12678: * block-ambcond:: Ambiguous Conditions
12679: * block-other:: Other System Documentation
12680: @end menu
12681:
12682:
12683: @c ---------------------------------------------------------------------
12684: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
12685: @subsection Implementation Defined Options
12686: @c ---------------------------------------------------------------------
12687: @cindex implementation-defined options, block words
12688: @cindex block words, implementation-defined options
12689:
12690: @table @i
12691: @item the format for display by @code{LIST}:
12692: @cindex @code{LIST} display format
12693: First the screen number is displayed, then 16 lines of 64 characters,
12694: each line preceded by the line number.
12695:
12696: @item the length of a line affected by @code{\}:
12697: @cindex length of a line affected by @code{\}
12698: @cindex @code{\}, line length in blocks
12699: 64 characters.
12700: @end table
12701:
12702:
12703: @c ---------------------------------------------------------------------
12704: @node block-ambcond, block-other, block-idef, The optional Block word set
12705: @subsection Ambiguous conditions
12706: @c ---------------------------------------------------------------------
12707: @cindex block words, ambiguous conditions
12708: @cindex ambiguous conditions, block words
12709:
12710: @table @i
12711: @item correct block read was not possible:
12712: @cindex block read not possible
12713: Typically results in a @code{throw} of some OS-derived value (between
12714: -512 and -2048). If the blocks file was just not long enough, blanks are
12715: supplied for the missing portion.
12716:
12717: @item I/O exception in block transfer:
12718: @cindex I/O exception in block transfer
12719: @cindex block transfer, I/O exception
12720: Typically results in a @code{throw} of some OS-derived value (between
12721: -512 and -2048).
12722:
12723: @item invalid block number:
12724: @cindex invalid block number
12725: @cindex block number invalid
12726: @code{-35 throw} (Invalid block number)
12727:
12728: @item a program directly alters the contents of @code{BLK}:
12729: @cindex @code{BLK}, altering @code{BLK}
12730: The input stream is switched to that other block, at the same
12731: position. If the storing to @code{BLK} happens when interpreting
12732: non-block input, the system will get quite confused when the block ends.
12733:
12734: @item no current block buffer for @code{UPDATE}:
12735: @cindex @code{UPDATE}, no current block buffer
12736: @code{UPDATE} has no effect.
12737:
12738: @end table
12739:
12740: @c ---------------------------------------------------------------------
12741: @node block-other, , block-ambcond, The optional Block word set
12742: @subsection Other system documentation
12743: @c ---------------------------------------------------------------------
12744: @cindex other system documentation, block words
12745: @cindex block words, other system documentation
12746:
12747: @table @i
12748: @item any restrictions a multiprogramming system places on the use of buffer addresses:
12749: No restrictions (yet).
12750:
12751: @item the number of blocks available for source and data:
12752: depends on your disk space.
12753:
12754: @end table
12755:
12756:
12757: @c =====================================================================
12758: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
12759: @section The optional Double Number word set
12760: @c =====================================================================
12761: @cindex system documentation, double words
12762: @cindex double words, system documentation
12763:
12764: @menu
12765: * double-ambcond:: Ambiguous Conditions
12766: @end menu
12767:
12768:
12769: @c ---------------------------------------------------------------------
12770: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
12771: @subsection Ambiguous conditions
12772: @c ---------------------------------------------------------------------
12773: @cindex double words, ambiguous conditions
12774: @cindex ambiguous conditions, double words
12775:
12776: @table @i
1.29 crook 12777: @item @i{d} outside of range of @i{n} in @code{D>S}:
12778: @cindex @code{D>S}, @i{d} out of range of @i{n}
12779: The least significant cell of @i{d} is produced.
1.1 anton 12780:
12781: @end table
12782:
12783:
12784: @c =====================================================================
12785: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
12786: @section The optional Exception word set
12787: @c =====================================================================
12788: @cindex system documentation, exception words
12789: @cindex exception words, system documentation
12790:
12791: @menu
12792: * exception-idef:: Implementation Defined Options
12793: @end menu
12794:
12795:
12796: @c ---------------------------------------------------------------------
12797: @node exception-idef, , The optional Exception word set, The optional Exception word set
12798: @subsection Implementation Defined Options
12799: @c ---------------------------------------------------------------------
12800: @cindex implementation-defined options, exception words
12801: @cindex exception words, implementation-defined options
12802:
12803: @table @i
12804: @item @code{THROW}-codes used in the system:
12805: @cindex @code{THROW}-codes used in the system
12806: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 12807: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 12808: codes -512@minus{}-2047 are used for OS errors (for file and memory
12809: allocation operations). The mapping from OS error numbers to throw codes
12810: is -512@minus{}@code{errno}. One side effect of this mapping is that
12811: undefined OS errors produce a message with a strange number; e.g.,
12812: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
12813: @end table
12814:
12815: @c =====================================================================
12816: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
12817: @section The optional Facility word set
12818: @c =====================================================================
12819: @cindex system documentation, facility words
12820: @cindex facility words, system documentation
12821:
12822: @menu
12823: * facility-idef:: Implementation Defined Options
12824: * facility-ambcond:: Ambiguous Conditions
12825: @end menu
12826:
12827:
12828: @c ---------------------------------------------------------------------
12829: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
12830: @subsection Implementation Defined Options
12831: @c ---------------------------------------------------------------------
12832: @cindex implementation-defined options, facility words
12833: @cindex facility words, implementation-defined options
12834:
12835: @table @i
12836: @item encoding of keyboard events (@code{EKEY}):
12837: @cindex keyboard events, encoding in @code{EKEY}
12838: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 12839: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 12840: Other keys are encoded with the constants @code{k-left}, @code{k-right},
12841: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
12842: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
12843: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 12844:
1.1 anton 12845:
12846: @item duration of a system clock tick:
12847: @cindex duration of a system clock tick
12848: @cindex clock tick duration
12849: System dependent. With respect to @code{MS}, the time is specified in
12850: microseconds. How well the OS and the hardware implement this, is
12851: another question.
12852:
12853: @item repeatability to be expected from the execution of @code{MS}:
12854: @cindex repeatability to be expected from the execution of @code{MS}
12855: @cindex @code{MS}, repeatability to be expected
12856: System dependent. On Unix, a lot depends on load. If the system is
12857: lightly loaded, and the delay is short enough that Gforth does not get
12858: swapped out, the performance should be acceptable. Under MS-DOS and
12859: other single-tasking systems, it should be good.
12860:
12861: @end table
12862:
12863:
12864: @c ---------------------------------------------------------------------
12865: @node facility-ambcond, , facility-idef, The optional Facility word set
12866: @subsection Ambiguous conditions
12867: @c ---------------------------------------------------------------------
12868: @cindex facility words, ambiguous conditions
12869: @cindex ambiguous conditions, facility words
12870:
12871: @table @i
12872: @item @code{AT-XY} can't be performed on user output device:
12873: @cindex @code{AT-XY} can't be performed on user output device
12874: Largely terminal dependent. No range checks are done on the arguments.
12875: No errors are reported. You may see some garbage appearing, you may see
12876: simply nothing happen.
12877:
12878: @end table
12879:
12880:
12881: @c =====================================================================
12882: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
12883: @section The optional File-Access word set
12884: @c =====================================================================
12885: @cindex system documentation, file words
12886: @cindex file words, system documentation
12887:
12888: @menu
12889: * file-idef:: Implementation Defined Options
12890: * file-ambcond:: Ambiguous Conditions
12891: @end menu
12892:
12893: @c ---------------------------------------------------------------------
12894: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
12895: @subsection Implementation Defined Options
12896: @c ---------------------------------------------------------------------
12897: @cindex implementation-defined options, file words
12898: @cindex file words, implementation-defined options
12899:
12900: @table @i
12901: @item file access methods used:
12902: @cindex file access methods used
12903: @code{R/O}, @code{R/W} and @code{BIN} work as you would
12904: expect. @code{W/O} translates into the C file opening mode @code{w} (or
12905: @code{wb}): The file is cleared, if it exists, and created, if it does
12906: not (with both @code{open-file} and @code{create-file}). Under Unix
12907: @code{create-file} creates a file with 666 permissions modified by your
12908: umask.
12909:
12910: @item file exceptions:
12911: @cindex file exceptions
12912: The file words do not raise exceptions (except, perhaps, memory access
12913: faults when you pass illegal addresses or file-ids).
12914:
12915: @item file line terminator:
12916: @cindex file line terminator
12917: System-dependent. Gforth uses C's newline character as line
12918: terminator. What the actual character code(s) of this are is
12919: system-dependent.
12920:
12921: @item file name format:
12922: @cindex file name format
12923: System dependent. Gforth just uses the file name format of your OS.
12924:
12925: @item information returned by @code{FILE-STATUS}:
12926: @cindex @code{FILE-STATUS}, returned information
12927: @code{FILE-STATUS} returns the most powerful file access mode allowed
12928: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
12929: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
12930: along with the returned mode.
12931:
12932: @item input file state after an exception when including source:
12933: @cindex exception when including source
12934: All files that are left via the exception are closed.
12935:
1.29 crook 12936: @item @i{ior} values and meaning:
12937: @cindex @i{ior} values and meaning
1.68 anton 12938: @cindex @i{wior} values and meaning
1.29 crook 12939: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 12940: intended as throw codes. They typically are in the range
12941: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 12942: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 12943:
12944: @item maximum depth of file input nesting:
12945: @cindex maximum depth of file input nesting
12946: @cindex file input nesting, maximum depth
12947: limited by the amount of return stack, locals/TIB stack, and the number
12948: of open files available. This should not give you troubles.
12949:
12950: @item maximum size of input line:
12951: @cindex maximum size of input line
12952: @cindex input line size, maximum
12953: @code{/line}. Currently 255.
12954:
12955: @item methods of mapping block ranges to files:
12956: @cindex mapping block ranges to files
12957: @cindex files containing blocks
12958: @cindex blocks in files
12959: By default, blocks are accessed in the file @file{blocks.fb} in the
12960: current working directory. The file can be switched with @code{USE}.
12961:
12962: @item number of string buffers provided by @code{S"}:
12963: @cindex @code{S"}, number of string buffers
12964: 1
12965:
12966: @item size of string buffer used by @code{S"}:
12967: @cindex @code{S"}, size of string buffer
12968: @code{/line}. currently 255.
12969:
12970: @end table
12971:
12972: @c ---------------------------------------------------------------------
12973: @node file-ambcond, , file-idef, The optional File-Access word set
12974: @subsection Ambiguous conditions
12975: @c ---------------------------------------------------------------------
12976: @cindex file words, ambiguous conditions
12977: @cindex ambiguous conditions, file words
12978:
12979: @table @i
12980: @item attempting to position a file outside its boundaries:
12981: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
12982: @code{REPOSITION-FILE} is performed as usual: Afterwards,
12983: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
12984:
12985: @item attempting to read from file positions not yet written:
12986: @cindex reading from file positions not yet written
12987: End-of-file, i.e., zero characters are read and no error is reported.
12988:
1.29 crook 12989: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
12990: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 12991: An appropriate exception may be thrown, but a memory fault or other
12992: problem is more probable.
12993:
1.29 crook 12994: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
12995: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
12996: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
12997: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 12998: thrown.
12999:
13000: @item named file cannot be opened (@code{INCLUDED}):
13001: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13002: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13003:
13004: @item requesting an unmapped block number:
13005: @cindex unmapped block numbers
13006: There are no unmapped legal block numbers. On some operating systems,
13007: writing a block with a large number may overflow the file system and
13008: have an error message as consequence.
13009:
13010: @item using @code{source-id} when @code{blk} is non-zero:
13011: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13012: @code{source-id} performs its function. Typically it will give the id of
13013: the source which loaded the block. (Better ideas?)
13014:
13015: @end table
13016:
13017:
13018: @c =====================================================================
13019: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13020: @section The optional Floating-Point word set
13021: @c =====================================================================
13022: @cindex system documentation, floating-point words
13023: @cindex floating-point words, system documentation
13024:
13025: @menu
13026: * floating-idef:: Implementation Defined Options
13027: * floating-ambcond:: Ambiguous Conditions
13028: @end menu
13029:
13030:
13031: @c ---------------------------------------------------------------------
13032: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13033: @subsection Implementation Defined Options
13034: @c ---------------------------------------------------------------------
13035: @cindex implementation-defined options, floating-point words
13036: @cindex floating-point words, implementation-defined options
13037:
13038: @table @i
13039: @item format and range of floating point numbers:
13040: @cindex format and range of floating point numbers
13041: @cindex floating point numbers, format and range
13042: System-dependent; the @code{double} type of C.
13043:
1.29 crook 13044: @item results of @code{REPRESENT} when @i{float} is out of range:
13045: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13046: System dependent; @code{REPRESENT} is implemented using the C library
13047: function @code{ecvt()} and inherits its behaviour in this respect.
13048:
13049: @item rounding or truncation of floating-point numbers:
13050: @cindex rounding of floating-point numbers
13051: @cindex truncation of floating-point numbers
13052: @cindex floating-point numbers, rounding or truncation
13053: System dependent; the rounding behaviour is inherited from the hosting C
13054: compiler. IEEE-FP-based (i.e., most) systems by default round to
13055: nearest, and break ties by rounding to even (i.e., such that the last
13056: bit of the mantissa is 0).
13057:
13058: @item size of floating-point stack:
13059: @cindex floating-point stack size
13060: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13061: the floating-point stack (in floats). You can specify this on startup
13062: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13063:
13064: @item width of floating-point stack:
13065: @cindex floating-point stack width
13066: @code{1 floats}.
13067:
13068: @end table
13069:
13070:
13071: @c ---------------------------------------------------------------------
13072: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13073: @subsection Ambiguous conditions
13074: @c ---------------------------------------------------------------------
13075: @cindex floating-point words, ambiguous conditions
13076: @cindex ambiguous conditions, floating-point words
13077:
13078: @table @i
13079: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13080: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13081: System-dependent. Typically results in a @code{-23 THROW} like other
13082: alignment violations.
13083:
13084: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13085: @cindex @code{f@@} used with an address that is not float aligned
13086: @cindex @code{f!} used with an address that is not float aligned
13087: System-dependent. Typically results in a @code{-23 THROW} like other
13088: alignment violations.
13089:
13090: @item floating-point result out of range:
13091: @cindex floating-point result out of range
1.80 anton 13092: System-dependent. Can result in a @code{-43 throw} (floating point
13093: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13094: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13095: unidentified fault), or can produce a special value representing, e.g.,
13096: Infinity.
13097:
13098: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13099: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13100: System-dependent. Typically results in an alignment fault like other
13101: alignment violations.
13102:
1.35 anton 13103: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13104: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13105: The floating-point number is converted into decimal nonetheless.
13106:
13107: @item Both arguments are equal to zero (@code{FATAN2}):
13108: @cindex @code{FATAN2}, both arguments are equal to zero
13109: System-dependent. @code{FATAN2} is implemented using the C library
13110: function @code{atan2()}.
13111:
1.29 crook 13112: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13113: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13114: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13115: because of small errors and the tan will be a very large (or very small)
13116: but finite number.
13117:
1.29 crook 13118: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13119: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13120: The result is rounded to the nearest float.
13121:
13122: @item dividing by zero:
13123: @cindex dividing by zero, floating-point
13124: @cindex floating-point dividing by zero
13125: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13126: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13127: (floating point divide by zero) or @code{-55 throw} (Floating-point
13128: unidentified fault).
1.1 anton 13129:
13130: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13131: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13132: System dependent. On IEEE-FP based systems the number is converted into
13133: an infinity.
13134:
1.29 crook 13135: @item @i{float}<1 (@code{FACOSH}):
13136: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13137: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13138: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13139:
1.29 crook 13140: @item @i{float}=<-1 (@code{FLNP1}):
13141: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13142: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13143: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13144: negative infinity for @i{float}=-1).
1.1 anton 13145:
1.29 crook 13146: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13147: @cindex @code{FLN}, @i{float}=<0
13148: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13149: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13150: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13151: negative infinity for @i{float}=0).
1.1 anton 13152:
1.29 crook 13153: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13154: @cindex @code{FASINH}, @i{float}<0
13155: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13156: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13157: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13158: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13159: C library?).
1.1 anton 13160:
1.29 crook 13161: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13162: @cindex @code{FACOS}, |@i{float}|>1
13163: @cindex @code{FASIN}, |@i{float}|>1
13164: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13165: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13166: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13167:
1.29 crook 13168: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13169: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13170: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13171: Platform-dependent; typically, some double number is produced and no
13172: error is reported.
1.1 anton 13173:
13174: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13175: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13176: @code{Precision} characters of the numeric output area are used. If
13177: @code{precision} is too high, these words will smash the data or code
13178: close to @code{here}.
1.1 anton 13179: @end table
13180:
13181: @c =====================================================================
13182: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13183: @section The optional Locals word set
13184: @c =====================================================================
13185: @cindex system documentation, locals words
13186: @cindex locals words, system documentation
13187:
13188: @menu
13189: * locals-idef:: Implementation Defined Options
13190: * locals-ambcond:: Ambiguous Conditions
13191: @end menu
13192:
13193:
13194: @c ---------------------------------------------------------------------
13195: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13196: @subsection Implementation Defined Options
13197: @c ---------------------------------------------------------------------
13198: @cindex implementation-defined options, locals words
13199: @cindex locals words, implementation-defined options
13200:
13201: @table @i
13202: @item maximum number of locals in a definition:
13203: @cindex maximum number of locals in a definition
13204: @cindex locals, maximum number in a definition
13205: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13206: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13207: characters. The number of locals in a definition is bounded by the size
13208: of locals-buffer, which contains the names of the locals.
13209:
13210: @end table
13211:
13212:
13213: @c ---------------------------------------------------------------------
13214: @node locals-ambcond, , locals-idef, The optional Locals word set
13215: @subsection Ambiguous conditions
13216: @c ---------------------------------------------------------------------
13217: @cindex locals words, ambiguous conditions
13218: @cindex ambiguous conditions, locals words
13219:
13220: @table @i
13221: @item executing a named local in interpretation state:
13222: @cindex local in interpretation state
13223: @cindex Interpreting a compile-only word, for a local
13224: Locals have no interpretation semantics. If you try to perform the
13225: interpretation semantics, you will get a @code{-14 throw} somewhere
13226: (Interpreting a compile-only word). If you perform the compilation
13227: semantics, the locals access will be compiled (irrespective of state).
13228:
1.29 crook 13229: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13230: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13231: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13232: @cindex Invalid name argument, @code{TO}
13233: @code{-32 throw} (Invalid name argument)
13234:
13235: @end table
13236:
13237:
13238: @c =====================================================================
13239: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13240: @section The optional Memory-Allocation word set
13241: @c =====================================================================
13242: @cindex system documentation, memory-allocation words
13243: @cindex memory-allocation words, system documentation
13244:
13245: @menu
13246: * memory-idef:: Implementation Defined Options
13247: @end menu
13248:
13249:
13250: @c ---------------------------------------------------------------------
13251: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13252: @subsection Implementation Defined Options
13253: @c ---------------------------------------------------------------------
13254: @cindex implementation-defined options, memory-allocation words
13255: @cindex memory-allocation words, implementation-defined options
13256:
13257: @table @i
1.29 crook 13258: @item values and meaning of @i{ior}:
13259: @cindex @i{ior} values and meaning
13260: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13261: intended as throw codes. They typically are in the range
13262: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13263: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13264:
13265: @end table
13266:
13267: @c =====================================================================
13268: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13269: @section The optional Programming-Tools word set
13270: @c =====================================================================
13271: @cindex system documentation, programming-tools words
13272: @cindex programming-tools words, system documentation
13273:
13274: @menu
13275: * programming-idef:: Implementation Defined Options
13276: * programming-ambcond:: Ambiguous Conditions
13277: @end menu
13278:
13279:
13280: @c ---------------------------------------------------------------------
13281: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13282: @subsection Implementation Defined Options
13283: @c ---------------------------------------------------------------------
13284: @cindex implementation-defined options, programming-tools words
13285: @cindex programming-tools words, implementation-defined options
13286:
13287: @table @i
13288: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13289: @cindex @code{;CODE} ending sequence
13290: @cindex @code{CODE} ending sequence
13291: @code{END-CODE}
13292:
13293: @item manner of processing input following @code{;CODE} and @code{CODE}:
13294: @cindex @code{;CODE}, processing input
13295: @cindex @code{CODE}, processing input
13296: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13297: the input is processed by the text interpreter, (starting) in interpret
13298: state.
13299:
13300: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13301: @cindex @code{ASSEMBLER}, search order capability
13302: The ANS Forth search order word set.
13303:
13304: @item source and format of display by @code{SEE}:
13305: @cindex @code{SEE}, source and format of output
1.80 anton 13306: The source for @code{see} is the executable code used by the inner
1.1 anton 13307: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13308: (and on some platforms, assembly code for primitives) as well as
13309: possible.
1.1 anton 13310:
13311: @end table
13312:
13313: @c ---------------------------------------------------------------------
13314: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13315: @subsection Ambiguous conditions
13316: @c ---------------------------------------------------------------------
13317: @cindex programming-tools words, ambiguous conditions
13318: @cindex ambiguous conditions, programming-tools words
13319:
13320: @table @i
13321:
1.21 crook 13322: @item deleting the compilation word list (@code{FORGET}):
13323: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13324: Not implemented (yet).
13325:
1.29 crook 13326: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13327: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13328: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13329: @cindex control-flow stack underflow
13330: This typically results in an @code{abort"} with a descriptive error
13331: message (may change into a @code{-22 throw} (Control structure mismatch)
13332: in the future). You may also get a memory access error. If you are
13333: unlucky, this ambiguous condition is not caught.
13334:
1.29 crook 13335: @item @i{name} can't be found (@code{FORGET}):
13336: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13337: Not implemented (yet).
13338:
1.29 crook 13339: @item @i{name} not defined via @code{CREATE}:
13340: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13341: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13342: the execution semantics of the last defined word no matter how it was
13343: defined.
13344:
13345: @item @code{POSTPONE} applied to @code{[IF]}:
13346: @cindex @code{POSTPONE} applied to @code{[IF]}
13347: @cindex @code{[IF]} and @code{POSTPONE}
13348: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13349: equivalent to @code{[IF]}.
13350:
13351: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13352: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13353: Continue in the same state of conditional compilation in the next outer
13354: input source. Currently there is no warning to the user about this.
13355:
13356: @item removing a needed definition (@code{FORGET}):
13357: @cindex @code{FORGET}, removing a needed definition
13358: Not implemented (yet).
13359:
13360: @end table
13361:
13362:
13363: @c =====================================================================
13364: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13365: @section The optional Search-Order word set
13366: @c =====================================================================
13367: @cindex system documentation, search-order words
13368: @cindex search-order words, system documentation
13369:
13370: @menu
13371: * search-idef:: Implementation Defined Options
13372: * search-ambcond:: Ambiguous Conditions
13373: @end menu
13374:
13375:
13376: @c ---------------------------------------------------------------------
13377: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13378: @subsection Implementation Defined Options
13379: @c ---------------------------------------------------------------------
13380: @cindex implementation-defined options, search-order words
13381: @cindex search-order words, implementation-defined options
13382:
13383: @table @i
13384: @item maximum number of word lists in search order:
13385: @cindex maximum number of word lists in search order
13386: @cindex search order, maximum depth
13387: @code{s" wordlists" environment? drop .}. Currently 16.
13388:
13389: @item minimum search order:
13390: @cindex minimum search order
13391: @cindex search order, minimum
13392: @code{root root}.
13393:
13394: @end table
13395:
13396: @c ---------------------------------------------------------------------
13397: @node search-ambcond, , search-idef, The optional Search-Order word set
13398: @subsection Ambiguous conditions
13399: @c ---------------------------------------------------------------------
13400: @cindex search-order words, ambiguous conditions
13401: @cindex ambiguous conditions, search-order words
13402:
13403: @table @i
1.21 crook 13404: @item changing the compilation word list (during compilation):
13405: @cindex changing the compilation word list (during compilation)
13406: @cindex compilation word list, change before definition ends
13407: The word is entered into the word list that was the compilation word list
1.1 anton 13408: at the start of the definition. Any changes to the name field (e.g.,
13409: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13410: are applied to the latest defined word (as reported by @code{latest} or
13411: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13412:
13413: @item search order empty (@code{previous}):
13414: @cindex @code{previous}, search order empty
1.26 crook 13415: @cindex vocstack empty, @code{previous}
1.1 anton 13416: @code{abort" Vocstack empty"}.
13417:
13418: @item too many word lists in search order (@code{also}):
13419: @cindex @code{also}, too many word lists in search order
1.26 crook 13420: @cindex vocstack full, @code{also}
1.1 anton 13421: @code{abort" Vocstack full"}.
13422:
13423: @end table
13424:
13425: @c ***************************************************************
1.65 anton 13426: @node Standard vs Extensions, Model, ANS conformance, Top
13427: @chapter Should I use Gforth extensions?
13428: @cindex Gforth extensions
13429:
13430: As you read through the rest of this manual, you will see documentation
13431: for @i{Standard} words, and documentation for some appealing Gforth
13432: @i{extensions}. You might ask yourself the question: @i{``Should I
13433: restrict myself to the standard, or should I use the extensions?''}
13434:
13435: The answer depends on the goals you have for the program you are working
13436: on:
13437:
13438: @itemize @bullet
13439:
13440: @item Is it just for yourself or do you want to share it with others?
13441:
13442: @item
13443: If you want to share it, do the others all use Gforth?
13444:
13445: @item
13446: If it is just for yourself, do you want to restrict yourself to Gforth?
13447:
13448: @end itemize
13449:
13450: If restricting the program to Gforth is ok, then there is no reason not
13451: to use extensions. It is still a good idea to keep to the standard
13452: where it is easy, in case you want to reuse these parts in another
13453: program that you want to be portable.
13454:
13455: If you want to be able to port the program to other Forth systems, there
13456: are the following points to consider:
13457:
13458: @itemize @bullet
13459:
13460: @item
13461: Most Forth systems that are being maintained support the ANS Forth
13462: standard. So if your program complies with the standard, it will be
13463: portable among many systems.
13464:
13465: @item
13466: A number of the Gforth extensions can be implemented in ANS Forth using
13467: public-domain files provided in the @file{compat/} directory. These are
13468: mentioned in the text in passing. There is no reason not to use these
13469: extensions, your program will still be ANS Forth compliant; just include
13470: the appropriate compat files with your program.
13471:
13472: @item
13473: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13474: analyse your program and determine what non-Standard words it relies
13475: upon. However, it does not check whether you use standard words in a
13476: non-standard way.
13477:
13478: @item
13479: Some techniques are not standardized by ANS Forth, and are hard or
13480: impossible to implement in a standard way, but can be implemented in
13481: most Forth systems easily, and usually in similar ways (e.g., accessing
13482: word headers). Forth has a rich historical precedent for programmers
13483: taking advantage of implementation-dependent features of their tools
13484: (for example, relying on a knowledge of the dictionary
13485: structure). Sometimes these techniques are necessary to extract every
13486: last bit of performance from the hardware, sometimes they are just a
13487: programming shorthand.
13488:
13489: @item
13490: Does using a Gforth extension save more work than the porting this part
13491: to other Forth systems (if any) will cost?
13492:
13493: @item
13494: Is the additional functionality worth the reduction in portability and
13495: the additional porting problems?
13496:
13497: @end itemize
13498:
13499: In order to perform these consideratios, you need to know what's
13500: standard and what's not. This manual generally states if something is
1.81 anton 13501: non-standard, but the authoritative source is the
13502: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 13503: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
13504: into the thought processes of the technical committee.
13505:
13506: Note also that portability between Forth systems is not the only
13507: portability issue; there is also the issue of portability between
13508: different platforms (processor/OS combinations).
13509:
13510: @c ***************************************************************
13511: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 13512: @chapter Model
13513:
13514: This chapter has yet to be written. It will contain information, on
13515: which internal structures you can rely.
13516:
13517: @c ***************************************************************
13518: @node Integrating Gforth, Emacs and Gforth, Model, Top
13519: @chapter Integrating Gforth into C programs
13520:
13521: This is not yet implemented.
13522:
13523: Several people like to use Forth as scripting language for applications
13524: that are otherwise written in C, C++, or some other language.
13525:
13526: The Forth system ATLAST provides facilities for embedding it into
13527: applications; unfortunately it has several disadvantages: most
13528: importantly, it is not based on ANS Forth, and it is apparently dead
13529: (i.e., not developed further and not supported). The facilities
1.21 crook 13530: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 13531: making the switch should not be hard.
13532:
13533: We also tried to design the interface such that it can easily be
13534: implemented by other Forth systems, so that we may one day arrive at a
13535: standardized interface. Such a standard interface would allow you to
13536: replace the Forth system without having to rewrite C code.
13537:
13538: You embed the Gforth interpreter by linking with the library
13539: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
13540: global symbols in this library that belong to the interface, have the
13541: prefix @code{forth_}. (Global symbols that are used internally have the
13542: prefix @code{gforth_}).
13543:
13544: You can include the declarations of Forth types and the functions and
13545: variables of the interface with @code{#include <forth.h>}.
13546:
13547: Types.
13548:
13549: Variables.
13550:
13551: Data and FP Stack pointer. Area sizes.
13552:
13553: functions.
13554:
13555: forth_init(imagefile)
13556: forth_evaluate(string) exceptions?
13557: forth_goto(address) (or forth_execute(xt)?)
13558: forth_continue() (a corountining mechanism)
13559:
13560: Adding primitives.
13561:
13562: No checking.
13563:
13564: Signals?
13565:
13566: Accessing the Stacks
13567:
1.26 crook 13568: @c ******************************************************************
1.1 anton 13569: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
13570: @chapter Emacs and Gforth
13571: @cindex Emacs and Gforth
13572:
13573: @cindex @file{gforth.el}
13574: @cindex @file{forth.el}
13575: @cindex Rydqvist, Goran
1.107 dvdkhlng 13576: @cindex Kuehling, David
1.1 anton 13577: @cindex comment editing commands
13578: @cindex @code{\}, editing with Emacs
13579: @cindex debug tracer editing commands
13580: @cindex @code{~~}, removal with Emacs
13581: @cindex Forth mode in Emacs
1.107 dvdkhlng 13582:
1.1 anton 13583: Gforth comes with @file{gforth.el}, an improved version of
13584: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 13585: improvements are:
13586:
13587: @itemize @bullet
13588: @item
1.107 dvdkhlng 13589: A better handling of indentation.
13590: @item
13591: A custom hilighting engine for Forth-code.
1.26 crook 13592: @item
13593: Comment paragraph filling (@kbd{M-q})
13594: @item
13595: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
13596: @item
13597: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 13598: @item
13599: Support of the @code{info-lookup} feature for looking up the
13600: documentation of a word.
1.107 dvdkhlng 13601: @item
13602: Support for reading and writing blocks files.
1.26 crook 13603: @end itemize
13604:
1.107 dvdkhlng 13605: To get a basic description of these features, enter Forth mode and
13606: type @kbd{C-h m}.
1.1 anton 13607:
13608: @cindex source location of error or debugging output in Emacs
13609: @cindex error output, finding the source location in Emacs
13610: @cindex debugging output, finding the source location in Emacs
13611: In addition, Gforth supports Emacs quite well: The source code locations
13612: given in error messages, debugging output (from @code{~~}) and failed
13613: assertion messages are in the right format for Emacs' compilation mode
13614: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
13615: Manual}) so the source location corresponding to an error or other
13616: message is only a few keystrokes away (@kbd{C-x `} for the next error,
13617: @kbd{C-c C-c} for the error under the cursor).
13618:
1.107 dvdkhlng 13619: @cindex viewing the documentation of a word in Emacs
13620: @cindex context-sensitive help
13621: Moreover, for words documented in this manual, you can look up the
13622: glossary entry quickly by using @kbd{C-h TAB}
13623: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
13624: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
13625: later and does not work for words containing @code{:}.
13626:
13627: @menu
13628: * Installing gforth.el:: Making Emacs aware of Forth.
13629: * Emacs Tags:: Viewing the source of a word in Emacs.
13630: * Hilighting:: Making Forth code look prettier.
13631: * Auto-Indentation:: Customizing auto-indentation.
13632: * Blocks Files:: Reading and writing blocks files.
13633: @end menu
13634:
13635: @c ----------------------------------
1.109 anton 13636: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 13637: @section Installing gforth.el
13638: @cindex @file{.emacs}
13639: @cindex @file{gforth.el}, installation
13640: To make the features from @file{gforth.el} available in Emacs, add
13641: the following lines to your @file{.emacs} file:
13642:
13643: @example
13644: (autoload 'forth-mode "gforth.el")
13645: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
13646: auto-mode-alist))
13647: (autoload 'forth-block-mode "gforth.el")
13648: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
13649: auto-mode-alist))
13650: (add-hook 'forth-mode-hook (function (lambda ()
13651: ;; customize variables here:
13652: (setq forth-indent-level 4)
13653: (setq forth-minor-indent-level 2)
13654: (setq forth-hilight-level 3)
13655: ;;; ...
13656: )))
13657: @end example
13658:
13659: @c ----------------------------------
13660: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
13661: @section Emacs Tags
1.1 anton 13662: @cindex @file{TAGS} file
13663: @cindex @file{etags.fs}
13664: @cindex viewing the source of a word in Emacs
1.43 anton 13665: @cindex @code{require}, placement in files
13666: @cindex @code{include}, placement in files
1.107 dvdkhlng 13667: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
13668: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 13669: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 13670: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 13671: several tags files at the same time (e.g., one for the Gforth sources
13672: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
13673: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
13674: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 13675: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
13676: with @file{etags.fs}, you should avoid putting definitions both before
13677: and after @code{require} etc., otherwise you will see the same file
13678: visited several times by commands like @code{tags-search}.
1.1 anton 13679:
1.107 dvdkhlng 13680: @c ----------------------------------
13681: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
13682: @section Hilighting
13683: @cindex hilighting Forth code in Emacs
13684: @cindex highlighting Forth code in Emacs
13685: @file{gforth.el} comes with a custom source hilighting engine. When
13686: you open a file in @code{forth-mode}, it will be completely parsed,
13687: assigning faces to keywords, comments, strings etc. While you edit
13688: the file, modified regions get parsed and updated on-the-fly.
13689:
13690: Use the variable `forth-hilight-level' to change the level of
13691: decoration from 0 (no hilighting at all) to 3 (the default). Even if
13692: you set the hilighting level to 0, the parser will still work in the
13693: background, collecting information about whether regions of text are
13694: ``compiled'' or ``interpreted''. Those information are required for
13695: auto-indentation to work properly. Set `forth-disable-parser' to
13696: non-nil if your computer is too slow to handle parsing. This will
13697: have an impact on the smartness of the auto-indentation engine,
13698: though.
13699:
13700: Sometimes Forth sources define new features that should be hilighted,
13701: new control structures, defining-words etc. You can use the variable
13702: `forth-custom-words' to make @code{forth-mode} hilight additional
13703: words and constructs. See the docstring of `forth-words' for details
13704: (in Emacs, type @kbd{C-h v forth-words}).
13705:
13706: `forth-custom-words' is meant to be customized in your
13707: @file{.emacs} file. To customize hilighing in a file-specific manner,
13708: set `forth-local-words' in a local-variables section at the end of
13709: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
13710:
13711: Example:
13712: @example
13713: 0 [IF]
13714: Local Variables:
13715: forth-local-words:
13716: ((("t:") definition-starter (font-lock-keyword-face . 1)
13717: "[ \t\n]" t name (font-lock-function-name-face . 3))
13718: ((";t") definition-ender (font-lock-keyword-face . 1)))
13719: End:
13720: [THEN]
13721: @end example
13722:
13723: @c ----------------------------------
13724: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
13725: @section Auto-Indentation
13726: @cindex auto-indentation of Forth code in Emacs
13727: @cindex indentation of Forth code in Emacs
13728: @code{forth-mode} automatically tries to indent lines in a smart way,
13729: whenever you type @key{TAB} or break a line with @kbd{C-m}.
13730:
13731: Simple customization can be achieved by setting
13732: `forth-indent-level' and `forth-minor-indent-level' in your
13733: @file{.emacs} file. For historical reasons @file{gforth.el} indents
13734: per default by multiples of 4 columns. To use the more traditional
13735: 3-column indentation, add the following lines to your @file{.emacs}:
13736:
13737: @example
13738: (add-hook 'forth-mode-hook (function (lambda ()
13739: ;; customize variables here:
13740: (setq forth-indent-level 3)
13741: (setq forth-minor-indent-level 1)
13742: )))
13743: @end example
13744:
13745: If you want indentation to recognize non-default words, customize it
13746: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
13747: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
13748: v forth-indent-words}).
13749:
13750: To customize indentation in a file-specific manner, set
13751: `forth-local-indent-words' in a local-variables section at the end of
13752: your source file (@pxref{Local Variables in Files, Variables,,emacs,
13753: Emacs Manual}).
13754:
13755: Example:
13756: @example
13757: 0 [IF]
13758: Local Variables:
13759: forth-local-indent-words:
13760: ((("t:") (0 . 2) (0 . 2))
13761: ((";t") (-2 . 0) (0 . -2)))
13762: End:
13763: [THEN]
13764: @end example
13765:
13766: @c ----------------------------------
1.109 anton 13767: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 13768: @section Blocks Files
13769: @cindex blocks files, use with Emacs
13770: @code{forth-mode} Autodetects blocks files by checking whether the
13771: length of the first line exceeds 1023 characters. It then tries to
13772: convert the file into normal text format. When you save the file, it
13773: will be written to disk as normal stream-source file.
13774:
13775: If you want to write blocks files, use @code{forth-blocks-mode}. It
13776: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 13777:
1.107 dvdkhlng 13778: @itemize @bullet
13779: @item
13780: Files are written to disk in blocks file format.
13781: @item
13782: Screen numbers are displayed in the mode line (enumerated beginning
13783: with the value of `forth-block-base')
13784: @item
13785: Warnings are displayed when lines exceed 64 characters.
13786: @item
13787: The beginning of the currently edited block is marked with an
13788: overlay-arrow.
13789: @end itemize
1.41 anton 13790:
1.107 dvdkhlng 13791: There are some restrictions you should be aware of. When you open a
13792: blocks file that contains tabulator or newline characters, these
13793: characters will be translated into spaces when the file is written
13794: back to disk. If tabs or newlines are encountered during blocks file
13795: reading, an error is output to the echo area. So have a look at the
13796: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 13797:
1.107 dvdkhlng 13798: Please consult the docstring of @code{forth-blocks-mode} for more
13799: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 13800:
1.26 crook 13801: @c ******************************************************************
1.1 anton 13802: @node Image Files, Engine, Emacs and Gforth, Top
13803: @chapter Image Files
1.26 crook 13804: @cindex image file
13805: @cindex @file{.fi} files
1.1 anton 13806: @cindex precompiled Forth code
13807: @cindex dictionary in persistent form
13808: @cindex persistent form of dictionary
13809:
13810: An image file is a file containing an image of the Forth dictionary,
13811: i.e., compiled Forth code and data residing in the dictionary. By
13812: convention, we use the extension @code{.fi} for image files.
13813:
13814: @menu
1.18 anton 13815: * Image Licensing Issues:: Distribution terms for images.
13816: * Image File Background:: Why have image files?
1.67 anton 13817: * Non-Relocatable Image Files:: don't always work.
1.18 anton 13818: * Data-Relocatable Image Files:: are better.
1.67 anton 13819: * Fully Relocatable Image Files:: better yet.
1.18 anton 13820: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 13821: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 13822: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 13823: @end menu
13824:
1.18 anton 13825: @node Image Licensing Issues, Image File Background, Image Files, Image Files
13826: @section Image Licensing Issues
13827: @cindex license for images
13828: @cindex image license
13829:
13830: An image created with @code{gforthmi} (@pxref{gforthmi}) or
13831: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
13832: original image; i.e., according to copyright law it is a derived work of
13833: the original image.
13834:
13835: Since Gforth is distributed under the GNU GPL, the newly created image
13836: falls under the GNU GPL, too. In particular, this means that if you
13837: distribute the image, you have to make all of the sources for the image
1.113 anton 13838: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 13839: GNU General Public License (Section 3)}.
13840:
13841: If you create an image with @code{cross} (@pxref{cross.fs}), the image
13842: contains only code compiled from the sources you gave it; if none of
13843: these sources is under the GPL, the terms discussed above do not apply
13844: to the image. However, if your image needs an engine (a gforth binary)
13845: that is under the GPL, you should make sure that you distribute both in
13846: a way that is at most a @emph{mere aggregation}, if you don't want the
13847: terms of the GPL to apply to the image.
13848:
13849: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 13850: @section Image File Background
13851: @cindex image file background
13852:
1.80 anton 13853: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 13854: definitions written in Forth. Since the Forth compiler itself belongs to
13855: those definitions, it is not possible to start the system with the
1.80 anton 13856: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 13857: code as an image file in nearly executable form. When Gforth starts up,
13858: a C routine loads the image file into memory, optionally relocates the
13859: addresses, then sets up the memory (stacks etc.) according to
13860: information in the image file, and (finally) starts executing Forth
13861: code.
1.1 anton 13862:
13863: The image file variants represent different compromises between the
13864: goals of making it easy to generate image files and making them
13865: portable.
13866:
13867: @cindex relocation at run-time
1.26 crook 13868: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 13869: run-time. This avoids many of the complications discussed below (image
13870: files are data relocatable without further ado), but costs performance
13871: (one addition per memory access).
13872:
13873: @cindex relocation at load-time
1.26 crook 13874: By contrast, the Gforth loader performs relocation at image load time. The
13875: loader also has to replace tokens that represent primitive calls with the
1.1 anton 13876: appropriate code-field addresses (or code addresses in the case of
13877: direct threading).
13878:
13879: There are three kinds of image files, with different degrees of
13880: relocatability: non-relocatable, data-relocatable, and fully relocatable
13881: image files.
13882:
13883: @cindex image file loader
13884: @cindex relocating loader
13885: @cindex loader for image files
13886: These image file variants have several restrictions in common; they are
13887: caused by the design of the image file loader:
13888:
13889: @itemize @bullet
13890: @item
13891: There is only one segment; in particular, this means, that an image file
13892: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 13893: them). The contents of the stacks are not represented, either.
1.1 anton 13894:
13895: @item
13896: The only kinds of relocation supported are: adding the same offset to
13897: all cells that represent data addresses; and replacing special tokens
13898: with code addresses or with pieces of machine code.
13899:
13900: If any complex computations involving addresses are performed, the
13901: results cannot be represented in the image file. Several applications that
13902: use such computations come to mind:
13903: @itemize @minus
13904: @item
13905: Hashing addresses (or data structures which contain addresses) for table
13906: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
13907: purpose, you will have no problem, because the hash tables are
13908: recomputed automatically when the system is started. If you use your own
13909: hash tables, you will have to do something similar.
13910:
13911: @item
13912: There's a cute implementation of doubly-linked lists that uses
13913: @code{XOR}ed addresses. You could represent such lists as singly-linked
13914: in the image file, and restore the doubly-linked representation on
13915: startup.@footnote{In my opinion, though, you should think thrice before
13916: using a doubly-linked list (whatever implementation).}
13917:
13918: @item
13919: The code addresses of run-time routines like @code{docol:} cannot be
13920: represented in the image file (because their tokens would be replaced by
13921: machine code in direct threaded implementations). As a workaround,
13922: compute these addresses at run-time with @code{>code-address} from the
13923: executions tokens of appropriate words (see the definitions of
1.80 anton 13924: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 13925:
13926: @item
13927: On many architectures addresses are represented in machine code in some
13928: shifted or mangled form. You cannot put @code{CODE} words that contain
13929: absolute addresses in this form in a relocatable image file. Workarounds
13930: are representing the address in some relative form (e.g., relative to
13931: the CFA, which is present in some register), or loading the address from
13932: a place where it is stored in a non-mangled form.
13933: @end itemize
13934: @end itemize
13935:
13936: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
13937: @section Non-Relocatable Image Files
13938: @cindex non-relocatable image files
1.26 crook 13939: @cindex image file, non-relocatable
1.1 anton 13940:
13941: These files are simple memory dumps of the dictionary. They are specific
13942: to the executable (i.e., @file{gforth} file) they were created
13943: with. What's worse, they are specific to the place on which the
13944: dictionary resided when the image was created. Now, there is no
13945: guarantee that the dictionary will reside at the same place the next
13946: time you start Gforth, so there's no guarantee that a non-relocatable
13947: image will work the next time (Gforth will complain instead of crashing,
13948: though).
13949:
13950: You can create a non-relocatable image file with
13951:
1.44 crook 13952:
1.1 anton 13953: doc-savesystem
13954:
1.44 crook 13955:
1.1 anton 13956: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
13957: @section Data-Relocatable Image Files
13958: @cindex data-relocatable image files
1.26 crook 13959: @cindex image file, data-relocatable
1.1 anton 13960:
13961: These files contain relocatable data addresses, but fixed code addresses
13962: (instead of tokens). They are specific to the executable (i.e.,
13963: @file{gforth} file) they were created with. For direct threading on some
13964: architectures (e.g., the i386), data-relocatable images do not work. You
13965: get a data-relocatable image, if you use @file{gforthmi} with a
13966: Gforth binary that is not doubly indirect threaded (@pxref{Fully
13967: Relocatable Image Files}).
13968:
13969: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
13970: @section Fully Relocatable Image Files
13971: @cindex fully relocatable image files
1.26 crook 13972: @cindex image file, fully relocatable
1.1 anton 13973:
13974: @cindex @file{kern*.fi}, relocatability
13975: @cindex @file{gforth.fi}, relocatability
13976: These image files have relocatable data addresses, and tokens for code
13977: addresses. They can be used with different binaries (e.g., with and
13978: without debugging) on the same machine, and even across machines with
13979: the same data formats (byte order, cell size, floating point
13980: format). However, they are usually specific to the version of Gforth
13981: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
13982: are fully relocatable.
13983:
13984: There are two ways to create a fully relocatable image file:
13985:
13986: @menu
1.29 crook 13987: * gforthmi:: The normal way
1.1 anton 13988: * cross.fs:: The hard way
13989: @end menu
13990:
13991: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
13992: @subsection @file{gforthmi}
13993: @cindex @file{comp-i.fs}
13994: @cindex @file{gforthmi}
13995:
13996: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 13997: image @i{file} that contains everything you would load by invoking
13998: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 13999: @example
1.29 crook 14000: gforthmi @i{file} @i{options}
1.1 anton 14001: @end example
14002:
14003: E.g., if you want to create an image @file{asm.fi} that has the file
14004: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14005: like this:
14006:
14007: @example
14008: gforthmi asm.fi asm.fs
14009: @end example
14010:
1.27 crook 14011: @file{gforthmi} is implemented as a sh script and works like this: It
14012: produces two non-relocatable images for different addresses and then
14013: compares them. Its output reflects this: first you see the output (if
1.62 crook 14014: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14015: files, then you see the output of the comparing program: It displays the
14016: offset used for data addresses and the offset used for code addresses;
1.1 anton 14017: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14018: image files, it displays a line like this:
1.1 anton 14019:
14020: @example
14021: 78DC BFFFFA50 BFFFFA40
14022: @end example
14023:
14024: This means that at offset $78dc from @code{forthstart}, one input image
14025: contains $bffffa50, and the other contains $bffffa40. Since these cells
14026: cannot be represented correctly in the output image, you should examine
14027: these places in the dictionary and verify that these cells are dead
14028: (i.e., not read before they are written).
1.39 anton 14029:
14030: @cindex --application, @code{gforthmi} option
14031: If you insert the option @code{--application} in front of the image file
14032: name, you will get an image that uses the @code{--appl-image} option
14033: instead of the @code{--image-file} option (@pxref{Invoking
14034: Gforth}). When you execute such an image on Unix (by typing the image
14035: name as command), the Gforth engine will pass all options to the image
14036: instead of trying to interpret them as engine options.
1.1 anton 14037:
1.27 crook 14038: If you type @file{gforthmi} with no arguments, it prints some usage
14039: instructions.
14040:
1.1 anton 14041: @cindex @code{savesystem} during @file{gforthmi}
14042: @cindex @code{bye} during @file{gforthmi}
14043: @cindex doubly indirect threaded code
1.44 crook 14044: @cindex environment variables
14045: @cindex @code{GFORTHD} -- environment variable
14046: @cindex @code{GFORTH} -- environment variable
1.1 anton 14047: @cindex @code{gforth-ditc}
1.29 crook 14048: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14049: words @code{savesystem} and @code{bye} must be visible. A special doubly
14050: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14051: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14052: this executable through the environment variable @code{GFORTHD}
14053: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14054: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14055: data-relocatable image (because there is no code address offset). The
14056: normal @file{gforth} executable is used for creating the relocatable
14057: image; you can pass the exact filename of this executable through the
14058: environment variable @code{GFORTH}.
1.1 anton 14059:
14060: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14061: @subsection @file{cross.fs}
14062: @cindex @file{cross.fs}
14063: @cindex cross-compiler
14064: @cindex metacompiler
1.47 crook 14065: @cindex target compiler
1.1 anton 14066:
14067: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14068: programming language (@pxref{Cross Compiler}).
1.1 anton 14069:
1.47 crook 14070: @code{cross} allows you to create image files for machines with
1.1 anton 14071: different data sizes and data formats than the one used for generating
14072: the image file. You can also use it to create an application image that
14073: does not contain a Forth compiler. These features are bought with
14074: restrictions and inconveniences in programming. E.g., addresses have to
14075: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14076: order to make the code relocatable.
14077:
14078:
14079: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14080: @section Stack and Dictionary Sizes
14081: @cindex image file, stack and dictionary sizes
14082: @cindex dictionary size default
14083: @cindex stack size default
14084:
14085: If you invoke Gforth with a command line flag for the size
14086: (@pxref{Invoking Gforth}), the size you specify is stored in the
14087: dictionary. If you save the dictionary with @code{savesystem} or create
14088: an image with @file{gforthmi}, this size will become the default
14089: for the resulting image file. E.g., the following will create a
1.21 crook 14090: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14091:
14092: @example
14093: gforthmi gforth.fi -m 1M
14094: @end example
14095:
14096: In other words, if you want to set the default size for the dictionary
14097: and the stacks of an image, just invoke @file{gforthmi} with the
14098: appropriate options when creating the image.
14099:
14100: @cindex stack size, cache-friendly
14101: Note: For cache-friendly behaviour (i.e., good performance), you should
14102: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14103: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14104: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14105:
14106: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14107: @section Running Image Files
14108: @cindex running image files
14109: @cindex invoking image files
14110: @cindex image file invocation
14111:
14112: @cindex -i, invoke image file
14113: @cindex --image file, invoke image file
1.29 crook 14114: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14115: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14116: @example
1.29 crook 14117: gforth -i @i{image}
1.1 anton 14118: @end example
14119:
14120: @cindex executable image file
1.26 crook 14121: @cindex image file, executable
1.1 anton 14122: If your operating system supports starting scripts with a line of the
14123: form @code{#! ...}, you just have to type the image file name to start
14124: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14125: just a convention). I.e., to run Gforth with the image file @i{image},
14126: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14127: This works because every @code{.fi} file starts with a line of this
14128: format:
14129:
14130: @example
14131: #! /usr/local/bin/gforth-0.4.0 -i
14132: @end example
14133:
14134: The file and pathname for the Gforth engine specified on this line is
14135: the specific Gforth executable that it was built against; i.e. the value
14136: of the environment variable @code{GFORTH} at the time that
14137: @file{gforthmi} was executed.
1.1 anton 14138:
1.27 crook 14139: You can make use of the same shell capability to make a Forth source
14140: file into an executable. For example, if you place this text in a file:
1.26 crook 14141:
14142: @example
14143: #! /usr/local/bin/gforth
14144:
14145: ." Hello, world" CR
14146: bye
14147: @end example
14148:
14149: @noindent
1.27 crook 14150: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14151: directly from the command line. The sequence @code{#!} is used in two
14152: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14153: system@footnote{The Unix kernel actually recognises two types of files:
14154: executable files and files of data, where the data is processed by an
14155: interpreter that is specified on the ``interpreter line'' -- the first
14156: line of the file, starting with the sequence #!. There may be a small
14157: limit (e.g., 32) on the number of characters that may be specified on
14158: the interpreter line.} secondly it is treated as a comment character by
14159: Gforth. Because of the second usage, a space is required between
1.80 anton 14160: @code{#!} and the path to the executable (moreover, some Unixes
14161: require the sequence @code{#! /}).
1.27 crook 14162:
14163: The disadvantage of this latter technique, compared with using
1.80 anton 14164: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14165: compiled on-the-fly, each time the program is invoked.
1.26 crook 14166:
1.1 anton 14167: doc-#!
14168:
1.44 crook 14169:
1.1 anton 14170: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14171: @section Modifying the Startup Sequence
14172: @cindex startup sequence for image file
14173: @cindex image file initialization sequence
14174: @cindex initialization sequence of image file
14175:
14176: You can add your own initialization to the startup sequence through the
1.26 crook 14177: deferred word @code{'cold}. @code{'cold} is invoked just before the
1.80 anton 14178: image-specific command line processing (i.e., loading files and
1.26 crook 14179: evaluating (@code{-e}) strings) starts.
1.1 anton 14180:
14181: A sequence for adding your initialization usually looks like this:
14182:
14183: @example
14184: :noname
14185: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14186: ... \ your stuff
14187: ; IS 'cold
14188: @end example
14189:
14190: @cindex turnkey image files
1.26 crook 14191: @cindex image file, turnkey applications
1.1 anton 14192: You can make a turnkey image by letting @code{'cold} execute a word
14193: (your turnkey application) that never returns; instead, it exits Gforth
14194: via @code{bye} or @code{throw}.
14195:
14196: @cindex command-line arguments, access
14197: @cindex arguments on the command line, access
14198: You can access the (image-specific) command-line arguments through the
1.26 crook 14199: variables @code{argc} and @code{argv}. @code{arg} provides convenient
1.1 anton 14200: access to @code{argv}.
14201:
1.26 crook 14202: If @code{'cold} exits normally, Gforth processes the command-line
14203: arguments as files to be loaded and strings to be evaluated. Therefore,
14204: @code{'cold} should remove the arguments it has used in this case.
14205:
1.44 crook 14206:
14207:
1.26 crook 14208: doc-'cold
1.1 anton 14209: doc-argc
14210: doc-argv
14211: doc-arg
14212:
14213:
1.44 crook 14214:
1.1 anton 14215: @c ******************************************************************
1.113 anton 14216: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14217: @chapter Engine
14218: @cindex engine
14219: @cindex virtual machine
14220:
1.26 crook 14221: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14222: may be helpful for finding your way in the Gforth sources.
14223:
1.109 anton 14224: The ideas in this section have also been published in the following
14225: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14226: Forth-Tagung '93; M. Anton Ertl,
14227: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14228: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14229: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14230: Threaded code variations and optimizations (extended version)}},
14231: Forth-Tagung '02.
1.1 anton 14232:
14233: @menu
14234: * Portability::
14235: * Threading::
14236: * Primitives::
14237: * Performance::
14238: @end menu
14239:
14240: @node Portability, Threading, Engine, Engine
14241: @section Portability
14242: @cindex engine portability
14243:
1.26 crook 14244: An important goal of the Gforth Project is availability across a wide
14245: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14246: achieved this goal by manually coding the engine in assembly language
14247: for several then-popular processors. This approach is very
14248: labor-intensive and the results are short-lived due to progress in
14249: computer architecture.
1.1 anton 14250:
14251: @cindex C, using C for the engine
14252: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14253: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14254: particularly popular for UNIX-based Forths due to the large variety of
14255: architectures of UNIX machines. Unfortunately an implementation in C
14256: does not mix well with the goals of efficiency and with using
14257: traditional techniques: Indirect or direct threading cannot be expressed
14258: in C, and switch threading, the fastest technique available in C, is
14259: significantly slower. Another problem with C is that it is very
14260: cumbersome to express double integer arithmetic.
14261:
14262: @cindex GNU C for the engine
14263: @cindex long long
14264: Fortunately, there is a portable language that does not have these
14265: limitations: GNU C, the version of C processed by the GNU C compiler
14266: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14267: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14268: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14269: threading possible, its @code{long long} type (@pxref{Long Long, ,
14270: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14271: double numbers on many systems. GNU C is freely available on all
1.1 anton 14272: important (and many unimportant) UNIX machines, VMS, 80386s running
14273: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14274: on all these machines.
14275:
14276: Writing in a portable language has the reputation of producing code that
14277: is slower than assembly. For our Forth engine we repeatedly looked at
14278: the code produced by the compiler and eliminated most compiler-induced
14279: inefficiencies by appropriate changes in the source code.
14280:
14281: @cindex explicit register declarations
14282: @cindex --enable-force-reg, configuration flag
14283: @cindex -DFORCE_REG
14284: However, register allocation cannot be portably influenced by the
14285: programmer, leading to some inefficiencies on register-starved
14286: machines. We use explicit register declarations (@pxref{Explicit Reg
14287: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14288: improve the speed on some machines. They are turned on by using the
14289: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14290: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14291: machine, but also on the compiler version: On some machines some
14292: compiler versions produce incorrect code when certain explicit register
14293: declarations are used. So by default @code{-DFORCE_REG} is not used.
14294:
14295: @node Threading, Primitives, Portability, Engine
14296: @section Threading
14297: @cindex inner interpreter implementation
14298: @cindex threaded code implementation
14299:
14300: @cindex labels as values
14301: GNU C's labels as values extension (available since @code{gcc-2.0},
14302: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14303: makes it possible to take the address of @i{label} by writing
14304: @code{&&@i{label}}. This address can then be used in a statement like
14305: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14306: @code{goto x}.
14307:
1.26 crook 14308: @cindex @code{NEXT}, indirect threaded
1.1 anton 14309: @cindex indirect threaded inner interpreter
14310: @cindex inner interpreter, indirect threaded
1.26 crook 14311: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14312: @example
14313: cfa = *ip++;
14314: ca = *cfa;
14315: goto *ca;
14316: @end example
14317: @cindex instruction pointer
14318: For those unfamiliar with the names: @code{ip} is the Forth instruction
14319: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14320: execution token and points to the code field of the next word to be
14321: executed; The @code{ca} (code address) fetched from there points to some
14322: executable code, e.g., a primitive or the colon definition handler
14323: @code{docol}.
14324:
1.26 crook 14325: @cindex @code{NEXT}, direct threaded
1.1 anton 14326: @cindex direct threaded inner interpreter
14327: @cindex inner interpreter, direct threaded
14328: Direct threading is even simpler:
14329: @example
14330: ca = *ip++;
14331: goto *ca;
14332: @end example
14333:
14334: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14335: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14336:
14337: @menu
14338: * Scheduling::
14339: * Direct or Indirect Threaded?::
1.109 anton 14340: * Dynamic Superinstructions::
1.1 anton 14341: * DOES>::
14342: @end menu
14343:
14344: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14345: @subsection Scheduling
14346: @cindex inner interpreter optimization
14347:
14348: There is a little complication: Pipelined and superscalar processors,
14349: i.e., RISC and some modern CISC machines can process independent
14350: instructions while waiting for the results of an instruction. The
14351: compiler usually reorders (schedules) the instructions in a way that
14352: achieves good usage of these delay slots. However, on our first tries
14353: the compiler did not do well on scheduling primitives. E.g., for
14354: @code{+} implemented as
14355: @example
14356: n=sp[0]+sp[1];
14357: sp++;
14358: sp[0]=n;
14359: NEXT;
14360: @end example
1.81 anton 14361: the @code{NEXT} comes strictly after the other code, i.e., there is
14362: nearly no scheduling. After a little thought the problem becomes clear:
14363: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14364: addresses (and the version of @code{gcc} we used would not know it even
14365: if it was possible), so it could not move the load of the cfa above the
14366: store to the TOS. Indeed the pointers could be the same, if code on or
14367: very near the top of stack were executed. In the interest of speed we
14368: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14369: in scheduling: @code{NEXT} is divided into several parts:
14370: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14371: like:
1.1 anton 14372: @example
1.81 anton 14373: NEXT_P0;
1.1 anton 14374: n=sp[0]+sp[1];
14375: sp++;
14376: NEXT_P1;
14377: sp[0]=n;
14378: NEXT_P2;
14379: @end example
14380:
1.81 anton 14381: There are various schemes that distribute the different operations of
14382: NEXT between these parts in several ways; in general, different schemes
14383: perform best on different processors. We use a scheme for most
14384: architectures that performs well for most processors of this
1.109 anton 14385: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14386: the scheme on installation time.
14387:
1.1 anton 14388:
1.109 anton 14389: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14390: @subsection Direct or Indirect Threaded?
14391: @cindex threading, direct or indirect?
14392:
1.109 anton 14393: Threaded forth code consists of references to primitives (simple machine
14394: code routines like @code{+}) and to non-primitives (e.g., colon
14395: definitions, variables, constants); for a specific class of
14396: non-primitives (e.g., variables) there is one code routine (e.g.,
14397: @code{dovar}), but each variable needs a separate reference to its data.
14398:
14399: Traditionally Forth has been implemented as indirect threaded code,
14400: because this allows to use only one cell to reference a non-primitive
14401: (basically you point to the data, and find the code address there).
14402:
14403: @cindex primitive-centric threaded code
14404: However, threaded code in Gforth (since 0.6.0) uses two cells for
14405: non-primitives, one for the code address, and one for the data address;
14406: the data pointer is an immediate argument for the virtual machine
14407: instruction represented by the code address. We call this
14408: @emph{primitive-centric} threaded code, because all code addresses point
14409: to simple primitives. E.g., for a variable, the code address is for
14410: @code{lit} (also used for integer literals like @code{99}).
14411:
14412: Primitive-centric threaded code allows us to use (faster) direct
14413: threading as dispatch method, completely portably (direct threaded code
14414: in Gforth before 0.6.0 required architecture-specific code). It also
14415: eliminates the performance problems related to I-cache consistency that
14416: 386 implementations have with direct threaded code, and allows
14417: additional optimizations.
14418:
14419: @cindex hybrid direct/indirect threaded code
14420: There is a catch, however: the @var{xt} parameter of @code{execute} can
14421: occupy only one cell, so how do we pass non-primitives with their code
14422: @emph{and} data addresses to them? Our answer is to use indirect
14423: threaded dispatch for @code{execute} and other words that use a
14424: single-cell xt. So, normal threaded code in colon definitions uses
14425: direct threading, and @code{execute} and similar words, which dispatch
14426: to xts on the data stack, use indirect threaded code. We call this
14427: @emph{hybrid direct/indirect} threaded code.
14428:
14429: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14430: @cindex gforth engine
14431: @cindex gforth-fast engine
14432: The engines @command{gforth} and @command{gforth-fast} use hybrid
14433: direct/indirect threaded code. This means that with these engines you
14434: cannot use @code{,} to compile an xt. Instead, you have to use
14435: @code{compile,}.
14436:
14437: @cindex gforth-itc engine
1.115 anton 14438: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14439: This engine uses plain old indirect threaded code. It still compiles in
14440: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14441: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14442: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14443: and execute @code{' , is compile,}. Your program can check if it is
14444: running on a hybrid direct/indirect threaded engine or a pure indirect
14445: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14446:
14447:
14448: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14449: @subsection Dynamic Superinstructions
14450: @cindex Dynamic superinstructions with replication
14451: @cindex Superinstructions
14452: @cindex Replication
14453:
14454: The engines @command{gforth} and @command{gforth-fast} use another
14455: optimization: Dynamic superinstructions with replication. As an
14456: example, consider the following colon definition:
14457:
14458: @example
14459: : squared ( n1 -- n2 )
14460: dup * ;
14461: @end example
14462:
14463: Gforth compiles this into the threaded code sequence
14464:
14465: @example
14466: dup
14467: *
14468: ;s
14469: @end example
14470:
14471: In normal direct threaded code there is a code address occupying one
14472: cell for each of these primitives. Each code address points to a
14473: machine code routine, and the interpreter jumps to this machine code in
14474: order to execute the primitive. The routines for these three
14475: primitives are (in @command{gforth-fast} on the 386):
14476:
14477: @example
14478: Code dup
14479: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14480: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14481: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14482: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14483: end-code
14484: Code *
14485: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14486: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14487: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14488: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14489: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14490: end-code
14491: Code ;s
14492: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14493: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14494: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14495: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14496: end-code
14497: @end example
14498:
14499: With dynamic superinstructions and replication the compiler does not
14500: just lay down the threaded code, but also copies the machine code
14501: fragments, usually without the jump at the end.
14502:
14503: @example
14504: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
14505: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
14506: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14507: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14508: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
14509: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
14510: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
14511: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
14512: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
14513: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14514: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14515: @end example
14516:
14517: Only when a threaded-code control-flow change happens (e.g., in
14518: @code{;s}), the jump is appended. This optimization eliminates many of
14519: these jumps and makes the rest much more predictable. The speedup
14520: depends on the processor and the application; on the Athlon and Pentium
14521: III this optimization typically produces a speedup by a factor of 2.
14522:
14523: The code addresses in the direct-threaded code are set to point to the
14524: appropriate points in the copied machine code, in this example like
14525: this:
1.1 anton 14526:
1.109 anton 14527: @example
14528: primitive code address
14529: dup $4057D27D
14530: * $4057D286
14531: ;s $4057D292
14532: @end example
14533:
14534: Thus there can be threaded-code jumps to any place in this piece of
14535: code. This also simplifies decompilation quite a bit.
14536:
14537: @cindex --no-dynamic command-line option
14538: @cindex --no-super command-line option
14539: You can disable this optimization with @option{--no-dynamic}. You can
14540: use the copying without eliminating the jumps (i.e., dynamic
14541: replication, but without superinstructions) with @option{--no-super};
14542: this gives the branch prediction benefit alone; the effect on
1.110 anton 14543: performance depends on the CPU; on the Athlon and Pentium III the
14544: speedup is a little less than for dynamic superinstructions with
14545: replication.
14546:
14547: @cindex patching threaded code
14548: One use of these options is if you want to patch the threaded code.
14549: With superinstructions, many of the dispatch jumps are eliminated, so
14550: patching often has no effect. These options preserve all the dispatch
14551: jumps.
1.109 anton 14552:
14553: @cindex --dynamic command-line option
1.110 anton 14554: On some machines dynamic superinstructions are disabled by default,
14555: because it is unsafe on these machines. However, if you feel
14556: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 14557:
14558: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 14559: @subsection DOES>
14560: @cindex @code{DOES>} implementation
14561:
1.26 crook 14562: @cindex @code{dodoes} routine
14563: @cindex @code{DOES>}-code
1.1 anton 14564: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
14565: the chunk of code executed by every word defined by a
1.109 anton 14566: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
14567: this is only needed if the xt of the word is @code{execute}d. The main
14568: problem here is: How to find the Forth code to be executed, i.e. the
14569: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
14570: solutions:
1.1 anton 14571:
1.21 crook 14572: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 14573: @code{DOES>}-code address is stored in the cell after the code address
14574: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
14575: illegal in the Forth-79 and all later standards, because in fig-Forth
14576: this address lies in the body (which is illegal in these
14577: standards). However, by making the code field larger for all words this
14578: solution becomes legal again. We use this approach. Leaving a cell
14579: unused in most words is a bit wasteful, but on the machines we are
14580: targeting this is hardly a problem.
14581:
1.1 anton 14582:
14583: @node Primitives, Performance, Threading, Engine
14584: @section Primitives
14585: @cindex primitives, implementation
14586: @cindex virtual machine instructions, implementation
14587:
14588: @menu
14589: * Automatic Generation::
14590: * TOS Optimization::
14591: * Produced code::
14592: @end menu
14593:
14594: @node Automatic Generation, TOS Optimization, Primitives, Primitives
14595: @subsection Automatic Generation
14596: @cindex primitives, automatic generation
14597:
14598: @cindex @file{prims2x.fs}
1.109 anton 14599:
1.1 anton 14600: Since the primitives are implemented in a portable language, there is no
14601: longer any need to minimize the number of primitives. On the contrary,
14602: having many primitives has an advantage: speed. In order to reduce the
14603: number of errors in primitives and to make programming them easier, we
1.109 anton 14604: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
14605: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
14606: generates most (and sometimes all) of the C code for a primitive from
14607: the stack effect notation. The source for a primitive has the following
14608: form:
1.1 anton 14609:
14610: @cindex primitive source format
14611: @format
1.58 anton 14612: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 14613: [@code{""}@i{glossary entry}@code{""}]
14614: @i{C code}
1.1 anton 14615: [@code{:}
1.29 crook 14616: @i{Forth code}]
1.1 anton 14617: @end format
14618:
14619: The items in brackets are optional. The category and glossary fields
14620: are there for generating the documentation, the Forth code is there
14621: for manual implementations on machines without GNU C. E.g., the source
14622: for the primitive @code{+} is:
14623: @example
1.58 anton 14624: + ( n1 n2 -- n ) core plus
1.1 anton 14625: n = n1+n2;
14626: @end example
14627:
14628: This looks like a specification, but in fact @code{n = n1+n2} is C
14629: code. Our primitive generation tool extracts a lot of information from
14630: the stack effect notations@footnote{We use a one-stack notation, even
14631: though we have separate data and floating-point stacks; The separate
14632: notation can be generated easily from the unified notation.}: The number
14633: of items popped from and pushed on the stack, their type, and by what
14634: name they are referred to in the C code. It then generates a C code
14635: prelude and postlude for each primitive. The final C code for @code{+}
14636: looks like this:
14637:
14638: @example
1.46 pazsan 14639: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 14640: /* */ /* documentation */
1.81 anton 14641: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 14642: @{
14643: DEF_CA /* definition of variable ca (indirect threading) */
14644: Cell n1; /* definitions of variables */
14645: Cell n2;
14646: Cell n;
1.81 anton 14647: NEXT_P0; /* NEXT part 0 */
1.1 anton 14648: n1 = (Cell) sp[1]; /* input */
14649: n2 = (Cell) TOS;
14650: sp += 1; /* stack adjustment */
14651: @{
14652: n = n1+n2; /* C code taken from the source */
14653: @}
14654: NEXT_P1; /* NEXT part 1 */
14655: TOS = (Cell)n; /* output */
14656: NEXT_P2; /* NEXT part 2 */
14657: @}
14658: @end example
14659:
14660: This looks long and inefficient, but the GNU C compiler optimizes quite
14661: well and produces optimal code for @code{+} on, e.g., the R3000 and the
14662: HP RISC machines: Defining the @code{n}s does not produce any code, and
14663: using them as intermediate storage also adds no cost.
14664:
1.26 crook 14665: There are also other optimizations that are not illustrated by this
14666: example: assignments between simple variables are usually for free (copy
1.1 anton 14667: propagation). If one of the stack items is not used by the primitive
14668: (e.g. in @code{drop}), the compiler eliminates the load from the stack
14669: (dead code elimination). On the other hand, there are some things that
14670: the compiler does not do, therefore they are performed by
14671: @file{prims2x.fs}: The compiler does not optimize code away that stores
14672: a stack item to the place where it just came from (e.g., @code{over}).
14673:
14674: While programming a primitive is usually easy, there are a few cases
14675: where the programmer has to take the actions of the generator into
14676: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 14677: fall through to @code{NEXT}.
1.109 anton 14678:
14679: For more information
1.1 anton 14680:
14681: @node TOS Optimization, Produced code, Automatic Generation, Primitives
14682: @subsection TOS Optimization
14683: @cindex TOS optimization for primitives
14684: @cindex primitives, keeping the TOS in a register
14685:
14686: An important optimization for stack machine emulators, e.g., Forth
14687: engines, is keeping one or more of the top stack items in
1.29 crook 14688: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
14689: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 14690: @itemize @bullet
14691: @item
1.29 crook 14692: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 14693: due to fewer loads from and stores to the stack.
1.29 crook 14694: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
14695: @i{y<n}, due to additional moves between registers.
1.1 anton 14696: @end itemize
14697:
14698: @cindex -DUSE_TOS
14699: @cindex -DUSE_NO_TOS
14700: In particular, keeping one item in a register is never a disadvantage,
14701: if there are enough registers. Keeping two items in registers is a
14702: disadvantage for frequent words like @code{?branch}, constants,
14703: variables, literals and @code{i}. Therefore our generator only produces
14704: code that keeps zero or one items in registers. The generated C code
14705: covers both cases; the selection between these alternatives is made at
14706: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
14707: code for @code{+} is just a simple variable name in the one-item case,
14708: otherwise it is a macro that expands into @code{sp[0]}. Note that the
14709: GNU C compiler tries to keep simple variables like @code{TOS} in
14710: registers, and it usually succeeds, if there are enough registers.
14711:
14712: @cindex -DUSE_FTOS
14713: @cindex -DUSE_NO_FTOS
14714: The primitive generator performs the TOS optimization for the
14715: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
14716: operations the benefit of this optimization is even larger:
14717: floating-point operations take quite long on most processors, but can be
14718: performed in parallel with other operations as long as their results are
14719: not used. If the FP-TOS is kept in a register, this works. If
14720: it is kept on the stack, i.e., in memory, the store into memory has to
14721: wait for the result of the floating-point operation, lengthening the
14722: execution time of the primitive considerably.
14723:
14724: The TOS optimization makes the automatic generation of primitives a
14725: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
14726: @code{TOS} is not sufficient. There are some special cases to
14727: consider:
14728: @itemize @bullet
14729: @item In the case of @code{dup ( w -- w w )} the generator must not
14730: eliminate the store to the original location of the item on the stack,
14731: if the TOS optimization is turned on.
14732: @item Primitives with stack effects of the form @code{--}
1.29 crook 14733: @i{out1}...@i{outy} must store the TOS to the stack at the start.
14734: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 14735: must load the TOS from the stack at the end. But for the null stack
14736: effect @code{--} no stores or loads should be generated.
14737: @end itemize
14738:
14739: @node Produced code, , TOS Optimization, Primitives
14740: @subsection Produced code
14741: @cindex primitives, assembly code listing
14742:
14743: @cindex @file{engine.s}
14744: To see what assembly code is produced for the primitives on your machine
14745: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 14746: look at the resulting file @file{engine.s}. Alternatively, you can also
14747: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 14748:
14749: @node Performance, , Primitives, Engine
14750: @section Performance
14751: @cindex performance of some Forth interpreters
14752: @cindex engine performance
14753: @cindex benchmarking Forth systems
14754: @cindex Gforth performance
14755:
14756: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 14757: impossible to write a significantly faster threaded-code engine.
1.1 anton 14758:
14759: On register-starved machines like the 386 architecture processors
14760: improvements are possible, because @code{gcc} does not utilize the
14761: registers as well as a human, even with explicit register declarations;
14762: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
14763: and hand-tuned it for the 486; this system is 1.19 times faster on the
14764: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 14765: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
14766: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
14767: registers fit in real registers (and we can even afford to use the TOS
14768: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 14769: earlier results. And dynamic superinstructions provide another speedup
14770: (but only around a factor 1.2 on the 486).
1.1 anton 14771:
14772: @cindex Win32Forth performance
14773: @cindex NT Forth performance
14774: @cindex eforth performance
14775: @cindex ThisForth performance
14776: @cindex PFE performance
14777: @cindex TILE performance
1.81 anton 14778: The potential advantage of assembly language implementations is not
1.112 anton 14779: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 14780: (direct threaded, compiled with @code{gcc-2.95.1} and
14781: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
14782: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
14783: (with and without peephole (aka pinhole) optimization of the threaded
14784: code); all these systems were written in assembly language. We also
14785: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
14786: with @code{gcc-2.6.3} with the default configuration for Linux:
14787: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
14788: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
14789: employs peephole optimization of the threaded code) and TILE (compiled
14790: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
14791: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
14792: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
14793: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
14794: then extended it to run the benchmarks, added the peephole optimizer,
14795: ran the benchmarks and reported the results.
1.40 anton 14796:
1.1 anton 14797: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
14798: matrix multiplication come from the Stanford integer benchmarks and have
14799: been translated into Forth by Martin Fraeman; we used the versions
14800: included in the TILE Forth package, but with bigger data set sizes; and
14801: a recursive Fibonacci number computation for benchmarking calling
14802: performance. The following table shows the time taken for the benchmarks
14803: scaled by the time taken by Gforth (in other words, it shows the speedup
14804: factor that Gforth achieved over the other systems).
14805:
14806: @example
1.112 anton 14807: relative Win32- NT eforth This-
14808: time Gforth Forth Forth eforth +opt PFE Forth TILE
14809: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
14810: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
14811: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
14812: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 14813: @end example
14814:
1.26 crook 14815: You may be quite surprised by the good performance of Gforth when
14816: compared with systems written in assembly language. One important reason
14817: for the disappointing performance of these other systems is probably
14818: that they are not written optimally for the 486 (e.g., they use the
14819: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
14820: but costly method for relocating the Forth image: like @code{cforth}, it
14821: computes the actual addresses at run time, resulting in two address
14822: computations per @code{NEXT} (@pxref{Image File Background}).
14823:
1.1 anton 14824: The speedup of Gforth over PFE, ThisForth and TILE can be easily
14825: explained with the self-imposed restriction of the latter systems to
14826: standard C, which makes efficient threading impossible (however, the
1.4 anton 14827: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 14828: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
14829: Moreover, current C compilers have a hard time optimizing other aspects
14830: of the ThisForth and the TILE source.
14831:
1.26 crook 14832: The performance of Gforth on 386 architecture processors varies widely
14833: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
14834: allocate any of the virtual machine registers into real machine
14835: registers by itself and would not work correctly with explicit register
1.112 anton 14836: declarations, giving a significantly slower engine (on a 486DX2/66
14837: running the Sieve) than the one measured above.
1.1 anton 14838:
1.26 crook 14839: Note that there have been several releases of Win32Forth since the
14840: release presented here, so the results presented above may have little
1.40 anton 14841: predictive value for the performance of Win32Forth today (results for
14842: the current release on an i486DX2/66 are welcome).
1.1 anton 14843:
14844: @cindex @file{Benchres}
1.66 anton 14845: In
14846: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
14847: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 14848: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 14849: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
14850: several native code systems; that version of Gforth is slower on a 486
1.112 anton 14851: than the version used here. You can find a newer version of these
14852: measurements at
1.47 crook 14853: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 14854: find numbers for Gforth on various machines in @file{Benchres}.
14855:
1.26 crook 14856: @c ******************************************************************
1.113 anton 14857: @c @node Binding to System Library, Cross Compiler, Engine, Top
14858: @c @chapter Binding to System Library
1.13 pazsan 14859:
1.113 anton 14860: @c ****************************************************************
14861: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 14862: @chapter Cross Compiler
1.47 crook 14863: @cindex @file{cross.fs}
14864: @cindex cross-compiler
14865: @cindex metacompiler
14866: @cindex target compiler
1.13 pazsan 14867:
1.46 pazsan 14868: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
14869: mostly written in Forth, including crucial parts like the outer
14870: interpreter and compiler, it needs compiled Forth code to get
14871: started. The cross compiler allows to create new images for other
14872: architectures, even running under another Forth system.
1.13 pazsan 14873:
14874: @menu
1.67 anton 14875: * Using the Cross Compiler::
14876: * How the Cross Compiler Works::
1.13 pazsan 14877: @end menu
14878:
1.21 crook 14879: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 14880: @section Using the Cross Compiler
1.46 pazsan 14881:
14882: The cross compiler uses a language that resembles Forth, but isn't. The
14883: main difference is that you can execute Forth code after definition,
14884: while you usually can't execute the code compiled by cross, because the
14885: code you are compiling is typically for a different computer than the
14886: one you are compiling on.
14887:
1.81 anton 14888: @c anton: This chapter is somewhat different from waht I would expect: I
14889: @c would expect an explanation of the cross language and how to create an
14890: @c application image with it. The section explains some aspects of
14891: @c creating a Gforth kernel.
14892:
1.46 pazsan 14893: The Makefile is already set up to allow you to create kernels for new
14894: architectures with a simple make command. The generic kernels using the
14895: GCC compiled virtual machine are created in the normal build process
14896: with @code{make}. To create a embedded Gforth executable for e.g. the
14897: 8086 processor (running on a DOS machine), type
14898:
14899: @example
14900: make kernl-8086.fi
14901: @end example
14902:
14903: This will use the machine description from the @file{arch/8086}
14904: directory to create a new kernel. A machine file may look like that:
14905:
14906: @example
14907: \ Parameter for target systems 06oct92py
14908:
14909: 4 Constant cell \ cell size in bytes
14910: 2 Constant cell<< \ cell shift to bytes
14911: 5 Constant cell>bit \ cell shift to bits
14912: 8 Constant bits/char \ bits per character
14913: 8 Constant bits/byte \ bits per byte [default: 8]
14914: 8 Constant float \ bytes per float
14915: 8 Constant /maxalign \ maximum alignment in bytes
14916: false Constant bigendian \ byte order
14917: ( true=big, false=little )
14918:
14919: include machpc.fs \ feature list
14920: @end example
14921:
14922: This part is obligatory for the cross compiler itself, the feature list
14923: is used by the kernel to conditionally compile some features in and out,
14924: depending on whether the target supports these features.
14925:
14926: There are some optional features, if you define your own primitives,
14927: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 14928: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 14929: @code{prims-include} includes primitives, and @code{>boot} prepares for
14930: booting.
14931:
14932: @example
14933: : asm-include ." Include assembler" cr
14934: s" arch/8086/asm.fs" included ;
14935:
14936: : prims-include ." Include primitives" cr
14937: s" arch/8086/prim.fs" included ;
14938:
14939: : >boot ." Prepare booting" cr
14940: s" ' boot >body into-forth 1+ !" evaluate ;
14941: @end example
14942:
14943: These words are used as sort of macro during the cross compilation in
1.81 anton 14944: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 14945: be possible --- but more complicated --- to write a new kernel project
14946: file, too.
14947:
14948: @file{kernel/main.fs} expects the machine description file name on the
14949: stack; the cross compiler itself (@file{cross.fs}) assumes that either
14950: @code{mach-file} leaves a counted string on the stack, or
14951: @code{machine-file} leaves an address, count pair of the filename on the
14952: stack.
14953:
14954: The feature list is typically controlled using @code{SetValue}, generic
14955: files that are used by several projects can use @code{DefaultValue}
14956: instead. Both functions work like @code{Value}, when the value isn't
14957: defined, but @code{SetValue} works like @code{to} if the value is
14958: defined, and @code{DefaultValue} doesn't set anything, if the value is
14959: defined.
14960:
14961: @example
14962: \ generic mach file for pc gforth 03sep97jaw
14963:
14964: true DefaultValue NIL \ relocating
14965:
14966: >ENVIRON
14967:
14968: true DefaultValue file \ controls the presence of the
14969: \ file access wordset
14970: true DefaultValue OS \ flag to indicate a operating system
14971:
14972: true DefaultValue prims \ true: primitives are c-code
14973:
14974: true DefaultValue floating \ floating point wordset is present
14975:
14976: true DefaultValue glocals \ gforth locals are present
14977: \ will be loaded
14978: true DefaultValue dcomps \ double number comparisons
14979:
14980: true DefaultValue hash \ hashing primitives are loaded/present
14981:
14982: true DefaultValue xconds \ used together with glocals,
14983: \ special conditionals supporting gforths'
14984: \ local variables
14985: true DefaultValue header \ save a header information
14986:
14987: true DefaultValue backtrace \ enables backtrace code
14988:
14989: false DefaultValue ec
14990: false DefaultValue crlf
14991:
14992: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
14993:
14994: &16 KB DefaultValue stack-size
14995: &15 KB &512 + DefaultValue fstack-size
14996: &15 KB DefaultValue rstack-size
14997: &14 KB &512 + DefaultValue lstack-size
14998: @end example
1.13 pazsan 14999:
1.48 anton 15000: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15001: @section How the Cross Compiler Works
1.13 pazsan 15002:
15003: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15004: @appendix Bugs
1.1 anton 15005: @cindex bug reporting
15006:
1.21 crook 15007: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15008:
1.103 anton 15009: If you find a bug, please submit a bug report through
15010: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15011:
15012: @itemize @bullet
15013: @item
1.81 anton 15014: A program (or a sequence of keyboard commands) that reproduces the bug.
15015: @item
15016: A description of what you think constitutes the buggy behaviour.
15017: @item
1.21 crook 15018: The Gforth version used (it is announced at the start of an
15019: interactive Gforth session).
15020: @item
15021: The machine and operating system (on Unix
15022: systems @code{uname -a} will report this information).
15023: @item
1.81 anton 15024: The installation options (you can find the configure options at the
15025: start of @file{config.status}) and configuration (@code{configure}
15026: output or @file{config.cache}).
1.21 crook 15027: @item
15028: A complete list of changes (if any) you (or your installer) have made to the
15029: Gforth sources.
15030: @end itemize
1.1 anton 15031:
15032: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15033: to Report Bugs, gcc.info, GNU C Manual}.
15034:
15035:
1.21 crook 15036: @node Origin, Forth-related information, Bugs, Top
15037: @appendix Authors and Ancestors of Gforth
1.1 anton 15038:
15039: @section Authors and Contributors
15040: @cindex authors of Gforth
15041: @cindex contributors to Gforth
15042:
15043: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15044: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15045: lot to the manual. Assemblers and disassemblers were contributed by
15046: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15047: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15048: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15049: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15050: support for calling C libraries. Helpful comments also came from Paul
15051: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15052: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15053: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15054: Gforth-0.2.1 there were also helpful comments from many others; thank
15055: you all, sorry for not listing you here (but digging through my mailbox
15056: to extract your names is on my to-do list).
1.1 anton 15057:
15058: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15059: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15060: was developed across the Internet, and its authors did not meet
1.20 pazsan 15061: physically for the first 4 years of development.
1.1 anton 15062:
15063: @section Pedigree
1.26 crook 15064: @cindex pedigree of Gforth
1.1 anton 15065:
1.81 anton 15066: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15067: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15068:
1.20 pazsan 15069: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15070: 32 bit native code version of VolksForth for the Atari ST, written
15071: mostly by Dietrich Weineck.
15072:
1.81 anton 15073: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15074: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
15075: the mid-80s and ported to the Atari ST in 1986. It descends from F83.
1.1 anton 15076:
15077: Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15078: Forth-83 standard. !! Pedigree? When?
15079:
15080: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15081: 1979. Robert Selzer and Bill Ragsdale developed the original
15082: implementation of fig-Forth for the 6502 based on microForth.
15083:
15084: The principal architect of microForth was Dean Sanderson. microForth was
15085: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15086: the 1802, and subsequently implemented on the 8080, the 6800 and the
15087: Z80.
15088:
15089: All earlier Forth systems were custom-made, usually by Charles Moore,
15090: who discovered (as he puts it) Forth during the late 60s. The first full
15091: Forth existed in 1971.
15092:
1.81 anton 15093: A part of the information in this section comes from
15094: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15095: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
15096: Charles H. Moore, presented at the HOPL-II conference and preprinted in
15097: SIGPLAN Notices 28(3), 1993. You can find more historical and
15098: genealogical information about Forth there.
1.1 anton 15099:
1.81 anton 15100: @c ------------------------------------------------------------------
1.113 anton 15101: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15102: @appendix Other Forth-related information
15103: @cindex Forth-related information
15104:
1.81 anton 15105: @c anton: I threw most of this stuff out, because it can be found through
15106: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15107:
15108: @cindex comp.lang.forth
15109: @cindex frequently asked questions
1.81 anton 15110: There is an active news group (comp.lang.forth) discussing Forth
15111: (including Gforth) and Forth-related issues. Its
15112: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15113: (frequently asked questions and their answers) contains a lot of
15114: information on Forth. You should read it before posting to
15115: comp.lang.forth.
1.21 crook 15116:
1.81 anton 15117: The ANS Forth standard is most usable in its
15118: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15119:
1.113 anton 15120: @c ---------------------------------------------------
15121: @node Licenses, Word Index, Forth-related information, Top
15122: @appendix Licenses
15123:
15124: @menu
15125: * GNU Free Documentation License:: License for copying this manual.
15126: * Copying:: GPL (for copying this software).
15127: @end menu
15128:
15129: @include fdl.texi
15130:
15131: @include gpl.texi
15132:
15133:
15134:
1.81 anton 15135: @c ------------------------------------------------------------------
1.113 anton 15136: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15137: @unnumbered Word Index
15138:
1.26 crook 15139: This index is a list of Forth words that have ``glossary'' entries
15140: within this manual. Each word is listed with its stack effect and
15141: wordset.
1.1 anton 15142:
15143: @printindex fn
15144:
1.81 anton 15145: @c anton: the name index seems superfluous given the word and concept indices.
15146:
15147: @c @node Name Index, Concept Index, Word Index, Top
15148: @c @unnumbered Name Index
1.41 anton 15149:
1.81 anton 15150: @c This index is a list of Forth words that have ``glossary'' entries
15151: @c within this manual.
1.41 anton 15152:
1.81 anton 15153: @c @printindex ky
1.41 anton 15154:
1.113 anton 15155: @c -------------------------------------------------------
1.81 anton 15156: @node Concept Index, , Word Index, Top
1.1 anton 15157: @unnumbered Concept and Word Index
15158:
1.26 crook 15159: Not all entries listed in this index are present verbatim in the
15160: text. This index also duplicates, in abbreviated form, all of the words
15161: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15162:
15163: @printindex cp
15164:
15165: @bye
1.81 anton 15166:
15167:
1.1 anton 15168:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>