Annotation of gforth/doc/gforth.ds, revision 1.156
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.142 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.87 anton 177: * Files Tutorial::
1.48 anton 178: * Interpretation and Compilation Semantics and Immediacy Tutorial::
179: * Execution Tokens Tutorial::
180: * Exceptions Tutorial::
181: * Defining Words Tutorial::
182: * Arrays and Records Tutorial::
183: * POSTPONE Tutorial::
184: * Literal Tutorial::
185: * Advanced macros Tutorial::
186: * Compilation Tokens Tutorial::
187: * Wordlists and Search Order Tutorial::
1.29 crook 188:
1.24 anton 189: An Introduction to ANS Forth
190:
1.67 anton 191: * Introducing the Text Interpreter::
192: * Stacks and Postfix notation::
193: * Your first definition::
194: * How does that work?::
195: * Forth is written in Forth::
196: * Review - elements of a Forth system::
197: * Where to go next::
198: * Exercises::
1.24 anton 199:
1.12 anton 200: Forth Words
201:
202: * Notation::
1.65 anton 203: * Case insensitivity::
204: * Comments::
205: * Boolean Flags::
1.12 anton 206: * Arithmetic::
207: * Stack Manipulation::
208: * Memory::
209: * Control Structures::
210: * Defining Words::
1.65 anton 211: * Interpretation and Compilation Semantics::
1.47 crook 212: * Tokens for Words::
1.81 anton 213: * Compiling words::
1.65 anton 214: * The Text Interpreter::
1.111 anton 215: * The Input Stream::
1.65 anton 216: * Word Lists::
217: * Environmental Queries::
1.12 anton 218: * Files::
219: * Blocks::
220: * Other I/O::
1.121 anton 221: * OS command line arguments::
1.78 anton 222: * Locals::
223: * Structures::
224: * Object-oriented Forth::
1.12 anton 225: * Programming Tools::
1.150 anton 226: * C Interface::
1.12 anton 227: * Assembler and Code Words::
228: * Threading Words::
1.65 anton 229: * Passing Commands to the OS::
230: * Keeping track of Time::
231: * Miscellaneous Words::
1.12 anton 232:
233: Arithmetic
234:
235: * Single precision::
1.67 anton 236: * Double precision:: Double-cell integer arithmetic
1.12 anton 237: * Bitwise operations::
1.67 anton 238: * Numeric comparison::
1.32 anton 239: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 240: * Floating Point::
241:
242: Stack Manipulation
243:
244: * Data stack::
245: * Floating point stack::
246: * Return stack::
247: * Locals stack::
248: * Stack pointer manipulation::
249:
250: Memory
251:
1.32 anton 252: * Memory model::
253: * Dictionary allocation::
254: * Heap Allocation::
255: * Memory Access::
256: * Address arithmetic::
257: * Memory Blocks::
1.12 anton 258:
259: Control Structures
260:
1.41 anton 261: * Selection:: IF ... ELSE ... ENDIF
262: * Simple Loops:: BEGIN ...
1.32 anton 263: * Counted Loops:: DO
1.67 anton 264: * Arbitrary control structures::
265: * Calls and returns::
1.12 anton 266: * Exception Handling::
267:
268: Defining Words
269:
1.67 anton 270: * CREATE::
1.44 crook 271: * Variables:: Variables and user variables
1.67 anton 272: * Constants::
1.44 crook 273: * Values:: Initialised variables
1.67 anton 274: * Colon Definitions::
1.44 crook 275: * Anonymous Definitions:: Definitions without names
1.71 anton 276: * Supplying names:: Passing definition names as strings
1.67 anton 277: * User-defined Defining Words::
1.44 crook 278: * Deferred words:: Allow forward references
1.67 anton 279: * Aliases::
1.47 crook 280:
1.63 anton 281: User-defined Defining Words
282:
283: * CREATE..DOES> applications::
284: * CREATE..DOES> details::
285: * Advanced does> usage example::
1.155 anton 286: * Const-does>::
1.63 anton 287:
1.47 crook 288: Interpretation and Compilation Semantics
289:
1.67 anton 290: * Combined words::
1.12 anton 291:
1.71 anton 292: Tokens for Words
293:
294: * Execution token:: represents execution/interpretation semantics
295: * Compilation token:: represents compilation semantics
296: * Name token:: represents named words
297:
1.82 anton 298: Compiling words
299:
300: * Literals:: Compiling data values
301: * Macros:: Compiling words
302:
1.21 crook 303: The Text Interpreter
304:
1.67 anton 305: * Input Sources::
306: * Number Conversion::
307: * Interpret/Compile states::
308: * Interpreter Directives::
1.21 crook 309:
1.26 crook 310: Word Lists
311:
1.75 anton 312: * Vocabularies::
1.67 anton 313: * Why use word lists?::
1.75 anton 314: * Word list example::
1.26 crook 315:
316: Files
317:
1.48 anton 318: * Forth source files::
319: * General files::
320: * Search Paths::
321:
322: Search Paths
323:
1.75 anton 324: * Source Search Paths::
1.26 crook 325: * General Search Paths::
326:
327: Other I/O
328:
1.32 anton 329: * Simple numeric output:: Predefined formats
330: * Formatted numeric output:: Formatted (pictured) output
331: * String Formats:: How Forth stores strings in memory
1.67 anton 332: * Displaying characters and strings:: Other stuff
1.32 anton 333: * Input:: Input
1.112 anton 334: * Pipes:: How to create your own pipes
1.149 pazsan 335: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 336:
337: Locals
338:
339: * Gforth locals::
340: * ANS Forth locals::
341:
342: Gforth locals
343:
344: * Where are locals visible by name?::
345: * How long do locals live?::
1.78 anton 346: * Locals programming style::
347: * Locals implementation::
1.26 crook 348:
1.12 anton 349: Structures
350:
351: * Why explicit structure support?::
352: * Structure Usage::
353: * Structure Naming Convention::
354: * Structure Implementation::
355: * Structure Glossary::
356:
357: Object-oriented Forth
358:
1.48 anton 359: * Why object-oriented programming?::
360: * Object-Oriented Terminology::
361: * Objects::
362: * OOF::
363: * Mini-OOF::
1.23 crook 364: * Comparison with other object models::
1.12 anton 365:
1.24 anton 366: The @file{objects.fs} model
1.12 anton 367:
368: * Properties of the Objects model::
369: * Basic Objects Usage::
1.41 anton 370: * The Objects base class::
1.12 anton 371: * Creating objects::
372: * Object-Oriented Programming Style::
373: * Class Binding::
374: * Method conveniences::
375: * Classes and Scoping::
1.41 anton 376: * Dividing classes::
1.12 anton 377: * Object Interfaces::
378: * Objects Implementation::
379: * Objects Glossary::
380:
1.24 anton 381: The @file{oof.fs} model
1.12 anton 382:
1.67 anton 383: * Properties of the OOF model::
384: * Basic OOF Usage::
385: * The OOF base class::
386: * Class Declaration::
387: * Class Implementation::
1.12 anton 388:
1.24 anton 389: The @file{mini-oof.fs} model
1.23 crook 390:
1.48 anton 391: * Basic Mini-OOF Usage::
392: * Mini-OOF Example::
393: * Mini-OOF Implementation::
1.23 crook 394:
1.78 anton 395: Programming Tools
396:
1.150 anton 397: * Examining:: Data and Code.
398: * Forgetting words:: Usually before reloading.
1.78 anton 399: * Debugging:: Simple and quick.
400: * Assertions:: Making your programs self-checking.
401: * Singlestep Debugger:: Executing your program word by word.
402:
1.155 anton 403: C Interface
404:
405: * Calling C Functions::
406: * Declaring C Functions::
407: * Callbacks::
408: * Low-Level C Interface Words::
409:
1.78 anton 410: Assembler and Code Words
411:
412: * Code and ;code::
413: * Common Assembler:: Assembler Syntax
414: * Common Disassembler::
415: * 386 Assembler:: Deviations and special cases
416: * Alpha Assembler:: Deviations and special cases
417: * MIPS assembler:: Deviations and special cases
418: * Other assemblers:: How to write them
419:
1.12 anton 420: Tools
421:
422: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 423: * Stack depth changes:: Where does this stack item come from?
1.12 anton 424:
425: ANS conformance
426:
427: * The Core Words::
428: * The optional Block word set::
429: * The optional Double Number word set::
430: * The optional Exception word set::
431: * The optional Facility word set::
432: * The optional File-Access word set::
433: * The optional Floating-Point word set::
434: * The optional Locals word set::
435: * The optional Memory-Allocation word set::
436: * The optional Programming-Tools word set::
437: * The optional Search-Order word set::
438:
439: The Core Words
440:
441: * core-idef:: Implementation Defined Options
442: * core-ambcond:: Ambiguous Conditions
443: * core-other:: Other System Documentation
444:
445: The optional Block word set
446:
447: * block-idef:: Implementation Defined Options
448: * block-ambcond:: Ambiguous Conditions
449: * block-other:: Other System Documentation
450:
451: The optional Double Number word set
452:
453: * double-ambcond:: Ambiguous Conditions
454:
455: The optional Exception word set
456:
457: * exception-idef:: Implementation Defined Options
458:
459: The optional Facility word set
460:
461: * facility-idef:: Implementation Defined Options
462: * facility-ambcond:: Ambiguous Conditions
463:
464: The optional File-Access word set
465:
466: * file-idef:: Implementation Defined Options
467: * file-ambcond:: Ambiguous Conditions
468:
469: The optional Floating-Point word set
470:
471: * floating-idef:: Implementation Defined Options
472: * floating-ambcond:: Ambiguous Conditions
473:
474: The optional Locals word set
475:
476: * locals-idef:: Implementation Defined Options
477: * locals-ambcond:: Ambiguous Conditions
478:
479: The optional Memory-Allocation word set
480:
481: * memory-idef:: Implementation Defined Options
482:
483: The optional Programming-Tools word set
484:
485: * programming-idef:: Implementation Defined Options
486: * programming-ambcond:: Ambiguous Conditions
487:
488: The optional Search-Order word set
489:
490: * search-idef:: Implementation Defined Options
491: * search-ambcond:: Ambiguous Conditions
492:
1.109 anton 493: Emacs and Gforth
494:
495: * Installing gforth.el:: Making Emacs aware of Forth.
496: * Emacs Tags:: Viewing the source of a word in Emacs.
497: * Hilighting:: Making Forth code look prettier.
498: * Auto-Indentation:: Customizing auto-indentation.
499: * Blocks Files:: Reading and writing blocks files.
500:
1.12 anton 501: Image Files
502:
1.24 anton 503: * Image Licensing Issues:: Distribution terms for images.
504: * Image File Background:: Why have image files?
1.67 anton 505: * Non-Relocatable Image Files:: don't always work.
1.24 anton 506: * Data-Relocatable Image Files:: are better.
1.67 anton 507: * Fully Relocatable Image Files:: better yet.
1.24 anton 508: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 509: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 510: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 511:
512: Fully Relocatable Image Files
513:
1.27 crook 514: * gforthmi:: The normal way
1.12 anton 515: * cross.fs:: The hard way
516:
517: Engine
518:
519: * Portability::
520: * Threading::
521: * Primitives::
522: * Performance::
523:
524: Threading
525:
526: * Scheduling::
527: * Direct or Indirect Threaded?::
1.109 anton 528: * Dynamic Superinstructions::
1.12 anton 529: * DOES>::
530:
531: Primitives
532:
533: * Automatic Generation::
534: * TOS Optimization::
535: * Produced code::
1.13 pazsan 536:
537: Cross Compiler
538:
1.67 anton 539: * Using the Cross Compiler::
540: * How the Cross Compiler Works::
1.13 pazsan 541:
1.113 anton 542: Licenses
543:
544: * GNU Free Documentation License:: License for copying this manual.
545: * Copying:: GPL (for copying this software).
546:
1.24 anton 547: @end detailmenu
1.1 anton 548: @end menu
549:
1.113 anton 550: @c ----------------------------------------------------------
1.1 anton 551: @iftex
552: @unnumbered Preface
553: @cindex Preface
1.21 crook 554: This manual documents Gforth. Some introductory material is provided for
555: readers who are unfamiliar with Forth or who are migrating to Gforth
556: from other Forth compilers. However, this manual is primarily a
557: reference manual.
1.1 anton 558: @end iftex
559:
1.28 crook 560: @comment TODO much more blurb here.
1.26 crook 561:
562: @c ******************************************************************
1.113 anton 563: @node Goals, Gforth Environment, Top, Top
1.26 crook 564: @comment node-name, next, previous, up
565: @chapter Goals of Gforth
566: @cindex goals of the Gforth project
567: The goal of the Gforth Project is to develop a standard model for
568: ANS Forth. This can be split into several subgoals:
569:
570: @itemize @bullet
571: @item
572: Gforth should conform to the ANS Forth Standard.
573: @item
574: It should be a model, i.e. it should define all the
575: implementation-dependent things.
576: @item
577: It should become standard, i.e. widely accepted and used. This goal
578: is the most difficult one.
579: @end itemize
580:
581: To achieve these goals Gforth should be
582: @itemize @bullet
583: @item
584: Similar to previous models (fig-Forth, F83)
585: @item
586: Powerful. It should provide for all the things that are considered
587: necessary today and even some that are not yet considered necessary.
588: @item
589: Efficient. It should not get the reputation of being exceptionally
590: slow.
591: @item
592: Free.
593: @item
594: Available on many machines/easy to port.
595: @end itemize
596:
597: Have we achieved these goals? Gforth conforms to the ANS Forth
598: standard. It may be considered a model, but we have not yet documented
599: which parts of the model are stable and which parts we are likely to
600: change. It certainly has not yet become a de facto standard, but it
601: appears to be quite popular. It has some similarities to and some
602: differences from previous models. It has some powerful features, but not
603: yet everything that we envisioned. We certainly have achieved our
1.65 anton 604: execution speed goals (@pxref{Performance})@footnote{However, in 1998
605: the bar was raised when the major commercial Forth vendors switched to
606: native code compilers.}. It is free and available on many machines.
1.29 crook 607:
1.26 crook 608: @c ******************************************************************
1.48 anton 609: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 610: @chapter Gforth Environment
611: @cindex Gforth environment
1.21 crook 612:
1.45 crook 613: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 614: material in this chapter.
1.21 crook 615:
616: @menu
1.29 crook 617: * Invoking Gforth:: Getting in
618: * Leaving Gforth:: Getting out
619: * Command-line editing::
1.48 anton 620: * Environment variables:: that affect how Gforth starts up
1.29 crook 621: * Gforth Files:: What gets installed and where
1.112 anton 622: * Gforth in pipes::
1.48 anton 623: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 624: @end menu
625:
1.49 anton 626: For related information about the creation of images see @ref{Image Files}.
1.29 crook 627:
1.21 crook 628: @comment ----------------------------------------------
1.48 anton 629: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 630: @section Invoking Gforth
631: @cindex invoking Gforth
632: @cindex running Gforth
633: @cindex command-line options
634: @cindex options on the command line
635: @cindex flags on the command line
1.21 crook 636:
1.30 anton 637: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 638: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 639: will usually just say @code{gforth} -- this automatically loads the
640: default image file @file{gforth.fi}. In many other cases the default
641: Gforth image will be invoked like this:
1.21 crook 642: @example
1.30 anton 643: gforth [file | -e forth-code] ...
1.21 crook 644: @end example
1.29 crook 645: @noindent
646: This interprets the contents of the files and the Forth code in the order they
647: are given.
1.21 crook 648:
1.109 anton 649: In addition to the @command{gforth} engine, there is also an engine
650: called @command{gforth-fast}, which is faster, but gives less
651: informative error messages (@pxref{Error messages}) and may catch some
652: stack underflows later or not at all. You should use it for debugged,
653: performance-critical programs.
654:
655: Moreover, there is an engine called @command{gforth-itc}, which is
656: useful in some backwards-compatibility situations (@pxref{Direct or
657: Indirect Threaded?}).
1.30 anton 658:
1.29 crook 659: In general, the command line looks like this:
1.21 crook 660:
661: @example
1.30 anton 662: gforth[-fast] [engine options] [image options]
1.21 crook 663: @end example
664:
1.30 anton 665: The engine options must come before the rest of the command
1.29 crook 666: line. They are:
1.26 crook 667:
1.29 crook 668: @table @code
669: @cindex -i, command-line option
670: @cindex --image-file, command-line option
671: @item --image-file @i{file}
672: @itemx -i @i{file}
673: Loads the Forth image @i{file} instead of the default
674: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 675:
1.39 anton 676: @cindex --appl-image, command-line option
677: @item --appl-image @i{file}
678: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 679: to the image (instead of processing them as engine options). This is
680: useful for building executable application images on Unix, built with
1.39 anton 681: @code{gforthmi --application ...}.
682:
1.29 crook 683: @cindex --path, command-line option
684: @cindex -p, command-line option
685: @item --path @i{path}
686: @itemx -p @i{path}
687: Uses @i{path} for searching the image file and Forth source code files
688: instead of the default in the environment variable @code{GFORTHPATH} or
689: the path specified at installation time (e.g.,
690: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
691: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 692:
1.29 crook 693: @cindex --dictionary-size, command-line option
694: @cindex -m, command-line option
695: @cindex @i{size} parameters for command-line options
696: @cindex size of the dictionary and the stacks
697: @item --dictionary-size @i{size}
698: @itemx -m @i{size}
699: Allocate @i{size} space for the Forth dictionary space instead of
700: using the default specified in the image (typically 256K). The
701: @i{size} specification for this and subsequent options consists of
702: an integer and a unit (e.g.,
703: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
704: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
705: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
706: @code{e} is used.
1.21 crook 707:
1.29 crook 708: @cindex --data-stack-size, command-line option
709: @cindex -d, command-line option
710: @item --data-stack-size @i{size}
711: @itemx -d @i{size}
712: Allocate @i{size} space for the data stack instead of using the
713: default specified in the image (typically 16K).
1.21 crook 714:
1.29 crook 715: @cindex --return-stack-size, command-line option
716: @cindex -r, command-line option
717: @item --return-stack-size @i{size}
718: @itemx -r @i{size}
719: Allocate @i{size} space for the return stack instead of using the
720: default specified in the image (typically 15K).
1.21 crook 721:
1.29 crook 722: @cindex --fp-stack-size, command-line option
723: @cindex -f, command-line option
724: @item --fp-stack-size @i{size}
725: @itemx -f @i{size}
726: Allocate @i{size} space for the floating point stack instead of
727: using the default specified in the image (typically 15.5K). In this case
728: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 729:
1.48 anton 730: @cindex --locals-stack-size, command-line option
731: @cindex -l, command-line option
732: @item --locals-stack-size @i{size}
733: @itemx -l @i{size}
734: Allocate @i{size} space for the locals stack instead of using the
735: default specified in the image (typically 14.5K).
736:
737: @cindex -h, command-line option
738: @cindex --help, command-line option
739: @item --help
740: @itemx -h
741: Print a message about the command-line options
742:
743: @cindex -v, command-line option
744: @cindex --version, command-line option
745: @item --version
746: @itemx -v
747: Print version and exit
748:
749: @cindex --debug, command-line option
750: @item --debug
751: Print some information useful for debugging on startup.
752:
753: @cindex --offset-image, command-line option
754: @item --offset-image
755: Start the dictionary at a slightly different position than would be used
756: otherwise (useful for creating data-relocatable images,
757: @pxref{Data-Relocatable Image Files}).
758:
759: @cindex --no-offset-im, command-line option
760: @item --no-offset-im
761: Start the dictionary at the normal position.
762:
763: @cindex --clear-dictionary, command-line option
764: @item --clear-dictionary
765: Initialize all bytes in the dictionary to 0 before loading the image
766: (@pxref{Data-Relocatable Image Files}).
767:
768: @cindex --die-on-signal, command-line-option
769: @item --die-on-signal
770: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
771: or the segmentation violation SIGSEGV) by translating it into a Forth
772: @code{THROW}. With this option, Gforth exits if it receives such a
773: signal. This option is useful when the engine and/or the image might be
774: severely broken (such that it causes another signal before recovering
775: from the first); this option avoids endless loops in such cases.
1.109 anton 776:
1.119 anton 777: @cindex --no-dynamic, command-line option
778: @cindex --dynamic, command-line option
1.109 anton 779: @item --no-dynamic
780: @item --dynamic
781: Disable or enable dynamic superinstructions with replication
782: (@pxref{Dynamic Superinstructions}).
783:
1.119 anton 784: @cindex --no-super, command-line option
1.109 anton 785: @item --no-super
1.110 anton 786: Disable dynamic superinstructions, use just dynamic replication; this is
787: useful if you want to patch threaded code (@pxref{Dynamic
788: Superinstructions}).
1.119 anton 789:
790: @cindex --ss-number, command-line option
791: @item --ss-number=@var{N}
792: Use only the first @var{N} static superinstructions compiled into the
793: engine (default: use them all; note that only @code{gforth-fast} has
794: any). This option is useful for measuring the performance impact of
795: static superinstructions.
796:
797: @cindex --ss-min-..., command-line options
798: @item --ss-min-codesize
799: @item --ss-min-ls
800: @item --ss-min-lsu
801: @item --ss-min-nexts
802: Use specified metric for determining the cost of a primitive or static
803: superinstruction for static superinstruction selection. @code{Codesize}
804: is the native code size of the primive or static superinstruction,
805: @code{ls} is the number of loads and stores, @code{lsu} is the number of
806: loads, stores, and updates, and @code{nexts} is the number of dispatches
807: (not taking dynamic superinstructions into account), i.e. every
808: primitive or static superinstruction has cost 1. Default:
809: @code{codesize} if you use dynamic code generation, otherwise
810: @code{nexts}.
811:
812: @cindex --ss-greedy, command-line option
813: @item --ss-greedy
814: This option is useful for measuring the performance impact of static
815: superinstructions. By default, an optimal shortest-path algorithm is
816: used for selecting static superinstructions. With @option{--ss-greedy}
817: this algorithm is modified to assume that anything after the static
818: superinstruction currently under consideration is not combined into
819: static superinstructions. With @option{--ss-min-nexts} this produces
820: the same result as a greedy algorithm that always selects the longest
821: superinstruction available at the moment. E.g., if there are
822: superinstructions AB and BCD, then for the sequence A B C D the optimal
823: algorithm will select A BCD and the greedy algorithm will select AB C D.
824:
825: @cindex --print-metrics, command-line option
826: @item --print-metrics
827: Prints some metrics used during static superinstruction selection:
828: @code{code size} is the actual size of the dynamically generated code.
829: @code{Metric codesize} is the sum of the codesize metrics as seen by
830: static superinstruction selection; there is a difference from @code{code
831: size}, because not all primitives and static superinstructions are
832: compiled into dynamically generated code, and because of markers. The
833: other metrics correspond to the @option{ss-min-...} options. This
834: option is useful for evaluating the effects of the @option{--ss-...}
835: options.
1.109 anton 836:
1.48 anton 837: @end table
838:
839: @cindex loading files at startup
840: @cindex executing code on startup
841: @cindex batch processing with Gforth
842: As explained above, the image-specific command-line arguments for the
843: default image @file{gforth.fi} consist of a sequence of filenames and
844: @code{-e @var{forth-code}} options that are interpreted in the sequence
845: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 846: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
847: option takes only one argument; if you want to evaluate more Forth
848: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 849: after processing the command line (instead of entering interactive mode)
1.121 anton 850: append @code{-e bye} to the command line. You can also process the
851: command-line arguments with a Forth program (@pxref{OS command line
852: arguments}).
1.48 anton 853:
854: @cindex versions, invoking other versions of Gforth
855: If you have several versions of Gforth installed, @code{gforth} will
856: invoke the version that was installed last. @code{gforth-@i{version}}
857: invokes a specific version. If your environment contains the variable
858: @code{GFORTHPATH}, you may want to override it by using the
859: @code{--path} option.
860:
861: Not yet implemented:
862: On startup the system first executes the system initialization file
863: (unless the option @code{--no-init-file} is given; note that the system
864: resulting from using this option may not be ANS Forth conformant). Then
865: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 866: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 867: then in @file{~}, then in the normal path (see above).
868:
869:
870:
871: @comment ----------------------------------------------
872: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
873: @section Leaving Gforth
874: @cindex Gforth - leaving
875: @cindex leaving Gforth
876:
877: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
878: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
879: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 880: data are discarded. For ways of saving the state of the system before
881: leaving Gforth see @ref{Image Files}.
1.48 anton 882:
883: doc-bye
884:
885:
886: @comment ----------------------------------------------
1.65 anton 887: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 888: @section Command-line editing
889: @cindex command-line editing
890:
891: Gforth maintains a history file that records every line that you type to
892: the text interpreter. This file is preserved between sessions, and is
893: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
894: repeatedly you can recall successively older commands from this (or
895: previous) session(s). The full list of command-line editing facilities is:
896:
897: @itemize @bullet
898: @item
899: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
900: commands from the history buffer.
901: @item
902: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
903: from the history buffer.
904: @item
905: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
906: @item
907: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
908: @item
909: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
910: closing up the line.
911: @item
912: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
913: @item
914: @kbd{Ctrl-a} to move the cursor to the start of the line.
915: @item
916: @kbd{Ctrl-e} to move the cursor to the end of the line.
917: @item
918: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
919: line.
920: @item
921: @key{TAB} to step through all possible full-word completions of the word
922: currently being typed.
923: @item
1.65 anton 924: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
925: using @code{bye}).
926: @item
927: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
928: character under the cursor.
1.48 anton 929: @end itemize
930:
931: When editing, displayable characters are inserted to the left of the
932: cursor position; the line is always in ``insert'' (as opposed to
933: ``overstrike'') mode.
934:
935: @cindex history file
936: @cindex @file{.gforth-history}
937: On Unix systems, the history file is @file{~/.gforth-history} by
938: default@footnote{i.e. it is stored in the user's home directory.}. You
939: can find out the name and location of your history file using:
940:
941: @example
942: history-file type \ Unix-class systems
943:
944: history-file type \ Other systems
945: history-dir type
946: @end example
947:
948: If you enter long definitions by hand, you can use a text editor to
949: paste them out of the history file into a Forth source file for reuse at
950: a later time.
951:
952: Gforth never trims the size of the history file, so you should do this
953: periodically, if necessary.
954:
955: @comment this is all defined in history.fs
956: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
957: @comment chosen?
958:
959:
960: @comment ----------------------------------------------
1.65 anton 961: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 962: @section Environment variables
963: @cindex environment variables
964:
965: Gforth uses these environment variables:
966:
967: @itemize @bullet
968: @item
969: @cindex @code{GFORTHHIST} -- environment variable
970: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
971: open/create the history file, @file{.gforth-history}. Default:
972: @code{$HOME}.
973:
974: @item
975: @cindex @code{GFORTHPATH} -- environment variable
976: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
977: for Forth source-code files.
978:
979: @item
1.147 anton 980: @cindex @code{LANG} -- environment variable
981: @code{LANG} -- see @code{LC_CTYPE}
982:
983: @item
984: @cindex @code{LC_ALL} -- environment variable
985: @code{LC_ALL} -- see @code{LC_CTYPE}
986:
987: @item
988: @cindex @code{LC_CTYPE} -- environment variable
989: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
990: startup, Gforth uses the UTF-8 encoding for strings internally and
991: expects its input and produces its output in UTF-8 encoding, otherwise
992: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
993: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
994: that is unset, in @code{LANG}.
995:
996: @item
1.129 anton 997: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
998:
999: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1000: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1001: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1002: and the command are directly concatenated, so if a space between them is
1003: necessary, append it to the prefix.
1004:
1005: @item
1.48 anton 1006: @cindex @code{GFORTH} -- environment variable
1.49 anton 1007: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1008:
1009: @item
1010: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1011: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1012:
1013: @item
1014: @cindex @code{TMP}, @code{TEMP} - environment variable
1015: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1016: location for the history file.
1017: @end itemize
1018:
1019: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1020: @comment mentioning these.
1021:
1022: All the Gforth environment variables default to sensible values if they
1023: are not set.
1024:
1025:
1026: @comment ----------------------------------------------
1.112 anton 1027: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1028: @section Gforth files
1029: @cindex Gforth files
1030:
1031: When you install Gforth on a Unix system, it installs files in these
1032: locations by default:
1033:
1034: @itemize @bullet
1035: @item
1036: @file{/usr/local/bin/gforth}
1037: @item
1038: @file{/usr/local/bin/gforthmi}
1039: @item
1040: @file{/usr/local/man/man1/gforth.1} - man page.
1041: @item
1042: @file{/usr/local/info} - the Info version of this manual.
1043: @item
1044: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1045: @item
1046: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1047: @item
1048: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1049: @item
1050: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1051: @end itemize
1052:
1053: You can select different places for installation by using
1054: @code{configure} options (listed with @code{configure --help}).
1055:
1056: @comment ----------------------------------------------
1.112 anton 1057: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1058: @section Gforth in pipes
1059: @cindex pipes, Gforth as part of
1060:
1061: Gforth can be used in pipes created elsewhere (described here). It can
1062: also create pipes on its own (@pxref{Pipes}).
1063:
1064: @cindex input from pipes
1065: If you pipe into Gforth, your program should read with @code{read-file}
1066: or @code{read-line} from @code{stdin} (@pxref{General files}).
1067: @code{Key} does not recognize the end of input. Words like
1068: @code{accept} echo the input and are therefore usually not useful for
1069: reading from a pipe. You have to invoke the Forth program with an OS
1070: command-line option, as you have no chance to use the Forth command line
1071: (the text interpreter would try to interpret the pipe input).
1072:
1073: @cindex output in pipes
1074: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1075:
1076: @cindex silent exiting from Gforth
1077: When you write to a pipe that has been closed at the other end, Gforth
1078: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1079: into the exception @code{broken-pipe-error}. If your application does
1080: not catch that exception, the system catches it and exits, usually
1081: silently (unless you were working on the Forth command line; then it
1082: prints an error message and exits). This is usually the desired
1083: behaviour.
1084:
1085: If you do not like this behaviour, you have to catch the exception
1086: yourself, and react to it.
1087:
1088: Here's an example of an invocation of Gforth that is usable in a pipe:
1089:
1090: @example
1091: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1092: type repeat ; foo bye"
1093: @end example
1094:
1095: This example just copies the input verbatim to the output. A very
1096: simple pipe containing this example looks like this:
1097:
1098: @example
1099: cat startup.fs |
1100: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1101: type repeat ; foo bye"|
1102: head
1103: @end example
1104:
1105: @cindex stderr and pipes
1106: Pipes involving Gforth's @code{stderr} output do not work.
1107:
1108: @comment ----------------------------------------------
1109: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1110: @section Startup speed
1111: @cindex Startup speed
1112: @cindex speed, startup
1113:
1114: If Gforth is used for CGI scripts or in shell scripts, its startup
1115: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1116: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1117: system time.
1118:
1119: If startup speed is a problem, you may consider the following ways to
1120: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1121: (for example, by using Fast-CGI).
1.48 anton 1122:
1.112 anton 1123: An easy step that influences Gforth startup speed is the use of the
1124: @option{--no-dynamic} option; this decreases image loading speed, but
1125: increases compile-time and run-time.
1126:
1127: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1128: building it with @code{XLDFLAGS=-static}. This requires more memory for
1129: the code and will therefore slow down the first invocation, but
1130: subsequent invocations avoid the dynamic linking overhead. Another
1131: disadvantage is that Gforth won't profit from library upgrades. As a
1132: result, @code{gforth-static -e bye} takes about 17.1ms user and
1133: 8.2ms system time.
1134:
1135: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1136: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1137: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1138: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1139: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1140: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1141: address for the dictionary, for whatever reason; so you better provide a
1142: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1143: bye} takes about 15.3ms user and 7.5ms system time.
1144:
1145: The final step is to disable dictionary hashing in Gforth. Gforth
1146: builds the hash table on startup, which takes much of the startup
1147: overhead. You can do this by commenting out the @code{include hash.fs}
1148: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1149: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1150: The disadvantages are that functionality like @code{table} and
1151: @code{ekey} is missing and that text interpretation (e.g., compiling)
1152: now takes much longer. So, you should only use this method if there is
1153: no significant text interpretation to perform (the script should be
1.62 crook 1154: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1155: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1156:
1157: @c ******************************************************************
1158: @node Tutorial, Introduction, Gforth Environment, Top
1159: @chapter Forth Tutorial
1160: @cindex Tutorial
1161: @cindex Forth Tutorial
1162:
1.67 anton 1163: @c Topics from nac's Introduction that could be mentioned:
1164: @c press <ret> after each line
1165: @c Prompt
1166: @c numbers vs. words in dictionary on text interpretation
1167: @c what happens on redefinition
1168: @c parsing words (in particular, defining words)
1169:
1.83 anton 1170: The difference of this chapter from the Introduction
1171: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1172: be used while sitting in front of a computer, and covers much more
1173: material, but does not explain how the Forth system works.
1174:
1.62 crook 1175: This tutorial can be used with any ANS-compliant Forth; any
1176: Gforth-specific features are marked as such and you can skip them if you
1177: work with another Forth. This tutorial does not explain all features of
1178: Forth, just enough to get you started and give you some ideas about the
1179: facilities available in Forth. Read the rest of the manual and the
1180: standard when you are through this.
1.48 anton 1181:
1182: The intended way to use this tutorial is that you work through it while
1183: sitting in front of the console, take a look at the examples and predict
1184: what they will do, then try them out; if the outcome is not as expected,
1185: find out why (e.g., by trying out variations of the example), so you
1186: understand what's going on. There are also some assignments that you
1187: should solve.
1188:
1189: This tutorial assumes that you have programmed before and know what,
1190: e.g., a loop is.
1191:
1192: @c !! explain compat library
1193:
1194: @menu
1195: * Starting Gforth Tutorial::
1196: * Syntax Tutorial::
1197: * Crash Course Tutorial::
1198: * Stack Tutorial::
1199: * Arithmetics Tutorial::
1200: * Stack Manipulation Tutorial::
1201: * Using files for Forth code Tutorial::
1202: * Comments Tutorial::
1203: * Colon Definitions Tutorial::
1204: * Decompilation Tutorial::
1205: * Stack-Effect Comments Tutorial::
1206: * Types Tutorial::
1207: * Factoring Tutorial::
1208: * Designing the stack effect Tutorial::
1209: * Local Variables Tutorial::
1210: * Conditional execution Tutorial::
1211: * Flags and Comparisons Tutorial::
1212: * General Loops Tutorial::
1213: * Counted loops Tutorial::
1214: * Recursion Tutorial::
1215: * Leaving definitions or loops Tutorial::
1216: * Return Stack Tutorial::
1217: * Memory Tutorial::
1218: * Characters and Strings Tutorial::
1219: * Alignment Tutorial::
1.87 anton 1220: * Files Tutorial::
1.48 anton 1221: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1222: * Execution Tokens Tutorial::
1223: * Exceptions Tutorial::
1224: * Defining Words Tutorial::
1225: * Arrays and Records Tutorial::
1226: * POSTPONE Tutorial::
1227: * Literal Tutorial::
1228: * Advanced macros Tutorial::
1229: * Compilation Tokens Tutorial::
1230: * Wordlists and Search Order Tutorial::
1231: @end menu
1232:
1233: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1234: @section Starting Gforth
1.66 anton 1235: @cindex starting Gforth tutorial
1.48 anton 1236: You can start Gforth by typing its name:
1237:
1238: @example
1239: gforth
1240: @end example
1241:
1242: That puts you into interactive mode; you can leave Gforth by typing
1243: @code{bye}. While in Gforth, you can edit the command line and access
1244: the command line history with cursor keys, similar to bash.
1245:
1246:
1247: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1248: @section Syntax
1.66 anton 1249: @cindex syntax tutorial
1.48 anton 1250:
1251: A @dfn{word} is a sequence of arbitrary characters (expcept white
1252: space). Words are separated by white space. E.g., each of the
1253: following lines contains exactly one word:
1254:
1255: @example
1256: word
1257: !@@#$%^&*()
1258: 1234567890
1259: 5!a
1260: @end example
1261:
1262: A frequent beginner's error is to leave away necessary white space,
1263: resulting in an error like @samp{Undefined word}; so if you see such an
1264: error, check if you have put spaces wherever necessary.
1265:
1266: @example
1267: ." hello, world" \ correct
1268: ."hello, world" \ gives an "Undefined word" error
1269: @end example
1270:
1.65 anton 1271: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1272: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1273: your system is case-sensitive, you may have to type all the examples
1274: given here in upper case.
1275:
1276:
1277: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1278: @section Crash Course
1279:
1280: Type
1281:
1282: @example
1283: 0 0 !
1284: here execute
1285: ' catch >body 20 erase abort
1286: ' (quit) >body 20 erase
1287: @end example
1288:
1289: The last two examples are guaranteed to destroy parts of Gforth (and
1290: most other systems), so you better leave Gforth afterwards (if it has
1291: not finished by itself). On some systems you may have to kill gforth
1292: from outside (e.g., in Unix with @code{kill}).
1293:
1294: Now that you know how to produce crashes (and that there's not much to
1295: them), let's learn how to produce meaningful programs.
1296:
1297:
1298: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1299: @section Stack
1.66 anton 1300: @cindex stack tutorial
1.48 anton 1301:
1302: The most obvious feature of Forth is the stack. When you type in a
1303: number, it is pushed on the stack. You can display the content of the
1304: stack with @code{.s}.
1305:
1306: @example
1307: 1 2 .s
1308: 3 .s
1309: @end example
1310:
1311: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1312: appear in @code{.s} output as they appeared in the input.
1313:
1314: You can print the top of stack element with @code{.}.
1315:
1316: @example
1317: 1 2 3 . . .
1318: @end example
1319:
1320: In general, words consume their stack arguments (@code{.s} is an
1321: exception).
1322:
1.141 anton 1323: @quotation Assignment
1.48 anton 1324: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1325: @end quotation
1.48 anton 1326:
1327:
1328: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1329: @section Arithmetics
1.66 anton 1330: @cindex arithmetics tutorial
1.48 anton 1331:
1332: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1333: operate on the top two stack items:
1334:
1335: @example
1.67 anton 1336: 2 2 .s
1337: + .s
1338: .
1.48 anton 1339: 2 1 - .
1340: 7 3 mod .
1341: @end example
1342:
1343: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1344: as in the corresponding infix expression (this is generally the case in
1345: Forth).
1346:
1347: Parentheses are superfluous (and not available), because the order of
1348: the words unambiguously determines the order of evaluation and the
1349: operands:
1350:
1351: @example
1352: 3 4 + 5 * .
1353: 3 4 5 * + .
1354: @end example
1355:
1.141 anton 1356: @quotation Assignment
1.48 anton 1357: What are the infix expressions corresponding to the Forth code above?
1358: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1359: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1360: @end quotation
1.48 anton 1361:
1362: To change the sign, use @code{negate}:
1363:
1364: @example
1365: 2 negate .
1366: @end example
1367:
1.141 anton 1368: @quotation Assignment
1.48 anton 1369: Convert -(-3)*4-5 to Forth.
1.141 anton 1370: @end quotation
1.48 anton 1371:
1372: @code{/mod} performs both @code{/} and @code{mod}.
1373:
1374: @example
1375: 7 3 /mod . .
1376: @end example
1377:
1.66 anton 1378: Reference: @ref{Arithmetic}.
1379:
1380:
1.48 anton 1381: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1382: @section Stack Manipulation
1.66 anton 1383: @cindex stack manipulation tutorial
1.48 anton 1384:
1385: Stack manipulation words rearrange the data on the stack.
1386:
1387: @example
1388: 1 .s drop .s
1389: 1 .s dup .s drop drop .s
1390: 1 2 .s over .s drop drop drop
1391: 1 2 .s swap .s drop drop
1392: 1 2 3 .s rot .s drop drop drop
1393: @end example
1394:
1395: These are the most important stack manipulation words. There are also
1396: variants that manipulate twice as many stack items:
1397:
1398: @example
1399: 1 2 3 4 .s 2swap .s 2drop 2drop
1400: @end example
1401:
1402: Two more stack manipulation words are:
1403:
1404: @example
1405: 1 2 .s nip .s drop
1406: 1 2 .s tuck .s 2drop drop
1407: @end example
1408:
1.141 anton 1409: @quotation Assignment
1.48 anton 1410: Replace @code{nip} and @code{tuck} with combinations of other stack
1411: manipulation words.
1412:
1413: @example
1414: Given: How do you get:
1415: 1 2 3 3 2 1
1416: 1 2 3 1 2 3 2
1417: 1 2 3 1 2 3 3
1418: 1 2 3 1 3 3
1419: 1 2 3 2 1 3
1420: 1 2 3 4 4 3 2 1
1421: 1 2 3 1 2 3 1 2 3
1422: 1 2 3 4 1 2 3 4 1 2
1423: 1 2 3
1424: 1 2 3 1 2 3 4
1425: 1 2 3 1 3
1426: @end example
1.141 anton 1427: @end quotation
1.48 anton 1428:
1429: @example
1430: 5 dup * .
1431: @end example
1432:
1.141 anton 1433: @quotation Assignment
1.48 anton 1434: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1435: Write a piece of Forth code that expects two numbers on the stack
1436: (@var{a} and @var{b}, with @var{b} on top) and computes
1437: @code{(a-b)(a+1)}.
1.141 anton 1438: @end quotation
1.48 anton 1439:
1.66 anton 1440: Reference: @ref{Stack Manipulation}.
1441:
1442:
1.48 anton 1443: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1444: @section Using files for Forth code
1.66 anton 1445: @cindex loading Forth code, tutorial
1446: @cindex files containing Forth code, tutorial
1.48 anton 1447:
1448: While working at the Forth command line is convenient for one-line
1449: examples and short one-off code, you probably want to store your source
1450: code in files for convenient editing and persistence. You can use your
1451: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1452: Gforth}) to create @var{file.fs} and use
1.48 anton 1453:
1454: @example
1.102 anton 1455: s" @var{file.fs}" included
1.48 anton 1456: @end example
1457:
1458: to load it into your Forth system. The file name extension I use for
1459: Forth files is @samp{.fs}.
1460:
1461: You can easily start Gforth with some files loaded like this:
1462:
1463: @example
1.102 anton 1464: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1465: @end example
1466:
1467: If an error occurs during loading these files, Gforth terminates,
1468: whereas an error during @code{INCLUDED} within Gforth usually gives you
1469: a Gforth command line. Starting the Forth system every time gives you a
1470: clean start every time, without interference from the results of earlier
1471: tries.
1472:
1473: I often put all the tests in a file, then load the code and run the
1474: tests with
1475:
1476: @example
1.102 anton 1477: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1478: @end example
1479:
1480: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1481: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1482: restart this command without ado.
1483:
1484: The advantage of this approach is that the tests can be repeated easily
1485: every time the program ist changed, making it easy to catch bugs
1486: introduced by the change.
1487:
1.66 anton 1488: Reference: @ref{Forth source files}.
1489:
1.48 anton 1490:
1491: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1492: @section Comments
1.66 anton 1493: @cindex comments tutorial
1.48 anton 1494:
1495: @example
1496: \ That's a comment; it ends at the end of the line
1497: ( Another comment; it ends here: ) .s
1498: @end example
1499:
1500: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1501: separated with white space from the following text.
1502:
1503: @example
1504: \This gives an "Undefined word" error
1505: @end example
1506:
1507: The first @code{)} ends a comment started with @code{(}, so you cannot
1508: nest @code{(}-comments; and you cannot comment out text containing a
1509: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1510: avoid @code{)} in word names.}.
1511:
1512: I use @code{\}-comments for descriptive text and for commenting out code
1513: of one or more line; I use @code{(}-comments for describing the stack
1514: effect, the stack contents, or for commenting out sub-line pieces of
1515: code.
1516:
1517: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1518: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1519: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1520: with @kbd{M-q}.
1521:
1.66 anton 1522: Reference: @ref{Comments}.
1523:
1.48 anton 1524:
1525: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1526: @section Colon Definitions
1.66 anton 1527: @cindex colon definitions, tutorial
1528: @cindex definitions, tutorial
1529: @cindex procedures, tutorial
1530: @cindex functions, tutorial
1.48 anton 1531:
1532: are similar to procedures and functions in other programming languages.
1533:
1534: @example
1535: : squared ( n -- n^2 )
1536: dup * ;
1537: 5 squared .
1538: 7 squared .
1539: @end example
1540:
1541: @code{:} starts the colon definition; its name is @code{squared}. The
1542: following comment describes its stack effect. The words @code{dup *}
1543: are not executed, but compiled into the definition. @code{;} ends the
1544: colon definition.
1545:
1546: The newly-defined word can be used like any other word, including using
1547: it in other definitions:
1548:
1549: @example
1550: : cubed ( n -- n^3 )
1551: dup squared * ;
1552: -5 cubed .
1553: : fourth-power ( n -- n^4 )
1554: squared squared ;
1555: 3 fourth-power .
1556: @end example
1557:
1.141 anton 1558: @quotation Assignment
1.48 anton 1559: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1560: @code{/mod} in terms of other Forth words, and check if they work (hint:
1561: test your tests on the originals first). Don't let the
1562: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1563: @end quotation
1.48 anton 1564:
1.66 anton 1565: Reference: @ref{Colon Definitions}.
1566:
1.48 anton 1567:
1568: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1569: @section Decompilation
1.66 anton 1570: @cindex decompilation tutorial
1571: @cindex see tutorial
1.48 anton 1572:
1573: You can decompile colon definitions with @code{see}:
1574:
1575: @example
1576: see squared
1577: see cubed
1578: @end example
1579:
1580: In Gforth @code{see} shows you a reconstruction of the source code from
1581: the executable code. Informations that were present in the source, but
1582: not in the executable code, are lost (e.g., comments).
1583:
1.65 anton 1584: You can also decompile the predefined words:
1585:
1586: @example
1587: see .
1588: see +
1589: @end example
1590:
1591:
1.48 anton 1592: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1593: @section Stack-Effect Comments
1.66 anton 1594: @cindex stack-effect comments, tutorial
1595: @cindex --, tutorial
1.48 anton 1596: By convention the comment after the name of a definition describes the
1597: stack effect: The part in from of the @samp{--} describes the state of
1598: the stack before the execution of the definition, i.e., the parameters
1599: that are passed into the colon definition; the part behind the @samp{--}
1600: is the state of the stack after the execution of the definition, i.e.,
1601: the results of the definition. The stack comment only shows the top
1602: stack items that the definition accesses and/or changes.
1603:
1604: You should put a correct stack effect on every definition, even if it is
1605: just @code{( -- )}. You should also add some descriptive comment to
1606: more complicated words (I usually do this in the lines following
1607: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1608: you have to work through every definition before you can understand
1.48 anton 1609: any).
1610:
1.141 anton 1611: @quotation Assignment
1.48 anton 1612: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1613: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1614: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1615: are done, you can compare your stack effects to those in this manual
1.48 anton 1616: (@pxref{Word Index}).
1.141 anton 1617: @end quotation
1.48 anton 1618:
1619: Sometimes programmers put comments at various places in colon
1620: definitions that describe the contents of the stack at that place (stack
1621: comments); i.e., they are like the first part of a stack-effect
1622: comment. E.g.,
1623:
1624: @example
1625: : cubed ( n -- n^3 )
1626: dup squared ( n n^2 ) * ;
1627: @end example
1628:
1629: In this case the stack comment is pretty superfluous, because the word
1630: is simple enough. If you think it would be a good idea to add such a
1631: comment to increase readability, you should also consider factoring the
1632: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1633: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1634: however, if you decide not to refactor it, then having such a comment is
1635: better than not having it.
1636:
1637: The names of the stack items in stack-effect and stack comments in the
1638: standard, in this manual, and in many programs specify the type through
1639: a type prefix, similar to Fortran and Hungarian notation. The most
1640: frequent prefixes are:
1641:
1642: @table @code
1643: @item n
1644: signed integer
1645: @item u
1646: unsigned integer
1647: @item c
1648: character
1649: @item f
1650: Boolean flags, i.e. @code{false} or @code{true}.
1651: @item a-addr,a-
1652: Cell-aligned address
1653: @item c-addr,c-
1654: Char-aligned address (note that a Char may have two bytes in Windows NT)
1655: @item xt
1656: Execution token, same size as Cell
1657: @item w,x
1658: Cell, can contain an integer or an address. It usually takes 32, 64 or
1659: 16 bits (depending on your platform and Forth system). A cell is more
1660: commonly known as machine word, but the term @emph{word} already means
1661: something different in Forth.
1662: @item d
1663: signed double-cell integer
1664: @item ud
1665: unsigned double-cell integer
1666: @item r
1667: Float (on the FP stack)
1668: @end table
1669:
1670: You can find a more complete list in @ref{Notation}.
1671:
1.141 anton 1672: @quotation Assignment
1.48 anton 1673: Write stack-effect comments for all definitions you have written up to
1674: now.
1.141 anton 1675: @end quotation
1.48 anton 1676:
1677:
1678: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1679: @section Types
1.66 anton 1680: @cindex types tutorial
1.48 anton 1681:
1682: In Forth the names of the operations are not overloaded; so similar
1683: operations on different types need different names; e.g., @code{+} adds
1684: integers, and you have to use @code{f+} to add floating-point numbers.
1685: The following prefixes are often used for related operations on
1686: different types:
1687:
1688: @table @code
1689: @item (none)
1690: signed integer
1691: @item u
1692: unsigned integer
1693: @item c
1694: character
1695: @item d
1696: signed double-cell integer
1697: @item ud, du
1698: unsigned double-cell integer
1699: @item 2
1700: two cells (not-necessarily double-cell numbers)
1701: @item m, um
1702: mixed single-cell and double-cell operations
1703: @item f
1704: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1705: and @samp{r} represents FP numbers).
1.48 anton 1706: @end table
1707:
1708: If there are no differences between the signed and the unsigned variant
1709: (e.g., for @code{+}), there is only the prefix-less variant.
1710:
1711: Forth does not perform type checking, neither at compile time, nor at
1712: run time. If you use the wrong oeration, the data are interpreted
1713: incorrectly:
1714:
1715: @example
1716: -1 u.
1717: @end example
1718:
1719: If you have only experience with type-checked languages until now, and
1720: have heard how important type-checking is, don't panic! In my
1721: experience (and that of other Forthers), type errors in Forth code are
1722: usually easy to find (once you get used to it), the increased vigilance
1723: of the programmer tends to catch some harder errors in addition to most
1724: type errors, and you never have to work around the type system, so in
1725: most situations the lack of type-checking seems to be a win (projects to
1726: add type checking to Forth have not caught on).
1727:
1728:
1729: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1730: @section Factoring
1.66 anton 1731: @cindex factoring tutorial
1.48 anton 1732:
1733: If you try to write longer definitions, you will soon find it hard to
1734: keep track of the stack contents. Therefore, good Forth programmers
1735: tend to write only short definitions (e.g., three lines). The art of
1736: finding meaningful short definitions is known as factoring (as in
1737: factoring polynomials).
1738:
1739: Well-factored programs offer additional advantages: smaller, more
1740: general words, are easier to test and debug and can be reused more and
1741: better than larger, specialized words.
1742:
1743: So, if you run into difficulties with stack management, when writing
1744: code, try to define meaningful factors for the word, and define the word
1745: in terms of those. Even if a factor contains only two words, it is
1746: often helpful.
1747:
1.65 anton 1748: Good factoring is not easy, and it takes some practice to get the knack
1749: for it; but even experienced Forth programmers often don't find the
1750: right solution right away, but only when rewriting the program. So, if
1751: you don't come up with a good solution immediately, keep trying, don't
1752: despair.
1.48 anton 1753:
1754: @c example !!
1755:
1756:
1757: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1758: @section Designing the stack effect
1.66 anton 1759: @cindex Stack effect design, tutorial
1760: @cindex design of stack effects, tutorial
1.48 anton 1761:
1762: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1763: function; and since there is only one result, you don't have to deal with
1.48 anton 1764: the order of results, either.
1765:
1.117 anton 1766: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1767: parameter and result order of a definition is important and should be
1768: designed well. The general guideline is to design the stack effect such
1769: that the word is simple to use in most cases, even if that complicates
1770: the implementation of the word. Some concrete rules are:
1771:
1772: @itemize @bullet
1773:
1774: @item
1775: Words consume all of their parameters (e.g., @code{.}).
1776:
1777: @item
1778: If there is a convention on the order of parameters (e.g., from
1779: mathematics or another programming language), stick with it (e.g.,
1780: @code{-}).
1781:
1782: @item
1783: If one parameter usually requires only a short computation (e.g., it is
1784: a constant), pass it on the top of the stack. Conversely, parameters
1785: that usually require a long sequence of code to compute should be passed
1786: as the bottom (i.e., first) parameter. This makes the code easier to
1787: read, because reader does not need to keep track of the bottom item
1788: through a long sequence of code (or, alternatively, through stack
1.49 anton 1789: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1790: address on top of the stack because it is usually simpler to compute
1791: than the stored value (often the address is just a variable).
1792:
1793: @item
1794: Similarly, results that are usually consumed quickly should be returned
1795: on the top of stack, whereas a result that is often used in long
1796: computations should be passed as bottom result. E.g., the file words
1797: like @code{open-file} return the error code on the top of stack, because
1798: it is usually consumed quickly by @code{throw}; moreover, the error code
1799: has to be checked before doing anything with the other results.
1800:
1801: @end itemize
1802:
1803: These rules are just general guidelines, don't lose sight of the overall
1804: goal to make the words easy to use. E.g., if the convention rule
1805: conflicts with the computation-length rule, you might decide in favour
1806: of the convention if the word will be used rarely, and in favour of the
1807: computation-length rule if the word will be used frequently (because
1808: with frequent use the cost of breaking the computation-length rule would
1809: be quite high, and frequent use makes it easier to remember an
1810: unconventional order).
1811:
1812: @c example !! structure package
1813:
1.65 anton 1814:
1.48 anton 1815: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1816: @section Local Variables
1.66 anton 1817: @cindex local variables, tutorial
1.48 anton 1818:
1819: You can define local variables (@emph{locals}) in a colon definition:
1820:
1821: @example
1822: : swap @{ a b -- b a @}
1823: b a ;
1824: 1 2 swap .s 2drop
1825: @end example
1826:
1827: (If your Forth system does not support this syntax, include
1828: @file{compat/anslocals.fs} first).
1829:
1830: In this example @code{@{ a b -- b a @}} is the locals definition; it
1831: takes two cells from the stack, puts the top of stack in @code{b} and
1832: the next stack element in @code{a}. @code{--} starts a comment ending
1833: with @code{@}}. After the locals definition, using the name of the
1834: local will push its value on the stack. You can leave the comment
1835: part (@code{-- b a}) away:
1836:
1837: @example
1838: : swap ( x1 x2 -- x2 x1 )
1839: @{ a b @} b a ;
1840: @end example
1841:
1842: In Gforth you can have several locals definitions, anywhere in a colon
1843: definition; in contrast, in a standard program you can have only one
1844: locals definition per colon definition, and that locals definition must
1845: be outside any controll structure.
1846:
1847: With locals you can write slightly longer definitions without running
1848: into stack trouble. However, I recommend trying to write colon
1849: definitions without locals for exercise purposes to help you gain the
1850: essential factoring skills.
1851:
1.141 anton 1852: @quotation Assignment
1.48 anton 1853: Rewrite your definitions until now with locals
1.141 anton 1854: @end quotation
1.48 anton 1855:
1.66 anton 1856: Reference: @ref{Locals}.
1857:
1.48 anton 1858:
1859: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1860: @section Conditional execution
1.66 anton 1861: @cindex conditionals, tutorial
1862: @cindex if, tutorial
1.48 anton 1863:
1864: In Forth you can use control structures only inside colon definitions.
1865: An @code{if}-structure looks like this:
1866:
1867: @example
1868: : abs ( n1 -- +n2 )
1869: dup 0 < if
1870: negate
1871: endif ;
1872: 5 abs .
1873: -5 abs .
1874: @end example
1875:
1876: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1877: the following code is performed, otherwise execution continues after the
1.51 pazsan 1878: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1879: elements and prioduces a flag:
1880:
1881: @example
1882: 1 2 < .
1883: 2 1 < .
1884: 1 1 < .
1885: @end example
1886:
1887: Actually the standard name for @code{endif} is @code{then}. This
1888: tutorial presents the examples using @code{endif}, because this is often
1889: less confusing for people familiar with other programming languages
1890: where @code{then} has a different meaning. If your system does not have
1891: @code{endif}, define it with
1892:
1893: @example
1894: : endif postpone then ; immediate
1895: @end example
1896:
1897: You can optionally use an @code{else}-part:
1898:
1899: @example
1900: : min ( n1 n2 -- n )
1901: 2dup < if
1902: drop
1903: else
1904: nip
1905: endif ;
1906: 2 3 min .
1907: 3 2 min .
1908: @end example
1909:
1.141 anton 1910: @quotation Assignment
1.48 anton 1911: Write @code{min} without @code{else}-part (hint: what's the definition
1912: of @code{nip}?).
1.141 anton 1913: @end quotation
1.48 anton 1914:
1.66 anton 1915: Reference: @ref{Selection}.
1916:
1.48 anton 1917:
1918: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1919: @section Flags and Comparisons
1.66 anton 1920: @cindex flags tutorial
1921: @cindex comparison tutorial
1.48 anton 1922:
1923: In a false-flag all bits are clear (0 when interpreted as integer). In
1924: a canonical true-flag all bits are set (-1 as a twos-complement signed
1925: integer); in many contexts (e.g., @code{if}) any non-zero value is
1926: treated as true flag.
1927:
1928: @example
1929: false .
1930: true .
1931: true hex u. decimal
1932: @end example
1933:
1934: Comparison words produce canonical flags:
1935:
1936: @example
1937: 1 1 = .
1938: 1 0= .
1939: 0 1 < .
1940: 0 0 < .
1941: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1942: -1 1 < .
1943: @end example
1944:
1.66 anton 1945: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1946: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1947: these combinations are standard (for details see the standard,
1948: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1949:
1950: You can use @code{and or xor invert} can be used as operations on
1951: canonical flags. Actually they are bitwise operations:
1952:
1953: @example
1954: 1 2 and .
1955: 1 2 or .
1956: 1 3 xor .
1957: 1 invert .
1958: @end example
1959:
1960: You can convert a zero/non-zero flag into a canonical flag with
1961: @code{0<>} (and complement it on the way with @code{0=}).
1962:
1963: @example
1964: 1 0= .
1965: 1 0<> .
1966: @end example
1967:
1.65 anton 1968: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1969: operation of the Boolean operations to avoid @code{if}s:
1970:
1971: @example
1972: : foo ( n1 -- n2 )
1973: 0= if
1974: 14
1975: else
1976: 0
1977: endif ;
1978: 0 foo .
1979: 1 foo .
1980:
1981: : foo ( n1 -- n2 )
1982: 0= 14 and ;
1983: 0 foo .
1984: 1 foo .
1985: @end example
1986:
1.141 anton 1987: @quotation Assignment
1.48 anton 1988: Write @code{min} without @code{if}.
1.141 anton 1989: @end quotation
1.48 anton 1990:
1.66 anton 1991: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1992: @ref{Bitwise operations}.
1993:
1.48 anton 1994:
1995: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1996: @section General Loops
1.66 anton 1997: @cindex loops, indefinite, tutorial
1.48 anton 1998:
1999: The endless loop is the most simple one:
2000:
2001: @example
2002: : endless ( -- )
2003: 0 begin
2004: dup . 1+
2005: again ;
2006: endless
2007: @end example
2008:
2009: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2010: does nothing at run-time, @code{again} jumps back to @code{begin}.
2011:
2012: A loop with one exit at any place looks like this:
2013:
2014: @example
2015: : log2 ( +n1 -- n2 )
2016: \ logarithmus dualis of n1>0, rounded down to the next integer
2017: assert( dup 0> )
2018: 2/ 0 begin
2019: over 0> while
2020: 1+ swap 2/ swap
2021: repeat
2022: nip ;
2023: 7 log2 .
2024: 8 log2 .
2025: @end example
2026:
2027: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2028: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2029: continues behind the @code{while}. @code{Repeat} jumps back to
2030: @code{begin}, just like @code{again}.
2031:
2032: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2033: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2034: one bit (arithmetic shift right):
2035:
2036: @example
2037: -5 2 / .
2038: -5 2/ .
2039: @end example
2040:
2041: @code{assert(} is no standard word, but you can get it on systems other
2042: then Gforth by including @file{compat/assert.fs}. You can see what it
2043: does by trying
2044:
2045: @example
2046: 0 log2 .
2047: @end example
2048:
2049: Here's a loop with an exit at the end:
2050:
2051: @example
2052: : log2 ( +n1 -- n2 )
2053: \ logarithmus dualis of n1>0, rounded down to the next integer
2054: assert( dup 0 > )
2055: -1 begin
2056: 1+ swap 2/ swap
2057: over 0 <=
2058: until
2059: nip ;
2060: @end example
2061:
2062: @code{Until} consumes a flag; if it is non-zero, execution continues at
2063: the @code{begin}, otherwise after the @code{until}.
2064:
1.141 anton 2065: @quotation Assignment
1.48 anton 2066: Write a definition for computing the greatest common divisor.
1.141 anton 2067: @end quotation
1.48 anton 2068:
1.66 anton 2069: Reference: @ref{Simple Loops}.
2070:
1.48 anton 2071:
2072: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2073: @section Counted loops
1.66 anton 2074: @cindex loops, counted, tutorial
1.48 anton 2075:
2076: @example
2077: : ^ ( n1 u -- n )
2078: \ n = the uth power of u1
2079: 1 swap 0 u+do
2080: over *
2081: loop
2082: nip ;
2083: 3 2 ^ .
2084: 4 3 ^ .
2085: @end example
2086:
2087: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2088: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2089: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2090: times (or not at all, if @code{u3-u4<0}).
2091:
2092: You can see the stack effect design rules at work in the stack effect of
2093: the loop start words: Since the start value of the loop is more
2094: frequently constant than the end value, the start value is passed on
2095: the top-of-stack.
2096:
2097: You can access the counter of a counted loop with @code{i}:
2098:
2099: @example
2100: : fac ( u -- u! )
2101: 1 swap 1+ 1 u+do
2102: i *
2103: loop ;
2104: 5 fac .
2105: 7 fac .
2106: @end example
2107:
2108: There is also @code{+do}, which expects signed numbers (important for
2109: deciding whether to enter the loop).
2110:
1.141 anton 2111: @quotation Assignment
1.48 anton 2112: Write a definition for computing the nth Fibonacci number.
1.141 anton 2113: @end quotation
1.48 anton 2114:
1.65 anton 2115: You can also use increments other than 1:
2116:
2117: @example
2118: : up2 ( n1 n2 -- )
2119: +do
2120: i .
2121: 2 +loop ;
2122: 10 0 up2
2123:
2124: : down2 ( n1 n2 -- )
2125: -do
2126: i .
2127: 2 -loop ;
2128: 0 10 down2
2129: @end example
1.48 anton 2130:
1.66 anton 2131: Reference: @ref{Counted Loops}.
2132:
1.48 anton 2133:
2134: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2135: @section Recursion
1.66 anton 2136: @cindex recursion tutorial
1.48 anton 2137:
2138: Usually the name of a definition is not visible in the definition; but
2139: earlier definitions are usually visible:
2140:
2141: @example
2142: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2143: : / ( n1 n2 -- n )
2144: dup 0= if
2145: -10 throw \ report division by zero
2146: endif
2147: / \ old version
2148: ;
2149: 1 0 /
2150: @end example
2151:
2152: For recursive definitions you can use @code{recursive} (non-standard) or
2153: @code{recurse}:
2154:
2155: @example
2156: : fac1 ( n -- n! ) recursive
2157: dup 0> if
2158: dup 1- fac1 *
2159: else
2160: drop 1
2161: endif ;
2162: 7 fac1 .
2163:
2164: : fac2 ( n -- n! )
2165: dup 0> if
2166: dup 1- recurse *
2167: else
2168: drop 1
2169: endif ;
2170: 8 fac2 .
2171: @end example
2172:
1.141 anton 2173: @quotation Assignment
1.48 anton 2174: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2175: @end quotation
1.48 anton 2176:
1.66 anton 2177: Reference (including indirect recursion): @xref{Calls and returns}.
2178:
1.48 anton 2179:
2180: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2181: @section Leaving definitions or loops
1.66 anton 2182: @cindex leaving definitions, tutorial
2183: @cindex leaving loops, tutorial
1.48 anton 2184:
2185: @code{EXIT} exits the current definition right away. For every counted
2186: loop that is left in this way, an @code{UNLOOP} has to be performed
2187: before the @code{EXIT}:
2188:
2189: @c !! real examples
2190: @example
2191: : ...
2192: ... u+do
2193: ... if
2194: ... unloop exit
2195: endif
2196: ...
2197: loop
2198: ... ;
2199: @end example
2200:
2201: @code{LEAVE} leaves the innermost counted loop right away:
2202:
2203: @example
2204: : ...
2205: ... u+do
2206: ... if
2207: ... leave
2208: endif
2209: ...
2210: loop
2211: ... ;
2212: @end example
2213:
1.65 anton 2214: @c !! example
1.48 anton 2215:
1.66 anton 2216: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2217:
2218:
1.48 anton 2219: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2220: @section Return Stack
1.66 anton 2221: @cindex return stack tutorial
1.48 anton 2222:
2223: In addition to the data stack Forth also has a second stack, the return
2224: stack; most Forth systems store the return addresses of procedure calls
2225: there (thus its name). Programmers can also use this stack:
2226:
2227: @example
2228: : foo ( n1 n2 -- )
2229: .s
2230: >r .s
1.50 anton 2231: r@@ .
1.48 anton 2232: >r .s
1.50 anton 2233: r@@ .
1.48 anton 2234: r> .
1.50 anton 2235: r@@ .
1.48 anton 2236: r> . ;
2237: 1 2 foo
2238: @end example
2239:
2240: @code{>r} takes an element from the data stack and pushes it onto the
2241: return stack; conversely, @code{r>} moves an elementm from the return to
2242: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2243: on the data stack.
1.48 anton 2244:
2245: Forth programmers usually use the return stack for storing data
2246: temporarily, if using the data stack alone would be too complex, and
2247: factoring and locals are not an option:
2248:
2249: @example
2250: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2251: rot >r rot r> ;
2252: @end example
2253:
2254: The return address of the definition and the loop control parameters of
2255: counted loops usually reside on the return stack, so you have to take
2256: all items, that you have pushed on the return stack in a colon
2257: definition or counted loop, from the return stack before the definition
2258: or loop ends. You cannot access items that you pushed on the return
2259: stack outside some definition or loop within the definition of loop.
2260:
2261: If you miscount the return stack items, this usually ends in a crash:
2262:
2263: @example
2264: : crash ( n -- )
2265: >r ;
2266: 5 crash
2267: @end example
2268:
2269: You cannot mix using locals and using the return stack (according to the
2270: standard; Gforth has no problem). However, they solve the same
2271: problems, so this shouldn't be an issue.
2272:
1.141 anton 2273: @quotation Assignment
1.48 anton 2274: Can you rewrite any of the definitions you wrote until now in a better
2275: way using the return stack?
1.141 anton 2276: @end quotation
1.48 anton 2277:
1.66 anton 2278: Reference: @ref{Return stack}.
2279:
1.48 anton 2280:
2281: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2282: @section Memory
1.66 anton 2283: @cindex memory access/allocation tutorial
1.48 anton 2284:
2285: You can create a global variable @code{v} with
2286:
2287: @example
2288: variable v ( -- addr )
2289: @end example
2290:
2291: @code{v} pushes the address of a cell in memory on the stack. This cell
2292: was reserved by @code{variable}. You can use @code{!} (store) to store
2293: values into this cell and @code{@@} (fetch) to load the value from the
2294: stack into memory:
2295:
2296: @example
2297: v .
2298: 5 v ! .s
1.50 anton 2299: v @@ .
1.48 anton 2300: @end example
2301:
1.65 anton 2302: You can see a raw dump of memory with @code{dump}:
2303:
2304: @example
2305: v 1 cells .s dump
2306: @end example
2307:
2308: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2309: generally, address units (aus)) that @code{n1 cells} occupy. You can
2310: also reserve more memory:
1.48 anton 2311:
2312: @example
2313: create v2 20 cells allot
1.65 anton 2314: v2 20 cells dump
1.48 anton 2315: @end example
2316:
1.65 anton 2317: creates a word @code{v2} and reserves 20 uninitialized cells; the
2318: address pushed by @code{v2} points to the start of these 20 cells. You
2319: can use address arithmetic to access these cells:
1.48 anton 2320:
2321: @example
2322: 3 v2 5 cells + !
1.65 anton 2323: v2 20 cells dump
1.48 anton 2324: @end example
2325:
2326: You can reserve and initialize memory with @code{,}:
2327:
2328: @example
2329: create v3
2330: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2331: v3 @@ .
2332: v3 cell+ @@ .
2333: v3 2 cells + @@ .
1.65 anton 2334: v3 5 cells dump
1.48 anton 2335: @end example
2336:
1.141 anton 2337: @quotation Assignment
1.48 anton 2338: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2339: @code{u} cells, with the first of these cells at @code{addr}, the next
2340: one at @code{addr cell+} etc.
1.141 anton 2341: @end quotation
1.48 anton 2342:
2343: You can also reserve memory without creating a new word:
2344:
2345: @example
1.60 anton 2346: here 10 cells allot .
2347: here .
1.48 anton 2348: @end example
2349:
2350: @code{Here} pushes the start address of the memory area. You should
2351: store it somewhere, or you will have a hard time finding the memory area
2352: again.
2353:
2354: @code{Allot} manages dictionary memory. The dictionary memory contains
2355: the system's data structures for words etc. on Gforth and most other
2356: Forth systems. It is managed like a stack: You can free the memory that
2357: you have just @code{allot}ed with
2358:
2359: @example
2360: -10 cells allot
1.60 anton 2361: here .
1.48 anton 2362: @end example
2363:
2364: Note that you cannot do this if you have created a new word in the
2365: meantime (because then your @code{allot}ed memory is no longer on the
2366: top of the dictionary ``stack'').
2367:
2368: Alternatively, you can use @code{allocate} and @code{free} which allow
2369: freeing memory in any order:
2370:
2371: @example
2372: 10 cells allocate throw .s
2373: 20 cells allocate throw .s
2374: swap
2375: free throw
2376: free throw
2377: @end example
2378:
2379: The @code{throw}s deal with errors (e.g., out of memory).
2380:
1.65 anton 2381: And there is also a
2382: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2383: garbage collector}, which eliminates the need to @code{free} memory
2384: explicitly.
1.48 anton 2385:
1.66 anton 2386: Reference: @ref{Memory}.
2387:
1.48 anton 2388:
2389: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2390: @section Characters and Strings
1.66 anton 2391: @cindex strings tutorial
2392: @cindex characters tutorial
1.48 anton 2393:
2394: On the stack characters take up a cell, like numbers. In memory they
2395: have their own size (one 8-bit byte on most systems), and therefore
2396: require their own words for memory access:
2397:
2398: @example
2399: create v4
2400: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2401: v4 4 chars + c@@ .
1.65 anton 2402: v4 5 chars dump
1.48 anton 2403: @end example
2404:
2405: The preferred representation of strings on the stack is @code{addr
2406: u-count}, where @code{addr} is the address of the first character and
2407: @code{u-count} is the number of characters in the string.
2408:
2409: @example
2410: v4 5 type
2411: @end example
2412:
2413: You get a string constant with
2414:
2415: @example
2416: s" hello, world" .s
2417: type
2418: @end example
2419:
2420: Make sure you have a space between @code{s"} and the string; @code{s"}
2421: is a normal Forth word and must be delimited with white space (try what
2422: happens when you remove the space).
2423:
2424: However, this interpretive use of @code{s"} is quite restricted: the
2425: string exists only until the next call of @code{s"} (some Forth systems
2426: keep more than one of these strings, but usually they still have a
1.62 crook 2427: limited lifetime).
1.48 anton 2428:
2429: @example
2430: s" hello," s" world" .s
2431: type
2432: type
2433: @end example
2434:
1.62 crook 2435: You can also use @code{s"} in a definition, and the resulting
2436: strings then live forever (well, for as long as the definition):
1.48 anton 2437:
2438: @example
2439: : foo s" hello," s" world" ;
2440: foo .s
2441: type
2442: type
2443: @end example
2444:
1.141 anton 2445: @quotation Assignment
1.48 anton 2446: @code{Emit ( c -- )} types @code{c} as character (not a number).
2447: Implement @code{type ( addr u -- )}.
1.141 anton 2448: @end quotation
1.48 anton 2449:
1.66 anton 2450: Reference: @ref{Memory Blocks}.
2451:
2452:
1.84 pazsan 2453: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2454: @section Alignment
1.66 anton 2455: @cindex alignment tutorial
2456: @cindex memory alignment tutorial
1.48 anton 2457:
2458: On many processors cells have to be aligned in memory, if you want to
2459: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2460: not require alignment, access to aligned cells is faster).
1.48 anton 2461:
2462: @code{Create} aligns @code{here} (i.e., the place where the next
2463: allocation will occur, and that the @code{create}d word points to).
2464: Likewise, the memory produced by @code{allocate} starts at an aligned
2465: address. Adding a number of @code{cells} to an aligned address produces
2466: another aligned address.
2467:
2468: However, address arithmetic involving @code{char+} and @code{chars} can
2469: create an address that is not cell-aligned. @code{Aligned ( addr --
2470: a-addr )} produces the next aligned address:
2471:
2472: @example
1.50 anton 2473: v3 char+ aligned .s @@ .
2474: v3 char+ .s @@ .
1.48 anton 2475: @end example
2476:
2477: Similarly, @code{align} advances @code{here} to the next aligned
2478: address:
2479:
2480: @example
2481: create v5 97 c,
2482: here .
2483: align here .
2484: 1000 ,
2485: @end example
2486:
2487: Note that you should use aligned addresses even if your processor does
2488: not require them, if you want your program to be portable.
2489:
1.66 anton 2490: Reference: @ref{Address arithmetic}.
2491:
1.48 anton 2492:
1.84 pazsan 2493: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2494: @section Files
2495: @cindex files tutorial
2496:
2497: This section gives a short introduction into how to use files inside
2498: Forth. It's broken up into five easy steps:
2499:
2500: @enumerate 1
2501: @item Opened an ASCII text file for input
2502: @item Opened a file for output
2503: @item Read input file until string matched (or some other condition matched)
2504: @item Wrote some lines from input ( modified or not) to output
2505: @item Closed the files.
2506: @end enumerate
2507:
1.153 anton 2508: Reference: @ref{General files}.
2509:
1.84 pazsan 2510: @subsection Open file for input
2511:
2512: @example
2513: s" foo.in" r/o open-file throw Value fd-in
2514: @end example
2515:
2516: @subsection Create file for output
2517:
2518: @example
2519: s" foo.out" w/o create-file throw Value fd-out
2520: @end example
2521:
2522: The available file modes are r/o for read-only access, r/w for
2523: read-write access, and w/o for write-only access. You could open both
2524: files with r/w, too, if you like. All file words return error codes; for
2525: most applications, it's best to pass there error codes with @code{throw}
2526: to the outer error handler.
2527:
2528: If you want words for opening and assigning, define them as follows:
2529:
2530: @example
2531: 0 Value fd-in
2532: 0 Value fd-out
2533: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2534: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2535: @end example
2536:
2537: Usage example:
2538:
2539: @example
2540: s" foo.in" open-input
2541: s" foo.out" open-output
2542: @end example
2543:
2544: @subsection Scan file for a particular line
2545:
2546: @example
2547: 256 Constant max-line
2548: Create line-buffer max-line 2 + allot
2549:
2550: : scan-file ( addr u -- )
2551: begin
2552: line-buffer max-line fd-in read-line throw
2553: while
2554: >r 2dup line-buffer r> compare 0=
2555: until
2556: else
2557: drop
2558: then
2559: 2drop ;
2560: @end example
2561:
2562: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2563: the buffer at addr, and returns the number of bytes read, a flag that is
2564: false when the end of file is reached, and an error code.
1.84 pazsan 2565:
2566: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2567: returns zero if both strings are equal. It returns a positive number if
2568: the first string is lexically greater, a negative if the second string
2569: is lexically greater.
2570:
2571: We haven't seen this loop here; it has two exits. Since the @code{while}
2572: exits with the number of bytes read on the stack, we have to clean up
2573: that separately; that's after the @code{else}.
2574:
2575: Usage example:
2576:
2577: @example
2578: s" The text I search is here" scan-file
2579: @end example
2580:
2581: @subsection Copy input to output
2582:
2583: @example
2584: : copy-file ( -- )
2585: begin
2586: line-buffer max-line fd-in read-line throw
2587: while
2588: line-buffer swap fd-out write-file throw
2589: repeat ;
2590: @end example
2591:
2592: @subsection Close files
2593:
2594: @example
2595: fd-in close-file throw
2596: fd-out close-file throw
2597: @end example
2598:
2599: Likewise, you can put that into definitions, too:
2600:
2601: @example
2602: : close-input ( -- ) fd-in close-file throw ;
2603: : close-output ( -- ) fd-out close-file throw ;
2604: @end example
2605:
1.141 anton 2606: @quotation Assignment
1.84 pazsan 2607: How could you modify @code{copy-file} so that it copies until a second line is
2608: matched? Can you write a program that extracts a section of a text file,
2609: given the line that starts and the line that terminates that section?
1.141 anton 2610: @end quotation
1.84 pazsan 2611:
2612: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2613: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2614: @cindex semantics tutorial
2615: @cindex interpretation semantics tutorial
2616: @cindex compilation semantics tutorial
2617: @cindex immediate, tutorial
1.48 anton 2618:
2619: When a word is compiled, it behaves differently from being interpreted.
2620: E.g., consider @code{+}:
2621:
2622: @example
2623: 1 2 + .
2624: : foo + ;
2625: @end example
2626:
2627: These two behaviours are known as compilation and interpretation
2628: semantics. For normal words (e.g., @code{+}), the compilation semantics
2629: is to append the interpretation semantics to the currently defined word
2630: (@code{foo} in the example above). I.e., when @code{foo} is executed
2631: later, the interpretation semantics of @code{+} (i.e., adding two
2632: numbers) will be performed.
2633:
2634: However, there are words with non-default compilation semantics, e.g.,
2635: the control-flow words like @code{if}. You can use @code{immediate} to
2636: change the compilation semantics of the last defined word to be equal to
2637: the interpretation semantics:
2638:
2639: @example
2640: : [FOO] ( -- )
2641: 5 . ; immediate
2642:
2643: [FOO]
2644: : bar ( -- )
2645: [FOO] ;
2646: bar
2647: see bar
2648: @end example
2649:
2650: Two conventions to mark words with non-default compilation semnatics are
2651: names with brackets (more frequently used) and to write them all in
2652: upper case (less frequently used).
2653:
2654: In Gforth (and many other systems) you can also remove the
2655: interpretation semantics with @code{compile-only} (the compilation
2656: semantics is derived from the original interpretation semantics):
2657:
2658: @example
2659: : flip ( -- )
2660: 6 . ; compile-only \ but not immediate
2661: flip
2662:
2663: : flop ( -- )
2664: flip ;
2665: flop
2666: @end example
2667:
2668: In this example the interpretation semantics of @code{flop} is equal to
2669: the original interpretation semantics of @code{flip}.
2670:
2671: The text interpreter has two states: in interpret state, it performs the
2672: interpretation semantics of words it encounters; in compile state, it
2673: performs the compilation semantics of these words.
2674:
2675: Among other things, @code{:} switches into compile state, and @code{;}
2676: switches back to interpret state. They contain the factors @code{]}
2677: (switch to compile state) and @code{[} (switch to interpret state), that
2678: do nothing but switch the state.
2679:
2680: @example
2681: : xxx ( -- )
2682: [ 5 . ]
2683: ;
2684:
2685: xxx
2686: see xxx
2687: @end example
2688:
2689: These brackets are also the source of the naming convention mentioned
2690: above.
2691:
1.66 anton 2692: Reference: @ref{Interpretation and Compilation Semantics}.
2693:
1.48 anton 2694:
2695: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2696: @section Execution Tokens
1.66 anton 2697: @cindex execution tokens tutorial
2698: @cindex XT tutorial
1.48 anton 2699:
2700: @code{' word} gives you the execution token (XT) of a word. The XT is a
2701: cell representing the interpretation semantics of a word. You can
2702: execute this semantics with @code{execute}:
2703:
2704: @example
2705: ' + .s
2706: 1 2 rot execute .
2707: @end example
2708:
2709: The XT is similar to a function pointer in C. However, parameter
2710: passing through the stack makes it a little more flexible:
2711:
2712: @example
2713: : map-array ( ... addr u xt -- ... )
1.50 anton 2714: \ executes xt ( ... x -- ... ) for every element of the array starting
2715: \ at addr and containing u elements
1.48 anton 2716: @{ xt @}
2717: cells over + swap ?do
1.50 anton 2718: i @@ xt execute
1.48 anton 2719: 1 cells +loop ;
2720:
2721: create a 3 , 4 , 2 , -1 , 4 ,
2722: a 5 ' . map-array .s
2723: 0 a 5 ' + map-array .
2724: s" max-n" environment? drop .s
2725: a 5 ' min map-array .
2726: @end example
2727:
2728: You can use map-array with the XTs of words that consume one element
2729: more than they produce. In theory you can also use it with other XTs,
2730: but the stack effect then depends on the size of the array, which is
2731: hard to understand.
2732:
1.51 pazsan 2733: Since XTs are cell-sized, you can store them in memory and manipulate
2734: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2735: word with @code{compile,}:
2736:
2737: @example
2738: : foo1 ( n1 n2 -- n )
2739: [ ' + compile, ] ;
2740: see foo
2741: @end example
2742:
2743: This is non-standard, because @code{compile,} has no compilation
2744: semantics in the standard, but it works in good Forth systems. For the
2745: broken ones, use
2746:
2747: @example
2748: : [compile,] compile, ; immediate
2749:
2750: : foo1 ( n1 n2 -- n )
2751: [ ' + ] [compile,] ;
2752: see foo
2753: @end example
2754:
2755: @code{'} is a word with default compilation semantics; it parses the
2756: next word when its interpretation semantics are executed, not during
2757: compilation:
2758:
2759: @example
2760: : foo ( -- xt )
2761: ' ;
2762: see foo
2763: : bar ( ... "word" -- ... )
2764: ' execute ;
2765: see bar
1.60 anton 2766: 1 2 bar + .
1.48 anton 2767: @end example
2768:
2769: You often want to parse a word during compilation and compile its XT so
2770: it will be pushed on the stack at run-time. @code{[']} does this:
2771:
2772: @example
2773: : xt-+ ( -- xt )
2774: ['] + ;
2775: see xt-+
2776: 1 2 xt-+ execute .
2777: @end example
2778:
2779: Many programmers tend to see @code{'} and the word it parses as one
2780: unit, and expect it to behave like @code{[']} when compiled, and are
2781: confused by the actual behaviour. If you are, just remember that the
2782: Forth system just takes @code{'} as one unit and has no idea that it is
2783: a parsing word (attempts to convenience programmers in this issue have
2784: usually resulted in even worse pitfalls, see
1.66 anton 2785: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2786: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2787:
2788: Note that the state of the interpreter does not come into play when
1.51 pazsan 2789: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2790: compile state, it still gives you the interpretation semantics. And
2791: whatever that state is, @code{execute} performs the semantics
1.66 anton 2792: represented by the XT (i.e., for XTs produced with @code{'} the
2793: interpretation semantics).
2794:
2795: Reference: @ref{Tokens for Words}.
1.48 anton 2796:
2797:
2798: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2799: @section Exceptions
1.66 anton 2800: @cindex exceptions tutorial
1.48 anton 2801:
2802: @code{throw ( n -- )} causes an exception unless n is zero.
2803:
2804: @example
2805: 100 throw .s
2806: 0 throw .s
2807: @end example
2808:
2809: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2810: it catches exceptions and pushes the number of the exception on the
2811: stack (or 0, if the xt executed without exception). If there was an
2812: exception, the stacks have the same depth as when entering @code{catch}:
2813:
2814: @example
2815: .s
2816: 3 0 ' / catch .s
2817: 3 2 ' / catch .s
2818: @end example
2819:
1.141 anton 2820: @quotation Assignment
1.48 anton 2821: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2822: @end quotation
1.48 anton 2823:
2824: @code{Throw} always jumps to the dynamically next enclosing
2825: @code{catch}, even if it has to leave several call levels to achieve
2826: this:
2827:
2828: @example
2829: : foo 100 throw ;
2830: : foo1 foo ." after foo" ;
1.51 pazsan 2831: : bar ['] foo1 catch ;
1.60 anton 2832: bar .
1.48 anton 2833: @end example
2834:
2835: It is often important to restore a value upon leaving a definition, even
2836: if the definition is left through an exception. You can ensure this
2837: like this:
2838:
2839: @example
2840: : ...
2841: save-x
1.51 pazsan 2842: ['] word-changing-x catch ( ... n )
1.48 anton 2843: restore-x
2844: ( ... n ) throw ;
2845: @end example
2846:
1.55 anton 2847: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2848: @code{try ... recover ... endtry}. If the code between @code{try} and
2849: @code{recover} has an exception, the stack depths are restored, the
2850: exception number is pushed on the stack, and the code between
2851: @code{recover} and @code{endtry} is performed. E.g., the definition for
2852: @code{catch} is
2853:
2854: @example
2855: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2856: try
2857: execute 0
2858: recover
2859: nip
2860: endtry ;
2861: @end example
2862:
2863: The equivalent to the restoration code above is
2864:
2865: @example
2866: : ...
2867: save-x
2868: try
1.92 anton 2869: word-changing-x 0
2870: recover endtry
1.48 anton 2871: restore-x
2872: throw ;
2873: @end example
2874:
1.92 anton 2875: This works if @code{word-changing-x} does not change the stack depth,
2876: otherwise you should add some code between @code{recover} and
2877: @code{endtry} to balance the stack.
1.48 anton 2878:
1.66 anton 2879: Reference: @ref{Exception Handling}.
2880:
1.48 anton 2881:
2882: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2883: @section Defining Words
1.66 anton 2884: @cindex defining words tutorial
2885: @cindex does> tutorial
2886: @cindex create...does> tutorial
2887:
2888: @c before semantics?
1.48 anton 2889:
2890: @code{:}, @code{create}, and @code{variable} are definition words: They
2891: define other words. @code{Constant} is another definition word:
2892:
2893: @example
2894: 5 constant foo
2895: foo .
2896: @end example
2897:
2898: You can also use the prefixes @code{2} (double-cell) and @code{f}
2899: (floating point) with @code{variable} and @code{constant}.
2900:
2901: You can also define your own defining words. E.g.:
2902:
2903: @example
2904: : variable ( "name" -- )
2905: create 0 , ;
2906: @end example
2907:
2908: You can also define defining words that create words that do something
2909: other than just producing their address:
2910:
2911: @example
2912: : constant ( n "name" -- )
2913: create ,
2914: does> ( -- n )
1.50 anton 2915: ( addr ) @@ ;
1.48 anton 2916:
2917: 5 constant foo
2918: foo .
2919: @end example
2920:
2921: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2922: @code{does>} replaces @code{;}, but it also does something else: It
2923: changes the last defined word such that it pushes the address of the
2924: body of the word and then performs the code after the @code{does>}
2925: whenever it is called.
2926:
2927: In the example above, @code{constant} uses @code{,} to store 5 into the
2928: body of @code{foo}. When @code{foo} executes, it pushes the address of
2929: the body onto the stack, then (in the code after the @code{does>})
2930: fetches the 5 from there.
2931:
2932: The stack comment near the @code{does>} reflects the stack effect of the
2933: defined word, not the stack effect of the code after the @code{does>}
2934: (the difference is that the code expects the address of the body that
2935: the stack comment does not show).
2936:
2937: You can use these definition words to do factoring in cases that involve
2938: (other) definition words. E.g., a field offset is always added to an
2939: address. Instead of defining
2940:
2941: @example
2942: 2 cells constant offset-field1
2943: @end example
2944:
2945: and using this like
2946:
2947: @example
2948: ( addr ) offset-field1 +
2949: @end example
2950:
2951: you can define a definition word
2952:
2953: @example
2954: : simple-field ( n "name" -- )
2955: create ,
2956: does> ( n1 -- n1+n )
1.50 anton 2957: ( addr ) @@ + ;
1.48 anton 2958: @end example
1.21 crook 2959:
1.48 anton 2960: Definition and use of field offsets now look like this:
1.21 crook 2961:
1.48 anton 2962: @example
2963: 2 cells simple-field field1
1.60 anton 2964: create mystruct 4 cells allot
2965: mystruct .s field1 .s drop
1.48 anton 2966: @end example
1.21 crook 2967:
1.48 anton 2968: If you want to do something with the word without performing the code
2969: after the @code{does>}, you can access the body of a @code{create}d word
2970: with @code{>body ( xt -- addr )}:
1.21 crook 2971:
1.48 anton 2972: @example
2973: : value ( n "name" -- )
2974: create ,
2975: does> ( -- n1 )
1.50 anton 2976: @@ ;
1.48 anton 2977: : to ( n "name" -- )
2978: ' >body ! ;
1.21 crook 2979:
1.48 anton 2980: 5 value foo
2981: foo .
2982: 7 to foo
2983: foo .
2984: @end example
1.21 crook 2985:
1.141 anton 2986: @quotation Assignment
1.48 anton 2987: Define @code{defer ( "name" -- )}, which creates a word that stores an
2988: XT (at the start the XT of @code{abort}), and upon execution
2989: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2990: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2991: recursion is one application of @code{defer}.
1.141 anton 2992: @end quotation
1.29 crook 2993:
1.66 anton 2994: Reference: @ref{User-defined Defining Words}.
2995:
2996:
1.48 anton 2997: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2998: @section Arrays and Records
1.66 anton 2999: @cindex arrays tutorial
3000: @cindex records tutorial
3001: @cindex structs tutorial
1.29 crook 3002:
1.48 anton 3003: Forth has no standard words for defining data structures such as arrays
3004: and records (structs in C terminology), but you can build them yourself
3005: based on address arithmetic. You can also define words for defining
3006: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3007:
1.48 anton 3008: One of the first projects a Forth newcomer sets out upon when learning
3009: about defining words is an array defining word (possibly for
3010: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3011: learn something from it. However, don't be disappointed when you later
3012: learn that you have little use for these words (inappropriate use would
3013: be even worse). I have not yet found a set of useful array words yet;
3014: the needs are just too diverse, and named, global arrays (the result of
3015: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3016: consider how to pass them as parameters). Another such project is a set
3017: of words to help dealing with strings.
1.29 crook 3018:
1.48 anton 3019: On the other hand, there is a useful set of record words, and it has
3020: been defined in @file{compat/struct.fs}; these words are predefined in
3021: Gforth. They are explained in depth elsewhere in this manual (see
3022: @pxref{Structures}). The @code{simple-field} example above is
3023: simplified variant of fields in this package.
1.21 crook 3024:
3025:
1.48 anton 3026: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3027: @section @code{POSTPONE}
1.66 anton 3028: @cindex postpone tutorial
1.21 crook 3029:
1.48 anton 3030: You can compile the compilation semantics (instead of compiling the
3031: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3032:
1.48 anton 3033: @example
3034: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3035: POSTPONE + ; immediate
1.48 anton 3036: : foo ( n1 n2 -- n )
3037: MY-+ ;
3038: 1 2 foo .
3039: see foo
3040: @end example
1.21 crook 3041:
1.48 anton 3042: During the definition of @code{foo} the text interpreter performs the
3043: compilation semantics of @code{MY-+}, which performs the compilation
3044: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3045:
3046: This example also displays separate stack comments for the compilation
3047: semantics and for the stack effect of the compiled code. For words with
3048: default compilation semantics these stack effects are usually not
3049: displayed; the stack effect of the compilation semantics is always
3050: @code{( -- )} for these words, the stack effect for the compiled code is
3051: the stack effect of the interpretation semantics.
3052:
3053: Note that the state of the interpreter does not come into play when
3054: performing the compilation semantics in this way. You can also perform
3055: it interpretively, e.g.:
3056:
3057: @example
3058: : foo2 ( n1 n2 -- n )
3059: [ MY-+ ] ;
3060: 1 2 foo .
3061: see foo
3062: @end example
1.21 crook 3063:
1.48 anton 3064: However, there are some broken Forth systems where this does not always
1.62 crook 3065: work, and therefore this practice was been declared non-standard in
1.48 anton 3066: 1999.
3067: @c !! repair.fs
3068:
3069: Here is another example for using @code{POSTPONE}:
1.44 crook 3070:
1.48 anton 3071: @example
3072: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3073: POSTPONE negate POSTPONE + ; immediate compile-only
3074: : bar ( n1 n2 -- n )
3075: MY-- ;
3076: 2 1 bar .
3077: see bar
3078: @end example
1.21 crook 3079:
1.48 anton 3080: You can define @code{ENDIF} in this way:
1.21 crook 3081:
1.48 anton 3082: @example
3083: : ENDIF ( Compilation: orig -- )
3084: POSTPONE then ; immediate
3085: @end example
1.21 crook 3086:
1.141 anton 3087: @quotation Assignment
1.48 anton 3088: Write @code{MY-2DUP} that has compilation semantics equivalent to
3089: @code{2dup}, but compiles @code{over over}.
1.141 anton 3090: @end quotation
1.29 crook 3091:
1.66 anton 3092: @c !! @xref{Macros} for reference
3093:
3094:
1.48 anton 3095: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3096: @section @code{Literal}
1.66 anton 3097: @cindex literal tutorial
1.29 crook 3098:
1.48 anton 3099: You cannot @code{POSTPONE} numbers:
1.21 crook 3100:
1.48 anton 3101: @example
3102: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3103: @end example
3104:
1.48 anton 3105: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3106:
1.48 anton 3107: @example
3108: : [FOO] ( compilation: --; run-time: -- n )
3109: 500 POSTPONE literal ; immediate
1.29 crook 3110:
1.60 anton 3111: : flip [FOO] ;
1.48 anton 3112: flip .
3113: see flip
3114: @end example
1.29 crook 3115:
1.48 anton 3116: @code{LITERAL} consumes a number at compile-time (when it's compilation
3117: semantics are executed) and pushes it at run-time (when the code it
3118: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3119: number computed at compile time into the current word:
1.29 crook 3120:
1.48 anton 3121: @example
3122: : bar ( -- n )
3123: [ 2 2 + ] literal ;
3124: see bar
3125: @end example
1.29 crook 3126:
1.141 anton 3127: @quotation Assignment
1.48 anton 3128: Write @code{]L} which allows writing the example above as @code{: bar (
3129: -- n ) [ 2 2 + ]L ;}
1.141 anton 3130: @end quotation
1.48 anton 3131:
1.66 anton 3132: @c !! @xref{Macros} for reference
3133:
1.48 anton 3134:
3135: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3136: @section Advanced macros
1.66 anton 3137: @cindex macros, advanced tutorial
3138: @cindex run-time code generation, tutorial
1.48 anton 3139:
1.66 anton 3140: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3141: Execution Tokens}. It frequently performs @code{execute}, a relatively
3142: expensive operation in some Forth implementations. You can use
1.48 anton 3143: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3144: and produce a word that contains the word to be performed directly:
3145:
3146: @c use ]] ... [[
3147: @example
3148: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3149: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3150: \ array beginning at addr and containing u elements
3151: @{ xt @}
3152: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3153: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3154: 1 cells POSTPONE literal POSTPONE +loop ;
3155:
3156: : sum-array ( addr u -- n )
3157: 0 rot rot [ ' + compile-map-array ] ;
3158: see sum-array
3159: a 5 sum-array .
3160: @end example
3161:
3162: You can use the full power of Forth for generating the code; here's an
3163: example where the code is generated in a loop:
3164:
3165: @example
3166: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3167: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3168: POSTPONE tuck POSTPONE @@
1.48 anton 3169: POSTPONE literal POSTPONE * POSTPONE +
3170: POSTPONE swap POSTPONE cell+ ;
3171:
3172: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3173: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3174: 0 postpone literal postpone swap
3175: [ ' compile-vmul-step compile-map-array ]
3176: postpone drop ;
3177: see compile-vmul
3178:
3179: : a-vmul ( addr -- n )
1.51 pazsan 3180: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3181: [ a 5 compile-vmul ] ;
3182: see a-vmul
3183: a a-vmul .
3184: @end example
3185:
3186: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3187: also use @code{map-array} instead (try it now!).
1.48 anton 3188:
3189: You can use this technique for efficient multiplication of large
3190: matrices. In matrix multiplication, you multiply every line of one
3191: matrix with every column of the other matrix. You can generate the code
3192: for one line once, and use it for every column. The only downside of
3193: this technique is that it is cumbersome to recover the memory consumed
3194: by the generated code when you are done (and in more complicated cases
3195: it is not possible portably).
3196:
1.66 anton 3197: @c !! @xref{Macros} for reference
3198:
3199:
1.48 anton 3200: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3201: @section Compilation Tokens
1.66 anton 3202: @cindex compilation tokens, tutorial
3203: @cindex CT, tutorial
1.48 anton 3204:
3205: This section is Gforth-specific. You can skip it.
3206:
3207: @code{' word compile,} compiles the interpretation semantics. For words
3208: with default compilation semantics this is the same as performing the
3209: compilation semantics. To represent the compilation semantics of other
3210: words (e.g., words like @code{if} that have no interpretation
3211: semantics), Gforth has the concept of a compilation token (CT,
3212: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3213: You can perform the compilation semantics represented by a CT with
3214: @code{execute}:
1.29 crook 3215:
1.48 anton 3216: @example
3217: : foo2 ( n1 n2 -- n )
3218: [ comp' + execute ] ;
3219: see foo
3220: @end example
1.29 crook 3221:
1.48 anton 3222: You can compile the compilation semantics represented by a CT with
3223: @code{postpone,}:
1.30 anton 3224:
1.48 anton 3225: @example
3226: : foo3 ( -- )
3227: [ comp' + postpone, ] ;
3228: see foo3
3229: @end example
1.30 anton 3230:
1.51 pazsan 3231: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3232: @code{comp'} is particularly useful for words that have no
3233: interpretation semantics:
1.29 crook 3234:
1.30 anton 3235: @example
1.48 anton 3236: ' if
1.60 anton 3237: comp' if .s 2drop
1.30 anton 3238: @end example
3239:
1.66 anton 3240: Reference: @ref{Tokens for Words}.
3241:
1.29 crook 3242:
1.48 anton 3243: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3244: @section Wordlists and Search Order
1.66 anton 3245: @cindex wordlists tutorial
3246: @cindex search order, tutorial
1.48 anton 3247:
3248: The dictionary is not just a memory area that allows you to allocate
3249: memory with @code{allot}, it also contains the Forth words, arranged in
3250: several wordlists. When searching for a word in a wordlist,
3251: conceptually you start searching at the youngest and proceed towards
3252: older words (in reality most systems nowadays use hash-tables); i.e., if
3253: you define a word with the same name as an older word, the new word
3254: shadows the older word.
3255:
3256: Which wordlists are searched in which order is determined by the search
3257: order. You can display the search order with @code{order}. It displays
3258: first the search order, starting with the wordlist searched first, then
3259: it displays the wordlist that will contain newly defined words.
1.21 crook 3260:
1.48 anton 3261: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3262:
1.48 anton 3263: @example
3264: wordlist constant mywords
3265: @end example
1.21 crook 3266:
1.48 anton 3267: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3268: defined words (the @emph{current} wordlist):
1.21 crook 3269:
1.48 anton 3270: @example
3271: mywords set-current
3272: order
3273: @end example
1.26 crook 3274:
1.48 anton 3275: Gforth does not display a name for the wordlist in @code{mywords}
3276: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3277:
1.48 anton 3278: You can get the current wordlist with @code{get-current ( -- wid)}. If
3279: you want to put something into a specific wordlist without overall
3280: effect on the current wordlist, this typically looks like this:
1.21 crook 3281:
1.48 anton 3282: @example
3283: get-current mywords set-current ( wid )
3284: create someword
3285: ( wid ) set-current
3286: @end example
1.21 crook 3287:
1.48 anton 3288: You can write the search order with @code{set-order ( wid1 .. widn n --
3289: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3290: searched wordlist is topmost.
1.21 crook 3291:
1.48 anton 3292: @example
3293: get-order mywords swap 1+ set-order
3294: order
3295: @end example
1.21 crook 3296:
1.48 anton 3297: Yes, the order of wordlists in the output of @code{order} is reversed
3298: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3299:
1.141 anton 3300: @quotation Assignment
1.48 anton 3301: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3302: wordlist to the search order. Define @code{previous ( -- )}, which
3303: removes the first searched wordlist from the search order. Experiment
3304: with boundary conditions (you will see some crashes or situations that
3305: are hard or impossible to leave).
1.141 anton 3306: @end quotation
1.21 crook 3307:
1.48 anton 3308: The search order is a powerful foundation for providing features similar
3309: to Modula-2 modules and C++ namespaces. However, trying to modularize
3310: programs in this way has disadvantages for debugging and reuse/factoring
3311: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3312: though). These disadvantages are not so clear in other
1.82 anton 3313: languages/programming environments, because these languages are not so
1.48 anton 3314: strong in debugging and reuse.
1.21 crook 3315:
1.66 anton 3316: @c !! example
3317:
3318: Reference: @ref{Word Lists}.
1.21 crook 3319:
1.29 crook 3320: @c ******************************************************************
1.48 anton 3321: @node Introduction, Words, Tutorial, Top
1.29 crook 3322: @comment node-name, next, previous, up
3323: @chapter An Introduction to ANS Forth
3324: @cindex Forth - an introduction
1.21 crook 3325:
1.83 anton 3326: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3327: that it is slower-paced in its examples, but uses them to dive deep into
3328: explaining Forth internals (not covered by the Tutorial). Apart from
3329: that, this chapter covers far less material. It is suitable for reading
3330: without using a computer.
3331:
1.29 crook 3332: The primary purpose of this manual is to document Gforth. However, since
3333: Forth is not a widely-known language and there is a lack of up-to-date
3334: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3335: material. For other sources of Forth-related
3336: information, see @ref{Forth-related information}.
1.21 crook 3337:
1.29 crook 3338: The examples in this section should work on any ANS Forth; the
3339: output shown was produced using Gforth. Each example attempts to
3340: reproduce the exact output that Gforth produces. If you try out the
3341: examples (and you should), what you should type is shown @kbd{like this}
3342: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3343: that, where the example shows @key{RET} it means that you should
1.29 crook 3344: press the ``carriage return'' key. Unfortunately, some output formats for
3345: this manual cannot show the difference between @kbd{this} and
3346: @code{this} which will make trying out the examples harder (but not
3347: impossible).
1.21 crook 3348:
1.29 crook 3349: Forth is an unusual language. It provides an interactive development
3350: environment which includes both an interpreter and compiler. Forth
3351: programming style encourages you to break a problem down into many
3352: @cindex factoring
3353: small fragments (@dfn{factoring}), and then to develop and test each
3354: fragment interactively. Forth advocates assert that breaking the
3355: edit-compile-test cycle used by conventional programming languages can
3356: lead to great productivity improvements.
1.21 crook 3357:
1.29 crook 3358: @menu
1.67 anton 3359: * Introducing the Text Interpreter::
3360: * Stacks and Postfix notation::
3361: * Your first definition::
3362: * How does that work?::
3363: * Forth is written in Forth::
3364: * Review - elements of a Forth system::
3365: * Where to go next::
3366: * Exercises::
1.29 crook 3367: @end menu
1.21 crook 3368:
1.29 crook 3369: @comment ----------------------------------------------
3370: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3371: @section Introducing the Text Interpreter
3372: @cindex text interpreter
3373: @cindex outer interpreter
1.21 crook 3374:
1.30 anton 3375: @c IMO this is too detailed and the pace is too slow for
3376: @c an introduction. If you know German, take a look at
3377: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3378: @c to see how I do it - anton
3379:
1.44 crook 3380: @c nac-> Where I have accepted your comments 100% and modified the text
3381: @c accordingly, I have deleted your comments. Elsewhere I have added a
3382: @c response like this to attempt to rationalise what I have done. Of
3383: @c course, this is a very clumsy mechanism for something that would be
3384: @c done far more efficiently over a beer. Please delete any dialogue
3385: @c you consider closed.
3386:
1.29 crook 3387: When you invoke the Forth image, you will see a startup banner printed
3388: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3389: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3390: its command line interpreter, which is called the @dfn{Text Interpreter}
3391: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3392: about the text interpreter as you read through this chapter, for more
3393: detail @pxref{The Text Interpreter}).
1.21 crook 3394:
1.29 crook 3395: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3396: input. Type a number and press the @key{RET} key:
1.21 crook 3397:
1.26 crook 3398: @example
1.30 anton 3399: @kbd{45@key{RET}} ok
1.26 crook 3400: @end example
1.21 crook 3401:
1.29 crook 3402: Rather than give you a prompt to invite you to input something, the text
3403: interpreter prints a status message @i{after} it has processed a line
3404: of input. The status message in this case (``@code{ ok}'' followed by
3405: carriage-return) indicates that the text interpreter was able to process
3406: all of your input successfully. Now type something illegal:
3407:
3408: @example
1.30 anton 3409: @kbd{qwer341@key{RET}}
1.134 anton 3410: *the terminal*:2: Undefined word
3411: >>>qwer341<<<
3412: Backtrace:
3413: $2A95B42A20 throw
3414: $2A95B57FB8 no.extensions
1.29 crook 3415: @end example
1.23 crook 3416:
1.134 anton 3417: The exact text, other than the ``Undefined word'' may differ slightly
3418: on your system, but the effect is the same; when the text interpreter
1.29 crook 3419: detects an error, it discards any remaining text on a line, resets
1.134 anton 3420: certain internal state and prints an error message. For a detailed
3421: description of error messages see @ref{Error messages}.
1.23 crook 3422:
1.29 crook 3423: The text interpreter waits for you to press carriage-return, and then
3424: processes your input line. Starting at the beginning of the line, it
3425: breaks the line into groups of characters separated by spaces. For each
3426: group of characters in turn, it makes two attempts to do something:
1.23 crook 3427:
1.29 crook 3428: @itemize @bullet
3429: @item
1.44 crook 3430: @cindex name dictionary
1.29 crook 3431: It tries to treat it as a command. It does this by searching a @dfn{name
3432: dictionary}. If the group of characters matches an entry in the name
3433: dictionary, the name dictionary provides the text interpreter with
3434: information that allows the text interpreter perform some actions. In
3435: Forth jargon, we say that the group
3436: @cindex word
3437: @cindex definition
3438: @cindex execution token
3439: @cindex xt
3440: of characters names a @dfn{word}, that the dictionary search returns an
3441: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3442: word, and that the text interpreter executes the xt. Often, the terms
3443: @dfn{word} and @dfn{definition} are used interchangeably.
3444: @item
3445: If the text interpreter fails to find a match in the name dictionary, it
3446: tries to treat the group of characters as a number in the current number
3447: base (when you start up Forth, the current number base is base 10). If
3448: the group of characters legitimately represents a number, the text
3449: interpreter pushes the number onto a stack (we'll learn more about that
3450: in the next section).
3451: @end itemize
1.23 crook 3452:
1.29 crook 3453: If the text interpreter is unable to do either of these things with any
3454: group of characters, it discards the group of characters and the rest of
3455: the line, then prints an error message. If the text interpreter reaches
3456: the end of the line without error, it prints the status message ``@code{ ok}''
3457: followed by carriage-return.
1.21 crook 3458:
1.29 crook 3459: This is the simplest command we can give to the text interpreter:
1.23 crook 3460:
3461: @example
1.30 anton 3462: @key{RET} ok
1.23 crook 3463: @end example
1.21 crook 3464:
1.29 crook 3465: The text interpreter did everything we asked it to do (nothing) without
3466: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3467: command:
1.21 crook 3468:
1.23 crook 3469: @example
1.30 anton 3470: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3471: *the terminal*:3: Undefined word
3472: 12 dup >>>fred<<< dup
3473: Backtrace:
3474: $2A95B42A20 throw
3475: $2A95B57FB8 no.extensions
1.23 crook 3476: @end example
1.21 crook 3477:
1.29 crook 3478: When you press the carriage-return key, the text interpreter starts to
3479: work its way along the line:
1.21 crook 3480:
1.29 crook 3481: @itemize @bullet
3482: @item
3483: When it gets to the space after the @code{2}, it takes the group of
3484: characters @code{12} and looks them up in the name
3485: dictionary@footnote{We can't tell if it found them or not, but assume
3486: for now that it did not}. There is no match for this group of characters
3487: in the name dictionary, so it tries to treat them as a number. It is
3488: able to do this successfully, so it puts the number, 12, ``on the stack''
3489: (whatever that means).
3490: @item
3491: The text interpreter resumes scanning the line and gets the next group
3492: of characters, @code{dup}. It looks it up in the name dictionary and
3493: (you'll have to take my word for this) finds it, and executes the word
3494: @code{dup} (whatever that means).
3495: @item
3496: Once again, the text interpreter resumes scanning the line and gets the
3497: group of characters @code{fred}. It looks them up in the name
3498: dictionary, but can't find them. It tries to treat them as a number, but
3499: they don't represent any legal number.
3500: @end itemize
1.21 crook 3501:
1.29 crook 3502: At this point, the text interpreter gives up and prints an error
3503: message. The error message shows exactly how far the text interpreter
3504: got in processing the line. In particular, it shows that the text
3505: interpreter made no attempt to do anything with the final character
3506: group, @code{dup}, even though we have good reason to believe that the
3507: text interpreter would have no problem looking that word up and
3508: executing it a second time.
1.21 crook 3509:
3510:
1.29 crook 3511: @comment ----------------------------------------------
3512: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3513: @section Stacks, postfix notation and parameter passing
3514: @cindex text interpreter
3515: @cindex outer interpreter
1.21 crook 3516:
1.29 crook 3517: In procedural programming languages (like C and Pascal), the
3518: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3519: functions or procedures are called with @dfn{explicit parameters}. For
3520: example, in C we might write:
1.21 crook 3521:
1.23 crook 3522: @example
1.29 crook 3523: total = total + new_volume(length,height,depth);
1.23 crook 3524: @end example
1.21 crook 3525:
1.23 crook 3526: @noindent
1.29 crook 3527: where new_volume is a function-call to another piece of code, and total,
3528: length, height and depth are all variables. length, height and depth are
3529: parameters to the function-call.
1.21 crook 3530:
1.29 crook 3531: In Forth, the equivalent of the function or procedure is the
3532: @dfn{definition} and parameters are implicitly passed between
3533: definitions using a shared stack that is visible to the
3534: programmer. Although Forth does support variables, the existence of the
3535: stack means that they are used far less often than in most other
3536: programming languages. When the text interpreter encounters a number, it
3537: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3538: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3539: used for any operation is implied unambiguously by the operation being
3540: performed. The stack used for all integer operations is called the @dfn{data
3541: stack} and, since this is the stack used most commonly, references to
3542: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3543:
1.29 crook 3544: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3545:
1.23 crook 3546: @example
1.30 anton 3547: @kbd{1 2 3@key{RET}} ok
1.23 crook 3548: @end example
1.21 crook 3549:
1.29 crook 3550: Then this instructs the text interpreter to placed three numbers on the
3551: (data) stack. An analogy for the behaviour of the stack is to take a
3552: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3553: the table. The 3 was the last card onto the pile (``last-in'') and if
3554: you take a card off the pile then, unless you're prepared to fiddle a
3555: bit, the card that you take off will be the 3 (``first-out''). The
3556: number that will be first-out of the stack is called the @dfn{top of
3557: stack}, which
3558: @cindex TOS definition
3559: is often abbreviated to @dfn{TOS}.
1.21 crook 3560:
1.29 crook 3561: To understand how parameters are passed in Forth, consider the
3562: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3563: be surprised to learn that this definition performs addition. More
3564: precisely, it adds two number together and produces a result. Where does
3565: it get the two numbers from? It takes the top two numbers off the
3566: stack. Where does it place the result? On the stack. You can act-out the
3567: behaviour of @code{+} with your playing cards like this:
1.21 crook 3568:
3569: @itemize @bullet
3570: @item
1.29 crook 3571: Pick up two cards from the stack on the table
1.21 crook 3572: @item
1.29 crook 3573: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3574: numbers''
1.21 crook 3575: @item
1.29 crook 3576: Decide that the answer is 5
1.21 crook 3577: @item
1.29 crook 3578: Shuffle the two cards back into the pack and find a 5
1.21 crook 3579: @item
1.29 crook 3580: Put a 5 on the remaining ace that's on the table.
1.21 crook 3581: @end itemize
3582:
1.29 crook 3583: If you don't have a pack of cards handy but you do have Forth running,
3584: you can use the definition @code{.s} to show the current state of the stack,
3585: without affecting the stack. Type:
1.21 crook 3586:
3587: @example
1.124 anton 3588: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3589: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3590: @end example
3591:
1.124 anton 3592: The text interpreter looks up the word @code{clearstacks} and executes
3593: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3594: left on it by earlier examples. The text interpreter pushes each of the
3595: three numbers in turn onto the stack. Finally, the text interpreter
3596: looks up the word @code{.s} and executes it. The effect of executing
3597: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3598: followed by a list of all the items on the stack; the item on the far
3599: right-hand side is the TOS.
1.21 crook 3600:
1.29 crook 3601: You can now type:
1.21 crook 3602:
1.29 crook 3603: @example
1.30 anton 3604: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3605: @end example
1.21 crook 3606:
1.29 crook 3607: @noindent
3608: which is correct; there are now 2 items on the stack and the result of
3609: the addition is 5.
1.23 crook 3610:
1.29 crook 3611: If you're playing with cards, try doing a second addition: pick up the
3612: two cards, work out that their sum is 6, shuffle them into the pack,
3613: look for a 6 and place that on the table. You now have just one item on
3614: the stack. What happens if you try to do a third addition? Pick up the
3615: first card, pick up the second card -- ah! There is no second card. This
3616: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3617: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3618: Underflow or an Invalid Memory Address error).
1.23 crook 3619:
1.29 crook 3620: The opposite situation to a stack underflow is a @dfn{stack overflow},
3621: which simply accepts that there is a finite amount of storage space
3622: reserved for the stack. To stretch the playing card analogy, if you had
3623: enough packs of cards and you piled the cards up on the table, you would
3624: eventually be unable to add another card; you'd hit the ceiling. Gforth
3625: allows you to set the maximum size of the stacks. In general, the only
3626: time that you will get a stack overflow is because a definition has a
3627: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3628:
1.29 crook 3629: There's one final use for the playing card analogy. If you model your
3630: stack using a pack of playing cards, the maximum number of items on
3631: your stack will be 52 (I assume you didn't use the Joker). The maximum
3632: @i{value} of any item on the stack is 13 (the King). In fact, the only
3633: possible numbers are positive integer numbers 1 through 13; you can't
3634: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3635: think about some of the cards, you can accommodate different
3636: numbers. For example, you could think of the Jack as representing 0,
3637: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3638: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3639: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3640:
1.29 crook 3641: In that analogy, the limit was the amount of information that a single
3642: stack entry could hold, and Forth has a similar limit. In Forth, the
3643: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3644: implementation dependent and affects the maximum value that a stack
3645: entry can hold. A Standard Forth provides a cell size of at least
3646: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3647:
1.29 crook 3648: Forth does not do any type checking for you, so you are free to
3649: manipulate and combine stack items in any way you wish. A convenient way
3650: of treating stack items is as 2's complement signed integers, and that
3651: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3652:
1.29 crook 3653: @example
1.30 anton 3654: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3655: @end example
1.21 crook 3656:
1.29 crook 3657: If you use numbers and definitions like @code{+} in order to turn Forth
3658: into a great big pocket calculator, you will realise that it's rather
3659: different from a normal calculator. Rather than typing 2 + 3 = you had
3660: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3661: result). The terminology used to describe this difference is to say that
3662: your calculator uses @dfn{Infix Notation} (parameters and operators are
3663: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3664: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3665:
1.29 crook 3666: Whilst postfix notation might look confusing to begin with, it has
3667: several important advantages:
1.21 crook 3668:
1.23 crook 3669: @itemize @bullet
3670: @item
1.29 crook 3671: it is unambiguous
1.23 crook 3672: @item
1.29 crook 3673: it is more concise
1.23 crook 3674: @item
1.29 crook 3675: it fits naturally with a stack-based system
1.23 crook 3676: @end itemize
1.21 crook 3677:
1.29 crook 3678: To examine these claims in more detail, consider these sums:
1.21 crook 3679:
1.29 crook 3680: @example
3681: 6 + 5 * 4 =
3682: 4 * 5 + 6 =
3683: @end example
1.21 crook 3684:
1.29 crook 3685: If you're just learning maths or your maths is very rusty, you will
3686: probably come up with the answer 44 for the first and 26 for the
3687: second. If you are a bit of a whizz at maths you will remember the
3688: @i{convention} that multiplication takes precendence over addition, and
3689: you'd come up with the answer 26 both times. To explain the answer 26
3690: to someone who got the answer 44, you'd probably rewrite the first sum
3691: like this:
1.21 crook 3692:
1.29 crook 3693: @example
3694: 6 + (5 * 4) =
3695: @end example
1.21 crook 3696:
1.29 crook 3697: If what you really wanted was to perform the addition before the
3698: multiplication, you would have to use parentheses to force it.
1.21 crook 3699:
1.29 crook 3700: If you did the first two sums on a pocket calculator you would probably
3701: get the right answers, unless you were very cautious and entered them using
3702: these keystroke sequences:
1.21 crook 3703:
1.29 crook 3704: 6 + 5 = * 4 =
3705: 4 * 5 = + 6 =
1.21 crook 3706:
1.29 crook 3707: Postfix notation is unambiguous because the order that the operators
3708: are applied is always explicit; that also means that parentheses are
3709: never required. The operators are @i{active} (the act of quoting the
3710: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3711:
1.29 crook 3712: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3713: equivalent ways:
1.26 crook 3714:
3715: @example
1.29 crook 3716: 6 5 4 * + or:
3717: 5 4 * 6 +
1.26 crook 3718: @end example
1.23 crook 3719:
1.29 crook 3720: An important thing that you should notice about this notation is that
3721: the @i{order} of the numbers does not change; if you want to subtract
3722: 2 from 10 you type @code{10 2 -}.
1.1 anton 3723:
1.29 crook 3724: The reason that Forth uses postfix notation is very simple to explain: it
3725: makes the implementation extremely simple, and it follows naturally from
3726: using the stack as a mechanism for passing parameters. Another way of
3727: thinking about this is to realise that all Forth definitions are
3728: @i{active}; they execute as they are encountered by the text
3729: interpreter. The result of this is that the syntax of Forth is trivially
3730: simple.
1.1 anton 3731:
3732:
3733:
1.29 crook 3734: @comment ----------------------------------------------
3735: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3736: @section Your first Forth definition
3737: @cindex first definition
1.1 anton 3738:
1.29 crook 3739: Until now, the examples we've seen have been trivial; we've just been
3740: using Forth as a bigger-than-pocket calculator. Also, each calculation
3741: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3742: again@footnote{That's not quite true. If you press the up-arrow key on
3743: your keyboard you should be able to scroll back to any earlier command,
3744: edit it and re-enter it.} In this section we'll see how to add new
3745: words to Forth's vocabulary.
1.1 anton 3746:
1.29 crook 3747: The easiest way to create a new word is to use a @dfn{colon
3748: definition}. We'll define a few and try them out before worrying too
3749: much about how they work. Try typing in these examples; be careful to
3750: copy the spaces accurately:
1.1 anton 3751:
1.29 crook 3752: @example
3753: : add-two 2 + . ;
3754: : greet ." Hello and welcome" ;
3755: : demo 5 add-two ;
3756: @end example
1.1 anton 3757:
1.29 crook 3758: @noindent
3759: Now try them out:
1.1 anton 3760:
1.29 crook 3761: @example
1.30 anton 3762: @kbd{greet@key{RET}} Hello and welcome ok
3763: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3764: @kbd{4 add-two@key{RET}} 6 ok
3765: @kbd{demo@key{RET}} 7 ok
3766: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3767: @end example
1.1 anton 3768:
1.29 crook 3769: The first new thing that we've introduced here is the pair of words
3770: @code{:} and @code{;}. These are used to start and terminate a new
3771: definition, respectively. The first word after the @code{:} is the name
3772: for the new definition.
1.1 anton 3773:
1.29 crook 3774: As you can see from the examples, a definition is built up of words that
3775: have already been defined; Forth makes no distinction between
3776: definitions that existed when you started the system up, and those that
3777: you define yourself.
1.1 anton 3778:
1.29 crook 3779: The examples also introduce the words @code{.} (dot), @code{."}
3780: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3781: the stack and displays it. It's like @code{.s} except that it only
3782: displays the top item of the stack and it is destructive; after it has
3783: executed, the number is no longer on the stack. There is always one
3784: space printed after the number, and no spaces before it. Dot-quote
3785: defines a string (a sequence of characters) that will be printed when
3786: the word is executed. The string can contain any printable characters
3787: except @code{"}. A @code{"} has a special function; it is not a Forth
3788: word but it acts as a delimiter (the way that delimiters work is
3789: described in the next section). Finally, @code{dup} duplicates the value
3790: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3791:
1.29 crook 3792: We already know that the text interpreter searches through the
3793: dictionary to locate names. If you've followed the examples earlier, you
3794: will already have a definition called @code{add-two}. Lets try modifying
3795: it by typing in a new definition:
1.1 anton 3796:
1.29 crook 3797: @example
1.30 anton 3798: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3799: @end example
1.5 anton 3800:
1.29 crook 3801: Forth recognised that we were defining a word that already exists, and
3802: printed a message to warn us of that fact. Let's try out the new
3803: definition:
1.5 anton 3804:
1.29 crook 3805: @example
1.30 anton 3806: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3807: @end example
1.1 anton 3808:
1.29 crook 3809: @noindent
3810: All that we've actually done here, though, is to create a new
3811: definition, with a particular name. The fact that there was already a
3812: definition with the same name did not make any difference to the way
3813: that the new definition was created (except that Forth printed a warning
3814: message). The old definition of add-two still exists (try @code{demo}
3815: again to see that this is true). Any new definition will use the new
3816: definition of @code{add-two}, but old definitions continue to use the
3817: version that already existed at the time that they were @code{compiled}.
1.1 anton 3818:
1.29 crook 3819: Before you go on to the next section, try defining and redefining some
3820: words of your own.
1.1 anton 3821:
1.29 crook 3822: @comment ----------------------------------------------
3823: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3824: @section How does that work?
3825: @cindex parsing words
1.1 anton 3826:
1.30 anton 3827: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3828:
3829: @c Is it a good idea to talk about the interpretation semantics of a
3830: @c number? We don't have an xt to go along with it. - anton
3831:
3832: @c Now that I have eliminated execution semantics, I wonder if it would not
3833: @c be better to keep them (or add run-time semantics), to make it easier to
3834: @c explain what compilation semantics usually does. - anton
3835:
1.44 crook 3836: @c nac-> I removed the term ``default compilation sematics'' from the
3837: @c introductory chapter. Removing ``execution semantics'' was making
3838: @c everything simpler to explain, then I think the use of this term made
3839: @c everything more complex again. I replaced it with ``default
3840: @c semantics'' (which is used elsewhere in the manual) by which I mean
3841: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3842: @c flag set''.
3843:
3844: @c anton: I have eliminated default semantics (except in one place where it
3845: @c means "default interpretation and compilation semantics"), because it
3846: @c makes no sense in the presence of combined words. I reverted to
3847: @c "execution semantics" where necessary.
3848:
3849: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3850: @c section (and, unusually for me, I think I even made it shorter!). See
3851: @c what you think -- I know I have not addressed your primary concern
3852: @c that it is too heavy-going for an introduction. From what I understood
3853: @c of your course notes it looks as though they might be a good framework.
3854: @c Things that I've tried to capture here are some things that came as a
3855: @c great revelation here when I first understood them. Also, I like the
3856: @c fact that a very simple code example shows up almost all of the issues
3857: @c that you need to understand to see how Forth works. That's unique and
3858: @c worthwhile to emphasise.
3859:
1.83 anton 3860: @c anton: I think it's a good idea to present the details, especially those
3861: @c that you found to be a revelation, and probably the tutorial tries to be
3862: @c too superficial and does not get some of the things across that make
3863: @c Forth special. I do believe that most of the time these things should
3864: @c be discussed at the end of a section or in separate sections instead of
3865: @c in the middle of a section (e.g., the stuff you added in "User-defined
3866: @c defining words" leads in a completely different direction from the rest
3867: @c of the section).
3868:
1.29 crook 3869: Now we're going to take another look at the definition of @code{add-two}
3870: from the previous section. From our knowledge of the way that the text
3871: interpreter works, we would have expected this result when we tried to
3872: define @code{add-two}:
1.21 crook 3873:
1.29 crook 3874: @example
1.44 crook 3875: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3876: *the terminal*:4: Undefined word
3877: : >>>add-two<<< 2 + . ;
1.29 crook 3878: @end example
1.28 crook 3879:
1.29 crook 3880: The reason that this didn't happen is bound up in the way that @code{:}
3881: works. The word @code{:} does two special things. The first special
3882: thing that it does prevents the text interpreter from ever seeing the
3883: characters @code{add-two}. The text interpreter uses a variable called
3884: @cindex modifying >IN
1.44 crook 3885: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3886: input line. When it encounters the word @code{:} it behaves in exactly
3887: the same way as it does for any other word; it looks it up in the name
3888: dictionary, finds its xt and executes it. When @code{:} executes, it
3889: looks at the input buffer, finds the word @code{add-two} and advances the
3890: value of @code{>IN} to point past it. It then does some other stuff
3891: associated with creating the new definition (including creating an entry
3892: for @code{add-two} in the name dictionary). When the execution of @code{:}
3893: completes, control returns to the text interpreter, which is oblivious
3894: to the fact that it has been tricked into ignoring part of the input
3895: line.
1.21 crook 3896:
1.29 crook 3897: @cindex parsing words
3898: Words like @code{:} -- words that advance the value of @code{>IN} and so
3899: prevent the text interpreter from acting on the whole of the input line
3900: -- are called @dfn{parsing words}.
1.21 crook 3901:
1.29 crook 3902: @cindex @code{state} - effect on the text interpreter
3903: @cindex text interpreter - effect of state
3904: The second special thing that @code{:} does is change the value of a
3905: variable called @code{state}, which affects the way that the text
3906: interpreter behaves. When Gforth starts up, @code{state} has the value
3907: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3908: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3909: the text interpreter is said to be @dfn{compiling}.
3910:
3911: In this example, the text interpreter is compiling when it processes the
3912: string ``@code{2 + . ;}''. It still breaks the string down into
3913: character sequences in the same way. However, instead of pushing the
3914: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3915: into the definition of @code{add-two} that will make the number @code{2} get
3916: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3917: the behaviours of @code{+} and @code{.} are also compiled into the
3918: definition.
3919:
3920: One category of words don't get compiled. These so-called @dfn{immediate
3921: words} get executed (performed @i{now}) regardless of whether the text
3922: interpreter is interpreting or compiling. The word @code{;} is an
3923: immediate word. Rather than being compiled into the definition, it
3924: executes. Its effect is to terminate the current definition, which
3925: includes changing the value of @code{state} back to 0.
3926:
3927: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3928: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3929: definition.
1.28 crook 3930:
1.30 anton 3931: In Forth, every word or number can be described in terms of two
1.29 crook 3932: properties:
1.28 crook 3933:
3934: @itemize @bullet
3935: @item
1.29 crook 3936: @cindex interpretation semantics
1.44 crook 3937: Its @dfn{interpretation semantics} describe how it will behave when the
3938: text interpreter encounters it in @dfn{interpret} state. The
3939: interpretation semantics of a word are represented by an @dfn{execution
3940: token}.
1.28 crook 3941: @item
1.29 crook 3942: @cindex compilation semantics
1.44 crook 3943: Its @dfn{compilation semantics} describe how it will behave when the
3944: text interpreter encounters it in @dfn{compile} state. The compilation
3945: semantics of a word are represented in an implementation-dependent way;
3946: Gforth uses a @dfn{compilation token}.
1.29 crook 3947: @end itemize
3948:
3949: @noindent
3950: Numbers are always treated in a fixed way:
3951:
3952: @itemize @bullet
1.28 crook 3953: @item
1.44 crook 3954: When the number is @dfn{interpreted}, its behaviour is to push the
3955: number onto the stack.
1.28 crook 3956: @item
1.30 anton 3957: When the number is @dfn{compiled}, a piece of code is appended to the
3958: current definition that pushes the number when it runs. (In other words,
3959: the compilation semantics of a number are to postpone its interpretation
3960: semantics until the run-time of the definition that it is being compiled
3961: into.)
1.29 crook 3962: @end itemize
3963:
1.44 crook 3964: Words don't behave in such a regular way, but most have @i{default
3965: semantics} which means that they behave like this:
1.29 crook 3966:
3967: @itemize @bullet
1.28 crook 3968: @item
1.30 anton 3969: The @dfn{interpretation semantics} of the word are to do something useful.
3970: @item
1.29 crook 3971: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3972: @dfn{interpretation semantics} to the current definition (so that its
3973: run-time behaviour is to do something useful).
1.28 crook 3974: @end itemize
3975:
1.30 anton 3976: @cindex immediate words
1.44 crook 3977: The actual behaviour of any particular word can be controlled by using
3978: the words @code{immediate} and @code{compile-only} when the word is
3979: defined. These words set flags in the name dictionary entry of the most
3980: recently defined word, and these flags are retrieved by the text
3981: interpreter when it finds the word in the name dictionary.
3982:
3983: A word that is marked as @dfn{immediate} has compilation semantics that
3984: are identical to its interpretation semantics. In other words, it
3985: behaves like this:
1.29 crook 3986:
3987: @itemize @bullet
3988: @item
1.30 anton 3989: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3990: @item
1.30 anton 3991: The @dfn{compilation semantics} of the word are to do something useful
3992: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3993: @end itemize
1.28 crook 3994:
1.44 crook 3995: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3996: performing the interpretation semantics of the word directly; an attempt
3997: to do so will generate an error. It is never necessary to use
3998: @code{compile-only} (and it is not even part of ANS Forth, though it is
3999: provided by many implementations) but it is good etiquette to apply it
4000: to a word that will not behave correctly (and might have unexpected
4001: side-effects) in interpret state. For example, it is only legal to use
4002: the conditional word @code{IF} within a definition. If you forget this
4003: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4004: @code{compile-only} allows the text interpreter to generate a helpful
4005: error message rather than subjecting you to the consequences of your
4006: folly.
4007:
1.29 crook 4008: This example shows the difference between an immediate and a
4009: non-immediate word:
1.28 crook 4010:
1.29 crook 4011: @example
4012: : show-state state @@ . ;
4013: : show-state-now show-state ; immediate
4014: : word1 show-state ;
4015: : word2 show-state-now ;
1.28 crook 4016: @end example
1.23 crook 4017:
1.29 crook 4018: The word @code{immediate} after the definition of @code{show-state-now}
4019: makes that word an immediate word. These definitions introduce a new
4020: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4021: variable, and leaves it on the stack. Therefore, the behaviour of
4022: @code{show-state} is to print a number that represents the current value
4023: of @code{state}.
1.28 crook 4024:
1.29 crook 4025: When you execute @code{word1}, it prints the number 0, indicating that
4026: the system is interpreting. When the text interpreter compiled the
4027: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4028: compilation semantics are to append its interpretation semantics to the
1.29 crook 4029: current definition. When you execute @code{word1}, it performs the
1.30 anton 4030: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4031: (and therefore @code{show-state}) are executed, the system is
4032: interpreting.
1.28 crook 4033:
1.30 anton 4034: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4035: you should have seen the number -1 printed, followed by ``@code{
4036: ok}''. When the text interpreter compiled the definition of
4037: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4038: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4039: semantics. It is executed straight away (even before the text
4040: interpreter has moved on to process another group of characters; the
4041: @code{;} in this example). The effect of executing it are to display the
4042: value of @code{state} @i{at the time that the definition of}
4043: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4044: system is compiling at this time. If you execute @code{word2} it does
4045: nothing at all.
1.28 crook 4046:
1.29 crook 4047: @cindex @code{."}, how it works
4048: Before leaving the subject of immediate words, consider the behaviour of
4049: @code{."} in the definition of @code{greet}, in the previous
4050: section. This word is both a parsing word and an immediate word. Notice
4051: that there is a space between @code{."} and the start of the text
4052: @code{Hello and welcome}, but that there is no space between the last
4053: letter of @code{welcome} and the @code{"} character. The reason for this
4054: is that @code{."} is a Forth word; it must have a space after it so that
4055: the text interpreter can identify it. The @code{"} is not a Forth word;
4056: it is a @dfn{delimiter}. The examples earlier show that, when the string
4057: is displayed, there is neither a space before the @code{H} nor after the
4058: @code{e}. Since @code{."} is an immediate word, it executes at the time
4059: that @code{greet} is defined. When it executes, its behaviour is to
4060: search forward in the input line looking for the delimiter. When it
4061: finds the delimiter, it updates @code{>IN} to point past the
4062: delimiter. It also compiles some magic code into the definition of
4063: @code{greet}; the xt of a run-time routine that prints a text string. It
4064: compiles the string @code{Hello and welcome} into memory so that it is
4065: available to be printed later. When the text interpreter gains control,
4066: the next word it finds in the input stream is @code{;} and so it
4067: terminates the definition of @code{greet}.
1.28 crook 4068:
4069:
4070: @comment ----------------------------------------------
1.29 crook 4071: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4072: @section Forth is written in Forth
4073: @cindex structure of Forth programs
4074:
4075: When you start up a Forth compiler, a large number of definitions
4076: already exist. In Forth, you develop a new application using bottom-up
4077: programming techniques to create new definitions that are defined in
4078: terms of existing definitions. As you create each definition you can
4079: test and debug it interactively.
4080:
4081: If you have tried out the examples in this section, you will probably
4082: have typed them in by hand; when you leave Gforth, your definitions will
4083: be lost. You can avoid this by using a text editor to enter Forth source
4084: code into a file, and then loading code from the file using
1.49 anton 4085: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4086: processed by the text interpreter, just as though you had typed it in by
4087: hand@footnote{Actually, there are some subtle differences -- see
4088: @ref{The Text Interpreter}.}.
4089:
4090: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4091: files for program entry (@pxref{Blocks}).
1.28 crook 4092:
1.29 crook 4093: In common with many, if not most, Forth compilers, most of Gforth is
4094: actually written in Forth. All of the @file{.fs} files in the
4095: installation directory@footnote{For example,
1.30 anton 4096: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4097: study to see examples of Forth programming.
1.28 crook 4098:
1.29 crook 4099: Gforth maintains a history file that records every line that you type to
4100: the text interpreter. This file is preserved between sessions, and is
4101: used to provide a command-line recall facility. If you enter long
4102: definitions by hand, you can use a text editor to paste them out of the
4103: history file into a Forth source file for reuse at a later time
1.49 anton 4104: (for more information @pxref{Command-line editing}).
1.28 crook 4105:
4106:
4107: @comment ----------------------------------------------
1.29 crook 4108: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4109: @section Review - elements of a Forth system
4110: @cindex elements of a Forth system
1.28 crook 4111:
1.29 crook 4112: To summarise this chapter:
1.28 crook 4113:
4114: @itemize @bullet
4115: @item
1.29 crook 4116: Forth programs use @dfn{factoring} to break a problem down into small
4117: fragments called @dfn{words} or @dfn{definitions}.
4118: @item
4119: Forth program development is an interactive process.
4120: @item
4121: The main command loop that accepts input, and controls both
4122: interpretation and compilation, is called the @dfn{text interpreter}
4123: (also known as the @dfn{outer interpreter}).
4124: @item
4125: Forth has a very simple syntax, consisting of words and numbers
4126: separated by spaces or carriage-return characters. Any additional syntax
4127: is imposed by @dfn{parsing words}.
4128: @item
4129: Forth uses a stack to pass parameters between words. As a result, it
4130: uses postfix notation.
4131: @item
4132: To use a word that has previously been defined, the text interpreter
4133: searches for the word in the @dfn{name dictionary}.
4134: @item
1.30 anton 4135: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4136: @item
1.29 crook 4137: The text interpreter uses the value of @code{state} to select between
4138: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4139: semantics} of a word that it encounters.
1.28 crook 4140: @item
1.30 anton 4141: The relationship between the @dfn{interpretation semantics} and
4142: @dfn{compilation semantics} for a word
1.29 crook 4143: depend upon the way in which the word was defined (for example, whether
4144: it is an @dfn{immediate} word).
1.28 crook 4145: @item
1.29 crook 4146: Forth definitions can be implemented in Forth (called @dfn{high-level
4147: definitions}) or in some other way (usually a lower-level language and
4148: as a result often called @dfn{low-level definitions}, @dfn{code
4149: definitions} or @dfn{primitives}).
1.28 crook 4150: @item
1.29 crook 4151: Many Forth systems are implemented mainly in Forth.
1.28 crook 4152: @end itemize
4153:
4154:
1.29 crook 4155: @comment ----------------------------------------------
1.48 anton 4156: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4157: @section Where To Go Next
4158: @cindex where to go next
1.28 crook 4159:
1.29 crook 4160: Amazing as it may seem, if you have read (and understood) this far, you
4161: know almost all the fundamentals about the inner workings of a Forth
4162: system. You certainly know enough to be able to read and understand the
4163: rest of this manual and the ANS Forth document, to learn more about the
4164: facilities that Forth in general and Gforth in particular provide. Even
4165: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4166: However, that's not a good idea just yet... better to try writing some
1.29 crook 4167: programs in Gforth.
1.28 crook 4168:
1.29 crook 4169: Forth has such a rich vocabulary that it can be hard to know where to
4170: start in learning it. This section suggests a few sets of words that are
4171: enough to write small but useful programs. Use the word index in this
4172: document to learn more about each word, then try it out and try to write
4173: small definitions using it. Start by experimenting with these words:
1.28 crook 4174:
4175: @itemize @bullet
4176: @item
1.29 crook 4177: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4178: @item
4179: Comparison: @code{MIN MAX =}
4180: @item
4181: Logic: @code{AND OR XOR NOT}
4182: @item
4183: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4184: @item
1.29 crook 4185: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4186: @item
1.29 crook 4187: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4188: @item
1.29 crook 4189: Defining words: @code{: ; CREATE}
1.28 crook 4190: @item
1.29 crook 4191: Memory allocation words: @code{ALLOT ,}
1.28 crook 4192: @item
1.29 crook 4193: Tools: @code{SEE WORDS .S MARKER}
4194: @end itemize
4195:
4196: When you have mastered those, go on to:
4197:
4198: @itemize @bullet
1.28 crook 4199: @item
1.29 crook 4200: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4201: @item
1.29 crook 4202: Memory access: @code{@@ !}
1.28 crook 4203: @end itemize
1.23 crook 4204:
1.29 crook 4205: When you have mastered these, there's nothing for it but to read through
4206: the whole of this manual and find out what you've missed.
4207:
4208: @comment ----------------------------------------------
1.48 anton 4209: @node Exercises, , Where to go next, Introduction
1.29 crook 4210: @section Exercises
4211: @cindex exercises
4212:
4213: TODO: provide a set of programming excercises linked into the stuff done
4214: already and into other sections of the manual. Provide solutions to all
4215: the exercises in a .fs file in the distribution.
4216:
4217: @c Get some inspiration from Starting Forth and Kelly&Spies.
4218:
4219: @c excercises:
4220: @c 1. take inches and convert to feet and inches.
4221: @c 2. take temperature and convert from fahrenheight to celcius;
4222: @c may need to care about symmetric vs floored??
4223: @c 3. take input line and do character substitution
4224: @c to encipher or decipher
4225: @c 4. as above but work on a file for in and out
4226: @c 5. take input line and convert to pig-latin
4227: @c
4228: @c thing of sets of things to exercise then come up with
4229: @c problems that need those things.
4230:
4231:
1.26 crook 4232: @c ******************************************************************
1.29 crook 4233: @node Words, Error messages, Introduction, Top
1.1 anton 4234: @chapter Forth Words
1.26 crook 4235: @cindex words
1.1 anton 4236:
4237: @menu
4238: * Notation::
1.65 anton 4239: * Case insensitivity::
4240: * Comments::
4241: * Boolean Flags::
1.1 anton 4242: * Arithmetic::
4243: * Stack Manipulation::
1.5 anton 4244: * Memory::
1.1 anton 4245: * Control Structures::
4246: * Defining Words::
1.65 anton 4247: * Interpretation and Compilation Semantics::
1.47 crook 4248: * Tokens for Words::
1.81 anton 4249: * Compiling words::
1.65 anton 4250: * The Text Interpreter::
1.111 anton 4251: * The Input Stream::
1.65 anton 4252: * Word Lists::
4253: * Environmental Queries::
1.12 anton 4254: * Files::
4255: * Blocks::
4256: * Other I/O::
1.121 anton 4257: * OS command line arguments::
1.78 anton 4258: * Locals::
4259: * Structures::
4260: * Object-oriented Forth::
1.12 anton 4261: * Programming Tools::
1.150 anton 4262: * C Interface::
1.12 anton 4263: * Assembler and Code Words::
4264: * Threading Words::
1.65 anton 4265: * Passing Commands to the OS::
4266: * Keeping track of Time::
4267: * Miscellaneous Words::
1.1 anton 4268: @end menu
4269:
1.65 anton 4270: @node Notation, Case insensitivity, Words, Words
1.1 anton 4271: @section Notation
4272: @cindex notation of glossary entries
4273: @cindex format of glossary entries
4274: @cindex glossary notation format
4275: @cindex word glossary entry format
4276:
4277: The Forth words are described in this section in the glossary notation
1.67 anton 4278: that has become a de-facto standard for Forth texts:
1.1 anton 4279:
4280: @format
1.29 crook 4281: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4282: @end format
1.29 crook 4283: @i{Description}
1.1 anton 4284:
4285: @table @var
4286: @item word
1.28 crook 4287: The name of the word.
1.1 anton 4288:
4289: @item Stack effect
4290: @cindex stack effect
1.29 crook 4291: The stack effect is written in the notation @code{@i{before} --
4292: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4293: stack entries before and after the execution of the word. The rest of
4294: the stack is not touched by the word. The top of stack is rightmost,
4295: i.e., a stack sequence is written as it is typed in. Note that Gforth
4296: uses a separate floating point stack, but a unified stack
1.29 crook 4297: notation. Also, return stack effects are not shown in @i{stack
4298: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4299: the type and/or the function of the item. See below for a discussion of
4300: the types.
4301:
4302: All words have two stack effects: A compile-time stack effect and a
4303: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4304: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4305: this standard behaviour, or the word does other unusual things at
4306: compile time, both stack effects are shown; otherwise only the run-time
4307: stack effect is shown.
4308:
4309: @cindex pronounciation of words
4310: @item pronunciation
4311: How the word is pronounced.
4312:
4313: @cindex wordset
1.67 anton 4314: @cindex environment wordset
1.1 anton 4315: @item wordset
1.21 crook 4316: The ANS Forth standard is divided into several word sets. A standard
4317: system need not support all of them. Therefore, in theory, the fewer
4318: word sets your program uses the more portable it will be. However, we
4319: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4320: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4321: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4322: describes words that will work in future releases of Gforth;
4323: @code{gforth-internal} words are more volatile. Environmental query
4324: strings are also displayed like words; you can recognize them by the
1.21 crook 4325: @code{environment} in the word set field.
1.1 anton 4326:
4327: @item Description
4328: A description of the behaviour of the word.
4329: @end table
4330:
4331: @cindex types of stack items
4332: @cindex stack item types
4333: The type of a stack item is specified by the character(s) the name
4334: starts with:
4335:
4336: @table @code
4337: @item f
4338: @cindex @code{f}, stack item type
4339: Boolean flags, i.e. @code{false} or @code{true}.
4340: @item c
4341: @cindex @code{c}, stack item type
4342: Char
4343: @item w
4344: @cindex @code{w}, stack item type
4345: Cell, can contain an integer or an address
4346: @item n
4347: @cindex @code{n}, stack item type
4348: signed integer
4349: @item u
4350: @cindex @code{u}, stack item type
4351: unsigned integer
4352: @item d
4353: @cindex @code{d}, stack item type
4354: double sized signed integer
4355: @item ud
4356: @cindex @code{ud}, stack item type
4357: double sized unsigned integer
4358: @item r
4359: @cindex @code{r}, stack item type
4360: Float (on the FP stack)
1.21 crook 4361: @item a-
1.1 anton 4362: @cindex @code{a_}, stack item type
4363: Cell-aligned address
1.21 crook 4364: @item c-
1.1 anton 4365: @cindex @code{c_}, stack item type
4366: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4367: @item f-
1.1 anton 4368: @cindex @code{f_}, stack item type
4369: Float-aligned address
1.21 crook 4370: @item df-
1.1 anton 4371: @cindex @code{df_}, stack item type
4372: Address aligned for IEEE double precision float
1.21 crook 4373: @item sf-
1.1 anton 4374: @cindex @code{sf_}, stack item type
4375: Address aligned for IEEE single precision float
4376: @item xt
4377: @cindex @code{xt}, stack item type
4378: Execution token, same size as Cell
4379: @item wid
4380: @cindex @code{wid}, stack item type
1.21 crook 4381: Word list ID, same size as Cell
1.68 anton 4382: @item ior, wior
4383: @cindex ior type description
4384: @cindex wior type description
4385: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4386: @item f83name
4387: @cindex @code{f83name}, stack item type
4388: Pointer to a name structure
4389: @item "
4390: @cindex @code{"}, stack item type
1.12 anton 4391: string in the input stream (not on the stack). The terminating character
4392: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4393: quotes.
4394: @end table
4395:
1.65 anton 4396: @comment ----------------------------------------------
4397: @node Case insensitivity, Comments, Notation, Words
4398: @section Case insensitivity
4399: @cindex case sensitivity
4400: @cindex upper and lower case
4401:
4402: Gforth is case-insensitive; you can enter definitions and invoke
4403: Standard words using upper, lower or mixed case (however,
4404: @pxref{core-idef, Implementation-defined options, Implementation-defined
4405: options}).
4406:
4407: ANS Forth only @i{requires} implementations to recognise Standard words
4408: when they are typed entirely in upper case. Therefore, a Standard
4409: program must use upper case for all Standard words. You can use whatever
4410: case you like for words that you define, but in a Standard program you
4411: have to use the words in the same case that you defined them.
4412:
4413: Gforth supports case sensitivity through @code{table}s (case-sensitive
4414: wordlists, @pxref{Word Lists}).
4415:
4416: Two people have asked how to convert Gforth to be case-sensitive; while
4417: we think this is a bad idea, you can change all wordlists into tables
4418: like this:
4419:
4420: @example
4421: ' table-find forth-wordlist wordlist-map @ !
4422: @end example
4423:
4424: Note that you now have to type the predefined words in the same case
4425: that we defined them, which are varying. You may want to convert them
4426: to your favourite case before doing this operation (I won't explain how,
4427: because if you are even contemplating doing this, you'd better have
4428: enough knowledge of Forth systems to know this already).
4429:
4430: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4431: @section Comments
1.26 crook 4432: @cindex comments
1.21 crook 4433:
1.29 crook 4434: Forth supports two styles of comment; the traditional @i{in-line} comment,
4435: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4436:
1.44 crook 4437:
1.23 crook 4438: doc-(
1.21 crook 4439: doc-\
1.23 crook 4440: doc-\G
1.21 crook 4441:
1.44 crook 4442:
1.21 crook 4443: @node Boolean Flags, Arithmetic, Comments, Words
4444: @section Boolean Flags
1.26 crook 4445: @cindex Boolean flags
1.21 crook 4446:
4447: A Boolean flag is cell-sized. A cell with all bits clear represents the
4448: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4449: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4450: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4451: @c on and off to Memory?
4452: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4453:
1.21 crook 4454: doc-true
4455: doc-false
1.29 crook 4456: doc-on
4457: doc-off
1.21 crook 4458:
1.44 crook 4459:
1.21 crook 4460: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4461: @section Arithmetic
4462: @cindex arithmetic words
4463:
4464: @cindex division with potentially negative operands
4465: Forth arithmetic is not checked, i.e., you will not hear about integer
4466: overflow on addition or multiplication, you may hear about division by
4467: zero if you are lucky. The operator is written after the operands, but
4468: the operands are still in the original order. I.e., the infix @code{2-1}
4469: corresponds to @code{2 1 -}. Forth offers a variety of division
4470: operators. If you perform division with potentially negative operands,
4471: you do not want to use @code{/} or @code{/mod} with its undefined
4472: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4473: former, @pxref{Mixed precision}).
1.26 crook 4474: @comment TODO discuss the different division forms and the std approach
1.1 anton 4475:
4476: @menu
4477: * Single precision::
1.67 anton 4478: * Double precision:: Double-cell integer arithmetic
1.1 anton 4479: * Bitwise operations::
1.67 anton 4480: * Numeric comparison::
1.29 crook 4481: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4482: * Floating Point::
4483: @end menu
4484:
1.67 anton 4485: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4486: @subsection Single precision
4487: @cindex single precision arithmetic words
4488:
1.67 anton 4489: @c !! cell undefined
4490:
4491: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4492: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4493: treat them. For the rules used by the text interpreter for recognising
4494: single-precision integers see @ref{Number Conversion}.
1.21 crook 4495:
1.67 anton 4496: These words are all defined for signed operands, but some of them also
4497: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4498: @code{*}.
1.44 crook 4499:
1.1 anton 4500: doc-+
1.21 crook 4501: doc-1+
1.128 anton 4502: doc-under+
1.1 anton 4503: doc--
1.21 crook 4504: doc-1-
1.1 anton 4505: doc-*
4506: doc-/
4507: doc-mod
4508: doc-/mod
4509: doc-negate
4510: doc-abs
4511: doc-min
4512: doc-max
1.27 crook 4513: doc-floored
1.1 anton 4514:
1.44 crook 4515:
1.67 anton 4516: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4517: @subsection Double precision
4518: @cindex double precision arithmetic words
4519:
1.49 anton 4520: For the rules used by the text interpreter for
4521: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4522:
4523: A double precision number is represented by a cell pair, with the most
1.67 anton 4524: significant cell at the TOS. It is trivial to convert an unsigned single
4525: to a double: simply push a @code{0} onto the TOS. Since numbers are
4526: represented by Gforth using 2's complement arithmetic, converting a
4527: signed single to a (signed) double requires sign-extension across the
4528: most significant cell. This can be achieved using @code{s>d}. The moral
4529: of the story is that you cannot convert a number without knowing whether
4530: it represents an unsigned or a signed number.
1.21 crook 4531:
1.67 anton 4532: These words are all defined for signed operands, but some of them also
4533: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4534:
1.21 crook 4535: doc-s>d
1.67 anton 4536: doc-d>s
1.21 crook 4537: doc-d+
4538: doc-d-
4539: doc-dnegate
4540: doc-dabs
4541: doc-dmin
4542: doc-dmax
4543:
1.44 crook 4544:
1.67 anton 4545: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4546: @subsection Bitwise operations
4547: @cindex bitwise operation words
4548:
4549:
4550: doc-and
4551: doc-or
4552: doc-xor
4553: doc-invert
4554: doc-lshift
4555: doc-rshift
4556: doc-2*
4557: doc-d2*
4558: doc-2/
4559: doc-d2/
4560:
4561:
4562: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4563: @subsection Numeric comparison
4564: @cindex numeric comparison words
4565:
1.67 anton 4566: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4567: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4568:
1.28 crook 4569: doc-<
4570: doc-<=
4571: doc-<>
4572: doc-=
4573: doc->
4574: doc->=
4575:
1.21 crook 4576: doc-0<
1.23 crook 4577: doc-0<=
1.21 crook 4578: doc-0<>
4579: doc-0=
1.23 crook 4580: doc-0>
4581: doc-0>=
1.28 crook 4582:
4583: doc-u<
4584: doc-u<=
1.44 crook 4585: @c u<> and u= exist but are the same as <> and =
1.31 anton 4586: @c doc-u<>
4587: @c doc-u=
1.28 crook 4588: doc-u>
4589: doc-u>=
4590:
4591: doc-within
4592:
4593: doc-d<
4594: doc-d<=
4595: doc-d<>
4596: doc-d=
4597: doc-d>
4598: doc-d>=
1.23 crook 4599:
1.21 crook 4600: doc-d0<
1.23 crook 4601: doc-d0<=
4602: doc-d0<>
1.21 crook 4603: doc-d0=
1.23 crook 4604: doc-d0>
4605: doc-d0>=
4606:
1.21 crook 4607: doc-du<
1.28 crook 4608: doc-du<=
1.44 crook 4609: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4610: @c doc-du<>
4611: @c doc-du=
1.28 crook 4612: doc-du>
4613: doc-du>=
1.1 anton 4614:
1.44 crook 4615:
1.21 crook 4616: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4617: @subsection Mixed precision
4618: @cindex mixed precision arithmetic words
4619:
1.44 crook 4620:
1.1 anton 4621: doc-m+
4622: doc-*/
4623: doc-*/mod
4624: doc-m*
4625: doc-um*
4626: doc-m*/
4627: doc-um/mod
4628: doc-fm/mod
4629: doc-sm/rem
4630:
1.44 crook 4631:
1.21 crook 4632: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4633: @subsection Floating Point
4634: @cindex floating point arithmetic words
4635:
1.49 anton 4636: For the rules used by the text interpreter for
4637: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4638:
1.67 anton 4639: Gforth has a separate floating point stack, but the documentation uses
4640: the unified notation.@footnote{It's easy to generate the separate
4641: notation from that by just separating the floating-point numbers out:
4642: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4643: r3 )}.}
1.1 anton 4644:
4645: @cindex floating-point arithmetic, pitfalls
4646: Floating point numbers have a number of unpleasant surprises for the
4647: unwary (e.g., floating point addition is not associative) and even a few
4648: for the wary. You should not use them unless you know what you are doing
4649: or you don't care that the results you get are totally bogus. If you
4650: want to learn about the problems of floating point numbers (and how to
1.66 anton 4651: avoid them), you might start with @cite{David Goldberg,
4652: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4653: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4654: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4655:
1.44 crook 4656:
1.21 crook 4657: doc-d>f
4658: doc-f>d
1.1 anton 4659: doc-f+
4660: doc-f-
4661: doc-f*
4662: doc-f/
4663: doc-fnegate
4664: doc-fabs
4665: doc-fmax
4666: doc-fmin
4667: doc-floor
4668: doc-fround
4669: doc-f**
4670: doc-fsqrt
4671: doc-fexp
4672: doc-fexpm1
4673: doc-fln
4674: doc-flnp1
4675: doc-flog
4676: doc-falog
1.32 anton 4677: doc-f2*
4678: doc-f2/
4679: doc-1/f
4680: doc-precision
4681: doc-set-precision
4682:
4683: @cindex angles in trigonometric operations
4684: @cindex trigonometric operations
4685: Angles in floating point operations are given in radians (a full circle
4686: has 2 pi radians).
4687:
1.1 anton 4688: doc-fsin
4689: doc-fcos
4690: doc-fsincos
4691: doc-ftan
4692: doc-fasin
4693: doc-facos
4694: doc-fatan
4695: doc-fatan2
4696: doc-fsinh
4697: doc-fcosh
4698: doc-ftanh
4699: doc-fasinh
4700: doc-facosh
4701: doc-fatanh
1.21 crook 4702: doc-pi
1.28 crook 4703:
1.32 anton 4704: @cindex equality of floats
4705: @cindex floating-point comparisons
1.31 anton 4706: One particular problem with floating-point arithmetic is that comparison
4707: for equality often fails when you would expect it to succeed. For this
4708: reason approximate equality is often preferred (but you still have to
1.67 anton 4709: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4710: differently from what you might expect. The comparison words are:
1.31 anton 4711:
4712: doc-f~rel
4713: doc-f~abs
1.68 anton 4714: doc-f~
1.31 anton 4715: doc-f=
4716: doc-f<>
4717:
4718: doc-f<
4719: doc-f<=
4720: doc-f>
4721: doc-f>=
4722:
1.21 crook 4723: doc-f0<
1.28 crook 4724: doc-f0<=
4725: doc-f0<>
1.21 crook 4726: doc-f0=
1.28 crook 4727: doc-f0>
4728: doc-f0>=
4729:
1.1 anton 4730:
4731: @node Stack Manipulation, Memory, Arithmetic, Words
4732: @section Stack Manipulation
4733: @cindex stack manipulation words
4734:
4735: @cindex floating-point stack in the standard
1.21 crook 4736: Gforth maintains a number of separate stacks:
4737:
1.29 crook 4738: @cindex data stack
4739: @cindex parameter stack
1.21 crook 4740: @itemize @bullet
4741: @item
1.29 crook 4742: A data stack (also known as the @dfn{parameter stack}) -- for
4743: characters, cells, addresses, and double cells.
1.21 crook 4744:
1.29 crook 4745: @cindex floating-point stack
1.21 crook 4746: @item
1.44 crook 4747: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4748:
1.29 crook 4749: @cindex return stack
1.21 crook 4750: @item
1.44 crook 4751: A return stack -- for holding the return addresses of colon
1.32 anton 4752: definitions and other (non-FP) data.
1.21 crook 4753:
1.29 crook 4754: @cindex locals stack
1.21 crook 4755: @item
1.44 crook 4756: A locals stack -- for holding local variables.
1.21 crook 4757: @end itemize
4758:
1.1 anton 4759: @menu
4760: * Data stack::
4761: * Floating point stack::
4762: * Return stack::
4763: * Locals stack::
4764: * Stack pointer manipulation::
4765: @end menu
4766:
4767: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4768: @subsection Data stack
4769: @cindex data stack manipulation words
4770: @cindex stack manipulations words, data stack
4771:
1.44 crook 4772:
1.1 anton 4773: doc-drop
4774: doc-nip
4775: doc-dup
4776: doc-over
4777: doc-tuck
4778: doc-swap
1.21 crook 4779: doc-pick
1.1 anton 4780: doc-rot
4781: doc--rot
4782: doc-?dup
4783: doc-roll
4784: doc-2drop
4785: doc-2nip
4786: doc-2dup
4787: doc-2over
4788: doc-2tuck
4789: doc-2swap
4790: doc-2rot
4791:
1.44 crook 4792:
1.1 anton 4793: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4794: @subsection Floating point stack
4795: @cindex floating-point stack manipulation words
4796: @cindex stack manipulation words, floating-point stack
4797:
1.32 anton 4798: Whilst every sane Forth has a separate floating-point stack, it is not
4799: strictly required; an ANS Forth system could theoretically keep
4800: floating-point numbers on the data stack. As an additional difficulty,
4801: you don't know how many cells a floating-point number takes. It is
4802: reportedly possible to write words in a way that they work also for a
4803: unified stack model, but we do not recommend trying it. Instead, just
4804: say that your program has an environmental dependency on a separate
4805: floating-point stack.
4806:
4807: doc-floating-stack
4808:
1.1 anton 4809: doc-fdrop
4810: doc-fnip
4811: doc-fdup
4812: doc-fover
4813: doc-ftuck
4814: doc-fswap
1.21 crook 4815: doc-fpick
1.1 anton 4816: doc-frot
4817:
1.44 crook 4818:
1.1 anton 4819: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4820: @subsection Return stack
4821: @cindex return stack manipulation words
4822: @cindex stack manipulation words, return stack
4823:
1.32 anton 4824: @cindex return stack and locals
4825: @cindex locals and return stack
4826: A Forth system is allowed to keep local variables on the
4827: return stack. This is reasonable, as local variables usually eliminate
4828: the need to use the return stack explicitly. So, if you want to produce
4829: a standard compliant program and you are using local variables in a
4830: word, forget about return stack manipulations in that word (refer to the
4831: standard document for the exact rules).
4832:
1.1 anton 4833: doc->r
4834: doc-r>
4835: doc-r@
4836: doc-rdrop
4837: doc-2>r
4838: doc-2r>
4839: doc-2r@
4840: doc-2rdrop
4841:
1.44 crook 4842:
1.1 anton 4843: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4844: @subsection Locals stack
4845:
1.78 anton 4846: Gforth uses an extra locals stack. It is described, along with the
4847: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4848:
1.1 anton 4849: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4850: @subsection Stack pointer manipulation
4851: @cindex stack pointer manipulation words
4852:
1.44 crook 4853: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4854: doc-sp0
1.1 anton 4855: doc-sp@
4856: doc-sp!
1.21 crook 4857: doc-fp0
1.1 anton 4858: doc-fp@
4859: doc-fp!
1.21 crook 4860: doc-rp0
1.1 anton 4861: doc-rp@
4862: doc-rp!
1.21 crook 4863: doc-lp0
1.1 anton 4864: doc-lp@
4865: doc-lp!
4866:
1.44 crook 4867:
1.1 anton 4868: @node Memory, Control Structures, Stack Manipulation, Words
4869: @section Memory
1.26 crook 4870: @cindex memory words
1.1 anton 4871:
1.32 anton 4872: @menu
4873: * Memory model::
4874: * Dictionary allocation::
4875: * Heap Allocation::
4876: * Memory Access::
4877: * Address arithmetic::
4878: * Memory Blocks::
4879: @end menu
4880:
1.67 anton 4881: In addition to the standard Forth memory allocation words, there is also
4882: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4883: garbage collector}.
4884:
1.32 anton 4885: @node Memory model, Dictionary allocation, Memory, Memory
4886: @subsection ANS Forth and Gforth memory models
4887:
4888: @c The ANS Forth description is a mess (e.g., is the heap part of
4889: @c the dictionary?), so let's not stick to closely with it.
4890:
1.67 anton 4891: ANS Forth considers a Forth system as consisting of several address
4892: spaces, of which only @dfn{data space} is managed and accessible with
4893: the memory words. Memory not necessarily in data space includes the
4894: stacks, the code (called code space) and the headers (called name
4895: space). In Gforth everything is in data space, but the code for the
4896: primitives is usually read-only.
1.32 anton 4897:
4898: Data space is divided into a number of areas: The (data space portion of
4899: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4900: refer to the search data structure embodied in word lists and headers,
4901: because it is used for looking up names, just as you would in a
4902: conventional dictionary.}, the heap, and a number of system-allocated
4903: buffers.
4904:
1.68 anton 4905: @cindex address arithmetic restrictions, ANS vs. Gforth
4906: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4907: In ANS Forth data space is also divided into contiguous regions. You
4908: can only use address arithmetic within a contiguous region, not between
4909: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4910: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4911: allocation}).
4912:
4913: Gforth provides one big address space, and address arithmetic can be
4914: performed between any addresses. However, in the dictionary headers or
4915: code are interleaved with data, so almost the only contiguous data space
4916: regions there are those described by ANS Forth as contiguous; but you
4917: can be sure that the dictionary is allocated towards increasing
4918: addresses even between contiguous regions. The memory order of
4919: allocations in the heap is platform-dependent (and possibly different
4920: from one run to the next).
4921:
1.27 crook 4922:
1.32 anton 4923: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4924: @subsection Dictionary allocation
1.27 crook 4925: @cindex reserving data space
4926: @cindex data space - reserving some
4927:
1.32 anton 4928: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4929: you want to deallocate X, you also deallocate everything
4930: allocated after X.
4931:
1.68 anton 4932: @cindex contiguous regions in dictionary allocation
1.32 anton 4933: The allocations using the words below are contiguous and grow the region
4934: towards increasing addresses. Other words that allocate dictionary
4935: memory of any kind (i.e., defining words including @code{:noname}) end
4936: the contiguous region and start a new one.
4937:
4938: In ANS Forth only @code{create}d words are guaranteed to produce an
4939: address that is the start of the following contiguous region. In
4940: particular, the cell allocated by @code{variable} is not guaranteed to
4941: be contiguous with following @code{allot}ed memory.
4942:
4943: You can deallocate memory by using @code{allot} with a negative argument
4944: (with some restrictions, see @code{allot}). For larger deallocations use
4945: @code{marker}.
1.27 crook 4946:
1.29 crook 4947:
1.27 crook 4948: doc-here
4949: doc-unused
4950: doc-allot
4951: doc-c,
1.29 crook 4952: doc-f,
1.27 crook 4953: doc-,
4954: doc-2,
4955:
1.32 anton 4956: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4957: course you should allocate memory in an aligned way, too. I.e., before
4958: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4959: The words below align @code{here} if it is not already. Basically it is
4960: only already aligned for a type, if the last allocation was a multiple
4961: of the size of this type and if @code{here} was aligned for this type
4962: before.
4963:
4964: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4965: ANS Forth (@code{maxalign}ed in Gforth).
4966:
4967: doc-align
4968: doc-falign
4969: doc-sfalign
4970: doc-dfalign
4971: doc-maxalign
4972: doc-cfalign
4973:
4974:
4975: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4976: @subsection Heap allocation
4977: @cindex heap allocation
4978: @cindex dynamic allocation of memory
4979: @cindex memory-allocation word set
4980:
1.68 anton 4981: @cindex contiguous regions and heap allocation
1.32 anton 4982: Heap allocation supports deallocation of allocated memory in any
4983: order. Dictionary allocation is not affected by it (i.e., it does not
4984: end a contiguous region). In Gforth, these words are implemented using
4985: the standard C library calls malloc(), free() and resize().
4986:
1.68 anton 4987: The memory region produced by one invocation of @code{allocate} or
4988: @code{resize} is internally contiguous. There is no contiguity between
4989: such a region and any other region (including others allocated from the
4990: heap).
4991:
1.32 anton 4992: doc-allocate
4993: doc-free
4994: doc-resize
4995:
1.27 crook 4996:
1.32 anton 4997: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4998: @subsection Memory Access
4999: @cindex memory access words
5000:
5001: doc-@
5002: doc-!
5003: doc-+!
5004: doc-c@
5005: doc-c!
5006: doc-2@
5007: doc-2!
5008: doc-f@
5009: doc-f!
5010: doc-sf@
5011: doc-sf!
5012: doc-df@
5013: doc-df!
1.144 anton 5014: doc-sw@
5015: doc-uw@
5016: doc-w!
5017: doc-sl@
5018: doc-ul@
5019: doc-l!
1.68 anton 5020:
1.32 anton 5021: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5022: @subsection Address arithmetic
1.1 anton 5023: @cindex address arithmetic words
5024:
1.67 anton 5025: Address arithmetic is the foundation on which you can build data
5026: structures like arrays, records (@pxref{Structures}) and objects
5027: (@pxref{Object-oriented Forth}).
1.32 anton 5028:
1.68 anton 5029: @cindex address unit
5030: @cindex au (address unit)
1.1 anton 5031: ANS Forth does not specify the sizes of the data types. Instead, it
5032: offers a number of words for computing sizes and doing address
1.29 crook 5033: arithmetic. Address arithmetic is performed in terms of address units
5034: (aus); on most systems the address unit is one byte. Note that a
5035: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5036: platforms where it is a noop, it compiles to nothing).
1.1 anton 5037:
1.67 anton 5038: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5039: you have the address of a cell, perform @code{1 cells +}, and you will
5040: have the address of the next cell.
5041:
1.68 anton 5042: @cindex contiguous regions and address arithmetic
1.67 anton 5043: In ANS Forth you can perform address arithmetic only within a contiguous
5044: region, i.e., if you have an address into one region, you can only add
5045: and subtract such that the result is still within the region; you can
5046: only subtract or compare addresses from within the same contiguous
5047: region. Reasons: several contiguous regions can be arranged in memory
5048: in any way; on segmented systems addresses may have unusual
5049: representations, such that address arithmetic only works within a
5050: region. Gforth provides a few more guarantees (linear address space,
5051: dictionary grows upwards), but in general I have found it easy to stay
5052: within contiguous regions (exception: computing and comparing to the
5053: address just beyond the end of an array).
5054:
1.1 anton 5055: @cindex alignment of addresses for types
5056: ANS Forth also defines words for aligning addresses for specific
5057: types. Many computers require that accesses to specific data types
5058: must only occur at specific addresses; e.g., that cells may only be
5059: accessed at addresses divisible by 4. Even if a machine allows unaligned
5060: accesses, it can usually perform aligned accesses faster.
5061:
5062: For the performance-conscious: alignment operations are usually only
5063: necessary during the definition of a data structure, not during the
5064: (more frequent) accesses to it.
5065:
5066: ANS Forth defines no words for character-aligning addresses. This is not
5067: an oversight, but reflects the fact that addresses that are not
5068: char-aligned have no use in the standard and therefore will not be
5069: created.
5070:
5071: @cindex @code{CREATE} and alignment
1.29 crook 5072: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5073: are cell-aligned; in addition, Gforth guarantees that these addresses
5074: are aligned for all purposes.
5075:
1.26 crook 5076: Note that the ANS Forth word @code{char} has nothing to do with address
5077: arithmetic.
1.1 anton 5078:
1.44 crook 5079:
1.1 anton 5080: doc-chars
5081: doc-char+
5082: doc-cells
5083: doc-cell+
5084: doc-cell
5085: doc-aligned
5086: doc-floats
5087: doc-float+
5088: doc-float
5089: doc-faligned
5090: doc-sfloats
5091: doc-sfloat+
5092: doc-sfaligned
5093: doc-dfloats
5094: doc-dfloat+
5095: doc-dfaligned
5096: doc-maxaligned
5097: doc-cfaligned
5098: doc-address-unit-bits
1.145 anton 5099: doc-/w
5100: doc-/l
1.44 crook 5101:
1.32 anton 5102: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5103: @subsection Memory Blocks
5104: @cindex memory block words
1.27 crook 5105: @cindex character strings - moving and copying
5106:
1.49 anton 5107: Memory blocks often represent character strings; For ways of storing
5108: character strings in memory see @ref{String Formats}. For other
5109: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5110:
1.67 anton 5111: A few of these words work on address unit blocks. In that case, you
5112: usually have to insert @code{CHARS} before the word when working on
5113: character strings. Most words work on character blocks, and expect a
5114: char-aligned address.
5115:
5116: When copying characters between overlapping memory regions, use
5117: @code{chars move} or choose carefully between @code{cmove} and
5118: @code{cmove>}.
1.44 crook 5119:
1.1 anton 5120: doc-move
5121: doc-erase
5122: doc-cmove
5123: doc-cmove>
5124: doc-fill
5125: doc-blank
1.21 crook 5126: doc-compare
1.111 anton 5127: doc-str=
5128: doc-str<
5129: doc-string-prefix?
1.21 crook 5130: doc-search
1.27 crook 5131: doc--trailing
5132: doc-/string
1.82 anton 5133: doc-bounds
1.141 anton 5134: doc-pad
1.111 anton 5135:
1.27 crook 5136: @comment TODO examples
5137:
1.1 anton 5138:
1.26 crook 5139: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5140: @section Control Structures
5141: @cindex control structures
5142:
1.33 anton 5143: Control structures in Forth cannot be used interpretively, only in a
5144: colon definition@footnote{To be precise, they have no interpretation
5145: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5146: not like this limitation, but have not seen a satisfying way around it
5147: yet, although many schemes have been proposed.
1.1 anton 5148:
5149: @menu
1.33 anton 5150: * Selection:: IF ... ELSE ... ENDIF
5151: * Simple Loops:: BEGIN ...
1.29 crook 5152: * Counted Loops:: DO
1.67 anton 5153: * Arbitrary control structures::
5154: * Calls and returns::
1.1 anton 5155: * Exception Handling::
5156: @end menu
5157:
5158: @node Selection, Simple Loops, Control Structures, Control Structures
5159: @subsection Selection
5160: @cindex selection control structures
5161: @cindex control structures for selection
5162:
5163: @cindex @code{IF} control structure
5164: @example
1.29 crook 5165: @i{flag}
1.1 anton 5166: IF
1.29 crook 5167: @i{code}
1.1 anton 5168: ENDIF
5169: @end example
1.21 crook 5170: @noindent
1.33 anton 5171:
1.44 crook 5172: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5173: with any bit set represents truth) @i{code} is executed.
1.33 anton 5174:
1.1 anton 5175: @example
1.29 crook 5176: @i{flag}
1.1 anton 5177: IF
1.29 crook 5178: @i{code1}
1.1 anton 5179: ELSE
1.29 crook 5180: @i{code2}
1.1 anton 5181: ENDIF
5182: @end example
5183:
1.44 crook 5184: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5185: executed.
1.33 anton 5186:
1.1 anton 5187: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5188: standard, and @code{ENDIF} is not, although it is quite popular. We
5189: recommend using @code{ENDIF}, because it is less confusing for people
5190: who also know other languages (and is not prone to reinforcing negative
5191: prejudices against Forth in these people). Adding @code{ENDIF} to a
5192: system that only supplies @code{THEN} is simple:
5193: @example
1.82 anton 5194: : ENDIF POSTPONE then ; immediate
1.1 anton 5195: @end example
5196:
5197: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5198: (adv.)} has the following meanings:
5199: @quotation
5200: ... 2b: following next after in order ... 3d: as a necessary consequence
5201: (if you were there, then you saw them).
5202: @end quotation
5203: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5204: and many other programming languages has the meaning 3d.]
5205:
1.21 crook 5206: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5207: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5208: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5209: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5210: @file{compat/control.fs}.
5211:
5212: @cindex @code{CASE} control structure
5213: @example
1.29 crook 5214: @i{n}
1.1 anton 5215: CASE
1.29 crook 5216: @i{n1} OF @i{code1} ENDOF
5217: @i{n2} OF @i{code2} ENDOF
1.1 anton 5218: @dots{}
1.68 anton 5219: ( n ) @i{default-code} ( n )
1.131 anton 5220: ENDCASE ( )
1.1 anton 5221: @end example
5222:
1.131 anton 5223: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5224: no @i{ni} matches, the optional @i{default-code} is executed. The
5225: optional default case can be added by simply writing the code after
5226: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5227: but must not consume it. The value @i{n} is consumed by this
5228: construction (either by a OF that matches, or by the ENDCASE, if no OF
5229: matches).
1.1 anton 5230:
1.69 anton 5231: @progstyle
1.131 anton 5232: To keep the code understandable, you should ensure that you change the
5233: stack in the same way (wrt. number and types of stack items consumed
5234: and pushed) on all paths through a selection construct.
1.69 anton 5235:
1.1 anton 5236: @node Simple Loops, Counted Loops, Selection, Control Structures
5237: @subsection Simple Loops
5238: @cindex simple loops
5239: @cindex loops without count
5240:
5241: @cindex @code{WHILE} loop
5242: @example
5243: BEGIN
1.29 crook 5244: @i{code1}
5245: @i{flag}
1.1 anton 5246: WHILE
1.29 crook 5247: @i{code2}
1.1 anton 5248: REPEAT
5249: @end example
5250:
1.29 crook 5251: @i{code1} is executed and @i{flag} is computed. If it is true,
5252: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5253: false, execution continues after the @code{REPEAT}.
5254:
5255: @cindex @code{UNTIL} loop
5256: @example
5257: BEGIN
1.29 crook 5258: @i{code}
5259: @i{flag}
1.1 anton 5260: UNTIL
5261: @end example
5262:
1.29 crook 5263: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5264:
1.69 anton 5265: @progstyle
5266: To keep the code understandable, a complete iteration of the loop should
5267: not change the number and types of the items on the stacks.
5268:
1.1 anton 5269: @cindex endless loop
5270: @cindex loops, endless
5271: @example
5272: BEGIN
1.29 crook 5273: @i{code}
1.1 anton 5274: AGAIN
5275: @end example
5276:
5277: This is an endless loop.
5278:
5279: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5280: @subsection Counted Loops
5281: @cindex counted loops
5282: @cindex loops, counted
5283: @cindex @code{DO} loops
5284:
5285: The basic counted loop is:
5286: @example
1.29 crook 5287: @i{limit} @i{start}
1.1 anton 5288: ?DO
1.29 crook 5289: @i{body}
1.1 anton 5290: LOOP
5291: @end example
5292:
1.29 crook 5293: This performs one iteration for every integer, starting from @i{start}
5294: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5295: accessed with @code{i}. For example, the loop:
1.1 anton 5296: @example
5297: 10 0 ?DO
5298: i .
5299: LOOP
5300: @end example
1.21 crook 5301: @noindent
5302: prints @code{0 1 2 3 4 5 6 7 8 9}
5303:
1.1 anton 5304: The index of the innermost loop can be accessed with @code{i}, the index
5305: of the next loop with @code{j}, and the index of the third loop with
5306: @code{k}.
5307:
1.44 crook 5308:
1.1 anton 5309: doc-i
5310: doc-j
5311: doc-k
5312:
1.44 crook 5313:
1.1 anton 5314: The loop control data are kept on the return stack, so there are some
1.21 crook 5315: restrictions on mixing return stack accesses and counted loop words. In
5316: particuler, if you put values on the return stack outside the loop, you
5317: cannot read them inside the loop@footnote{well, not in a way that is
5318: portable.}. If you put values on the return stack within a loop, you
5319: have to remove them before the end of the loop and before accessing the
5320: index of the loop.
1.1 anton 5321:
5322: There are several variations on the counted loop:
5323:
1.21 crook 5324: @itemize @bullet
5325: @item
5326: @code{LEAVE} leaves the innermost counted loop immediately; execution
5327: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5328:
5329: @example
5330: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5331: @end example
5332: prints @code{0 1 2 3}
5333:
1.1 anton 5334:
1.21 crook 5335: @item
5336: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5337: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5338: return stack so @code{EXIT} can get to its return address. For example:
5339:
5340: @example
5341: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5342: @end example
5343: prints @code{0 1 2 3}
5344:
5345:
5346: @item
1.29 crook 5347: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5348: (and @code{LOOP} iterates until they become equal by wrap-around
5349: arithmetic). This behaviour is usually not what you want. Therefore,
5350: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5351: @code{?DO}), which do not enter the loop if @i{start} is greater than
5352: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5353: unsigned loop parameters.
5354:
1.21 crook 5355: @item
5356: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5357: the loop, independent of the loop parameters. Do not use @code{DO}, even
5358: if you know that the loop is entered in any case. Such knowledge tends
5359: to become invalid during maintenance of a program, and then the
5360: @code{DO} will make trouble.
5361:
5362: @item
1.29 crook 5363: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5364: index by @i{n} instead of by 1. The loop is terminated when the border
5365: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5366:
1.21 crook 5367: @example
5368: 4 0 +DO i . 2 +LOOP
5369: @end example
5370: @noindent
5371: prints @code{0 2}
5372:
5373: @example
5374: 4 1 +DO i . 2 +LOOP
5375: @end example
5376: @noindent
5377: prints @code{1 3}
1.1 anton 5378:
1.68 anton 5379: @item
1.1 anton 5380: @cindex negative increment for counted loops
5381: @cindex counted loops with negative increment
1.29 crook 5382: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5383:
1.21 crook 5384: @example
5385: -1 0 ?DO i . -1 +LOOP
5386: @end example
5387: @noindent
5388: prints @code{0 -1}
1.1 anton 5389:
1.21 crook 5390: @example
5391: 0 0 ?DO i . -1 +LOOP
5392: @end example
5393: prints nothing.
1.1 anton 5394:
1.29 crook 5395: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5396: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5397: index by @i{u} each iteration. The loop is terminated when the border
5398: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5399: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5400:
1.21 crook 5401: @example
5402: -2 0 -DO i . 1 -LOOP
5403: @end example
5404: @noindent
5405: prints @code{0 -1}
1.1 anton 5406:
1.21 crook 5407: @example
5408: -1 0 -DO i . 1 -LOOP
5409: @end example
5410: @noindent
5411: prints @code{0}
5412:
5413: @example
5414: 0 0 -DO i . 1 -LOOP
5415: @end example
5416: @noindent
5417: prints nothing.
1.1 anton 5418:
1.21 crook 5419: @end itemize
1.1 anton 5420:
5421: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5422: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5423: for these words that uses only standard words is provided in
5424: @file{compat/loops.fs}.
1.1 anton 5425:
5426:
5427: @cindex @code{FOR} loops
1.26 crook 5428: Another counted loop is:
1.1 anton 5429: @example
1.29 crook 5430: @i{n}
1.1 anton 5431: FOR
1.29 crook 5432: @i{body}
1.1 anton 5433: NEXT
5434: @end example
5435: This is the preferred loop of native code compiler writers who are too
1.26 crook 5436: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5437: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5438: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5439: Forth systems may behave differently, even if they support @code{FOR}
5440: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5441:
5442: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5443: @subsection Arbitrary control structures
5444: @cindex control structures, user-defined
5445:
5446: @cindex control-flow stack
5447: ANS Forth permits and supports using control structures in a non-nested
5448: way. Information about incomplete control structures is stored on the
5449: control-flow stack. This stack may be implemented on the Forth data
5450: stack, and this is what we have done in Gforth.
5451:
5452: @cindex @code{orig}, control-flow stack item
5453: @cindex @code{dest}, control-flow stack item
5454: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5455: entry represents a backward branch target. A few words are the basis for
5456: building any control structure possible (except control structures that
5457: need storage, like calls, coroutines, and backtracking).
5458:
1.44 crook 5459:
1.1 anton 5460: doc-if
5461: doc-ahead
5462: doc-then
5463: doc-begin
5464: doc-until
5465: doc-again
5466: doc-cs-pick
5467: doc-cs-roll
5468:
1.44 crook 5469:
1.21 crook 5470: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5471: manipulate the control-flow stack in a portable way. Without them, you
5472: would need to know how many stack items are occupied by a control-flow
5473: entry (many systems use one cell. In Gforth they currently take three,
5474: but this may change in the future).
5475:
1.1 anton 5476: Some standard control structure words are built from these words:
5477:
1.44 crook 5478:
1.1 anton 5479: doc-else
5480: doc-while
5481: doc-repeat
5482:
1.44 crook 5483:
5484: @noindent
1.1 anton 5485: Gforth adds some more control-structure words:
5486:
1.44 crook 5487:
1.1 anton 5488: doc-endif
5489: doc-?dup-if
5490: doc-?dup-0=-if
5491:
1.44 crook 5492:
5493: @noindent
1.1 anton 5494: Counted loop words constitute a separate group of words:
5495:
1.44 crook 5496:
1.1 anton 5497: doc-?do
5498: doc-+do
5499: doc-u+do
5500: doc--do
5501: doc-u-do
5502: doc-do
5503: doc-for
5504: doc-loop
5505: doc-+loop
5506: doc--loop
5507: doc-next
5508: doc-leave
5509: doc-?leave
5510: doc-unloop
5511: doc-done
5512:
1.44 crook 5513:
1.21 crook 5514: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5515: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5516: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5517: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5518: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5519: resolved (by using one of the loop-ending words or @code{DONE}).
5520:
1.44 crook 5521: @noindent
1.26 crook 5522: Another group of control structure words are:
1.1 anton 5523:
1.44 crook 5524:
1.1 anton 5525: doc-case
5526: doc-endcase
5527: doc-of
5528: doc-endof
5529:
1.44 crook 5530:
1.21 crook 5531: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5532: @code{CS-ROLL}.
1.1 anton 5533:
5534: @subsubsection Programming Style
1.47 crook 5535: @cindex control structures programming style
5536: @cindex programming style, arbitrary control structures
1.1 anton 5537:
5538: In order to ensure readability we recommend that you do not create
5539: arbitrary control structures directly, but define new control structure
5540: words for the control structure you want and use these words in your
1.26 crook 5541: program. For example, instead of writing:
1.1 anton 5542:
5543: @example
1.26 crook 5544: BEGIN
1.1 anton 5545: ...
1.26 crook 5546: IF [ 1 CS-ROLL ]
1.1 anton 5547: ...
1.26 crook 5548: AGAIN THEN
1.1 anton 5549: @end example
5550:
1.21 crook 5551: @noindent
1.1 anton 5552: we recommend defining control structure words, e.g.,
5553:
5554: @example
1.26 crook 5555: : WHILE ( DEST -- ORIG DEST )
5556: POSTPONE IF
5557: 1 CS-ROLL ; immediate
5558:
5559: : REPEAT ( orig dest -- )
5560: POSTPONE AGAIN
5561: POSTPONE THEN ; immediate
1.1 anton 5562: @end example
5563:
1.21 crook 5564: @noindent
1.1 anton 5565: and then using these to create the control structure:
5566:
5567: @example
1.26 crook 5568: BEGIN
1.1 anton 5569: ...
1.26 crook 5570: WHILE
1.1 anton 5571: ...
1.26 crook 5572: REPEAT
1.1 anton 5573: @end example
5574:
5575: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5576: @code{WHILE} are predefined, so in this example it would not be
5577: necessary to define them.
5578:
5579: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5580: @subsection Calls and returns
5581: @cindex calling a definition
5582: @cindex returning from a definition
5583:
1.3 anton 5584: @cindex recursive definitions
5585: A definition can be called simply be writing the name of the definition
1.26 crook 5586: to be called. Normally a definition is invisible during its own
1.3 anton 5587: definition. If you want to write a directly recursive definition, you
1.26 crook 5588: can use @code{recursive} to make the current definition visible, or
5589: @code{recurse} to call the current definition directly.
1.3 anton 5590:
1.44 crook 5591:
1.3 anton 5592: doc-recursive
5593: doc-recurse
5594:
1.44 crook 5595:
1.21 crook 5596: @comment TODO add example of the two recursion methods
1.12 anton 5597: @quotation
5598: @progstyle
5599: I prefer using @code{recursive} to @code{recurse}, because calling the
5600: definition by name is more descriptive (if the name is well-chosen) than
5601: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5602: implementation, it is much better to read (and think) ``now sort the
5603: partitions'' than to read ``now do a recursive call''.
5604: @end quotation
1.3 anton 5605:
1.29 crook 5606: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5607:
5608: @example
1.28 crook 5609: Defer foo
1.3 anton 5610:
5611: : bar ( ... -- ... )
5612: ... foo ... ;
5613:
5614: :noname ( ... -- ... )
5615: ... bar ... ;
5616: IS foo
5617: @end example
5618:
1.44 crook 5619: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5620:
1.26 crook 5621: The current definition returns control to the calling definition when
1.33 anton 5622: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5623:
5624: doc-exit
5625: doc-;s
5626:
1.44 crook 5627:
1.1 anton 5628: @node Exception Handling, , Calls and returns, Control Structures
5629: @subsection Exception Handling
1.26 crook 5630: @cindex exceptions
1.1 anton 5631:
1.68 anton 5632: @c quit is a very bad idea for error handling,
5633: @c because it does not translate into a THROW
5634: @c it also does not belong into this chapter
5635:
5636: If a word detects an error condition that it cannot handle, it can
5637: @code{throw} an exception. In the simplest case, this will terminate
5638: your program, and report an appropriate error.
1.21 crook 5639:
1.68 anton 5640: doc-throw
1.1 anton 5641:
1.69 anton 5642: @code{Throw} consumes a cell-sized error number on the stack. There are
5643: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5644: Gforth (and most other systems) you can use the iors produced by various
5645: words as error numbers (e.g., a typical use of @code{allocate} is
5646: @code{allocate throw}). Gforth also provides the word @code{exception}
5647: to define your own error numbers (with decent error reporting); an ANS
5648: Forth version of this word (but without the error messages) is available
5649: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5650: numbers (anything outside the range -4095..0), but won't get nice error
5651: messages, only numbers. For example, try:
5652:
5653: @example
1.69 anton 5654: -10 throw \ ANS defined
5655: -267 throw \ system defined
5656: s" my error" exception throw \ user defined
5657: 7 throw \ arbitrary number
1.68 anton 5658: @end example
5659:
5660: doc---exception-exception
1.1 anton 5661:
1.69 anton 5662: A common idiom to @code{THROW} a specific error if a flag is true is
5663: this:
5664:
5665: @example
5666: @code{( flag ) 0<> @i{errno} and throw}
5667: @end example
5668:
5669: Your program can provide exception handlers to catch exceptions. An
5670: exception handler can be used to correct the problem, or to clean up
5671: some data structures and just throw the exception to the next exception
5672: handler. Note that @code{throw} jumps to the dynamically innermost
5673: exception handler. The system's exception handler is outermost, and just
5674: prints an error and restarts command-line interpretation (or, in batch
5675: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5676:
1.68 anton 5677: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5678:
1.68 anton 5679: doc-catch
5680:
5681: The most common use of exception handlers is to clean up the state when
5682: an error happens. E.g.,
1.1 anton 5683:
1.26 crook 5684: @example
1.68 anton 5685: base @ >r hex \ actually the hex should be inside foo, or we h
5686: ['] foo catch ( nerror|0 )
5687: r> base !
1.69 anton 5688: ( nerror|0 ) throw \ pass it on
1.26 crook 5689: @end example
1.1 anton 5690:
1.69 anton 5691: A use of @code{catch} for handling the error @code{myerror} might look
5692: like this:
1.44 crook 5693:
1.68 anton 5694: @example
1.69 anton 5695: ['] foo catch
5696: CASE
5697: myerror OF ... ( do something about it ) ENDOF
5698: dup throw \ default: pass other errors on, do nothing on non-errors
5699: ENDCASE
1.68 anton 5700: @end example
1.44 crook 5701:
1.68 anton 5702: Having to wrap the code into a separate word is often cumbersome,
5703: therefore Gforth provides an alternative syntax:
1.1 anton 5704:
5705: @example
1.69 anton 5706: TRY
1.68 anton 5707: @i{code1}
1.69 anton 5708: RECOVER \ optional
1.68 anton 5709: @i{code2} \ optional
1.69 anton 5710: ENDTRY
1.1 anton 5711: @end example
5712:
1.68 anton 5713: This performs @i{Code1}. If @i{code1} completes normally, execution
5714: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5715: reset to the state during @code{try}, the throw value is pushed on the
5716: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5717: through the @code{endtry} into the following code.
1.26 crook 5718:
1.68 anton 5719: doc-try
5720: doc-recover
5721: doc-endtry
1.26 crook 5722:
1.69 anton 5723: The cleanup example from above in this syntax:
1.26 crook 5724:
1.68 anton 5725: @example
1.69 anton 5726: base @ >r TRY
1.68 anton 5727: hex foo \ now the hex is placed correctly
1.69 anton 5728: 0 \ value for throw
1.92 anton 5729: RECOVER ENDTRY
1.68 anton 5730: r> base ! throw
1.1 anton 5731: @end example
5732:
1.69 anton 5733: And here's the error handling example:
1.1 anton 5734:
1.68 anton 5735: @example
1.69 anton 5736: TRY
1.68 anton 5737: foo
1.69 anton 5738: RECOVER
5739: CASE
5740: myerror OF ... ( do something about it ) ENDOF
5741: throw \ pass other errors on
5742: ENDCASE
5743: ENDTRY
1.68 anton 5744: @end example
1.1 anton 5745:
1.69 anton 5746: @progstyle
5747: As usual, you should ensure that the stack depth is statically known at
5748: the end: either after the @code{throw} for passing on errors, or after
5749: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5750: selection construct for handling the error).
5751:
1.68 anton 5752: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5753: and you can provide an error message. @code{Abort} just produces an
5754: ``Aborted'' error.
1.1 anton 5755:
1.68 anton 5756: The problem with these words is that exception handlers cannot
5757: differentiate between different @code{abort"}s; they just look like
5758: @code{-2 throw} to them (the error message cannot be accessed by
5759: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5760: exception handlers.
1.44 crook 5761:
1.68 anton 5762: doc-abort"
1.26 crook 5763: doc-abort
1.29 crook 5764:
5765:
1.44 crook 5766:
1.29 crook 5767: @c -------------------------------------------------------------
1.47 crook 5768: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5769: @section Defining Words
5770: @cindex defining words
5771:
1.47 crook 5772: Defining words are used to extend Forth by creating new entries in the dictionary.
5773:
1.29 crook 5774: @menu
1.67 anton 5775: * CREATE::
1.44 crook 5776: * Variables:: Variables and user variables
1.67 anton 5777: * Constants::
1.44 crook 5778: * Values:: Initialised variables
1.67 anton 5779: * Colon Definitions::
1.44 crook 5780: * Anonymous Definitions:: Definitions without names
1.69 anton 5781: * Supplying names:: Passing definition names as strings
1.67 anton 5782: * User-defined Defining Words::
1.44 crook 5783: * Deferred words:: Allow forward references
1.67 anton 5784: * Aliases::
1.29 crook 5785: @end menu
5786:
1.44 crook 5787: @node CREATE, Variables, Defining Words, Defining Words
5788: @subsection @code{CREATE}
1.29 crook 5789: @cindex simple defining words
5790: @cindex defining words, simple
5791:
5792: Defining words are used to create new entries in the dictionary. The
5793: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5794: this:
5795:
5796: @example
5797: CREATE new-word1
5798: @end example
5799:
1.69 anton 5800: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5801: input stream (@code{new-word1} in our example). It generates a
5802: dictionary entry for @code{new-word1}. When @code{new-word1} is
5803: executed, all that it does is leave an address on the stack. The address
5804: represents the value of the data space pointer (@code{HERE}) at the time
5805: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5806: associating a name with the address of a region of memory.
1.29 crook 5807:
1.34 anton 5808: doc-create
5809:
1.69 anton 5810: Note that in ANS Forth guarantees only for @code{create} that its body
5811: is in dictionary data space (i.e., where @code{here}, @code{allot}
5812: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5813: @code{create}d words can be modified with @code{does>}
5814: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5815: can only be applied to @code{create}d words.
5816:
1.29 crook 5817: By extending this example to reserve some memory in data space, we end
1.69 anton 5818: up with something like a @i{variable}. Here are two different ways to do
5819: it:
1.29 crook 5820:
5821: @example
5822: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5823: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5824: @end example
5825:
5826: The variable can be examined and modified using @code{@@} (``fetch'') and
5827: @code{!} (``store'') like this:
5828:
5829: @example
5830: new-word2 @@ . \ get address, fetch from it and display
5831: 1234 new-word2 ! \ new value, get address, store to it
5832: @end example
5833:
1.44 crook 5834: @cindex arrays
5835: A similar mechanism can be used to create arrays. For example, an
5836: 80-character text input buffer:
1.29 crook 5837:
5838: @example
1.44 crook 5839: CREATE text-buf 80 chars allot
5840:
5841: text-buf 0 chars c@@ \ the 1st character (offset 0)
5842: text-buf 3 chars c@@ \ the 4th character (offset 3)
5843: @end example
1.29 crook 5844:
1.44 crook 5845: You can build arbitrarily complex data structures by allocating
1.49 anton 5846: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5847: learn about some Gforth tools that make it easier,
1.49 anton 5848: @xref{Structures}.
1.44 crook 5849:
5850:
5851: @node Variables, Constants, CREATE, Defining Words
5852: @subsection Variables
5853: @cindex variables
5854:
5855: The previous section showed how a sequence of commands could be used to
5856: generate a variable. As a final refinement, the whole code sequence can
5857: be wrapped up in a defining word (pre-empting the subject of the next
5858: section), making it easier to create new variables:
5859:
5860: @example
5861: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5862: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5863:
5864: myvariableX foo \ variable foo starts off with an unknown value
5865: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5866:
5867: 45 3 * foo ! \ set foo to 135
5868: 1234 joe ! \ set joe to 1234
5869: 3 joe +! \ increment joe by 3.. to 1237
5870: @end example
5871:
5872: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5873: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5874: guarantee that a @code{Variable} is initialised when it is created
5875: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5876: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5877: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5878: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5879: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5880: store a boolean, you can use @code{on} and @code{off} to toggle its
5881: state.
1.29 crook 5882:
1.34 anton 5883: doc-variable
5884: doc-2variable
5885: doc-fvariable
5886:
1.29 crook 5887: @cindex user variables
5888: @cindex user space
5889: The defining word @code{User} behaves in the same way as @code{Variable}.
5890: The difference is that it reserves space in @i{user (data) space} rather
5891: than normal data space. In a Forth system that has a multi-tasker, each
5892: task has its own set of user variables.
5893:
1.34 anton 5894: doc-user
1.67 anton 5895: @c doc-udp
5896: @c doc-uallot
1.34 anton 5897:
1.29 crook 5898: @comment TODO is that stuff about user variables strictly correct? Is it
5899: @comment just terminal tasks that have user variables?
5900: @comment should document tasker.fs (with some examples) elsewhere
5901: @comment in this manual, then expand on user space and user variables.
5902:
1.44 crook 5903: @node Constants, Values, Variables, Defining Words
5904: @subsection Constants
5905: @cindex constants
5906:
5907: @code{Constant} allows you to declare a fixed value and refer to it by
5908: name. For example:
1.29 crook 5909:
5910: @example
5911: 12 Constant INCHES-PER-FOOT
5912: 3E+08 fconstant SPEED-O-LIGHT
5913: @end example
5914:
5915: A @code{Variable} can be both read and written, so its run-time
5916: behaviour is to supply an address through which its current value can be
5917: manipulated. In contrast, the value of a @code{Constant} cannot be
5918: changed once it has been declared@footnote{Well, often it can be -- but
5919: not in a Standard, portable way. It's safer to use a @code{Value} (read
5920: on).} so it's not necessary to supply the address -- it is more
5921: efficient to return the value of the constant directly. That's exactly
5922: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5923: the top of the stack (You can find one
5924: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5925:
1.69 anton 5926: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5927: double and floating-point constants, respectively.
5928:
1.34 anton 5929: doc-constant
5930: doc-2constant
5931: doc-fconstant
5932:
5933: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5934: @c nac-> How could that not be true in an ANS Forth? You can't define a
5935: @c constant, use it and then delete the definition of the constant..
1.69 anton 5936:
5937: @c anton->An ANS Forth system can compile a constant to a literal; On
5938: @c decompilation you would see only the number, just as if it had been used
5939: @c in the first place. The word will stay, of course, but it will only be
5940: @c used by the text interpreter (no run-time duties, except when it is
5941: @c POSTPONEd or somesuch).
5942:
5943: @c nac:
1.44 crook 5944: @c I agree that it's rather deep, but IMO it is an important difference
5945: @c relative to other programming languages.. often it's annoying: it
5946: @c certainly changes my programming style relative to C.
5947:
1.69 anton 5948: @c anton: In what way?
5949:
1.29 crook 5950: Constants in Forth behave differently from their equivalents in other
5951: programming languages. In other languages, a constant (such as an EQU in
5952: assembler or a #define in C) only exists at compile-time; in the
5953: executable program the constant has been translated into an absolute
5954: number and, unless you are using a symbolic debugger, it's impossible to
5955: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5956: an entry in the header space and remains there after the code that uses
5957: it has been defined. In fact, it must remain in the dictionary since it
5958: has run-time duties to perform. For example:
1.29 crook 5959:
5960: @example
5961: 12 Constant INCHES-PER-FOOT
5962: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5963: @end example
5964:
5965: @cindex in-lining of constants
5966: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5967: associated with the constant @code{INCHES-PER-FOOT}. If you use
5968: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5969: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5970: attempt to optimise constants by in-lining them where they are used. You
5971: can force Gforth to in-line a constant like this:
5972:
5973: @example
5974: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5975: @end example
5976:
5977: If you use @code{see} to decompile @i{this} version of
5978: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5979: longer present. To understand how this works, read
5980: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5981:
5982: In-lining constants in this way might improve execution time
5983: fractionally, and can ensure that a constant is now only referenced at
5984: compile-time. However, the definition of the constant still remains in
5985: the dictionary. Some Forth compilers provide a mechanism for controlling
5986: a second dictionary for holding transient words such that this second
5987: dictionary can be deleted later in order to recover memory
5988: space. However, there is no standard way of doing this.
5989:
5990:
1.44 crook 5991: @node Values, Colon Definitions, Constants, Defining Words
5992: @subsection Values
5993: @cindex values
1.34 anton 5994:
1.69 anton 5995: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5996: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5997: (not in ANS Forth) you can access (and change) a @code{value} also with
5998: @code{>body}.
5999:
6000: Here are some
6001: examples:
1.29 crook 6002:
6003: @example
1.69 anton 6004: 12 Value APPLES \ Define APPLES with an initial value of 12
6005: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6006: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6007: APPLES \ puts 35 on the top of the stack.
1.29 crook 6008: @end example
6009:
1.44 crook 6010: doc-value
6011: doc-to
1.29 crook 6012:
1.35 anton 6013:
1.69 anton 6014:
1.44 crook 6015: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6016: @subsection Colon Definitions
6017: @cindex colon definitions
1.35 anton 6018:
6019: @example
1.44 crook 6020: : name ( ... -- ... )
6021: word1 word2 word3 ;
1.29 crook 6022: @end example
6023:
1.44 crook 6024: @noindent
6025: Creates a word called @code{name} that, upon execution, executes
6026: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6027:
1.49 anton 6028: The explanation above is somewhat superficial. For simple examples of
6029: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6030: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6031: Compilation Semantics}.
1.29 crook 6032:
1.44 crook 6033: doc-:
6034: doc-;
1.1 anton 6035:
1.34 anton 6036:
1.69 anton 6037: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6038: @subsection Anonymous Definitions
6039: @cindex colon definitions
6040: @cindex defining words without name
1.34 anton 6041:
1.44 crook 6042: Sometimes you want to define an @dfn{anonymous word}; a word without a
6043: name. You can do this with:
1.1 anton 6044:
1.44 crook 6045: doc-:noname
1.1 anton 6046:
1.44 crook 6047: This leaves the execution token for the word on the stack after the
6048: closing @code{;}. Here's an example in which a deferred word is
6049: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6050:
1.29 crook 6051: @example
1.44 crook 6052: Defer deferred
6053: :noname ( ... -- ... )
6054: ... ;
6055: IS deferred
1.29 crook 6056: @end example
1.26 crook 6057:
1.44 crook 6058: @noindent
6059: Gforth provides an alternative way of doing this, using two separate
6060: words:
1.27 crook 6061:
1.44 crook 6062: doc-noname
6063: @cindex execution token of last defined word
1.116 anton 6064: doc-latestxt
1.1 anton 6065:
1.44 crook 6066: @noindent
6067: The previous example can be rewritten using @code{noname} and
1.116 anton 6068: @code{latestxt}:
1.1 anton 6069:
1.26 crook 6070: @example
1.44 crook 6071: Defer deferred
6072: noname : ( ... -- ... )
6073: ... ;
1.116 anton 6074: latestxt IS deferred
1.26 crook 6075: @end example
1.1 anton 6076:
1.29 crook 6077: @noindent
1.44 crook 6078: @code{noname} works with any defining word, not just @code{:}.
6079:
1.116 anton 6080: @code{latestxt} also works when the last word was not defined as
1.71 anton 6081: @code{noname}. It does not work for combined words, though. It also has
6082: the useful property that is is valid as soon as the header for a
6083: definition has been built. Thus:
1.44 crook 6084:
6085: @example
1.116 anton 6086: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6087: @end example
1.1 anton 6088:
1.44 crook 6089: @noindent
6090: prints 3 numbers; the last two are the same.
1.26 crook 6091:
1.69 anton 6092: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6093: @subsection Supplying the name of a defined word
6094: @cindex names for defined words
6095: @cindex defining words, name given in a string
6096:
6097: By default, a defining word takes the name for the defined word from the
6098: input stream. Sometimes you want to supply the name from a string. You
6099: can do this with:
6100:
6101: doc-nextname
6102:
6103: For example:
6104:
6105: @example
6106: s" foo" nextname create
6107: @end example
6108:
6109: @noindent
6110: is equivalent to:
6111:
6112: @example
6113: create foo
6114: @end example
6115:
6116: @noindent
6117: @code{nextname} works with any defining word.
6118:
1.1 anton 6119:
1.69 anton 6120: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6121: @subsection User-defined Defining Words
6122: @cindex user-defined defining words
6123: @cindex defining words, user-defined
1.1 anton 6124:
1.29 crook 6125: You can create a new defining word by wrapping defining-time code around
6126: an existing defining word and putting the sequence in a colon
1.69 anton 6127: definition.
6128:
6129: @c anton: This example is very complex and leads in a quite different
6130: @c direction from the CREATE-DOES> stuff that follows. It should probably
6131: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6132: @c subsection of Defining Words)
6133:
6134: For example, suppose that you have a word @code{stats} that
1.29 crook 6135: gathers statistics about colon definitions given the @i{xt} of the
6136: definition, and you want every colon definition in your application to
6137: make a call to @code{stats}. You can define and use a new version of
6138: @code{:} like this:
6139:
6140: @example
6141: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6142: ... ; \ other code
6143:
1.116 anton 6144: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6145:
6146: my: foo + - ;
6147: @end example
6148:
6149: When @code{foo} is defined using @code{my:} these steps occur:
6150:
6151: @itemize @bullet
6152: @item
6153: @code{my:} is executed.
6154: @item
6155: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6156: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6157: the input stream for a name, builds a dictionary header for the name
6158: @code{foo} and switches @code{state} from interpret to compile.
6159: @item
1.116 anton 6160: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6161: being defined -- @code{foo} -- onto the stack.
6162: @item
6163: The code that was produced by @code{postpone literal} is executed; this
6164: causes the value on the stack to be compiled as a literal in the code
6165: area of @code{foo}.
6166: @item
6167: The code @code{['] stats} compiles a literal into the definition of
6168: @code{my:}. When @code{compile,} is executed, that literal -- the
6169: execution token for @code{stats} -- is layed down in the code area of
6170: @code{foo} , following the literal@footnote{Strictly speaking, the
6171: mechanism that @code{compile,} uses to convert an @i{xt} into something
6172: in the code area is implementation-dependent. A threaded implementation
6173: might spit out the execution token directly whilst another
6174: implementation might spit out a native code sequence.}.
6175: @item
6176: At this point, the execution of @code{my:} is complete, and control
6177: returns to the text interpreter. The text interpreter is in compile
6178: state, so subsequent text @code{+ -} is compiled into the definition of
6179: @code{foo} and the @code{;} terminates the definition as always.
6180: @end itemize
6181:
6182: You can use @code{see} to decompile a word that was defined using
6183: @code{my:} and see how it is different from a normal @code{:}
6184: definition. For example:
6185:
6186: @example
6187: : bar + - ; \ like foo but using : rather than my:
6188: see bar
6189: : bar
6190: + - ;
6191: see foo
6192: : foo
6193: 107645672 stats + - ;
6194:
1.140 anton 6195: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6196: @end example
6197:
6198: You can use techniques like this to make new defining words in terms of
6199: @i{any} existing defining word.
1.1 anton 6200:
6201:
1.29 crook 6202: @cindex defining defining words
1.26 crook 6203: @cindex @code{CREATE} ... @code{DOES>}
6204: If you want the words defined with your defining words to behave
6205: differently from words defined with standard defining words, you can
6206: write your defining word like this:
1.1 anton 6207:
6208: @example
1.26 crook 6209: : def-word ( "name" -- )
1.29 crook 6210: CREATE @i{code1}
1.26 crook 6211: DOES> ( ... -- ... )
1.29 crook 6212: @i{code2} ;
1.26 crook 6213:
6214: def-word name
1.1 anton 6215: @end example
6216:
1.29 crook 6217: @cindex child words
6218: This fragment defines a @dfn{defining word} @code{def-word} and then
6219: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6220: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6221: is not executed at this time. The word @code{name} is sometimes called a
6222: @dfn{child} of @code{def-word}.
6223:
6224: When you execute @code{name}, the address of the body of @code{name} is
6225: put on the data stack and @i{code2} is executed (the address of the body
6226: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6227: @code{CREATE}, i.e., the address a @code{create}d word returns by
6228: default).
6229:
6230: @c anton:
6231: @c www.dictionary.com says:
6232: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6233: @c several generations of absence, usually caused by the chance
6234: @c recombination of genes. 2.An individual or a part that exhibits
6235: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6236: @c of previous behavior after a period of absence.
6237: @c
6238: @c Doesn't seem to fit.
1.29 crook 6239:
1.69 anton 6240: @c @cindex atavism in child words
1.33 anton 6241: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6242: similarly; they all have a common run-time behaviour determined by
6243: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6244: body of the child word. The structure of the data is common to all
6245: children of @code{def-word}, but the data values are specific -- and
6246: private -- to each child word. When a child word is executed, the
6247: address of its private data area is passed as a parameter on TOS to be
6248: used and manipulated@footnote{It is legitimate both to read and write to
6249: this data area.} by @i{code2}.
1.29 crook 6250:
6251: The two fragments of code that make up the defining words act (are
6252: executed) at two completely separate times:
1.1 anton 6253:
1.29 crook 6254: @itemize @bullet
6255: @item
6256: At @i{define time}, the defining word executes @i{code1} to generate a
6257: child word
6258: @item
6259: At @i{child execution time}, when a child word is invoked, @i{code2}
6260: is executed, using parameters (data) that are private and specific to
6261: the child word.
6262: @end itemize
6263:
1.44 crook 6264: Another way of understanding the behaviour of @code{def-word} and
6265: @code{name} is to say that, if you make the following definitions:
1.33 anton 6266: @example
6267: : def-word1 ( "name" -- )
6268: CREATE @i{code1} ;
6269:
6270: : action1 ( ... -- ... )
6271: @i{code2} ;
6272:
6273: def-word1 name1
6274: @end example
6275:
1.44 crook 6276: @noindent
6277: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6278:
1.29 crook 6279: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6280:
1.1 anton 6281: @example
1.29 crook 6282: : CONSTANT ( w "name" -- )
6283: CREATE ,
1.26 crook 6284: DOES> ( -- w )
6285: @@ ;
1.1 anton 6286: @end example
6287:
1.29 crook 6288: @comment There is a beautiful description of how this works and what
6289: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6290: @comment commentary on the Counting Fruits problem.
6291:
6292: When you create a constant with @code{5 CONSTANT five}, a set of
6293: define-time actions take place; first a new word @code{five} is created,
6294: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6295: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6296: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6297: no code of its own; it simply contains a data field and a pointer to the
6298: code that follows @code{DOES>} in its defining word. That makes words
6299: created in this way very compact.
6300:
6301: The final example in this section is intended to remind you that space
6302: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6303: both read and written by a Standard program@footnote{Exercise: use this
6304: example as a starting point for your own implementation of @code{Value}
6305: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6306: @code{[']}.}:
6307:
6308: @example
6309: : foo ( "name" -- )
6310: CREATE -1 ,
6311: DOES> ( -- )
1.33 anton 6312: @@ . ;
1.29 crook 6313:
6314: foo first-word
6315: foo second-word
6316:
6317: 123 ' first-word >BODY !
6318: @end example
6319:
6320: If @code{first-word} had been a @code{CREATE}d word, we could simply
6321: have executed it to get the address of its data field. However, since it
6322: was defined to have @code{DOES>} actions, its execution semantics are to
6323: perform those @code{DOES>} actions. To get the address of its data field
6324: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6325: translate the xt into the address of the data field. When you execute
6326: @code{first-word}, it will display @code{123}. When you execute
6327: @code{second-word} it will display @code{-1}.
1.26 crook 6328:
6329: @cindex stack effect of @code{DOES>}-parts
6330: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6331: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6332: the stack effect of the defined words, not the stack effect of the
6333: following code (the following code expects the address of the body on
6334: the top of stack, which is not reflected in the stack comment). This is
6335: the convention that I use and recommend (it clashes a bit with using
6336: locals declarations for stack effect specification, though).
1.1 anton 6337:
1.53 anton 6338: @menu
6339: * CREATE..DOES> applications::
6340: * CREATE..DOES> details::
1.63 anton 6341: * Advanced does> usage example::
1.155 anton 6342: * Const-does>::
1.53 anton 6343: @end menu
6344:
6345: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6346: @subsubsection Applications of @code{CREATE..DOES>}
6347: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6348:
1.26 crook 6349: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6350:
1.26 crook 6351: @cindex factoring similar colon definitions
6352: When you see a sequence of code occurring several times, and you can
6353: identify a meaning, you will factor it out as a colon definition. When
6354: you see similar colon definitions, you can factor them using
6355: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6356: that look very similar:
1.1 anton 6357: @example
1.26 crook 6358: : ori, ( reg-target reg-source n -- )
6359: 0 asm-reg-reg-imm ;
6360: : andi, ( reg-target reg-source n -- )
6361: 1 asm-reg-reg-imm ;
1.1 anton 6362: @end example
6363:
1.26 crook 6364: @noindent
6365: This could be factored with:
6366: @example
6367: : reg-reg-imm ( op-code -- )
6368: CREATE ,
6369: DOES> ( reg-target reg-source n -- )
6370: @@ asm-reg-reg-imm ;
6371:
6372: 0 reg-reg-imm ori,
6373: 1 reg-reg-imm andi,
6374: @end example
1.1 anton 6375:
1.26 crook 6376: @cindex currying
6377: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6378: supply a part of the parameters for a word (known as @dfn{currying} in
6379: the functional language community). E.g., @code{+} needs two
6380: parameters. Creating versions of @code{+} with one parameter fixed can
6381: be done like this:
1.82 anton 6382:
1.1 anton 6383: @example
1.82 anton 6384: : curry+ ( n1 "name" -- )
1.26 crook 6385: CREATE ,
6386: DOES> ( n2 -- n1+n2 )
6387: @@ + ;
6388:
6389: 3 curry+ 3+
6390: -2 curry+ 2-
1.1 anton 6391: @end example
6392:
1.91 anton 6393:
1.63 anton 6394: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6395: @subsubsection The gory details of @code{CREATE..DOES>}
6396: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6397:
1.26 crook 6398: doc-does>
1.1 anton 6399:
1.26 crook 6400: @cindex @code{DOES>} in a separate definition
6401: This means that you need not use @code{CREATE} and @code{DOES>} in the
6402: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6403: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6404: @example
6405: : does1
6406: DOES> ( ... -- ... )
1.44 crook 6407: ... ;
6408:
6409: : does2
6410: DOES> ( ... -- ... )
6411: ... ;
6412:
6413: : def-word ( ... -- ... )
6414: create ...
6415: IF
6416: does1
6417: ELSE
6418: does2
6419: ENDIF ;
6420: @end example
6421:
6422: In this example, the selection of whether to use @code{does1} or
1.69 anton 6423: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6424: @code{CREATE}d.
6425:
6426: @cindex @code{DOES>} in interpretation state
6427: In a standard program you can apply a @code{DOES>}-part only if the last
6428: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6429: will override the behaviour of the last word defined in any case. In a
6430: standard program, you can use @code{DOES>} only in a colon
6431: definition. In Gforth, you can also use it in interpretation state, in a
6432: kind of one-shot mode; for example:
6433: @example
6434: CREATE name ( ... -- ... )
6435: @i{initialization}
6436: DOES>
6437: @i{code} ;
6438: @end example
6439:
6440: @noindent
6441: is equivalent to the standard:
6442: @example
6443: :noname
6444: DOES>
6445: @i{code} ;
6446: CREATE name EXECUTE ( ... -- ... )
6447: @i{initialization}
6448: @end example
6449:
1.53 anton 6450: doc->body
6451:
1.152 pazsan 6452: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6453: @subsubsection Advanced does> usage example
6454:
6455: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6456: for disassembling instructions, that follow a very repetetive scheme:
6457:
6458: @example
6459: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6460: @var{entry-num} cells @var{table} + !
6461: @end example
6462:
6463: Of course, this inspires the idea to factor out the commonalities to
6464: allow a definition like
6465:
6466: @example
6467: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6468: @end example
6469:
6470: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6471: correlated. Moreover, before I wrote the disassembler, there already
6472: existed code that defines instructions like this:
1.63 anton 6473:
6474: @example
6475: @var{entry-num} @var{inst-format} @var{inst-name}
6476: @end example
6477:
6478: This code comes from the assembler and resides in
6479: @file{arch/mips/insts.fs}.
6480:
6481: So I had to define the @var{inst-format} words that performed the scheme
6482: above when executed. At first I chose to use run-time code-generation:
6483:
6484: @example
6485: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6486: :noname Postpone @var{disasm-operands}
6487: name Postpone sliteral Postpone type Postpone ;
6488: swap cells @var{table} + ! ;
6489: @end example
6490:
6491: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6492:
1.63 anton 6493: An alternative would have been to write this using
6494: @code{create}/@code{does>}:
6495:
6496: @example
6497: : @var{inst-format} ( entry-num "name" -- )
6498: here name string, ( entry-num c-addr ) \ parse and save "name"
6499: noname create , ( entry-num )
1.116 anton 6500: latestxt swap cells @var{table} + !
1.63 anton 6501: does> ( addr w -- )
6502: \ disassemble instruction w at addr
6503: @@ >r
6504: @var{disasm-operands}
6505: r> count type ;
6506: @end example
6507:
6508: Somehow the first solution is simpler, mainly because it's simpler to
6509: shift a string from definition-time to use-time with @code{sliteral}
6510: than with @code{string,} and friends.
6511:
6512: I wrote a lot of words following this scheme and soon thought about
6513: factoring out the commonalities among them. Note that this uses a
6514: two-level defining word, i.e., a word that defines ordinary defining
6515: words.
6516:
6517: This time a solution involving @code{postpone} and friends seemed more
6518: difficult (try it as an exercise), so I decided to use a
6519: @code{create}/@code{does>} word; since I was already at it, I also used
6520: @code{create}/@code{does>} for the lower level (try using
6521: @code{postpone} etc. as an exercise), resulting in the following
6522: definition:
6523:
6524: @example
6525: : define-format ( disasm-xt table-xt -- )
6526: \ define an instruction format that uses disasm-xt for
6527: \ disassembling and enters the defined instructions into table
6528: \ table-xt
6529: create 2,
6530: does> ( u "inst" -- )
6531: \ defines an anonymous word for disassembling instruction inst,
6532: \ and enters it as u-th entry into table-xt
6533: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6534: noname create 2, \ define anonymous word
1.116 anton 6535: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6536: does> ( addr w -- )
6537: \ disassemble instruction w at addr
6538: 2@@ >r ( addr w disasm-xt R: c-addr )
6539: execute ( R: c-addr ) \ disassemble operands
6540: r> count type ; \ print name
6541: @end example
6542:
6543: Note that the tables here (in contrast to above) do the @code{cells +}
6544: by themselves (that's why you have to pass an xt). This word is used in
6545: the following way:
6546:
6547: @example
6548: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6549: @end example
6550:
1.71 anton 6551: As shown above, the defined instruction format is then used like this:
6552:
6553: @example
6554: @var{entry-num} @var{inst-format} @var{inst-name}
6555: @end example
6556:
1.63 anton 6557: In terms of currying, this kind of two-level defining word provides the
6558: parameters in three stages: first @var{disasm-operands} and @var{table},
6559: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6560: the instruction to be disassembled.
6561:
6562: Of course this did not quite fit all the instruction format names used
6563: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6564: the parameters into the right form.
6565:
6566: If you have trouble following this section, don't worry. First, this is
6567: involved and takes time (and probably some playing around) to
6568: understand; second, this is the first two-level
6569: @code{create}/@code{does>} word I have written in seventeen years of
6570: Forth; and if I did not have @file{insts.fs} to start with, I may well
6571: have elected to use just a one-level defining word (with some repeating
6572: of parameters when using the defining word). So it is not necessary to
6573: understand this, but it may improve your understanding of Forth.
1.44 crook 6574:
6575:
1.152 pazsan 6576: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6577: @subsubsection @code{Const-does>}
6578:
6579: A frequent use of @code{create}...@code{does>} is for transferring some
6580: values from definition-time to run-time. Gforth supports this use with
6581:
6582: doc-const-does>
6583:
6584: A typical use of this word is:
6585:
6586: @example
6587: : curry+ ( n1 "name" -- )
6588: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6589: + ;
6590:
6591: 3 curry+ 3+
6592: @end example
6593:
6594: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6595: definition to run-time.
6596:
6597: The advantages of using @code{const-does>} are:
6598:
6599: @itemize
6600:
6601: @item
6602: You don't have to deal with storing and retrieving the values, i.e.,
6603: your program becomes more writable and readable.
6604:
6605: @item
6606: When using @code{does>}, you have to introduce a @code{@@} that cannot
6607: be optimized away (because you could change the data using
6608: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6609:
6610: @end itemize
6611:
6612: An ANS Forth implementation of @code{const-does>} is available in
6613: @file{compat/const-does.fs}.
6614:
6615:
1.44 crook 6616: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6617: @subsection Deferred words
6618: @cindex deferred words
6619:
6620: The defining word @code{Defer} allows you to define a word by name
6621: without defining its behaviour; the definition of its behaviour is
6622: deferred. Here are two situation where this can be useful:
6623:
6624: @itemize @bullet
6625: @item
6626: Where you want to allow the behaviour of a word to be altered later, and
6627: for all precompiled references to the word to change when its behaviour
6628: is changed.
6629: @item
6630: For mutual recursion; @xref{Calls and returns}.
6631: @end itemize
6632:
6633: In the following example, @code{foo} always invokes the version of
6634: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6635: always invokes the version that prints ``@code{Hello}''. There is no way
6636: of getting @code{foo} to use the later version without re-ordering the
6637: source code and recompiling it.
6638:
6639: @example
6640: : greet ." Good morning" ;
6641: : foo ... greet ... ;
6642: : greet ." Hello" ;
6643: : bar ... greet ... ;
6644: @end example
6645:
6646: This problem can be solved by defining @code{greet} as a @code{Defer}red
6647: word. The behaviour of a @code{Defer}red word can be defined and
6648: redefined at any time by using @code{IS} to associate the xt of a
6649: previously-defined word with it. The previous example becomes:
6650:
6651: @example
1.69 anton 6652: Defer greet ( -- )
1.44 crook 6653: : foo ... greet ... ;
6654: : bar ... greet ... ;
1.69 anton 6655: : greet1 ( -- ) ." Good morning" ;
6656: : greet2 ( -- ) ." Hello" ;
1.132 anton 6657: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6658: @end example
6659:
1.69 anton 6660: @progstyle
6661: You should write a stack comment for every deferred word, and put only
6662: XTs into deferred words that conform to this stack effect. Otherwise
6663: it's too difficult to use the deferred word.
6664:
1.44 crook 6665: A deferred word can be used to improve the statistics-gathering example
6666: from @ref{User-defined Defining Words}; rather than edit the
6667: application's source code to change every @code{:} to a @code{my:}, do
6668: this:
6669:
6670: @example
6671: : real: : ; \ retain access to the original
6672: defer : \ redefine as a deferred word
1.132 anton 6673: ' my: IS : \ use special version of :
1.44 crook 6674: \
6675: \ load application here
6676: \
1.132 anton 6677: ' real: IS : \ go back to the original
1.44 crook 6678: @end example
6679:
6680:
1.132 anton 6681: One thing to note is that @code{IS} has special compilation semantics,
6682: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6683:
6684: @example
6685: : set-greet ( xt -- )
1.132 anton 6686: IS greet ;
1.44 crook 6687:
6688: ' greet1 set-greet
6689: @end example
6690:
1.132 anton 6691: In situations where @code{IS} does not fit, use @code{defer!} instead.
6692:
1.69 anton 6693: A deferred word can only inherit execution semantics from the xt
6694: (because that is all that an xt can represent -- for more discussion of
6695: this @pxref{Tokens for Words}); by default it will have default
6696: interpretation and compilation semantics deriving from this execution
6697: semantics. However, you can change the interpretation and compilation
6698: semantics of the deferred word in the usual ways:
1.44 crook 6699:
6700: @example
1.132 anton 6701: : bar .... ; immediate
1.44 crook 6702: Defer fred immediate
6703: Defer jim
6704:
1.132 anton 6705: ' bar IS jim \ jim has default semantics
6706: ' bar IS fred \ fred is immediate
1.44 crook 6707: @end example
6708:
6709: doc-defer
1.132 anton 6710: doc-defer!
1.44 crook 6711: doc-is
1.132 anton 6712: doc-defer@
6713: doc-action-of
1.44 crook 6714: @comment TODO document these: what's defers [is]
6715: doc-defers
6716:
6717: @c Use @code{words-deferred} to see a list of deferred words.
6718:
1.132 anton 6719: Definitions of these words (except @code{defers}) in ANS Forth are
6720: provided in @file{compat/defer.fs}.
1.44 crook 6721:
6722:
1.69 anton 6723: @node Aliases, , Deferred words, Defining Words
1.44 crook 6724: @subsection Aliases
6725: @cindex aliases
1.1 anton 6726:
1.44 crook 6727: The defining word @code{Alias} allows you to define a word by name that
6728: has the same behaviour as some other word. Here are two situation where
6729: this can be useful:
1.1 anton 6730:
1.44 crook 6731: @itemize @bullet
6732: @item
6733: When you want access to a word's definition from a different word list
6734: (for an example of this, see the definition of the @code{Root} word list
6735: in the Gforth source).
6736: @item
6737: When you want to create a synonym; a definition that can be known by
6738: either of two names (for example, @code{THEN} and @code{ENDIF} are
6739: aliases).
6740: @end itemize
1.1 anton 6741:
1.69 anton 6742: Like deferred words, an alias has default compilation and interpretation
6743: semantics at the beginning (not the modifications of the other word),
6744: but you can change them in the usual ways (@code{immediate},
6745: @code{compile-only}). For example:
1.1 anton 6746:
6747: @example
1.44 crook 6748: : foo ... ; immediate
6749:
6750: ' foo Alias bar \ bar is not an immediate word
6751: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6752: @end example
6753:
1.44 crook 6754: Words that are aliases have the same xt, different headers in the
6755: dictionary, and consequently different name tokens (@pxref{Tokens for
6756: Words}) and possibly different immediate flags. An alias can only have
6757: default or immediate compilation semantics; you can define aliases for
6758: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6759:
1.44 crook 6760: doc-alias
1.1 anton 6761:
6762:
1.47 crook 6763: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6764: @section Interpretation and Compilation Semantics
1.26 crook 6765: @cindex semantics, interpretation and compilation
1.1 anton 6766:
1.71 anton 6767: @c !! state and ' are used without explanation
6768: @c example for immediate/compile-only? or is the tutorial enough
6769:
1.26 crook 6770: @cindex interpretation semantics
1.71 anton 6771: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6772: interpreter does when it encounters the word in interpret state. It also
6773: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6774: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6775: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6776: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6777:
1.26 crook 6778: @cindex compilation semantics
1.71 anton 6779: The @dfn{compilation semantics} of a (named) word are what the text
6780: interpreter does when it encounters the word in compile state. It also
6781: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6782: compiles@footnote{In standard terminology, ``appends to the current
6783: definition''.} the compilation semantics of @i{word}.
1.1 anton 6784:
1.26 crook 6785: @cindex execution semantics
6786: The standard also talks about @dfn{execution semantics}. They are used
6787: only for defining the interpretation and compilation semantics of many
6788: words. By default, the interpretation semantics of a word are to
6789: @code{execute} its execution semantics, and the compilation semantics of
6790: a word are to @code{compile,} its execution semantics.@footnote{In
6791: standard terminology: The default interpretation semantics are its
6792: execution semantics; the default compilation semantics are to append its
6793: execution semantics to the execution semantics of the current
6794: definition.}
6795:
1.71 anton 6796: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6797: the text interpreter, ticked, or @code{postpone}d, so they have no
6798: interpretation or compilation semantics. Their behaviour is represented
6799: by their XT (@pxref{Tokens for Words}), and we call it execution
6800: semantics, too.
6801:
1.26 crook 6802: @comment TODO expand, make it co-operate with new sections on text interpreter.
6803:
6804: @cindex immediate words
6805: @cindex compile-only words
6806: You can change the semantics of the most-recently defined word:
6807:
1.44 crook 6808:
1.26 crook 6809: doc-immediate
6810: doc-compile-only
6811: doc-restrict
6812:
1.82 anton 6813: By convention, words with non-default compilation semantics (e.g.,
6814: immediate words) often have names surrounded with brackets (e.g.,
6815: @code{[']}, @pxref{Execution token}).
1.44 crook 6816:
1.26 crook 6817: Note that ticking (@code{'}) a compile-only word gives an error
6818: (``Interpreting a compile-only word'').
1.1 anton 6819:
1.47 crook 6820: @menu
1.67 anton 6821: * Combined words::
1.47 crook 6822: @end menu
1.44 crook 6823:
1.71 anton 6824:
1.48 anton 6825: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6826: @subsection Combined Words
6827: @cindex combined words
6828:
6829: Gforth allows you to define @dfn{combined words} -- words that have an
6830: arbitrary combination of interpretation and compilation semantics.
6831:
1.26 crook 6832: doc-interpret/compile:
1.1 anton 6833:
1.26 crook 6834: This feature was introduced for implementing @code{TO} and @code{S"}. I
6835: recommend that you do not define such words, as cute as they may be:
6836: they make it hard to get at both parts of the word in some contexts.
6837: E.g., assume you want to get an execution token for the compilation
6838: part. Instead, define two words, one that embodies the interpretation
6839: part, and one that embodies the compilation part. Once you have done
6840: that, you can define a combined word with @code{interpret/compile:} for
6841: the convenience of your users.
1.1 anton 6842:
1.26 crook 6843: You might try to use this feature to provide an optimizing
6844: implementation of the default compilation semantics of a word. For
6845: example, by defining:
1.1 anton 6846: @example
1.26 crook 6847: :noname
6848: foo bar ;
6849: :noname
6850: POSTPONE foo POSTPONE bar ;
1.29 crook 6851: interpret/compile: opti-foobar
1.1 anton 6852: @end example
1.26 crook 6853:
1.23 crook 6854: @noindent
1.26 crook 6855: as an optimizing version of:
6856:
1.1 anton 6857: @example
1.26 crook 6858: : foobar
6859: foo bar ;
1.1 anton 6860: @end example
6861:
1.26 crook 6862: Unfortunately, this does not work correctly with @code{[compile]},
6863: because @code{[compile]} assumes that the compilation semantics of all
6864: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6865: opti-foobar} would compile compilation semantics, whereas
6866: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6867:
1.26 crook 6868: @cindex state-smart words (are a bad idea)
1.82 anton 6869: @anchor{state-smartness}
1.29 crook 6870: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6871: by @code{interpret/compile:} (words are state-smart if they check
6872: @code{STATE} during execution). E.g., they would try to code
6873: @code{foobar} like this:
1.1 anton 6874:
1.26 crook 6875: @example
6876: : foobar
6877: STATE @@
6878: IF ( compilation state )
6879: POSTPONE foo POSTPONE bar
6880: ELSE
6881: foo bar
6882: ENDIF ; immediate
6883: @end example
1.1 anton 6884:
1.26 crook 6885: Although this works if @code{foobar} is only processed by the text
6886: interpreter, it does not work in other contexts (like @code{'} or
6887: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6888: for a state-smart word, not for the interpretation semantics of the
6889: original @code{foobar}; when you execute this execution token (directly
6890: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6891: state, the result will not be what you expected (i.e., it will not
6892: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6893: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6894: M. Anton Ertl,
6895: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6896: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6897:
1.26 crook 6898: @cindex defining words with arbitrary semantics combinations
6899: It is also possible to write defining words that define words with
6900: arbitrary combinations of interpretation and compilation semantics. In
6901: general, they look like this:
1.1 anton 6902:
1.26 crook 6903: @example
6904: : def-word
6905: create-interpret/compile
1.29 crook 6906: @i{code1}
1.26 crook 6907: interpretation>
1.29 crook 6908: @i{code2}
1.26 crook 6909: <interpretation
6910: compilation>
1.29 crook 6911: @i{code3}
1.26 crook 6912: <compilation ;
6913: @end example
1.1 anton 6914:
1.29 crook 6915: For a @i{word} defined with @code{def-word}, the interpretation
6916: semantics are to push the address of the body of @i{word} and perform
6917: @i{code2}, and the compilation semantics are to push the address of
6918: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6919: can also be defined like this (except that the defined constants don't
6920: behave correctly when @code{[compile]}d):
1.1 anton 6921:
1.26 crook 6922: @example
6923: : constant ( n "name" -- )
6924: create-interpret/compile
6925: ,
6926: interpretation> ( -- n )
6927: @@
6928: <interpretation
6929: compilation> ( compilation. -- ; run-time. -- n )
6930: @@ postpone literal
6931: <compilation ;
6932: @end example
1.1 anton 6933:
1.44 crook 6934:
1.26 crook 6935: doc-create-interpret/compile
6936: doc-interpretation>
6937: doc-<interpretation
6938: doc-compilation>
6939: doc-<compilation
1.1 anton 6940:
1.44 crook 6941:
1.29 crook 6942: Words defined with @code{interpret/compile:} and
1.26 crook 6943: @code{create-interpret/compile} have an extended header structure that
6944: differs from other words; however, unless you try to access them with
6945: plain address arithmetic, you should not notice this. Words for
6946: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6947: @code{'} @i{word} @code{>body} also gives you the body of a word created
6948: with @code{create-interpret/compile}.
1.1 anton 6949:
1.44 crook 6950:
1.47 crook 6951: @c -------------------------------------------------------------
1.81 anton 6952: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6953: @section Tokens for Words
6954: @cindex tokens for words
6955:
6956: This section describes the creation and use of tokens that represent
6957: words.
6958:
1.71 anton 6959: @menu
6960: * Execution token:: represents execution/interpretation semantics
6961: * Compilation token:: represents compilation semantics
6962: * Name token:: represents named words
6963: @end menu
1.47 crook 6964:
1.71 anton 6965: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6966: @subsection Execution token
1.47 crook 6967:
6968: @cindex xt
6969: @cindex execution token
1.71 anton 6970: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6971: You can use @code{execute} to invoke this behaviour.
1.47 crook 6972:
1.71 anton 6973: @cindex tick (')
6974: You can use @code{'} to get an execution token that represents the
6975: interpretation semantics of a named word:
1.47 crook 6976:
6977: @example
1.97 anton 6978: 5 ' . ( n xt )
6979: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6980: @end example
1.47 crook 6981:
1.71 anton 6982: doc-'
6983:
6984: @code{'} parses at run-time; there is also a word @code{[']} that parses
6985: when it is compiled, and compiles the resulting XT:
6986:
6987: @example
6988: : foo ['] . execute ;
6989: 5 foo
6990: : bar ' execute ; \ by contrast,
6991: 5 bar . \ ' parses "." when bar executes
6992: @end example
6993:
6994: doc-[']
6995:
6996: If you want the execution token of @i{word}, write @code{['] @i{word}}
6997: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
6998: @code{'} and @code{[']} behave somewhat unusually by complaining about
6999: compile-only words (because these words have no interpretation
7000: semantics). You might get what you want by using @code{COMP' @i{word}
7001: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7002: token}).
7003:
1.116 anton 7004: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7005: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7006: for the only behaviour the word has (the execution semantics). For
1.116 anton 7007: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7008: would produce if the word was defined anonymously.
7009:
7010: @example
7011: :noname ." hello" ;
7012: execute
1.47 crook 7013: @end example
7014:
1.71 anton 7015: An XT occupies one cell and can be manipulated like any other cell.
7016:
1.47 crook 7017: @cindex code field address
7018: @cindex CFA
1.71 anton 7019: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7020: operations that produce or consume it). For old hands: In Gforth, the
7021: XT is implemented as a code field address (CFA).
7022:
7023: doc-execute
7024: doc-perform
7025:
7026: @node Compilation token, Name token, Execution token, Tokens for Words
7027: @subsection Compilation token
1.47 crook 7028:
7029: @cindex compilation token
1.71 anton 7030: @cindex CT (compilation token)
7031: Gforth represents the compilation semantics of a named word by a
1.47 crook 7032: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7033: @i{xt} is an execution token. The compilation semantics represented by
7034: the compilation token can be performed with @code{execute}, which
7035: consumes the whole compilation token, with an additional stack effect
7036: determined by the represented compilation semantics.
7037:
7038: At present, the @i{w} part of a compilation token is an execution token,
7039: and the @i{xt} part represents either @code{execute} or
7040: @code{compile,}@footnote{Depending upon the compilation semantics of the
7041: word. If the word has default compilation semantics, the @i{xt} will
7042: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7043: @i{xt} will represent @code{execute}.}. However, don't rely on that
7044: knowledge, unless necessary; future versions of Gforth may introduce
7045: unusual compilation tokens (e.g., a compilation token that represents
7046: the compilation semantics of a literal).
7047:
1.71 anton 7048: You can perform the compilation semantics represented by the compilation
7049: token with @code{execute}. You can compile the compilation semantics
7050: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7051: equivalent to @code{postpone @i{word}}.
7052:
7053: doc-[comp']
7054: doc-comp'
7055: doc-postpone,
7056:
7057: @node Name token, , Compilation token, Tokens for Words
7058: @subsection Name token
1.47 crook 7059:
7060: @cindex name token
1.116 anton 7061: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7062: token is an abstract data type that occurs as argument or result of the
7063: words below.
7064:
7065: @c !! put this elswhere?
1.47 crook 7066: @cindex name field address
7067: @cindex NFA
1.116 anton 7068: The closest thing to the nt in older Forth systems is the name field
7069: address (NFA), but there are significant differences: in older Forth
7070: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7071: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7072: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7073: is a link field in the structure identified by the name token, but
7074: searching usually uses a hash table external to these structures; the
7075: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7076: implemented as the address of that count field.
1.47 crook 7077:
7078: doc-find-name
1.116 anton 7079: doc-latest
7080: doc->name
1.47 crook 7081: doc-name>int
7082: doc-name?int
7083: doc-name>comp
7084: doc-name>string
1.109 anton 7085: doc-id.
7086: doc-.name
7087: doc-.id
1.47 crook 7088:
1.81 anton 7089: @c ----------------------------------------------------------
7090: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7091: @section Compiling words
7092: @cindex compiling words
7093: @cindex macros
7094:
7095: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7096: between compilation and run-time. E.g., you can run arbitrary code
7097: between defining words (or for computing data used by defining words
7098: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7099: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7100: running arbitrary code while compiling a colon definition (exception:
7101: you must not allot dictionary space).
7102:
7103: @menu
7104: * Literals:: Compiling data values
7105: * Macros:: Compiling words
7106: @end menu
7107:
7108: @node Literals, Macros, Compiling words, Compiling words
7109: @subsection Literals
7110: @cindex Literals
7111:
7112: The simplest and most frequent example is to compute a literal during
7113: compilation. E.g., the following definition prints an array of strings,
7114: one string per line:
7115:
7116: @example
7117: : .strings ( addr u -- ) \ gforth
7118: 2* cells bounds U+DO
7119: cr i 2@@ type
7120: 2 cells +LOOP ;
7121: @end example
1.81 anton 7122:
1.82 anton 7123: With a simple-minded compiler like Gforth's, this computes @code{2
7124: cells} on every loop iteration. You can compute this value once and for
7125: all at compile time and compile it into the definition like this:
7126:
7127: @example
7128: : .strings ( addr u -- ) \ gforth
7129: 2* cells bounds U+DO
7130: cr i 2@@ type
7131: [ 2 cells ] literal +LOOP ;
7132: @end example
7133:
7134: @code{[} switches the text interpreter to interpret state (you will get
7135: an @code{ok} prompt if you type this example interactively and insert a
7136: newline between @code{[} and @code{]}), so it performs the
7137: interpretation semantics of @code{2 cells}; this computes a number.
7138: @code{]} switches the text interpreter back into compile state. It then
7139: performs @code{Literal}'s compilation semantics, which are to compile
7140: this number into the current word. You can decompile the word with
7141: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7142:
1.82 anton 7143: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7144: *} in this way.
1.81 anton 7145:
1.82 anton 7146: doc-[
7147: doc-]
1.81 anton 7148: doc-literal
7149: doc-]L
1.82 anton 7150:
7151: There are also words for compiling other data types than single cells as
7152: literals:
7153:
1.81 anton 7154: doc-2literal
7155: doc-fliteral
1.82 anton 7156: doc-sliteral
7157:
7158: @cindex colon-sys, passing data across @code{:}
7159: @cindex @code{:}, passing data across
7160: You might be tempted to pass data from outside a colon definition to the
7161: inside on the data stack. This does not work, because @code{:} puhes a
7162: colon-sys, making stuff below unaccessible. E.g., this does not work:
7163:
7164: @example
7165: 5 : foo literal ; \ error: "unstructured"
7166: @end example
7167:
7168: Instead, you have to pass the value in some other way, e.g., through a
7169: variable:
7170:
7171: @example
7172: variable temp
7173: 5 temp !
7174: : foo [ temp @@ ] literal ;
7175: @end example
7176:
7177:
7178: @node Macros, , Literals, Compiling words
7179: @subsection Macros
7180: @cindex Macros
7181: @cindex compiling compilation semantics
7182:
7183: @code{Literal} and friends compile data values into the current
7184: definition. You can also write words that compile other words into the
7185: current definition. E.g.,
7186:
7187: @example
7188: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7189: POSTPONE + ;
7190:
7191: : foo ( n1 n2 -- n )
7192: [ compile-+ ] ;
7193: 1 2 foo .
7194: @end example
7195:
7196: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7197: What happens in this example? @code{Postpone} compiles the compilation
7198: semantics of @code{+} into @code{compile-+}; later the text interpreter
7199: executes @code{compile-+} and thus the compilation semantics of +, which
7200: compile (the execution semantics of) @code{+} into
7201: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7202: should only be executed in compile state, so this example is not
7203: guaranteed to work on all standard systems, but on any decent system it
7204: will work.}
7205:
7206: doc-postpone
7207: doc-[compile]
7208:
7209: Compiling words like @code{compile-+} are usually immediate (or similar)
7210: so you do not have to switch to interpret state to execute them;
7211: mopifying the last example accordingly produces:
7212:
7213: @example
7214: : [compile-+] ( compilation: --; interpretation: -- )
7215: \ compiled code: ( n1 n2 -- n )
7216: POSTPONE + ; immediate
7217:
7218: : foo ( n1 n2 -- n )
7219: [compile-+] ;
7220: 1 2 foo .
7221: @end example
7222:
7223: Immediate compiling words are similar to macros in other languages (in
7224: particular, Lisp). The important differences to macros in, e.g., C are:
7225:
7226: @itemize @bullet
7227:
7228: @item
7229: You use the same language for defining and processing macros, not a
7230: separate preprocessing language and processor.
7231:
7232: @item
7233: Consequently, the full power of Forth is available in macro definitions.
7234: E.g., you can perform arbitrarily complex computations, or generate
7235: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7236: Tutorial}). This power is very useful when writing a parser generators
7237: or other code-generating software.
7238:
7239: @item
7240: Macros defined using @code{postpone} etc. deal with the language at a
7241: higher level than strings; name binding happens at macro definition
7242: time, so you can avoid the pitfalls of name collisions that can happen
7243: in C macros. Of course, Forth is a liberal language and also allows to
7244: shoot yourself in the foot with text-interpreted macros like
7245:
7246: @example
7247: : [compile-+] s" +" evaluate ; immediate
7248: @end example
7249:
7250: Apart from binding the name at macro use time, using @code{evaluate}
7251: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7252: @end itemize
7253:
7254: You may want the macro to compile a number into a word. The word to do
7255: it is @code{literal}, but you have to @code{postpone} it, so its
7256: compilation semantics take effect when the macro is executed, not when
7257: it is compiled:
7258:
7259: @example
7260: : [compile-5] ( -- ) \ compiled code: ( -- n )
7261: 5 POSTPONE literal ; immediate
7262:
7263: : foo [compile-5] ;
7264: foo .
7265: @end example
7266:
7267: You may want to pass parameters to a macro, that the macro should
7268: compile into the current definition. If the parameter is a number, then
7269: you can use @code{postpone literal} (similar for other values).
7270:
7271: If you want to pass a word that is to be compiled, the usual way is to
7272: pass an execution token and @code{compile,} it:
7273:
7274: @example
7275: : twice1 ( xt -- ) \ compiled code: ... -- ...
7276: dup compile, compile, ;
7277:
7278: : 2+ ( n1 -- n2 )
7279: [ ' 1+ twice1 ] ;
7280: @end example
7281:
7282: doc-compile,
7283:
7284: An alternative available in Gforth, that allows you to pass compile-only
7285: words as parameters is to use the compilation token (@pxref{Compilation
7286: token}). The same example in this technique:
7287:
7288: @example
7289: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7290: 2dup 2>r execute 2r> execute ;
7291:
7292: : 2+ ( n1 -- n2 )
7293: [ comp' 1+ twice ] ;
7294: @end example
7295:
7296: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7297: works even if the executed compilation semantics has an effect on the
7298: data stack.
7299:
7300: You can also define complete definitions with these words; this provides
7301: an alternative to using @code{does>} (@pxref{User-defined Defining
7302: Words}). E.g., instead of
7303:
7304: @example
7305: : curry+ ( n1 "name" -- )
7306: CREATE ,
7307: DOES> ( n2 -- n1+n2 )
7308: @@ + ;
7309: @end example
7310:
7311: you could define
7312:
7313: @example
7314: : curry+ ( n1 "name" -- )
7315: \ name execution: ( n2 -- n1+n2 )
7316: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7317:
1.82 anton 7318: -3 curry+ 3-
7319: see 3-
7320: @end example
1.81 anton 7321:
1.82 anton 7322: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7323: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7324:
1.82 anton 7325: This way of writing defining words is sometimes more, sometimes less
7326: convenient than using @code{does>} (@pxref{Advanced does> usage
7327: example}). One advantage of this method is that it can be optimized
7328: better, because the compiler knows that the value compiled with
7329: @code{literal} is fixed, whereas the data associated with a
7330: @code{create}d word can be changed.
1.47 crook 7331:
1.26 crook 7332: @c ----------------------------------------------------------
1.111 anton 7333: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7334: @section The Text Interpreter
7335: @cindex interpreter - outer
7336: @cindex text interpreter
7337: @cindex outer interpreter
1.1 anton 7338:
1.34 anton 7339: @c Should we really describe all these ugly details? IMO the text
7340: @c interpreter should be much cleaner, but that may not be possible within
7341: @c ANS Forth. - anton
1.44 crook 7342: @c nac-> I wanted to explain how it works to show how you can exploit
7343: @c it in your own programs. When I was writing a cross-compiler, figuring out
7344: @c some of these gory details was very helpful to me. None of the textbooks
7345: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7346: @c seems to positively avoid going into too much detail for some of
7347: @c the internals.
1.34 anton 7348:
1.71 anton 7349: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7350: @c it is; for the ugly details, I would prefer another place. I wonder
7351: @c whether we should have a chapter before "Words" that describes some
7352: @c basic concepts referred to in words, and a chapter after "Words" that
7353: @c describes implementation details.
7354:
1.29 crook 7355: The text interpreter@footnote{This is an expanded version of the
7356: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7357: that processes input from the current input device. It is also called
7358: the outer interpreter, in contrast to the inner interpreter
7359: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7360: implementations.
1.27 crook 7361:
1.29 crook 7362: @cindex interpret state
7363: @cindex compile state
7364: The text interpreter operates in one of two states: @dfn{interpret
7365: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7366: aptly-named variable @code{state}.
1.29 crook 7367:
7368: This section starts by describing how the text interpreter behaves when
7369: it is in interpret state, processing input from the user input device --
7370: the keyboard. This is the mode that a Forth system is in after it starts
7371: up.
7372:
7373: @cindex input buffer
7374: @cindex terminal input buffer
7375: The text interpreter works from an area of memory called the @dfn{input
7376: buffer}@footnote{When the text interpreter is processing input from the
7377: keyboard, this area of memory is called the @dfn{terminal input buffer}
7378: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7379: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7380: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7381: leading spaces (called @dfn{delimiters}) then parses a string (a
7382: sequence of non-space characters) until it reaches either a space
7383: character or the end of the buffer. Having parsed a string, it makes two
7384: attempts to process it:
1.27 crook 7385:
1.29 crook 7386: @cindex dictionary
1.27 crook 7387: @itemize @bullet
7388: @item
1.29 crook 7389: It looks for the string in a @dfn{dictionary} of definitions. If the
7390: string is found, the string names a @dfn{definition} (also known as a
7391: @dfn{word}) and the dictionary search returns information that allows
7392: the text interpreter to perform the word's @dfn{interpretation
7393: semantics}. In most cases, this simply means that the word will be
7394: executed.
1.27 crook 7395: @item
7396: If the string is not found in the dictionary, the text interpreter
1.29 crook 7397: attempts to treat it as a number, using the rules described in
7398: @ref{Number Conversion}. If the string represents a legal number in the
7399: current radix, the number is pushed onto a parameter stack (the data
7400: stack for integers, the floating-point stack for floating-point
7401: numbers).
7402: @end itemize
7403:
7404: If both attempts fail, or if the word is found in the dictionary but has
7405: no interpretation semantics@footnote{This happens if the word was
7406: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7407: remainder of the input buffer, issues an error message and waits for
7408: more input. If one of the attempts succeeds, the text interpreter
7409: repeats the parsing process until the whole of the input buffer has been
7410: processed, at which point it prints the status message ``@code{ ok}''
7411: and waits for more input.
7412:
1.71 anton 7413: @c anton: this should be in the input stream subsection (or below it)
7414:
1.29 crook 7415: @cindex parse area
7416: The text interpreter keeps track of its position in the input buffer by
7417: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7418: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7419: of the input buffer. The region from offset @code{>IN @@} to the end of
7420: the input buffer is called the @dfn{parse area}@footnote{In other words,
7421: the text interpreter processes the contents of the input buffer by
7422: parsing strings from the parse area until the parse area is empty.}.
7423: This example shows how @code{>IN} changes as the text interpreter parses
7424: the input buffer:
7425:
7426: @example
7427: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7428: CR ." ->" TYPE ." <-" ; IMMEDIATE
7429:
7430: 1 2 3 remaining + remaining .
7431:
7432: : foo 1 2 3 remaining SWAP remaining ;
7433: @end example
7434:
7435: @noindent
7436: The result is:
7437:
7438: @example
7439: ->+ remaining .<-
7440: ->.<-5 ok
7441:
7442: ->SWAP remaining ;-<
7443: ->;<- ok
7444: @end example
7445:
7446: @cindex parsing words
7447: The value of @code{>IN} can also be modified by a word in the input
7448: buffer that is executed by the text interpreter. This means that a word
7449: can ``trick'' the text interpreter into either skipping a section of the
7450: input buffer@footnote{This is how parsing words work.} or into parsing a
7451: section twice. For example:
1.27 crook 7452:
1.29 crook 7453: @example
1.71 anton 7454: : lat ." <<foo>>" ;
7455: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7456: @end example
7457:
7458: @noindent
7459: When @code{flat} is executed, this output is produced@footnote{Exercise
7460: for the reader: what would happen if the @code{3} were replaced with
7461: @code{4}?}:
7462:
7463: @example
1.71 anton 7464: <<bar>><<foo>>
1.29 crook 7465: @end example
7466:
1.71 anton 7467: This technique can be used to work around some of the interoperability
7468: problems of parsing words. Of course, it's better to avoid parsing
7469: words where possible.
7470:
1.29 crook 7471: @noindent
7472: Two important notes about the behaviour of the text interpreter:
1.27 crook 7473:
7474: @itemize @bullet
7475: @item
7476: It processes each input string to completion before parsing additional
1.29 crook 7477: characters from the input buffer.
7478: @item
7479: It treats the input buffer as a read-only region (and so must your code).
7480: @end itemize
7481:
7482: @noindent
7483: When the text interpreter is in compile state, its behaviour changes in
7484: these ways:
7485:
7486: @itemize @bullet
7487: @item
7488: If a parsed string is found in the dictionary, the text interpreter will
7489: perform the word's @dfn{compilation semantics}. In most cases, this
7490: simply means that the execution semantics of the word will be appended
7491: to the current definition.
1.27 crook 7492: @item
1.29 crook 7493: When a number is encountered, it is compiled into the current definition
7494: (as a literal) rather than being pushed onto a parameter stack.
7495: @item
7496: If an error occurs, @code{state} is modified to put the text interpreter
7497: back into interpret state.
7498: @item
7499: Each time a line is entered from the keyboard, Gforth prints
7500: ``@code{ compiled}'' rather than `` @code{ok}''.
7501: @end itemize
7502:
7503: @cindex text interpreter - input sources
7504: When the text interpreter is using an input device other than the
7505: keyboard, its behaviour changes in these ways:
7506:
7507: @itemize @bullet
7508: @item
7509: When the parse area is empty, the text interpreter attempts to refill
7510: the input buffer from the input source. When the input source is
1.71 anton 7511: exhausted, the input source is set back to the previous input source.
1.29 crook 7512: @item
7513: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7514: time the parse area is emptied.
7515: @item
7516: If an error occurs, the input source is set back to the user input
7517: device.
1.27 crook 7518: @end itemize
1.21 crook 7519:
1.49 anton 7520: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7521:
1.26 crook 7522: doc->in
1.27 crook 7523: doc-source
7524:
1.26 crook 7525: doc-tib
7526: doc-#tib
1.1 anton 7527:
1.44 crook 7528:
1.26 crook 7529: @menu
1.67 anton 7530: * Input Sources::
7531: * Number Conversion::
7532: * Interpret/Compile states::
7533: * Interpreter Directives::
1.26 crook 7534: @end menu
1.1 anton 7535:
1.29 crook 7536: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7537: @subsection Input Sources
7538: @cindex input sources
7539: @cindex text interpreter - input sources
7540:
1.44 crook 7541: By default, the text interpreter processes input from the user input
1.29 crook 7542: device (the keyboard) when Forth starts up. The text interpreter can
7543: process input from any of these sources:
7544:
7545: @itemize @bullet
7546: @item
7547: The user input device -- the keyboard.
7548: @item
7549: A file, using the words described in @ref{Forth source files}.
7550: @item
7551: A block, using the words described in @ref{Blocks}.
7552: @item
7553: A text string, using @code{evaluate}.
7554: @end itemize
7555:
7556: A program can identify the current input device from the values of
7557: @code{source-id} and @code{blk}.
7558:
1.44 crook 7559:
1.29 crook 7560: doc-source-id
7561: doc-blk
7562:
7563: doc-save-input
7564: doc-restore-input
7565:
7566: doc-evaluate
1.111 anton 7567: doc-query
1.1 anton 7568:
1.29 crook 7569:
1.44 crook 7570:
1.29 crook 7571: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7572: @subsection Number Conversion
7573: @cindex number conversion
7574: @cindex double-cell numbers, input format
7575: @cindex input format for double-cell numbers
7576: @cindex single-cell numbers, input format
7577: @cindex input format for single-cell numbers
7578: @cindex floating-point numbers, input format
7579: @cindex input format for floating-point numbers
1.1 anton 7580:
1.29 crook 7581: This section describes the rules that the text interpreter uses when it
7582: tries to convert a string into a number.
1.1 anton 7583:
1.26 crook 7584: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7585: number base@footnote{For example, 0-9 when the number base is decimal or
7586: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7587:
1.26 crook 7588: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7589:
1.29 crook 7590: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7591: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7592:
1.26 crook 7593: Let * represent any number of instances of the previous character
7594: (including none).
1.1 anton 7595:
1.26 crook 7596: Let any other character represent itself.
1.1 anton 7597:
1.29 crook 7598: @noindent
1.26 crook 7599: Now, the conversion rules are:
1.21 crook 7600:
1.26 crook 7601: @itemize @bullet
7602: @item
7603: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7604: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7605: @item
7606: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7607: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7608: arithmetic. Examples are -45 -5681 -0
7609: @item
7610: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7611: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7612: (all three of these represent the same number).
1.26 crook 7613: @item
7614: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7615: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7616: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7617: -34.65 (all three of these represent the same number).
1.26 crook 7618: @item
1.29 crook 7619: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7620: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7621: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7622: number) +12.E-4
1.26 crook 7623: @end itemize
1.1 anton 7624:
1.26 crook 7625: By default, the number base used for integer number conversion is given
1.35 anton 7626: by the contents of the variable @code{base}. Note that a lot of
7627: confusion can result from unexpected values of @code{base}. If you
7628: change @code{base} anywhere, make sure to save the old value and restore
7629: it afterwards. In general I recommend keeping @code{base} decimal, and
7630: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7631:
1.29 crook 7632: doc-dpl
1.26 crook 7633: doc-base
7634: doc-hex
7635: doc-decimal
1.1 anton 7636:
1.26 crook 7637: @cindex '-prefix for character strings
7638: @cindex &-prefix for decimal numbers
1.133 anton 7639: @cindex #-prefix for decimal numbers
1.26 crook 7640: @cindex %-prefix for binary numbers
7641: @cindex $-prefix for hexadecimal numbers
1.133 anton 7642: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7643: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7644: prefix@footnote{Some Forth implementations provide a similar scheme by
7645: implementing @code{$} etc. as parsing words that process the subsequent
7646: number in the input stream and push it onto the stack. For example, see
7647: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7648: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7649: is required between the prefix and the number.} before the first digit
1.133 anton 7650: of an (integer) number. The following prefixes are supported:
1.1 anton 7651:
1.26 crook 7652: @itemize @bullet
7653: @item
1.35 anton 7654: @code{&} -- decimal
1.26 crook 7655: @item
1.133 anton 7656: @code{#} -- decimal
7657: @item
1.35 anton 7658: @code{%} -- binary
1.26 crook 7659: @item
1.35 anton 7660: @code{$} -- hexadecimal
1.26 crook 7661: @item
1.133 anton 7662: @code{0x} -- hexadecimal, if base<33.
7663: @item
7664: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7665: optional @code{'} may be present after the character.
1.26 crook 7666: @end itemize
1.1 anton 7667:
1.26 crook 7668: Here are some examples, with the equivalent decimal number shown after
7669: in braces:
1.1 anton 7670:
1.26 crook 7671: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7672: 'A (65),
7673: -'a' (-97),
1.26 crook 7674: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7675:
1.26 crook 7676: @cindex number conversion - traps for the unwary
1.29 crook 7677: @noindent
1.26 crook 7678: Number conversion has a number of traps for the unwary:
1.1 anton 7679:
1.26 crook 7680: @itemize @bullet
7681: @item
7682: You cannot determine the current number base using the code sequence
1.35 anton 7683: @code{base @@ .} -- the number base is always 10 in the current number
7684: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7685: @item
7686: If the number base is set to a value greater than 14 (for example,
7687: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7688: it to be intepreted as either a single-precision integer or a
7689: floating-point number (Gforth treats it as an integer). The ambiguity
7690: can be resolved by explicitly stating the sign of the mantissa and/or
7691: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7692: ambiguity arises; either representation will be treated as a
7693: floating-point number.
7694: @item
1.29 crook 7695: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7696: It is used to specify file types.
7697: @item
1.72 anton 7698: ANS Forth requires the @code{.} of a double-precision number to be the
7699: final character in the string. Gforth allows the @code{.} to be
7700: anywhere after the first digit.
1.26 crook 7701: @item
7702: The number conversion process does not check for overflow.
7703: @item
1.72 anton 7704: In an ANS Forth program @code{base} is required to be decimal when
7705: converting floating-point numbers. In Gforth, number conversion to
7706: floating-point numbers always uses base &10, irrespective of the value
7707: of @code{base}.
1.26 crook 7708: @end itemize
1.1 anton 7709:
1.49 anton 7710: You can read numbers into your programs with the words described in
7711: @ref{Input}.
1.1 anton 7712:
1.82 anton 7713: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7714: @subsection Interpret/Compile states
7715: @cindex Interpret/Compile states
1.1 anton 7716:
1.29 crook 7717: A standard program is not permitted to change @code{state}
7718: explicitly. However, it can change @code{state} implicitly, using the
7719: words @code{[} and @code{]}. When @code{[} is executed it switches
7720: @code{state} to interpret state, and therefore the text interpreter
7721: starts interpreting. When @code{]} is executed it switches @code{state}
7722: to compile state and therefore the text interpreter starts
1.44 crook 7723: compiling. The most common usage for these words is for switching into
7724: interpret state and back from within a colon definition; this technique
1.49 anton 7725: can be used to compile a literal (for an example, @pxref{Literals}) or
7726: for conditional compilation (for an example, @pxref{Interpreter
7727: Directives}).
1.44 crook 7728:
1.35 anton 7729:
7730: @c This is a bad example: It's non-standard, and it's not necessary.
7731: @c However, I can't think of a good example for switching into compile
7732: @c state when there is no current word (@code{state}-smart words are not a
7733: @c good reason). So maybe we should use an example for switching into
7734: @c interpret @code{state} in a colon def. - anton
1.44 crook 7735: @c nac-> I agree. I started out by putting in the example, then realised
7736: @c that it was non-ANS, so wrote more words around it. I hope this
7737: @c re-written version is acceptable to you. I do want to keep the example
7738: @c as it is helpful for showing what is and what is not portable, particularly
7739: @c where it outlaws a style in common use.
7740:
1.72 anton 7741: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7742: @c that, we can also show what's not. In any case, I have written a
7743: @c section Compiling Words which also deals with [ ].
1.35 anton 7744:
1.95 anton 7745: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7746:
1.95 anton 7747: @c @code{[} and @code{]} also give you the ability to switch into compile
7748: @c state and back, but we cannot think of any useful Standard application
7749: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7750:
7751: @c @example
7752: @c : AA ." this is A" ;
7753: @c : BB ." this is B" ;
7754: @c : CC ." this is C" ;
7755:
7756: @c create table ] aa bb cc [
7757:
7758: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7759: @c cells table + @@ execute ;
7760: @c @end example
7761:
7762: @c This example builds a jump table; @code{0 go} will display ``@code{this
7763: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7764: @c defining @code{table} like this:
7765:
7766: @c @example
7767: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7768: @c @end example
7769:
7770: @c The problem with this code is that the definition of @code{table} is not
7771: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7772: @c @i{may} work on systems where code space and data space co-incide, the
7773: @c Standard only allows data space to be assigned for a @code{CREATE}d
7774: @c word. In addition, the Standard only allows @code{@@} to access data
7775: @c space, whilst this example is using it to access code space. The only
7776: @c portable, Standard way to build this table is to build it in data space,
7777: @c like this:
7778:
7779: @c @example
7780: @c create table ' aa , ' bb , ' cc ,
7781: @c @end example
1.29 crook 7782:
1.95 anton 7783: @c doc-state
1.44 crook 7784:
1.29 crook 7785:
1.82 anton 7786: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7787: @subsection Interpreter Directives
7788: @cindex interpreter directives
1.72 anton 7789: @cindex conditional compilation
1.1 anton 7790:
1.29 crook 7791: These words are usually used in interpret state; typically to control
7792: which parts of a source file are processed by the text
1.26 crook 7793: interpreter. There are only a few ANS Forth Standard words, but Gforth
7794: supplements these with a rich set of immediate control structure words
7795: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7796: used in compile state (@pxref{Control Structures}). Typical usages:
7797:
7798: @example
1.72 anton 7799: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7800: .
7801: .
1.72 anton 7802: HAVE-ASSEMBLER [IF]
1.29 crook 7803: : ASSEMBLER-FEATURE
7804: ...
7805: ;
7806: [ENDIF]
7807: .
7808: .
7809: : SEE
7810: ... \ general-purpose SEE code
1.72 anton 7811: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7812: ... \ assembler-specific SEE code
7813: [ [ENDIF] ]
7814: ;
7815: @end example
1.1 anton 7816:
1.44 crook 7817:
1.26 crook 7818: doc-[IF]
7819: doc-[ELSE]
7820: doc-[THEN]
7821: doc-[ENDIF]
1.1 anton 7822:
1.26 crook 7823: doc-[IFDEF]
7824: doc-[IFUNDEF]
1.1 anton 7825:
1.26 crook 7826: doc-[?DO]
7827: doc-[DO]
7828: doc-[FOR]
7829: doc-[LOOP]
7830: doc-[+LOOP]
7831: doc-[NEXT]
1.1 anton 7832:
1.26 crook 7833: doc-[BEGIN]
7834: doc-[UNTIL]
7835: doc-[AGAIN]
7836: doc-[WHILE]
7837: doc-[REPEAT]
1.1 anton 7838:
1.27 crook 7839:
1.26 crook 7840: @c -------------------------------------------------------------
1.111 anton 7841: @node The Input Stream, Word Lists, The Text Interpreter, Words
7842: @section The Input Stream
7843: @cindex input stream
7844:
7845: @c !! integrate this better with the "Text Interpreter" section
7846: The text interpreter reads from the input stream, which can come from
7847: several sources (@pxref{Input Sources}). Some words, in particular
7848: defining words, but also words like @code{'}, read parameters from the
7849: input stream instead of from the stack.
7850:
7851: Such words are called parsing words, because they parse the input
7852: stream. Parsing words are hard to use in other words, because it is
7853: hard to pass program-generated parameters through the input stream.
7854: They also usually have an unintuitive combination of interpretation and
7855: compilation semantics when implemented naively, leading to various
7856: approaches that try to produce a more intuitive behaviour
7857: (@pxref{Combined words}).
7858:
7859: It should be obvious by now that parsing words are a bad idea. If you
7860: want to implement a parsing word for convenience, also provide a factor
7861: of the word that does not parse, but takes the parameters on the stack.
7862: To implement the parsing word on top if it, you can use the following
7863: words:
7864:
7865: @c anton: these belong in the input stream section
7866: doc-parse
1.138 anton 7867: doc-parse-name
1.111 anton 7868: doc-parse-word
7869: doc-name
7870: doc-word
7871: doc-\"-parse
7872: doc-refill
7873:
7874: Conversely, if you have the bad luck (or lack of foresight) to have to
7875: deal with parsing words without having such factors, how do you pass a
7876: string that is not in the input stream to it?
7877:
7878: doc-execute-parsing
7879:
1.146 anton 7880: A definition of this word in ANS Forth is provided in
7881: @file{compat/execute-parsing.fs}.
7882:
1.111 anton 7883: If you want to run a parsing word on a file, the following word should
7884: help:
7885:
7886: doc-execute-parsing-file
7887:
7888: @c -------------------------------------------------------------
7889: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7890: @section Word Lists
7891: @cindex word lists
1.32 anton 7892: @cindex header space
1.1 anton 7893:
1.36 anton 7894: A wordlist is a list of named words; you can add new words and look up
7895: words by name (and you can remove words in a restricted way with
7896: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7897:
7898: @cindex search order stack
7899: The text interpreter searches the wordlists present in the search order
7900: (a stack of wordlists), from the top to the bottom. Within each
7901: wordlist, the search starts conceptually at the newest word; i.e., if
7902: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7903:
1.26 crook 7904: @cindex compilation word list
1.36 anton 7905: New words are added to the @dfn{compilation wordlist} (aka current
7906: wordlist).
1.1 anton 7907:
1.36 anton 7908: @cindex wid
7909: A word list is identified by a cell-sized word list identifier (@i{wid})
7910: in much the same way as a file is identified by a file handle. The
7911: numerical value of the wid has no (portable) meaning, and might change
7912: from session to session.
1.1 anton 7913:
1.29 crook 7914: The ANS Forth ``Search order'' word set is intended to provide a set of
7915: low-level tools that allow various different schemes to be
1.74 anton 7916: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7917: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7918: Forth.
1.1 anton 7919:
1.27 crook 7920: @comment TODO: locals section refers to here, saying that every word list (aka
7921: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7922: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7923:
1.45 crook 7924: @comment TODO: document markers, reveal, tables, mappedwordlist
7925:
7926: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7927: @comment word from the source files, rather than some alias.
1.44 crook 7928:
1.26 crook 7929: doc-forth-wordlist
7930: doc-definitions
7931: doc-get-current
7932: doc-set-current
7933: doc-get-order
1.45 crook 7934: doc---gforthman-set-order
1.26 crook 7935: doc-wordlist
1.30 anton 7936: doc-table
1.79 anton 7937: doc->order
1.36 anton 7938: doc-previous
1.26 crook 7939: doc-also
1.45 crook 7940: doc---gforthman-forth
1.26 crook 7941: doc-only
1.45 crook 7942: doc---gforthman-order
1.15 anton 7943:
1.26 crook 7944: doc-find
7945: doc-search-wordlist
1.15 anton 7946:
1.26 crook 7947: doc-words
7948: doc-vlist
1.44 crook 7949: @c doc-words-deferred
1.1 anton 7950:
1.74 anton 7951: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7952: doc-root
7953: doc-vocabulary
7954: doc-seal
7955: doc-vocs
7956: doc-current
7957: doc-context
1.1 anton 7958:
1.44 crook 7959:
1.26 crook 7960: @menu
1.75 anton 7961: * Vocabularies::
1.67 anton 7962: * Why use word lists?::
1.75 anton 7963: * Word list example::
1.26 crook 7964: @end menu
7965:
1.75 anton 7966: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7967: @subsection Vocabularies
7968: @cindex Vocabularies, detailed explanation
7969:
7970: Here is an example of creating and using a new wordlist using ANS
7971: Forth words:
7972:
7973: @example
7974: wordlist constant my-new-words-wordlist
7975: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7976:
7977: \ add it to the search order
7978: also my-new-words
7979:
7980: \ alternatively, add it to the search order and make it
7981: \ the compilation word list
7982: also my-new-words definitions
7983: \ type "order" to see the problem
7984: @end example
7985:
7986: The problem with this example is that @code{order} has no way to
7987: associate the name @code{my-new-words} with the wid of the word list (in
7988: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7989: that has no associated name). There is no Standard way of associating a
7990: name with a wid.
7991:
7992: In Gforth, this example can be re-coded using @code{vocabulary}, which
7993: associates a name with a wid:
7994:
7995: @example
7996: vocabulary my-new-words
7997:
7998: \ add it to the search order
7999: also my-new-words
8000:
8001: \ alternatively, add it to the search order and make it
8002: \ the compilation word list
8003: my-new-words definitions
8004: \ type "order" to see that the problem is solved
8005: @end example
8006:
8007:
8008: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8009: @subsection Why use word lists?
8010: @cindex word lists - why use them?
8011:
1.74 anton 8012: Here are some reasons why people use wordlists:
1.26 crook 8013:
8014: @itemize @bullet
1.74 anton 8015:
8016: @c anton: Gforth's hashing implementation makes the search speed
8017: @c independent from the number of words. But it is linear with the number
8018: @c of wordlists that have to be searched, so in effect using more wordlists
8019: @c actually slows down compilation.
8020:
8021: @c @item
8022: @c To improve compilation speed by reducing the number of header space
8023: @c entries that must be searched. This is achieved by creating a new
8024: @c word list that contains all of the definitions that are used in the
8025: @c definition of a Forth system but which would not usually be used by
8026: @c programs running on that system. That word list would be on the search
8027: @c list when the Forth system was compiled but would be removed from the
8028: @c search list for normal operation. This can be a useful technique for
8029: @c low-performance systems (for example, 8-bit processors in embedded
8030: @c systems) but is unlikely to be necessary in high-performance desktop
8031: @c systems.
8032:
1.26 crook 8033: @item
8034: To prevent a set of words from being used outside the context in which
8035: they are valid. Two classic examples of this are an integrated editor
8036: (all of the edit commands are defined in a separate word list; the
8037: search order is set to the editor word list when the editor is invoked;
8038: the old search order is restored when the editor is terminated) and an
8039: integrated assembler (the op-codes for the machine are defined in a
8040: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8041:
8042: @item
8043: To organize the words of an application or library into a user-visible
8044: set (in @code{forth-wordlist} or some other common wordlist) and a set
8045: of helper words used just for the implementation (hidden in a separate
1.75 anton 8046: wordlist). This keeps @code{words}' output smaller, separates
8047: implementation and interface, and reduces the chance of name conflicts
8048: within the common wordlist.
1.74 anton 8049:
1.26 crook 8050: @item
8051: To prevent a name-space clash between multiple definitions with the same
8052: name. For example, when building a cross-compiler you might have a word
8053: @code{IF} that generates conditional code for your target system. By
8054: placing this definition in a different word list you can control whether
8055: the host system's @code{IF} or the target system's @code{IF} get used in
8056: any particular context by controlling the order of the word lists on the
8057: search order stack.
1.74 anton 8058:
1.26 crook 8059: @end itemize
1.1 anton 8060:
1.74 anton 8061: The downsides of using wordlists are:
8062:
8063: @itemize
8064:
8065: @item
8066: Debugging becomes more cumbersome.
8067:
8068: @item
8069: Name conflicts worked around with wordlists are still there, and you
8070: have to arrange the search order carefully to get the desired results;
8071: if you forget to do that, you get hard-to-find errors (as in any case
8072: where you read the code differently from the compiler; @code{see} can
1.75 anton 8073: help seeing which of several possible words the name resolves to in such
8074: cases). @code{See} displays just the name of the words, not what
8075: wordlist they belong to, so it might be misleading. Using unique names
8076: is a better approach to avoid name conflicts.
1.74 anton 8077:
8078: @item
8079: You have to explicitly undo any changes to the search order. In many
8080: cases it would be more convenient if this happened implicitly. Gforth
8081: currently does not provide such a feature, but it may do so in the
8082: future.
8083: @end itemize
8084:
8085:
1.75 anton 8086: @node Word list example, , Why use word lists?, Word Lists
8087: @subsection Word list example
8088: @cindex word lists - example
1.1 anton 8089:
1.74 anton 8090: The following example is from the
8091: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8092: garbage collector} and uses wordlists to separate public words from
8093: helper words:
8094:
8095: @example
8096: get-current ( wid )
8097: vocabulary garbage-collector also garbage-collector definitions
8098: ... \ define helper words
8099: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8100: ... \ define the public (i.e., API) words
8101: \ they can refer to the helper words
8102: previous \ restore original search order (helper words become invisible)
8103: @end example
8104:
1.26 crook 8105: @c -------------------------------------------------------------
8106: @node Environmental Queries, Files, Word Lists, Words
8107: @section Environmental Queries
8108: @cindex environmental queries
1.21 crook 8109:
1.26 crook 8110: ANS Forth introduced the idea of ``environmental queries'' as a way
8111: for a program running on a system to determine certain characteristics of the system.
8112: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8113:
1.32 anton 8114: The Standard requires that the header space used for environmental queries
8115: be distinct from the header space used for definitions.
1.21 crook 8116:
1.26 crook 8117: Typically, environmental queries are supported by creating a set of
1.29 crook 8118: definitions in a word list that is @i{only} used during environmental
1.26 crook 8119: queries; that is what Gforth does. There is no Standard way of adding
8120: definitions to the set of recognised environmental queries, but any
8121: implementation that supports the loading of optional word sets must have
8122: some mechanism for doing this (after loading the word set, the
8123: associated environmental query string must return @code{true}). In
8124: Gforth, the word list used to honour environmental queries can be
8125: manipulated just like any other word list.
1.21 crook 8126:
1.44 crook 8127:
1.26 crook 8128: doc-environment?
8129: doc-environment-wordlist
1.21 crook 8130:
1.26 crook 8131: doc-gforth
8132: doc-os-class
1.21 crook 8133:
1.44 crook 8134:
1.26 crook 8135: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8136: returning two items on the stack, querying it using @code{environment?}
8137: will return an additional item; the @code{true} flag that shows that the
8138: string was recognised.
1.21 crook 8139:
1.26 crook 8140: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8141:
1.26 crook 8142: Here are some examples of using environmental queries:
1.21 crook 8143:
1.26 crook 8144: @example
8145: s" address-unit-bits" environment? 0=
8146: [IF]
8147: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8148: [ELSE]
8149: drop \ ensure balanced stack effect
1.26 crook 8150: [THEN]
1.21 crook 8151:
1.75 anton 8152: \ this might occur in the prelude of a standard program that uses THROW
8153: s" exception" environment? [IF]
8154: 0= [IF]
8155: : throw abort" exception thrown" ;
8156: [THEN]
8157: [ELSE] \ we don't know, so make sure
8158: : throw abort" exception thrown" ;
8159: [THEN]
1.21 crook 8160:
1.26 crook 8161: s" gforth" environment? [IF] .( Gforth version ) TYPE
8162: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8163:
8164: \ a program using v*
8165: s" gforth" environment? [IF]
8166: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8167: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8168: >r swap 2swap swap 0e r> 0 ?DO
8169: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8170: LOOP
8171: 2drop 2drop ;
8172: [THEN]
8173: [ELSE] \
8174: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8175: ...
8176: [THEN]
1.26 crook 8177: @end example
1.21 crook 8178:
1.26 crook 8179: Here is an example of adding a definition to the environment word list:
1.21 crook 8180:
1.26 crook 8181: @example
8182: get-current environment-wordlist set-current
8183: true constant block
8184: true constant block-ext
8185: set-current
8186: @end example
1.21 crook 8187:
1.26 crook 8188: You can see what definitions are in the environment word list like this:
1.21 crook 8189:
1.26 crook 8190: @example
1.79 anton 8191: environment-wordlist >order words previous
1.26 crook 8192: @end example
1.21 crook 8193:
8194:
1.26 crook 8195: @c -------------------------------------------------------------
8196: @node Files, Blocks, Environmental Queries, Words
8197: @section Files
1.28 crook 8198: @cindex files
8199: @cindex I/O - file-handling
1.21 crook 8200:
1.26 crook 8201: Gforth provides facilities for accessing files that are stored in the
8202: host operating system's file-system. Files that are processed by Gforth
8203: can be divided into two categories:
1.21 crook 8204:
1.23 crook 8205: @itemize @bullet
8206: @item
1.29 crook 8207: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8208: @item
1.29 crook 8209: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8210: @end itemize
8211:
8212: @menu
1.48 anton 8213: * Forth source files::
8214: * General files::
8215: * Search Paths::
1.26 crook 8216: @end menu
8217:
8218: @c -------------------------------------------------------------
8219: @node Forth source files, General files, Files, Files
8220: @subsection Forth source files
8221: @cindex including files
8222: @cindex Forth source files
1.21 crook 8223:
1.26 crook 8224: The simplest way to interpret the contents of a file is to use one of
8225: these two formats:
1.21 crook 8226:
1.26 crook 8227: @example
8228: include mysource.fs
8229: s" mysource.fs" included
8230: @end example
1.21 crook 8231:
1.75 anton 8232: You usually want to include a file only if it is not included already
1.26 crook 8233: (by, say, another source file). In that case, you can use one of these
1.45 crook 8234: three formats:
1.21 crook 8235:
1.26 crook 8236: @example
8237: require mysource.fs
8238: needs mysource.fs
8239: s" mysource.fs" required
8240: @end example
1.21 crook 8241:
1.26 crook 8242: @cindex stack effect of included files
8243: @cindex including files, stack effect
1.45 crook 8244: It is good practice to write your source files such that interpreting them
8245: does not change the stack. Source files designed in this way can be used with
1.26 crook 8246: @code{required} and friends without complications. For example:
1.21 crook 8247:
1.26 crook 8248: @example
1.75 anton 8249: 1024 require foo.fs drop
1.26 crook 8250: @end example
1.21 crook 8251:
1.75 anton 8252: Here you want to pass the argument 1024 (e.g., a buffer size) to
8253: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8254: ), which allows its use with @code{require}. Of course with such
8255: parameters to required files, you have to ensure that the first
8256: @code{require} fits for all uses (i.e., @code{require} it early in the
8257: master load file).
1.44 crook 8258:
1.26 crook 8259: doc-include-file
8260: doc-included
1.28 crook 8261: doc-included?
1.26 crook 8262: doc-include
8263: doc-required
8264: doc-require
8265: doc-needs
1.75 anton 8266: @c doc-init-included-files @c internal
8267: doc-sourcefilename
8268: doc-sourceline#
1.44 crook 8269:
1.26 crook 8270: A definition in ANS Forth for @code{required} is provided in
8271: @file{compat/required.fs}.
1.21 crook 8272:
1.26 crook 8273: @c -------------------------------------------------------------
8274: @node General files, Search Paths, Forth source files, Files
8275: @subsection General files
8276: @cindex general files
8277: @cindex file-handling
1.21 crook 8278:
1.75 anton 8279: Files are opened/created by name and type. The following file access
8280: methods (FAMs) are recognised:
1.44 crook 8281:
1.75 anton 8282: @cindex fam (file access method)
1.26 crook 8283: doc-r/o
8284: doc-r/w
8285: doc-w/o
8286: doc-bin
1.1 anton 8287:
1.44 crook 8288:
1.26 crook 8289: When a file is opened/created, it returns a file identifier,
1.29 crook 8290: @i{wfileid} that is used for all other file commands. All file
8291: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8292: successful operation and an implementation-defined non-zero value in the
8293: case of an error.
1.21 crook 8294:
1.44 crook 8295:
1.26 crook 8296: doc-open-file
8297: doc-create-file
1.21 crook 8298:
1.26 crook 8299: doc-close-file
8300: doc-delete-file
8301: doc-rename-file
8302: doc-read-file
8303: doc-read-line
1.154 anton 8304: doc-key-file
8305: doc-key?-file
1.26 crook 8306: doc-write-file
8307: doc-write-line
8308: doc-emit-file
8309: doc-flush-file
1.21 crook 8310:
1.26 crook 8311: doc-file-status
8312: doc-file-position
8313: doc-reposition-file
8314: doc-file-size
8315: doc-resize-file
1.21 crook 8316:
1.93 anton 8317: doc-slurp-file
8318: doc-slurp-fid
1.112 anton 8319: doc-stdin
8320: doc-stdout
8321: doc-stderr
1.44 crook 8322:
1.26 crook 8323: @c ---------------------------------------------------------
1.48 anton 8324: @node Search Paths, , General files, Files
1.26 crook 8325: @subsection Search Paths
8326: @cindex path for @code{included}
8327: @cindex file search path
8328: @cindex @code{include} search path
8329: @cindex search path for files
1.21 crook 8330:
1.26 crook 8331: If you specify an absolute filename (i.e., a filename starting with
8332: @file{/} or @file{~}, or with @file{:} in the second position (as in
8333: @samp{C:...})) for @code{included} and friends, that file is included
8334: just as you would expect.
1.21 crook 8335:
1.75 anton 8336: If the filename starts with @file{./}, this refers to the directory that
8337: the present file was @code{included} from. This allows files to include
8338: other files relative to their own position (irrespective of the current
8339: working directory or the absolute position). This feature is essential
8340: for libraries consisting of several files, where a file may include
8341: other files from the library. It corresponds to @code{#include "..."}
8342: in C. If the current input source is not a file, @file{.} refers to the
8343: directory of the innermost file being included, or, if there is no file
8344: being included, to the current working directory.
8345:
8346: For relative filenames (not starting with @file{./}), Gforth uses a
8347: search path similar to Forth's search order (@pxref{Word Lists}). It
8348: tries to find the given filename in the directories present in the path,
8349: and includes the first one it finds. There are separate search paths for
8350: Forth source files and general files. If the search path contains the
8351: directory @file{.}, this refers to the directory of the current file, or
8352: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8353:
1.26 crook 8354: Use @file{~+} to refer to the current working directory (as in the
8355: @code{bash}).
1.1 anton 8356:
1.75 anton 8357: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8358:
1.48 anton 8359: @menu
1.75 anton 8360: * Source Search Paths::
1.48 anton 8361: * General Search Paths::
8362: @end menu
8363:
1.26 crook 8364: @c ---------------------------------------------------------
1.75 anton 8365: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8366: @subsubsection Source Search Paths
8367: @cindex search path control, source files
1.5 anton 8368:
1.26 crook 8369: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8370: Gforth}). You can display it and change it using @code{fpath} in
8371: combination with the general path handling words.
1.5 anton 8372:
1.75 anton 8373: doc-fpath
8374: @c the functionality of the following words is easily available through
8375: @c fpath and the general path words. The may go away.
8376: @c doc-.fpath
8377: @c doc-fpath+
8378: @c doc-fpath=
8379: @c doc-open-fpath-file
1.44 crook 8380:
8381: @noindent
1.26 crook 8382: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8383:
1.26 crook 8384: @example
1.75 anton 8385: fpath path= /usr/lib/forth/|./
1.26 crook 8386: require timer.fs
8387: @end example
1.5 anton 8388:
1.75 anton 8389:
1.26 crook 8390: @c ---------------------------------------------------------
1.75 anton 8391: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8392: @subsubsection General Search Paths
1.75 anton 8393: @cindex search path control, source files
1.5 anton 8394:
1.26 crook 8395: Your application may need to search files in several directories, like
8396: @code{included} does. To facilitate this, Gforth allows you to define
8397: and use your own search paths, by providing generic equivalents of the
8398: Forth search path words:
1.5 anton 8399:
1.75 anton 8400: doc-open-path-file
8401: doc-path-allot
8402: doc-clear-path
8403: doc-also-path
1.26 crook 8404: doc-.path
8405: doc-path+
8406: doc-path=
1.5 anton 8407:
1.75 anton 8408: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8409:
1.75 anton 8410: Here's an example of creating an empty search path:
8411: @c
1.26 crook 8412: @example
1.75 anton 8413: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8414: @end example
1.5 anton 8415:
1.26 crook 8416: @c -------------------------------------------------------------
8417: @node Blocks, Other I/O, Files, Words
8418: @section Blocks
1.28 crook 8419: @cindex I/O - blocks
8420: @cindex blocks
8421:
8422: When you run Gforth on a modern desk-top computer, it runs under the
8423: control of an operating system which provides certain services. One of
8424: these services is @var{file services}, which allows Forth source code
8425: and data to be stored in files and read into Gforth (@pxref{Files}).
8426:
8427: Traditionally, Forth has been an important programming language on
8428: systems where it has interfaced directly to the underlying hardware with
8429: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8430: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8431:
8432: A block is a 1024-byte data area, which can be used to hold data or
8433: Forth source code. No structure is imposed on the contents of the
8434: block. A block is identified by its number; blocks are numbered
8435: contiguously from 1 to an implementation-defined maximum.
8436:
8437: A typical system that used blocks but no operating system might use a
8438: single floppy-disk drive for mass storage, with the disks formatted to
8439: provide 256-byte sectors. Blocks would be implemented by assigning the
8440: first four sectors of the disk to block 1, the second four sectors to
8441: block 2 and so on, up to the limit of the capacity of the disk. The disk
8442: would not contain any file system information, just the set of blocks.
8443:
1.29 crook 8444: @cindex blocks file
1.28 crook 8445: On systems that do provide file services, blocks are typically
1.29 crook 8446: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8447: file}. The size of the blocks file will be an exact multiple of 1024
8448: bytes, corresponding to the number of blocks it contains. This is the
8449: mechanism that Gforth uses.
8450:
1.29 crook 8451: @cindex @file{blocks.fb}
1.75 anton 8452: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8453: having specified a blocks file, Gforth defaults to the blocks file
8454: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8455: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8456:
1.29 crook 8457: @cindex block buffers
1.28 crook 8458: When you read and write blocks under program control, Gforth uses a
1.29 crook 8459: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8460: not used when you use @code{load} to interpret the contents of a block.
8461:
1.75 anton 8462: The behaviour of the block buffers is analagous to that of a cache.
8463: Each block buffer has three states:
1.28 crook 8464:
8465: @itemize @bullet
8466: @item
8467: Unassigned
8468: @item
8469: Assigned-clean
8470: @item
8471: Assigned-dirty
8472: @end itemize
8473:
1.29 crook 8474: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8475: block, the block (specified by its block number) must be assigned to a
8476: block buffer.
8477:
8478: The assignment of a block to a block buffer is performed by @code{block}
8479: or @code{buffer}. Use @code{block} when you wish to modify the existing
8480: contents of a block. Use @code{buffer} when you don't care about the
8481: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8482: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8483: with the particular block is already stored in a block buffer due to an
8484: earlier @code{block} command, @code{buffer} will return that block
8485: buffer and the existing contents of the block will be
8486: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8487: block buffer for the block.}.
1.28 crook 8488:
1.47 crook 8489: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8490: @code{buffer}, that block buffer becomes the @i{current block
8491: buffer}. Data may only be manipulated (read or written) within the
8492: current block buffer.
1.47 crook 8493:
8494: When the contents of the current block buffer has been modified it is
1.48 anton 8495: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8496: either abandon the changes (by doing nothing) or mark the block as
8497: changed (assigned-dirty), using @code{update}. Using @code{update} does
8498: not change the blocks file; it simply changes a block buffer's state to
8499: @i{assigned-dirty}. The block will be written implicitly when it's
8500: buffer is needed for another block, or explicitly by @code{flush} or
8501: @code{save-buffers}.
8502:
8503: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8504: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8505: @code{flush}.
1.28 crook 8506:
1.29 crook 8507: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8508: algorithm to assign a block buffer to a block. That means that any
8509: particular block can only be assigned to one specific block buffer,
1.29 crook 8510: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8511: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8512: the new block immediately. If it is @i{assigned-dirty} its current
8513: contents are written back to the blocks file on disk before it is
1.28 crook 8514: allocated to the new block.
8515:
8516: Although no structure is imposed on the contents of a block, it is
8517: traditional to display the contents as 16 lines each of 64 characters. A
8518: block provides a single, continuous stream of input (for example, it
8519: acts as a single parse area) -- there are no end-of-line characters
8520: within a block, and no end-of-file character at the end of a
8521: block. There are two consequences of this:
1.26 crook 8522:
1.28 crook 8523: @itemize @bullet
8524: @item
8525: The last character of one line wraps straight into the first character
8526: of the following line
8527: @item
8528: The word @code{\} -- comment to end of line -- requires special
8529: treatment; in the context of a block it causes all characters until the
8530: end of the current 64-character ``line'' to be ignored.
8531: @end itemize
8532:
8533: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8534: the current blocks file will be extended to the appropriate size and the
1.28 crook 8535: block buffer will be initialised with spaces.
8536:
1.47 crook 8537: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8538: for details) but doesn't encourage the use of blocks; the mechanism is
8539: only provided for backward compatibility -- ANS Forth requires blocks to
8540: be available when files are.
1.28 crook 8541:
8542: Common techniques that are used when working with blocks include:
8543:
8544: @itemize @bullet
8545: @item
8546: A screen editor that allows you to edit blocks without leaving the Forth
8547: environment.
8548: @item
8549: Shadow screens; where every code block has an associated block
8550: containing comments (for example: code in odd block numbers, comments in
8551: even block numbers). Typically, the block editor provides a convenient
8552: mechanism to toggle between code and comments.
8553: @item
8554: Load blocks; a single block (typically block 1) contains a number of
8555: @code{thru} commands which @code{load} the whole of the application.
8556: @end itemize
1.26 crook 8557:
1.29 crook 8558: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8559: integrated into a Forth programming environment.
1.26 crook 8560:
8561: @comment TODO what about errors on open-blocks?
1.44 crook 8562:
1.26 crook 8563: doc-open-blocks
8564: doc-use
1.75 anton 8565: doc-block-offset
1.26 crook 8566: doc-get-block-fid
8567: doc-block-position
1.28 crook 8568:
1.75 anton 8569: doc-list
1.28 crook 8570: doc-scr
8571:
1.45 crook 8572: doc---gforthman-block
1.28 crook 8573: doc-buffer
8574:
1.75 anton 8575: doc-empty-buffers
8576: doc-empty-buffer
1.26 crook 8577: doc-update
1.28 crook 8578: doc-updated?
1.26 crook 8579: doc-save-buffers
1.75 anton 8580: doc-save-buffer
1.26 crook 8581: doc-flush
1.28 crook 8582:
1.26 crook 8583: doc-load
8584: doc-thru
8585: doc-+load
8586: doc-+thru
1.45 crook 8587: doc---gforthman--->
1.26 crook 8588: doc-block-included
8589:
1.44 crook 8590:
1.26 crook 8591: @c -------------------------------------------------------------
1.126 pazsan 8592: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8593: @section Other I/O
1.28 crook 8594: @cindex I/O - keyboard and display
1.26 crook 8595:
8596: @menu
8597: * Simple numeric output:: Predefined formats
8598: * Formatted numeric output:: Formatted (pictured) output
8599: * String Formats:: How Forth stores strings in memory
1.67 anton 8600: * Displaying characters and strings:: Other stuff
1.26 crook 8601: * Input:: Input
1.112 anton 8602: * Pipes:: How to create your own pipes
1.149 pazsan 8603: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8604: @end menu
8605:
8606: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8607: @subsection Simple numeric output
1.28 crook 8608: @cindex numeric output - simple/free-format
1.5 anton 8609:
1.26 crook 8610: The simplest output functions are those that display numbers from the
8611: data or floating-point stacks. Floating-point output is always displayed
8612: using base 10. Numbers displayed from the data stack use the value stored
8613: in @code{base}.
1.5 anton 8614:
1.44 crook 8615:
1.26 crook 8616: doc-.
8617: doc-dec.
8618: doc-hex.
8619: doc-u.
8620: doc-.r
8621: doc-u.r
8622: doc-d.
8623: doc-ud.
8624: doc-d.r
8625: doc-ud.r
8626: doc-f.
8627: doc-fe.
8628: doc-fs.
1.111 anton 8629: doc-f.rdp
1.44 crook 8630:
1.26 crook 8631: Examples of printing the number 1234.5678E23 in the different floating-point output
8632: formats are shown below:
1.5 anton 8633:
8634: @example
1.26 crook 8635: f. 123456779999999000000000000.
8636: fe. 123.456779999999E24
8637: fs. 1.23456779999999E26
1.5 anton 8638: @end example
8639:
8640:
1.26 crook 8641: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8642: @subsection Formatted numeric output
1.28 crook 8643: @cindex formatted numeric output
1.26 crook 8644: @cindex pictured numeric output
1.28 crook 8645: @cindex numeric output - formatted
1.26 crook 8646:
1.29 crook 8647: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8648: output} for formatted printing of integers. In this technique, digits
8649: are extracted from the number (using the current output radix defined by
8650: @code{base}), converted to ASCII codes and appended to a string that is
8651: built in a scratch-pad area of memory (@pxref{core-idef,
8652: Implementation-defined options, Implementation-defined
8653: options}). Arbitrary characters can be appended to the string during the
8654: extraction process. The completed string is specified by an address
8655: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8656: under program control.
1.5 anton 8657:
1.75 anton 8658: All of the integer output words described in the previous section
8659: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8660: numeric output.
1.5 anton 8661:
1.47 crook 8662: Three important things to remember about pictured numeric output:
1.5 anton 8663:
1.26 crook 8664: @itemize @bullet
8665: @item
1.28 crook 8666: It always operates on double-precision numbers; to display a
1.49 anton 8667: single-precision number, convert it first (for ways of doing this
8668: @pxref{Double precision}).
1.26 crook 8669: @item
1.28 crook 8670: It always treats the double-precision number as though it were
8671: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8672: @item
8673: The string is built up from right to left; least significant digit first.
8674: @end itemize
1.5 anton 8675:
1.44 crook 8676:
1.26 crook 8677: doc-<#
1.47 crook 8678: doc-<<#
1.26 crook 8679: doc-#
8680: doc-#s
8681: doc-hold
8682: doc-sign
8683: doc-#>
1.47 crook 8684: doc-#>>
1.5 anton 8685:
1.26 crook 8686: doc-represent
1.111 anton 8687: doc-f>str-rdp
8688: doc-f>buf-rdp
1.5 anton 8689:
1.44 crook 8690:
8691: @noindent
1.26 crook 8692: Here are some examples of using pictured numeric output:
1.5 anton 8693:
8694: @example
1.26 crook 8695: : my-u. ( u -- )
8696: \ Simplest use of pns.. behaves like Standard u.
8697: 0 \ convert to unsigned double
1.75 anton 8698: <<# \ start conversion
1.26 crook 8699: #s \ convert all digits
8700: #> \ complete conversion
1.75 anton 8701: TYPE SPACE \ display, with trailing space
8702: #>> ; \ release hold area
1.5 anton 8703:
1.26 crook 8704: : cents-only ( u -- )
8705: 0 \ convert to unsigned double
1.75 anton 8706: <<# \ start conversion
1.26 crook 8707: # # \ convert two least-significant digits
8708: #> \ complete conversion, discard other digits
1.75 anton 8709: TYPE SPACE \ display, with trailing space
8710: #>> ; \ release hold area
1.5 anton 8711:
1.26 crook 8712: : dollars-and-cents ( u -- )
8713: 0 \ convert to unsigned double
1.75 anton 8714: <<# \ start conversion
1.26 crook 8715: # # \ convert two least-significant digits
8716: [char] . hold \ insert decimal point
8717: #s \ convert remaining digits
8718: [char] $ hold \ append currency symbol
8719: #> \ complete conversion
1.75 anton 8720: TYPE SPACE \ display, with trailing space
8721: #>> ; \ release hold area
1.5 anton 8722:
1.26 crook 8723: : my-. ( n -- )
8724: \ handling negatives.. behaves like Standard .
8725: s>d \ convert to signed double
8726: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8727: <<# \ start conversion
1.26 crook 8728: #s \ convert all digits
8729: rot sign \ get at sign byte, append "-" if needed
8730: #> \ complete conversion
1.75 anton 8731: TYPE SPACE \ display, with trailing space
8732: #>> ; \ release hold area
1.5 anton 8733:
1.26 crook 8734: : account. ( n -- )
1.75 anton 8735: \ accountants don't like minus signs, they use parentheses
1.26 crook 8736: \ for negative numbers
8737: s>d \ convert to signed double
8738: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8739: <<# \ start conversion
1.26 crook 8740: 2 pick \ get copy of sign byte
8741: 0< IF [char] ) hold THEN \ right-most character of output
8742: #s \ convert all digits
8743: rot \ get at sign byte
8744: 0< IF [char] ( hold THEN
8745: #> \ complete conversion
1.75 anton 8746: TYPE SPACE \ display, with trailing space
8747: #>> ; \ release hold area
8748:
1.5 anton 8749: @end example
8750:
1.26 crook 8751: Here are some examples of using these words:
1.5 anton 8752:
8753: @example
1.26 crook 8754: 1 my-u. 1
8755: hex -1 my-u. decimal FFFFFFFF
8756: 1 cents-only 01
8757: 1234 cents-only 34
8758: 2 dollars-and-cents $0.02
8759: 1234 dollars-and-cents $12.34
8760: 123 my-. 123
8761: -123 my. -123
8762: 123 account. 123
8763: -456 account. (456)
1.5 anton 8764: @end example
8765:
8766:
1.26 crook 8767: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8768: @subsection String Formats
1.27 crook 8769: @cindex strings - see character strings
8770: @cindex character strings - formats
1.28 crook 8771: @cindex I/O - see character strings
1.75 anton 8772: @cindex counted strings
8773:
8774: @c anton: this does not really belong here; maybe the memory section,
8775: @c or the principles chapter
1.26 crook 8776:
1.27 crook 8777: Forth commonly uses two different methods for representing character
8778: strings:
1.26 crook 8779:
8780: @itemize @bullet
8781: @item
8782: @cindex address of counted string
1.45 crook 8783: @cindex counted string
1.29 crook 8784: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8785: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8786: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8787: memory.
8788: @item
1.29 crook 8789: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8790: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8791: first byte of the string.
8792: @end itemize
8793:
8794: ANS Forth encourages the use of the second format when representing
1.75 anton 8795: strings.
1.26 crook 8796:
1.44 crook 8797:
1.26 crook 8798: doc-count
8799:
1.44 crook 8800:
1.49 anton 8801: For words that move, copy and search for strings see @ref{Memory
8802: Blocks}. For words that display characters and strings see
8803: @ref{Displaying characters and strings}.
1.26 crook 8804:
8805: @node Displaying characters and strings, Input, String Formats, Other I/O
8806: @subsection Displaying characters and strings
1.27 crook 8807: @cindex characters - compiling and displaying
8808: @cindex character strings - compiling and displaying
1.26 crook 8809:
8810: This section starts with a glossary of Forth words and ends with a set
8811: of examples.
8812:
1.44 crook 8813:
1.26 crook 8814: doc-bl
8815: doc-space
8816: doc-spaces
8817: doc-emit
8818: doc-toupper
8819: doc-."
8820: doc-.(
1.98 anton 8821: doc-.\"
1.26 crook 8822: doc-type
1.44 crook 8823: doc-typewhite
1.26 crook 8824: doc-cr
1.27 crook 8825: @cindex cursor control
1.26 crook 8826: doc-at-xy
8827: doc-page
8828: doc-s"
1.98 anton 8829: doc-s\"
1.26 crook 8830: doc-c"
8831: doc-char
8832: doc-[char]
8833:
1.44 crook 8834:
8835: @noindent
1.26 crook 8836: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8837:
8838: @example
1.26 crook 8839: .( text-1)
8840: : my-word
8841: ." text-2" cr
8842: .( text-3)
8843: ;
8844:
8845: ." text-4"
8846:
8847: : my-char
8848: [char] ALPHABET emit
8849: char emit
8850: ;
1.5 anton 8851: @end example
8852:
1.26 crook 8853: When you load this code into Gforth, the following output is generated:
1.5 anton 8854:
1.26 crook 8855: @example
1.30 anton 8856: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8857: @end example
1.5 anton 8858:
1.26 crook 8859: @itemize @bullet
8860: @item
8861: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8862: is an immediate word; it behaves in the same way whether it is used inside
8863: or outside a colon definition.
8864: @item
8865: Message @code{text-4} is displayed because of Gforth's added interpretation
8866: semantics for @code{."}.
8867: @item
1.29 crook 8868: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8869: performs the compilation semantics for @code{."} within the definition of
8870: @code{my-word}.
8871: @end itemize
1.5 anton 8872:
1.26 crook 8873: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8874:
1.26 crook 8875: @example
1.30 anton 8876: @kbd{my-word @key{RET}} text-2
1.26 crook 8877: ok
1.30 anton 8878: @kbd{my-char fred @key{RET}} Af ok
8879: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8880: @end example
1.5 anton 8881:
8882: @itemize @bullet
8883: @item
1.26 crook 8884: Message @code{text-2} is displayed because of the run-time behaviour of
8885: @code{."}.
8886: @item
8887: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8888: on the stack at run-time. @code{emit} always displays the character
8889: when @code{my-char} is executed.
8890: @item
8891: @code{char} parses a string at run-time and the second @code{emit} displays
8892: the first character of the string.
1.5 anton 8893: @item
1.26 crook 8894: If you type @code{see my-char} you can see that @code{[char]} discarded
8895: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8896: definition of @code{my-char}.
1.5 anton 8897: @end itemize
8898:
8899:
8900:
1.112 anton 8901: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8902: @subsection Input
8903: @cindex input
1.28 crook 8904: @cindex I/O - see input
8905: @cindex parsing a string
1.5 anton 8906:
1.49 anton 8907: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8908:
1.27 crook 8909: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8910: @comment then index them
1.27 crook 8911:
1.44 crook 8912:
1.27 crook 8913: doc-key
8914: doc-key?
1.45 crook 8915: doc-ekey
1.141 anton 8916: doc-ekey>char
1.45 crook 8917: doc-ekey?
1.141 anton 8918:
8919: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8920: you need the ANSI.SYS driver to get that behaviour). These are the
8921: keyboard events produced by various common keys:
8922:
8923: doc-k-left
8924: doc-k-right
8925: doc-k-up
8926: doc-k-down
8927: doc-k-home
8928: doc-k-end
8929: doc-k-prior
8930: doc-k-next
8931: doc-k-insert
8932: doc-k-delete
8933:
8934: The function keys (aka keypad keys) are:
8935:
8936: doc-k1
8937: doc-k2
8938: doc-k3
8939: doc-k4
8940: doc-k5
8941: doc-k6
8942: doc-k7
8943: doc-k8
8944: doc-k9
8945: doc-k10
8946: doc-k11
8947: doc-k12
8948:
8949: Note that K11 and K12 are not as widely available. The shifted
8950: function keys are also not very widely available:
8951:
8952: doc-s-k8
8953: doc-s-k1
8954: doc-s-k2
8955: doc-s-k3
8956: doc-s-k4
8957: doc-s-k5
8958: doc-s-k6
8959: doc-s-k7
8960: doc-s-k8
8961: doc-s-k9
8962: doc-s-k10
8963: doc-s-k11
8964: doc-s-k12
8965:
8966: Words for inputting one line from the keyboard:
8967:
8968: doc-accept
8969: doc-edit-line
8970:
8971: Conversion words:
8972:
1.143 anton 8973: doc-s>number?
8974: doc-s>unumber?
1.26 crook 8975: doc->number
8976: doc->float
1.143 anton 8977:
1.141 anton 8978:
1.27 crook 8979: @comment obsolescent words..
1.141 anton 8980: Obsolescent input and conversion words:
8981:
1.27 crook 8982: doc-convert
1.26 crook 8983: doc-expect
1.27 crook 8984: doc-span
1.5 anton 8985:
8986:
1.149 pazsan 8987: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112 anton 8988: @subsection Pipes
8989: @cindex pipes, creating your own
8990:
8991: In addition to using Gforth in pipes created by other processes
8992: (@pxref{Gforth in pipes}), you can create your own pipe with
8993: @code{open-pipe}, and read from or write to it.
8994:
8995: doc-open-pipe
8996: doc-close-pipe
8997:
8998: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
8999: you don't catch this exception, Gforth will catch it and exit, usually
9000: silently (@pxref{Gforth in pipes}). Since you probably do not want
9001: this, you should wrap a @code{catch} or @code{try} block around the code
9002: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9003: problem yourself, and then return to regular processing.
9004:
9005: doc-broken-pipe-error
9006:
1.155 anton 9007: @node Xchars and Unicode, , Pipes, Other I/O
9008: @subsection Xchars and Unicode
1.149 pazsan 9009:
9010: This chapter needs completion
1.112 anton 9011:
1.121 anton 9012: @node OS command line arguments, Locals, Other I/O, Words
9013: @section OS command line arguments
9014: @cindex OS command line arguments
9015: @cindex command line arguments, OS
9016: @cindex arguments, OS command line
9017:
9018: The usual way to pass arguments to Gforth programs on the command line
9019: is via the @option{-e} option, e.g.
9020:
9021: @example
9022: gforth -e "123 456" foo.fs -e bye
9023: @end example
9024:
9025: However, you may want to interpret the command-line arguments directly.
9026: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9027: through @code{next-arg}:
1.121 anton 9028:
1.123 anton 9029: doc-next-arg
1.121 anton 9030:
1.123 anton 9031: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9032:
9033: @example
9034: : echo ( -- )
1.122 anton 9035: begin
1.123 anton 9036: next-arg 2dup 0 0 d<> while
9037: type space
9038: repeat
9039: 2drop ;
1.121 anton 9040:
9041: echo cr bye
9042: @end example
9043:
9044: This can be invoked with
9045:
9046: @example
9047: gforth echo.fs hello world
9048: @end example
1.123 anton 9049:
9050: and it will print
9051:
9052: @example
9053: hello world
9054: @end example
9055:
9056: The next lower level of dealing with the OS command line are the
9057: following words:
9058:
9059: doc-arg
9060: doc-shift-args
9061:
9062: Finally, at the lowest level Gforth provides the following words:
9063:
9064: doc-argc
9065: doc-argv
1.121 anton 9066:
1.78 anton 9067: @c -------------------------------------------------------------
1.126 pazsan 9068: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9069: @section Locals
9070: @cindex locals
9071:
9072: Local variables can make Forth programming more enjoyable and Forth
9073: programs easier to read. Unfortunately, the locals of ANS Forth are
9074: laden with restrictions. Therefore, we provide not only the ANS Forth
9075: locals wordset, but also our own, more powerful locals wordset (we
9076: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9077:
1.78 anton 9078: The ideas in this section have also been published in M. Anton Ertl,
9079: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9080: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9081:
9082: @menu
1.78 anton 9083: * Gforth locals::
9084: * ANS Forth locals::
1.5 anton 9085: @end menu
9086:
1.78 anton 9087: @node Gforth locals, ANS Forth locals, Locals, Locals
9088: @subsection Gforth locals
9089: @cindex Gforth locals
9090: @cindex locals, Gforth style
1.5 anton 9091:
1.78 anton 9092: Locals can be defined with
1.44 crook 9093:
1.78 anton 9094: @example
9095: @{ local1 local2 ... -- comment @}
9096: @end example
9097: or
9098: @example
9099: @{ local1 local2 ... @}
9100: @end example
1.5 anton 9101:
1.78 anton 9102: E.g.,
9103: @example
9104: : max @{ n1 n2 -- n3 @}
9105: n1 n2 > if
9106: n1
9107: else
9108: n2
9109: endif ;
9110: @end example
1.44 crook 9111:
1.78 anton 9112: The similarity of locals definitions with stack comments is intended. A
9113: locals definition often replaces the stack comment of a word. The order
9114: of the locals corresponds to the order in a stack comment and everything
9115: after the @code{--} is really a comment.
1.77 anton 9116:
1.78 anton 9117: This similarity has one disadvantage: It is too easy to confuse locals
9118: declarations with stack comments, causing bugs and making them hard to
9119: find. However, this problem can be avoided by appropriate coding
9120: conventions: Do not use both notations in the same program. If you do,
9121: they should be distinguished using additional means, e.g. by position.
1.77 anton 9122:
1.78 anton 9123: @cindex types of locals
9124: @cindex locals types
9125: The name of the local may be preceded by a type specifier, e.g.,
9126: @code{F:} for a floating point value:
1.5 anton 9127:
1.78 anton 9128: @example
9129: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9130: \ complex multiplication
9131: Ar Br f* Ai Bi f* f-
9132: Ar Bi f* Ai Br f* f+ ;
9133: @end example
1.44 crook 9134:
1.78 anton 9135: @cindex flavours of locals
9136: @cindex locals flavours
9137: @cindex value-flavoured locals
9138: @cindex variable-flavoured locals
9139: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9140: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9141: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9142: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9143: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9144: produces its address (which becomes invalid when the variable's scope is
9145: left). E.g., the standard word @code{emit} can be defined in terms of
9146: @code{type} like this:
1.5 anton 9147:
1.78 anton 9148: @example
9149: : emit @{ C^ char* -- @}
9150: char* 1 type ;
9151: @end example
1.5 anton 9152:
1.78 anton 9153: @cindex default type of locals
9154: @cindex locals, default type
9155: A local without type specifier is a @code{W:} local. Both flavours of
9156: locals are initialized with values from the data or FP stack.
1.44 crook 9157:
1.78 anton 9158: Currently there is no way to define locals with user-defined data
9159: structures, but we are working on it.
1.5 anton 9160:
1.78 anton 9161: Gforth allows defining locals everywhere in a colon definition. This
9162: poses the following questions:
1.5 anton 9163:
1.78 anton 9164: @menu
9165: * Where are locals visible by name?::
9166: * How long do locals live?::
9167: * Locals programming style::
9168: * Locals implementation::
9169: @end menu
1.44 crook 9170:
1.78 anton 9171: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9172: @subsubsection Where are locals visible by name?
9173: @cindex locals visibility
9174: @cindex visibility of locals
9175: @cindex scope of locals
1.5 anton 9176:
1.78 anton 9177: Basically, the answer is that locals are visible where you would expect
9178: it in block-structured languages, and sometimes a little longer. If you
9179: want to restrict the scope of a local, enclose its definition in
9180: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9181:
9182:
1.78 anton 9183: doc-scope
9184: doc-endscope
1.5 anton 9185:
9186:
1.78 anton 9187: These words behave like control structure words, so you can use them
9188: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9189: arbitrary ways.
1.77 anton 9190:
1.78 anton 9191: If you want a more exact answer to the visibility question, here's the
9192: basic principle: A local is visible in all places that can only be
9193: reached through the definition of the local@footnote{In compiler
9194: construction terminology, all places dominated by the definition of the
9195: local.}. In other words, it is not visible in places that can be reached
9196: without going through the definition of the local. E.g., locals defined
9197: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9198: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9199: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9200:
1.78 anton 9201: The reasoning behind this solution is: We want to have the locals
9202: visible as long as it is meaningful. The user can always make the
9203: visibility shorter by using explicit scoping. In a place that can
9204: only be reached through the definition of a local, the meaning of a
9205: local name is clear. In other places it is not: How is the local
9206: initialized at the control flow path that does not contain the
9207: definition? Which local is meant, if the same name is defined twice in
9208: two independent control flow paths?
1.77 anton 9209:
1.78 anton 9210: This should be enough detail for nearly all users, so you can skip the
9211: rest of this section. If you really must know all the gory details and
9212: options, read on.
1.77 anton 9213:
1.78 anton 9214: In order to implement this rule, the compiler has to know which places
9215: are unreachable. It knows this automatically after @code{AHEAD},
9216: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9217: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9218: compiler that the control flow never reaches that place. If
9219: @code{UNREACHABLE} is not used where it could, the only consequence is
9220: that the visibility of some locals is more limited than the rule above
9221: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9222: lie to the compiler), buggy code will be produced.
1.77 anton 9223:
1.5 anton 9224:
1.78 anton 9225: doc-unreachable
1.5 anton 9226:
1.23 crook 9227:
1.78 anton 9228: Another problem with this rule is that at @code{BEGIN}, the compiler
9229: does not know which locals will be visible on the incoming
9230: back-edge. All problems discussed in the following are due to this
9231: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9232: loops as examples; the discussion also applies to @code{?DO} and other
9233: loops). Perhaps the most insidious example is:
1.26 crook 9234: @example
1.78 anton 9235: AHEAD
9236: BEGIN
9237: x
9238: [ 1 CS-ROLL ] THEN
9239: @{ x @}
9240: ...
9241: UNTIL
1.26 crook 9242: @end example
1.23 crook 9243:
1.78 anton 9244: This should be legal according to the visibility rule. The use of
9245: @code{x} can only be reached through the definition; but that appears
9246: textually below the use.
9247:
9248: From this example it is clear that the visibility rules cannot be fully
9249: implemented without major headaches. Our implementation treats common
9250: cases as advertised and the exceptions are treated in a safe way: The
9251: compiler makes a reasonable guess about the locals visible after a
9252: @code{BEGIN}; if it is too pessimistic, the
9253: user will get a spurious error about the local not being defined; if the
9254: compiler is too optimistic, it will notice this later and issue a
9255: warning. In the case above the compiler would complain about @code{x}
9256: being undefined at its use. You can see from the obscure examples in
9257: this section that it takes quite unusual control structures to get the
9258: compiler into trouble, and even then it will often do fine.
1.23 crook 9259:
1.78 anton 9260: If the @code{BEGIN} is reachable from above, the most optimistic guess
9261: is that all locals visible before the @code{BEGIN} will also be
9262: visible after the @code{BEGIN}. This guess is valid for all loops that
9263: are entered only through the @code{BEGIN}, in particular, for normal
9264: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9265: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9266: compiler. When the branch to the @code{BEGIN} is finally generated by
9267: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9268: warns the user if it was too optimistic:
1.26 crook 9269: @example
1.78 anton 9270: IF
9271: @{ x @}
9272: BEGIN
9273: \ x ?
9274: [ 1 cs-roll ] THEN
9275: ...
9276: UNTIL
1.26 crook 9277: @end example
1.23 crook 9278:
1.78 anton 9279: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9280: optimistically assumes that it lives until the @code{THEN}. It notices
9281: this difference when it compiles the @code{UNTIL} and issues a
9282: warning. The user can avoid the warning, and make sure that @code{x}
9283: is not used in the wrong area by using explicit scoping:
9284: @example
9285: IF
9286: SCOPE
9287: @{ x @}
9288: ENDSCOPE
9289: BEGIN
9290: [ 1 cs-roll ] THEN
9291: ...
9292: UNTIL
9293: @end example
1.23 crook 9294:
1.78 anton 9295: Since the guess is optimistic, there will be no spurious error messages
9296: about undefined locals.
1.44 crook 9297:
1.78 anton 9298: If the @code{BEGIN} is not reachable from above (e.g., after
9299: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9300: optimistic guess, as the locals visible after the @code{BEGIN} may be
9301: defined later. Therefore, the compiler assumes that no locals are
9302: visible after the @code{BEGIN}. However, the user can use
9303: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9304: visible at the BEGIN as at the point where the top control-flow stack
9305: item was created.
1.23 crook 9306:
1.44 crook 9307:
1.78 anton 9308: doc-assume-live
1.26 crook 9309:
1.23 crook 9310:
1.78 anton 9311: @noindent
9312: E.g.,
9313: @example
9314: @{ x @}
9315: AHEAD
9316: ASSUME-LIVE
9317: BEGIN
9318: x
9319: [ 1 CS-ROLL ] THEN
9320: ...
9321: UNTIL
9322: @end example
1.44 crook 9323:
1.78 anton 9324: Other cases where the locals are defined before the @code{BEGIN} can be
9325: handled by inserting an appropriate @code{CS-ROLL} before the
9326: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9327: behind the @code{ASSUME-LIVE}).
1.23 crook 9328:
1.78 anton 9329: Cases where locals are defined after the @code{BEGIN} (but should be
9330: visible immediately after the @code{BEGIN}) can only be handled by
9331: rearranging the loop. E.g., the ``most insidious'' example above can be
9332: arranged into:
9333: @example
9334: BEGIN
9335: @{ x @}
9336: ... 0=
9337: WHILE
9338: x
9339: REPEAT
9340: @end example
1.44 crook 9341:
1.78 anton 9342: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9343: @subsubsection How long do locals live?
9344: @cindex locals lifetime
9345: @cindex lifetime of locals
1.23 crook 9346:
1.78 anton 9347: The right answer for the lifetime question would be: A local lives at
9348: least as long as it can be accessed. For a value-flavoured local this
9349: means: until the end of its visibility. However, a variable-flavoured
9350: local could be accessed through its address far beyond its visibility
9351: scope. Ultimately, this would mean that such locals would have to be
9352: garbage collected. Since this entails un-Forth-like implementation
9353: complexities, I adopted the same cowardly solution as some other
9354: languages (e.g., C): The local lives only as long as it is visible;
9355: afterwards its address is invalid (and programs that access it
9356: afterwards are erroneous).
1.23 crook 9357:
1.78 anton 9358: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9359: @subsubsection Locals programming style
9360: @cindex locals programming style
9361: @cindex programming style, locals
1.23 crook 9362:
1.78 anton 9363: The freedom to define locals anywhere has the potential to change
9364: programming styles dramatically. In particular, the need to use the
9365: return stack for intermediate storage vanishes. Moreover, all stack
9366: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9367: determined arguments) can be eliminated: If the stack items are in the
9368: wrong order, just write a locals definition for all of them; then
9369: write the items in the order you want.
1.23 crook 9370:
1.78 anton 9371: This seems a little far-fetched and eliminating stack manipulations is
9372: unlikely to become a conscious programming objective. Still, the number
9373: of stack manipulations will be reduced dramatically if local variables
9374: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9375: a traditional implementation of @code{max}).
1.23 crook 9376:
1.78 anton 9377: This shows one potential benefit of locals: making Forth programs more
9378: readable. Of course, this benefit will only be realized if the
9379: programmers continue to honour the principle of factoring instead of
9380: using the added latitude to make the words longer.
1.23 crook 9381:
1.78 anton 9382: @cindex single-assignment style for locals
9383: Using @code{TO} can and should be avoided. Without @code{TO},
9384: every value-flavoured local has only a single assignment and many
9385: advantages of functional languages apply to Forth. I.e., programs are
9386: easier to analyse, to optimize and to read: It is clear from the
9387: definition what the local stands for, it does not turn into something
9388: different later.
1.23 crook 9389:
1.78 anton 9390: E.g., a definition using @code{TO} might look like this:
9391: @example
9392: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9393: u1 u2 min 0
9394: ?do
9395: addr1 c@@ addr2 c@@ -
9396: ?dup-if
9397: unloop exit
9398: then
9399: addr1 char+ TO addr1
9400: addr2 char+ TO addr2
9401: loop
9402: u1 u2 - ;
1.26 crook 9403: @end example
1.78 anton 9404: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9405: every loop iteration. @code{strcmp} is a typical example of the
9406: readability problems of using @code{TO}. When you start reading
9407: @code{strcmp}, you think that @code{addr1} refers to the start of the
9408: string. Only near the end of the loop you realize that it is something
9409: else.
1.23 crook 9410:
1.78 anton 9411: This can be avoided by defining two locals at the start of the loop that
9412: are initialized with the right value for the current iteration.
9413: @example
9414: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9415: addr1 addr2
9416: u1 u2 min 0
9417: ?do @{ s1 s2 @}
9418: s1 c@@ s2 c@@ -
9419: ?dup-if
9420: unloop exit
9421: then
9422: s1 char+ s2 char+
9423: loop
9424: 2drop
9425: u1 u2 - ;
9426: @end example
9427: Here it is clear from the start that @code{s1} has a different value
9428: in every loop iteration.
1.23 crook 9429:
1.78 anton 9430: @node Locals implementation, , Locals programming style, Gforth locals
9431: @subsubsection Locals implementation
9432: @cindex locals implementation
9433: @cindex implementation of locals
1.23 crook 9434:
1.78 anton 9435: @cindex locals stack
9436: Gforth uses an extra locals stack. The most compelling reason for
9437: this is that the return stack is not float-aligned; using an extra stack
9438: also eliminates the problems and restrictions of using the return stack
9439: as locals stack. Like the other stacks, the locals stack grows toward
9440: lower addresses. A few primitives allow an efficient implementation:
9441:
9442:
9443: doc-@local#
9444: doc-f@local#
9445: doc-laddr#
9446: doc-lp+!#
9447: doc-lp!
9448: doc->l
9449: doc-f>l
9450:
9451:
9452: In addition to these primitives, some specializations of these
9453: primitives for commonly occurring inline arguments are provided for
9454: efficiency reasons, e.g., @code{@@local0} as specialization of
9455: @code{@@local#} for the inline argument 0. The following compiling words
9456: compile the right specialized version, or the general version, as
9457: appropriate:
1.23 crook 9458:
1.5 anton 9459:
1.107 dvdkhlng 9460: @c doc-compile-@local
9461: @c doc-compile-f@local
1.78 anton 9462: doc-compile-lp+!
1.5 anton 9463:
9464:
1.78 anton 9465: Combinations of conditional branches and @code{lp+!#} like
9466: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9467: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9468:
1.78 anton 9469: A special area in the dictionary space is reserved for keeping the
9470: local variable names. @code{@{} switches the dictionary pointer to this
9471: area and @code{@}} switches it back and generates the locals
9472: initializing code. @code{W:} etc.@ are normal defining words. This
9473: special area is cleared at the start of every colon definition.
1.5 anton 9474:
1.78 anton 9475: @cindex word list for defining locals
9476: A special feature of Gforth's dictionary is used to implement the
9477: definition of locals without type specifiers: every word list (aka
9478: vocabulary) has its own methods for searching
9479: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9480: with a special search method: When it is searched for a word, it
9481: actually creates that word using @code{W:}. @code{@{} changes the search
9482: order to first search the word list containing @code{@}}, @code{W:} etc.,
9483: and then the word list for defining locals without type specifiers.
1.5 anton 9484:
1.78 anton 9485: The lifetime rules support a stack discipline within a colon
9486: definition: The lifetime of a local is either nested with other locals
9487: lifetimes or it does not overlap them.
1.23 crook 9488:
1.78 anton 9489: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9490: pointer manipulation is generated. Between control structure words
9491: locals definitions can push locals onto the locals stack. @code{AGAIN}
9492: is the simplest of the other three control flow words. It has to
9493: restore the locals stack depth of the corresponding @code{BEGIN}
9494: before branching. The code looks like this:
9495: @format
9496: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9497: @code{branch} <begin>
9498: @end format
1.26 crook 9499:
1.78 anton 9500: @code{UNTIL} is a little more complicated: If it branches back, it
9501: must adjust the stack just like @code{AGAIN}. But if it falls through,
9502: the locals stack must not be changed. The compiler generates the
9503: following code:
9504: @format
9505: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9506: @end format
9507: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9508:
1.78 anton 9509: @code{THEN} can produce somewhat inefficient code:
9510: @format
9511: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9512: <orig target>:
9513: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9514: @end format
9515: The second @code{lp+!#} adjusts the locals stack pointer from the
9516: level at the @i{orig} point to the level after the @code{THEN}. The
9517: first @code{lp+!#} adjusts the locals stack pointer from the current
9518: level to the level at the orig point, so the complete effect is an
9519: adjustment from the current level to the right level after the
9520: @code{THEN}.
1.26 crook 9521:
1.78 anton 9522: @cindex locals information on the control-flow stack
9523: @cindex control-flow stack items, locals information
9524: In a conventional Forth implementation a dest control-flow stack entry
9525: is just the target address and an orig entry is just the address to be
9526: patched. Our locals implementation adds a word list to every orig or dest
9527: item. It is the list of locals visible (or assumed visible) at the point
9528: described by the entry. Our implementation also adds a tag to identify
9529: the kind of entry, in particular to differentiate between live and dead
9530: (reachable and unreachable) orig entries.
1.26 crook 9531:
1.78 anton 9532: A few unusual operations have to be performed on locals word lists:
1.44 crook 9533:
1.5 anton 9534:
1.78 anton 9535: doc-common-list
9536: doc-sub-list?
9537: doc-list-size
1.52 anton 9538:
9539:
1.78 anton 9540: Several features of our locals word list implementation make these
9541: operations easy to implement: The locals word lists are organised as
9542: linked lists; the tails of these lists are shared, if the lists
9543: contain some of the same locals; and the address of a name is greater
9544: than the address of the names behind it in the list.
1.5 anton 9545:
1.78 anton 9546: Another important implementation detail is the variable
9547: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9548: determine if they can be reached directly or only through the branch
9549: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9550: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9551: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9552:
1.78 anton 9553: Counted loops are similar to other loops in most respects, but
9554: @code{LEAVE} requires special attention: It performs basically the same
9555: service as @code{AHEAD}, but it does not create a control-flow stack
9556: entry. Therefore the information has to be stored elsewhere;
9557: traditionally, the information was stored in the target fields of the
9558: branches created by the @code{LEAVE}s, by organizing these fields into a
9559: linked list. Unfortunately, this clever trick does not provide enough
9560: space for storing our extended control flow information. Therefore, we
9561: introduce another stack, the leave stack. It contains the control-flow
9562: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9563:
1.78 anton 9564: Local names are kept until the end of the colon definition, even if
9565: they are no longer visible in any control-flow path. In a few cases
9566: this may lead to increased space needs for the locals name area, but
9567: usually less than reclaiming this space would cost in code size.
1.5 anton 9568:
1.44 crook 9569:
1.78 anton 9570: @node ANS Forth locals, , Gforth locals, Locals
9571: @subsection ANS Forth locals
9572: @cindex locals, ANS Forth style
1.5 anton 9573:
1.78 anton 9574: The ANS Forth locals wordset does not define a syntax for locals, but
9575: words that make it possible to define various syntaxes. One of the
9576: possible syntaxes is a subset of the syntax we used in the Gforth locals
9577: wordset, i.e.:
1.29 crook 9578:
9579: @example
1.78 anton 9580: @{ local1 local2 ... -- comment @}
9581: @end example
9582: @noindent
9583: or
9584: @example
9585: @{ local1 local2 ... @}
1.29 crook 9586: @end example
9587:
1.78 anton 9588: The order of the locals corresponds to the order in a stack comment. The
9589: restrictions are:
1.5 anton 9590:
1.78 anton 9591: @itemize @bullet
9592: @item
9593: Locals can only be cell-sized values (no type specifiers are allowed).
9594: @item
9595: Locals can be defined only outside control structures.
9596: @item
9597: Locals can interfere with explicit usage of the return stack. For the
9598: exact (and long) rules, see the standard. If you don't use return stack
9599: accessing words in a definition using locals, you will be all right. The
9600: purpose of this rule is to make locals implementation on the return
9601: stack easier.
9602: @item
9603: The whole definition must be in one line.
9604: @end itemize
1.5 anton 9605:
1.78 anton 9606: Locals defined in ANS Forth behave like @code{VALUE}s
9607: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9608: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9609:
1.78 anton 9610: Since the syntax above is supported by Gforth directly, you need not do
9611: anything to use it. If you want to port a program using this syntax to
9612: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9613: syntax on the other system.
1.5 anton 9614:
1.78 anton 9615: Note that a syntax shown in the standard, section A.13 looks
9616: similar, but is quite different in having the order of locals
9617: reversed. Beware!
1.5 anton 9618:
1.78 anton 9619: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9620:
1.78 anton 9621: doc-(local)
1.5 anton 9622:
1.78 anton 9623: The ANS Forth locals extension wordset defines a syntax using
9624: @code{locals|}, but it is so awful that we strongly recommend not to use
9625: it. We have implemented this syntax to make porting to Gforth easy, but
9626: do not document it here. The problem with this syntax is that the locals
9627: are defined in an order reversed with respect to the standard stack
9628: comment notation, making programs harder to read, and easier to misread
9629: and miswrite. The only merit of this syntax is that it is easy to
9630: implement using the ANS Forth locals wordset.
1.53 anton 9631:
9632:
1.78 anton 9633: @c ----------------------------------------------------------
9634: @node Structures, Object-oriented Forth, Locals, Words
9635: @section Structures
9636: @cindex structures
9637: @cindex records
1.53 anton 9638:
1.78 anton 9639: This section presents the structure package that comes with Gforth. A
9640: version of the package implemented in ANS Forth is available in
9641: @file{compat/struct.fs}. This package was inspired by a posting on
9642: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9643: possibly John Hayes). A version of this section has been published in
9644: M. Anton Ertl,
9645: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9646: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9647: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9648:
1.78 anton 9649: @menu
9650: * Why explicit structure support?::
9651: * Structure Usage::
9652: * Structure Naming Convention::
9653: * Structure Implementation::
9654: * Structure Glossary::
9655: @end menu
1.55 anton 9656:
1.78 anton 9657: @node Why explicit structure support?, Structure Usage, Structures, Structures
9658: @subsection Why explicit structure support?
1.53 anton 9659:
1.78 anton 9660: @cindex address arithmetic for structures
9661: @cindex structures using address arithmetic
9662: If we want to use a structure containing several fields, we could simply
9663: reserve memory for it, and access the fields using address arithmetic
9664: (@pxref{Address arithmetic}). As an example, consider a structure with
9665: the following fields
1.57 anton 9666:
1.78 anton 9667: @table @code
9668: @item a
9669: is a float
9670: @item b
9671: is a cell
9672: @item c
9673: is a float
9674: @end table
1.57 anton 9675:
1.78 anton 9676: Given the (float-aligned) base address of the structure we get the
9677: address of the field
1.52 anton 9678:
1.78 anton 9679: @table @code
9680: @item a
9681: without doing anything further.
9682: @item b
9683: with @code{float+}
9684: @item c
9685: with @code{float+ cell+ faligned}
9686: @end table
1.52 anton 9687:
1.78 anton 9688: It is easy to see that this can become quite tiring.
1.52 anton 9689:
1.78 anton 9690: Moreover, it is not very readable, because seeing a
9691: @code{cell+} tells us neither which kind of structure is
9692: accessed nor what field is accessed; we have to somehow infer the kind
9693: of structure, and then look up in the documentation, which field of
9694: that structure corresponds to that offset.
1.53 anton 9695:
1.78 anton 9696: Finally, this kind of address arithmetic also causes maintenance
9697: troubles: If you add or delete a field somewhere in the middle of the
9698: structure, you have to find and change all computations for the fields
9699: afterwards.
1.52 anton 9700:
1.78 anton 9701: So, instead of using @code{cell+} and friends directly, how
9702: about storing the offsets in constants:
1.52 anton 9703:
1.78 anton 9704: @example
9705: 0 constant a-offset
9706: 0 float+ constant b-offset
9707: 0 float+ cell+ faligned c-offset
9708: @end example
1.64 pazsan 9709:
1.78 anton 9710: Now we can get the address of field @code{x} with @code{x-offset
9711: +}. This is much better in all respects. Of course, you still
9712: have to change all later offset definitions if you add a field. You can
9713: fix this by declaring the offsets in the following way:
1.57 anton 9714:
1.78 anton 9715: @example
9716: 0 constant a-offset
9717: a-offset float+ constant b-offset
9718: b-offset cell+ faligned constant c-offset
9719: @end example
1.57 anton 9720:
1.78 anton 9721: Since we always use the offsets with @code{+}, we could use a defining
9722: word @code{cfield} that includes the @code{+} in the action of the
9723: defined word:
1.64 pazsan 9724:
1.78 anton 9725: @example
9726: : cfield ( n "name" -- )
9727: create ,
9728: does> ( name execution: addr1 -- addr2 )
9729: @@ + ;
1.64 pazsan 9730:
1.78 anton 9731: 0 cfield a
9732: 0 a float+ cfield b
9733: 0 b cell+ faligned cfield c
9734: @end example
1.64 pazsan 9735:
1.78 anton 9736: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9737:
1.78 anton 9738: The structure field words now can be used quite nicely. However,
9739: their definition is still a bit cumbersome: We have to repeat the
9740: name, the information about size and alignment is distributed before
9741: and after the field definitions etc. The structure package presented
9742: here addresses these problems.
1.64 pazsan 9743:
1.78 anton 9744: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9745: @subsection Structure Usage
9746: @cindex structure usage
1.57 anton 9747:
1.78 anton 9748: @cindex @code{field} usage
9749: @cindex @code{struct} usage
9750: @cindex @code{end-struct} usage
9751: You can define a structure for a (data-less) linked list with:
1.57 anton 9752: @example
1.78 anton 9753: struct
9754: cell% field list-next
9755: end-struct list%
1.57 anton 9756: @end example
9757:
1.78 anton 9758: With the address of the list node on the stack, you can compute the
9759: address of the field that contains the address of the next node with
9760: @code{list-next}. E.g., you can determine the length of a list
9761: with:
1.57 anton 9762:
9763: @example
1.78 anton 9764: : list-length ( list -- n )
9765: \ "list" is a pointer to the first element of a linked list
9766: \ "n" is the length of the list
9767: 0 BEGIN ( list1 n1 )
9768: over
9769: WHILE ( list1 n1 )
9770: 1+ swap list-next @@ swap
9771: REPEAT
9772: nip ;
1.57 anton 9773: @end example
9774:
1.78 anton 9775: You can reserve memory for a list node in the dictionary with
9776: @code{list% %allot}, which leaves the address of the list node on the
9777: stack. For the equivalent allocation on the heap you can use @code{list%
9778: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9779: use @code{list% %allocate}). You can get the the size of a list
9780: node with @code{list% %size} and its alignment with @code{list%
9781: %alignment}.
9782:
9783: Note that in ANS Forth the body of a @code{create}d word is
9784: @code{aligned} but not necessarily @code{faligned};
9785: therefore, if you do a:
1.57 anton 9786:
9787: @example
1.78 anton 9788: create @emph{name} foo% %allot drop
1.57 anton 9789: @end example
9790:
1.78 anton 9791: @noindent
9792: then the memory alloted for @code{foo%} is guaranteed to start at the
9793: body of @code{@emph{name}} only if @code{foo%} contains only character,
9794: cell and double fields. Therefore, if your structure contains floats,
9795: better use
1.57 anton 9796:
9797: @example
1.78 anton 9798: foo% %allot constant @emph{name}
1.57 anton 9799: @end example
9800:
1.78 anton 9801: @cindex structures containing structures
9802: You can include a structure @code{foo%} as a field of
9803: another structure, like this:
1.65 anton 9804: @example
1.78 anton 9805: struct
9806: ...
9807: foo% field ...
9808: ...
9809: end-struct ...
1.65 anton 9810: @end example
1.52 anton 9811:
1.78 anton 9812: @cindex structure extension
9813: @cindex extended records
9814: Instead of starting with an empty structure, you can extend an
9815: existing structure. E.g., a plain linked list without data, as defined
9816: above, is hardly useful; You can extend it to a linked list of integers,
9817: like this:@footnote{This feature is also known as @emph{extended
9818: records}. It is the main innovation in the Oberon language; in other
9819: words, adding this feature to Modula-2 led Wirth to create a new
9820: language, write a new compiler etc. Adding this feature to Forth just
9821: required a few lines of code.}
1.52 anton 9822:
1.78 anton 9823: @example
9824: list%
9825: cell% field intlist-int
9826: end-struct intlist%
9827: @end example
1.55 anton 9828:
1.78 anton 9829: @code{intlist%} is a structure with two fields:
9830: @code{list-next} and @code{intlist-int}.
1.55 anton 9831:
1.78 anton 9832: @cindex structures containing arrays
9833: You can specify an array type containing @emph{n} elements of
9834: type @code{foo%} like this:
1.55 anton 9835:
9836: @example
1.78 anton 9837: foo% @emph{n} *
1.56 anton 9838: @end example
1.55 anton 9839:
1.78 anton 9840: You can use this array type in any place where you can use a normal
9841: type, e.g., when defining a @code{field}, or with
9842: @code{%allot}.
9843:
9844: @cindex first field optimization
9845: The first field is at the base address of a structure and the word for
9846: this field (e.g., @code{list-next}) actually does not change the address
9847: on the stack. You may be tempted to leave it away in the interest of
9848: run-time and space efficiency. This is not necessary, because the
9849: structure package optimizes this case: If you compile a first-field
9850: words, no code is generated. So, in the interest of readability and
9851: maintainability you should include the word for the field when accessing
9852: the field.
1.52 anton 9853:
9854:
1.78 anton 9855: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9856: @subsection Structure Naming Convention
9857: @cindex structure naming convention
1.52 anton 9858:
1.78 anton 9859: The field names that come to (my) mind are often quite generic, and,
9860: if used, would cause frequent name clashes. E.g., many structures
9861: probably contain a @code{counter} field. The structure names
9862: that come to (my) mind are often also the logical choice for the names
9863: of words that create such a structure.
1.52 anton 9864:
1.78 anton 9865: Therefore, I have adopted the following naming conventions:
1.52 anton 9866:
1.78 anton 9867: @itemize @bullet
9868: @cindex field naming convention
9869: @item
9870: The names of fields are of the form
9871: @code{@emph{struct}-@emph{field}}, where
9872: @code{@emph{struct}} is the basic name of the structure, and
9873: @code{@emph{field}} is the basic name of the field. You can
9874: think of field words as converting the (address of the)
9875: structure into the (address of the) field.
1.52 anton 9876:
1.78 anton 9877: @cindex structure naming convention
9878: @item
9879: The names of structures are of the form
9880: @code{@emph{struct}%}, where
9881: @code{@emph{struct}} is the basic name of the structure.
9882: @end itemize
1.52 anton 9883:
1.78 anton 9884: This naming convention does not work that well for fields of extended
9885: structures; e.g., the integer list structure has a field
9886: @code{intlist-int}, but has @code{list-next}, not
9887: @code{intlist-next}.
1.53 anton 9888:
1.78 anton 9889: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9890: @subsection Structure Implementation
9891: @cindex structure implementation
9892: @cindex implementation of structures
1.52 anton 9893:
1.78 anton 9894: The central idea in the implementation is to pass the data about the
9895: structure being built on the stack, not in some global
9896: variable. Everything else falls into place naturally once this design
9897: decision is made.
1.53 anton 9898:
1.78 anton 9899: The type description on the stack is of the form @emph{align
9900: size}. Keeping the size on the top-of-stack makes dealing with arrays
9901: very simple.
1.53 anton 9902:
1.78 anton 9903: @code{field} is a defining word that uses @code{Create}
9904: and @code{DOES>}. The body of the field contains the offset
9905: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9906:
9907: @example
1.78 anton 9908: @@ +
1.53 anton 9909: @end example
9910:
1.78 anton 9911: @noindent
9912: i.e., add the offset to the address, giving the stack effect
9913: @i{addr1 -- addr2} for a field.
9914:
9915: @cindex first field optimization, implementation
9916: This simple structure is slightly complicated by the optimization
9917: for fields with offset 0, which requires a different
9918: @code{DOES>}-part (because we cannot rely on there being
9919: something on the stack if such a field is invoked during
9920: compilation). Therefore, we put the different @code{DOES>}-parts
9921: in separate words, and decide which one to invoke based on the
9922: offset. For a zero offset, the field is basically a noop; it is
9923: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9924:
1.78 anton 9925: @node Structure Glossary, , Structure Implementation, Structures
9926: @subsection Structure Glossary
9927: @cindex structure glossary
1.53 anton 9928:
1.5 anton 9929:
1.78 anton 9930: doc-%align
9931: doc-%alignment
9932: doc-%alloc
9933: doc-%allocate
9934: doc-%allot
9935: doc-cell%
9936: doc-char%
9937: doc-dfloat%
9938: doc-double%
9939: doc-end-struct
9940: doc-field
9941: doc-float%
9942: doc-naligned
9943: doc-sfloat%
9944: doc-%size
9945: doc-struct
1.54 anton 9946:
9947:
1.26 crook 9948: @c -------------------------------------------------------------
1.78 anton 9949: @node Object-oriented Forth, Programming Tools, Structures, Words
9950: @section Object-oriented Forth
9951:
9952: Gforth comes with three packages for object-oriented programming:
9953: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9954: is preloaded, so you have to @code{include} them before use. The most
9955: important differences between these packages (and others) are discussed
9956: in @ref{Comparison with other object models}. All packages are written
9957: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9958:
1.78 anton 9959: @menu
9960: * Why object-oriented programming?::
9961: * Object-Oriented Terminology::
9962: * Objects::
9963: * OOF::
9964: * Mini-OOF::
9965: * Comparison with other object models::
9966: @end menu
1.5 anton 9967:
1.78 anton 9968: @c ----------------------------------------------------------------
9969: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9970: @subsection Why object-oriented programming?
9971: @cindex object-oriented programming motivation
9972: @cindex motivation for object-oriented programming
1.44 crook 9973:
1.78 anton 9974: Often we have to deal with several data structures (@emph{objects}),
9975: that have to be treated similarly in some respects, but differently in
9976: others. Graphical objects are the textbook example: circles, triangles,
9977: dinosaurs, icons, and others, and we may want to add more during program
9978: development. We want to apply some operations to any graphical object,
9979: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9980: has to do something different for every kind of object.
9981: @comment TODO add some other operations eg perimeter, area
9982: @comment and tie in to concrete examples later..
1.5 anton 9983:
1.78 anton 9984: We could implement @code{draw} as a big @code{CASE}
9985: control structure that executes the appropriate code depending on the
9986: kind of object to be drawn. This would be not be very elegant, and,
9987: moreover, we would have to change @code{draw} every time we add
9988: a new kind of graphical object (say, a spaceship).
1.44 crook 9989:
1.78 anton 9990: What we would rather do is: When defining spaceships, we would tell
9991: the system: ``Here's how you @code{draw} a spaceship; you figure
9992: out the rest''.
1.5 anton 9993:
1.78 anton 9994: This is the problem that all systems solve that (rightfully) call
9995: themselves object-oriented; the object-oriented packages presented here
9996: solve this problem (and not much else).
9997: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9998:
1.78 anton 9999: @c ------------------------------------------------------------------------
10000: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10001: @subsection Object-Oriented Terminology
10002: @cindex object-oriented terminology
10003: @cindex terminology for object-oriented programming
1.5 anton 10004:
1.78 anton 10005: This section is mainly for reference, so you don't have to understand
10006: all of it right away. The terminology is mainly Smalltalk-inspired. In
10007: short:
1.44 crook 10008:
1.78 anton 10009: @table @emph
10010: @cindex class
10011: @item class
10012: a data structure definition with some extras.
1.5 anton 10013:
1.78 anton 10014: @cindex object
10015: @item object
10016: an instance of the data structure described by the class definition.
1.5 anton 10017:
1.78 anton 10018: @cindex instance variables
10019: @item instance variables
10020: fields of the data structure.
1.5 anton 10021:
1.78 anton 10022: @cindex selector
10023: @cindex method selector
10024: @cindex virtual function
10025: @item selector
10026: (or @emph{method selector}) a word (e.g.,
10027: @code{draw}) that performs an operation on a variety of data
10028: structures (classes). A selector describes @emph{what} operation to
10029: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10030:
1.78 anton 10031: @cindex method
10032: @item method
10033: the concrete definition that performs the operation
10034: described by the selector for a specific class. A method specifies
10035: @emph{how} the operation is performed for a specific class.
1.5 anton 10036:
1.78 anton 10037: @cindex selector invocation
10038: @cindex message send
10039: @cindex invoking a selector
10040: @item selector invocation
10041: a call of a selector. One argument of the call (the TOS (top-of-stack))
10042: is used for determining which method is used. In Smalltalk terminology:
10043: a message (consisting of the selector and the other arguments) is sent
10044: to the object.
1.5 anton 10045:
1.78 anton 10046: @cindex receiving object
10047: @item receiving object
10048: the object used for determining the method executed by a selector
10049: invocation. In the @file{objects.fs} model, it is the object that is on
10050: the TOS when the selector is invoked. (@emph{Receiving} comes from
10051: the Smalltalk @emph{message} terminology.)
1.5 anton 10052:
1.78 anton 10053: @cindex child class
10054: @cindex parent class
10055: @cindex inheritance
10056: @item child class
10057: a class that has (@emph{inherits}) all properties (instance variables,
10058: selectors, methods) from a @emph{parent class}. In Smalltalk
10059: terminology: The subclass inherits from the superclass. In C++
10060: terminology: The derived class inherits from the base class.
1.5 anton 10061:
1.78 anton 10062: @end table
1.5 anton 10063:
1.78 anton 10064: @c If you wonder about the message sending terminology, it comes from
10065: @c a time when each object had it's own task and objects communicated via
10066: @c message passing; eventually the Smalltalk developers realized that
10067: @c they can do most things through simple (indirect) calls. They kept the
10068: @c terminology.
1.5 anton 10069:
1.78 anton 10070: @c --------------------------------------------------------------
10071: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10072: @subsection The @file{objects.fs} model
10073: @cindex objects
10074: @cindex object-oriented programming
1.26 crook 10075:
1.78 anton 10076: @cindex @file{objects.fs}
10077: @cindex @file{oof.fs}
1.26 crook 10078:
1.78 anton 10079: This section describes the @file{objects.fs} package. This material also
10080: has been published in M. Anton Ertl,
10081: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10082: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10083: 37--43.
10084: @c McKewan's and Zsoter's packages
1.26 crook 10085:
1.78 anton 10086: This section assumes that you have read @ref{Structures}.
1.5 anton 10087:
1.78 anton 10088: The techniques on which this model is based have been used to implement
10089: the parser generator, Gray, and have also been used in Gforth for
10090: implementing the various flavours of word lists (hashed or not,
10091: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10092:
10093:
1.26 crook 10094: @menu
1.78 anton 10095: * Properties of the Objects model::
10096: * Basic Objects Usage::
10097: * The Objects base class::
10098: * Creating objects::
10099: * Object-Oriented Programming Style::
10100: * Class Binding::
10101: * Method conveniences::
10102: * Classes and Scoping::
10103: * Dividing classes::
10104: * Object Interfaces::
10105: * Objects Implementation::
10106: * Objects Glossary::
1.26 crook 10107: @end menu
1.5 anton 10108:
1.78 anton 10109: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10110:
1.78 anton 10111: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10112: @subsubsection Properties of the @file{objects.fs} model
10113: @cindex @file{objects.fs} properties
1.5 anton 10114:
1.78 anton 10115: @itemize @bullet
10116: @item
10117: It is straightforward to pass objects on the stack. Passing
10118: selectors on the stack is a little less convenient, but possible.
1.44 crook 10119:
1.78 anton 10120: @item
10121: Objects are just data structures in memory, and are referenced by their
10122: address. You can create words for objects with normal defining words
10123: like @code{constant}. Likewise, there is no difference between instance
10124: variables that contain objects and those that contain other data.
1.5 anton 10125:
1.78 anton 10126: @item
10127: Late binding is efficient and easy to use.
1.44 crook 10128:
1.78 anton 10129: @item
10130: It avoids parsing, and thus avoids problems with state-smartness
10131: and reduced extensibility; for convenience there are a few parsing
10132: words, but they have non-parsing counterparts. There are also a few
10133: defining words that parse. This is hard to avoid, because all standard
10134: defining words parse (except @code{:noname}); however, such
10135: words are not as bad as many other parsing words, because they are not
10136: state-smart.
1.5 anton 10137:
1.78 anton 10138: @item
10139: It does not try to incorporate everything. It does a few things and does
10140: them well (IMO). In particular, this model was not designed to support
10141: information hiding (although it has features that may help); you can use
10142: a separate package for achieving this.
1.5 anton 10143:
1.78 anton 10144: @item
10145: It is layered; you don't have to learn and use all features to use this
10146: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10147: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10148: are optional and independent of each other.
1.5 anton 10149:
1.78 anton 10150: @item
10151: An implementation in ANS Forth is available.
1.5 anton 10152:
1.78 anton 10153: @end itemize
1.5 anton 10154:
1.44 crook 10155:
1.78 anton 10156: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10157: @subsubsection Basic @file{objects.fs} Usage
10158: @cindex basic objects usage
10159: @cindex objects, basic usage
1.5 anton 10160:
1.78 anton 10161: You can define a class for graphical objects like this:
1.44 crook 10162:
1.78 anton 10163: @cindex @code{class} usage
10164: @cindex @code{end-class} usage
10165: @cindex @code{selector} usage
1.5 anton 10166: @example
1.78 anton 10167: object class \ "object" is the parent class
10168: selector draw ( x y graphical -- )
10169: end-class graphical
10170: @end example
10171:
10172: This code defines a class @code{graphical} with an
10173: operation @code{draw}. We can perform the operation
10174: @code{draw} on any @code{graphical} object, e.g.:
10175:
10176: @example
10177: 100 100 t-rex draw
1.26 crook 10178: @end example
1.5 anton 10179:
1.78 anton 10180: @noindent
10181: where @code{t-rex} is a word (say, a constant) that produces a
10182: graphical object.
10183:
10184: @comment TODO add a 2nd operation eg perimeter.. and use for
10185: @comment a concrete example
1.5 anton 10186:
1.78 anton 10187: @cindex abstract class
10188: How do we create a graphical object? With the present definitions,
10189: we cannot create a useful graphical object. The class
10190: @code{graphical} describes graphical objects in general, but not
10191: any concrete graphical object type (C++ users would call it an
10192: @emph{abstract class}); e.g., there is no method for the selector
10193: @code{draw} in the class @code{graphical}.
1.5 anton 10194:
1.78 anton 10195: For concrete graphical objects, we define child classes of the
10196: class @code{graphical}, e.g.:
1.5 anton 10197:
1.78 anton 10198: @cindex @code{overrides} usage
10199: @cindex @code{field} usage in class definition
1.26 crook 10200: @example
1.78 anton 10201: graphical class \ "graphical" is the parent class
10202: cell% field circle-radius
1.5 anton 10203:
1.78 anton 10204: :noname ( x y circle -- )
10205: circle-radius @@ draw-circle ;
10206: overrides draw
1.5 anton 10207:
1.78 anton 10208: :noname ( n-radius circle -- )
10209: circle-radius ! ;
10210: overrides construct
1.5 anton 10211:
1.78 anton 10212: end-class circle
10213: @end example
1.44 crook 10214:
1.78 anton 10215: Here we define a class @code{circle} as a child of @code{graphical},
10216: with field @code{circle-radius} (which behaves just like a field
10217: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10218: for the selectors @code{draw} and @code{construct} (@code{construct} is
10219: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10220:
1.78 anton 10221: Now we can create a circle on the heap (i.e.,
10222: @code{allocate}d memory) with:
1.44 crook 10223:
1.78 anton 10224: @cindex @code{heap-new} usage
1.5 anton 10225: @example
1.78 anton 10226: 50 circle heap-new constant my-circle
1.5 anton 10227: @end example
10228:
1.78 anton 10229: @noindent
10230: @code{heap-new} invokes @code{construct}, thus
10231: initializing the field @code{circle-radius} with 50. We can draw
10232: this new circle at (100,100) with:
1.5 anton 10233:
10234: @example
1.78 anton 10235: 100 100 my-circle draw
1.5 anton 10236: @end example
10237:
1.78 anton 10238: @cindex selector invocation, restrictions
10239: @cindex class definition, restrictions
10240: Note: You can only invoke a selector if the object on the TOS
10241: (the receiving object) belongs to the class where the selector was
10242: defined or one of its descendents; e.g., you can invoke
10243: @code{draw} only for objects belonging to @code{graphical}
10244: or its descendents (e.g., @code{circle}). Immediately before
10245: @code{end-class}, the search order has to be the same as
10246: immediately after @code{class}.
10247:
10248: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10249: @subsubsection The @file{object.fs} base class
10250: @cindex @code{object} class
10251:
10252: When you define a class, you have to specify a parent class. So how do
10253: you start defining classes? There is one class available from the start:
10254: @code{object}. It is ancestor for all classes and so is the
10255: only class that has no parent. It has two selectors: @code{construct}
10256: and @code{print}.
10257:
10258: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10259: @subsubsection Creating objects
10260: @cindex creating objects
10261: @cindex object creation
10262: @cindex object allocation options
10263:
10264: @cindex @code{heap-new} discussion
10265: @cindex @code{dict-new} discussion
10266: @cindex @code{construct} discussion
10267: You can create and initialize an object of a class on the heap with
10268: @code{heap-new} ( ... class -- object ) and in the dictionary
10269: (allocation with @code{allot}) with @code{dict-new} (
10270: ... class -- object ). Both words invoke @code{construct}, which
10271: consumes the stack items indicated by "..." above.
10272:
10273: @cindex @code{init-object} discussion
10274: @cindex @code{class-inst-size} discussion
10275: If you want to allocate memory for an object yourself, you can get its
10276: alignment and size with @code{class-inst-size 2@@} ( class --
10277: align size ). Once you have memory for an object, you can initialize
10278: it with @code{init-object} ( ... class object -- );
10279: @code{construct} does only a part of the necessary work.
10280:
10281: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10282: @subsubsection Object-Oriented Programming Style
10283: @cindex object-oriented programming style
10284: @cindex programming style, object-oriented
1.5 anton 10285:
1.78 anton 10286: This section is not exhaustive.
1.5 anton 10287:
1.78 anton 10288: @cindex stack effects of selectors
10289: @cindex selectors and stack effects
10290: In general, it is a good idea to ensure that all methods for the
10291: same selector have the same stack effect: when you invoke a selector,
10292: you often have no idea which method will be invoked, so, unless all
10293: methods have the same stack effect, you will not know the stack effect
10294: of the selector invocation.
1.5 anton 10295:
1.78 anton 10296: One exception to this rule is methods for the selector
10297: @code{construct}. We know which method is invoked, because we
10298: specify the class to be constructed at the same place. Actually, I
10299: defined @code{construct} as a selector only to give the users a
10300: convenient way to specify initialization. The way it is used, a
10301: mechanism different from selector invocation would be more natural
10302: (but probably would take more code and more space to explain).
1.5 anton 10303:
1.78 anton 10304: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10305: @subsubsection Class Binding
10306: @cindex class binding
10307: @cindex early binding
1.5 anton 10308:
1.78 anton 10309: @cindex late binding
10310: Normal selector invocations determine the method at run-time depending
10311: on the class of the receiving object. This run-time selection is called
10312: @i{late binding}.
1.5 anton 10313:
1.78 anton 10314: Sometimes it's preferable to invoke a different method. For example,
10315: you might want to use the simple method for @code{print}ing
10316: @code{object}s instead of the possibly long-winded @code{print} method
10317: of the receiver class. You can achieve this by replacing the invocation
10318: of @code{print} with:
1.5 anton 10319:
1.78 anton 10320: @cindex @code{[bind]} usage
1.5 anton 10321: @example
1.78 anton 10322: [bind] object print
1.5 anton 10323: @end example
10324:
1.78 anton 10325: @noindent
10326: in compiled code or:
10327:
10328: @cindex @code{bind} usage
1.5 anton 10329: @example
1.78 anton 10330: bind object print
1.5 anton 10331: @end example
10332:
1.78 anton 10333: @cindex class binding, alternative to
10334: @noindent
10335: in interpreted code. Alternatively, you can define the method with a
10336: name (e.g., @code{print-object}), and then invoke it through the
10337: name. Class binding is just a (often more convenient) way to achieve
10338: the same effect; it avoids name clutter and allows you to invoke
10339: methods directly without naming them first.
1.5 anton 10340:
1.78 anton 10341: @cindex superclass binding
10342: @cindex parent class binding
10343: A frequent use of class binding is this: When we define a method
10344: for a selector, we often want the method to do what the selector does
10345: in the parent class, and a little more. There is a special word for
10346: this purpose: @code{[parent]}; @code{[parent]
10347: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10348: selector}}, where @code{@emph{parent}} is the parent
10349: class of the current class. E.g., a method definition might look like:
1.44 crook 10350:
1.78 anton 10351: @cindex @code{[parent]} usage
10352: @example
10353: :noname
10354: dup [parent] foo \ do parent's foo on the receiving object
10355: ... \ do some more
10356: ; overrides foo
10357: @end example
1.6 pazsan 10358:
1.78 anton 10359: @cindex class binding as optimization
10360: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10361: March 1997), Andrew McKewan presents class binding as an optimization
10362: technique. I recommend not using it for this purpose unless you are in
10363: an emergency. Late binding is pretty fast with this model anyway, so the
10364: benefit of using class binding is small; the cost of using class binding
10365: where it is not appropriate is reduced maintainability.
1.44 crook 10366:
1.78 anton 10367: While we are at programming style questions: You should bind
10368: selectors only to ancestor classes of the receiving object. E.g., say,
10369: you know that the receiving object is of class @code{foo} or its
10370: descendents; then you should bind only to @code{foo} and its
10371: ancestors.
1.12 anton 10372:
1.78 anton 10373: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10374: @subsubsection Method conveniences
10375: @cindex method conveniences
1.44 crook 10376:
1.78 anton 10377: In a method you usually access the receiving object pretty often. If
10378: you define the method as a plain colon definition (e.g., with
10379: @code{:noname}), you may have to do a lot of stack
10380: gymnastics. To avoid this, you can define the method with @code{m:
10381: ... ;m}. E.g., you could define the method for
10382: @code{draw}ing a @code{circle} with
1.6 pazsan 10383:
1.78 anton 10384: @cindex @code{this} usage
10385: @cindex @code{m:} usage
10386: @cindex @code{;m} usage
10387: @example
10388: m: ( x y circle -- )
10389: ( x y ) this circle-radius @@ draw-circle ;m
10390: @end example
1.6 pazsan 10391:
1.78 anton 10392: @cindex @code{exit} in @code{m: ... ;m}
10393: @cindex @code{exitm} discussion
10394: @cindex @code{catch} in @code{m: ... ;m}
10395: When this method is executed, the receiver object is removed from the
10396: stack; you can access it with @code{this} (admittedly, in this
10397: example the use of @code{m: ... ;m} offers no advantage). Note
10398: that I specify the stack effect for the whole method (i.e. including
10399: the receiver object), not just for the code between @code{m:}
10400: and @code{;m}. You cannot use @code{exit} in
10401: @code{m:...;m}; instead, use
10402: @code{exitm}.@footnote{Moreover, for any word that calls
10403: @code{catch} and was defined before loading
10404: @code{objects.fs}, you have to redefine it like I redefined
10405: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10406:
1.78 anton 10407: @cindex @code{inst-var} usage
10408: You will frequently use sequences of the form @code{this
10409: @emph{field}} (in the example above: @code{this
10410: circle-radius}). If you use the field only in this way, you can
10411: define it with @code{inst-var} and eliminate the
10412: @code{this} before the field name. E.g., the @code{circle}
10413: class above could also be defined with:
1.6 pazsan 10414:
1.78 anton 10415: @example
10416: graphical class
10417: cell% inst-var radius
1.6 pazsan 10418:
1.78 anton 10419: m: ( x y circle -- )
10420: radius @@ draw-circle ;m
10421: overrides draw
1.6 pazsan 10422:
1.78 anton 10423: m: ( n-radius circle -- )
10424: radius ! ;m
10425: overrides construct
1.6 pazsan 10426:
1.78 anton 10427: end-class circle
10428: @end example
1.6 pazsan 10429:
1.78 anton 10430: @code{radius} can only be used in @code{circle} and its
10431: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10432:
1.78 anton 10433: @cindex @code{inst-value} usage
10434: You can also define fields with @code{inst-value}, which is
10435: to @code{inst-var} what @code{value} is to
10436: @code{variable}. You can change the value of such a field with
10437: @code{[to-inst]}. E.g., we could also define the class
10438: @code{circle} like this:
1.44 crook 10439:
1.78 anton 10440: @example
10441: graphical class
10442: inst-value radius
1.6 pazsan 10443:
1.78 anton 10444: m: ( x y circle -- )
10445: radius draw-circle ;m
10446: overrides draw
1.44 crook 10447:
1.78 anton 10448: m: ( n-radius circle -- )
10449: [to-inst] radius ;m
10450: overrides construct
1.6 pazsan 10451:
1.78 anton 10452: end-class circle
10453: @end example
1.6 pazsan 10454:
1.78 anton 10455: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10456:
1.78 anton 10457: @c Finally, you can define named methods with @code{:m}. One use of this
10458: @c feature is the definition of words that occur only in one class and are
10459: @c not intended to be overridden, but which still need method context
10460: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10461: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10462:
10463:
1.78 anton 10464: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10465: @subsubsection Classes and Scoping
10466: @cindex classes and scoping
10467: @cindex scoping and classes
1.6 pazsan 10468:
1.78 anton 10469: Inheritance is frequent, unlike structure extension. This exacerbates
10470: the problem with the field name convention (@pxref{Structure Naming
10471: Convention}): One always has to remember in which class the field was
10472: originally defined; changing a part of the class structure would require
10473: changes for renaming in otherwise unaffected code.
1.6 pazsan 10474:
1.78 anton 10475: @cindex @code{inst-var} visibility
10476: @cindex @code{inst-value} visibility
10477: To solve this problem, I added a scoping mechanism (which was not in my
10478: original charter): A field defined with @code{inst-var} (or
10479: @code{inst-value}) is visible only in the class where it is defined and in
10480: the descendent classes of this class. Using such fields only makes
10481: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10482:
1.78 anton 10483: This scoping mechanism allows us to use the unadorned field name,
10484: because name clashes with unrelated words become much less likely.
1.6 pazsan 10485:
1.78 anton 10486: @cindex @code{protected} discussion
10487: @cindex @code{private} discussion
10488: Once we have this mechanism, we can also use it for controlling the
10489: visibility of other words: All words defined after
10490: @code{protected} are visible only in the current class and its
10491: descendents. @code{public} restores the compilation
10492: (i.e. @code{current}) word list that was in effect before. If you
10493: have several @code{protected}s without an intervening
10494: @code{public} or @code{set-current}, @code{public}
10495: will restore the compilation word list in effect before the first of
10496: these @code{protected}s.
1.6 pazsan 10497:
1.78 anton 10498: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10499: @subsubsection Dividing classes
10500: @cindex Dividing classes
10501: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10502:
1.78 anton 10503: You may want to do the definition of methods separate from the
10504: definition of the class, its selectors, fields, and instance variables,
10505: i.e., separate the implementation from the definition. You can do this
10506: in the following way:
1.6 pazsan 10507:
1.78 anton 10508: @example
10509: graphical class
10510: inst-value radius
10511: end-class circle
1.6 pazsan 10512:
1.78 anton 10513: ... \ do some other stuff
1.6 pazsan 10514:
1.78 anton 10515: circle methods \ now we are ready
1.44 crook 10516:
1.78 anton 10517: m: ( x y circle -- )
10518: radius draw-circle ;m
10519: overrides draw
1.6 pazsan 10520:
1.78 anton 10521: m: ( n-radius circle -- )
10522: [to-inst] radius ;m
10523: overrides construct
1.44 crook 10524:
1.78 anton 10525: end-methods
10526: @end example
1.7 pazsan 10527:
1.78 anton 10528: You can use several @code{methods}...@code{end-methods} sections. The
10529: only things you can do to the class in these sections are: defining
10530: methods, and overriding the class's selectors. You must not define new
10531: selectors or fields.
1.7 pazsan 10532:
1.78 anton 10533: Note that you often have to override a selector before using it. In
10534: particular, you usually have to override @code{construct} with a new
10535: method before you can invoke @code{heap-new} and friends. E.g., you
10536: must not create a circle before the @code{overrides construct} sequence
10537: in the example above.
1.7 pazsan 10538:
1.78 anton 10539: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10540: @subsubsection Object Interfaces
10541: @cindex object interfaces
10542: @cindex interfaces for objects
1.7 pazsan 10543:
1.78 anton 10544: In this model you can only call selectors defined in the class of the
10545: receiving objects or in one of its ancestors. If you call a selector
10546: with a receiving object that is not in one of these classes, the
10547: result is undefined; if you are lucky, the program crashes
10548: immediately.
1.7 pazsan 10549:
1.78 anton 10550: @cindex selectors common to hardly-related classes
10551: Now consider the case when you want to have a selector (or several)
10552: available in two classes: You would have to add the selector to a
10553: common ancestor class, in the worst case to @code{object}. You
10554: may not want to do this, e.g., because someone else is responsible for
10555: this ancestor class.
1.7 pazsan 10556:
1.78 anton 10557: The solution for this problem is interfaces. An interface is a
10558: collection of selectors. If a class implements an interface, the
10559: selectors become available to the class and its descendents. A class
10560: can implement an unlimited number of interfaces. For the problem
10561: discussed above, we would define an interface for the selector(s), and
10562: both classes would implement the interface.
1.7 pazsan 10563:
1.78 anton 10564: As an example, consider an interface @code{storage} for
10565: writing objects to disk and getting them back, and a class
10566: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10567:
1.78 anton 10568: @cindex @code{interface} usage
10569: @cindex @code{end-interface} usage
10570: @cindex @code{implementation} usage
10571: @example
10572: interface
10573: selector write ( file object -- )
10574: selector read1 ( file object -- )
10575: end-interface storage
1.13 pazsan 10576:
1.78 anton 10577: bar class
10578: storage implementation
1.13 pazsan 10579:
1.78 anton 10580: ... overrides write
10581: ... overrides read1
10582: ...
10583: end-class foo
10584: @end example
1.13 pazsan 10585:
1.78 anton 10586: @noindent
10587: (I would add a word @code{read} @i{( file -- object )} that uses
10588: @code{read1} internally, but that's beyond the point illustrated
10589: here.)
1.13 pazsan 10590:
1.78 anton 10591: Note that you cannot use @code{protected} in an interface; and
10592: of course you cannot define fields.
1.13 pazsan 10593:
1.78 anton 10594: In the Neon model, all selectors are available for all classes;
10595: therefore it does not need interfaces. The price you pay in this model
10596: is slower late binding, and therefore, added complexity to avoid late
10597: binding.
1.13 pazsan 10598:
1.78 anton 10599: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10600: @subsubsection @file{objects.fs} Implementation
10601: @cindex @file{objects.fs} implementation
1.13 pazsan 10602:
1.78 anton 10603: @cindex @code{object-map} discussion
10604: An object is a piece of memory, like one of the data structures
10605: described with @code{struct...end-struct}. It has a field
10606: @code{object-map} that points to the method map for the object's
10607: class.
1.13 pazsan 10608:
1.78 anton 10609: @cindex method map
10610: @cindex virtual function table
10611: The @emph{method map}@footnote{This is Self terminology; in C++
10612: terminology: virtual function table.} is an array that contains the
10613: execution tokens (@i{xt}s) of the methods for the object's class. Each
10614: selector contains an offset into a method map.
1.13 pazsan 10615:
1.78 anton 10616: @cindex @code{selector} implementation, class
10617: @code{selector} is a defining word that uses
10618: @code{CREATE} and @code{DOES>}. The body of the
10619: selector contains the offset; the @code{DOES>} action for a
10620: class selector is, basically:
1.8 pazsan 10621:
10622: @example
1.78 anton 10623: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10624: @end example
10625:
1.78 anton 10626: Since @code{object-map} is the first field of the object, it
10627: does not generate any code. As you can see, calling a selector has a
10628: small, constant cost.
1.26 crook 10629:
1.78 anton 10630: @cindex @code{current-interface} discussion
10631: @cindex class implementation and representation
10632: A class is basically a @code{struct} combined with a method
10633: map. During the class definition the alignment and size of the class
10634: are passed on the stack, just as with @code{struct}s, so
10635: @code{field} can also be used for defining class
10636: fields. However, passing more items on the stack would be
10637: inconvenient, so @code{class} builds a data structure in memory,
10638: which is accessed through the variable
10639: @code{current-interface}. After its definition is complete, the
10640: class is represented on the stack by a pointer (e.g., as parameter for
10641: a child class definition).
1.26 crook 10642:
1.78 anton 10643: A new class starts off with the alignment and size of its parent,
10644: and a copy of the parent's method map. Defining new fields extends the
10645: size and alignment; likewise, defining new selectors extends the
10646: method map. @code{overrides} just stores a new @i{xt} in the method
10647: map at the offset given by the selector.
1.13 pazsan 10648:
1.78 anton 10649: @cindex class binding, implementation
10650: Class binding just gets the @i{xt} at the offset given by the selector
10651: from the class's method map and @code{compile,}s (in the case of
10652: @code{[bind]}) it.
1.13 pazsan 10653:
1.78 anton 10654: @cindex @code{this} implementation
10655: @cindex @code{catch} and @code{this}
10656: @cindex @code{this} and @code{catch}
10657: I implemented @code{this} as a @code{value}. At the
10658: start of an @code{m:...;m} method the old @code{this} is
10659: stored to the return stack and restored at the end; and the object on
10660: the TOS is stored @code{TO this}. This technique has one
10661: disadvantage: If the user does not leave the method via
10662: @code{;m}, but via @code{throw} or @code{exit},
10663: @code{this} is not restored (and @code{exit} may
10664: crash). To deal with the @code{throw} problem, I have redefined
10665: @code{catch} to save and restore @code{this}; the same
10666: should be done with any word that can catch an exception. As for
10667: @code{exit}, I simply forbid it (as a replacement, there is
10668: @code{exitm}).
1.13 pazsan 10669:
1.78 anton 10670: @cindex @code{inst-var} implementation
10671: @code{inst-var} is just the same as @code{field}, with
10672: a different @code{DOES>} action:
1.13 pazsan 10673: @example
1.78 anton 10674: @@ this +
1.8 pazsan 10675: @end example
1.78 anton 10676: Similar for @code{inst-value}.
1.8 pazsan 10677:
1.78 anton 10678: @cindex class scoping implementation
10679: Each class also has a word list that contains the words defined with
10680: @code{inst-var} and @code{inst-value}, and its protected
10681: words. It also has a pointer to its parent. @code{class} pushes
10682: the word lists of the class and all its ancestors onto the search order stack,
10683: and @code{end-class} drops them.
1.20 pazsan 10684:
1.78 anton 10685: @cindex interface implementation
10686: An interface is like a class without fields, parent and protected
10687: words; i.e., it just has a method map. If a class implements an
10688: interface, its method map contains a pointer to the method map of the
10689: interface. The positive offsets in the map are reserved for class
10690: methods, therefore interface map pointers have negative
10691: offsets. Interfaces have offsets that are unique throughout the
10692: system, unlike class selectors, whose offsets are only unique for the
10693: classes where the selector is available (invokable).
1.20 pazsan 10694:
1.78 anton 10695: This structure means that interface selectors have to perform one
10696: indirection more than class selectors to find their method. Their body
10697: contains the interface map pointer offset in the class method map, and
10698: the method offset in the interface method map. The
10699: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10700:
10701: @example
1.78 anton 10702: ( object selector-body )
10703: 2dup selector-interface @@ ( object selector-body object interface-offset )
10704: swap object-map @@ + @@ ( object selector-body map )
10705: swap selector-offset @@ + @@ execute
1.20 pazsan 10706: @end example
10707:
1.78 anton 10708: where @code{object-map} and @code{selector-offset} are
10709: first fields and generate no code.
1.20 pazsan 10710:
1.78 anton 10711: As a concrete example, consider the following code:
1.20 pazsan 10712:
10713: @example
1.78 anton 10714: interface
10715: selector if1sel1
10716: selector if1sel2
10717: end-interface if1
1.20 pazsan 10718:
1.78 anton 10719: object class
10720: if1 implementation
10721: selector cl1sel1
10722: cell% inst-var cl1iv1
1.20 pazsan 10723:
1.78 anton 10724: ' m1 overrides construct
10725: ' m2 overrides if1sel1
10726: ' m3 overrides if1sel2
10727: ' m4 overrides cl1sel2
10728: end-class cl1
1.20 pazsan 10729:
1.78 anton 10730: create obj1 object dict-new drop
10731: create obj2 cl1 dict-new drop
10732: @end example
1.20 pazsan 10733:
1.78 anton 10734: The data structure created by this code (including the data structure
10735: for @code{object}) is shown in the
10736: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10737: @comment TODO add this diagram..
1.20 pazsan 10738:
1.78 anton 10739: @node Objects Glossary, , Objects Implementation, Objects
10740: @subsubsection @file{objects.fs} Glossary
10741: @cindex @file{objects.fs} Glossary
1.20 pazsan 10742:
10743:
1.78 anton 10744: doc---objects-bind
10745: doc---objects-<bind>
10746: doc---objects-bind'
10747: doc---objects-[bind]
10748: doc---objects-class
10749: doc---objects-class->map
10750: doc---objects-class-inst-size
10751: doc---objects-class-override!
1.79 anton 10752: doc---objects-class-previous
10753: doc---objects-class>order
1.78 anton 10754: doc---objects-construct
10755: doc---objects-current'
10756: doc---objects-[current]
10757: doc---objects-current-interface
10758: doc---objects-dict-new
10759: doc---objects-end-class
10760: doc---objects-end-class-noname
10761: doc---objects-end-interface
10762: doc---objects-end-interface-noname
10763: doc---objects-end-methods
10764: doc---objects-exitm
10765: doc---objects-heap-new
10766: doc---objects-implementation
10767: doc---objects-init-object
10768: doc---objects-inst-value
10769: doc---objects-inst-var
10770: doc---objects-interface
10771: doc---objects-m:
10772: doc---objects-:m
10773: doc---objects-;m
10774: doc---objects-method
10775: doc---objects-methods
10776: doc---objects-object
10777: doc---objects-overrides
10778: doc---objects-[parent]
10779: doc---objects-print
10780: doc---objects-protected
10781: doc---objects-public
10782: doc---objects-selector
10783: doc---objects-this
10784: doc---objects-<to-inst>
10785: doc---objects-[to-inst]
10786: doc---objects-to-this
10787: doc---objects-xt-new
1.20 pazsan 10788:
10789:
1.78 anton 10790: @c -------------------------------------------------------------
10791: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10792: @subsection The @file{oof.fs} model
10793: @cindex oof
10794: @cindex object-oriented programming
1.20 pazsan 10795:
1.78 anton 10796: @cindex @file{objects.fs}
10797: @cindex @file{oof.fs}
1.20 pazsan 10798:
1.78 anton 10799: This section describes the @file{oof.fs} package.
1.20 pazsan 10800:
1.78 anton 10801: The package described in this section has been used in bigFORTH since 1991, and
10802: used for two large applications: a chromatographic system used to
10803: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10804:
1.78 anton 10805: You can find a description (in German) of @file{oof.fs} in @cite{Object
10806: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10807: 10(2), 1994.
1.20 pazsan 10808:
1.78 anton 10809: @menu
10810: * Properties of the OOF model::
10811: * Basic OOF Usage::
10812: * The OOF base class::
10813: * Class Declaration::
10814: * Class Implementation::
10815: @end menu
1.20 pazsan 10816:
1.78 anton 10817: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10818: @subsubsection Properties of the @file{oof.fs} model
10819: @cindex @file{oof.fs} properties
1.20 pazsan 10820:
1.78 anton 10821: @itemize @bullet
10822: @item
10823: This model combines object oriented programming with information
10824: hiding. It helps you writing large application, where scoping is
10825: necessary, because it provides class-oriented scoping.
1.20 pazsan 10826:
1.78 anton 10827: @item
10828: Named objects, object pointers, and object arrays can be created,
10829: selector invocation uses the ``object selector'' syntax. Selector invocation
10830: to objects and/or selectors on the stack is a bit less convenient, but
10831: possible.
1.44 crook 10832:
1.78 anton 10833: @item
10834: Selector invocation and instance variable usage of the active object is
10835: straightforward, since both make use of the active object.
1.44 crook 10836:
1.78 anton 10837: @item
10838: Late binding is efficient and easy to use.
1.20 pazsan 10839:
1.78 anton 10840: @item
10841: State-smart objects parse selectors. However, extensibility is provided
10842: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10843:
1.78 anton 10844: @item
10845: An implementation in ANS Forth is available.
1.20 pazsan 10846:
1.78 anton 10847: @end itemize
1.23 crook 10848:
10849:
1.78 anton 10850: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10851: @subsubsection Basic @file{oof.fs} Usage
10852: @cindex @file{oof.fs} usage
1.23 crook 10853:
1.78 anton 10854: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10855:
1.78 anton 10856: You can define a class for graphical objects like this:
1.23 crook 10857:
1.78 anton 10858: @cindex @code{class} usage
10859: @cindex @code{class;} usage
10860: @cindex @code{method} usage
10861: @example
10862: object class graphical \ "object" is the parent class
1.139 pazsan 10863: method draw ( x y -- )
1.78 anton 10864: class;
10865: @end example
1.23 crook 10866:
1.78 anton 10867: This code defines a class @code{graphical} with an
10868: operation @code{draw}. We can perform the operation
10869: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10870:
1.78 anton 10871: @example
10872: 100 100 t-rex draw
10873: @end example
1.23 crook 10874:
1.78 anton 10875: @noindent
10876: where @code{t-rex} is an object or object pointer, created with e.g.
10877: @code{graphical : t-rex}.
1.23 crook 10878:
1.78 anton 10879: @cindex abstract class
10880: How do we create a graphical object? With the present definitions,
10881: we cannot create a useful graphical object. The class
10882: @code{graphical} describes graphical objects in general, but not
10883: any concrete graphical object type (C++ users would call it an
10884: @emph{abstract class}); e.g., there is no method for the selector
10885: @code{draw} in the class @code{graphical}.
1.23 crook 10886:
1.78 anton 10887: For concrete graphical objects, we define child classes of the
10888: class @code{graphical}, e.g.:
1.23 crook 10889:
1.78 anton 10890: @example
10891: graphical class circle \ "graphical" is the parent class
10892: cell var circle-radius
10893: how:
10894: : draw ( x y -- )
10895: circle-radius @@ draw-circle ;
1.23 crook 10896:
1.139 pazsan 10897: : init ( n-radius -- )
1.78 anton 10898: circle-radius ! ;
10899: class;
10900: @end example
1.1 anton 10901:
1.78 anton 10902: Here we define a class @code{circle} as a child of @code{graphical},
10903: with a field @code{circle-radius}; it defines new methods for the
10904: selectors @code{draw} and @code{init} (@code{init} is defined in
10905: @code{object}, the parent class of @code{graphical}).
1.1 anton 10906:
1.78 anton 10907: Now we can create a circle in the dictionary with:
1.1 anton 10908:
1.78 anton 10909: @example
10910: 50 circle : my-circle
10911: @end example
1.21 crook 10912:
1.78 anton 10913: @noindent
10914: @code{:} invokes @code{init}, thus initializing the field
10915: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10916: with:
1.1 anton 10917:
1.78 anton 10918: @example
10919: 100 100 my-circle draw
10920: @end example
1.1 anton 10921:
1.78 anton 10922: @cindex selector invocation, restrictions
10923: @cindex class definition, restrictions
10924: Note: You can only invoke a selector if the receiving object belongs to
10925: the class where the selector was defined or one of its descendents;
10926: e.g., you can invoke @code{draw} only for objects belonging to
10927: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10928: mechanism will check if you try to invoke a selector that is not
10929: defined in this class hierarchy, so you'll get an error at compilation
10930: time.
1.1 anton 10931:
10932:
1.78 anton 10933: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10934: @subsubsection The @file{oof.fs} base class
10935: @cindex @file{oof.fs} base class
1.1 anton 10936:
1.78 anton 10937: When you define a class, you have to specify a parent class. So how do
10938: you start defining classes? There is one class available from the start:
10939: @code{object}. You have to use it as ancestor for all classes. It is the
10940: only class that has no parent. Classes are also objects, except that
10941: they don't have instance variables; class manipulation such as
10942: inheritance or changing definitions of a class is handled through
10943: selectors of the class @code{object}.
1.1 anton 10944:
1.78 anton 10945: @code{object} provides a number of selectors:
1.1 anton 10946:
1.78 anton 10947: @itemize @bullet
10948: @item
10949: @code{class} for subclassing, @code{definitions} to add definitions
10950: later on, and @code{class?} to get type informations (is the class a
10951: subclass of the class passed on the stack?).
1.1 anton 10952:
1.78 anton 10953: doc---object-class
10954: doc---object-definitions
10955: doc---object-class?
1.1 anton 10956:
10957:
1.26 crook 10958: @item
1.78 anton 10959: @code{init} and @code{dispose} as constructor and destructor of the
10960: object. @code{init} is invocated after the object's memory is allocated,
10961: while @code{dispose} also handles deallocation. Thus if you redefine
10962: @code{dispose}, you have to call the parent's dispose with @code{super
10963: dispose}, too.
10964:
10965: doc---object-init
10966: doc---object-dispose
10967:
1.1 anton 10968:
1.26 crook 10969: @item
1.78 anton 10970: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10971: @code{[]} to create named and unnamed objects and object arrays or
10972: object pointers.
10973:
10974: doc---object-new
10975: doc---object-new[]
10976: doc---object-:
10977: doc---object-ptr
10978: doc---object-asptr
10979: doc---object-[]
10980:
1.1 anton 10981:
1.26 crook 10982: @item
1.78 anton 10983: @code{::} and @code{super} for explicit scoping. You should use explicit
10984: scoping only for super classes or classes with the same set of instance
10985: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10986:
1.78 anton 10987: doc---object-::
10988: doc---object-super
1.21 crook 10989:
10990:
1.26 crook 10991: @item
1.78 anton 10992: @code{self} to get the address of the object
1.21 crook 10993:
1.78 anton 10994: doc---object-self
1.21 crook 10995:
10996:
1.78 anton 10997: @item
10998: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
10999: pointers and instance defers.
1.21 crook 11000:
1.78 anton 11001: doc---object-bind
11002: doc---object-bound
11003: doc---object-link
11004: doc---object-is
1.21 crook 11005:
11006:
1.78 anton 11007: @item
11008: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11009: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11010:
1.78 anton 11011: doc---object-'
11012: doc---object-postpone
1.21 crook 11013:
11014:
1.78 anton 11015: @item
11016: @code{with} and @code{endwith} to select the active object from the
11017: stack, and enable its scope. Using @code{with} and @code{endwith}
11018: also allows you to create code using selector @code{postpone} without being
11019: trapped by the state-smart objects.
1.21 crook 11020:
1.78 anton 11021: doc---object-with
11022: doc---object-endwith
1.21 crook 11023:
11024:
1.78 anton 11025: @end itemize
1.21 crook 11026:
1.78 anton 11027: @node Class Declaration, Class Implementation, The OOF base class, OOF
11028: @subsubsection Class Declaration
11029: @cindex class declaration
1.21 crook 11030:
1.78 anton 11031: @itemize @bullet
11032: @item
11033: Instance variables
1.21 crook 11034:
1.78 anton 11035: doc---oof-var
1.21 crook 11036:
11037:
1.78 anton 11038: @item
11039: Object pointers
1.21 crook 11040:
1.78 anton 11041: doc---oof-ptr
11042: doc---oof-asptr
1.21 crook 11043:
11044:
1.78 anton 11045: @item
11046: Instance defers
1.21 crook 11047:
1.78 anton 11048: doc---oof-defer
1.21 crook 11049:
11050:
1.78 anton 11051: @item
11052: Method selectors
1.21 crook 11053:
1.78 anton 11054: doc---oof-early
11055: doc---oof-method
1.21 crook 11056:
11057:
1.78 anton 11058: @item
11059: Class-wide variables
1.21 crook 11060:
1.78 anton 11061: doc---oof-static
1.21 crook 11062:
11063:
1.78 anton 11064: @item
11065: End declaration
1.1 anton 11066:
1.78 anton 11067: doc---oof-how:
11068: doc---oof-class;
1.21 crook 11069:
11070:
1.78 anton 11071: @end itemize
1.21 crook 11072:
1.78 anton 11073: @c -------------------------------------------------------------
11074: @node Class Implementation, , Class Declaration, OOF
11075: @subsubsection Class Implementation
11076: @cindex class implementation
1.21 crook 11077:
1.78 anton 11078: @c -------------------------------------------------------------
11079: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11080: @subsection The @file{mini-oof.fs} model
11081: @cindex mini-oof
1.21 crook 11082:
1.78 anton 11083: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11084: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11085: and reduces to the bare minimum of features. This is based on a posting
11086: of Bernd Paysan in comp.lang.forth.
1.21 crook 11087:
1.78 anton 11088: @menu
11089: * Basic Mini-OOF Usage::
11090: * Mini-OOF Example::
11091: * Mini-OOF Implementation::
11092: @end menu
1.21 crook 11093:
1.78 anton 11094: @c -------------------------------------------------------------
11095: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11096: @subsubsection Basic @file{mini-oof.fs} Usage
11097: @cindex mini-oof usage
1.21 crook 11098:
1.78 anton 11099: There is a base class (@code{class}, which allocates one cell for the
11100: object pointer) plus seven other words: to define a method, a variable,
11101: a class; to end a class, to resolve binding, to allocate an object and
11102: to compile a class method.
11103: @comment TODO better description of the last one
1.26 crook 11104:
1.21 crook 11105:
1.78 anton 11106: doc-object
11107: doc-method
11108: doc-var
11109: doc-class
11110: doc-end-class
11111: doc-defines
11112: doc-new
11113: doc-::
1.21 crook 11114:
11115:
11116:
1.78 anton 11117: @c -------------------------------------------------------------
11118: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11119: @subsubsection Mini-OOF Example
11120: @cindex mini-oof example
1.1 anton 11121:
1.78 anton 11122: A short example shows how to use this package. This example, in slightly
11123: extended form, is supplied as @file{moof-exm.fs}
11124: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11125:
1.26 crook 11126: @example
1.78 anton 11127: object class
11128: method init
11129: method draw
11130: end-class graphical
1.26 crook 11131: @end example
1.20 pazsan 11132:
1.78 anton 11133: This code defines a class @code{graphical} with an
11134: operation @code{draw}. We can perform the operation
11135: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11136:
1.26 crook 11137: @example
1.78 anton 11138: 100 100 t-rex draw
1.26 crook 11139: @end example
1.12 anton 11140:
1.78 anton 11141: where @code{t-rex} is an object or object pointer, created with e.g.
11142: @code{graphical new Constant t-rex}.
1.12 anton 11143:
1.78 anton 11144: For concrete graphical objects, we define child classes of the
11145: class @code{graphical}, e.g.:
1.12 anton 11146:
1.26 crook 11147: @example
11148: graphical class
1.78 anton 11149: cell var circle-radius
11150: end-class circle \ "graphical" is the parent class
1.12 anton 11151:
1.78 anton 11152: :noname ( x y -- )
11153: circle-radius @@ draw-circle ; circle defines draw
11154: :noname ( r -- )
11155: circle-radius ! ; circle defines init
11156: @end example
1.12 anton 11157:
1.78 anton 11158: There is no implicit init method, so we have to define one. The creation
11159: code of the object now has to call init explicitely.
1.21 crook 11160:
1.78 anton 11161: @example
11162: circle new Constant my-circle
11163: 50 my-circle init
1.12 anton 11164: @end example
11165:
1.78 anton 11166: It is also possible to add a function to create named objects with
11167: automatic call of @code{init}, given that all objects have @code{init}
11168: on the same place:
1.38 anton 11169:
1.78 anton 11170: @example
11171: : new: ( .. o "name" -- )
11172: new dup Constant init ;
11173: 80 circle new: large-circle
11174: @end example
1.12 anton 11175:
1.78 anton 11176: We can draw this new circle at (100,100) with:
1.12 anton 11177:
1.78 anton 11178: @example
11179: 100 100 my-circle draw
11180: @end example
1.12 anton 11181:
1.78 anton 11182: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11183: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11184:
1.78 anton 11185: Object-oriented systems with late binding typically use a
11186: ``vtable''-approach: the first variable in each object is a pointer to a
11187: table, which contains the methods as function pointers. The vtable
11188: may also contain other information.
1.12 anton 11189:
1.79 anton 11190: So first, let's declare selectors:
1.37 anton 11191:
11192: @example
1.79 anton 11193: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11194: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11195: @end example
1.37 anton 11196:
1.79 anton 11197: During selector declaration, the number of selectors and instance
11198: variables is on the stack (in address units). @code{method} creates one
11199: selector and increments the selector number. To execute a selector, it
1.78 anton 11200: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11201: executes the method @i{xt} stored there. Each selector takes the object
11202: it is invoked with as top of stack parameter; it passes the parameters
11203: (including the object) unchanged to the appropriate method which should
1.78 anton 11204: consume that object.
1.37 anton 11205:
1.78 anton 11206: Now, we also have to declare instance variables
1.37 anton 11207:
1.78 anton 11208: @example
1.79 anton 11209: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11210: DOES> ( o -- addr ) @@ + ;
1.37 anton 11211: @end example
11212:
1.78 anton 11213: As before, a word is created with the current offset. Instance
11214: variables can have different sizes (cells, floats, doubles, chars), so
11215: all we do is take the size and add it to the offset. If your machine
11216: has alignment restrictions, put the proper @code{aligned} or
11217: @code{faligned} before the variable, to adjust the variable
11218: offset. That's why it is on the top of stack.
1.37 anton 11219:
1.78 anton 11220: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11221:
1.78 anton 11222: @example
11223: Create object 1 cells , 2 cells ,
1.79 anton 11224: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11225: @end example
1.12 anton 11226:
1.78 anton 11227: For inheritance, the vtable of the parent object has to be
11228: copied when a new, derived class is declared. This gives all the
11229: methods of the parent class, which can be overridden, though.
1.12 anton 11230:
1.78 anton 11231: @example
1.79 anton 11232: : end-class ( class selectors vars "name" -- )
1.78 anton 11233: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11234: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11235: @end example
1.12 anton 11236:
1.78 anton 11237: The first line creates the vtable, initialized with
11238: @code{noop}s. The second line is the inheritance mechanism, it
11239: copies the xts from the parent vtable.
1.12 anton 11240:
1.78 anton 11241: We still have no way to define new methods, let's do that now:
1.12 anton 11242:
1.26 crook 11243: @example
1.79 anton 11244: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11245: @end example
1.12 anton 11246:
1.78 anton 11247: To allocate a new object, we need a word, too:
1.12 anton 11248:
1.78 anton 11249: @example
11250: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11251: @end example
11252:
1.78 anton 11253: Sometimes derived classes want to access the method of the
11254: parent object. There are two ways to achieve this with Mini-OOF:
11255: first, you could use named words, and second, you could look up the
11256: vtable of the parent object.
1.12 anton 11257:
1.78 anton 11258: @example
11259: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11260: @end example
1.12 anton 11261:
11262:
1.78 anton 11263: Nothing can be more confusing than a good example, so here is
11264: one. First let's declare a text object (called
11265: @code{button}), that stores text and position:
1.12 anton 11266:
1.78 anton 11267: @example
11268: object class
11269: cell var text
11270: cell var len
11271: cell var x
11272: cell var y
11273: method init
11274: method draw
11275: end-class button
11276: @end example
1.12 anton 11277:
1.78 anton 11278: @noindent
11279: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11280:
1.26 crook 11281: @example
1.78 anton 11282: :noname ( o -- )
11283: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11284: button defines draw
11285: :noname ( addr u o -- )
11286: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11287: button defines init
1.26 crook 11288: @end example
1.12 anton 11289:
1.78 anton 11290: @noindent
11291: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11292: new data and no new selectors:
1.78 anton 11293:
11294: @example
11295: button class
11296: end-class bold-button
1.12 anton 11297:
1.78 anton 11298: : bold 27 emit ." [1m" ;
11299: : normal 27 emit ." [0m" ;
11300: @end example
1.1 anton 11301:
1.78 anton 11302: @noindent
11303: The class @code{bold-button} has a different draw method to
11304: @code{button}, but the new method is defined in terms of the draw method
11305: for @code{button}:
1.20 pazsan 11306:
1.78 anton 11307: @example
11308: :noname bold [ button :: draw ] normal ; bold-button defines draw
11309: @end example
1.21 crook 11310:
1.78 anton 11311: @noindent
1.79 anton 11312: Finally, create two objects and apply selectors:
1.21 crook 11313:
1.26 crook 11314: @example
1.78 anton 11315: button new Constant foo
11316: s" thin foo" foo init
11317: page
11318: foo draw
11319: bold-button new Constant bar
11320: s" fat bar" bar init
11321: 1 bar y !
11322: bar draw
1.26 crook 11323: @end example
1.21 crook 11324:
11325:
1.78 anton 11326: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11327: @subsection Comparison with other object models
11328: @cindex comparison of object models
11329: @cindex object models, comparison
11330:
11331: Many object-oriented Forth extensions have been proposed (@cite{A survey
11332: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11333: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11334: relation of the object models described here to two well-known and two
11335: closely-related (by the use of method maps) models. Andras Zsoter
11336: helped us with this section.
11337:
11338: @cindex Neon model
11339: The most popular model currently seems to be the Neon model (see
11340: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11341: 1997) by Andrew McKewan) but this model has a number of limitations
11342: @footnote{A longer version of this critique can be
11343: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11344: Dimensions, May 1997) by Anton Ertl.}:
11345:
11346: @itemize @bullet
11347: @item
11348: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11349: to pass objects on the stack.
1.21 crook 11350:
1.78 anton 11351: @item
11352: It requires that the selector parses the input stream (at
1.79 anton 11353: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11354: hard to find.
1.21 crook 11355:
1.78 anton 11356: @item
1.79 anton 11357: It allows using every selector on every object; this eliminates the
11358: need for interfaces, but makes it harder to create efficient
11359: implementations.
1.78 anton 11360: @end itemize
1.21 crook 11361:
1.78 anton 11362: @cindex Pountain's object-oriented model
11363: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11364: Press, London, 1987) by Dick Pountain. However, it is not really about
11365: object-oriented programming, because it hardly deals with late
11366: binding. Instead, it focuses on features like information hiding and
11367: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11368:
1.78 anton 11369: @cindex Zsoter's object-oriented model
1.79 anton 11370: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11371: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11372: describes a model that makes heavy use of an active object (like
11373: @code{this} in @file{objects.fs}): The active object is not only used
11374: for accessing all fields, but also specifies the receiving object of
11375: every selector invocation; you have to change the active object
11376: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11377: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11378: the method entry point is unnecessary with Zsoter's model, because the
11379: receiving object is the active object already. On the other hand, the
11380: explicit change is absolutely necessary in that model, because otherwise
11381: no one could ever change the active object. An ANS Forth implementation
11382: of this model is available through
11383: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11384:
1.78 anton 11385: @cindex @file{oof.fs}, differences to other models
11386: The @file{oof.fs} model combines information hiding and overloading
11387: resolution (by keeping names in various word lists) with object-oriented
11388: programming. It sets the active object implicitly on method entry, but
11389: also allows explicit changing (with @code{>o...o>} or with
11390: @code{with...endwith}). It uses parsing and state-smart objects and
11391: classes for resolving overloading and for early binding: the object or
11392: class parses the selector and determines the method from this. If the
11393: selector is not parsed by an object or class, it performs a call to the
11394: selector for the active object (late binding), like Zsoter's model.
11395: Fields are always accessed through the active object. The big
11396: disadvantage of this model is the parsing and the state-smartness, which
11397: reduces extensibility and increases the opportunities for subtle bugs;
11398: essentially, you are only safe if you never tick or @code{postpone} an
11399: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11400:
1.78 anton 11401: @cindex @file{mini-oof.fs}, differences to other models
11402: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11403: version of the @file{objects.fs} model, but syntactically it is a
11404: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11405:
11406:
1.78 anton 11407: @c -------------------------------------------------------------
1.150 anton 11408: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11409: @section Programming Tools
11410: @cindex programming tools
1.21 crook 11411:
1.78 anton 11412: @c !! move this and assembler down below OO stuff.
1.21 crook 11413:
1.78 anton 11414: @menu
1.150 anton 11415: * Examining:: Data and Code.
11416: * Forgetting words:: Usually before reloading.
1.78 anton 11417: * Debugging:: Simple and quick.
11418: * Assertions:: Making your programs self-checking.
11419: * Singlestep Debugger:: Executing your program word by word.
11420: @end menu
1.21 crook 11421:
1.78 anton 11422: @node Examining, Forgetting words, Programming Tools, Programming Tools
11423: @subsection Examining data and code
11424: @cindex examining data and code
11425: @cindex data examination
11426: @cindex code examination
1.44 crook 11427:
1.78 anton 11428: The following words inspect the stack non-destructively:
1.21 crook 11429:
1.78 anton 11430: doc-.s
11431: doc-f.s
1.44 crook 11432:
1.78 anton 11433: There is a word @code{.r} but it does @i{not} display the return stack!
11434: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11435:
1.78 anton 11436: doc-depth
11437: doc-fdepth
11438: doc-clearstack
1.124 anton 11439: doc-clearstacks
1.21 crook 11440:
1.78 anton 11441: The following words inspect memory.
1.21 crook 11442:
1.78 anton 11443: doc-?
11444: doc-dump
1.21 crook 11445:
1.78 anton 11446: And finally, @code{see} allows to inspect code:
1.21 crook 11447:
1.78 anton 11448: doc-see
11449: doc-xt-see
1.111 anton 11450: doc-simple-see
11451: doc-simple-see-range
1.21 crook 11452:
1.78 anton 11453: @node Forgetting words, Debugging, Examining, Programming Tools
11454: @subsection Forgetting words
11455: @cindex words, forgetting
11456: @cindex forgeting words
1.21 crook 11457:
1.78 anton 11458: @c anton: other, maybe better places for this subsection: Defining Words;
11459: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11460:
1.78 anton 11461: Forth allows you to forget words (and everything that was alloted in the
11462: dictonary after them) in a LIFO manner.
1.21 crook 11463:
1.78 anton 11464: doc-marker
1.21 crook 11465:
1.78 anton 11466: The most common use of this feature is during progam development: when
11467: you change a source file, forget all the words it defined and load it
11468: again (since you also forget everything defined after the source file
11469: was loaded, you have to reload that, too). Note that effects like
11470: storing to variables and destroyed system words are not undone when you
11471: forget words. With a system like Gforth, that is fast enough at
11472: starting up and compiling, I find it more convenient to exit and restart
11473: Gforth, as this gives me a clean slate.
1.21 crook 11474:
1.78 anton 11475: Here's an example of using @code{marker} at the start of a source file
11476: that you are debugging; it ensures that you only ever have one copy of
11477: the file's definitions compiled at any time:
1.21 crook 11478:
1.78 anton 11479: @example
11480: [IFDEF] my-code
11481: my-code
11482: [ENDIF]
1.26 crook 11483:
1.78 anton 11484: marker my-code
11485: init-included-files
1.21 crook 11486:
1.78 anton 11487: \ .. definitions start here
11488: \ .
11489: \ .
11490: \ end
11491: @end example
1.21 crook 11492:
1.26 crook 11493:
1.78 anton 11494: @node Debugging, Assertions, Forgetting words, Programming Tools
11495: @subsection Debugging
11496: @cindex debugging
1.21 crook 11497:
1.78 anton 11498: Languages with a slow edit/compile/link/test development loop tend to
11499: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11500:
1.78 anton 11501: A much better (faster) way in fast-compiling languages is to add
11502: printing code at well-selected places, let the program run, look at
11503: the output, see where things went wrong, add more printing code, etc.,
11504: until the bug is found.
1.21 crook 11505:
1.78 anton 11506: The simple debugging aids provided in @file{debugs.fs}
11507: are meant to support this style of debugging.
1.21 crook 11508:
1.78 anton 11509: The word @code{~~} prints debugging information (by default the source
11510: location and the stack contents). It is easy to insert. If you use Emacs
11511: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11512: query-replace them with nothing). The deferred words
1.101 anton 11513: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11514: @code{~~}. The default source location output format works well with
11515: Emacs' compilation mode, so you can step through the program at the
11516: source level using @kbd{C-x `} (the advantage over a stepping debugger
11517: is that you can step in any direction and you know where the crash has
11518: happened or where the strange data has occurred).
1.21 crook 11519:
1.78 anton 11520: doc-~~
11521: doc-printdebugdata
1.101 anton 11522: doc-.debugline
1.21 crook 11523:
1.106 anton 11524: @cindex filenames in @code{~~} output
11525: @code{~~} (and assertions) will usually print the wrong file name if a
11526: marker is executed in the same file after their occurance. They will
11527: print @samp{*somewhere*} as file name if a marker is executed in the
11528: same file before their occurance.
11529:
11530:
1.78 anton 11531: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11532: @subsection Assertions
11533: @cindex assertions
1.21 crook 11534:
1.78 anton 11535: It is a good idea to make your programs self-checking, especially if you
11536: make an assumption that may become invalid during maintenance (for
11537: example, that a certain field of a data structure is never zero). Gforth
11538: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11539:
11540: @example
1.78 anton 11541: assert( @i{flag} )
1.26 crook 11542: @end example
11543:
1.78 anton 11544: The code between @code{assert(} and @code{)} should compute a flag, that
11545: should be true if everything is alright and false otherwise. It should
11546: not change anything else on the stack. The overall stack effect of the
11547: assertion is @code{( -- )}. E.g.
1.21 crook 11548:
1.26 crook 11549: @example
1.78 anton 11550: assert( 1 1 + 2 = ) \ what we learn in school
11551: assert( dup 0<> ) \ assert that the top of stack is not zero
11552: assert( false ) \ this code should not be reached
1.21 crook 11553: @end example
11554:
1.78 anton 11555: The need for assertions is different at different times. During
11556: debugging, we want more checking, in production we sometimes care more
11557: for speed. Therefore, assertions can be turned off, i.e., the assertion
11558: becomes a comment. Depending on the importance of an assertion and the
11559: time it takes to check it, you may want to turn off some assertions and
11560: keep others turned on. Gforth provides several levels of assertions for
11561: this purpose:
11562:
11563:
11564: doc-assert0(
11565: doc-assert1(
11566: doc-assert2(
11567: doc-assert3(
11568: doc-assert(
11569: doc-)
1.21 crook 11570:
11571:
1.78 anton 11572: The variable @code{assert-level} specifies the highest assertions that
11573: are turned on. I.e., at the default @code{assert-level} of one,
11574: @code{assert0(} and @code{assert1(} assertions perform checking, while
11575: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11576:
1.78 anton 11577: The value of @code{assert-level} is evaluated at compile-time, not at
11578: run-time. Therefore you cannot turn assertions on or off at run-time;
11579: you have to set the @code{assert-level} appropriately before compiling a
11580: piece of code. You can compile different pieces of code at different
11581: @code{assert-level}s (e.g., a trusted library at level 1 and
11582: newly-written code at level 3).
1.26 crook 11583:
11584:
1.78 anton 11585: doc-assert-level
1.26 crook 11586:
11587:
1.78 anton 11588: If an assertion fails, a message compatible with Emacs' compilation mode
11589: is produced and the execution is aborted (currently with @code{ABORT"}.
11590: If there is interest, we will introduce a special throw code. But if you
11591: intend to @code{catch} a specific condition, using @code{throw} is
11592: probably more appropriate than an assertion).
1.106 anton 11593:
11594: @cindex filenames in assertion output
11595: Assertions (and @code{~~}) will usually print the wrong file name if a
11596: marker is executed in the same file after their occurance. They will
11597: print @samp{*somewhere*} as file name if a marker is executed in the
11598: same file before their occurance.
1.44 crook 11599:
1.78 anton 11600: Definitions in ANS Forth for these assertion words are provided
11601: in @file{compat/assert.fs}.
1.26 crook 11602:
1.44 crook 11603:
1.78 anton 11604: @node Singlestep Debugger, , Assertions, Programming Tools
11605: @subsection Singlestep Debugger
11606: @cindex singlestep Debugger
11607: @cindex debugging Singlestep
1.44 crook 11608:
1.112 anton 11609: The singlestep debugger does not work in this release.
11610:
1.78 anton 11611: When you create a new word there's often the need to check whether it
11612: behaves correctly or not. You can do this by typing @code{dbg
11613: badword}. A debug session might look like this:
1.26 crook 11614:
1.78 anton 11615: @example
11616: : badword 0 DO i . LOOP ; ok
11617: 2 dbg badword
11618: : badword
11619: Scanning code...
1.44 crook 11620:
1.78 anton 11621: Nesting debugger ready!
1.44 crook 11622:
1.78 anton 11623: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11624: 400D4740 8049F68 DO -> [ 0 ]
11625: 400D4744 804A0C8 i -> [ 1 ] 00000
11626: 400D4748 400C5E60 . -> 0 [ 0 ]
11627: 400D474C 8049D0C LOOP -> [ 0 ]
11628: 400D4744 804A0C8 i -> [ 1 ] 00001
11629: 400D4748 400C5E60 . -> 1 [ 0 ]
11630: 400D474C 8049D0C LOOP -> [ 0 ]
11631: 400D4758 804B384 ; -> ok
11632: @end example
1.21 crook 11633:
1.78 anton 11634: Each line displayed is one step. You always have to hit return to
11635: execute the next word that is displayed. If you don't want to execute
11636: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11637: an overview what keys are available:
1.44 crook 11638:
1.78 anton 11639: @table @i
1.44 crook 11640:
1.78 anton 11641: @item @key{RET}
11642: Next; Execute the next word.
1.21 crook 11643:
1.78 anton 11644: @item n
11645: Nest; Single step through next word.
1.44 crook 11646:
1.78 anton 11647: @item u
11648: Unnest; Stop debugging and execute rest of word. If we got to this word
11649: with nest, continue debugging with the calling word.
1.44 crook 11650:
1.78 anton 11651: @item d
11652: Done; Stop debugging and execute rest.
1.21 crook 11653:
1.78 anton 11654: @item s
11655: Stop; Abort immediately.
1.44 crook 11656:
1.78 anton 11657: @end table
1.44 crook 11658:
1.78 anton 11659: Debugging large application with this mechanism is very difficult, because
11660: you have to nest very deeply into the program before the interesting part
11661: begins. This takes a lot of time.
1.26 crook 11662:
1.78 anton 11663: To do it more directly put a @code{BREAK:} command into your source code.
11664: When program execution reaches @code{BREAK:} the single step debugger is
11665: invoked and you have all the features described above.
1.44 crook 11666:
1.78 anton 11667: If you have more than one part to debug it is useful to know where the
11668: program has stopped at the moment. You can do this by the
11669: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11670: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11671:
1.26 crook 11672:
1.78 anton 11673: doc-dbg
11674: doc-break:
11675: doc-break"
1.44 crook 11676:
1.150 anton 11677: @c ------------------------------------------------------------
11678: @node C Interface, Assembler and Code Words, Programming Tools, Words
11679: @section C Interface
11680: @cindex C interface
11681: @cindex foreign language interface
11682: @cindex interface to C functions
11683:
11684: Note that the C interface is not yet complete; a better way of
11685: declaring C functions is planned, as well as a way of declaring
11686: structs, unions, and their fields.
11687:
11688: @menu
11689: * Calling C Functions::
11690: * Declaring C Functions::
11691: * Callbacks::
1.155 anton 11692: * Low-Level C Interface Words::
1.150 anton 11693: @end menu
11694:
1.151 pazsan 11695: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 11696: @subsection Calling C functions
1.155 anton 11697: @cindex C functions, calls to
11698: @cindex calling C functions
1.150 anton 11699:
1.151 pazsan 11700: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 11701: can call it as follows: You push the arguments on the stack(s), and
11702: then call the word for the C function. The arguments have to be
11703: pushed in the same order as the arguments appear in the C
11704: documentation (i.e., the first argument is deepest on the stack).
11705: Integer and pointer arguments have to be pushed on the data stack,
11706: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 11707: by the called C function.
1.150 anton 11708:
1.155 anton 11709: On returning from the C function, the return value, if any, resides on
11710: the appropriate stack: an integer return value is pushed on the data
11711: stack, an FP return value on the FP stack, and a void return value
11712: results in not pushing anything. Note that most C functions have a
11713: return value, even if that is often not used in C; in Forth, you have
11714: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 11715:
11716: By default, an integer argument or return value corresponds to a
11717: single cell, and a floating-point argument or return value corresponds
11718: to a Forth float value; the C interface performs the appropriate
11719: conversions where necessary, on a best-effort basis (in some cases,
11720: there may be some loss).
11721:
11722: As an example, consider the POSIX function @code{lseek()}:
11723:
11724: @example
11725: off_t lseek(int fd, off_t offset, int whence);
11726: @end example
11727:
11728: This function takes three integer arguments, and returns an integer
11729: argument, so a Forth call for setting the current file offset to the
11730: start of the file could look like this:
11731:
11732: @example
11733: fd @@ 0 SEEK_SET lseek -1 = if
11734: ... \ error handling
11735: then
11736: @end example
11737:
11738: You might be worried that an @code{off_t} does not fit into a cell, so
11739: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 11740: of the return values. In that case, in your declaration of the
11741: function (@pxref{Declaring C Functions}) you should declare it to use
11742: double-cells for the off_t argument and return value, and maybe give
11743: the resulting Forth word a different name, like @code{dlseek}; the
11744: result could be called like this:
1.150 anton 11745:
11746: @example
11747: fd @@ 0. SEEK_SET dlseek -1. d= if
11748: ... \ error handling
11749: then
11750: @end example
11751:
11752: Passing and returning structs or unions is currently not supported by
11753: our interface@footnote{If you know the calling convention of your C
11754: compiler, you usually can call such functions in some way, but that
11755: way is usually not portable between platforms, and sometimes not even
11756: between C compilers.}.
11757:
11758: Calling functions with a variable number of arguments (e.g.,
11759: @code{printf()}) is currently only supported by having you declare one
11760: function-calling word for each argument pattern, and calling the
11761: appropriate word for the desired pattern.
11762:
1.155 anton 11763:
1.151 pazsan 11764: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
1.150 anton 11765: @subsection Declaring C Functions
1.155 anton 11766: @cindex C functions, declarations
11767: @cindex declaring C functions
1.150 anton 11768:
11769: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11770: it. You have to look up in your system what the concrete type for the
11771: abstract type @code{off_t} is; let's assume it is @code{long}. Then
11772: the declarations for these words are:
11773:
11774: @example
11775: library libc libc.so.6
11776: libc lseek int long int (long) lseek ( fd noffset whence -- noffset2 )
11777: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 )
11778: @end example
11779:
11780: The first line defines a Forth word @code{libc} for accessing the C
11781: functions in the shared library @file{libc.so.6} (the name of the
11782: shared library depends on the library and the OS; this example is the
11783: standard C library (containing most of the standard C and Unix
11784: functions) for GNU/Linux systems since about 1998).
11785:
11786: The next two lines define two Forth words for the same C function
11787: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
1.155 anton 11788: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d )}.
1.150 anton 11789:
11790: As you can see, the declarations are relatively platform-dependent
11791: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11792: another platform it may be a @code{long long}; actually, in this case
11793: you can have this difference even on the same platform), while the
11794: resulting function-calling words are platform-independent, and calls
11795: to them are portable.
11796:
11797: At some point in the future this interface will be superseded by a
11798: more convenient one with fewer portability issues. But the resulting
1.155 anton 11799: words for calling the C function will still have the same interface,
1.156 ! anton 11800: so you will not need to change the calls.
1.155 anton 11801:
11802: Anyway, here are the words for the current interface:
1.150 anton 11803:
1.155 anton 11804: doc-library
11805: doc-int
11806: doc-dint
11807: doc-uint
11808: doc-udint
11809: doc-long
11810: doc-dlong
11811: doc-ulong
11812: doc-udlong
11813: doc-longlong
11814: doc-dlonglong
11815: doc-ulonglong
11816: doc-udlonglong
1.156 ! anton 11817: doc-ptr
1.155 anton 11818: doc-cfloat
11819: doc-cdouble
11820: doc-clongdouble
11821: doc-(int)
11822: doc-(dint)
11823: doc-(uint)
11824: doc-(udint)
11825: doc-(long)
11826: doc-(dlong)
11827: doc-(ulong)
11828: doc-(udlong)
11829: doc-(longlong)
11830: doc-(dlonglong)
11831: doc-(ulonglong)
11832: doc-(udlonglong)
1.156 ! anton 11833: doc-(ptr)
1.155 anton 11834: doc-(cfloat)
11835: doc-(cdouble)
11836: doc-(clongdouble)
1.150 anton 11837:
1.155 anton 11838:
11839: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
1.150 anton 11840: @subsection Callbacks
1.155 anton 11841: @cindex Callback functions written in Forth
11842: @cindex C function pointers to Forth words
11843:
11844: In some cases you have to pass a function pointer to a C function,
11845: i.e., the library wants to call back to your application (and the
11846: pointed-to function is called a callback function). You can pass the
11847: address of an existing C function (that you get with @code{lib-sym},
11848: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
11849: function, you probably want to define the function as a Forth word.
11850:
11851: !!!
11852: @c I don't understand the existing callback interface from the example - anton
11853:
11854: doc-callback
11855: doc-callback;
11856: doc-fptr
1.150 anton 11857:
1.155 anton 11858: @node Low-Level C Interface Words, , Callbacks, C Interface
11859: @subsection Low-Level C Interface Words
1.44 crook 11860:
1.155 anton 11861: doc-open-lib
11862: doc-lib-sym
1.26 crook 11863:
1.78 anton 11864: @c -------------------------------------------------------------
1.150 anton 11865: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 11866: @section Assembler and Code Words
11867: @cindex assembler
11868: @cindex code words
1.44 crook 11869:
1.78 anton 11870: @menu
11871: * Code and ;code::
11872: * Common Assembler:: Assembler Syntax
11873: * Common Disassembler::
11874: * 386 Assembler:: Deviations and special cases
11875: * Alpha Assembler:: Deviations and special cases
11876: * MIPS assembler:: Deviations and special cases
11877: * Other assemblers:: How to write them
11878: @end menu
1.21 crook 11879:
1.78 anton 11880: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11881: @subsection @code{Code} and @code{;code}
1.26 crook 11882:
1.78 anton 11883: Gforth provides some words for defining primitives (words written in
11884: machine code), and for defining the machine-code equivalent of
11885: @code{DOES>}-based defining words. However, the machine-independent
11886: nature of Gforth poses a few problems: First of all, Gforth runs on
11887: several architectures, so it can provide no standard assembler. What's
11888: worse is that the register allocation not only depends on the processor,
11889: but also on the @code{gcc} version and options used.
1.44 crook 11890:
1.78 anton 11891: The words that Gforth offers encapsulate some system dependences (e.g.,
11892: the header structure), so a system-independent assembler may be used in
11893: Gforth. If you do not have an assembler, you can compile machine code
11894: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11895: because these words emit stuff in @i{data} space; it works because
11896: Gforth has unified code/data spaces. Assembler isn't likely to be
11897: portable anyway.}.
1.21 crook 11898:
1.44 crook 11899:
1.78 anton 11900: doc-assembler
11901: doc-init-asm
11902: doc-code
11903: doc-end-code
11904: doc-;code
11905: doc-flush-icache
1.44 crook 11906:
1.21 crook 11907:
1.78 anton 11908: If @code{flush-icache} does not work correctly, @code{code} words
11909: etc. will not work (reliably), either.
1.44 crook 11910:
1.78 anton 11911: The typical usage of these @code{code} words can be shown most easily by
11912: analogy to the equivalent high-level defining words:
1.44 crook 11913:
1.78 anton 11914: @example
11915: : foo code foo
11916: <high-level Forth words> <assembler>
11917: ; end-code
11918:
11919: : bar : bar
11920: <high-level Forth words> <high-level Forth words>
11921: CREATE CREATE
11922: <high-level Forth words> <high-level Forth words>
11923: DOES> ;code
11924: <high-level Forth words> <assembler>
11925: ; end-code
11926: @end example
1.21 crook 11927:
1.78 anton 11928: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11929:
1.78 anton 11930: @cindex registers of the inner interpreter
11931: In the assembly code you will want to refer to the inner interpreter's
11932: registers (e.g., the data stack pointer) and you may want to use other
11933: registers for temporary storage. Unfortunately, the register allocation
11934: is installation-dependent.
1.44 crook 11935:
1.78 anton 11936: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11937: (return stack pointer) may be in different places in @code{gforth} and
11938: @code{gforth-fast}, or different installations. This means that you
11939: cannot write a @code{NEXT} routine that works reliably on both versions
11940: or different installations; so for doing @code{NEXT}, I recommend
11941: jumping to @code{' noop >code-address}, which contains nothing but a
11942: @code{NEXT}.
1.21 crook 11943:
1.78 anton 11944: For general accesses to the inner interpreter's registers, the easiest
11945: solution is to use explicit register declarations (@pxref{Explicit Reg
11946: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11947: all of the inner interpreter's registers: You have to compile Gforth
11948: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11949: the appropriate declarations must be present in the @code{machine.h}
11950: file (see @code{mips.h} for an example; you can find a full list of all
11951: declarable register symbols with @code{grep register engine.c}). If you
11952: give explicit registers to all variables that are declared at the
11953: beginning of @code{engine()}, you should be able to use the other
11954: caller-saved registers for temporary storage. Alternatively, you can use
11955: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11956: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11957: reserve a register (however, this restriction on register allocation may
11958: slow Gforth significantly).
1.44 crook 11959:
1.78 anton 11960: If this solution is not viable (e.g., because @code{gcc} does not allow
11961: you to explicitly declare all the registers you need), you have to find
11962: out by looking at the code where the inner interpreter's registers
11963: reside and which registers can be used for temporary storage. You can
11964: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11965:
1.78 anton 11966: In any case, it is good practice to abstract your assembly code from the
11967: actual register allocation. E.g., if the data stack pointer resides in
11968: register @code{$17}, create an alias for this register called @code{sp},
11969: and use that in your assembly code.
1.21 crook 11970:
1.78 anton 11971: @cindex code words, portable
11972: Another option for implementing normal and defining words efficiently
11973: is to add the desired functionality to the source of Gforth. For normal
11974: words you just have to edit @file{primitives} (@pxref{Automatic
11975: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11976: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11977: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11978:
1.78 anton 11979: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11980: @subsection Common Assembler
1.44 crook 11981:
1.78 anton 11982: The assemblers in Gforth generally use a postfix syntax, i.e., the
11983: instruction name follows the operands.
1.21 crook 11984:
1.78 anton 11985: The operands are passed in the usual order (the same that is used in the
11986: manual of the architecture). Since they all are Forth words, they have
11987: to be separated by spaces; you can also use Forth words to compute the
11988: operands.
1.44 crook 11989:
1.78 anton 11990: The instruction names usually end with a @code{,}. This makes it easier
11991: to visually separate instructions if you put several of them on one
11992: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11993:
1.78 anton 11994: Registers are usually specified by number; e.g., (decimal) @code{11}
11995: specifies registers R11 and F11 on the Alpha architecture (which one,
11996: depends on the instruction). The usual names are also available, e.g.,
11997: @code{s2} for R11 on Alpha.
1.21 crook 11998:
1.78 anton 11999: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12000: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12001: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12002: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12003: conditions are specified in a way specific to each assembler.
1.1 anton 12004:
1.78 anton 12005: Note that the register assignments of the Gforth engine can change
12006: between Gforth versions, or even between different compilations of the
12007: same Gforth version (e.g., if you use a different GCC version). So if
12008: you want to refer to Gforth's registers (e.g., the stack pointer or
12009: TOS), I recommend defining your own words for refering to these
12010: registers, and using them later on; then you can easily adapt to a
12011: changed register assignment. The stability of the register assignment
12012: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12013:
1.100 anton 12014: The most common use of these registers is to dispatch to the next word
12015: (the @code{next} routine). A portable way to do this is to jump to
12016: @code{' noop >code-address} (of course, this is less efficient than
12017: integrating the @code{next} code and scheduling it well).
1.1 anton 12018:
1.96 anton 12019: Another difference between Gforth version is that the top of stack is
12020: kept in memory in @code{gforth} and, on most platforms, in a register in
12021: @code{gforth-fast}.
12022:
1.78 anton 12023: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12024: @subsection Common Disassembler
1.127 anton 12025: @cindex disassembler, general
12026: @cindex gdb disassembler
1.1 anton 12027:
1.78 anton 12028: You can disassemble a @code{code} word with @code{see}
12029: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12030:
1.127 anton 12031: doc-discode
1.44 crook 12032:
1.127 anton 12033: There are two kinds of disassembler for Gforth: The Forth disassembler
12034: (available on some CPUs) and the gdb disassembler (available on
12035: platforms with @command{gdb} and @command{mktemp}). If both are
12036: available, the Forth disassembler is used by default. If you prefer
12037: the gdb disassembler, say
12038:
12039: @example
12040: ' disasm-gdb is discode
12041: @end example
12042:
12043: If neither is available, @code{discode} performs @code{dump}.
12044:
12045: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12046: assembler (i.e., same syntax, etc.). It also includes additional
12047: information in comments. In particular, the address of the instruction
12048: is given in a comment before the instruction.
1.1 anton 12049:
1.127 anton 12050: The gdb disassembler produces output in the same format as the gdb
12051: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12052: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12053: the 386 and AMD64 architectures).
12054:
1.78 anton 12055: @code{See} may display more or less than the actual code of the word,
12056: because the recognition of the end of the code is unreliable. You can
1.127 anton 12057: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12058: the code word is not immediately followed by a named word. If you have
1.116 anton 12059: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12060: to ensure that the end is recognized.
1.21 crook 12061:
1.78 anton 12062: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12063: @subsection 386 Assembler
1.44 crook 12064:
1.78 anton 12065: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12066: available under GPL, and originally part of bigFORTH.
1.21 crook 12067:
1.78 anton 12068: The 386 disassembler included in Gforth was written by Andrew McKewan
12069: and is in the public domain.
1.21 crook 12070:
1.91 anton 12071: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12072:
1.78 anton 12073: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12074:
1.78 anton 12075: The assembler includes all instruction of the Athlon, i.e. 486 core
12076: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12077: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12078: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12079:
1.78 anton 12080: There are several prefixes to switch between different operation sizes,
12081: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12082: double-word accesses. Addressing modes can be switched with @code{.wa}
12083: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12084: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12085:
1.78 anton 12086: For floating point operations, the prefixes are @code{.fs} (IEEE
12087: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12088: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12089:
1.78 anton 12090: The MMX opcodes don't have size prefixes, they are spelled out like in
12091: the Intel assembler. Instead of move from and to memory, there are
12092: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12093:
1.78 anton 12094: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12095: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12096: e.g., @code{3 #}. Here are some examples of addressing modes in various
12097: syntaxes:
1.21 crook 12098:
1.26 crook 12099: @example
1.91 anton 12100: Gforth Intel (NASM) AT&T (gas) Name
12101: .w ax ax %ax register (16 bit)
12102: ax eax %eax register (32 bit)
12103: 3 # offset 3 $3 immediate
12104: 1000 #) byte ptr 1000 1000 displacement
12105: bx ) [ebx] (%ebx) base
12106: 100 di d) 100[edi] 100(%edi) base+displacement
12107: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12108: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12109: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12110: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12111: @end example
12112:
12113: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12114: @code{DI)} to enforce 32-bit displacement fields (useful for
12115: later patching).
1.21 crook 12116:
1.78 anton 12117: Some example of instructions are:
1.1 anton 12118:
12119: @example
1.78 anton 12120: ax bx mov \ move ebx,eax
12121: 3 # ax mov \ mov eax,3
1.137 pazsan 12122: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12123: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12124: .w ax bx mov \ mov bx,ax
1.1 anton 12125: @end example
12126:
1.78 anton 12127: The following forms are supported for binary instructions:
1.1 anton 12128:
12129: @example
1.78 anton 12130: <reg> <reg> <inst>
12131: <n> # <reg> <inst>
12132: <mem> <reg> <inst>
12133: <reg> <mem> <inst>
1.136 pazsan 12134: <n> # <mem> <inst>
1.1 anton 12135: @end example
12136:
1.136 pazsan 12137: The shift/rotate syntax is:
1.1 anton 12138:
1.26 crook 12139: @example
1.78 anton 12140: <reg/mem> 1 # shl \ shortens to shift without immediate
12141: <reg/mem> 4 # shl
12142: <reg/mem> cl shl
1.26 crook 12143: @end example
1.1 anton 12144:
1.78 anton 12145: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12146: the byte version.
1.1 anton 12147:
1.78 anton 12148: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12149: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12150: pc < >= <= >}. (Note that most of these words shadow some Forth words
12151: when @code{assembler} is in front of @code{forth} in the search path,
12152: e.g., in @code{code} words). Currently the control structure words use
12153: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12154: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12155:
1.78 anton 12156: Here is an example of a @code{code} word (assumes that the stack pointer
12157: is in esi and the TOS is in ebx):
1.21 crook 12158:
1.26 crook 12159: @example
1.78 anton 12160: code my+ ( n1 n2 -- n )
12161: 4 si D) bx add
12162: 4 # si add
12163: Next
12164: end-code
1.26 crook 12165: @end example
1.21 crook 12166:
1.78 anton 12167: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12168: @subsection Alpha Assembler
1.21 crook 12169:
1.78 anton 12170: The Alpha assembler and disassembler were originally written by Bernd
12171: Thallner.
1.26 crook 12172:
1.78 anton 12173: The register names @code{a0}--@code{a5} are not available to avoid
12174: shadowing hex numbers.
1.2 jwilke 12175:
1.78 anton 12176: Immediate forms of arithmetic instructions are distinguished by a
12177: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12178: does not count as arithmetic instruction).
1.2 jwilke 12179:
1.78 anton 12180: You have to specify all operands to an instruction, even those that
12181: other assemblers consider optional, e.g., the destination register for
12182: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12183:
1.78 anton 12184: You can specify conditions for @code{if,} by removing the first @code{b}
12185: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12186:
1.26 crook 12187: @example
1.78 anton 12188: 11 fgt if, \ if F11>0e
12189: ...
12190: endif,
1.26 crook 12191: @end example
1.2 jwilke 12192:
1.78 anton 12193: @code{fbgt,} gives @code{fgt}.
12194:
12195: @node MIPS assembler, Other assemblers, Alpha Assembler, Assembler and Code Words
12196: @subsection MIPS assembler
1.2 jwilke 12197:
1.78 anton 12198: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12199:
1.78 anton 12200: Currently the assembler and disassembler only cover the MIPS-I
12201: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12202:
1.78 anton 12203: The register names @code{$a0}--@code{$a3} are not available to avoid
12204: shadowing hex numbers.
1.2 jwilke 12205:
1.78 anton 12206: Because there is no way to distinguish registers from immediate values,
12207: you have to explicitly use the immediate forms of instructions, i.e.,
12208: @code{addiu,}, not just @code{addu,} (@command{as} does this
12209: implicitly).
1.2 jwilke 12210:
1.78 anton 12211: If the architecture manual specifies several formats for the instruction
12212: (e.g., for @code{jalr,}), you usually have to use the one with more
12213: arguments (i.e., two for @code{jalr,}). When in doubt, see
12214: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12215:
1.78 anton 12216: Branches and jumps in the MIPS architecture have a delay slot. You have
12217: to fill it yourself (the simplest way is to use @code{nop,}), the
12218: assembler does not do it for you (unlike @command{as}). Even
12219: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12220: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12221: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12222:
1.78 anton 12223: Note that you must not put branches, jumps, or @code{li,} into the delay
12224: slot: @code{li,} may expand to several instructions, and control flow
12225: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12226:
1.78 anton 12227: For branches the argument specifying the target is a relative address;
12228: You have to add the address of the delay slot to get the absolute
12229: address.
1.1 anton 12230:
1.78 anton 12231: The MIPS architecture also has load delay slots and restrictions on
12232: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12233: yourself to satisfy these restrictions, the assembler does not do it for
12234: you.
1.1 anton 12235:
1.78 anton 12236: You can specify the conditions for @code{if,} etc. by taking a
12237: conditional branch and leaving away the @code{b} at the start and the
12238: @code{,} at the end. E.g.,
1.1 anton 12239:
1.26 crook 12240: @example
1.78 anton 12241: 4 5 eq if,
12242: ... \ do something if $4 equals $5
12243: then,
1.26 crook 12244: @end example
1.1 anton 12245:
1.78 anton 12246: @node Other assemblers, , MIPS assembler, Assembler and Code Words
12247: @subsection Other assemblers
12248:
12249: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12250: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12251: an assembler already. If you are writing them from scratch, please use
12252: a similar syntax style as the one we use (i.e., postfix, commas at the
12253: end of the instruction names, @pxref{Common Assembler}); make the output
12254: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12255: similar to the style we used.
12256:
12257: Hints on implementation: The most important part is to have a good test
12258: suite that contains all instructions. Once you have that, the rest is
12259: easy. For actual coding you can take a look at
12260: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12261: the assembler and disassembler, avoiding redundancy and some potential
12262: bugs. You can also look at that file (and @pxref{Advanced does> usage
12263: example}) to get ideas how to factor a disassembler.
12264:
12265: Start with the disassembler, because it's easier to reuse data from the
12266: disassembler for the assembler than the other way round.
1.1 anton 12267:
1.78 anton 12268: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12269: how simple it can be.
1.1 anton 12270:
1.78 anton 12271: @c -------------------------------------------------------------
12272: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12273: @section Threading Words
12274: @cindex threading words
1.1 anton 12275:
1.78 anton 12276: @cindex code address
12277: These words provide access to code addresses and other threading stuff
12278: in Gforth (and, possibly, other interpretive Forths). It more or less
12279: abstracts away the differences between direct and indirect threading
12280: (and, for direct threading, the machine dependences). However, at
12281: present this wordset is still incomplete. It is also pretty low-level;
12282: some day it will hopefully be made unnecessary by an internals wordset
12283: that abstracts implementation details away completely.
1.1 anton 12284:
1.78 anton 12285: The terminology used here stems from indirect threaded Forth systems; in
12286: such a system, the XT of a word is represented by the CFA (code field
12287: address) of a word; the CFA points to a cell that contains the code
12288: address. The code address is the address of some machine code that
12289: performs the run-time action of invoking the word (e.g., the
12290: @code{dovar:} routine pushes the address of the body of the word (a
12291: variable) on the stack
12292: ).
1.1 anton 12293:
1.78 anton 12294: @cindex code address
12295: @cindex code field address
12296: In an indirect threaded Forth, you can get the code address of @i{name}
12297: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12298: >code-address}, independent of the threading method.
1.1 anton 12299:
1.78 anton 12300: doc-threading-method
12301: doc->code-address
12302: doc-code-address!
1.1 anton 12303:
1.78 anton 12304: @cindex @code{does>}-handler
12305: @cindex @code{does>}-code
12306: For a word defined with @code{DOES>}, the code address usually points to
12307: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12308: routine (in Gforth on some platforms, it can also point to the dodoes
12309: routine itself). What you are typically interested in, though, is
12310: whether a word is a @code{DOES>}-defined word, and what Forth code it
12311: executes; @code{>does-code} tells you that.
1.1 anton 12312:
1.78 anton 12313: doc->does-code
1.1 anton 12314:
1.78 anton 12315: To create a @code{DOES>}-defined word with the following basic words,
12316: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12317: @code{/does-handler} aus behind you have to place your executable Forth
12318: code. Finally you have to create a word and modify its behaviour with
12319: @code{does-handler!}.
1.1 anton 12320:
1.78 anton 12321: doc-does-code!
12322: doc-does-handler!
12323: doc-/does-handler
1.1 anton 12324:
1.78 anton 12325: The code addresses produced by various defining words are produced by
12326: the following words:
1.1 anton 12327:
1.78 anton 12328: doc-docol:
12329: doc-docon:
12330: doc-dovar:
12331: doc-douser:
12332: doc-dodefer:
12333: doc-dofield:
1.1 anton 12334:
1.99 anton 12335: @cindex definer
12336: The following two words generalize @code{>code-address},
12337: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12338:
12339: doc->definer
12340: doc-definer!
12341:
1.26 crook 12342: @c -------------------------------------------------------------
1.78 anton 12343: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12344: @section Passing Commands to the Operating System
12345: @cindex operating system - passing commands
12346: @cindex shell commands
12347:
12348: Gforth allows you to pass an arbitrary string to the host operating
12349: system shell (if such a thing exists) for execution.
12350:
12351: doc-sh
12352: doc-system
12353: doc-$?
1.23 crook 12354: doc-getenv
1.44 crook 12355:
1.26 crook 12356: @c -------------------------------------------------------------
1.47 crook 12357: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12358: @section Keeping track of Time
12359: @cindex time-related words
12360:
12361: doc-ms
12362: doc-time&date
1.79 anton 12363: doc-utime
12364: doc-cputime
1.47 crook 12365:
12366:
12367: @c -------------------------------------------------------------
12368: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12369: @section Miscellaneous Words
12370: @cindex miscellaneous words
12371:
1.29 crook 12372: @comment TODO find homes for these
12373:
1.26 crook 12374: These section lists the ANS Forth words that are not documented
1.21 crook 12375: elsewhere in this manual. Ultimately, they all need proper homes.
12376:
1.68 anton 12377: doc-quit
1.44 crook 12378:
1.26 crook 12379: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12380: (@pxref{ANS conformance}):
1.21 crook 12381:
12382: @code{EDITOR}
12383: @code{EMIT?}
12384: @code{FORGET}
12385:
1.24 anton 12386: @c ******************************************************************
12387: @node Error messages, Tools, Words, Top
12388: @chapter Error messages
12389: @cindex error messages
12390: @cindex backtrace
12391:
12392: A typical Gforth error message looks like this:
12393:
12394: @example
1.86 anton 12395: in file included from \evaluated string/:-1
1.24 anton 12396: in file included from ./yyy.fs:1
12397: ./xxx.fs:4: Invalid memory address
1.134 anton 12398: >>>bar<<<
1.79 anton 12399: Backtrace:
1.25 anton 12400: $400E664C @@
12401: $400E6664 foo
1.24 anton 12402: @end example
12403:
12404: The message identifying the error is @code{Invalid memory address}. The
12405: error happened when text-interpreting line 4 of the file
12406: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12407: word on the line where the error happened, is pointed out (with
1.134 anton 12408: @code{>>>} and @code{<<<}).
1.24 anton 12409:
12410: The file containing the error was included in line 1 of @file{./yyy.fs},
12411: and @file{yyy.fs} was included from a non-file (in this case, by giving
12412: @file{yyy.fs} as command-line parameter to Gforth).
12413:
12414: At the end of the error message you find a return stack dump that can be
12415: interpreted as a backtrace (possibly empty). On top you find the top of
12416: the return stack when the @code{throw} happened, and at the bottom you
12417: find the return stack entry just above the return stack of the topmost
12418: text interpreter.
12419:
12420: To the right of most return stack entries you see a guess for the word
12421: that pushed that return stack entry as its return address. This gives a
12422: backtrace. In our case we see that @code{bar} called @code{foo}, and
12423: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12424: address} exception).
12425:
12426: Note that the backtrace is not perfect: We don't know which return stack
12427: entries are return addresses (so we may get false positives); and in
12428: some cases (e.g., for @code{abort"}) we cannot determine from the return
12429: address the word that pushed the return address, so for some return
12430: addresses you see no names in the return stack dump.
1.25 anton 12431:
12432: @cindex @code{catch} and backtraces
12433: The return stack dump represents the return stack at the time when a
12434: specific @code{throw} was executed. In programs that make use of
12435: @code{catch}, it is not necessarily clear which @code{throw} should be
12436: used for the return stack dump (e.g., consider one @code{throw} that
12437: indicates an error, which is caught, and during recovery another error
1.42 anton 12438: happens; which @code{throw} should be used for the stack dump?). Gforth
1.25 anton 12439: presents the return stack dump for the first @code{throw} after the last
12440: executed (not returned-to) @code{catch}; this works well in the usual
12441: case.
12442:
12443: @cindex @code{gforth-fast} and backtraces
12444: @cindex @code{gforth-fast}, difference from @code{gforth}
12445: @cindex backtraces with @code{gforth-fast}
12446: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12447: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12448: from primitives (e.g., invalid memory address, stack empty etc.);
12449: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12450: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12451: exception caused by a primitive in @code{gforth-fast}, you will
12452: typically see no return stack dump at all; however, if the exception is
12453: caught by @code{catch} (e.g., for restoring some state), and then
12454: @code{throw}n again, the return stack dump will be for the first such
12455: @code{throw}.
1.2 jwilke 12456:
1.5 anton 12457: @c ******************************************************************
1.24 anton 12458: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12459: @chapter Tools
12460:
12461: @menu
12462: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12463: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12464: @end menu
12465:
12466: See also @ref{Emacs and Gforth}.
12467:
1.126 pazsan 12468: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12469: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12470: @cindex @file{ans-report.fs}
12471: @cindex report the words used in your program
12472: @cindex words used in your program
12473:
12474: If you want to label a Forth program as ANS Forth Program, you must
12475: document which wordsets the program uses; for extension wordsets, it is
12476: helpful to list the words the program requires from these wordsets
12477: (because Forth systems are allowed to provide only some words of them).
12478:
12479: The @file{ans-report.fs} tool makes it easy for you to determine which
12480: words from which wordset and which non-ANS words your application
12481: uses. You simply have to include @file{ans-report.fs} before loading the
12482: program you want to check. After loading your program, you can get the
12483: report with @code{print-ans-report}. A typical use is to run this as
12484: batch job like this:
12485: @example
12486: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12487: @end example
12488:
12489: The output looks like this (for @file{compat/control.fs}):
12490: @example
12491: The program uses the following words
12492: from CORE :
12493: : POSTPONE THEN ; immediate ?dup IF 0=
12494: from BLOCK-EXT :
12495: \
12496: from FILE :
12497: (
12498: @end example
12499:
12500: @subsection Caveats
12501:
12502: Note that @file{ans-report.fs} just checks which words are used, not whether
12503: they are used in an ANS Forth conforming way!
12504:
12505: Some words are defined in several wordsets in the
12506: standard. @file{ans-report.fs} reports them for only one of the
12507: wordsets, and not necessarily the one you expect. It depends on usage
12508: which wordset is the right one to specify. E.g., if you only use the
12509: compilation semantics of @code{S"}, it is a Core word; if you also use
12510: its interpretation semantics, it is a File word.
1.124 anton 12511:
12512:
1.127 anton 12513: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12514: @section Stack depth changes during interpretation
12515: @cindex @file{depth-changes.fs}
12516: @cindex depth changes during interpretation
12517: @cindex stack depth changes during interpretation
12518: @cindex items on the stack after interpretation
12519:
12520: Sometimes you notice that, after loading a file, there are items left
12521: on the stack. The tool @file{depth-changes.fs} helps you find out
12522: quickly where in the file these stack items are coming from.
12523:
12524: The simplest way of using @file{depth-changes.fs} is to include it
12525: before the file(s) you want to check, e.g.:
12526:
12527: @example
12528: gforth depth-changes.fs my-file.fs
12529: @end example
12530:
12531: This will compare the stack depths of the data and FP stack at every
12532: empty line (in interpretation state) against these depths at the last
12533: empty line (in interpretation state). If the depths are not equal,
12534: the position in the file and the stack contents are printed with
12535: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12536: change has occured in the paragraph of non-empty lines before the
12537: indicated line. It is a good idea to leave an empty line at the end
12538: of the file, so the last paragraph is checked, too.
12539:
12540: Checking only at empty lines usually works well, but sometimes you
12541: have big blocks of non-empty lines (e.g., when building a big table),
12542: and you want to know where in this block the stack depth changed. You
12543: can check all interpreted lines with
12544:
12545: @example
12546: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12547: @end example
12548:
12549: This checks the stack depth at every end-of-line. So the depth change
12550: occured in the line reported by the @code{~~} (not in the line
12551: before).
12552:
12553: Note that, while this offers better accuracy in indicating where the
12554: stack depth changes, it will often report many intentional stack depth
12555: changes (e.g., when an interpreted computation stretches across
12556: several lines). You can suppress the checking of some lines by
12557: putting backslashes at the end of these lines (not followed by white
12558: space), and using
12559:
12560: @example
12561: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12562: @end example
1.1 anton 12563:
12564: @c ******************************************************************
1.65 anton 12565: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12566: @chapter ANS conformance
12567: @cindex ANS conformance of Gforth
12568:
12569: To the best of our knowledge, Gforth is an
12570:
12571: ANS Forth System
12572: @itemize @bullet
12573: @item providing the Core Extensions word set
12574: @item providing the Block word set
12575: @item providing the Block Extensions word set
12576: @item providing the Double-Number word set
12577: @item providing the Double-Number Extensions word set
12578: @item providing the Exception word set
12579: @item providing the Exception Extensions word set
12580: @item providing the Facility word set
1.40 anton 12581: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12582: @item providing the File Access word set
12583: @item providing the File Access Extensions word set
12584: @item providing the Floating-Point word set
12585: @item providing the Floating-Point Extensions word set
12586: @item providing the Locals word set
12587: @item providing the Locals Extensions word set
12588: @item providing the Memory-Allocation word set
12589: @item providing the Memory-Allocation Extensions word set (that one's easy)
12590: @item providing the Programming-Tools word set
12591: @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
12592: @item providing the Search-Order word set
12593: @item providing the Search-Order Extensions word set
12594: @item providing the String word set
12595: @item providing the String Extensions word set (another easy one)
12596: @end itemize
12597:
1.118 anton 12598: Gforth has the following environmental restrictions:
12599:
12600: @cindex environmental restrictions
12601: @itemize @bullet
12602: @item
12603: While processing the OS command line, if an exception is not caught,
12604: Gforth exits with a non-zero exit code instyead of performing QUIT.
12605:
12606: @item
12607: When an @code{throw} is performed after a @code{query}, Gforth does not
12608: allways restore the input source specification in effect at the
12609: corresponding catch.
12610:
12611: @end itemize
12612:
12613:
1.1 anton 12614: @cindex system documentation
12615: In addition, ANS Forth systems are required to document certain
12616: implementation choices. This chapter tries to meet these
12617: requirements. In many cases it gives a way to ask the system for the
12618: information instead of providing the information directly, in
12619: particular, if the information depends on the processor, the operating
12620: system or the installation options chosen, or if they are likely to
12621: change during the maintenance of Gforth.
12622:
12623: @comment The framework for the rest has been taken from pfe.
12624:
12625: @menu
12626: * The Core Words::
12627: * The optional Block word set::
12628: * The optional Double Number word set::
12629: * The optional Exception word set::
12630: * The optional Facility word set::
12631: * The optional File-Access word set::
12632: * The optional Floating-Point word set::
12633: * The optional Locals word set::
12634: * The optional Memory-Allocation word set::
12635: * The optional Programming-Tools word set::
12636: * The optional Search-Order word set::
12637: @end menu
12638:
12639:
12640: @c =====================================================================
12641: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12642: @comment node-name, next, previous, up
12643: @section The Core Words
12644: @c =====================================================================
12645: @cindex core words, system documentation
12646: @cindex system documentation, core words
12647:
12648: @menu
12649: * core-idef:: Implementation Defined Options
12650: * core-ambcond:: Ambiguous Conditions
12651: * core-other:: Other System Documentation
12652: @end menu
12653:
12654: @c ---------------------------------------------------------------------
12655: @node core-idef, core-ambcond, The Core Words, The Core Words
12656: @subsection Implementation Defined Options
12657: @c ---------------------------------------------------------------------
12658: @cindex core words, implementation-defined options
12659: @cindex implementation-defined options, core words
12660:
12661:
12662: @table @i
12663: @item (Cell) aligned addresses:
12664: @cindex cell-aligned addresses
12665: @cindex aligned addresses
12666: processor-dependent. Gforth's alignment words perform natural alignment
12667: (e.g., an address aligned for a datum of size 8 is divisible by
12668: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12669:
12670: @item @code{EMIT} and non-graphic characters:
12671: @cindex @code{EMIT} and non-graphic characters
12672: @cindex non-graphic characters and @code{EMIT}
12673: The character is output using the C library function (actually, macro)
12674: @code{putc}.
12675:
12676: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12677: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12678: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12679: @cindex @code{ACCEPT}, editing
12680: @cindex @code{EXPECT}, editing
12681: This is modeled on the GNU readline library (@pxref{Readline
12682: Interaction, , Command Line Editing, readline, The GNU Readline
12683: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12684: producing a full word completion every time you type it (instead of
1.28 crook 12685: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12686:
12687: @item character set:
12688: @cindex character set
12689: The character set of your computer and display device. Gforth is
12690: 8-bit-clean (but some other component in your system may make trouble).
12691:
12692: @item Character-aligned address requirements:
12693: @cindex character-aligned address requirements
12694: installation-dependent. Currently a character is represented by a C
12695: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12696: (Comments on that requested).
12697:
12698: @item character-set extensions and matching of names:
12699: @cindex character-set extensions and matching of names
1.26 crook 12700: @cindex case-sensitivity for name lookup
12701: @cindex name lookup, case-sensitivity
12702: @cindex locale and case-sensitivity
1.21 crook 12703: Any character except the ASCII NUL character can be used in a
1.1 anton 12704: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12705: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12706: function is probably influenced by the locale. E.g., the @code{C} locale
12707: does not know about accents and umlauts, so they are matched
12708: case-sensitively in that locale. For portability reasons it is best to
12709: write programs such that they work in the @code{C} locale. Then one can
12710: use libraries written by a Polish programmer (who might use words
12711: containing ISO Latin-2 encoded characters) and by a French programmer
12712: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12713: funny results for some of the words (which ones, depends on the font you
12714: are using)). Also, the locale you prefer may not be available in other
12715: operating systems. Hopefully, Unicode will solve these problems one day.
12716:
12717: @item conditions under which control characters match a space delimiter:
12718: @cindex space delimiters
12719: @cindex control characters as delimiters
1.117 anton 12720: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12721: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12722: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12723: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12724: interpreter (aka text interpreter) by default, treats all white-space
12725: characters as delimiters.
12726:
1.26 crook 12727: @item format of the control-flow stack:
12728: @cindex control-flow stack, format
12729: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12730: stack item in cells is given by the constant @code{cs-item-size}. At the
12731: time of this writing, an item consists of a (pointer to a) locals list
12732: (third), an address in the code (second), and a tag for identifying the
12733: item (TOS). The following tags are used: @code{defstart},
12734: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12735: @code{scopestart}.
12736:
12737: @item conversion of digits > 35
12738: @cindex digits > 35
12739: The characters @code{[\]^_'} are the digits with the decimal value
12740: 36@minus{}41. There is no way to input many of the larger digits.
12741:
12742: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12743: @cindex @code{EXPECT}, display after end of input
12744: @cindex @code{ACCEPT}, display after end of input
12745: The cursor is moved to the end of the entered string. If the input is
12746: terminated using the @kbd{Return} key, a space is typed.
12747:
12748: @item exception abort sequence of @code{ABORT"}:
12749: @cindex exception abort sequence of @code{ABORT"}
12750: @cindex @code{ABORT"}, exception abort sequence
12751: The error string is stored into the variable @code{"error} and a
12752: @code{-2 throw} is performed.
12753:
12754: @item input line terminator:
12755: @cindex input line terminator
12756: @cindex line terminator on input
1.26 crook 12757: @cindex newline character on input
1.1 anton 12758: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12759: lines. One of these characters is typically produced when you type the
12760: @kbd{Enter} or @kbd{Return} key.
12761:
12762: @item maximum size of a counted string:
12763: @cindex maximum size of a counted string
12764: @cindex counted string, maximum size
12765: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12766: on all platforms, but this may change.
1.1 anton 12767:
12768: @item maximum size of a parsed string:
12769: @cindex maximum size of a parsed string
12770: @cindex parsed string, maximum size
12771: Given by the constant @code{/line}. Currently 255 characters.
12772:
12773: @item maximum size of a definition name, in characters:
12774: @cindex maximum size of a definition name, in characters
12775: @cindex name, maximum length
1.113 anton 12776: MAXU/8
1.1 anton 12777:
12778: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12779: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12780: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12781: MAXU/8
1.1 anton 12782:
12783: @item method of selecting the user input device:
12784: @cindex user input device, method of selecting
12785: The user input device is the standard input. There is currently no way to
12786: change it from within Gforth. However, the input can typically be
12787: redirected in the command line that starts Gforth.
12788:
12789: @item method of selecting the user output device:
12790: @cindex user output device, method of selecting
12791: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12792: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12793: output when the user output device is a terminal, otherwise the output
12794: is buffered.
1.1 anton 12795:
12796: @item methods of dictionary compilation:
12797: What are we expected to document here?
12798:
12799: @item number of bits in one address unit:
12800: @cindex number of bits in one address unit
12801: @cindex address unit, size in bits
12802: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12803: platforms.
1.1 anton 12804:
12805: @item number representation and arithmetic:
12806: @cindex number representation and arithmetic
1.79 anton 12807: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12808:
12809: @item ranges for integer types:
12810: @cindex ranges for integer types
12811: @cindex integer types, ranges
12812: Installation-dependent. Make environmental queries for @code{MAX-N},
12813: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12814: unsigned (and positive) types is 0. The lower bound for signed types on
12815: two's complement and one's complement machines machines can be computed
12816: by adding 1 to the upper bound.
12817:
12818: @item read-only data space regions:
12819: @cindex read-only data space regions
12820: @cindex data-space, read-only regions
12821: The whole Forth data space is writable.
12822:
12823: @item size of buffer at @code{WORD}:
12824: @cindex size of buffer at @code{WORD}
12825: @cindex @code{WORD} buffer size
12826: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12827: shared with the pictured numeric output string. If overwriting
12828: @code{PAD} is acceptable, it is as large as the remaining dictionary
12829: space, although only as much can be sensibly used as fits in a counted
12830: string.
12831:
12832: @item size of one cell in address units:
12833: @cindex cell size
12834: @code{1 cells .}.
12835:
12836: @item size of one character in address units:
12837: @cindex char size
1.79 anton 12838: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12839:
12840: @item size of the keyboard terminal buffer:
12841: @cindex size of the keyboard terminal buffer
12842: @cindex terminal buffer, size
12843: Varies. You can determine the size at a specific time using @code{lp@@
12844: tib - .}. It is shared with the locals stack and TIBs of files that
12845: include the current file. You can change the amount of space for TIBs
12846: and locals stack at Gforth startup with the command line option
12847: @code{-l}.
12848:
12849: @item size of the pictured numeric output buffer:
12850: @cindex size of the pictured numeric output buffer
12851: @cindex pictured numeric output buffer, size
12852: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12853: shared with @code{WORD}.
12854:
12855: @item size of the scratch area returned by @code{PAD}:
12856: @cindex size of the scratch area returned by @code{PAD}
12857: @cindex @code{PAD} size
12858: The remainder of dictionary space. @code{unused pad here - - .}.
12859:
12860: @item system case-sensitivity characteristics:
12861: @cindex case-sensitivity characteristics
1.26 crook 12862: Dictionary searches are case-insensitive (except in
1.1 anton 12863: @code{TABLE}s). However, as explained above under @i{character-set
12864: extensions}, the matching for non-ASCII characters is determined by the
12865: locale you are using. In the default @code{C} locale all non-ASCII
12866: characters are matched case-sensitively.
12867:
12868: @item system prompt:
12869: @cindex system prompt
12870: @cindex prompt
12871: @code{ ok} in interpret state, @code{ compiled} in compile state.
12872:
12873: @item division rounding:
12874: @cindex division rounding
12875: installation dependent. @code{s" floored" environment? drop .}. We leave
12876: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12877: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12878:
12879: @item values of @code{STATE} when true:
12880: @cindex @code{STATE} values
12881: -1.
12882:
12883: @item values returned after arithmetic overflow:
12884: On two's complement machines, arithmetic is performed modulo
12885: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12886: arithmetic (with appropriate mapping for signed types). Division by zero
12887: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12888: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12889:
12890: @item whether the current definition can be found after @t{DOES>}:
12891: @cindex @t{DOES>}, visibility of current definition
12892: No.
12893:
12894: @end table
12895:
12896: @c ---------------------------------------------------------------------
12897: @node core-ambcond, core-other, core-idef, The Core Words
12898: @subsection Ambiguous conditions
12899: @c ---------------------------------------------------------------------
12900: @cindex core words, ambiguous conditions
12901: @cindex ambiguous conditions, core words
12902:
12903: @table @i
12904:
12905: @item a name is neither a word nor a number:
12906: @cindex name not found
1.26 crook 12907: @cindex undefined word
1.80 anton 12908: @code{-13 throw} (Undefined word).
1.1 anton 12909:
12910: @item a definition name exceeds the maximum length allowed:
1.26 crook 12911: @cindex word name too long
1.1 anton 12912: @code{-19 throw} (Word name too long)
12913:
12914: @item addressing a region not inside the various data spaces of the forth system:
12915: @cindex Invalid memory address
1.32 anton 12916: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12917: typically readable. Accessing other addresses gives results dependent on
12918: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12919: address).
12920:
12921: @item argument type incompatible with parameter:
1.26 crook 12922: @cindex argument type mismatch
1.1 anton 12923: This is usually not caught. Some words perform checks, e.g., the control
12924: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12925: mismatch).
12926:
12927: @item attempting to obtain the execution token of a word with undefined execution semantics:
12928: @cindex Interpreting a compile-only word, for @code{'} etc.
12929: @cindex execution token of words with undefined execution semantics
12930: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12931: get an execution token for @code{compile-only-error} (which performs a
12932: @code{-14 throw} when executed).
12933:
12934: @item dividing by zero:
12935: @cindex dividing by zero
12936: @cindex floating point unidentified fault, integer division
1.80 anton 12937: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12938: zero); on other systems, this typically results in a @code{-55 throw}
12939: (Floating-point unidentified fault).
1.1 anton 12940:
12941: @item insufficient data stack or return stack space:
12942: @cindex insufficient data stack or return stack space
12943: @cindex stack overflow
1.26 crook 12944: @cindex address alignment exception, stack overflow
1.1 anton 12945: @cindex Invalid memory address, stack overflow
12946: Depending on the operating system, the installation, and the invocation
12947: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12948: it is not checked. If it is checked, you typically get a @code{-3 throw}
12949: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12950: throw} (Invalid memory address) (depending on the platform and how you
12951: achieved the overflow) as soon as the overflow happens. If it is not
12952: checked, overflows typically result in mysterious illegal memory
12953: accesses, producing @code{-9 throw} (Invalid memory address) or
12954: @code{-23 throw} (Address alignment exception); they might also destroy
12955: the internal data structure of @code{ALLOCATE} and friends, resulting in
12956: various errors in these words.
1.1 anton 12957:
12958: @item insufficient space for loop control parameters:
12959: @cindex insufficient space for loop control parameters
1.80 anton 12960: Like other return stack overflows.
1.1 anton 12961:
12962: @item insufficient space in the dictionary:
12963: @cindex insufficient space in the dictionary
12964: @cindex dictionary overflow
1.12 anton 12965: If you try to allot (either directly with @code{allot}, or indirectly
12966: with @code{,}, @code{create} etc.) more memory than available in the
12967: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
12968: to access memory beyond the end of the dictionary, the results are
12969: similar to stack overflows.
1.1 anton 12970:
12971: @item interpreting a word with undefined interpretation semantics:
12972: @cindex interpreting a word with undefined interpretation semantics
12973: @cindex Interpreting a compile-only word
12974: For some words, we have defined interpretation semantics. For the
12975: others: @code{-14 throw} (Interpreting a compile-only word).
12976:
12977: @item modifying the contents of the input buffer or a string literal:
12978: @cindex modifying the contents of the input buffer or a string literal
12979: These are located in writable memory and can be modified.
12980:
12981: @item overflow of the pictured numeric output string:
12982: @cindex overflow of the pictured numeric output string
12983: @cindex pictured numeric output string, overflow
1.24 anton 12984: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 12985:
12986: @item parsed string overflow:
12987: @cindex parsed string overflow
12988: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
12989:
12990: @item producing a result out of range:
12991: @cindex result out of range
12992: On two's complement machines, arithmetic is performed modulo
12993: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12994: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 12995: typically results in a @code{-10 throw} (divide by zero) or @code{-55
12996: throw} (floating point unidentified fault). @code{convert} and
12997: @code{>number} currently overflow silently.
1.1 anton 12998:
12999: @item reading from an empty data or return stack:
13000: @cindex stack empty
13001: @cindex stack underflow
1.24 anton 13002: @cindex return stack underflow
1.1 anton 13003: The data stack is checked by the outer (aka text) interpreter after
13004: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13005: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13006: depending on operating system, installation, and invocation. If they are
13007: caught by a check, they typically result in @code{-4 throw} (Stack
13008: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13009: (Invalid memory address), depending on the platform and which stack
13010: underflows and by how much. Note that even if the system uses checking
13011: (through the MMU), your program may have to underflow by a significant
13012: number of stack items to trigger the reaction (the reason for this is
13013: that the MMU, and therefore the checking, works with a page-size
13014: granularity). If there is no checking, the symptoms resulting from an
13015: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13016: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13017: (Invalid memory address) and Illegal Instruction (typically @code{-260
13018: throw}).
1.1 anton 13019:
13020: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13021: @cindex unexpected end of the input buffer
13022: @cindex zero-length string as a name
13023: @cindex Attempt to use zero-length string as a name
13024: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13025: use zero-length string as a name). Words like @code{'} probably will not
13026: find what they search. Note that it is possible to create zero-length
13027: names with @code{nextname} (should it not?).
13028:
13029: @item @code{>IN} greater than input buffer:
13030: @cindex @code{>IN} greater than input buffer
13031: The next invocation of a parsing word returns a string with length 0.
13032:
13033: @item @code{RECURSE} appears after @code{DOES>}:
13034: @cindex @code{RECURSE} appears after @code{DOES>}
13035: Compiles a recursive call to the defining word, not to the defined word.
13036:
13037: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13038: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13039: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13040: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13041: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13042: the end of the file was reached), its source-id may be
13043: reused. Therefore, restoring an input source specification referencing a
13044: closed file may lead to unpredictable results instead of a @code{-12
13045: THROW}.
13046:
13047: In the future, Gforth may be able to restore input source specifications
13048: from other than the current input source.
13049:
13050: @item data space containing definitions gets de-allocated:
13051: @cindex data space containing definitions gets de-allocated
13052: Deallocation with @code{allot} is not checked. This typically results in
13053: memory access faults or execution of illegal instructions.
13054:
13055: @item data space read/write with incorrect alignment:
13056: @cindex data space read/write with incorrect alignment
13057: @cindex alignment faults
1.26 crook 13058: @cindex address alignment exception
1.1 anton 13059: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13060: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13061: alignment turned on, incorrect alignment results in a @code{-9 throw}
13062: (Invalid memory address). There are reportedly some processors with
1.12 anton 13063: alignment restrictions that do not report violations.
1.1 anton 13064:
13065: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13066: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13067: Like other alignment errors.
13068:
13069: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13070: Like other stack underflows.
13071:
13072: @item loop control parameters not available:
13073: @cindex loop control parameters not available
13074: Not checked. The counted loop words simply assume that the top of return
13075: stack items are loop control parameters and behave accordingly.
13076:
13077: @item most recent definition does not have a name (@code{IMMEDIATE}):
13078: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13079: @cindex last word was headerless
13080: @code{abort" last word was headerless"}.
13081:
13082: @item name not defined by @code{VALUE} used by @code{TO}:
13083: @cindex name not defined by @code{VALUE} used by @code{TO}
13084: @cindex @code{TO} on non-@code{VALUE}s
13085: @cindex Invalid name argument, @code{TO}
13086: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13087: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13088:
13089: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13090: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13091: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13092: @code{-13 throw} (Undefined word)
13093:
13094: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13095: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13096: Gforth behaves as if they were of the same type. I.e., you can predict
13097: the behaviour by interpreting all parameters as, e.g., signed.
13098:
13099: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13100: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13101: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13102: compilation semantics of @code{TO}.
13103:
13104: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13105: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13106: @cindex @code{WORD}, string overflow
13107: Not checked. The string will be ok, but the count will, of course,
13108: contain only the least significant bits of the length.
13109:
13110: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13111: @cindex @code{LSHIFT}, large shift counts
13112: @cindex @code{RSHIFT}, large shift counts
13113: Processor-dependent. Typical behaviours are returning 0 and using only
13114: the low bits of the shift count.
13115:
13116: @item word not defined via @code{CREATE}:
13117: @cindex @code{>BODY} of non-@code{CREATE}d words
13118: @code{>BODY} produces the PFA of the word no matter how it was defined.
13119:
13120: @cindex @code{DOES>} of non-@code{CREATE}d words
13121: @code{DOES>} changes the execution semantics of the last defined word no
13122: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13123: @code{CREATE , DOES>}.
13124:
13125: @item words improperly used outside @code{<#} and @code{#>}:
13126: Not checked. As usual, you can expect memory faults.
13127:
13128: @end table
13129:
13130:
13131: @c ---------------------------------------------------------------------
13132: @node core-other, , core-ambcond, The Core Words
13133: @subsection Other system documentation
13134: @c ---------------------------------------------------------------------
13135: @cindex other system documentation, core words
13136: @cindex core words, other system documentation
13137:
13138: @table @i
13139: @item nonstandard words using @code{PAD}:
13140: @cindex @code{PAD} use by nonstandard words
13141: None.
13142:
13143: @item operator's terminal facilities available:
13144: @cindex operator's terminal facilities available
1.80 anton 13145: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13146: and you can give commands to Gforth interactively. The actual facilities
13147: available depend on how you invoke Gforth.
13148:
13149: @item program data space available:
13150: @cindex program data space available
13151: @cindex data space available
13152: @code{UNUSED .} gives the remaining dictionary space. The total
13153: dictionary space can be specified with the @code{-m} switch
13154: (@pxref{Invoking Gforth}) when Gforth starts up.
13155:
13156: @item return stack space available:
13157: @cindex return stack space available
13158: You can compute the total return stack space in cells with
13159: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13160: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13161:
13162: @item stack space available:
13163: @cindex stack space available
13164: You can compute the total data stack space in cells with
13165: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13166: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13167:
13168: @item system dictionary space required, in address units:
13169: @cindex system dictionary space required, in address units
13170: Type @code{here forthstart - .} after startup. At the time of this
13171: writing, this gives 80080 (bytes) on a 32-bit system.
13172: @end table
13173:
13174:
13175: @c =====================================================================
13176: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13177: @section The optional Block word set
13178: @c =====================================================================
13179: @cindex system documentation, block words
13180: @cindex block words, system documentation
13181:
13182: @menu
13183: * block-idef:: Implementation Defined Options
13184: * block-ambcond:: Ambiguous Conditions
13185: * block-other:: Other System Documentation
13186: @end menu
13187:
13188:
13189: @c ---------------------------------------------------------------------
13190: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13191: @subsection Implementation Defined Options
13192: @c ---------------------------------------------------------------------
13193: @cindex implementation-defined options, block words
13194: @cindex block words, implementation-defined options
13195:
13196: @table @i
13197: @item the format for display by @code{LIST}:
13198: @cindex @code{LIST} display format
13199: First the screen number is displayed, then 16 lines of 64 characters,
13200: each line preceded by the line number.
13201:
13202: @item the length of a line affected by @code{\}:
13203: @cindex length of a line affected by @code{\}
13204: @cindex @code{\}, line length in blocks
13205: 64 characters.
13206: @end table
13207:
13208:
13209: @c ---------------------------------------------------------------------
13210: @node block-ambcond, block-other, block-idef, The optional Block word set
13211: @subsection Ambiguous conditions
13212: @c ---------------------------------------------------------------------
13213: @cindex block words, ambiguous conditions
13214: @cindex ambiguous conditions, block words
13215:
13216: @table @i
13217: @item correct block read was not possible:
13218: @cindex block read not possible
13219: Typically results in a @code{throw} of some OS-derived value (between
13220: -512 and -2048). If the blocks file was just not long enough, blanks are
13221: supplied for the missing portion.
13222:
13223: @item I/O exception in block transfer:
13224: @cindex I/O exception in block transfer
13225: @cindex block transfer, I/O exception
13226: Typically results in a @code{throw} of some OS-derived value (between
13227: -512 and -2048).
13228:
13229: @item invalid block number:
13230: @cindex invalid block number
13231: @cindex block number invalid
13232: @code{-35 throw} (Invalid block number)
13233:
13234: @item a program directly alters the contents of @code{BLK}:
13235: @cindex @code{BLK}, altering @code{BLK}
13236: The input stream is switched to that other block, at the same
13237: position. If the storing to @code{BLK} happens when interpreting
13238: non-block input, the system will get quite confused when the block ends.
13239:
13240: @item no current block buffer for @code{UPDATE}:
13241: @cindex @code{UPDATE}, no current block buffer
13242: @code{UPDATE} has no effect.
13243:
13244: @end table
13245:
13246: @c ---------------------------------------------------------------------
13247: @node block-other, , block-ambcond, The optional Block word set
13248: @subsection Other system documentation
13249: @c ---------------------------------------------------------------------
13250: @cindex other system documentation, block words
13251: @cindex block words, other system documentation
13252:
13253: @table @i
13254: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13255: No restrictions (yet).
13256:
13257: @item the number of blocks available for source and data:
13258: depends on your disk space.
13259:
13260: @end table
13261:
13262:
13263: @c =====================================================================
13264: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13265: @section The optional Double Number word set
13266: @c =====================================================================
13267: @cindex system documentation, double words
13268: @cindex double words, system documentation
13269:
13270: @menu
13271: * double-ambcond:: Ambiguous Conditions
13272: @end menu
13273:
13274:
13275: @c ---------------------------------------------------------------------
13276: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13277: @subsection Ambiguous conditions
13278: @c ---------------------------------------------------------------------
13279: @cindex double words, ambiguous conditions
13280: @cindex ambiguous conditions, double words
13281:
13282: @table @i
1.29 crook 13283: @item @i{d} outside of range of @i{n} in @code{D>S}:
13284: @cindex @code{D>S}, @i{d} out of range of @i{n}
13285: The least significant cell of @i{d} is produced.
1.1 anton 13286:
13287: @end table
13288:
13289:
13290: @c =====================================================================
13291: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13292: @section The optional Exception word set
13293: @c =====================================================================
13294: @cindex system documentation, exception words
13295: @cindex exception words, system documentation
13296:
13297: @menu
13298: * exception-idef:: Implementation Defined Options
13299: @end menu
13300:
13301:
13302: @c ---------------------------------------------------------------------
13303: @node exception-idef, , The optional Exception word set, The optional Exception word set
13304: @subsection Implementation Defined Options
13305: @c ---------------------------------------------------------------------
13306: @cindex implementation-defined options, exception words
13307: @cindex exception words, implementation-defined options
13308:
13309: @table @i
13310: @item @code{THROW}-codes used in the system:
13311: @cindex @code{THROW}-codes used in the system
13312: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13313: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13314: codes -512@minus{}-2047 are used for OS errors (for file and memory
13315: allocation operations). The mapping from OS error numbers to throw codes
13316: is -512@minus{}@code{errno}. One side effect of this mapping is that
13317: undefined OS errors produce a message with a strange number; e.g.,
13318: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13319: @end table
13320:
13321: @c =====================================================================
13322: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13323: @section The optional Facility word set
13324: @c =====================================================================
13325: @cindex system documentation, facility words
13326: @cindex facility words, system documentation
13327:
13328: @menu
13329: * facility-idef:: Implementation Defined Options
13330: * facility-ambcond:: Ambiguous Conditions
13331: @end menu
13332:
13333:
13334: @c ---------------------------------------------------------------------
13335: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13336: @subsection Implementation Defined Options
13337: @c ---------------------------------------------------------------------
13338: @cindex implementation-defined options, facility words
13339: @cindex facility words, implementation-defined options
13340:
13341: @table @i
13342: @item encoding of keyboard events (@code{EKEY}):
13343: @cindex keyboard events, encoding in @code{EKEY}
13344: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13345: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13346: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13347: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13348: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13349: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13350:
1.1 anton 13351:
13352: @item duration of a system clock tick:
13353: @cindex duration of a system clock tick
13354: @cindex clock tick duration
13355: System dependent. With respect to @code{MS}, the time is specified in
13356: microseconds. How well the OS and the hardware implement this, is
13357: another question.
13358:
13359: @item repeatability to be expected from the execution of @code{MS}:
13360: @cindex repeatability to be expected from the execution of @code{MS}
13361: @cindex @code{MS}, repeatability to be expected
13362: System dependent. On Unix, a lot depends on load. If the system is
13363: lightly loaded, and the delay is short enough that Gforth does not get
13364: swapped out, the performance should be acceptable. Under MS-DOS and
13365: other single-tasking systems, it should be good.
13366:
13367: @end table
13368:
13369:
13370: @c ---------------------------------------------------------------------
13371: @node facility-ambcond, , facility-idef, The optional Facility word set
13372: @subsection Ambiguous conditions
13373: @c ---------------------------------------------------------------------
13374: @cindex facility words, ambiguous conditions
13375: @cindex ambiguous conditions, facility words
13376:
13377: @table @i
13378: @item @code{AT-XY} can't be performed on user output device:
13379: @cindex @code{AT-XY} can't be performed on user output device
13380: Largely terminal dependent. No range checks are done on the arguments.
13381: No errors are reported. You may see some garbage appearing, you may see
13382: simply nothing happen.
13383:
13384: @end table
13385:
13386:
13387: @c =====================================================================
13388: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13389: @section The optional File-Access word set
13390: @c =====================================================================
13391: @cindex system documentation, file words
13392: @cindex file words, system documentation
13393:
13394: @menu
13395: * file-idef:: Implementation Defined Options
13396: * file-ambcond:: Ambiguous Conditions
13397: @end menu
13398:
13399: @c ---------------------------------------------------------------------
13400: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13401: @subsection Implementation Defined Options
13402: @c ---------------------------------------------------------------------
13403: @cindex implementation-defined options, file words
13404: @cindex file words, implementation-defined options
13405:
13406: @table @i
13407: @item file access methods used:
13408: @cindex file access methods used
13409: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13410: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13411: @code{wb}): The file is cleared, if it exists, and created, if it does
13412: not (with both @code{open-file} and @code{create-file}). Under Unix
13413: @code{create-file} creates a file with 666 permissions modified by your
13414: umask.
13415:
13416: @item file exceptions:
13417: @cindex file exceptions
13418: The file words do not raise exceptions (except, perhaps, memory access
13419: faults when you pass illegal addresses or file-ids).
13420:
13421: @item file line terminator:
13422: @cindex file line terminator
13423: System-dependent. Gforth uses C's newline character as line
13424: terminator. What the actual character code(s) of this are is
13425: system-dependent.
13426:
13427: @item file name format:
13428: @cindex file name format
13429: System dependent. Gforth just uses the file name format of your OS.
13430:
13431: @item information returned by @code{FILE-STATUS}:
13432: @cindex @code{FILE-STATUS}, returned information
13433: @code{FILE-STATUS} returns the most powerful file access mode allowed
13434: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13435: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13436: along with the returned mode.
13437:
13438: @item input file state after an exception when including source:
13439: @cindex exception when including source
13440: All files that are left via the exception are closed.
13441:
1.29 crook 13442: @item @i{ior} values and meaning:
13443: @cindex @i{ior} values and meaning
1.68 anton 13444: @cindex @i{wior} values and meaning
1.29 crook 13445: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13446: intended as throw codes. They typically are in the range
13447: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13448: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13449:
13450: @item maximum depth of file input nesting:
13451: @cindex maximum depth of file input nesting
13452: @cindex file input nesting, maximum depth
13453: limited by the amount of return stack, locals/TIB stack, and the number
13454: of open files available. This should not give you troubles.
13455:
13456: @item maximum size of input line:
13457: @cindex maximum size of input line
13458: @cindex input line size, maximum
13459: @code{/line}. Currently 255.
13460:
13461: @item methods of mapping block ranges to files:
13462: @cindex mapping block ranges to files
13463: @cindex files containing blocks
13464: @cindex blocks in files
13465: By default, blocks are accessed in the file @file{blocks.fb} in the
13466: current working directory. The file can be switched with @code{USE}.
13467:
13468: @item number of string buffers provided by @code{S"}:
13469: @cindex @code{S"}, number of string buffers
13470: 1
13471:
13472: @item size of string buffer used by @code{S"}:
13473: @cindex @code{S"}, size of string buffer
13474: @code{/line}. currently 255.
13475:
13476: @end table
13477:
13478: @c ---------------------------------------------------------------------
13479: @node file-ambcond, , file-idef, The optional File-Access word set
13480: @subsection Ambiguous conditions
13481: @c ---------------------------------------------------------------------
13482: @cindex file words, ambiguous conditions
13483: @cindex ambiguous conditions, file words
13484:
13485: @table @i
13486: @item attempting to position a file outside its boundaries:
13487: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13488: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13489: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13490:
13491: @item attempting to read from file positions not yet written:
13492: @cindex reading from file positions not yet written
13493: End-of-file, i.e., zero characters are read and no error is reported.
13494:
1.29 crook 13495: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13496: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13497: An appropriate exception may be thrown, but a memory fault or other
13498: problem is more probable.
13499:
1.29 crook 13500: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13501: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13502: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13503: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13504: thrown.
13505:
13506: @item named file cannot be opened (@code{INCLUDED}):
13507: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13508: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13509:
13510: @item requesting an unmapped block number:
13511: @cindex unmapped block numbers
13512: There are no unmapped legal block numbers. On some operating systems,
13513: writing a block with a large number may overflow the file system and
13514: have an error message as consequence.
13515:
13516: @item using @code{source-id} when @code{blk} is non-zero:
13517: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13518: @code{source-id} performs its function. Typically it will give the id of
13519: the source which loaded the block. (Better ideas?)
13520:
13521: @end table
13522:
13523:
13524: @c =====================================================================
13525: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13526: @section The optional Floating-Point word set
13527: @c =====================================================================
13528: @cindex system documentation, floating-point words
13529: @cindex floating-point words, system documentation
13530:
13531: @menu
13532: * floating-idef:: Implementation Defined Options
13533: * floating-ambcond:: Ambiguous Conditions
13534: @end menu
13535:
13536:
13537: @c ---------------------------------------------------------------------
13538: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13539: @subsection Implementation Defined Options
13540: @c ---------------------------------------------------------------------
13541: @cindex implementation-defined options, floating-point words
13542: @cindex floating-point words, implementation-defined options
13543:
13544: @table @i
13545: @item format and range of floating point numbers:
13546: @cindex format and range of floating point numbers
13547: @cindex floating point numbers, format and range
13548: System-dependent; the @code{double} type of C.
13549:
1.29 crook 13550: @item results of @code{REPRESENT} when @i{float} is out of range:
13551: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13552: System dependent; @code{REPRESENT} is implemented using the C library
13553: function @code{ecvt()} and inherits its behaviour in this respect.
13554:
13555: @item rounding or truncation of floating-point numbers:
13556: @cindex rounding of floating-point numbers
13557: @cindex truncation of floating-point numbers
13558: @cindex floating-point numbers, rounding or truncation
13559: System dependent; the rounding behaviour is inherited from the hosting C
13560: compiler. IEEE-FP-based (i.e., most) systems by default round to
13561: nearest, and break ties by rounding to even (i.e., such that the last
13562: bit of the mantissa is 0).
13563:
13564: @item size of floating-point stack:
13565: @cindex floating-point stack size
13566: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13567: the floating-point stack (in floats). You can specify this on startup
13568: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13569:
13570: @item width of floating-point stack:
13571: @cindex floating-point stack width
13572: @code{1 floats}.
13573:
13574: @end table
13575:
13576:
13577: @c ---------------------------------------------------------------------
13578: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13579: @subsection Ambiguous conditions
13580: @c ---------------------------------------------------------------------
13581: @cindex floating-point words, ambiguous conditions
13582: @cindex ambiguous conditions, floating-point words
13583:
13584: @table @i
13585: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13586: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13587: System-dependent. Typically results in a @code{-23 THROW} like other
13588: alignment violations.
13589:
13590: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13591: @cindex @code{f@@} used with an address that is not float aligned
13592: @cindex @code{f!} used with an address that is not float aligned
13593: System-dependent. Typically results in a @code{-23 THROW} like other
13594: alignment violations.
13595:
13596: @item floating-point result out of range:
13597: @cindex floating-point result out of range
1.80 anton 13598: System-dependent. Can result in a @code{-43 throw} (floating point
13599: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13600: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13601: unidentified fault), or can produce a special value representing, e.g.,
13602: Infinity.
13603:
13604: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13605: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13606: System-dependent. Typically results in an alignment fault like other
13607: alignment violations.
13608:
1.35 anton 13609: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13610: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13611: The floating-point number is converted into decimal nonetheless.
13612:
13613: @item Both arguments are equal to zero (@code{FATAN2}):
13614: @cindex @code{FATAN2}, both arguments are equal to zero
13615: System-dependent. @code{FATAN2} is implemented using the C library
13616: function @code{atan2()}.
13617:
1.29 crook 13618: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13619: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13620: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13621: because of small errors and the tan will be a very large (or very small)
13622: but finite number.
13623:
1.29 crook 13624: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13625: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13626: The result is rounded to the nearest float.
13627:
13628: @item dividing by zero:
13629: @cindex dividing by zero, floating-point
13630: @cindex floating-point dividing by zero
13631: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13632: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13633: (floating point divide by zero) or @code{-55 throw} (Floating-point
13634: unidentified fault).
1.1 anton 13635:
13636: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13637: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13638: System dependent. On IEEE-FP based systems the number is converted into
13639: an infinity.
13640:
1.29 crook 13641: @item @i{float}<1 (@code{FACOSH}):
13642: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13643: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13644: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13645:
1.29 crook 13646: @item @i{float}=<-1 (@code{FLNP1}):
13647: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13648: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13649: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13650: negative infinity for @i{float}=-1).
1.1 anton 13651:
1.29 crook 13652: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13653: @cindex @code{FLN}, @i{float}=<0
13654: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13655: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13656: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13657: negative infinity for @i{float}=0).
1.1 anton 13658:
1.29 crook 13659: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13660: @cindex @code{FASINH}, @i{float}<0
13661: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13662: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13663: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13664: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13665: C library?).
1.1 anton 13666:
1.29 crook 13667: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13668: @cindex @code{FACOS}, |@i{float}|>1
13669: @cindex @code{FASIN}, |@i{float}|>1
13670: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13671: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13672: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13673:
1.29 crook 13674: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13675: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13676: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13677: Platform-dependent; typically, some double number is produced and no
13678: error is reported.
1.1 anton 13679:
13680: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13681: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13682: @code{Precision} characters of the numeric output area are used. If
13683: @code{precision} is too high, these words will smash the data or code
13684: close to @code{here}.
1.1 anton 13685: @end table
13686:
13687: @c =====================================================================
13688: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13689: @section The optional Locals word set
13690: @c =====================================================================
13691: @cindex system documentation, locals words
13692: @cindex locals words, system documentation
13693:
13694: @menu
13695: * locals-idef:: Implementation Defined Options
13696: * locals-ambcond:: Ambiguous Conditions
13697: @end menu
13698:
13699:
13700: @c ---------------------------------------------------------------------
13701: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13702: @subsection Implementation Defined Options
13703: @c ---------------------------------------------------------------------
13704: @cindex implementation-defined options, locals words
13705: @cindex locals words, implementation-defined options
13706:
13707: @table @i
13708: @item maximum number of locals in a definition:
13709: @cindex maximum number of locals in a definition
13710: @cindex locals, maximum number in a definition
13711: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13712: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13713: characters. The number of locals in a definition is bounded by the size
13714: of locals-buffer, which contains the names of the locals.
13715:
13716: @end table
13717:
13718:
13719: @c ---------------------------------------------------------------------
13720: @node locals-ambcond, , locals-idef, The optional Locals word set
13721: @subsection Ambiguous conditions
13722: @c ---------------------------------------------------------------------
13723: @cindex locals words, ambiguous conditions
13724: @cindex ambiguous conditions, locals words
13725:
13726: @table @i
13727: @item executing a named local in interpretation state:
13728: @cindex local in interpretation state
13729: @cindex Interpreting a compile-only word, for a local
13730: Locals have no interpretation semantics. If you try to perform the
13731: interpretation semantics, you will get a @code{-14 throw} somewhere
13732: (Interpreting a compile-only word). If you perform the compilation
13733: semantics, the locals access will be compiled (irrespective of state).
13734:
1.29 crook 13735: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13736: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13737: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13738: @cindex Invalid name argument, @code{TO}
13739: @code{-32 throw} (Invalid name argument)
13740:
13741: @end table
13742:
13743:
13744: @c =====================================================================
13745: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13746: @section The optional Memory-Allocation word set
13747: @c =====================================================================
13748: @cindex system documentation, memory-allocation words
13749: @cindex memory-allocation words, system documentation
13750:
13751: @menu
13752: * memory-idef:: Implementation Defined Options
13753: @end menu
13754:
13755:
13756: @c ---------------------------------------------------------------------
13757: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13758: @subsection Implementation Defined Options
13759: @c ---------------------------------------------------------------------
13760: @cindex implementation-defined options, memory-allocation words
13761: @cindex memory-allocation words, implementation-defined options
13762:
13763: @table @i
1.29 crook 13764: @item values and meaning of @i{ior}:
13765: @cindex @i{ior} values and meaning
13766: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13767: intended as throw codes. They typically are in the range
13768: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13769: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13770:
13771: @end table
13772:
13773: @c =====================================================================
13774: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13775: @section The optional Programming-Tools word set
13776: @c =====================================================================
13777: @cindex system documentation, programming-tools words
13778: @cindex programming-tools words, system documentation
13779:
13780: @menu
13781: * programming-idef:: Implementation Defined Options
13782: * programming-ambcond:: Ambiguous Conditions
13783: @end menu
13784:
13785:
13786: @c ---------------------------------------------------------------------
13787: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13788: @subsection Implementation Defined Options
13789: @c ---------------------------------------------------------------------
13790: @cindex implementation-defined options, programming-tools words
13791: @cindex programming-tools words, implementation-defined options
13792:
13793: @table @i
13794: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13795: @cindex @code{;CODE} ending sequence
13796: @cindex @code{CODE} ending sequence
13797: @code{END-CODE}
13798:
13799: @item manner of processing input following @code{;CODE} and @code{CODE}:
13800: @cindex @code{;CODE}, processing input
13801: @cindex @code{CODE}, processing input
13802: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13803: the input is processed by the text interpreter, (starting) in interpret
13804: state.
13805:
13806: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13807: @cindex @code{ASSEMBLER}, search order capability
13808: The ANS Forth search order word set.
13809:
13810: @item source and format of display by @code{SEE}:
13811: @cindex @code{SEE}, source and format of output
1.80 anton 13812: The source for @code{see} is the executable code used by the inner
1.1 anton 13813: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13814: (and on some platforms, assembly code for primitives) as well as
13815: possible.
1.1 anton 13816:
13817: @end table
13818:
13819: @c ---------------------------------------------------------------------
13820: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13821: @subsection Ambiguous conditions
13822: @c ---------------------------------------------------------------------
13823: @cindex programming-tools words, ambiguous conditions
13824: @cindex ambiguous conditions, programming-tools words
13825:
13826: @table @i
13827:
1.21 crook 13828: @item deleting the compilation word list (@code{FORGET}):
13829: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13830: Not implemented (yet).
13831:
1.29 crook 13832: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13833: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13834: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13835: @cindex control-flow stack underflow
13836: This typically results in an @code{abort"} with a descriptive error
13837: message (may change into a @code{-22 throw} (Control structure mismatch)
13838: in the future). You may also get a memory access error. If you are
13839: unlucky, this ambiguous condition is not caught.
13840:
1.29 crook 13841: @item @i{name} can't be found (@code{FORGET}):
13842: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13843: Not implemented (yet).
13844:
1.29 crook 13845: @item @i{name} not defined via @code{CREATE}:
13846: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13847: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13848: the execution semantics of the last defined word no matter how it was
13849: defined.
13850:
13851: @item @code{POSTPONE} applied to @code{[IF]}:
13852: @cindex @code{POSTPONE} applied to @code{[IF]}
13853: @cindex @code{[IF]} and @code{POSTPONE}
13854: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13855: equivalent to @code{[IF]}.
13856:
13857: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13858: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13859: Continue in the same state of conditional compilation in the next outer
13860: input source. Currently there is no warning to the user about this.
13861:
13862: @item removing a needed definition (@code{FORGET}):
13863: @cindex @code{FORGET}, removing a needed definition
13864: Not implemented (yet).
13865:
13866: @end table
13867:
13868:
13869: @c =====================================================================
13870: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13871: @section The optional Search-Order word set
13872: @c =====================================================================
13873: @cindex system documentation, search-order words
13874: @cindex search-order words, system documentation
13875:
13876: @menu
13877: * search-idef:: Implementation Defined Options
13878: * search-ambcond:: Ambiguous Conditions
13879: @end menu
13880:
13881:
13882: @c ---------------------------------------------------------------------
13883: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13884: @subsection Implementation Defined Options
13885: @c ---------------------------------------------------------------------
13886: @cindex implementation-defined options, search-order words
13887: @cindex search-order words, implementation-defined options
13888:
13889: @table @i
13890: @item maximum number of word lists in search order:
13891: @cindex maximum number of word lists in search order
13892: @cindex search order, maximum depth
13893: @code{s" wordlists" environment? drop .}. Currently 16.
13894:
13895: @item minimum search order:
13896: @cindex minimum search order
13897: @cindex search order, minimum
13898: @code{root root}.
13899:
13900: @end table
13901:
13902: @c ---------------------------------------------------------------------
13903: @node search-ambcond, , search-idef, The optional Search-Order word set
13904: @subsection Ambiguous conditions
13905: @c ---------------------------------------------------------------------
13906: @cindex search-order words, ambiguous conditions
13907: @cindex ambiguous conditions, search-order words
13908:
13909: @table @i
1.21 crook 13910: @item changing the compilation word list (during compilation):
13911: @cindex changing the compilation word list (during compilation)
13912: @cindex compilation word list, change before definition ends
13913: The word is entered into the word list that was the compilation word list
1.1 anton 13914: at the start of the definition. Any changes to the name field (e.g.,
13915: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13916: are applied to the latest defined word (as reported by @code{latest} or
13917: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13918:
13919: @item search order empty (@code{previous}):
13920: @cindex @code{previous}, search order empty
1.26 crook 13921: @cindex vocstack empty, @code{previous}
1.1 anton 13922: @code{abort" Vocstack empty"}.
13923:
13924: @item too many word lists in search order (@code{also}):
13925: @cindex @code{also}, too many word lists in search order
1.26 crook 13926: @cindex vocstack full, @code{also}
1.1 anton 13927: @code{abort" Vocstack full"}.
13928:
13929: @end table
13930:
13931: @c ***************************************************************
1.65 anton 13932: @node Standard vs Extensions, Model, ANS conformance, Top
13933: @chapter Should I use Gforth extensions?
13934: @cindex Gforth extensions
13935:
13936: As you read through the rest of this manual, you will see documentation
13937: for @i{Standard} words, and documentation for some appealing Gforth
13938: @i{extensions}. You might ask yourself the question: @i{``Should I
13939: restrict myself to the standard, or should I use the extensions?''}
13940:
13941: The answer depends on the goals you have for the program you are working
13942: on:
13943:
13944: @itemize @bullet
13945:
13946: @item Is it just for yourself or do you want to share it with others?
13947:
13948: @item
13949: If you want to share it, do the others all use Gforth?
13950:
13951: @item
13952: If it is just for yourself, do you want to restrict yourself to Gforth?
13953:
13954: @end itemize
13955:
13956: If restricting the program to Gforth is ok, then there is no reason not
13957: to use extensions. It is still a good idea to keep to the standard
13958: where it is easy, in case you want to reuse these parts in another
13959: program that you want to be portable.
13960:
13961: If you want to be able to port the program to other Forth systems, there
13962: are the following points to consider:
13963:
13964: @itemize @bullet
13965:
13966: @item
13967: Most Forth systems that are being maintained support the ANS Forth
13968: standard. So if your program complies with the standard, it will be
13969: portable among many systems.
13970:
13971: @item
13972: A number of the Gforth extensions can be implemented in ANS Forth using
13973: public-domain files provided in the @file{compat/} directory. These are
13974: mentioned in the text in passing. There is no reason not to use these
13975: extensions, your program will still be ANS Forth compliant; just include
13976: the appropriate compat files with your program.
13977:
13978: @item
13979: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
13980: analyse your program and determine what non-Standard words it relies
13981: upon. However, it does not check whether you use standard words in a
13982: non-standard way.
13983:
13984: @item
13985: Some techniques are not standardized by ANS Forth, and are hard or
13986: impossible to implement in a standard way, but can be implemented in
13987: most Forth systems easily, and usually in similar ways (e.g., accessing
13988: word headers). Forth has a rich historical precedent for programmers
13989: taking advantage of implementation-dependent features of their tools
13990: (for example, relying on a knowledge of the dictionary
13991: structure). Sometimes these techniques are necessary to extract every
13992: last bit of performance from the hardware, sometimes they are just a
13993: programming shorthand.
13994:
13995: @item
13996: Does using a Gforth extension save more work than the porting this part
13997: to other Forth systems (if any) will cost?
13998:
13999: @item
14000: Is the additional functionality worth the reduction in portability and
14001: the additional porting problems?
14002:
14003: @end itemize
14004:
14005: In order to perform these consideratios, you need to know what's
14006: standard and what's not. This manual generally states if something is
1.81 anton 14007: non-standard, but the authoritative source is the
14008: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14009: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14010: into the thought processes of the technical committee.
14011:
14012: Note also that portability between Forth systems is not the only
14013: portability issue; there is also the issue of portability between
14014: different platforms (processor/OS combinations).
14015:
14016: @c ***************************************************************
14017: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14018: @chapter Model
14019:
14020: This chapter has yet to be written. It will contain information, on
14021: which internal structures you can rely.
14022:
14023: @c ***************************************************************
14024: @node Integrating Gforth, Emacs and Gforth, Model, Top
14025: @chapter Integrating Gforth into C programs
14026:
14027: This is not yet implemented.
14028:
14029: Several people like to use Forth as scripting language for applications
14030: that are otherwise written in C, C++, or some other language.
14031:
14032: The Forth system ATLAST provides facilities for embedding it into
14033: applications; unfortunately it has several disadvantages: most
14034: importantly, it is not based on ANS Forth, and it is apparently dead
14035: (i.e., not developed further and not supported). The facilities
1.21 crook 14036: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14037: making the switch should not be hard.
14038:
14039: We also tried to design the interface such that it can easily be
14040: implemented by other Forth systems, so that we may one day arrive at a
14041: standardized interface. Such a standard interface would allow you to
14042: replace the Forth system without having to rewrite C code.
14043:
14044: You embed the Gforth interpreter by linking with the library
14045: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14046: global symbols in this library that belong to the interface, have the
14047: prefix @code{forth_}. (Global symbols that are used internally have the
14048: prefix @code{gforth_}).
14049:
14050: You can include the declarations of Forth types and the functions and
14051: variables of the interface with @code{#include <forth.h>}.
14052:
14053: Types.
14054:
14055: Variables.
14056:
14057: Data and FP Stack pointer. Area sizes.
14058:
14059: functions.
14060:
14061: forth_init(imagefile)
14062: forth_evaluate(string) exceptions?
14063: forth_goto(address) (or forth_execute(xt)?)
14064: forth_continue() (a corountining mechanism)
14065:
14066: Adding primitives.
14067:
14068: No checking.
14069:
14070: Signals?
14071:
14072: Accessing the Stacks
14073:
1.26 crook 14074: @c ******************************************************************
1.1 anton 14075: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14076: @chapter Emacs and Gforth
14077: @cindex Emacs and Gforth
14078:
14079: @cindex @file{gforth.el}
14080: @cindex @file{forth.el}
14081: @cindex Rydqvist, Goran
1.107 dvdkhlng 14082: @cindex Kuehling, David
1.1 anton 14083: @cindex comment editing commands
14084: @cindex @code{\}, editing with Emacs
14085: @cindex debug tracer editing commands
14086: @cindex @code{~~}, removal with Emacs
14087: @cindex Forth mode in Emacs
1.107 dvdkhlng 14088:
1.1 anton 14089: Gforth comes with @file{gforth.el}, an improved version of
14090: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14091: improvements are:
14092:
14093: @itemize @bullet
14094: @item
1.107 dvdkhlng 14095: A better handling of indentation.
14096: @item
14097: A custom hilighting engine for Forth-code.
1.26 crook 14098: @item
14099: Comment paragraph filling (@kbd{M-q})
14100: @item
14101: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14102: @item
14103: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14104: @item
14105: Support of the @code{info-lookup} feature for looking up the
14106: documentation of a word.
1.107 dvdkhlng 14107: @item
14108: Support for reading and writing blocks files.
1.26 crook 14109: @end itemize
14110:
1.107 dvdkhlng 14111: To get a basic description of these features, enter Forth mode and
14112: type @kbd{C-h m}.
1.1 anton 14113:
14114: @cindex source location of error or debugging output in Emacs
14115: @cindex error output, finding the source location in Emacs
14116: @cindex debugging output, finding the source location in Emacs
14117: In addition, Gforth supports Emacs quite well: The source code locations
14118: given in error messages, debugging output (from @code{~~}) and failed
14119: assertion messages are in the right format for Emacs' compilation mode
14120: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14121: Manual}) so the source location corresponding to an error or other
14122: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14123: @kbd{C-c C-c} for the error under the cursor).
14124:
1.107 dvdkhlng 14125: @cindex viewing the documentation of a word in Emacs
14126: @cindex context-sensitive help
14127: Moreover, for words documented in this manual, you can look up the
14128: glossary entry quickly by using @kbd{C-h TAB}
14129: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14130: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14131: later and does not work for words containing @code{:}.
14132:
14133: @menu
14134: * Installing gforth.el:: Making Emacs aware of Forth.
14135: * Emacs Tags:: Viewing the source of a word in Emacs.
14136: * Hilighting:: Making Forth code look prettier.
14137: * Auto-Indentation:: Customizing auto-indentation.
14138: * Blocks Files:: Reading and writing blocks files.
14139: @end menu
14140:
14141: @c ----------------------------------
1.109 anton 14142: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14143: @section Installing gforth.el
14144: @cindex @file{.emacs}
14145: @cindex @file{gforth.el}, installation
14146: To make the features from @file{gforth.el} available in Emacs, add
14147: the following lines to your @file{.emacs} file:
14148:
14149: @example
14150: (autoload 'forth-mode "gforth.el")
14151: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14152: auto-mode-alist))
14153: (autoload 'forth-block-mode "gforth.el")
14154: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14155: auto-mode-alist))
14156: (add-hook 'forth-mode-hook (function (lambda ()
14157: ;; customize variables here:
14158: (setq forth-indent-level 4)
14159: (setq forth-minor-indent-level 2)
14160: (setq forth-hilight-level 3)
14161: ;;; ...
14162: )))
14163: @end example
14164:
14165: @c ----------------------------------
14166: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14167: @section Emacs Tags
1.1 anton 14168: @cindex @file{TAGS} file
14169: @cindex @file{etags.fs}
14170: @cindex viewing the source of a word in Emacs
1.43 anton 14171: @cindex @code{require}, placement in files
14172: @cindex @code{include}, placement in files
1.107 dvdkhlng 14173: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14174: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14175: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14176: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14177: several tags files at the same time (e.g., one for the Gforth sources
14178: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14179: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14180: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14181: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14182: with @file{etags.fs}, you should avoid putting definitions both before
14183: and after @code{require} etc., otherwise you will see the same file
14184: visited several times by commands like @code{tags-search}.
1.1 anton 14185:
1.107 dvdkhlng 14186: @c ----------------------------------
14187: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14188: @section Hilighting
14189: @cindex hilighting Forth code in Emacs
14190: @cindex highlighting Forth code in Emacs
14191: @file{gforth.el} comes with a custom source hilighting engine. When
14192: you open a file in @code{forth-mode}, it will be completely parsed,
14193: assigning faces to keywords, comments, strings etc. While you edit
14194: the file, modified regions get parsed and updated on-the-fly.
14195:
14196: Use the variable `forth-hilight-level' to change the level of
14197: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14198: you set the hilighting level to 0, the parser will still work in the
14199: background, collecting information about whether regions of text are
14200: ``compiled'' or ``interpreted''. Those information are required for
14201: auto-indentation to work properly. Set `forth-disable-parser' to
14202: non-nil if your computer is too slow to handle parsing. This will
14203: have an impact on the smartness of the auto-indentation engine,
14204: though.
14205:
14206: Sometimes Forth sources define new features that should be hilighted,
14207: new control structures, defining-words etc. You can use the variable
14208: `forth-custom-words' to make @code{forth-mode} hilight additional
14209: words and constructs. See the docstring of `forth-words' for details
14210: (in Emacs, type @kbd{C-h v forth-words}).
14211:
14212: `forth-custom-words' is meant to be customized in your
14213: @file{.emacs} file. To customize hilighing in a file-specific manner,
14214: set `forth-local-words' in a local-variables section at the end of
14215: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14216:
14217: Example:
14218: @example
14219: 0 [IF]
14220: Local Variables:
14221: forth-local-words:
14222: ((("t:") definition-starter (font-lock-keyword-face . 1)
14223: "[ \t\n]" t name (font-lock-function-name-face . 3))
14224: ((";t") definition-ender (font-lock-keyword-face . 1)))
14225: End:
14226: [THEN]
14227: @end example
14228:
14229: @c ----------------------------------
14230: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14231: @section Auto-Indentation
14232: @cindex auto-indentation of Forth code in Emacs
14233: @cindex indentation of Forth code in Emacs
14234: @code{forth-mode} automatically tries to indent lines in a smart way,
14235: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14236:
14237: Simple customization can be achieved by setting
14238: `forth-indent-level' and `forth-minor-indent-level' in your
14239: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14240: per default by multiples of 4 columns. To use the more traditional
14241: 3-column indentation, add the following lines to your @file{.emacs}:
14242:
14243: @example
14244: (add-hook 'forth-mode-hook (function (lambda ()
14245: ;; customize variables here:
14246: (setq forth-indent-level 3)
14247: (setq forth-minor-indent-level 1)
14248: )))
14249: @end example
14250:
14251: If you want indentation to recognize non-default words, customize it
14252: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14253: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14254: v forth-indent-words}).
14255:
14256: To customize indentation in a file-specific manner, set
14257: `forth-local-indent-words' in a local-variables section at the end of
14258: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14259: Emacs Manual}).
14260:
14261: Example:
14262: @example
14263: 0 [IF]
14264: Local Variables:
14265: forth-local-indent-words:
14266: ((("t:") (0 . 2) (0 . 2))
14267: ((";t") (-2 . 0) (0 . -2)))
14268: End:
14269: [THEN]
14270: @end example
14271:
14272: @c ----------------------------------
1.109 anton 14273: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14274: @section Blocks Files
14275: @cindex blocks files, use with Emacs
14276: @code{forth-mode} Autodetects blocks files by checking whether the
14277: length of the first line exceeds 1023 characters. It then tries to
14278: convert the file into normal text format. When you save the file, it
14279: will be written to disk as normal stream-source file.
14280:
14281: If you want to write blocks files, use @code{forth-blocks-mode}. It
14282: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14283:
1.107 dvdkhlng 14284: @itemize @bullet
14285: @item
14286: Files are written to disk in blocks file format.
14287: @item
14288: Screen numbers are displayed in the mode line (enumerated beginning
14289: with the value of `forth-block-base')
14290: @item
14291: Warnings are displayed when lines exceed 64 characters.
14292: @item
14293: The beginning of the currently edited block is marked with an
14294: overlay-arrow.
14295: @end itemize
1.41 anton 14296:
1.107 dvdkhlng 14297: There are some restrictions you should be aware of. When you open a
14298: blocks file that contains tabulator or newline characters, these
14299: characters will be translated into spaces when the file is written
14300: back to disk. If tabs or newlines are encountered during blocks file
14301: reading, an error is output to the echo area. So have a look at the
14302: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14303:
1.107 dvdkhlng 14304: Please consult the docstring of @code{forth-blocks-mode} for more
14305: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14306:
1.26 crook 14307: @c ******************************************************************
1.1 anton 14308: @node Image Files, Engine, Emacs and Gforth, Top
14309: @chapter Image Files
1.26 crook 14310: @cindex image file
14311: @cindex @file{.fi} files
1.1 anton 14312: @cindex precompiled Forth code
14313: @cindex dictionary in persistent form
14314: @cindex persistent form of dictionary
14315:
14316: An image file is a file containing an image of the Forth dictionary,
14317: i.e., compiled Forth code and data residing in the dictionary. By
14318: convention, we use the extension @code{.fi} for image files.
14319:
14320: @menu
1.18 anton 14321: * Image Licensing Issues:: Distribution terms for images.
14322: * Image File Background:: Why have image files?
1.67 anton 14323: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14324: * Data-Relocatable Image Files:: are better.
1.67 anton 14325: * Fully Relocatable Image Files:: better yet.
1.18 anton 14326: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14327: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14328: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14329: @end menu
14330:
1.18 anton 14331: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14332: @section Image Licensing Issues
14333: @cindex license for images
14334: @cindex image license
14335:
14336: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14337: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14338: original image; i.e., according to copyright law it is a derived work of
14339: the original image.
14340:
14341: Since Gforth is distributed under the GNU GPL, the newly created image
14342: falls under the GNU GPL, too. In particular, this means that if you
14343: distribute the image, you have to make all of the sources for the image
1.113 anton 14344: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14345: GNU General Public License (Section 3)}.
14346:
14347: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14348: contains only code compiled from the sources you gave it; if none of
14349: these sources is under the GPL, the terms discussed above do not apply
14350: to the image. However, if your image needs an engine (a gforth binary)
14351: that is under the GPL, you should make sure that you distribute both in
14352: a way that is at most a @emph{mere aggregation}, if you don't want the
14353: terms of the GPL to apply to the image.
14354:
14355: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14356: @section Image File Background
14357: @cindex image file background
14358:
1.80 anton 14359: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14360: definitions written in Forth. Since the Forth compiler itself belongs to
14361: those definitions, it is not possible to start the system with the
1.80 anton 14362: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14363: code as an image file in nearly executable form. When Gforth starts up,
14364: a C routine loads the image file into memory, optionally relocates the
14365: addresses, then sets up the memory (stacks etc.) according to
14366: information in the image file, and (finally) starts executing Forth
14367: code.
1.1 anton 14368:
14369: The image file variants represent different compromises between the
14370: goals of making it easy to generate image files and making them
14371: portable.
14372:
14373: @cindex relocation at run-time
1.26 crook 14374: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14375: run-time. This avoids many of the complications discussed below (image
14376: files are data relocatable without further ado), but costs performance
14377: (one addition per memory access).
14378:
14379: @cindex relocation at load-time
1.26 crook 14380: By contrast, the Gforth loader performs relocation at image load time. The
14381: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14382: appropriate code-field addresses (or code addresses in the case of
14383: direct threading).
14384:
14385: There are three kinds of image files, with different degrees of
14386: relocatability: non-relocatable, data-relocatable, and fully relocatable
14387: image files.
14388:
14389: @cindex image file loader
14390: @cindex relocating loader
14391: @cindex loader for image files
14392: These image file variants have several restrictions in common; they are
14393: caused by the design of the image file loader:
14394:
14395: @itemize @bullet
14396: @item
14397: There is only one segment; in particular, this means, that an image file
14398: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14399: them). The contents of the stacks are not represented, either.
1.1 anton 14400:
14401: @item
14402: The only kinds of relocation supported are: adding the same offset to
14403: all cells that represent data addresses; and replacing special tokens
14404: with code addresses or with pieces of machine code.
14405:
14406: If any complex computations involving addresses are performed, the
14407: results cannot be represented in the image file. Several applications that
14408: use such computations come to mind:
14409: @itemize @minus
14410: @item
14411: Hashing addresses (or data structures which contain addresses) for table
14412: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14413: purpose, you will have no problem, because the hash tables are
14414: recomputed automatically when the system is started. If you use your own
14415: hash tables, you will have to do something similar.
14416:
14417: @item
14418: There's a cute implementation of doubly-linked lists that uses
14419: @code{XOR}ed addresses. You could represent such lists as singly-linked
14420: in the image file, and restore the doubly-linked representation on
14421: startup.@footnote{In my opinion, though, you should think thrice before
14422: using a doubly-linked list (whatever implementation).}
14423:
14424: @item
14425: The code addresses of run-time routines like @code{docol:} cannot be
14426: represented in the image file (because their tokens would be replaced by
14427: machine code in direct threaded implementations). As a workaround,
14428: compute these addresses at run-time with @code{>code-address} from the
14429: executions tokens of appropriate words (see the definitions of
1.80 anton 14430: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14431:
14432: @item
14433: On many architectures addresses are represented in machine code in some
14434: shifted or mangled form. You cannot put @code{CODE} words that contain
14435: absolute addresses in this form in a relocatable image file. Workarounds
14436: are representing the address in some relative form (e.g., relative to
14437: the CFA, which is present in some register), or loading the address from
14438: a place where it is stored in a non-mangled form.
14439: @end itemize
14440: @end itemize
14441:
14442: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14443: @section Non-Relocatable Image Files
14444: @cindex non-relocatable image files
1.26 crook 14445: @cindex image file, non-relocatable
1.1 anton 14446:
14447: These files are simple memory dumps of the dictionary. They are specific
14448: to the executable (i.e., @file{gforth} file) they were created
14449: with. What's worse, they are specific to the place on which the
14450: dictionary resided when the image was created. Now, there is no
14451: guarantee that the dictionary will reside at the same place the next
14452: time you start Gforth, so there's no guarantee that a non-relocatable
14453: image will work the next time (Gforth will complain instead of crashing,
14454: though).
14455:
14456: You can create a non-relocatable image file with
14457:
1.44 crook 14458:
1.1 anton 14459: doc-savesystem
14460:
1.44 crook 14461:
1.1 anton 14462: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14463: @section Data-Relocatable Image Files
14464: @cindex data-relocatable image files
1.26 crook 14465: @cindex image file, data-relocatable
1.1 anton 14466:
14467: These files contain relocatable data addresses, but fixed code addresses
14468: (instead of tokens). They are specific to the executable (i.e.,
14469: @file{gforth} file) they were created with. For direct threading on some
14470: architectures (e.g., the i386), data-relocatable images do not work. You
14471: get a data-relocatable image, if you use @file{gforthmi} with a
14472: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14473: Relocatable Image Files}).
14474:
14475: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14476: @section Fully Relocatable Image Files
14477: @cindex fully relocatable image files
1.26 crook 14478: @cindex image file, fully relocatable
1.1 anton 14479:
14480: @cindex @file{kern*.fi}, relocatability
14481: @cindex @file{gforth.fi}, relocatability
14482: These image files have relocatable data addresses, and tokens for code
14483: addresses. They can be used with different binaries (e.g., with and
14484: without debugging) on the same machine, and even across machines with
14485: the same data formats (byte order, cell size, floating point
14486: format). However, they are usually specific to the version of Gforth
14487: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14488: are fully relocatable.
14489:
14490: There are two ways to create a fully relocatable image file:
14491:
14492: @menu
1.29 crook 14493: * gforthmi:: The normal way
1.1 anton 14494: * cross.fs:: The hard way
14495: @end menu
14496:
14497: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14498: @subsection @file{gforthmi}
14499: @cindex @file{comp-i.fs}
14500: @cindex @file{gforthmi}
14501:
14502: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14503: image @i{file} that contains everything you would load by invoking
14504: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14505: @example
1.29 crook 14506: gforthmi @i{file} @i{options}
1.1 anton 14507: @end example
14508:
14509: E.g., if you want to create an image @file{asm.fi} that has the file
14510: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14511: like this:
14512:
14513: @example
14514: gforthmi asm.fi asm.fs
14515: @end example
14516:
1.27 crook 14517: @file{gforthmi} is implemented as a sh script and works like this: It
14518: produces two non-relocatable images for different addresses and then
14519: compares them. Its output reflects this: first you see the output (if
1.62 crook 14520: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14521: files, then you see the output of the comparing program: It displays the
14522: offset used for data addresses and the offset used for code addresses;
1.1 anton 14523: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14524: image files, it displays a line like this:
1.1 anton 14525:
14526: @example
14527: 78DC BFFFFA50 BFFFFA40
14528: @end example
14529:
14530: This means that at offset $78dc from @code{forthstart}, one input image
14531: contains $bffffa50, and the other contains $bffffa40. Since these cells
14532: cannot be represented correctly in the output image, you should examine
14533: these places in the dictionary and verify that these cells are dead
14534: (i.e., not read before they are written).
1.39 anton 14535:
14536: @cindex --application, @code{gforthmi} option
14537: If you insert the option @code{--application} in front of the image file
14538: name, you will get an image that uses the @code{--appl-image} option
14539: instead of the @code{--image-file} option (@pxref{Invoking
14540: Gforth}). When you execute such an image on Unix (by typing the image
14541: name as command), the Gforth engine will pass all options to the image
14542: instead of trying to interpret them as engine options.
1.1 anton 14543:
1.27 crook 14544: If you type @file{gforthmi} with no arguments, it prints some usage
14545: instructions.
14546:
1.1 anton 14547: @cindex @code{savesystem} during @file{gforthmi}
14548: @cindex @code{bye} during @file{gforthmi}
14549: @cindex doubly indirect threaded code
1.44 crook 14550: @cindex environment variables
14551: @cindex @code{GFORTHD} -- environment variable
14552: @cindex @code{GFORTH} -- environment variable
1.1 anton 14553: @cindex @code{gforth-ditc}
1.29 crook 14554: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14555: words @code{savesystem} and @code{bye} must be visible. A special doubly
14556: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14557: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14558: this executable through the environment variable @code{GFORTHD}
14559: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14560: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14561: data-relocatable image (because there is no code address offset). The
14562: normal @file{gforth} executable is used for creating the relocatable
14563: image; you can pass the exact filename of this executable through the
14564: environment variable @code{GFORTH}.
1.1 anton 14565:
14566: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14567: @subsection @file{cross.fs}
14568: @cindex @file{cross.fs}
14569: @cindex cross-compiler
14570: @cindex metacompiler
1.47 crook 14571: @cindex target compiler
1.1 anton 14572:
14573: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14574: programming language (@pxref{Cross Compiler}).
1.1 anton 14575:
1.47 crook 14576: @code{cross} allows you to create image files for machines with
1.1 anton 14577: different data sizes and data formats than the one used for generating
14578: the image file. You can also use it to create an application image that
14579: does not contain a Forth compiler. These features are bought with
14580: restrictions and inconveniences in programming. E.g., addresses have to
14581: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14582: order to make the code relocatable.
14583:
14584:
14585: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14586: @section Stack and Dictionary Sizes
14587: @cindex image file, stack and dictionary sizes
14588: @cindex dictionary size default
14589: @cindex stack size default
14590:
14591: If you invoke Gforth with a command line flag for the size
14592: (@pxref{Invoking Gforth}), the size you specify is stored in the
14593: dictionary. If you save the dictionary with @code{savesystem} or create
14594: an image with @file{gforthmi}, this size will become the default
14595: for the resulting image file. E.g., the following will create a
1.21 crook 14596: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14597:
14598: @example
14599: gforthmi gforth.fi -m 1M
14600: @end example
14601:
14602: In other words, if you want to set the default size for the dictionary
14603: and the stacks of an image, just invoke @file{gforthmi} with the
14604: appropriate options when creating the image.
14605:
14606: @cindex stack size, cache-friendly
14607: Note: For cache-friendly behaviour (i.e., good performance), you should
14608: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14609: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14610: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14611:
14612: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14613: @section Running Image Files
14614: @cindex running image files
14615: @cindex invoking image files
14616: @cindex image file invocation
14617:
14618: @cindex -i, invoke image file
14619: @cindex --image file, invoke image file
1.29 crook 14620: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14621: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14622: @example
1.29 crook 14623: gforth -i @i{image}
1.1 anton 14624: @end example
14625:
14626: @cindex executable image file
1.26 crook 14627: @cindex image file, executable
1.1 anton 14628: If your operating system supports starting scripts with a line of the
14629: form @code{#! ...}, you just have to type the image file name to start
14630: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14631: just a convention). I.e., to run Gforth with the image file @i{image},
14632: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14633: This works because every @code{.fi} file starts with a line of this
14634: format:
14635:
14636: @example
14637: #! /usr/local/bin/gforth-0.4.0 -i
14638: @end example
14639:
14640: The file and pathname for the Gforth engine specified on this line is
14641: the specific Gforth executable that it was built against; i.e. the value
14642: of the environment variable @code{GFORTH} at the time that
14643: @file{gforthmi} was executed.
1.1 anton 14644:
1.27 crook 14645: You can make use of the same shell capability to make a Forth source
14646: file into an executable. For example, if you place this text in a file:
1.26 crook 14647:
14648: @example
14649: #! /usr/local/bin/gforth
14650:
14651: ." Hello, world" CR
14652: bye
14653: @end example
14654:
14655: @noindent
1.27 crook 14656: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14657: directly from the command line. The sequence @code{#!} is used in two
14658: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14659: system@footnote{The Unix kernel actually recognises two types of files:
14660: executable files and files of data, where the data is processed by an
14661: interpreter that is specified on the ``interpreter line'' -- the first
14662: line of the file, starting with the sequence #!. There may be a small
14663: limit (e.g., 32) on the number of characters that may be specified on
14664: the interpreter line.} secondly it is treated as a comment character by
14665: Gforth. Because of the second usage, a space is required between
1.80 anton 14666: @code{#!} and the path to the executable (moreover, some Unixes
14667: require the sequence @code{#! /}).
1.27 crook 14668:
14669: The disadvantage of this latter technique, compared with using
1.80 anton 14670: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14671: compiled on-the-fly, each time the program is invoked.
1.26 crook 14672:
1.1 anton 14673: doc-#!
14674:
1.44 crook 14675:
1.1 anton 14676: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14677: @section Modifying the Startup Sequence
14678: @cindex startup sequence for image file
14679: @cindex image file initialization sequence
14680: @cindex initialization sequence of image file
14681:
1.120 anton 14682: You can add your own initialization to the startup sequence of an image
14683: through the deferred word @code{'cold}. @code{'cold} is invoked just
14684: before the image-specific command line processing (i.e., loading files
14685: and evaluating (@code{-e}) strings) starts.
1.1 anton 14686:
14687: A sequence for adding your initialization usually looks like this:
14688:
14689: @example
14690: :noname
14691: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14692: ... \ your stuff
14693: ; IS 'cold
14694: @end example
14695:
14696: @cindex turnkey image files
1.26 crook 14697: @cindex image file, turnkey applications
1.1 anton 14698: You can make a turnkey image by letting @code{'cold} execute a word
14699: (your turnkey application) that never returns; instead, it exits Gforth
14700: via @code{bye} or @code{throw}.
14701:
1.121 anton 14702: You can access the (image-specific) command-line arguments through
14703: @code{argc}, @code{argv} and @code{arg} (@pxref{OS command line
14704: arguments}).
1.1 anton 14705:
1.26 crook 14706: If @code{'cold} exits normally, Gforth processes the command-line
14707: arguments as files to be loaded and strings to be evaluated. Therefore,
14708: @code{'cold} should remove the arguments it has used in this case.
14709:
14710: doc-'cold
1.44 crook 14711:
1.1 anton 14712: @c ******************************************************************
1.113 anton 14713: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14714: @chapter Engine
14715: @cindex engine
14716: @cindex virtual machine
14717:
1.26 crook 14718: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14719: may be helpful for finding your way in the Gforth sources.
14720:
1.109 anton 14721: The ideas in this section have also been published in the following
14722: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14723: Forth-Tagung '93; M. Anton Ertl,
14724: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14725: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14726: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14727: Threaded code variations and optimizations (extended version)}},
14728: Forth-Tagung '02.
1.1 anton 14729:
14730: @menu
14731: * Portability::
14732: * Threading::
14733: * Primitives::
14734: * Performance::
14735: @end menu
14736:
14737: @node Portability, Threading, Engine, Engine
14738: @section Portability
14739: @cindex engine portability
14740:
1.26 crook 14741: An important goal of the Gforth Project is availability across a wide
14742: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14743: achieved this goal by manually coding the engine in assembly language
14744: for several then-popular processors. This approach is very
14745: labor-intensive and the results are short-lived due to progress in
14746: computer architecture.
1.1 anton 14747:
14748: @cindex C, using C for the engine
14749: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14750: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14751: particularly popular for UNIX-based Forths due to the large variety of
14752: architectures of UNIX machines. Unfortunately an implementation in C
14753: does not mix well with the goals of efficiency and with using
14754: traditional techniques: Indirect or direct threading cannot be expressed
14755: in C, and switch threading, the fastest technique available in C, is
14756: significantly slower. Another problem with C is that it is very
14757: cumbersome to express double integer arithmetic.
14758:
14759: @cindex GNU C for the engine
14760: @cindex long long
14761: Fortunately, there is a portable language that does not have these
14762: limitations: GNU C, the version of C processed by the GNU C compiler
14763: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14764: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14765: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14766: threading possible, its @code{long long} type (@pxref{Long Long, ,
14767: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14768: double numbers on many systems. GNU C is freely available on all
1.1 anton 14769: important (and many unimportant) UNIX machines, VMS, 80386s running
14770: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14771: on all these machines.
14772:
14773: Writing in a portable language has the reputation of producing code that
14774: is slower than assembly. For our Forth engine we repeatedly looked at
14775: the code produced by the compiler and eliminated most compiler-induced
14776: inefficiencies by appropriate changes in the source code.
14777:
14778: @cindex explicit register declarations
14779: @cindex --enable-force-reg, configuration flag
14780: @cindex -DFORCE_REG
14781: However, register allocation cannot be portably influenced by the
14782: programmer, leading to some inefficiencies on register-starved
14783: machines. We use explicit register declarations (@pxref{Explicit Reg
14784: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14785: improve the speed on some machines. They are turned on by using the
14786: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14787: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14788: machine, but also on the compiler version: On some machines some
14789: compiler versions produce incorrect code when certain explicit register
14790: declarations are used. So by default @code{-DFORCE_REG} is not used.
14791:
14792: @node Threading, Primitives, Portability, Engine
14793: @section Threading
14794: @cindex inner interpreter implementation
14795: @cindex threaded code implementation
14796:
14797: @cindex labels as values
14798: GNU C's labels as values extension (available since @code{gcc-2.0},
14799: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14800: makes it possible to take the address of @i{label} by writing
14801: @code{&&@i{label}}. This address can then be used in a statement like
14802: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14803: @code{goto x}.
14804:
1.26 crook 14805: @cindex @code{NEXT}, indirect threaded
1.1 anton 14806: @cindex indirect threaded inner interpreter
14807: @cindex inner interpreter, indirect threaded
1.26 crook 14808: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14809: @example
14810: cfa = *ip++;
14811: ca = *cfa;
14812: goto *ca;
14813: @end example
14814: @cindex instruction pointer
14815: For those unfamiliar with the names: @code{ip} is the Forth instruction
14816: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14817: execution token and points to the code field of the next word to be
14818: executed; The @code{ca} (code address) fetched from there points to some
14819: executable code, e.g., a primitive or the colon definition handler
14820: @code{docol}.
14821:
1.26 crook 14822: @cindex @code{NEXT}, direct threaded
1.1 anton 14823: @cindex direct threaded inner interpreter
14824: @cindex inner interpreter, direct threaded
14825: Direct threading is even simpler:
14826: @example
14827: ca = *ip++;
14828: goto *ca;
14829: @end example
14830:
14831: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14832: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14833:
14834: @menu
14835: * Scheduling::
14836: * Direct or Indirect Threaded?::
1.109 anton 14837: * Dynamic Superinstructions::
1.1 anton 14838: * DOES>::
14839: @end menu
14840:
14841: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14842: @subsection Scheduling
14843: @cindex inner interpreter optimization
14844:
14845: There is a little complication: Pipelined and superscalar processors,
14846: i.e., RISC and some modern CISC machines can process independent
14847: instructions while waiting for the results of an instruction. The
14848: compiler usually reorders (schedules) the instructions in a way that
14849: achieves good usage of these delay slots. However, on our first tries
14850: the compiler did not do well on scheduling primitives. E.g., for
14851: @code{+} implemented as
14852: @example
14853: n=sp[0]+sp[1];
14854: sp++;
14855: sp[0]=n;
14856: NEXT;
14857: @end example
1.81 anton 14858: the @code{NEXT} comes strictly after the other code, i.e., there is
14859: nearly no scheduling. After a little thought the problem becomes clear:
14860: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14861: addresses (and the version of @code{gcc} we used would not know it even
14862: if it was possible), so it could not move the load of the cfa above the
14863: store to the TOS. Indeed the pointers could be the same, if code on or
14864: very near the top of stack were executed. In the interest of speed we
14865: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14866: in scheduling: @code{NEXT} is divided into several parts:
14867: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14868: like:
1.1 anton 14869: @example
1.81 anton 14870: NEXT_P0;
1.1 anton 14871: n=sp[0]+sp[1];
14872: sp++;
14873: NEXT_P1;
14874: sp[0]=n;
14875: NEXT_P2;
14876: @end example
14877:
1.81 anton 14878: There are various schemes that distribute the different operations of
14879: NEXT between these parts in several ways; in general, different schemes
14880: perform best on different processors. We use a scheme for most
14881: architectures that performs well for most processors of this
1.109 anton 14882: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14883: the scheme on installation time.
14884:
1.1 anton 14885:
1.109 anton 14886: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14887: @subsection Direct or Indirect Threaded?
14888: @cindex threading, direct or indirect?
14889:
1.109 anton 14890: Threaded forth code consists of references to primitives (simple machine
14891: code routines like @code{+}) and to non-primitives (e.g., colon
14892: definitions, variables, constants); for a specific class of
14893: non-primitives (e.g., variables) there is one code routine (e.g.,
14894: @code{dovar}), but each variable needs a separate reference to its data.
14895:
14896: Traditionally Forth has been implemented as indirect threaded code,
14897: because this allows to use only one cell to reference a non-primitive
14898: (basically you point to the data, and find the code address there).
14899:
14900: @cindex primitive-centric threaded code
14901: However, threaded code in Gforth (since 0.6.0) uses two cells for
14902: non-primitives, one for the code address, and one for the data address;
14903: the data pointer is an immediate argument for the virtual machine
14904: instruction represented by the code address. We call this
14905: @emph{primitive-centric} threaded code, because all code addresses point
14906: to simple primitives. E.g., for a variable, the code address is for
14907: @code{lit} (also used for integer literals like @code{99}).
14908:
14909: Primitive-centric threaded code allows us to use (faster) direct
14910: threading as dispatch method, completely portably (direct threaded code
14911: in Gforth before 0.6.0 required architecture-specific code). It also
14912: eliminates the performance problems related to I-cache consistency that
14913: 386 implementations have with direct threaded code, and allows
14914: additional optimizations.
14915:
14916: @cindex hybrid direct/indirect threaded code
14917: There is a catch, however: the @var{xt} parameter of @code{execute} can
14918: occupy only one cell, so how do we pass non-primitives with their code
14919: @emph{and} data addresses to them? Our answer is to use indirect
14920: threaded dispatch for @code{execute} and other words that use a
14921: single-cell xt. So, normal threaded code in colon definitions uses
14922: direct threading, and @code{execute} and similar words, which dispatch
14923: to xts on the data stack, use indirect threaded code. We call this
14924: @emph{hybrid direct/indirect} threaded code.
14925:
14926: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14927: @cindex gforth engine
14928: @cindex gforth-fast engine
14929: The engines @command{gforth} and @command{gforth-fast} use hybrid
14930: direct/indirect threaded code. This means that with these engines you
14931: cannot use @code{,} to compile an xt. Instead, you have to use
14932: @code{compile,}.
14933:
14934: @cindex gforth-itc engine
1.115 anton 14935: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14936: This engine uses plain old indirect threaded code. It still compiles in
14937: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14938: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14939: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14940: and execute @code{' , is compile,}. Your program can check if it is
14941: running on a hybrid direct/indirect threaded engine or a pure indirect
14942: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14943:
14944:
14945: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
14946: @subsection Dynamic Superinstructions
14947: @cindex Dynamic superinstructions with replication
14948: @cindex Superinstructions
14949: @cindex Replication
14950:
14951: The engines @command{gforth} and @command{gforth-fast} use another
14952: optimization: Dynamic superinstructions with replication. As an
14953: example, consider the following colon definition:
14954:
14955: @example
14956: : squared ( n1 -- n2 )
14957: dup * ;
14958: @end example
14959:
14960: Gforth compiles this into the threaded code sequence
14961:
14962: @example
14963: dup
14964: *
14965: ;s
14966: @end example
14967:
14968: In normal direct threaded code there is a code address occupying one
14969: cell for each of these primitives. Each code address points to a
14970: machine code routine, and the interpreter jumps to this machine code in
14971: order to execute the primitive. The routines for these three
14972: primitives are (in @command{gforth-fast} on the 386):
14973:
14974: @example
14975: Code dup
14976: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
14977: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
14978: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
14979: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14980: end-code
14981: Code *
14982: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
14983: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
14984: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
14985: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
14986: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14987: end-code
14988: Code ;s
14989: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
14990: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
14991: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
14992: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
14993: end-code
14994: @end example
14995:
14996: With dynamic superinstructions and replication the compiler does not
14997: just lay down the threaded code, but also copies the machine code
14998: fragments, usually without the jump at the end.
14999:
15000: @example
15001: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15002: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15003: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15004: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15005: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15006: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15007: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15008: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15009: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15010: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15011: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15012: @end example
15013:
15014: Only when a threaded-code control-flow change happens (e.g., in
15015: @code{;s}), the jump is appended. This optimization eliminates many of
15016: these jumps and makes the rest much more predictable. The speedup
15017: depends on the processor and the application; on the Athlon and Pentium
15018: III this optimization typically produces a speedup by a factor of 2.
15019:
15020: The code addresses in the direct-threaded code are set to point to the
15021: appropriate points in the copied machine code, in this example like
15022: this:
1.1 anton 15023:
1.109 anton 15024: @example
15025: primitive code address
15026: dup $4057D27D
15027: * $4057D286
15028: ;s $4057D292
15029: @end example
15030:
15031: Thus there can be threaded-code jumps to any place in this piece of
15032: code. This also simplifies decompilation quite a bit.
15033:
15034: @cindex --no-dynamic command-line option
15035: @cindex --no-super command-line option
15036: You can disable this optimization with @option{--no-dynamic}. You can
15037: use the copying without eliminating the jumps (i.e., dynamic
15038: replication, but without superinstructions) with @option{--no-super};
15039: this gives the branch prediction benefit alone; the effect on
1.110 anton 15040: performance depends on the CPU; on the Athlon and Pentium III the
15041: speedup is a little less than for dynamic superinstructions with
15042: replication.
15043:
15044: @cindex patching threaded code
15045: One use of these options is if you want to patch the threaded code.
15046: With superinstructions, many of the dispatch jumps are eliminated, so
15047: patching often has no effect. These options preserve all the dispatch
15048: jumps.
1.109 anton 15049:
15050: @cindex --dynamic command-line option
1.110 anton 15051: On some machines dynamic superinstructions are disabled by default,
15052: because it is unsafe on these machines. However, if you feel
15053: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15054:
15055: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15056: @subsection DOES>
15057: @cindex @code{DOES>} implementation
15058:
1.26 crook 15059: @cindex @code{dodoes} routine
15060: @cindex @code{DOES>}-code
1.1 anton 15061: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15062: the chunk of code executed by every word defined by a
1.109 anton 15063: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15064: this is only needed if the xt of the word is @code{execute}d. The main
15065: problem here is: How to find the Forth code to be executed, i.e. the
15066: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15067: solutions:
1.1 anton 15068:
1.21 crook 15069: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15070: @code{DOES>}-code address is stored in the cell after the code address
15071: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15072: illegal in the Forth-79 and all later standards, because in fig-Forth
15073: this address lies in the body (which is illegal in these
15074: standards). However, by making the code field larger for all words this
15075: solution becomes legal again. We use this approach. Leaving a cell
15076: unused in most words is a bit wasteful, but on the machines we are
15077: targeting this is hardly a problem.
15078:
1.1 anton 15079:
15080: @node Primitives, Performance, Threading, Engine
15081: @section Primitives
15082: @cindex primitives, implementation
15083: @cindex virtual machine instructions, implementation
15084:
15085: @menu
15086: * Automatic Generation::
15087: * TOS Optimization::
15088: * Produced code::
15089: @end menu
15090:
15091: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15092: @subsection Automatic Generation
15093: @cindex primitives, automatic generation
15094:
15095: @cindex @file{prims2x.fs}
1.109 anton 15096:
1.1 anton 15097: Since the primitives are implemented in a portable language, there is no
15098: longer any need to minimize the number of primitives. On the contrary,
15099: having many primitives has an advantage: speed. In order to reduce the
15100: number of errors in primitives and to make programming them easier, we
1.109 anton 15101: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15102: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15103: generates most (and sometimes all) of the C code for a primitive from
15104: the stack effect notation. The source for a primitive has the following
15105: form:
1.1 anton 15106:
15107: @cindex primitive source format
15108: @format
1.58 anton 15109: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15110: [@code{""}@i{glossary entry}@code{""}]
15111: @i{C code}
1.1 anton 15112: [@code{:}
1.29 crook 15113: @i{Forth code}]
1.1 anton 15114: @end format
15115:
15116: The items in brackets are optional. The category and glossary fields
15117: are there for generating the documentation, the Forth code is there
15118: for manual implementations on machines without GNU C. E.g., the source
15119: for the primitive @code{+} is:
15120: @example
1.58 anton 15121: + ( n1 n2 -- n ) core plus
1.1 anton 15122: n = n1+n2;
15123: @end example
15124:
15125: This looks like a specification, but in fact @code{n = n1+n2} is C
15126: code. Our primitive generation tool extracts a lot of information from
15127: the stack effect notations@footnote{We use a one-stack notation, even
15128: though we have separate data and floating-point stacks; The separate
15129: notation can be generated easily from the unified notation.}: The number
15130: of items popped from and pushed on the stack, their type, and by what
15131: name they are referred to in the C code. It then generates a C code
15132: prelude and postlude for each primitive. The final C code for @code{+}
15133: looks like this:
15134:
15135: @example
1.46 pazsan 15136: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15137: /* */ /* documentation */
1.81 anton 15138: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15139: @{
15140: DEF_CA /* definition of variable ca (indirect threading) */
15141: Cell n1; /* definitions of variables */
15142: Cell n2;
15143: Cell n;
1.81 anton 15144: NEXT_P0; /* NEXT part 0 */
1.1 anton 15145: n1 = (Cell) sp[1]; /* input */
15146: n2 = (Cell) TOS;
15147: sp += 1; /* stack adjustment */
15148: @{
15149: n = n1+n2; /* C code taken from the source */
15150: @}
15151: NEXT_P1; /* NEXT part 1 */
15152: TOS = (Cell)n; /* output */
15153: NEXT_P2; /* NEXT part 2 */
15154: @}
15155: @end example
15156:
15157: This looks long and inefficient, but the GNU C compiler optimizes quite
15158: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15159: HP RISC machines: Defining the @code{n}s does not produce any code, and
15160: using them as intermediate storage also adds no cost.
15161:
1.26 crook 15162: There are also other optimizations that are not illustrated by this
15163: example: assignments between simple variables are usually for free (copy
1.1 anton 15164: propagation). If one of the stack items is not used by the primitive
15165: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15166: (dead code elimination). On the other hand, there are some things that
15167: the compiler does not do, therefore they are performed by
15168: @file{prims2x.fs}: The compiler does not optimize code away that stores
15169: a stack item to the place where it just came from (e.g., @code{over}).
15170:
15171: While programming a primitive is usually easy, there are a few cases
15172: where the programmer has to take the actions of the generator into
15173: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15174: fall through to @code{NEXT}.
1.109 anton 15175:
15176: For more information
1.1 anton 15177:
15178: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15179: @subsection TOS Optimization
15180: @cindex TOS optimization for primitives
15181: @cindex primitives, keeping the TOS in a register
15182:
15183: An important optimization for stack machine emulators, e.g., Forth
15184: engines, is keeping one or more of the top stack items in
1.29 crook 15185: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15186: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15187: @itemize @bullet
15188: @item
1.29 crook 15189: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15190: due to fewer loads from and stores to the stack.
1.29 crook 15191: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15192: @i{y<n}, due to additional moves between registers.
1.1 anton 15193: @end itemize
15194:
15195: @cindex -DUSE_TOS
15196: @cindex -DUSE_NO_TOS
15197: In particular, keeping one item in a register is never a disadvantage,
15198: if there are enough registers. Keeping two items in registers is a
15199: disadvantage for frequent words like @code{?branch}, constants,
15200: variables, literals and @code{i}. Therefore our generator only produces
15201: code that keeps zero or one items in registers. The generated C code
15202: covers both cases; the selection between these alternatives is made at
15203: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15204: code for @code{+} is just a simple variable name in the one-item case,
15205: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15206: GNU C compiler tries to keep simple variables like @code{TOS} in
15207: registers, and it usually succeeds, if there are enough registers.
15208:
15209: @cindex -DUSE_FTOS
15210: @cindex -DUSE_NO_FTOS
15211: The primitive generator performs the TOS optimization for the
15212: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15213: operations the benefit of this optimization is even larger:
15214: floating-point operations take quite long on most processors, but can be
15215: performed in parallel with other operations as long as their results are
15216: not used. If the FP-TOS is kept in a register, this works. If
15217: it is kept on the stack, i.e., in memory, the store into memory has to
15218: wait for the result of the floating-point operation, lengthening the
15219: execution time of the primitive considerably.
15220:
15221: The TOS optimization makes the automatic generation of primitives a
15222: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15223: @code{TOS} is not sufficient. There are some special cases to
15224: consider:
15225: @itemize @bullet
15226: @item In the case of @code{dup ( w -- w w )} the generator must not
15227: eliminate the store to the original location of the item on the stack,
15228: if the TOS optimization is turned on.
15229: @item Primitives with stack effects of the form @code{--}
1.29 crook 15230: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15231: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15232: must load the TOS from the stack at the end. But for the null stack
15233: effect @code{--} no stores or loads should be generated.
15234: @end itemize
15235:
15236: @node Produced code, , TOS Optimization, Primitives
15237: @subsection Produced code
15238: @cindex primitives, assembly code listing
15239:
15240: @cindex @file{engine.s}
15241: To see what assembly code is produced for the primitives on your machine
15242: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15243: look at the resulting file @file{engine.s}. Alternatively, you can also
15244: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15245:
15246: @node Performance, , Primitives, Engine
15247: @section Performance
15248: @cindex performance of some Forth interpreters
15249: @cindex engine performance
15250: @cindex benchmarking Forth systems
15251: @cindex Gforth performance
15252:
15253: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15254: impossible to write a significantly faster threaded-code engine.
1.1 anton 15255:
15256: On register-starved machines like the 386 architecture processors
15257: improvements are possible, because @code{gcc} does not utilize the
15258: registers as well as a human, even with explicit register declarations;
15259: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15260: and hand-tuned it for the 486; this system is 1.19 times faster on the
15261: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15262: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15263: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15264: registers fit in real registers (and we can even afford to use the TOS
15265: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15266: earlier results. And dynamic superinstructions provide another speedup
15267: (but only around a factor 1.2 on the 486).
1.1 anton 15268:
15269: @cindex Win32Forth performance
15270: @cindex NT Forth performance
15271: @cindex eforth performance
15272: @cindex ThisForth performance
15273: @cindex PFE performance
15274: @cindex TILE performance
1.81 anton 15275: The potential advantage of assembly language implementations is not
1.112 anton 15276: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15277: (direct threaded, compiled with @code{gcc-2.95.1} and
15278: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15279: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15280: (with and without peephole (aka pinhole) optimization of the threaded
15281: code); all these systems were written in assembly language. We also
15282: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15283: with @code{gcc-2.6.3} with the default configuration for Linux:
15284: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15285: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15286: employs peephole optimization of the threaded code) and TILE (compiled
15287: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15288: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15289: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15290: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15291: then extended it to run the benchmarks, added the peephole optimizer,
15292: ran the benchmarks and reported the results.
1.40 anton 15293:
1.1 anton 15294: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15295: matrix multiplication come from the Stanford integer benchmarks and have
15296: been translated into Forth by Martin Fraeman; we used the versions
15297: included in the TILE Forth package, but with bigger data set sizes; and
15298: a recursive Fibonacci number computation for benchmarking calling
15299: performance. The following table shows the time taken for the benchmarks
15300: scaled by the time taken by Gforth (in other words, it shows the speedup
15301: factor that Gforth achieved over the other systems).
15302:
15303: @example
1.112 anton 15304: relative Win32- NT eforth This-
15305: time Gforth Forth Forth eforth +opt PFE Forth TILE
15306: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15307: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15308: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15309: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15310: @end example
15311:
1.26 crook 15312: You may be quite surprised by the good performance of Gforth when
15313: compared with systems written in assembly language. One important reason
15314: for the disappointing performance of these other systems is probably
15315: that they are not written optimally for the 486 (e.g., they use the
15316: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15317: but costly method for relocating the Forth image: like @code{cforth}, it
15318: computes the actual addresses at run time, resulting in two address
15319: computations per @code{NEXT} (@pxref{Image File Background}).
15320:
1.1 anton 15321: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15322: explained with the self-imposed restriction of the latter systems to
15323: standard C, which makes efficient threading impossible (however, the
1.4 anton 15324: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15325: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15326: Moreover, current C compilers have a hard time optimizing other aspects
15327: of the ThisForth and the TILE source.
15328:
1.26 crook 15329: The performance of Gforth on 386 architecture processors varies widely
15330: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15331: allocate any of the virtual machine registers into real machine
15332: registers by itself and would not work correctly with explicit register
1.112 anton 15333: declarations, giving a significantly slower engine (on a 486DX2/66
15334: running the Sieve) than the one measured above.
1.1 anton 15335:
1.26 crook 15336: Note that there have been several releases of Win32Forth since the
15337: release presented here, so the results presented above may have little
1.40 anton 15338: predictive value for the performance of Win32Forth today (results for
15339: the current release on an i486DX2/66 are welcome).
1.1 anton 15340:
15341: @cindex @file{Benchres}
1.66 anton 15342: In
15343: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15344: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15345: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15346: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15347: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15348: than the version used here. You can find a newer version of these
15349: measurements at
1.47 crook 15350: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15351: find numbers for Gforth on various machines in @file{Benchres}.
15352:
1.26 crook 15353: @c ******************************************************************
1.113 anton 15354: @c @node Binding to System Library, Cross Compiler, Engine, Top
15355: @c @chapter Binding to System Library
1.13 pazsan 15356:
1.113 anton 15357: @c ****************************************************************
15358: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15359: @chapter Cross Compiler
1.47 crook 15360: @cindex @file{cross.fs}
15361: @cindex cross-compiler
15362: @cindex metacompiler
15363: @cindex target compiler
1.13 pazsan 15364:
1.46 pazsan 15365: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15366: mostly written in Forth, including crucial parts like the outer
15367: interpreter and compiler, it needs compiled Forth code to get
15368: started. The cross compiler allows to create new images for other
15369: architectures, even running under another Forth system.
1.13 pazsan 15370:
15371: @menu
1.67 anton 15372: * Using the Cross Compiler::
15373: * How the Cross Compiler Works::
1.13 pazsan 15374: @end menu
15375:
1.21 crook 15376: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15377: @section Using the Cross Compiler
1.46 pazsan 15378:
15379: The cross compiler uses a language that resembles Forth, but isn't. The
15380: main difference is that you can execute Forth code after definition,
15381: while you usually can't execute the code compiled by cross, because the
15382: code you are compiling is typically for a different computer than the
15383: one you are compiling on.
15384:
1.81 anton 15385: @c anton: This chapter is somewhat different from waht I would expect: I
15386: @c would expect an explanation of the cross language and how to create an
15387: @c application image with it. The section explains some aspects of
15388: @c creating a Gforth kernel.
15389:
1.46 pazsan 15390: The Makefile is already set up to allow you to create kernels for new
15391: architectures with a simple make command. The generic kernels using the
15392: GCC compiled virtual machine are created in the normal build process
15393: with @code{make}. To create a embedded Gforth executable for e.g. the
15394: 8086 processor (running on a DOS machine), type
15395:
15396: @example
15397: make kernl-8086.fi
15398: @end example
15399:
15400: This will use the machine description from the @file{arch/8086}
15401: directory to create a new kernel. A machine file may look like that:
15402:
15403: @example
15404: \ Parameter for target systems 06oct92py
15405:
15406: 4 Constant cell \ cell size in bytes
15407: 2 Constant cell<< \ cell shift to bytes
15408: 5 Constant cell>bit \ cell shift to bits
15409: 8 Constant bits/char \ bits per character
15410: 8 Constant bits/byte \ bits per byte [default: 8]
15411: 8 Constant float \ bytes per float
15412: 8 Constant /maxalign \ maximum alignment in bytes
15413: false Constant bigendian \ byte order
15414: ( true=big, false=little )
15415:
15416: include machpc.fs \ feature list
15417: @end example
15418:
15419: This part is obligatory for the cross compiler itself, the feature list
15420: is used by the kernel to conditionally compile some features in and out,
15421: depending on whether the target supports these features.
15422:
15423: There are some optional features, if you define your own primitives,
15424: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15425: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15426: @code{prims-include} includes primitives, and @code{>boot} prepares for
15427: booting.
15428:
15429: @example
15430: : asm-include ." Include assembler" cr
15431: s" arch/8086/asm.fs" included ;
15432:
15433: : prims-include ." Include primitives" cr
15434: s" arch/8086/prim.fs" included ;
15435:
15436: : >boot ." Prepare booting" cr
15437: s" ' boot >body into-forth 1+ !" evaluate ;
15438: @end example
15439:
15440: These words are used as sort of macro during the cross compilation in
1.81 anton 15441: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15442: be possible --- but more complicated --- to write a new kernel project
15443: file, too.
15444:
15445: @file{kernel/main.fs} expects the machine description file name on the
15446: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15447: @code{mach-file} leaves a counted string on the stack, or
15448: @code{machine-file} leaves an address, count pair of the filename on the
15449: stack.
15450:
15451: The feature list is typically controlled using @code{SetValue}, generic
15452: files that are used by several projects can use @code{DefaultValue}
15453: instead. Both functions work like @code{Value}, when the value isn't
15454: defined, but @code{SetValue} works like @code{to} if the value is
15455: defined, and @code{DefaultValue} doesn't set anything, if the value is
15456: defined.
15457:
15458: @example
15459: \ generic mach file for pc gforth 03sep97jaw
15460:
15461: true DefaultValue NIL \ relocating
15462:
15463: >ENVIRON
15464:
15465: true DefaultValue file \ controls the presence of the
15466: \ file access wordset
15467: true DefaultValue OS \ flag to indicate a operating system
15468:
15469: true DefaultValue prims \ true: primitives are c-code
15470:
15471: true DefaultValue floating \ floating point wordset is present
15472:
15473: true DefaultValue glocals \ gforth locals are present
15474: \ will be loaded
15475: true DefaultValue dcomps \ double number comparisons
15476:
15477: true DefaultValue hash \ hashing primitives are loaded/present
15478:
15479: true DefaultValue xconds \ used together with glocals,
15480: \ special conditionals supporting gforths'
15481: \ local variables
15482: true DefaultValue header \ save a header information
15483:
15484: true DefaultValue backtrace \ enables backtrace code
15485:
15486: false DefaultValue ec
15487: false DefaultValue crlf
15488:
15489: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15490:
15491: &16 KB DefaultValue stack-size
15492: &15 KB &512 + DefaultValue fstack-size
15493: &15 KB DefaultValue rstack-size
15494: &14 KB &512 + DefaultValue lstack-size
15495: @end example
1.13 pazsan 15496:
1.48 anton 15497: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15498: @section How the Cross Compiler Works
1.13 pazsan 15499:
15500: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15501: @appendix Bugs
1.1 anton 15502: @cindex bug reporting
15503:
1.21 crook 15504: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15505:
1.103 anton 15506: If you find a bug, please submit a bug report through
15507: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15508:
15509: @itemize @bullet
15510: @item
1.81 anton 15511: A program (or a sequence of keyboard commands) that reproduces the bug.
15512: @item
15513: A description of what you think constitutes the buggy behaviour.
15514: @item
1.21 crook 15515: The Gforth version used (it is announced at the start of an
15516: interactive Gforth session).
15517: @item
15518: The machine and operating system (on Unix
15519: systems @code{uname -a} will report this information).
15520: @item
1.81 anton 15521: The installation options (you can find the configure options at the
15522: start of @file{config.status}) and configuration (@code{configure}
15523: output or @file{config.cache}).
1.21 crook 15524: @item
15525: A complete list of changes (if any) you (or your installer) have made to the
15526: Gforth sources.
15527: @end itemize
1.1 anton 15528:
15529: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15530: to Report Bugs, gcc.info, GNU C Manual}.
15531:
15532:
1.21 crook 15533: @node Origin, Forth-related information, Bugs, Top
15534: @appendix Authors and Ancestors of Gforth
1.1 anton 15535:
15536: @section Authors and Contributors
15537: @cindex authors of Gforth
15538: @cindex contributors to Gforth
15539:
15540: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15541: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15542: lot to the manual. Assemblers and disassemblers were contributed by
15543: Andrew McKewan, Christian Pirker, and Bernd Thallner. Lennart Benschop
15544: (who was one of Gforth's first users, in mid-1993) and Stuart Ramsden
15545: inspired us with their continuous feedback. Lennart Benshop contributed
1.1 anton 15546: @file{glosgen.fs}, while Stuart Ramsden has been working on automatic
15547: support for calling C libraries. Helpful comments also came from Paul
15548: Kleinrubatscher, Christian Pirker, Dirk Zoller, Marcel Hendrix, John
1.113 anton 15549: Wavrik, Barrie Stott, Marc de Groot, Jorge Acerada, Bruce Hoyt, Robert
15550: Epprecht, Dennis Ruffer and David N. Williams. Since the release of
15551: Gforth-0.2.1 there were also helpful comments from many others; thank
15552: you all, sorry for not listing you here (but digging through my mailbox
15553: to extract your names is on my to-do list).
1.1 anton 15554:
15555: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15556: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15557: was developed across the Internet, and its authors did not meet
1.20 pazsan 15558: physically for the first 4 years of development.
1.1 anton 15559:
15560: @section Pedigree
1.26 crook 15561: @cindex pedigree of Gforth
1.1 anton 15562:
1.81 anton 15563: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15564: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15565:
1.20 pazsan 15566: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15567: 32 bit native code version of VolksForth for the Atari ST, written
15568: mostly by Dietrich Weineck.
15569:
1.81 anton 15570: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15571: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15572: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15573:
1.147 anton 15574: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15575: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15576:
15577: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15578: 1979. Robert Selzer and Bill Ragsdale developed the original
15579: implementation of fig-Forth for the 6502 based on microForth.
15580:
15581: The principal architect of microForth was Dean Sanderson. microForth was
15582: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15583: the 1802, and subsequently implemented on the 8080, the 6800 and the
15584: Z80.
15585:
15586: All earlier Forth systems were custom-made, usually by Charles Moore,
15587: who discovered (as he puts it) Forth during the late 60s. The first full
15588: Forth existed in 1971.
15589:
1.81 anton 15590: A part of the information in this section comes from
15591: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15592: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15593: Charles H. Moore, presented at the HOPL-II conference and preprinted
15594: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15595: genealogical information about Forth there. For a more general (and
15596: graphical) Forth family tree look see
15597: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15598: Forth Family Tree and Timeline}.
1.1 anton 15599:
1.81 anton 15600: @c ------------------------------------------------------------------
1.113 anton 15601: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15602: @appendix Other Forth-related information
15603: @cindex Forth-related information
15604:
1.81 anton 15605: @c anton: I threw most of this stuff out, because it can be found through
15606: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15607:
15608: @cindex comp.lang.forth
15609: @cindex frequently asked questions
1.81 anton 15610: There is an active news group (comp.lang.forth) discussing Forth
15611: (including Gforth) and Forth-related issues. Its
15612: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15613: (frequently asked questions and their answers) contains a lot of
15614: information on Forth. You should read it before posting to
15615: comp.lang.forth.
1.21 crook 15616:
1.81 anton 15617: The ANS Forth standard is most usable in its
15618: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15619:
1.113 anton 15620: @c ---------------------------------------------------
15621: @node Licenses, Word Index, Forth-related information, Top
15622: @appendix Licenses
15623:
15624: @menu
15625: * GNU Free Documentation License:: License for copying this manual.
15626: * Copying:: GPL (for copying this software).
15627: @end menu
15628:
15629: @include fdl.texi
15630:
15631: @include gpl.texi
15632:
15633:
15634:
1.81 anton 15635: @c ------------------------------------------------------------------
1.113 anton 15636: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15637: @unnumbered Word Index
15638:
1.26 crook 15639: This index is a list of Forth words that have ``glossary'' entries
15640: within this manual. Each word is listed with its stack effect and
15641: wordset.
1.1 anton 15642:
15643: @printindex fn
15644:
1.81 anton 15645: @c anton: the name index seems superfluous given the word and concept indices.
15646:
15647: @c @node Name Index, Concept Index, Word Index, Top
15648: @c @unnumbered Name Index
1.41 anton 15649:
1.81 anton 15650: @c This index is a list of Forth words that have ``glossary'' entries
15651: @c within this manual.
1.41 anton 15652:
1.81 anton 15653: @c @printindex ky
1.41 anton 15654:
1.113 anton 15655: @c -------------------------------------------------------
1.81 anton 15656: @node Concept Index, , Word Index, Top
1.1 anton 15657: @unnumbered Concept and Word Index
15658:
1.26 crook 15659: Not all entries listed in this index are present verbatim in the
15660: text. This index also duplicates, in abbreviated form, all of the words
15661: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15662:
15663: @printindex cp
15664:
15665: @bye
1.81 anton 15666:
15667:
1.1 anton 15668:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>