Annotation of gforth/doc/gforth.ds, revision 1.162
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
1.161 anton 418: * PowerPC assembler::
1.78 anton 419: * Other assemblers:: How to write them
420:
1.12 anton 421: Tools
422:
423: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 424: * Stack depth changes:: Where does this stack item come from?
1.12 anton 425:
426: ANS conformance
427:
428: * The Core Words::
429: * The optional Block word set::
430: * The optional Double Number word set::
431: * The optional Exception word set::
432: * The optional Facility word set::
433: * The optional File-Access word set::
434: * The optional Floating-Point word set::
435: * The optional Locals word set::
436: * The optional Memory-Allocation word set::
437: * The optional Programming-Tools word set::
438: * The optional Search-Order word set::
439:
440: The Core Words
441:
442: * core-idef:: Implementation Defined Options
443: * core-ambcond:: Ambiguous Conditions
444: * core-other:: Other System Documentation
445:
446: The optional Block word set
447:
448: * block-idef:: Implementation Defined Options
449: * block-ambcond:: Ambiguous Conditions
450: * block-other:: Other System Documentation
451:
452: The optional Double Number word set
453:
454: * double-ambcond:: Ambiguous Conditions
455:
456: The optional Exception word set
457:
458: * exception-idef:: Implementation Defined Options
459:
460: The optional Facility word set
461:
462: * facility-idef:: Implementation Defined Options
463: * facility-ambcond:: Ambiguous Conditions
464:
465: The optional File-Access word set
466:
467: * file-idef:: Implementation Defined Options
468: * file-ambcond:: Ambiguous Conditions
469:
470: The optional Floating-Point word set
471:
472: * floating-idef:: Implementation Defined Options
473: * floating-ambcond:: Ambiguous Conditions
474:
475: The optional Locals word set
476:
477: * locals-idef:: Implementation Defined Options
478: * locals-ambcond:: Ambiguous Conditions
479:
480: The optional Memory-Allocation word set
481:
482: * memory-idef:: Implementation Defined Options
483:
484: The optional Programming-Tools word set
485:
486: * programming-idef:: Implementation Defined Options
487: * programming-ambcond:: Ambiguous Conditions
488:
489: The optional Search-Order word set
490:
491: * search-idef:: Implementation Defined Options
492: * search-ambcond:: Ambiguous Conditions
493:
1.109 anton 494: Emacs and Gforth
495:
496: * Installing gforth.el:: Making Emacs aware of Forth.
497: * Emacs Tags:: Viewing the source of a word in Emacs.
498: * Hilighting:: Making Forth code look prettier.
499: * Auto-Indentation:: Customizing auto-indentation.
500: * Blocks Files:: Reading and writing blocks files.
501:
1.12 anton 502: Image Files
503:
1.24 anton 504: * Image Licensing Issues:: Distribution terms for images.
505: * Image File Background:: Why have image files?
1.67 anton 506: * Non-Relocatable Image Files:: don't always work.
1.24 anton 507: * Data-Relocatable Image Files:: are better.
1.67 anton 508: * Fully Relocatable Image Files:: better yet.
1.24 anton 509: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 510: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 511: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 512:
513: Fully Relocatable Image Files
514:
1.27 crook 515: * gforthmi:: The normal way
1.12 anton 516: * cross.fs:: The hard way
517:
518: Engine
519:
520: * Portability::
521: * Threading::
522: * Primitives::
523: * Performance::
524:
525: Threading
526:
527: * Scheduling::
528: * Direct or Indirect Threaded?::
1.109 anton 529: * Dynamic Superinstructions::
1.12 anton 530: * DOES>::
531:
532: Primitives
533:
534: * Automatic Generation::
535: * TOS Optimization::
536: * Produced code::
1.13 pazsan 537:
538: Cross Compiler
539:
1.67 anton 540: * Using the Cross Compiler::
541: * How the Cross Compiler Works::
1.13 pazsan 542:
1.113 anton 543: Licenses
544:
545: * GNU Free Documentation License:: License for copying this manual.
546: * Copying:: GPL (for copying this software).
547:
1.24 anton 548: @end detailmenu
1.1 anton 549: @end menu
550:
1.113 anton 551: @c ----------------------------------------------------------
1.1 anton 552: @iftex
553: @unnumbered Preface
554: @cindex Preface
1.21 crook 555: This manual documents Gforth. Some introductory material is provided for
556: readers who are unfamiliar with Forth or who are migrating to Gforth
557: from other Forth compilers. However, this manual is primarily a
558: reference manual.
1.1 anton 559: @end iftex
560:
1.28 crook 561: @comment TODO much more blurb here.
1.26 crook 562:
563: @c ******************************************************************
1.113 anton 564: @node Goals, Gforth Environment, Top, Top
1.26 crook 565: @comment node-name, next, previous, up
566: @chapter Goals of Gforth
567: @cindex goals of the Gforth project
568: The goal of the Gforth Project is to develop a standard model for
569: ANS Forth. This can be split into several subgoals:
570:
571: @itemize @bullet
572: @item
573: Gforth should conform to the ANS Forth Standard.
574: @item
575: It should be a model, i.e. it should define all the
576: implementation-dependent things.
577: @item
578: It should become standard, i.e. widely accepted and used. This goal
579: is the most difficult one.
580: @end itemize
581:
582: To achieve these goals Gforth should be
583: @itemize @bullet
584: @item
585: Similar to previous models (fig-Forth, F83)
586: @item
587: Powerful. It should provide for all the things that are considered
588: necessary today and even some that are not yet considered necessary.
589: @item
590: Efficient. It should not get the reputation of being exceptionally
591: slow.
592: @item
593: Free.
594: @item
595: Available on many machines/easy to port.
596: @end itemize
597:
598: Have we achieved these goals? Gforth conforms to the ANS Forth
599: standard. It may be considered a model, but we have not yet documented
600: which parts of the model are stable and which parts we are likely to
601: change. It certainly has not yet become a de facto standard, but it
602: appears to be quite popular. It has some similarities to and some
603: differences from previous models. It has some powerful features, but not
604: yet everything that we envisioned. We certainly have achieved our
1.65 anton 605: execution speed goals (@pxref{Performance})@footnote{However, in 1998
606: the bar was raised when the major commercial Forth vendors switched to
607: native code compilers.}. It is free and available on many machines.
1.29 crook 608:
1.26 crook 609: @c ******************************************************************
1.48 anton 610: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 611: @chapter Gforth Environment
612: @cindex Gforth environment
1.21 crook 613:
1.45 crook 614: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 615: material in this chapter.
1.21 crook 616:
617: @menu
1.29 crook 618: * Invoking Gforth:: Getting in
619: * Leaving Gforth:: Getting out
620: * Command-line editing::
1.48 anton 621: * Environment variables:: that affect how Gforth starts up
1.29 crook 622: * Gforth Files:: What gets installed and where
1.112 anton 623: * Gforth in pipes::
1.48 anton 624: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 625: @end menu
626:
1.49 anton 627: For related information about the creation of images see @ref{Image Files}.
1.29 crook 628:
1.21 crook 629: @comment ----------------------------------------------
1.48 anton 630: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 631: @section Invoking Gforth
632: @cindex invoking Gforth
633: @cindex running Gforth
634: @cindex command-line options
635: @cindex options on the command line
636: @cindex flags on the command line
1.21 crook 637:
1.30 anton 638: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 639: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 640: will usually just say @code{gforth} -- this automatically loads the
641: default image file @file{gforth.fi}. In many other cases the default
642: Gforth image will be invoked like this:
1.21 crook 643: @example
1.30 anton 644: gforth [file | -e forth-code] ...
1.21 crook 645: @end example
1.29 crook 646: @noindent
647: This interprets the contents of the files and the Forth code in the order they
648: are given.
1.21 crook 649:
1.109 anton 650: In addition to the @command{gforth} engine, there is also an engine
651: called @command{gforth-fast}, which is faster, but gives less
652: informative error messages (@pxref{Error messages}) and may catch some
653: stack underflows later or not at all. You should use it for debugged,
654: performance-critical programs.
655:
656: Moreover, there is an engine called @command{gforth-itc}, which is
657: useful in some backwards-compatibility situations (@pxref{Direct or
658: Indirect Threaded?}).
1.30 anton 659:
1.29 crook 660: In general, the command line looks like this:
1.21 crook 661:
662: @example
1.30 anton 663: gforth[-fast] [engine options] [image options]
1.21 crook 664: @end example
665:
1.30 anton 666: The engine options must come before the rest of the command
1.29 crook 667: line. They are:
1.26 crook 668:
1.29 crook 669: @table @code
670: @cindex -i, command-line option
671: @cindex --image-file, command-line option
672: @item --image-file @i{file}
673: @itemx -i @i{file}
674: Loads the Forth image @i{file} instead of the default
675: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 676:
1.39 anton 677: @cindex --appl-image, command-line option
678: @item --appl-image @i{file}
679: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 680: to the image (instead of processing them as engine options). This is
681: useful for building executable application images on Unix, built with
1.39 anton 682: @code{gforthmi --application ...}.
683:
1.29 crook 684: @cindex --path, command-line option
685: @cindex -p, command-line option
686: @item --path @i{path}
687: @itemx -p @i{path}
688: Uses @i{path} for searching the image file and Forth source code files
689: instead of the default in the environment variable @code{GFORTHPATH} or
690: the path specified at installation time (e.g.,
691: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
692: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 693:
1.29 crook 694: @cindex --dictionary-size, command-line option
695: @cindex -m, command-line option
696: @cindex @i{size} parameters for command-line options
697: @cindex size of the dictionary and the stacks
698: @item --dictionary-size @i{size}
699: @itemx -m @i{size}
700: Allocate @i{size} space for the Forth dictionary space instead of
701: using the default specified in the image (typically 256K). The
702: @i{size} specification for this and subsequent options consists of
703: an integer and a unit (e.g.,
704: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
705: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
706: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
707: @code{e} is used.
1.21 crook 708:
1.29 crook 709: @cindex --data-stack-size, command-line option
710: @cindex -d, command-line option
711: @item --data-stack-size @i{size}
712: @itemx -d @i{size}
713: Allocate @i{size} space for the data stack instead of using the
714: default specified in the image (typically 16K).
1.21 crook 715:
1.29 crook 716: @cindex --return-stack-size, command-line option
717: @cindex -r, command-line option
718: @item --return-stack-size @i{size}
719: @itemx -r @i{size}
720: Allocate @i{size} space for the return stack instead of using the
721: default specified in the image (typically 15K).
1.21 crook 722:
1.29 crook 723: @cindex --fp-stack-size, command-line option
724: @cindex -f, command-line option
725: @item --fp-stack-size @i{size}
726: @itemx -f @i{size}
727: Allocate @i{size} space for the floating point stack instead of
728: using the default specified in the image (typically 15.5K). In this case
729: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 730:
1.48 anton 731: @cindex --locals-stack-size, command-line option
732: @cindex -l, command-line option
733: @item --locals-stack-size @i{size}
734: @itemx -l @i{size}
735: Allocate @i{size} space for the locals stack instead of using the
736: default specified in the image (typically 14.5K).
737:
738: @cindex -h, command-line option
739: @cindex --help, command-line option
740: @item --help
741: @itemx -h
742: Print a message about the command-line options
743:
744: @cindex -v, command-line option
745: @cindex --version, command-line option
746: @item --version
747: @itemx -v
748: Print version and exit
749:
750: @cindex --debug, command-line option
751: @item --debug
752: Print some information useful for debugging on startup.
753:
754: @cindex --offset-image, command-line option
755: @item --offset-image
756: Start the dictionary at a slightly different position than would be used
757: otherwise (useful for creating data-relocatable images,
758: @pxref{Data-Relocatable Image Files}).
759:
760: @cindex --no-offset-im, command-line option
761: @item --no-offset-im
762: Start the dictionary at the normal position.
763:
764: @cindex --clear-dictionary, command-line option
765: @item --clear-dictionary
766: Initialize all bytes in the dictionary to 0 before loading the image
767: (@pxref{Data-Relocatable Image Files}).
768:
769: @cindex --die-on-signal, command-line-option
770: @item --die-on-signal
771: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
772: or the segmentation violation SIGSEGV) by translating it into a Forth
773: @code{THROW}. With this option, Gforth exits if it receives such a
774: signal. This option is useful when the engine and/or the image might be
775: severely broken (such that it causes another signal before recovering
776: from the first); this option avoids endless loops in such cases.
1.109 anton 777:
1.119 anton 778: @cindex --no-dynamic, command-line option
779: @cindex --dynamic, command-line option
1.109 anton 780: @item --no-dynamic
781: @item --dynamic
782: Disable or enable dynamic superinstructions with replication
783: (@pxref{Dynamic Superinstructions}).
784:
1.119 anton 785: @cindex --no-super, command-line option
1.109 anton 786: @item --no-super
1.110 anton 787: Disable dynamic superinstructions, use just dynamic replication; this is
788: useful if you want to patch threaded code (@pxref{Dynamic
789: Superinstructions}).
1.119 anton 790:
791: @cindex --ss-number, command-line option
792: @item --ss-number=@var{N}
793: Use only the first @var{N} static superinstructions compiled into the
794: engine (default: use them all; note that only @code{gforth-fast} has
795: any). This option is useful for measuring the performance impact of
796: static superinstructions.
797:
798: @cindex --ss-min-..., command-line options
799: @item --ss-min-codesize
800: @item --ss-min-ls
801: @item --ss-min-lsu
802: @item --ss-min-nexts
803: Use specified metric for determining the cost of a primitive or static
804: superinstruction for static superinstruction selection. @code{Codesize}
805: is the native code size of the primive or static superinstruction,
806: @code{ls} is the number of loads and stores, @code{lsu} is the number of
807: loads, stores, and updates, and @code{nexts} is the number of dispatches
808: (not taking dynamic superinstructions into account), i.e. every
809: primitive or static superinstruction has cost 1. Default:
810: @code{codesize} if you use dynamic code generation, otherwise
811: @code{nexts}.
812:
813: @cindex --ss-greedy, command-line option
814: @item --ss-greedy
815: This option is useful for measuring the performance impact of static
816: superinstructions. By default, an optimal shortest-path algorithm is
817: used for selecting static superinstructions. With @option{--ss-greedy}
818: this algorithm is modified to assume that anything after the static
819: superinstruction currently under consideration is not combined into
820: static superinstructions. With @option{--ss-min-nexts} this produces
821: the same result as a greedy algorithm that always selects the longest
822: superinstruction available at the moment. E.g., if there are
823: superinstructions AB and BCD, then for the sequence A B C D the optimal
824: algorithm will select A BCD and the greedy algorithm will select AB C D.
825:
826: @cindex --print-metrics, command-line option
827: @item --print-metrics
828: Prints some metrics used during static superinstruction selection:
829: @code{code size} is the actual size of the dynamically generated code.
830: @code{Metric codesize} is the sum of the codesize metrics as seen by
831: static superinstruction selection; there is a difference from @code{code
832: size}, because not all primitives and static superinstructions are
833: compiled into dynamically generated code, and because of markers. The
834: other metrics correspond to the @option{ss-min-...} options. This
835: option is useful for evaluating the effects of the @option{--ss-...}
836: options.
1.109 anton 837:
1.48 anton 838: @end table
839:
840: @cindex loading files at startup
841: @cindex executing code on startup
842: @cindex batch processing with Gforth
843: As explained above, the image-specific command-line arguments for the
844: default image @file{gforth.fi} consist of a sequence of filenames and
845: @code{-e @var{forth-code}} options that are interpreted in the sequence
846: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 847: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
848: option takes only one argument; if you want to evaluate more Forth
849: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 850: after processing the command line (instead of entering interactive mode)
1.121 anton 851: append @code{-e bye} to the command line. You can also process the
852: command-line arguments with a Forth program (@pxref{OS command line
853: arguments}).
1.48 anton 854:
855: @cindex versions, invoking other versions of Gforth
856: If you have several versions of Gforth installed, @code{gforth} will
857: invoke the version that was installed last. @code{gforth-@i{version}}
858: invokes a specific version. If your environment contains the variable
859: @code{GFORTHPATH}, you may want to override it by using the
860: @code{--path} option.
861:
862: Not yet implemented:
863: On startup the system first executes the system initialization file
864: (unless the option @code{--no-init-file} is given; note that the system
865: resulting from using this option may not be ANS Forth conformant). Then
866: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 867: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 868: then in @file{~}, then in the normal path (see above).
869:
870:
871:
872: @comment ----------------------------------------------
873: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
874: @section Leaving Gforth
875: @cindex Gforth - leaving
876: @cindex leaving Gforth
877:
878: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
879: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
880: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 881: data are discarded. For ways of saving the state of the system before
882: leaving Gforth see @ref{Image Files}.
1.48 anton 883:
884: doc-bye
885:
886:
887: @comment ----------------------------------------------
1.65 anton 888: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 889: @section Command-line editing
890: @cindex command-line editing
891:
892: Gforth maintains a history file that records every line that you type to
893: the text interpreter. This file is preserved between sessions, and is
894: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
895: repeatedly you can recall successively older commands from this (or
896: previous) session(s). The full list of command-line editing facilities is:
897:
898: @itemize @bullet
899: @item
900: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
901: commands from the history buffer.
902: @item
903: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
904: from the history buffer.
905: @item
906: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
907: @item
908: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
909: @item
910: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
911: closing up the line.
912: @item
913: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
914: @item
915: @kbd{Ctrl-a} to move the cursor to the start of the line.
916: @item
917: @kbd{Ctrl-e} to move the cursor to the end of the line.
918: @item
919: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
920: line.
921: @item
922: @key{TAB} to step through all possible full-word completions of the word
923: currently being typed.
924: @item
1.65 anton 925: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
926: using @code{bye}).
927: @item
928: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
929: character under the cursor.
1.48 anton 930: @end itemize
931:
932: When editing, displayable characters are inserted to the left of the
933: cursor position; the line is always in ``insert'' (as opposed to
934: ``overstrike'') mode.
935:
936: @cindex history file
937: @cindex @file{.gforth-history}
938: On Unix systems, the history file is @file{~/.gforth-history} by
939: default@footnote{i.e. it is stored in the user's home directory.}. You
940: can find out the name and location of your history file using:
941:
942: @example
943: history-file type \ Unix-class systems
944:
945: history-file type \ Other systems
946: history-dir type
947: @end example
948:
949: If you enter long definitions by hand, you can use a text editor to
950: paste them out of the history file into a Forth source file for reuse at
951: a later time.
952:
953: Gforth never trims the size of the history file, so you should do this
954: periodically, if necessary.
955:
956: @comment this is all defined in history.fs
957: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
958: @comment chosen?
959:
960:
961: @comment ----------------------------------------------
1.65 anton 962: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 963: @section Environment variables
964: @cindex environment variables
965:
966: Gforth uses these environment variables:
967:
968: @itemize @bullet
969: @item
970: @cindex @code{GFORTHHIST} -- environment variable
971: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
972: open/create the history file, @file{.gforth-history}. Default:
973: @code{$HOME}.
974:
975: @item
976: @cindex @code{GFORTHPATH} -- environment variable
977: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
978: for Forth source-code files.
979:
980: @item
1.147 anton 981: @cindex @code{LANG} -- environment variable
982: @code{LANG} -- see @code{LC_CTYPE}
983:
984: @item
985: @cindex @code{LC_ALL} -- environment variable
986: @code{LC_ALL} -- see @code{LC_CTYPE}
987:
988: @item
989: @cindex @code{LC_CTYPE} -- environment variable
990: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
991: startup, Gforth uses the UTF-8 encoding for strings internally and
992: expects its input and produces its output in UTF-8 encoding, otherwise
993: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
994: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
995: that is unset, in @code{LANG}.
996:
997: @item
1.129 anton 998: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
999:
1000: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1001: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1002: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1003: and the command are directly concatenated, so if a space between them is
1004: necessary, append it to the prefix.
1005:
1006: @item
1.48 anton 1007: @cindex @code{GFORTH} -- environment variable
1.49 anton 1008: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1009:
1010: @item
1011: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1012: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1013:
1014: @item
1015: @cindex @code{TMP}, @code{TEMP} - environment variable
1016: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1017: location for the history file.
1018: @end itemize
1019:
1020: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1021: @comment mentioning these.
1022:
1023: All the Gforth environment variables default to sensible values if they
1024: are not set.
1025:
1026:
1027: @comment ----------------------------------------------
1.112 anton 1028: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1029: @section Gforth files
1030: @cindex Gforth files
1031:
1032: When you install Gforth on a Unix system, it installs files in these
1033: locations by default:
1034:
1035: @itemize @bullet
1036: @item
1037: @file{/usr/local/bin/gforth}
1038: @item
1039: @file{/usr/local/bin/gforthmi}
1040: @item
1041: @file{/usr/local/man/man1/gforth.1} - man page.
1042: @item
1043: @file{/usr/local/info} - the Info version of this manual.
1044: @item
1045: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1046: @item
1047: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1048: @item
1049: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1050: @item
1051: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1052: @end itemize
1053:
1054: You can select different places for installation by using
1055: @code{configure} options (listed with @code{configure --help}).
1056:
1057: @comment ----------------------------------------------
1.112 anton 1058: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1059: @section Gforth in pipes
1060: @cindex pipes, Gforth as part of
1061:
1062: Gforth can be used in pipes created elsewhere (described here). It can
1063: also create pipes on its own (@pxref{Pipes}).
1064:
1065: @cindex input from pipes
1066: If you pipe into Gforth, your program should read with @code{read-file}
1067: or @code{read-line} from @code{stdin} (@pxref{General files}).
1068: @code{Key} does not recognize the end of input. Words like
1069: @code{accept} echo the input and are therefore usually not useful for
1070: reading from a pipe. You have to invoke the Forth program with an OS
1071: command-line option, as you have no chance to use the Forth command line
1072: (the text interpreter would try to interpret the pipe input).
1073:
1074: @cindex output in pipes
1075: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1076:
1077: @cindex silent exiting from Gforth
1078: When you write to a pipe that has been closed at the other end, Gforth
1079: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1080: into the exception @code{broken-pipe-error}. If your application does
1081: not catch that exception, the system catches it and exits, usually
1082: silently (unless you were working on the Forth command line; then it
1083: prints an error message and exits). This is usually the desired
1084: behaviour.
1085:
1086: If you do not like this behaviour, you have to catch the exception
1087: yourself, and react to it.
1088:
1089: Here's an example of an invocation of Gforth that is usable in a pipe:
1090:
1091: @example
1092: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1093: type repeat ; foo bye"
1094: @end example
1095:
1096: This example just copies the input verbatim to the output. A very
1097: simple pipe containing this example looks like this:
1098:
1099: @example
1100: cat startup.fs |
1101: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1102: type repeat ; foo bye"|
1103: head
1104: @end example
1105:
1106: @cindex stderr and pipes
1107: Pipes involving Gforth's @code{stderr} output do not work.
1108:
1109: @comment ----------------------------------------------
1110: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1111: @section Startup speed
1112: @cindex Startup speed
1113: @cindex speed, startup
1114:
1115: If Gforth is used for CGI scripts or in shell scripts, its startup
1116: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1117: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1118: system time.
1119:
1120: If startup speed is a problem, you may consider the following ways to
1121: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1122: (for example, by using Fast-CGI).
1.48 anton 1123:
1.112 anton 1124: An easy step that influences Gforth startup speed is the use of the
1125: @option{--no-dynamic} option; this decreases image loading speed, but
1126: increases compile-time and run-time.
1127:
1128: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1129: building it with @code{XLDFLAGS=-static}. This requires more memory for
1130: the code and will therefore slow down the first invocation, but
1131: subsequent invocations avoid the dynamic linking overhead. Another
1132: disadvantage is that Gforth won't profit from library upgrades. As a
1133: result, @code{gforth-static -e bye} takes about 17.1ms user and
1134: 8.2ms system time.
1135:
1136: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1137: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1138: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1139: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1140: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1141: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1142: address for the dictionary, for whatever reason; so you better provide a
1143: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1144: bye} takes about 15.3ms user and 7.5ms system time.
1145:
1146: The final step is to disable dictionary hashing in Gforth. Gforth
1147: builds the hash table on startup, which takes much of the startup
1148: overhead. You can do this by commenting out the @code{include hash.fs}
1149: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1150: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1151: The disadvantages are that functionality like @code{table} and
1152: @code{ekey} is missing and that text interpretation (e.g., compiling)
1153: now takes much longer. So, you should only use this method if there is
1154: no significant text interpretation to perform (the script should be
1.62 crook 1155: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1156: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1157:
1158: @c ******************************************************************
1159: @node Tutorial, Introduction, Gforth Environment, Top
1160: @chapter Forth Tutorial
1161: @cindex Tutorial
1162: @cindex Forth Tutorial
1163:
1.67 anton 1164: @c Topics from nac's Introduction that could be mentioned:
1165: @c press <ret> after each line
1166: @c Prompt
1167: @c numbers vs. words in dictionary on text interpretation
1168: @c what happens on redefinition
1169: @c parsing words (in particular, defining words)
1170:
1.83 anton 1171: The difference of this chapter from the Introduction
1172: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1173: be used while sitting in front of a computer, and covers much more
1174: material, but does not explain how the Forth system works.
1175:
1.62 crook 1176: This tutorial can be used with any ANS-compliant Forth; any
1177: Gforth-specific features are marked as such and you can skip them if you
1178: work with another Forth. This tutorial does not explain all features of
1179: Forth, just enough to get you started and give you some ideas about the
1180: facilities available in Forth. Read the rest of the manual and the
1181: standard when you are through this.
1.48 anton 1182:
1183: The intended way to use this tutorial is that you work through it while
1184: sitting in front of the console, take a look at the examples and predict
1185: what they will do, then try them out; if the outcome is not as expected,
1186: find out why (e.g., by trying out variations of the example), so you
1187: understand what's going on. There are also some assignments that you
1188: should solve.
1189:
1190: This tutorial assumes that you have programmed before and know what,
1191: e.g., a loop is.
1192:
1193: @c !! explain compat library
1194:
1195: @menu
1196: * Starting Gforth Tutorial::
1197: * Syntax Tutorial::
1198: * Crash Course Tutorial::
1199: * Stack Tutorial::
1200: * Arithmetics Tutorial::
1201: * Stack Manipulation Tutorial::
1202: * Using files for Forth code Tutorial::
1203: * Comments Tutorial::
1204: * Colon Definitions Tutorial::
1205: * Decompilation Tutorial::
1206: * Stack-Effect Comments Tutorial::
1207: * Types Tutorial::
1208: * Factoring Tutorial::
1209: * Designing the stack effect Tutorial::
1210: * Local Variables Tutorial::
1211: * Conditional execution Tutorial::
1212: * Flags and Comparisons Tutorial::
1213: * General Loops Tutorial::
1214: * Counted loops Tutorial::
1215: * Recursion Tutorial::
1216: * Leaving definitions or loops Tutorial::
1217: * Return Stack Tutorial::
1218: * Memory Tutorial::
1219: * Characters and Strings Tutorial::
1220: * Alignment Tutorial::
1.87 anton 1221: * Files Tutorial::
1.48 anton 1222: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1223: * Execution Tokens Tutorial::
1224: * Exceptions Tutorial::
1225: * Defining Words Tutorial::
1226: * Arrays and Records Tutorial::
1227: * POSTPONE Tutorial::
1228: * Literal Tutorial::
1229: * Advanced macros Tutorial::
1230: * Compilation Tokens Tutorial::
1231: * Wordlists and Search Order Tutorial::
1232: @end menu
1233:
1234: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1235: @section Starting Gforth
1.66 anton 1236: @cindex starting Gforth tutorial
1.48 anton 1237: You can start Gforth by typing its name:
1238:
1239: @example
1240: gforth
1241: @end example
1242:
1243: That puts you into interactive mode; you can leave Gforth by typing
1244: @code{bye}. While in Gforth, you can edit the command line and access
1245: the command line history with cursor keys, similar to bash.
1246:
1247:
1248: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1249: @section Syntax
1.66 anton 1250: @cindex syntax tutorial
1.48 anton 1251:
1252: A @dfn{word} is a sequence of arbitrary characters (expcept white
1253: space). Words are separated by white space. E.g., each of the
1254: following lines contains exactly one word:
1255:
1256: @example
1257: word
1258: !@@#$%^&*()
1259: 1234567890
1260: 5!a
1261: @end example
1262:
1263: A frequent beginner's error is to leave away necessary white space,
1264: resulting in an error like @samp{Undefined word}; so if you see such an
1265: error, check if you have put spaces wherever necessary.
1266:
1267: @example
1268: ." hello, world" \ correct
1269: ."hello, world" \ gives an "Undefined word" error
1270: @end example
1271:
1.65 anton 1272: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1273: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1274: your system is case-sensitive, you may have to type all the examples
1275: given here in upper case.
1276:
1277:
1278: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1279: @section Crash Course
1280:
1281: Type
1282:
1283: @example
1284: 0 0 !
1285: here execute
1286: ' catch >body 20 erase abort
1287: ' (quit) >body 20 erase
1288: @end example
1289:
1290: The last two examples are guaranteed to destroy parts of Gforth (and
1291: most other systems), so you better leave Gforth afterwards (if it has
1292: not finished by itself). On some systems you may have to kill gforth
1293: from outside (e.g., in Unix with @code{kill}).
1294:
1295: Now that you know how to produce crashes (and that there's not much to
1296: them), let's learn how to produce meaningful programs.
1297:
1298:
1299: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1300: @section Stack
1.66 anton 1301: @cindex stack tutorial
1.48 anton 1302:
1303: The most obvious feature of Forth is the stack. When you type in a
1304: number, it is pushed on the stack. You can display the content of the
1305: stack with @code{.s}.
1306:
1307: @example
1308: 1 2 .s
1309: 3 .s
1310: @end example
1311:
1312: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1313: appear in @code{.s} output as they appeared in the input.
1314:
1315: You can print the top of stack element with @code{.}.
1316:
1317: @example
1318: 1 2 3 . . .
1319: @end example
1320:
1321: In general, words consume their stack arguments (@code{.s} is an
1322: exception).
1323:
1.141 anton 1324: @quotation Assignment
1.48 anton 1325: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1326: @end quotation
1.48 anton 1327:
1328:
1329: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1330: @section Arithmetics
1.66 anton 1331: @cindex arithmetics tutorial
1.48 anton 1332:
1333: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1334: operate on the top two stack items:
1335:
1336: @example
1.67 anton 1337: 2 2 .s
1338: + .s
1339: .
1.48 anton 1340: 2 1 - .
1341: 7 3 mod .
1342: @end example
1343:
1344: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1345: as in the corresponding infix expression (this is generally the case in
1346: Forth).
1347:
1348: Parentheses are superfluous (and not available), because the order of
1349: the words unambiguously determines the order of evaluation and the
1350: operands:
1351:
1352: @example
1353: 3 4 + 5 * .
1354: 3 4 5 * + .
1355: @end example
1356:
1.141 anton 1357: @quotation Assignment
1.48 anton 1358: What are the infix expressions corresponding to the Forth code above?
1359: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1360: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1361: @end quotation
1.48 anton 1362:
1363: To change the sign, use @code{negate}:
1364:
1365: @example
1366: 2 negate .
1367: @end example
1368:
1.141 anton 1369: @quotation Assignment
1.48 anton 1370: Convert -(-3)*4-5 to Forth.
1.141 anton 1371: @end quotation
1.48 anton 1372:
1373: @code{/mod} performs both @code{/} and @code{mod}.
1374:
1375: @example
1376: 7 3 /mod . .
1377: @end example
1378:
1.66 anton 1379: Reference: @ref{Arithmetic}.
1380:
1381:
1.48 anton 1382: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1383: @section Stack Manipulation
1.66 anton 1384: @cindex stack manipulation tutorial
1.48 anton 1385:
1386: Stack manipulation words rearrange the data on the stack.
1387:
1388: @example
1389: 1 .s drop .s
1390: 1 .s dup .s drop drop .s
1391: 1 2 .s over .s drop drop drop
1392: 1 2 .s swap .s drop drop
1393: 1 2 3 .s rot .s drop drop drop
1394: @end example
1395:
1396: These are the most important stack manipulation words. There are also
1397: variants that manipulate twice as many stack items:
1398:
1399: @example
1400: 1 2 3 4 .s 2swap .s 2drop 2drop
1401: @end example
1402:
1403: Two more stack manipulation words are:
1404:
1405: @example
1406: 1 2 .s nip .s drop
1407: 1 2 .s tuck .s 2drop drop
1408: @end example
1409:
1.141 anton 1410: @quotation Assignment
1.48 anton 1411: Replace @code{nip} and @code{tuck} with combinations of other stack
1412: manipulation words.
1413:
1414: @example
1415: Given: How do you get:
1416: 1 2 3 3 2 1
1417: 1 2 3 1 2 3 2
1418: 1 2 3 1 2 3 3
1419: 1 2 3 1 3 3
1420: 1 2 3 2 1 3
1421: 1 2 3 4 4 3 2 1
1422: 1 2 3 1 2 3 1 2 3
1423: 1 2 3 4 1 2 3 4 1 2
1424: 1 2 3
1425: 1 2 3 1 2 3 4
1426: 1 2 3 1 3
1427: @end example
1.141 anton 1428: @end quotation
1.48 anton 1429:
1430: @example
1431: 5 dup * .
1432: @end example
1433:
1.141 anton 1434: @quotation Assignment
1.48 anton 1435: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1436: Write a piece of Forth code that expects two numbers on the stack
1437: (@var{a} and @var{b}, with @var{b} on top) and computes
1438: @code{(a-b)(a+1)}.
1.141 anton 1439: @end quotation
1.48 anton 1440:
1.66 anton 1441: Reference: @ref{Stack Manipulation}.
1442:
1443:
1.48 anton 1444: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1445: @section Using files for Forth code
1.66 anton 1446: @cindex loading Forth code, tutorial
1447: @cindex files containing Forth code, tutorial
1.48 anton 1448:
1449: While working at the Forth command line is convenient for one-line
1450: examples and short one-off code, you probably want to store your source
1451: code in files for convenient editing and persistence. You can use your
1452: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1453: Gforth}) to create @var{file.fs} and use
1.48 anton 1454:
1455: @example
1.102 anton 1456: s" @var{file.fs}" included
1.48 anton 1457: @end example
1458:
1459: to load it into your Forth system. The file name extension I use for
1460: Forth files is @samp{.fs}.
1461:
1462: You can easily start Gforth with some files loaded like this:
1463:
1464: @example
1.102 anton 1465: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1466: @end example
1467:
1468: If an error occurs during loading these files, Gforth terminates,
1469: whereas an error during @code{INCLUDED} within Gforth usually gives you
1470: a Gforth command line. Starting the Forth system every time gives you a
1471: clean start every time, without interference from the results of earlier
1472: tries.
1473:
1474: I often put all the tests in a file, then load the code and run the
1475: tests with
1476:
1477: @example
1.102 anton 1478: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1479: @end example
1480:
1481: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1482: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1483: restart this command without ado.
1484:
1485: The advantage of this approach is that the tests can be repeated easily
1486: every time the program ist changed, making it easy to catch bugs
1487: introduced by the change.
1488:
1.66 anton 1489: Reference: @ref{Forth source files}.
1490:
1.48 anton 1491:
1492: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1493: @section Comments
1.66 anton 1494: @cindex comments tutorial
1.48 anton 1495:
1496: @example
1497: \ That's a comment; it ends at the end of the line
1498: ( Another comment; it ends here: ) .s
1499: @end example
1500:
1501: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1502: separated with white space from the following text.
1503:
1504: @example
1505: \This gives an "Undefined word" error
1506: @end example
1507:
1508: The first @code{)} ends a comment started with @code{(}, so you cannot
1509: nest @code{(}-comments; and you cannot comment out text containing a
1510: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1511: avoid @code{)} in word names.}.
1512:
1513: I use @code{\}-comments for descriptive text and for commenting out code
1514: of one or more line; I use @code{(}-comments for describing the stack
1515: effect, the stack contents, or for commenting out sub-line pieces of
1516: code.
1517:
1518: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1519: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1520: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1521: with @kbd{M-q}.
1522:
1.66 anton 1523: Reference: @ref{Comments}.
1524:
1.48 anton 1525:
1526: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1527: @section Colon Definitions
1.66 anton 1528: @cindex colon definitions, tutorial
1529: @cindex definitions, tutorial
1530: @cindex procedures, tutorial
1531: @cindex functions, tutorial
1.48 anton 1532:
1533: are similar to procedures and functions in other programming languages.
1534:
1535: @example
1536: : squared ( n -- n^2 )
1537: dup * ;
1538: 5 squared .
1539: 7 squared .
1540: @end example
1541:
1542: @code{:} starts the colon definition; its name is @code{squared}. The
1543: following comment describes its stack effect. The words @code{dup *}
1544: are not executed, but compiled into the definition. @code{;} ends the
1545: colon definition.
1546:
1547: The newly-defined word can be used like any other word, including using
1548: it in other definitions:
1549:
1550: @example
1551: : cubed ( n -- n^3 )
1552: dup squared * ;
1553: -5 cubed .
1554: : fourth-power ( n -- n^4 )
1555: squared squared ;
1556: 3 fourth-power .
1557: @end example
1558:
1.141 anton 1559: @quotation Assignment
1.48 anton 1560: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1561: @code{/mod} in terms of other Forth words, and check if they work (hint:
1562: test your tests on the originals first). Don't let the
1563: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1564: @end quotation
1.48 anton 1565:
1.66 anton 1566: Reference: @ref{Colon Definitions}.
1567:
1.48 anton 1568:
1569: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1570: @section Decompilation
1.66 anton 1571: @cindex decompilation tutorial
1572: @cindex see tutorial
1.48 anton 1573:
1574: You can decompile colon definitions with @code{see}:
1575:
1576: @example
1577: see squared
1578: see cubed
1579: @end example
1580:
1581: In Gforth @code{see} shows you a reconstruction of the source code from
1582: the executable code. Informations that were present in the source, but
1583: not in the executable code, are lost (e.g., comments).
1584:
1.65 anton 1585: You can also decompile the predefined words:
1586:
1587: @example
1588: see .
1589: see +
1590: @end example
1591:
1592:
1.48 anton 1593: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1594: @section Stack-Effect Comments
1.66 anton 1595: @cindex stack-effect comments, tutorial
1596: @cindex --, tutorial
1.48 anton 1597: By convention the comment after the name of a definition describes the
1598: stack effect: The part in from of the @samp{--} describes the state of
1599: the stack before the execution of the definition, i.e., the parameters
1600: that are passed into the colon definition; the part behind the @samp{--}
1601: is the state of the stack after the execution of the definition, i.e.,
1602: the results of the definition. The stack comment only shows the top
1603: stack items that the definition accesses and/or changes.
1604:
1605: You should put a correct stack effect on every definition, even if it is
1606: just @code{( -- )}. You should also add some descriptive comment to
1607: more complicated words (I usually do this in the lines following
1608: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1609: you have to work through every definition before you can understand
1.48 anton 1610: any).
1611:
1.141 anton 1612: @quotation Assignment
1.48 anton 1613: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1614: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1615: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1616: are done, you can compare your stack effects to those in this manual
1.48 anton 1617: (@pxref{Word Index}).
1.141 anton 1618: @end quotation
1.48 anton 1619:
1620: Sometimes programmers put comments at various places in colon
1621: definitions that describe the contents of the stack at that place (stack
1622: comments); i.e., they are like the first part of a stack-effect
1623: comment. E.g.,
1624:
1625: @example
1626: : cubed ( n -- n^3 )
1627: dup squared ( n n^2 ) * ;
1628: @end example
1629:
1630: In this case the stack comment is pretty superfluous, because the word
1631: is simple enough. If you think it would be a good idea to add such a
1632: comment to increase readability, you should also consider factoring the
1633: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1634: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1635: however, if you decide not to refactor it, then having such a comment is
1636: better than not having it.
1637:
1638: The names of the stack items in stack-effect and stack comments in the
1639: standard, in this manual, and in many programs specify the type through
1640: a type prefix, similar to Fortran and Hungarian notation. The most
1641: frequent prefixes are:
1642:
1643: @table @code
1644: @item n
1645: signed integer
1646: @item u
1647: unsigned integer
1648: @item c
1649: character
1650: @item f
1651: Boolean flags, i.e. @code{false} or @code{true}.
1652: @item a-addr,a-
1653: Cell-aligned address
1654: @item c-addr,c-
1655: Char-aligned address (note that a Char may have two bytes in Windows NT)
1656: @item xt
1657: Execution token, same size as Cell
1658: @item w,x
1659: Cell, can contain an integer or an address. It usually takes 32, 64 or
1660: 16 bits (depending on your platform and Forth system). A cell is more
1661: commonly known as machine word, but the term @emph{word} already means
1662: something different in Forth.
1663: @item d
1664: signed double-cell integer
1665: @item ud
1666: unsigned double-cell integer
1667: @item r
1668: Float (on the FP stack)
1669: @end table
1670:
1671: You can find a more complete list in @ref{Notation}.
1672:
1.141 anton 1673: @quotation Assignment
1.48 anton 1674: Write stack-effect comments for all definitions you have written up to
1675: now.
1.141 anton 1676: @end quotation
1.48 anton 1677:
1678:
1679: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1680: @section Types
1.66 anton 1681: @cindex types tutorial
1.48 anton 1682:
1683: In Forth the names of the operations are not overloaded; so similar
1684: operations on different types need different names; e.g., @code{+} adds
1685: integers, and you have to use @code{f+} to add floating-point numbers.
1686: The following prefixes are often used for related operations on
1687: different types:
1688:
1689: @table @code
1690: @item (none)
1691: signed integer
1692: @item u
1693: unsigned integer
1694: @item c
1695: character
1696: @item d
1697: signed double-cell integer
1698: @item ud, du
1699: unsigned double-cell integer
1700: @item 2
1701: two cells (not-necessarily double-cell numbers)
1702: @item m, um
1703: mixed single-cell and double-cell operations
1704: @item f
1705: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1706: and @samp{r} represents FP numbers).
1.48 anton 1707: @end table
1708:
1709: If there are no differences between the signed and the unsigned variant
1710: (e.g., for @code{+}), there is only the prefix-less variant.
1711:
1712: Forth does not perform type checking, neither at compile time, nor at
1713: run time. If you use the wrong oeration, the data are interpreted
1714: incorrectly:
1715:
1716: @example
1717: -1 u.
1718: @end example
1719:
1720: If you have only experience with type-checked languages until now, and
1721: have heard how important type-checking is, don't panic! In my
1722: experience (and that of other Forthers), type errors in Forth code are
1723: usually easy to find (once you get used to it), the increased vigilance
1724: of the programmer tends to catch some harder errors in addition to most
1725: type errors, and you never have to work around the type system, so in
1726: most situations the lack of type-checking seems to be a win (projects to
1727: add type checking to Forth have not caught on).
1728:
1729:
1730: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1731: @section Factoring
1.66 anton 1732: @cindex factoring tutorial
1.48 anton 1733:
1734: If you try to write longer definitions, you will soon find it hard to
1735: keep track of the stack contents. Therefore, good Forth programmers
1736: tend to write only short definitions (e.g., three lines). The art of
1737: finding meaningful short definitions is known as factoring (as in
1738: factoring polynomials).
1739:
1740: Well-factored programs offer additional advantages: smaller, more
1741: general words, are easier to test and debug and can be reused more and
1742: better than larger, specialized words.
1743:
1744: So, if you run into difficulties with stack management, when writing
1745: code, try to define meaningful factors for the word, and define the word
1746: in terms of those. Even if a factor contains only two words, it is
1747: often helpful.
1748:
1.65 anton 1749: Good factoring is not easy, and it takes some practice to get the knack
1750: for it; but even experienced Forth programmers often don't find the
1751: right solution right away, but only when rewriting the program. So, if
1752: you don't come up with a good solution immediately, keep trying, don't
1753: despair.
1.48 anton 1754:
1755: @c example !!
1756:
1757:
1758: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1759: @section Designing the stack effect
1.66 anton 1760: @cindex Stack effect design, tutorial
1761: @cindex design of stack effects, tutorial
1.48 anton 1762:
1763: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1764: function; and since there is only one result, you don't have to deal with
1.48 anton 1765: the order of results, either.
1766:
1.117 anton 1767: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1768: parameter and result order of a definition is important and should be
1769: designed well. The general guideline is to design the stack effect such
1770: that the word is simple to use in most cases, even if that complicates
1771: the implementation of the word. Some concrete rules are:
1772:
1773: @itemize @bullet
1774:
1775: @item
1776: Words consume all of their parameters (e.g., @code{.}).
1777:
1778: @item
1779: If there is a convention on the order of parameters (e.g., from
1780: mathematics or another programming language), stick with it (e.g.,
1781: @code{-}).
1782:
1783: @item
1784: If one parameter usually requires only a short computation (e.g., it is
1785: a constant), pass it on the top of the stack. Conversely, parameters
1786: that usually require a long sequence of code to compute should be passed
1787: as the bottom (i.e., first) parameter. This makes the code easier to
1788: read, because reader does not need to keep track of the bottom item
1789: through a long sequence of code (or, alternatively, through stack
1.49 anton 1790: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1791: address on top of the stack because it is usually simpler to compute
1792: than the stored value (often the address is just a variable).
1793:
1794: @item
1795: Similarly, results that are usually consumed quickly should be returned
1796: on the top of stack, whereas a result that is often used in long
1797: computations should be passed as bottom result. E.g., the file words
1798: like @code{open-file} return the error code on the top of stack, because
1799: it is usually consumed quickly by @code{throw}; moreover, the error code
1800: has to be checked before doing anything with the other results.
1801:
1802: @end itemize
1803:
1804: These rules are just general guidelines, don't lose sight of the overall
1805: goal to make the words easy to use. E.g., if the convention rule
1806: conflicts with the computation-length rule, you might decide in favour
1807: of the convention if the word will be used rarely, and in favour of the
1808: computation-length rule if the word will be used frequently (because
1809: with frequent use the cost of breaking the computation-length rule would
1810: be quite high, and frequent use makes it easier to remember an
1811: unconventional order).
1812:
1813: @c example !! structure package
1814:
1.65 anton 1815:
1.48 anton 1816: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1817: @section Local Variables
1.66 anton 1818: @cindex local variables, tutorial
1.48 anton 1819:
1820: You can define local variables (@emph{locals}) in a colon definition:
1821:
1822: @example
1823: : swap @{ a b -- b a @}
1824: b a ;
1825: 1 2 swap .s 2drop
1826: @end example
1827:
1828: (If your Forth system does not support this syntax, include
1829: @file{compat/anslocals.fs} first).
1830:
1831: In this example @code{@{ a b -- b a @}} is the locals definition; it
1832: takes two cells from the stack, puts the top of stack in @code{b} and
1833: the next stack element in @code{a}. @code{--} starts a comment ending
1834: with @code{@}}. After the locals definition, using the name of the
1835: local will push its value on the stack. You can leave the comment
1836: part (@code{-- b a}) away:
1837:
1838: @example
1839: : swap ( x1 x2 -- x2 x1 )
1840: @{ a b @} b a ;
1841: @end example
1842:
1843: In Gforth you can have several locals definitions, anywhere in a colon
1844: definition; in contrast, in a standard program you can have only one
1845: locals definition per colon definition, and that locals definition must
1846: be outside any controll structure.
1847:
1848: With locals you can write slightly longer definitions without running
1849: into stack trouble. However, I recommend trying to write colon
1850: definitions without locals for exercise purposes to help you gain the
1851: essential factoring skills.
1852:
1.141 anton 1853: @quotation Assignment
1.48 anton 1854: Rewrite your definitions until now with locals
1.141 anton 1855: @end quotation
1.48 anton 1856:
1.66 anton 1857: Reference: @ref{Locals}.
1858:
1.48 anton 1859:
1860: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1861: @section Conditional execution
1.66 anton 1862: @cindex conditionals, tutorial
1863: @cindex if, tutorial
1.48 anton 1864:
1865: In Forth you can use control structures only inside colon definitions.
1866: An @code{if}-structure looks like this:
1867:
1868: @example
1869: : abs ( n1 -- +n2 )
1870: dup 0 < if
1871: negate
1872: endif ;
1873: 5 abs .
1874: -5 abs .
1875: @end example
1876:
1877: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1878: the following code is performed, otherwise execution continues after the
1.51 pazsan 1879: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.48 anton 1880: elements and prioduces a flag:
1881:
1882: @example
1883: 1 2 < .
1884: 2 1 < .
1885: 1 1 < .
1886: @end example
1887:
1888: Actually the standard name for @code{endif} is @code{then}. This
1889: tutorial presents the examples using @code{endif}, because this is often
1890: less confusing for people familiar with other programming languages
1891: where @code{then} has a different meaning. If your system does not have
1892: @code{endif}, define it with
1893:
1894: @example
1895: : endif postpone then ; immediate
1896: @end example
1897:
1898: You can optionally use an @code{else}-part:
1899:
1900: @example
1901: : min ( n1 n2 -- n )
1902: 2dup < if
1903: drop
1904: else
1905: nip
1906: endif ;
1907: 2 3 min .
1908: 3 2 min .
1909: @end example
1910:
1.141 anton 1911: @quotation Assignment
1.48 anton 1912: Write @code{min} without @code{else}-part (hint: what's the definition
1913: of @code{nip}?).
1.141 anton 1914: @end quotation
1.48 anton 1915:
1.66 anton 1916: Reference: @ref{Selection}.
1917:
1.48 anton 1918:
1919: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1920: @section Flags and Comparisons
1.66 anton 1921: @cindex flags tutorial
1922: @cindex comparison tutorial
1.48 anton 1923:
1924: In a false-flag all bits are clear (0 when interpreted as integer). In
1925: a canonical true-flag all bits are set (-1 as a twos-complement signed
1926: integer); in many contexts (e.g., @code{if}) any non-zero value is
1927: treated as true flag.
1928:
1929: @example
1930: false .
1931: true .
1932: true hex u. decimal
1933: @end example
1934:
1935: Comparison words produce canonical flags:
1936:
1937: @example
1938: 1 1 = .
1939: 1 0= .
1940: 0 1 < .
1941: 0 0 < .
1942: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1943: -1 1 < .
1944: @end example
1945:
1.66 anton 1946: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1947: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1948: these combinations are standard (for details see the standard,
1949: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1950:
1951: You can use @code{and or xor invert} can be used as operations on
1952: canonical flags. Actually they are bitwise operations:
1953:
1954: @example
1955: 1 2 and .
1956: 1 2 or .
1957: 1 3 xor .
1958: 1 invert .
1959: @end example
1960:
1961: You can convert a zero/non-zero flag into a canonical flag with
1962: @code{0<>} (and complement it on the way with @code{0=}).
1963:
1964: @example
1965: 1 0= .
1966: 1 0<> .
1967: @end example
1968:
1.65 anton 1969: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1970: operation of the Boolean operations to avoid @code{if}s:
1971:
1972: @example
1973: : foo ( n1 -- n2 )
1974: 0= if
1975: 14
1976: else
1977: 0
1978: endif ;
1979: 0 foo .
1980: 1 foo .
1981:
1982: : foo ( n1 -- n2 )
1983: 0= 14 and ;
1984: 0 foo .
1985: 1 foo .
1986: @end example
1987:
1.141 anton 1988: @quotation Assignment
1.48 anton 1989: Write @code{min} without @code{if}.
1.141 anton 1990: @end quotation
1.48 anton 1991:
1.66 anton 1992: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
1993: @ref{Bitwise operations}.
1994:
1.48 anton 1995:
1996: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
1997: @section General Loops
1.66 anton 1998: @cindex loops, indefinite, tutorial
1.48 anton 1999:
2000: The endless loop is the most simple one:
2001:
2002: @example
2003: : endless ( -- )
2004: 0 begin
2005: dup . 1+
2006: again ;
2007: endless
2008: @end example
2009:
2010: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2011: does nothing at run-time, @code{again} jumps back to @code{begin}.
2012:
2013: A loop with one exit at any place looks like this:
2014:
2015: @example
2016: : log2 ( +n1 -- n2 )
2017: \ logarithmus dualis of n1>0, rounded down to the next integer
2018: assert( dup 0> )
2019: 2/ 0 begin
2020: over 0> while
2021: 1+ swap 2/ swap
2022: repeat
2023: nip ;
2024: 7 log2 .
2025: 8 log2 .
2026: @end example
2027:
2028: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2029: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2030: continues behind the @code{while}. @code{Repeat} jumps back to
2031: @code{begin}, just like @code{again}.
2032:
2033: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2034: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2035: one bit (arithmetic shift right):
2036:
2037: @example
2038: -5 2 / .
2039: -5 2/ .
2040: @end example
2041:
2042: @code{assert(} is no standard word, but you can get it on systems other
2043: then Gforth by including @file{compat/assert.fs}. You can see what it
2044: does by trying
2045:
2046: @example
2047: 0 log2 .
2048: @end example
2049:
2050: Here's a loop with an exit at the end:
2051:
2052: @example
2053: : log2 ( +n1 -- n2 )
2054: \ logarithmus dualis of n1>0, rounded down to the next integer
2055: assert( dup 0 > )
2056: -1 begin
2057: 1+ swap 2/ swap
2058: over 0 <=
2059: until
2060: nip ;
2061: @end example
2062:
2063: @code{Until} consumes a flag; if it is non-zero, execution continues at
2064: the @code{begin}, otherwise after the @code{until}.
2065:
1.141 anton 2066: @quotation Assignment
1.48 anton 2067: Write a definition for computing the greatest common divisor.
1.141 anton 2068: @end quotation
1.48 anton 2069:
1.66 anton 2070: Reference: @ref{Simple Loops}.
2071:
1.48 anton 2072:
2073: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2074: @section Counted loops
1.66 anton 2075: @cindex loops, counted, tutorial
1.48 anton 2076:
2077: @example
2078: : ^ ( n1 u -- n )
2079: \ n = the uth power of u1
2080: 1 swap 0 u+do
2081: over *
2082: loop
2083: nip ;
2084: 3 2 ^ .
2085: 4 3 ^ .
2086: @end example
2087:
2088: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2089: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2090: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2091: times (or not at all, if @code{u3-u4<0}).
2092:
2093: You can see the stack effect design rules at work in the stack effect of
2094: the loop start words: Since the start value of the loop is more
2095: frequently constant than the end value, the start value is passed on
2096: the top-of-stack.
2097:
2098: You can access the counter of a counted loop with @code{i}:
2099:
2100: @example
2101: : fac ( u -- u! )
2102: 1 swap 1+ 1 u+do
2103: i *
2104: loop ;
2105: 5 fac .
2106: 7 fac .
2107: @end example
2108:
2109: There is also @code{+do}, which expects signed numbers (important for
2110: deciding whether to enter the loop).
2111:
1.141 anton 2112: @quotation Assignment
1.48 anton 2113: Write a definition for computing the nth Fibonacci number.
1.141 anton 2114: @end quotation
1.48 anton 2115:
1.65 anton 2116: You can also use increments other than 1:
2117:
2118: @example
2119: : up2 ( n1 n2 -- )
2120: +do
2121: i .
2122: 2 +loop ;
2123: 10 0 up2
2124:
2125: : down2 ( n1 n2 -- )
2126: -do
2127: i .
2128: 2 -loop ;
2129: 0 10 down2
2130: @end example
1.48 anton 2131:
1.66 anton 2132: Reference: @ref{Counted Loops}.
2133:
1.48 anton 2134:
2135: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2136: @section Recursion
1.66 anton 2137: @cindex recursion tutorial
1.48 anton 2138:
2139: Usually the name of a definition is not visible in the definition; but
2140: earlier definitions are usually visible:
2141:
2142: @example
2143: 1 0 / . \ "Floating-point unidentified fault" in Gforth on most platforms
2144: : / ( n1 n2 -- n )
2145: dup 0= if
2146: -10 throw \ report division by zero
2147: endif
2148: / \ old version
2149: ;
2150: 1 0 /
2151: @end example
2152:
2153: For recursive definitions you can use @code{recursive} (non-standard) or
2154: @code{recurse}:
2155:
2156: @example
2157: : fac1 ( n -- n! ) recursive
2158: dup 0> if
2159: dup 1- fac1 *
2160: else
2161: drop 1
2162: endif ;
2163: 7 fac1 .
2164:
2165: : fac2 ( n -- n! )
2166: dup 0> if
2167: dup 1- recurse *
2168: else
2169: drop 1
2170: endif ;
2171: 8 fac2 .
2172: @end example
2173:
1.141 anton 2174: @quotation Assignment
1.48 anton 2175: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2176: @end quotation
1.48 anton 2177:
1.66 anton 2178: Reference (including indirect recursion): @xref{Calls and returns}.
2179:
1.48 anton 2180:
2181: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2182: @section Leaving definitions or loops
1.66 anton 2183: @cindex leaving definitions, tutorial
2184: @cindex leaving loops, tutorial
1.48 anton 2185:
2186: @code{EXIT} exits the current definition right away. For every counted
2187: loop that is left in this way, an @code{UNLOOP} has to be performed
2188: before the @code{EXIT}:
2189:
2190: @c !! real examples
2191: @example
2192: : ...
2193: ... u+do
2194: ... if
2195: ... unloop exit
2196: endif
2197: ...
2198: loop
2199: ... ;
2200: @end example
2201:
2202: @code{LEAVE} leaves the innermost counted loop right away:
2203:
2204: @example
2205: : ...
2206: ... u+do
2207: ... if
2208: ... leave
2209: endif
2210: ...
2211: loop
2212: ... ;
2213: @end example
2214:
1.65 anton 2215: @c !! example
1.48 anton 2216:
1.66 anton 2217: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2218:
2219:
1.48 anton 2220: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2221: @section Return Stack
1.66 anton 2222: @cindex return stack tutorial
1.48 anton 2223:
2224: In addition to the data stack Forth also has a second stack, the return
2225: stack; most Forth systems store the return addresses of procedure calls
2226: there (thus its name). Programmers can also use this stack:
2227:
2228: @example
2229: : foo ( n1 n2 -- )
2230: .s
2231: >r .s
1.50 anton 2232: r@@ .
1.48 anton 2233: >r .s
1.50 anton 2234: r@@ .
1.48 anton 2235: r> .
1.50 anton 2236: r@@ .
1.48 anton 2237: r> . ;
2238: 1 2 foo
2239: @end example
2240:
2241: @code{>r} takes an element from the data stack and pushes it onto the
2242: return stack; conversely, @code{r>} moves an elementm from the return to
2243: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2244: on the data stack.
1.48 anton 2245:
2246: Forth programmers usually use the return stack for storing data
2247: temporarily, if using the data stack alone would be too complex, and
2248: factoring and locals are not an option:
2249:
2250: @example
2251: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2252: rot >r rot r> ;
2253: @end example
2254:
2255: The return address of the definition and the loop control parameters of
2256: counted loops usually reside on the return stack, so you have to take
2257: all items, that you have pushed on the return stack in a colon
2258: definition or counted loop, from the return stack before the definition
2259: or loop ends. You cannot access items that you pushed on the return
2260: stack outside some definition or loop within the definition of loop.
2261:
2262: If you miscount the return stack items, this usually ends in a crash:
2263:
2264: @example
2265: : crash ( n -- )
2266: >r ;
2267: 5 crash
2268: @end example
2269:
2270: You cannot mix using locals and using the return stack (according to the
2271: standard; Gforth has no problem). However, they solve the same
2272: problems, so this shouldn't be an issue.
2273:
1.141 anton 2274: @quotation Assignment
1.48 anton 2275: Can you rewrite any of the definitions you wrote until now in a better
2276: way using the return stack?
1.141 anton 2277: @end quotation
1.48 anton 2278:
1.66 anton 2279: Reference: @ref{Return stack}.
2280:
1.48 anton 2281:
2282: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2283: @section Memory
1.66 anton 2284: @cindex memory access/allocation tutorial
1.48 anton 2285:
2286: You can create a global variable @code{v} with
2287:
2288: @example
2289: variable v ( -- addr )
2290: @end example
2291:
2292: @code{v} pushes the address of a cell in memory on the stack. This cell
2293: was reserved by @code{variable}. You can use @code{!} (store) to store
2294: values into this cell and @code{@@} (fetch) to load the value from the
2295: stack into memory:
2296:
2297: @example
2298: v .
2299: 5 v ! .s
1.50 anton 2300: v @@ .
1.48 anton 2301: @end example
2302:
1.65 anton 2303: You can see a raw dump of memory with @code{dump}:
2304:
2305: @example
2306: v 1 cells .s dump
2307: @end example
2308:
2309: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2310: generally, address units (aus)) that @code{n1 cells} occupy. You can
2311: also reserve more memory:
1.48 anton 2312:
2313: @example
2314: create v2 20 cells allot
1.65 anton 2315: v2 20 cells dump
1.48 anton 2316: @end example
2317:
1.65 anton 2318: creates a word @code{v2} and reserves 20 uninitialized cells; the
2319: address pushed by @code{v2} points to the start of these 20 cells. You
2320: can use address arithmetic to access these cells:
1.48 anton 2321:
2322: @example
2323: 3 v2 5 cells + !
1.65 anton 2324: v2 20 cells dump
1.48 anton 2325: @end example
2326:
2327: You can reserve and initialize memory with @code{,}:
2328:
2329: @example
2330: create v3
2331: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2332: v3 @@ .
2333: v3 cell+ @@ .
2334: v3 2 cells + @@ .
1.65 anton 2335: v3 5 cells dump
1.48 anton 2336: @end example
2337:
1.141 anton 2338: @quotation Assignment
1.48 anton 2339: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2340: @code{u} cells, with the first of these cells at @code{addr}, the next
2341: one at @code{addr cell+} etc.
1.141 anton 2342: @end quotation
1.48 anton 2343:
2344: You can also reserve memory without creating a new word:
2345:
2346: @example
1.60 anton 2347: here 10 cells allot .
2348: here .
1.48 anton 2349: @end example
2350:
2351: @code{Here} pushes the start address of the memory area. You should
2352: store it somewhere, or you will have a hard time finding the memory area
2353: again.
2354:
2355: @code{Allot} manages dictionary memory. The dictionary memory contains
2356: the system's data structures for words etc. on Gforth and most other
2357: Forth systems. It is managed like a stack: You can free the memory that
2358: you have just @code{allot}ed with
2359:
2360: @example
2361: -10 cells allot
1.60 anton 2362: here .
1.48 anton 2363: @end example
2364:
2365: Note that you cannot do this if you have created a new word in the
2366: meantime (because then your @code{allot}ed memory is no longer on the
2367: top of the dictionary ``stack'').
2368:
2369: Alternatively, you can use @code{allocate} and @code{free} which allow
2370: freeing memory in any order:
2371:
2372: @example
2373: 10 cells allocate throw .s
2374: 20 cells allocate throw .s
2375: swap
2376: free throw
2377: free throw
2378: @end example
2379:
2380: The @code{throw}s deal with errors (e.g., out of memory).
2381:
1.65 anton 2382: And there is also a
2383: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2384: garbage collector}, which eliminates the need to @code{free} memory
2385: explicitly.
1.48 anton 2386:
1.66 anton 2387: Reference: @ref{Memory}.
2388:
1.48 anton 2389:
2390: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2391: @section Characters and Strings
1.66 anton 2392: @cindex strings tutorial
2393: @cindex characters tutorial
1.48 anton 2394:
2395: On the stack characters take up a cell, like numbers. In memory they
2396: have their own size (one 8-bit byte on most systems), and therefore
2397: require their own words for memory access:
2398:
2399: @example
2400: create v4
2401: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2402: v4 4 chars + c@@ .
1.65 anton 2403: v4 5 chars dump
1.48 anton 2404: @end example
2405:
2406: The preferred representation of strings on the stack is @code{addr
2407: u-count}, where @code{addr} is the address of the first character and
2408: @code{u-count} is the number of characters in the string.
2409:
2410: @example
2411: v4 5 type
2412: @end example
2413:
2414: You get a string constant with
2415:
2416: @example
2417: s" hello, world" .s
2418: type
2419: @end example
2420:
2421: Make sure you have a space between @code{s"} and the string; @code{s"}
2422: is a normal Forth word and must be delimited with white space (try what
2423: happens when you remove the space).
2424:
2425: However, this interpretive use of @code{s"} is quite restricted: the
2426: string exists only until the next call of @code{s"} (some Forth systems
2427: keep more than one of these strings, but usually they still have a
1.62 crook 2428: limited lifetime).
1.48 anton 2429:
2430: @example
2431: s" hello," s" world" .s
2432: type
2433: type
2434: @end example
2435:
1.62 crook 2436: You can also use @code{s"} in a definition, and the resulting
2437: strings then live forever (well, for as long as the definition):
1.48 anton 2438:
2439: @example
2440: : foo s" hello," s" world" ;
2441: foo .s
2442: type
2443: type
2444: @end example
2445:
1.141 anton 2446: @quotation Assignment
1.48 anton 2447: @code{Emit ( c -- )} types @code{c} as character (not a number).
2448: Implement @code{type ( addr u -- )}.
1.141 anton 2449: @end quotation
1.48 anton 2450:
1.66 anton 2451: Reference: @ref{Memory Blocks}.
2452:
2453:
1.84 pazsan 2454: @node Alignment Tutorial, Files Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2455: @section Alignment
1.66 anton 2456: @cindex alignment tutorial
2457: @cindex memory alignment tutorial
1.48 anton 2458:
2459: On many processors cells have to be aligned in memory, if you want to
2460: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2461: not require alignment, access to aligned cells is faster).
1.48 anton 2462:
2463: @code{Create} aligns @code{here} (i.e., the place where the next
2464: allocation will occur, and that the @code{create}d word points to).
2465: Likewise, the memory produced by @code{allocate} starts at an aligned
2466: address. Adding a number of @code{cells} to an aligned address produces
2467: another aligned address.
2468:
2469: However, address arithmetic involving @code{char+} and @code{chars} can
2470: create an address that is not cell-aligned. @code{Aligned ( addr --
2471: a-addr )} produces the next aligned address:
2472:
2473: @example
1.50 anton 2474: v3 char+ aligned .s @@ .
2475: v3 char+ .s @@ .
1.48 anton 2476: @end example
2477:
2478: Similarly, @code{align} advances @code{here} to the next aligned
2479: address:
2480:
2481: @example
2482: create v5 97 c,
2483: here .
2484: align here .
2485: 1000 ,
2486: @end example
2487:
2488: Note that you should use aligned addresses even if your processor does
2489: not require them, if you want your program to be portable.
2490:
1.66 anton 2491: Reference: @ref{Address arithmetic}.
2492:
1.48 anton 2493:
1.84 pazsan 2494: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Alignment Tutorial, Tutorial
2495: @section Files
2496: @cindex files tutorial
2497:
2498: This section gives a short introduction into how to use files inside
2499: Forth. It's broken up into five easy steps:
2500:
2501: @enumerate 1
2502: @item Opened an ASCII text file for input
2503: @item Opened a file for output
2504: @item Read input file until string matched (or some other condition matched)
2505: @item Wrote some lines from input ( modified or not) to output
2506: @item Closed the files.
2507: @end enumerate
2508:
1.153 anton 2509: Reference: @ref{General files}.
2510:
1.84 pazsan 2511: @subsection Open file for input
2512:
2513: @example
2514: s" foo.in" r/o open-file throw Value fd-in
2515: @end example
2516:
2517: @subsection Create file for output
2518:
2519: @example
2520: s" foo.out" w/o create-file throw Value fd-out
2521: @end example
2522:
2523: The available file modes are r/o for read-only access, r/w for
2524: read-write access, and w/o for write-only access. You could open both
2525: files with r/w, too, if you like. All file words return error codes; for
2526: most applications, it's best to pass there error codes with @code{throw}
2527: to the outer error handler.
2528:
2529: If you want words for opening and assigning, define them as follows:
2530:
2531: @example
2532: 0 Value fd-in
2533: 0 Value fd-out
2534: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2535: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2536: @end example
2537:
2538: Usage example:
2539:
2540: @example
2541: s" foo.in" open-input
2542: s" foo.out" open-output
2543: @end example
2544:
2545: @subsection Scan file for a particular line
2546:
2547: @example
2548: 256 Constant max-line
2549: Create line-buffer max-line 2 + allot
2550:
2551: : scan-file ( addr u -- )
2552: begin
2553: line-buffer max-line fd-in read-line throw
2554: while
2555: >r 2dup line-buffer r> compare 0=
2556: until
2557: else
2558: drop
2559: then
2560: 2drop ;
2561: @end example
2562:
2563: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2564: the buffer at addr, and returns the number of bytes read, a flag that is
2565: false when the end of file is reached, and an error code.
1.84 pazsan 2566:
2567: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2568: returns zero if both strings are equal. It returns a positive number if
2569: the first string is lexically greater, a negative if the second string
2570: is lexically greater.
2571:
2572: We haven't seen this loop here; it has two exits. Since the @code{while}
2573: exits with the number of bytes read on the stack, we have to clean up
2574: that separately; that's after the @code{else}.
2575:
2576: Usage example:
2577:
2578: @example
2579: s" The text I search is here" scan-file
2580: @end example
2581:
2582: @subsection Copy input to output
2583:
2584: @example
2585: : copy-file ( -- )
2586: begin
2587: line-buffer max-line fd-in read-line throw
2588: while
2589: line-buffer swap fd-out write-file throw
2590: repeat ;
2591: @end example
2592:
2593: @subsection Close files
2594:
2595: @example
2596: fd-in close-file throw
2597: fd-out close-file throw
2598: @end example
2599:
2600: Likewise, you can put that into definitions, too:
2601:
2602: @example
2603: : close-input ( -- ) fd-in close-file throw ;
2604: : close-output ( -- ) fd-out close-file throw ;
2605: @end example
2606:
1.141 anton 2607: @quotation Assignment
1.84 pazsan 2608: How could you modify @code{copy-file} so that it copies until a second line is
2609: matched? Can you write a program that extracts a section of a text file,
2610: given the line that starts and the line that terminates that section?
1.141 anton 2611: @end quotation
1.84 pazsan 2612:
2613: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2614: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2615: @cindex semantics tutorial
2616: @cindex interpretation semantics tutorial
2617: @cindex compilation semantics tutorial
2618: @cindex immediate, tutorial
1.48 anton 2619:
2620: When a word is compiled, it behaves differently from being interpreted.
2621: E.g., consider @code{+}:
2622:
2623: @example
2624: 1 2 + .
2625: : foo + ;
2626: @end example
2627:
2628: These two behaviours are known as compilation and interpretation
2629: semantics. For normal words (e.g., @code{+}), the compilation semantics
2630: is to append the interpretation semantics to the currently defined word
2631: (@code{foo} in the example above). I.e., when @code{foo} is executed
2632: later, the interpretation semantics of @code{+} (i.e., adding two
2633: numbers) will be performed.
2634:
2635: However, there are words with non-default compilation semantics, e.g.,
2636: the control-flow words like @code{if}. You can use @code{immediate} to
2637: change the compilation semantics of the last defined word to be equal to
2638: the interpretation semantics:
2639:
2640: @example
2641: : [FOO] ( -- )
2642: 5 . ; immediate
2643:
2644: [FOO]
2645: : bar ( -- )
2646: [FOO] ;
2647: bar
2648: see bar
2649: @end example
2650:
2651: Two conventions to mark words with non-default compilation semnatics are
2652: names with brackets (more frequently used) and to write them all in
2653: upper case (less frequently used).
2654:
2655: In Gforth (and many other systems) you can also remove the
2656: interpretation semantics with @code{compile-only} (the compilation
2657: semantics is derived from the original interpretation semantics):
2658:
2659: @example
2660: : flip ( -- )
2661: 6 . ; compile-only \ but not immediate
2662: flip
2663:
2664: : flop ( -- )
2665: flip ;
2666: flop
2667: @end example
2668:
2669: In this example the interpretation semantics of @code{flop} is equal to
2670: the original interpretation semantics of @code{flip}.
2671:
2672: The text interpreter has two states: in interpret state, it performs the
2673: interpretation semantics of words it encounters; in compile state, it
2674: performs the compilation semantics of these words.
2675:
2676: Among other things, @code{:} switches into compile state, and @code{;}
2677: switches back to interpret state. They contain the factors @code{]}
2678: (switch to compile state) and @code{[} (switch to interpret state), that
2679: do nothing but switch the state.
2680:
2681: @example
2682: : xxx ( -- )
2683: [ 5 . ]
2684: ;
2685:
2686: xxx
2687: see xxx
2688: @end example
2689:
2690: These brackets are also the source of the naming convention mentioned
2691: above.
2692:
1.66 anton 2693: Reference: @ref{Interpretation and Compilation Semantics}.
2694:
1.48 anton 2695:
2696: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2697: @section Execution Tokens
1.66 anton 2698: @cindex execution tokens tutorial
2699: @cindex XT tutorial
1.48 anton 2700:
2701: @code{' word} gives you the execution token (XT) of a word. The XT is a
2702: cell representing the interpretation semantics of a word. You can
2703: execute this semantics with @code{execute}:
2704:
2705: @example
2706: ' + .s
2707: 1 2 rot execute .
2708: @end example
2709:
2710: The XT is similar to a function pointer in C. However, parameter
2711: passing through the stack makes it a little more flexible:
2712:
2713: @example
2714: : map-array ( ... addr u xt -- ... )
1.50 anton 2715: \ executes xt ( ... x -- ... ) for every element of the array starting
2716: \ at addr and containing u elements
1.48 anton 2717: @{ xt @}
2718: cells over + swap ?do
1.50 anton 2719: i @@ xt execute
1.48 anton 2720: 1 cells +loop ;
2721:
2722: create a 3 , 4 , 2 , -1 , 4 ,
2723: a 5 ' . map-array .s
2724: 0 a 5 ' + map-array .
2725: s" max-n" environment? drop .s
2726: a 5 ' min map-array .
2727: @end example
2728:
2729: You can use map-array with the XTs of words that consume one element
2730: more than they produce. In theory you can also use it with other XTs,
2731: but the stack effect then depends on the size of the array, which is
2732: hard to understand.
2733:
1.51 pazsan 2734: Since XTs are cell-sized, you can store them in memory and manipulate
2735: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2736: word with @code{compile,}:
2737:
2738: @example
2739: : foo1 ( n1 n2 -- n )
2740: [ ' + compile, ] ;
2741: see foo
2742: @end example
2743:
2744: This is non-standard, because @code{compile,} has no compilation
2745: semantics in the standard, but it works in good Forth systems. For the
2746: broken ones, use
2747:
2748: @example
2749: : [compile,] compile, ; immediate
2750:
2751: : foo1 ( n1 n2 -- n )
2752: [ ' + ] [compile,] ;
2753: see foo
2754: @end example
2755:
2756: @code{'} is a word with default compilation semantics; it parses the
2757: next word when its interpretation semantics are executed, not during
2758: compilation:
2759:
2760: @example
2761: : foo ( -- xt )
2762: ' ;
2763: see foo
2764: : bar ( ... "word" -- ... )
2765: ' execute ;
2766: see bar
1.60 anton 2767: 1 2 bar + .
1.48 anton 2768: @end example
2769:
2770: You often want to parse a word during compilation and compile its XT so
2771: it will be pushed on the stack at run-time. @code{[']} does this:
2772:
2773: @example
2774: : xt-+ ( -- xt )
2775: ['] + ;
2776: see xt-+
2777: 1 2 xt-+ execute .
2778: @end example
2779:
2780: Many programmers tend to see @code{'} and the word it parses as one
2781: unit, and expect it to behave like @code{[']} when compiled, and are
2782: confused by the actual behaviour. If you are, just remember that the
2783: Forth system just takes @code{'} as one unit and has no idea that it is
2784: a parsing word (attempts to convenience programmers in this issue have
2785: usually resulted in even worse pitfalls, see
1.66 anton 2786: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2787: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2788:
2789: Note that the state of the interpreter does not come into play when
1.51 pazsan 2790: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2791: compile state, it still gives you the interpretation semantics. And
2792: whatever that state is, @code{execute} performs the semantics
1.66 anton 2793: represented by the XT (i.e., for XTs produced with @code{'} the
2794: interpretation semantics).
2795:
2796: Reference: @ref{Tokens for Words}.
1.48 anton 2797:
2798:
2799: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2800: @section Exceptions
1.66 anton 2801: @cindex exceptions tutorial
1.48 anton 2802:
2803: @code{throw ( n -- )} causes an exception unless n is zero.
2804:
2805: @example
2806: 100 throw .s
2807: 0 throw .s
2808: @end example
2809:
2810: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2811: it catches exceptions and pushes the number of the exception on the
2812: stack (or 0, if the xt executed without exception). If there was an
2813: exception, the stacks have the same depth as when entering @code{catch}:
2814:
2815: @example
2816: .s
2817: 3 0 ' / catch .s
2818: 3 2 ' / catch .s
2819: @end example
2820:
1.141 anton 2821: @quotation Assignment
1.48 anton 2822: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2823: @end quotation
1.48 anton 2824:
2825: @code{Throw} always jumps to the dynamically next enclosing
2826: @code{catch}, even if it has to leave several call levels to achieve
2827: this:
2828:
2829: @example
2830: : foo 100 throw ;
2831: : foo1 foo ." after foo" ;
1.51 pazsan 2832: : bar ['] foo1 catch ;
1.60 anton 2833: bar .
1.48 anton 2834: @end example
2835:
2836: It is often important to restore a value upon leaving a definition, even
2837: if the definition is left through an exception. You can ensure this
2838: like this:
2839:
2840: @example
2841: : ...
2842: save-x
1.51 pazsan 2843: ['] word-changing-x catch ( ... n )
1.48 anton 2844: restore-x
2845: ( ... n ) throw ;
2846: @end example
2847:
1.55 anton 2848: Gforth provides an alternative syntax in addition to @code{catch}:
1.48 anton 2849: @code{try ... recover ... endtry}. If the code between @code{try} and
2850: @code{recover} has an exception, the stack depths are restored, the
2851: exception number is pushed on the stack, and the code between
2852: @code{recover} and @code{endtry} is performed. E.g., the definition for
2853: @code{catch} is
2854:
2855: @example
2856: : catch ( x1 .. xn xt -- y1 .. ym 0 / z1 .. zn error ) \ exception
2857: try
2858: execute 0
2859: recover
2860: nip
2861: endtry ;
2862: @end example
2863:
2864: The equivalent to the restoration code above is
2865:
2866: @example
2867: : ...
2868: save-x
2869: try
1.92 anton 2870: word-changing-x 0
2871: recover endtry
1.48 anton 2872: restore-x
2873: throw ;
2874: @end example
2875:
1.92 anton 2876: This works if @code{word-changing-x} does not change the stack depth,
2877: otherwise you should add some code between @code{recover} and
2878: @code{endtry} to balance the stack.
1.48 anton 2879:
1.66 anton 2880: Reference: @ref{Exception Handling}.
2881:
1.48 anton 2882:
2883: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2884: @section Defining Words
1.66 anton 2885: @cindex defining words tutorial
2886: @cindex does> tutorial
2887: @cindex create...does> tutorial
2888:
2889: @c before semantics?
1.48 anton 2890:
2891: @code{:}, @code{create}, and @code{variable} are definition words: They
2892: define other words. @code{Constant} is another definition word:
2893:
2894: @example
2895: 5 constant foo
2896: foo .
2897: @end example
2898:
2899: You can also use the prefixes @code{2} (double-cell) and @code{f}
2900: (floating point) with @code{variable} and @code{constant}.
2901:
2902: You can also define your own defining words. E.g.:
2903:
2904: @example
2905: : variable ( "name" -- )
2906: create 0 , ;
2907: @end example
2908:
2909: You can also define defining words that create words that do something
2910: other than just producing their address:
2911:
2912: @example
2913: : constant ( n "name" -- )
2914: create ,
2915: does> ( -- n )
1.50 anton 2916: ( addr ) @@ ;
1.48 anton 2917:
2918: 5 constant foo
2919: foo .
2920: @end example
2921:
2922: The definition of @code{constant} above ends at the @code{does>}; i.e.,
2923: @code{does>} replaces @code{;}, but it also does something else: It
2924: changes the last defined word such that it pushes the address of the
2925: body of the word and then performs the code after the @code{does>}
2926: whenever it is called.
2927:
2928: In the example above, @code{constant} uses @code{,} to store 5 into the
2929: body of @code{foo}. When @code{foo} executes, it pushes the address of
2930: the body onto the stack, then (in the code after the @code{does>})
2931: fetches the 5 from there.
2932:
2933: The stack comment near the @code{does>} reflects the stack effect of the
2934: defined word, not the stack effect of the code after the @code{does>}
2935: (the difference is that the code expects the address of the body that
2936: the stack comment does not show).
2937:
2938: You can use these definition words to do factoring in cases that involve
2939: (other) definition words. E.g., a field offset is always added to an
2940: address. Instead of defining
2941:
2942: @example
2943: 2 cells constant offset-field1
2944: @end example
2945:
2946: and using this like
2947:
2948: @example
2949: ( addr ) offset-field1 +
2950: @end example
2951:
2952: you can define a definition word
2953:
2954: @example
2955: : simple-field ( n "name" -- )
2956: create ,
2957: does> ( n1 -- n1+n )
1.50 anton 2958: ( addr ) @@ + ;
1.48 anton 2959: @end example
1.21 crook 2960:
1.48 anton 2961: Definition and use of field offsets now look like this:
1.21 crook 2962:
1.48 anton 2963: @example
2964: 2 cells simple-field field1
1.60 anton 2965: create mystruct 4 cells allot
2966: mystruct .s field1 .s drop
1.48 anton 2967: @end example
1.21 crook 2968:
1.48 anton 2969: If you want to do something with the word without performing the code
2970: after the @code{does>}, you can access the body of a @code{create}d word
2971: with @code{>body ( xt -- addr )}:
1.21 crook 2972:
1.48 anton 2973: @example
2974: : value ( n "name" -- )
2975: create ,
2976: does> ( -- n1 )
1.50 anton 2977: @@ ;
1.48 anton 2978: : to ( n "name" -- )
2979: ' >body ! ;
1.21 crook 2980:
1.48 anton 2981: 5 value foo
2982: foo .
2983: 7 to foo
2984: foo .
2985: @end example
1.21 crook 2986:
1.141 anton 2987: @quotation Assignment
1.48 anton 2988: Define @code{defer ( "name" -- )}, which creates a word that stores an
2989: XT (at the start the XT of @code{abort}), and upon execution
2990: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
2991: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
2992: recursion is one application of @code{defer}.
1.141 anton 2993: @end quotation
1.29 crook 2994:
1.66 anton 2995: Reference: @ref{User-defined Defining Words}.
2996:
2997:
1.48 anton 2998: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
2999: @section Arrays and Records
1.66 anton 3000: @cindex arrays tutorial
3001: @cindex records tutorial
3002: @cindex structs tutorial
1.29 crook 3003:
1.48 anton 3004: Forth has no standard words for defining data structures such as arrays
3005: and records (structs in C terminology), but you can build them yourself
3006: based on address arithmetic. You can also define words for defining
3007: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3008:
1.48 anton 3009: One of the first projects a Forth newcomer sets out upon when learning
3010: about defining words is an array defining word (possibly for
3011: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3012: learn something from it. However, don't be disappointed when you later
3013: learn that you have little use for these words (inappropriate use would
3014: be even worse). I have not yet found a set of useful array words yet;
3015: the needs are just too diverse, and named, global arrays (the result of
3016: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3017: consider how to pass them as parameters). Another such project is a set
3018: of words to help dealing with strings.
1.29 crook 3019:
1.48 anton 3020: On the other hand, there is a useful set of record words, and it has
3021: been defined in @file{compat/struct.fs}; these words are predefined in
3022: Gforth. They are explained in depth elsewhere in this manual (see
3023: @pxref{Structures}). The @code{simple-field} example above is
3024: simplified variant of fields in this package.
1.21 crook 3025:
3026:
1.48 anton 3027: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3028: @section @code{POSTPONE}
1.66 anton 3029: @cindex postpone tutorial
1.21 crook 3030:
1.48 anton 3031: You can compile the compilation semantics (instead of compiling the
3032: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3033:
1.48 anton 3034: @example
3035: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3036: POSTPONE + ; immediate
1.48 anton 3037: : foo ( n1 n2 -- n )
3038: MY-+ ;
3039: 1 2 foo .
3040: see foo
3041: @end example
1.21 crook 3042:
1.48 anton 3043: During the definition of @code{foo} the text interpreter performs the
3044: compilation semantics of @code{MY-+}, which performs the compilation
3045: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3046:
3047: This example also displays separate stack comments for the compilation
3048: semantics and for the stack effect of the compiled code. For words with
3049: default compilation semantics these stack effects are usually not
3050: displayed; the stack effect of the compilation semantics is always
3051: @code{( -- )} for these words, the stack effect for the compiled code is
3052: the stack effect of the interpretation semantics.
3053:
3054: Note that the state of the interpreter does not come into play when
3055: performing the compilation semantics in this way. You can also perform
3056: it interpretively, e.g.:
3057:
3058: @example
3059: : foo2 ( n1 n2 -- n )
3060: [ MY-+ ] ;
3061: 1 2 foo .
3062: see foo
3063: @end example
1.21 crook 3064:
1.48 anton 3065: However, there are some broken Forth systems where this does not always
1.62 crook 3066: work, and therefore this practice was been declared non-standard in
1.48 anton 3067: 1999.
3068: @c !! repair.fs
3069:
3070: Here is another example for using @code{POSTPONE}:
1.44 crook 3071:
1.48 anton 3072: @example
3073: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3074: POSTPONE negate POSTPONE + ; immediate compile-only
3075: : bar ( n1 n2 -- n )
3076: MY-- ;
3077: 2 1 bar .
3078: see bar
3079: @end example
1.21 crook 3080:
1.48 anton 3081: You can define @code{ENDIF} in this way:
1.21 crook 3082:
1.48 anton 3083: @example
3084: : ENDIF ( Compilation: orig -- )
3085: POSTPONE then ; immediate
3086: @end example
1.21 crook 3087:
1.141 anton 3088: @quotation Assignment
1.48 anton 3089: Write @code{MY-2DUP} that has compilation semantics equivalent to
3090: @code{2dup}, but compiles @code{over over}.
1.141 anton 3091: @end quotation
1.29 crook 3092:
1.66 anton 3093: @c !! @xref{Macros} for reference
3094:
3095:
1.48 anton 3096: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3097: @section @code{Literal}
1.66 anton 3098: @cindex literal tutorial
1.29 crook 3099:
1.48 anton 3100: You cannot @code{POSTPONE} numbers:
1.21 crook 3101:
1.48 anton 3102: @example
3103: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3104: @end example
3105:
1.48 anton 3106: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3107:
1.48 anton 3108: @example
3109: : [FOO] ( compilation: --; run-time: -- n )
3110: 500 POSTPONE literal ; immediate
1.29 crook 3111:
1.60 anton 3112: : flip [FOO] ;
1.48 anton 3113: flip .
3114: see flip
3115: @end example
1.29 crook 3116:
1.48 anton 3117: @code{LITERAL} consumes a number at compile-time (when it's compilation
3118: semantics are executed) and pushes it at run-time (when the code it
3119: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3120: number computed at compile time into the current word:
1.29 crook 3121:
1.48 anton 3122: @example
3123: : bar ( -- n )
3124: [ 2 2 + ] literal ;
3125: see bar
3126: @end example
1.29 crook 3127:
1.141 anton 3128: @quotation Assignment
1.48 anton 3129: Write @code{]L} which allows writing the example above as @code{: bar (
3130: -- n ) [ 2 2 + ]L ;}
1.141 anton 3131: @end quotation
1.48 anton 3132:
1.66 anton 3133: @c !! @xref{Macros} for reference
3134:
1.48 anton 3135:
3136: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3137: @section Advanced macros
1.66 anton 3138: @cindex macros, advanced tutorial
3139: @cindex run-time code generation, tutorial
1.48 anton 3140:
1.66 anton 3141: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3142: Execution Tokens}. It frequently performs @code{execute}, a relatively
3143: expensive operation in some Forth implementations. You can use
1.48 anton 3144: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3145: and produce a word that contains the word to be performed directly:
3146:
3147: @c use ]] ... [[
3148: @example
3149: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3150: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3151: \ array beginning at addr and containing u elements
3152: @{ xt @}
3153: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3154: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3155: 1 cells POSTPONE literal POSTPONE +loop ;
3156:
3157: : sum-array ( addr u -- n )
3158: 0 rot rot [ ' + compile-map-array ] ;
3159: see sum-array
3160: a 5 sum-array .
3161: @end example
3162:
3163: You can use the full power of Forth for generating the code; here's an
3164: example where the code is generated in a loop:
3165:
3166: @example
3167: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3168: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3169: POSTPONE tuck POSTPONE @@
1.48 anton 3170: POSTPONE literal POSTPONE * POSTPONE +
3171: POSTPONE swap POSTPONE cell+ ;
3172:
3173: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3174: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3175: 0 postpone literal postpone swap
3176: [ ' compile-vmul-step compile-map-array ]
3177: postpone drop ;
3178: see compile-vmul
3179:
3180: : a-vmul ( addr -- n )
1.51 pazsan 3181: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3182: [ a 5 compile-vmul ] ;
3183: see a-vmul
3184: a a-vmul .
3185: @end example
3186:
3187: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3188: also use @code{map-array} instead (try it now!).
1.48 anton 3189:
3190: You can use this technique for efficient multiplication of large
3191: matrices. In matrix multiplication, you multiply every line of one
3192: matrix with every column of the other matrix. You can generate the code
3193: for one line once, and use it for every column. The only downside of
3194: this technique is that it is cumbersome to recover the memory consumed
3195: by the generated code when you are done (and in more complicated cases
3196: it is not possible portably).
3197:
1.66 anton 3198: @c !! @xref{Macros} for reference
3199:
3200:
1.48 anton 3201: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3202: @section Compilation Tokens
1.66 anton 3203: @cindex compilation tokens, tutorial
3204: @cindex CT, tutorial
1.48 anton 3205:
3206: This section is Gforth-specific. You can skip it.
3207:
3208: @code{' word compile,} compiles the interpretation semantics. For words
3209: with default compilation semantics this is the same as performing the
3210: compilation semantics. To represent the compilation semantics of other
3211: words (e.g., words like @code{if} that have no interpretation
3212: semantics), Gforth has the concept of a compilation token (CT,
3213: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3214: You can perform the compilation semantics represented by a CT with
3215: @code{execute}:
1.29 crook 3216:
1.48 anton 3217: @example
3218: : foo2 ( n1 n2 -- n )
3219: [ comp' + execute ] ;
3220: see foo
3221: @end example
1.29 crook 3222:
1.48 anton 3223: You can compile the compilation semantics represented by a CT with
3224: @code{postpone,}:
1.30 anton 3225:
1.48 anton 3226: @example
3227: : foo3 ( -- )
3228: [ comp' + postpone, ] ;
3229: see foo3
3230: @end example
1.30 anton 3231:
1.51 pazsan 3232: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3233: @code{comp'} is particularly useful for words that have no
3234: interpretation semantics:
1.29 crook 3235:
1.30 anton 3236: @example
1.48 anton 3237: ' if
1.60 anton 3238: comp' if .s 2drop
1.30 anton 3239: @end example
3240:
1.66 anton 3241: Reference: @ref{Tokens for Words}.
3242:
1.29 crook 3243:
1.48 anton 3244: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3245: @section Wordlists and Search Order
1.66 anton 3246: @cindex wordlists tutorial
3247: @cindex search order, tutorial
1.48 anton 3248:
3249: The dictionary is not just a memory area that allows you to allocate
3250: memory with @code{allot}, it also contains the Forth words, arranged in
3251: several wordlists. When searching for a word in a wordlist,
3252: conceptually you start searching at the youngest and proceed towards
3253: older words (in reality most systems nowadays use hash-tables); i.e., if
3254: you define a word with the same name as an older word, the new word
3255: shadows the older word.
3256:
3257: Which wordlists are searched in which order is determined by the search
3258: order. You can display the search order with @code{order}. It displays
3259: first the search order, starting with the wordlist searched first, then
3260: it displays the wordlist that will contain newly defined words.
1.21 crook 3261:
1.48 anton 3262: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3263:
1.48 anton 3264: @example
3265: wordlist constant mywords
3266: @end example
1.21 crook 3267:
1.48 anton 3268: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3269: defined words (the @emph{current} wordlist):
1.21 crook 3270:
1.48 anton 3271: @example
3272: mywords set-current
3273: order
3274: @end example
1.26 crook 3275:
1.48 anton 3276: Gforth does not display a name for the wordlist in @code{mywords}
3277: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3278:
1.48 anton 3279: You can get the current wordlist with @code{get-current ( -- wid)}. If
3280: you want to put something into a specific wordlist without overall
3281: effect on the current wordlist, this typically looks like this:
1.21 crook 3282:
1.48 anton 3283: @example
3284: get-current mywords set-current ( wid )
3285: create someword
3286: ( wid ) set-current
3287: @end example
1.21 crook 3288:
1.48 anton 3289: You can write the search order with @code{set-order ( wid1 .. widn n --
3290: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3291: searched wordlist is topmost.
1.21 crook 3292:
1.48 anton 3293: @example
3294: get-order mywords swap 1+ set-order
3295: order
3296: @end example
1.21 crook 3297:
1.48 anton 3298: Yes, the order of wordlists in the output of @code{order} is reversed
3299: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3300:
1.141 anton 3301: @quotation Assignment
1.48 anton 3302: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3303: wordlist to the search order. Define @code{previous ( -- )}, which
3304: removes the first searched wordlist from the search order. Experiment
3305: with boundary conditions (you will see some crashes or situations that
3306: are hard or impossible to leave).
1.141 anton 3307: @end quotation
1.21 crook 3308:
1.48 anton 3309: The search order is a powerful foundation for providing features similar
3310: to Modula-2 modules and C++ namespaces. However, trying to modularize
3311: programs in this way has disadvantages for debugging and reuse/factoring
3312: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3313: though). These disadvantages are not so clear in other
1.82 anton 3314: languages/programming environments, because these languages are not so
1.48 anton 3315: strong in debugging and reuse.
1.21 crook 3316:
1.66 anton 3317: @c !! example
3318:
3319: Reference: @ref{Word Lists}.
1.21 crook 3320:
1.29 crook 3321: @c ******************************************************************
1.48 anton 3322: @node Introduction, Words, Tutorial, Top
1.29 crook 3323: @comment node-name, next, previous, up
3324: @chapter An Introduction to ANS Forth
3325: @cindex Forth - an introduction
1.21 crook 3326:
1.83 anton 3327: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3328: that it is slower-paced in its examples, but uses them to dive deep into
3329: explaining Forth internals (not covered by the Tutorial). Apart from
3330: that, this chapter covers far less material. It is suitable for reading
3331: without using a computer.
3332:
1.29 crook 3333: The primary purpose of this manual is to document Gforth. However, since
3334: Forth is not a widely-known language and there is a lack of up-to-date
3335: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3336: material. For other sources of Forth-related
3337: information, see @ref{Forth-related information}.
1.21 crook 3338:
1.29 crook 3339: The examples in this section should work on any ANS Forth; the
3340: output shown was produced using Gforth. Each example attempts to
3341: reproduce the exact output that Gforth produces. If you try out the
3342: examples (and you should), what you should type is shown @kbd{like this}
3343: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3344: that, where the example shows @key{RET} it means that you should
1.29 crook 3345: press the ``carriage return'' key. Unfortunately, some output formats for
3346: this manual cannot show the difference between @kbd{this} and
3347: @code{this} which will make trying out the examples harder (but not
3348: impossible).
1.21 crook 3349:
1.29 crook 3350: Forth is an unusual language. It provides an interactive development
3351: environment which includes both an interpreter and compiler. Forth
3352: programming style encourages you to break a problem down into many
3353: @cindex factoring
3354: small fragments (@dfn{factoring}), and then to develop and test each
3355: fragment interactively. Forth advocates assert that breaking the
3356: edit-compile-test cycle used by conventional programming languages can
3357: lead to great productivity improvements.
1.21 crook 3358:
1.29 crook 3359: @menu
1.67 anton 3360: * Introducing the Text Interpreter::
3361: * Stacks and Postfix notation::
3362: * Your first definition::
3363: * How does that work?::
3364: * Forth is written in Forth::
3365: * Review - elements of a Forth system::
3366: * Where to go next::
3367: * Exercises::
1.29 crook 3368: @end menu
1.21 crook 3369:
1.29 crook 3370: @comment ----------------------------------------------
3371: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3372: @section Introducing the Text Interpreter
3373: @cindex text interpreter
3374: @cindex outer interpreter
1.21 crook 3375:
1.30 anton 3376: @c IMO this is too detailed and the pace is too slow for
3377: @c an introduction. If you know German, take a look at
3378: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3379: @c to see how I do it - anton
3380:
1.44 crook 3381: @c nac-> Where I have accepted your comments 100% and modified the text
3382: @c accordingly, I have deleted your comments. Elsewhere I have added a
3383: @c response like this to attempt to rationalise what I have done. Of
3384: @c course, this is a very clumsy mechanism for something that would be
3385: @c done far more efficiently over a beer. Please delete any dialogue
3386: @c you consider closed.
3387:
1.29 crook 3388: When you invoke the Forth image, you will see a startup banner printed
3389: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3390: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3391: its command line interpreter, which is called the @dfn{Text Interpreter}
3392: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3393: about the text interpreter as you read through this chapter, for more
3394: detail @pxref{The Text Interpreter}).
1.21 crook 3395:
1.29 crook 3396: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3397: input. Type a number and press the @key{RET} key:
1.21 crook 3398:
1.26 crook 3399: @example
1.30 anton 3400: @kbd{45@key{RET}} ok
1.26 crook 3401: @end example
1.21 crook 3402:
1.29 crook 3403: Rather than give you a prompt to invite you to input something, the text
3404: interpreter prints a status message @i{after} it has processed a line
3405: of input. The status message in this case (``@code{ ok}'' followed by
3406: carriage-return) indicates that the text interpreter was able to process
3407: all of your input successfully. Now type something illegal:
3408:
3409: @example
1.30 anton 3410: @kbd{qwer341@key{RET}}
1.134 anton 3411: *the terminal*:2: Undefined word
3412: >>>qwer341<<<
3413: Backtrace:
3414: $2A95B42A20 throw
3415: $2A95B57FB8 no.extensions
1.29 crook 3416: @end example
1.23 crook 3417:
1.134 anton 3418: The exact text, other than the ``Undefined word'' may differ slightly
3419: on your system, but the effect is the same; when the text interpreter
1.29 crook 3420: detects an error, it discards any remaining text on a line, resets
1.134 anton 3421: certain internal state and prints an error message. For a detailed
3422: description of error messages see @ref{Error messages}.
1.23 crook 3423:
1.29 crook 3424: The text interpreter waits for you to press carriage-return, and then
3425: processes your input line. Starting at the beginning of the line, it
3426: breaks the line into groups of characters separated by spaces. For each
3427: group of characters in turn, it makes two attempts to do something:
1.23 crook 3428:
1.29 crook 3429: @itemize @bullet
3430: @item
1.44 crook 3431: @cindex name dictionary
1.29 crook 3432: It tries to treat it as a command. It does this by searching a @dfn{name
3433: dictionary}. If the group of characters matches an entry in the name
3434: dictionary, the name dictionary provides the text interpreter with
3435: information that allows the text interpreter perform some actions. In
3436: Forth jargon, we say that the group
3437: @cindex word
3438: @cindex definition
3439: @cindex execution token
3440: @cindex xt
3441: of characters names a @dfn{word}, that the dictionary search returns an
3442: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3443: word, and that the text interpreter executes the xt. Often, the terms
3444: @dfn{word} and @dfn{definition} are used interchangeably.
3445: @item
3446: If the text interpreter fails to find a match in the name dictionary, it
3447: tries to treat the group of characters as a number in the current number
3448: base (when you start up Forth, the current number base is base 10). If
3449: the group of characters legitimately represents a number, the text
3450: interpreter pushes the number onto a stack (we'll learn more about that
3451: in the next section).
3452: @end itemize
1.23 crook 3453:
1.29 crook 3454: If the text interpreter is unable to do either of these things with any
3455: group of characters, it discards the group of characters and the rest of
3456: the line, then prints an error message. If the text interpreter reaches
3457: the end of the line without error, it prints the status message ``@code{ ok}''
3458: followed by carriage-return.
1.21 crook 3459:
1.29 crook 3460: This is the simplest command we can give to the text interpreter:
1.23 crook 3461:
3462: @example
1.30 anton 3463: @key{RET} ok
1.23 crook 3464: @end example
1.21 crook 3465:
1.29 crook 3466: The text interpreter did everything we asked it to do (nothing) without
3467: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3468: command:
1.21 crook 3469:
1.23 crook 3470: @example
1.30 anton 3471: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3472: *the terminal*:3: Undefined word
3473: 12 dup >>>fred<<< dup
3474: Backtrace:
3475: $2A95B42A20 throw
3476: $2A95B57FB8 no.extensions
1.23 crook 3477: @end example
1.21 crook 3478:
1.29 crook 3479: When you press the carriage-return key, the text interpreter starts to
3480: work its way along the line:
1.21 crook 3481:
1.29 crook 3482: @itemize @bullet
3483: @item
3484: When it gets to the space after the @code{2}, it takes the group of
3485: characters @code{12} and looks them up in the name
3486: dictionary@footnote{We can't tell if it found them or not, but assume
3487: for now that it did not}. There is no match for this group of characters
3488: in the name dictionary, so it tries to treat them as a number. It is
3489: able to do this successfully, so it puts the number, 12, ``on the stack''
3490: (whatever that means).
3491: @item
3492: The text interpreter resumes scanning the line and gets the next group
3493: of characters, @code{dup}. It looks it up in the name dictionary and
3494: (you'll have to take my word for this) finds it, and executes the word
3495: @code{dup} (whatever that means).
3496: @item
3497: Once again, the text interpreter resumes scanning the line and gets the
3498: group of characters @code{fred}. It looks them up in the name
3499: dictionary, but can't find them. It tries to treat them as a number, but
3500: they don't represent any legal number.
3501: @end itemize
1.21 crook 3502:
1.29 crook 3503: At this point, the text interpreter gives up and prints an error
3504: message. The error message shows exactly how far the text interpreter
3505: got in processing the line. In particular, it shows that the text
3506: interpreter made no attempt to do anything with the final character
3507: group, @code{dup}, even though we have good reason to believe that the
3508: text interpreter would have no problem looking that word up and
3509: executing it a second time.
1.21 crook 3510:
3511:
1.29 crook 3512: @comment ----------------------------------------------
3513: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3514: @section Stacks, postfix notation and parameter passing
3515: @cindex text interpreter
3516: @cindex outer interpreter
1.21 crook 3517:
1.29 crook 3518: In procedural programming languages (like C and Pascal), the
3519: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3520: functions or procedures are called with @dfn{explicit parameters}. For
3521: example, in C we might write:
1.21 crook 3522:
1.23 crook 3523: @example
1.29 crook 3524: total = total + new_volume(length,height,depth);
1.23 crook 3525: @end example
1.21 crook 3526:
1.23 crook 3527: @noindent
1.29 crook 3528: where new_volume is a function-call to another piece of code, and total,
3529: length, height and depth are all variables. length, height and depth are
3530: parameters to the function-call.
1.21 crook 3531:
1.29 crook 3532: In Forth, the equivalent of the function or procedure is the
3533: @dfn{definition} and parameters are implicitly passed between
3534: definitions using a shared stack that is visible to the
3535: programmer. Although Forth does support variables, the existence of the
3536: stack means that they are used far less often than in most other
3537: programming languages. When the text interpreter encounters a number, it
3538: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3539: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3540: used for any operation is implied unambiguously by the operation being
3541: performed. The stack used for all integer operations is called the @dfn{data
3542: stack} and, since this is the stack used most commonly, references to
3543: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3544:
1.29 crook 3545: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3546:
1.23 crook 3547: @example
1.30 anton 3548: @kbd{1 2 3@key{RET}} ok
1.23 crook 3549: @end example
1.21 crook 3550:
1.29 crook 3551: Then this instructs the text interpreter to placed three numbers on the
3552: (data) stack. An analogy for the behaviour of the stack is to take a
3553: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3554: the table. The 3 was the last card onto the pile (``last-in'') and if
3555: you take a card off the pile then, unless you're prepared to fiddle a
3556: bit, the card that you take off will be the 3 (``first-out''). The
3557: number that will be first-out of the stack is called the @dfn{top of
3558: stack}, which
3559: @cindex TOS definition
3560: is often abbreviated to @dfn{TOS}.
1.21 crook 3561:
1.29 crook 3562: To understand how parameters are passed in Forth, consider the
3563: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3564: be surprised to learn that this definition performs addition. More
3565: precisely, it adds two number together and produces a result. Where does
3566: it get the two numbers from? It takes the top two numbers off the
3567: stack. Where does it place the result? On the stack. You can act-out the
3568: behaviour of @code{+} with your playing cards like this:
1.21 crook 3569:
3570: @itemize @bullet
3571: @item
1.29 crook 3572: Pick up two cards from the stack on the table
1.21 crook 3573: @item
1.29 crook 3574: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3575: numbers''
1.21 crook 3576: @item
1.29 crook 3577: Decide that the answer is 5
1.21 crook 3578: @item
1.29 crook 3579: Shuffle the two cards back into the pack and find a 5
1.21 crook 3580: @item
1.29 crook 3581: Put a 5 on the remaining ace that's on the table.
1.21 crook 3582: @end itemize
3583:
1.29 crook 3584: If you don't have a pack of cards handy but you do have Forth running,
3585: you can use the definition @code{.s} to show the current state of the stack,
3586: without affecting the stack. Type:
1.21 crook 3587:
3588: @example
1.124 anton 3589: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3590: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3591: @end example
3592:
1.124 anton 3593: The text interpreter looks up the word @code{clearstacks} and executes
3594: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3595: left on it by earlier examples. The text interpreter pushes each of the
3596: three numbers in turn onto the stack. Finally, the text interpreter
3597: looks up the word @code{.s} and executes it. The effect of executing
3598: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3599: followed by a list of all the items on the stack; the item on the far
3600: right-hand side is the TOS.
1.21 crook 3601:
1.29 crook 3602: You can now type:
1.21 crook 3603:
1.29 crook 3604: @example
1.30 anton 3605: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3606: @end example
1.21 crook 3607:
1.29 crook 3608: @noindent
3609: which is correct; there are now 2 items on the stack and the result of
3610: the addition is 5.
1.23 crook 3611:
1.29 crook 3612: If you're playing with cards, try doing a second addition: pick up the
3613: two cards, work out that their sum is 6, shuffle them into the pack,
3614: look for a 6 and place that on the table. You now have just one item on
3615: the stack. What happens if you try to do a third addition? Pick up the
3616: first card, pick up the second card -- ah! There is no second card. This
3617: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3618: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3619: Underflow or an Invalid Memory Address error).
1.23 crook 3620:
1.29 crook 3621: The opposite situation to a stack underflow is a @dfn{stack overflow},
3622: which simply accepts that there is a finite amount of storage space
3623: reserved for the stack. To stretch the playing card analogy, if you had
3624: enough packs of cards and you piled the cards up on the table, you would
3625: eventually be unable to add another card; you'd hit the ceiling. Gforth
3626: allows you to set the maximum size of the stacks. In general, the only
3627: time that you will get a stack overflow is because a definition has a
3628: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3629:
1.29 crook 3630: There's one final use for the playing card analogy. If you model your
3631: stack using a pack of playing cards, the maximum number of items on
3632: your stack will be 52 (I assume you didn't use the Joker). The maximum
3633: @i{value} of any item on the stack is 13 (the King). In fact, the only
3634: possible numbers are positive integer numbers 1 through 13; you can't
3635: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3636: think about some of the cards, you can accommodate different
3637: numbers. For example, you could think of the Jack as representing 0,
3638: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3639: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3640: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3641:
1.29 crook 3642: In that analogy, the limit was the amount of information that a single
3643: stack entry could hold, and Forth has a similar limit. In Forth, the
3644: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3645: implementation dependent and affects the maximum value that a stack
3646: entry can hold. A Standard Forth provides a cell size of at least
3647: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3648:
1.29 crook 3649: Forth does not do any type checking for you, so you are free to
3650: manipulate and combine stack items in any way you wish. A convenient way
3651: of treating stack items is as 2's complement signed integers, and that
3652: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3653:
1.29 crook 3654: @example
1.30 anton 3655: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3656: @end example
1.21 crook 3657:
1.29 crook 3658: If you use numbers and definitions like @code{+} in order to turn Forth
3659: into a great big pocket calculator, you will realise that it's rather
3660: different from a normal calculator. Rather than typing 2 + 3 = you had
3661: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3662: result). The terminology used to describe this difference is to say that
3663: your calculator uses @dfn{Infix Notation} (parameters and operators are
3664: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3665: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3666:
1.29 crook 3667: Whilst postfix notation might look confusing to begin with, it has
3668: several important advantages:
1.21 crook 3669:
1.23 crook 3670: @itemize @bullet
3671: @item
1.29 crook 3672: it is unambiguous
1.23 crook 3673: @item
1.29 crook 3674: it is more concise
1.23 crook 3675: @item
1.29 crook 3676: it fits naturally with a stack-based system
1.23 crook 3677: @end itemize
1.21 crook 3678:
1.29 crook 3679: To examine these claims in more detail, consider these sums:
1.21 crook 3680:
1.29 crook 3681: @example
3682: 6 + 5 * 4 =
3683: 4 * 5 + 6 =
3684: @end example
1.21 crook 3685:
1.29 crook 3686: If you're just learning maths or your maths is very rusty, you will
3687: probably come up with the answer 44 for the first and 26 for the
3688: second. If you are a bit of a whizz at maths you will remember the
3689: @i{convention} that multiplication takes precendence over addition, and
3690: you'd come up with the answer 26 both times. To explain the answer 26
3691: to someone who got the answer 44, you'd probably rewrite the first sum
3692: like this:
1.21 crook 3693:
1.29 crook 3694: @example
3695: 6 + (5 * 4) =
3696: @end example
1.21 crook 3697:
1.29 crook 3698: If what you really wanted was to perform the addition before the
3699: multiplication, you would have to use parentheses to force it.
1.21 crook 3700:
1.29 crook 3701: If you did the first two sums on a pocket calculator you would probably
3702: get the right answers, unless you were very cautious and entered them using
3703: these keystroke sequences:
1.21 crook 3704:
1.29 crook 3705: 6 + 5 = * 4 =
3706: 4 * 5 = + 6 =
1.21 crook 3707:
1.29 crook 3708: Postfix notation is unambiguous because the order that the operators
3709: are applied is always explicit; that also means that parentheses are
3710: never required. The operators are @i{active} (the act of quoting the
3711: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3712:
1.29 crook 3713: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3714: equivalent ways:
1.26 crook 3715:
3716: @example
1.29 crook 3717: 6 5 4 * + or:
3718: 5 4 * 6 +
1.26 crook 3719: @end example
1.23 crook 3720:
1.29 crook 3721: An important thing that you should notice about this notation is that
3722: the @i{order} of the numbers does not change; if you want to subtract
3723: 2 from 10 you type @code{10 2 -}.
1.1 anton 3724:
1.29 crook 3725: The reason that Forth uses postfix notation is very simple to explain: it
3726: makes the implementation extremely simple, and it follows naturally from
3727: using the stack as a mechanism for passing parameters. Another way of
3728: thinking about this is to realise that all Forth definitions are
3729: @i{active}; they execute as they are encountered by the text
3730: interpreter. The result of this is that the syntax of Forth is trivially
3731: simple.
1.1 anton 3732:
3733:
3734:
1.29 crook 3735: @comment ----------------------------------------------
3736: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3737: @section Your first Forth definition
3738: @cindex first definition
1.1 anton 3739:
1.29 crook 3740: Until now, the examples we've seen have been trivial; we've just been
3741: using Forth as a bigger-than-pocket calculator. Also, each calculation
3742: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3743: again@footnote{That's not quite true. If you press the up-arrow key on
3744: your keyboard you should be able to scroll back to any earlier command,
3745: edit it and re-enter it.} In this section we'll see how to add new
3746: words to Forth's vocabulary.
1.1 anton 3747:
1.29 crook 3748: The easiest way to create a new word is to use a @dfn{colon
3749: definition}. We'll define a few and try them out before worrying too
3750: much about how they work. Try typing in these examples; be careful to
3751: copy the spaces accurately:
1.1 anton 3752:
1.29 crook 3753: @example
3754: : add-two 2 + . ;
3755: : greet ." Hello and welcome" ;
3756: : demo 5 add-two ;
3757: @end example
1.1 anton 3758:
1.29 crook 3759: @noindent
3760: Now try them out:
1.1 anton 3761:
1.29 crook 3762: @example
1.30 anton 3763: @kbd{greet@key{RET}} Hello and welcome ok
3764: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3765: @kbd{4 add-two@key{RET}} 6 ok
3766: @kbd{demo@key{RET}} 7 ok
3767: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3768: @end example
1.1 anton 3769:
1.29 crook 3770: The first new thing that we've introduced here is the pair of words
3771: @code{:} and @code{;}. These are used to start and terminate a new
3772: definition, respectively. The first word after the @code{:} is the name
3773: for the new definition.
1.1 anton 3774:
1.29 crook 3775: As you can see from the examples, a definition is built up of words that
3776: have already been defined; Forth makes no distinction between
3777: definitions that existed when you started the system up, and those that
3778: you define yourself.
1.1 anton 3779:
1.29 crook 3780: The examples also introduce the words @code{.} (dot), @code{."}
3781: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3782: the stack and displays it. It's like @code{.s} except that it only
3783: displays the top item of the stack and it is destructive; after it has
3784: executed, the number is no longer on the stack. There is always one
3785: space printed after the number, and no spaces before it. Dot-quote
3786: defines a string (a sequence of characters) that will be printed when
3787: the word is executed. The string can contain any printable characters
3788: except @code{"}. A @code{"} has a special function; it is not a Forth
3789: word but it acts as a delimiter (the way that delimiters work is
3790: described in the next section). Finally, @code{dup} duplicates the value
3791: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3792:
1.29 crook 3793: We already know that the text interpreter searches through the
3794: dictionary to locate names. If you've followed the examples earlier, you
3795: will already have a definition called @code{add-two}. Lets try modifying
3796: it by typing in a new definition:
1.1 anton 3797:
1.29 crook 3798: @example
1.30 anton 3799: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3800: @end example
1.5 anton 3801:
1.29 crook 3802: Forth recognised that we were defining a word that already exists, and
3803: printed a message to warn us of that fact. Let's try out the new
3804: definition:
1.5 anton 3805:
1.29 crook 3806: @example
1.30 anton 3807: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3808: @end example
1.1 anton 3809:
1.29 crook 3810: @noindent
3811: All that we've actually done here, though, is to create a new
3812: definition, with a particular name. The fact that there was already a
3813: definition with the same name did not make any difference to the way
3814: that the new definition was created (except that Forth printed a warning
3815: message). The old definition of add-two still exists (try @code{demo}
3816: again to see that this is true). Any new definition will use the new
3817: definition of @code{add-two}, but old definitions continue to use the
3818: version that already existed at the time that they were @code{compiled}.
1.1 anton 3819:
1.29 crook 3820: Before you go on to the next section, try defining and redefining some
3821: words of your own.
1.1 anton 3822:
1.29 crook 3823: @comment ----------------------------------------------
3824: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3825: @section How does that work?
3826: @cindex parsing words
1.1 anton 3827:
1.30 anton 3828: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3829:
3830: @c Is it a good idea to talk about the interpretation semantics of a
3831: @c number? We don't have an xt to go along with it. - anton
3832:
3833: @c Now that I have eliminated execution semantics, I wonder if it would not
3834: @c be better to keep them (or add run-time semantics), to make it easier to
3835: @c explain what compilation semantics usually does. - anton
3836:
1.44 crook 3837: @c nac-> I removed the term ``default compilation sematics'' from the
3838: @c introductory chapter. Removing ``execution semantics'' was making
3839: @c everything simpler to explain, then I think the use of this term made
3840: @c everything more complex again. I replaced it with ``default
3841: @c semantics'' (which is used elsewhere in the manual) by which I mean
3842: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3843: @c flag set''.
3844:
3845: @c anton: I have eliminated default semantics (except in one place where it
3846: @c means "default interpretation and compilation semantics"), because it
3847: @c makes no sense in the presence of combined words. I reverted to
3848: @c "execution semantics" where necessary.
3849:
3850: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3851: @c section (and, unusually for me, I think I even made it shorter!). See
3852: @c what you think -- I know I have not addressed your primary concern
3853: @c that it is too heavy-going for an introduction. From what I understood
3854: @c of your course notes it looks as though they might be a good framework.
3855: @c Things that I've tried to capture here are some things that came as a
3856: @c great revelation here when I first understood them. Also, I like the
3857: @c fact that a very simple code example shows up almost all of the issues
3858: @c that you need to understand to see how Forth works. That's unique and
3859: @c worthwhile to emphasise.
3860:
1.83 anton 3861: @c anton: I think it's a good idea to present the details, especially those
3862: @c that you found to be a revelation, and probably the tutorial tries to be
3863: @c too superficial and does not get some of the things across that make
3864: @c Forth special. I do believe that most of the time these things should
3865: @c be discussed at the end of a section or in separate sections instead of
3866: @c in the middle of a section (e.g., the stuff you added in "User-defined
3867: @c defining words" leads in a completely different direction from the rest
3868: @c of the section).
3869:
1.29 crook 3870: Now we're going to take another look at the definition of @code{add-two}
3871: from the previous section. From our knowledge of the way that the text
3872: interpreter works, we would have expected this result when we tried to
3873: define @code{add-two}:
1.21 crook 3874:
1.29 crook 3875: @example
1.44 crook 3876: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3877: *the terminal*:4: Undefined word
3878: : >>>add-two<<< 2 + . ;
1.29 crook 3879: @end example
1.28 crook 3880:
1.29 crook 3881: The reason that this didn't happen is bound up in the way that @code{:}
3882: works. The word @code{:} does two special things. The first special
3883: thing that it does prevents the text interpreter from ever seeing the
3884: characters @code{add-two}. The text interpreter uses a variable called
3885: @cindex modifying >IN
1.44 crook 3886: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3887: input line. When it encounters the word @code{:} it behaves in exactly
3888: the same way as it does for any other word; it looks it up in the name
3889: dictionary, finds its xt and executes it. When @code{:} executes, it
3890: looks at the input buffer, finds the word @code{add-two} and advances the
3891: value of @code{>IN} to point past it. It then does some other stuff
3892: associated with creating the new definition (including creating an entry
3893: for @code{add-two} in the name dictionary). When the execution of @code{:}
3894: completes, control returns to the text interpreter, which is oblivious
3895: to the fact that it has been tricked into ignoring part of the input
3896: line.
1.21 crook 3897:
1.29 crook 3898: @cindex parsing words
3899: Words like @code{:} -- words that advance the value of @code{>IN} and so
3900: prevent the text interpreter from acting on the whole of the input line
3901: -- are called @dfn{parsing words}.
1.21 crook 3902:
1.29 crook 3903: @cindex @code{state} - effect on the text interpreter
3904: @cindex text interpreter - effect of state
3905: The second special thing that @code{:} does is change the value of a
3906: variable called @code{state}, which affects the way that the text
3907: interpreter behaves. When Gforth starts up, @code{state} has the value
3908: 0, and the text interpreter is said to be @dfn{interpreting}. During a
3909: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 3910: the text interpreter is said to be @dfn{compiling}.
3911:
3912: In this example, the text interpreter is compiling when it processes the
3913: string ``@code{2 + . ;}''. It still breaks the string down into
3914: character sequences in the same way. However, instead of pushing the
3915: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
3916: into the definition of @code{add-two} that will make the number @code{2} get
3917: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
3918: the behaviours of @code{+} and @code{.} are also compiled into the
3919: definition.
3920:
3921: One category of words don't get compiled. These so-called @dfn{immediate
3922: words} get executed (performed @i{now}) regardless of whether the text
3923: interpreter is interpreting or compiling. The word @code{;} is an
3924: immediate word. Rather than being compiled into the definition, it
3925: executes. Its effect is to terminate the current definition, which
3926: includes changing the value of @code{state} back to 0.
3927:
3928: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
3929: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
3930: definition.
1.28 crook 3931:
1.30 anton 3932: In Forth, every word or number can be described in terms of two
1.29 crook 3933: properties:
1.28 crook 3934:
3935: @itemize @bullet
3936: @item
1.29 crook 3937: @cindex interpretation semantics
1.44 crook 3938: Its @dfn{interpretation semantics} describe how it will behave when the
3939: text interpreter encounters it in @dfn{interpret} state. The
3940: interpretation semantics of a word are represented by an @dfn{execution
3941: token}.
1.28 crook 3942: @item
1.29 crook 3943: @cindex compilation semantics
1.44 crook 3944: Its @dfn{compilation semantics} describe how it will behave when the
3945: text interpreter encounters it in @dfn{compile} state. The compilation
3946: semantics of a word are represented in an implementation-dependent way;
3947: Gforth uses a @dfn{compilation token}.
1.29 crook 3948: @end itemize
3949:
3950: @noindent
3951: Numbers are always treated in a fixed way:
3952:
3953: @itemize @bullet
1.28 crook 3954: @item
1.44 crook 3955: When the number is @dfn{interpreted}, its behaviour is to push the
3956: number onto the stack.
1.28 crook 3957: @item
1.30 anton 3958: When the number is @dfn{compiled}, a piece of code is appended to the
3959: current definition that pushes the number when it runs. (In other words,
3960: the compilation semantics of a number are to postpone its interpretation
3961: semantics until the run-time of the definition that it is being compiled
3962: into.)
1.29 crook 3963: @end itemize
3964:
1.44 crook 3965: Words don't behave in such a regular way, but most have @i{default
3966: semantics} which means that they behave like this:
1.29 crook 3967:
3968: @itemize @bullet
1.28 crook 3969: @item
1.30 anton 3970: The @dfn{interpretation semantics} of the word are to do something useful.
3971: @item
1.29 crook 3972: The @dfn{compilation semantics} of the word are to append its
1.30 anton 3973: @dfn{interpretation semantics} to the current definition (so that its
3974: run-time behaviour is to do something useful).
1.28 crook 3975: @end itemize
3976:
1.30 anton 3977: @cindex immediate words
1.44 crook 3978: The actual behaviour of any particular word can be controlled by using
3979: the words @code{immediate} and @code{compile-only} when the word is
3980: defined. These words set flags in the name dictionary entry of the most
3981: recently defined word, and these flags are retrieved by the text
3982: interpreter when it finds the word in the name dictionary.
3983:
3984: A word that is marked as @dfn{immediate} has compilation semantics that
3985: are identical to its interpretation semantics. In other words, it
3986: behaves like this:
1.29 crook 3987:
3988: @itemize @bullet
3989: @item
1.30 anton 3990: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 3991: @item
1.30 anton 3992: The @dfn{compilation semantics} of the word are to do something useful
3993: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 3994: @end itemize
1.28 crook 3995:
1.44 crook 3996: Marking a word as @dfn{compile-only} prohibits the text interpreter from
3997: performing the interpretation semantics of the word directly; an attempt
3998: to do so will generate an error. It is never necessary to use
3999: @code{compile-only} (and it is not even part of ANS Forth, though it is
4000: provided by many implementations) but it is good etiquette to apply it
4001: to a word that will not behave correctly (and might have unexpected
4002: side-effects) in interpret state. For example, it is only legal to use
4003: the conditional word @code{IF} within a definition. If you forget this
4004: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4005: @code{compile-only} allows the text interpreter to generate a helpful
4006: error message rather than subjecting you to the consequences of your
4007: folly.
4008:
1.29 crook 4009: This example shows the difference between an immediate and a
4010: non-immediate word:
1.28 crook 4011:
1.29 crook 4012: @example
4013: : show-state state @@ . ;
4014: : show-state-now show-state ; immediate
4015: : word1 show-state ;
4016: : word2 show-state-now ;
1.28 crook 4017: @end example
1.23 crook 4018:
1.29 crook 4019: The word @code{immediate} after the definition of @code{show-state-now}
4020: makes that word an immediate word. These definitions introduce a new
4021: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4022: variable, and leaves it on the stack. Therefore, the behaviour of
4023: @code{show-state} is to print a number that represents the current value
4024: of @code{state}.
1.28 crook 4025:
1.29 crook 4026: When you execute @code{word1}, it prints the number 0, indicating that
4027: the system is interpreting. When the text interpreter compiled the
4028: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4029: compilation semantics are to append its interpretation semantics to the
1.29 crook 4030: current definition. When you execute @code{word1}, it performs the
1.30 anton 4031: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4032: (and therefore @code{show-state}) are executed, the system is
4033: interpreting.
1.28 crook 4034:
1.30 anton 4035: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4036: you should have seen the number -1 printed, followed by ``@code{
4037: ok}''. When the text interpreter compiled the definition of
4038: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4039: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4040: semantics. It is executed straight away (even before the text
4041: interpreter has moved on to process another group of characters; the
4042: @code{;} in this example). The effect of executing it are to display the
4043: value of @code{state} @i{at the time that the definition of}
4044: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4045: system is compiling at this time. If you execute @code{word2} it does
4046: nothing at all.
1.28 crook 4047:
1.29 crook 4048: @cindex @code{."}, how it works
4049: Before leaving the subject of immediate words, consider the behaviour of
4050: @code{."} in the definition of @code{greet}, in the previous
4051: section. This word is both a parsing word and an immediate word. Notice
4052: that there is a space between @code{."} and the start of the text
4053: @code{Hello and welcome}, but that there is no space between the last
4054: letter of @code{welcome} and the @code{"} character. The reason for this
4055: is that @code{."} is a Forth word; it must have a space after it so that
4056: the text interpreter can identify it. The @code{"} is not a Forth word;
4057: it is a @dfn{delimiter}. The examples earlier show that, when the string
4058: is displayed, there is neither a space before the @code{H} nor after the
4059: @code{e}. Since @code{."} is an immediate word, it executes at the time
4060: that @code{greet} is defined. When it executes, its behaviour is to
4061: search forward in the input line looking for the delimiter. When it
4062: finds the delimiter, it updates @code{>IN} to point past the
4063: delimiter. It also compiles some magic code into the definition of
4064: @code{greet}; the xt of a run-time routine that prints a text string. It
4065: compiles the string @code{Hello and welcome} into memory so that it is
4066: available to be printed later. When the text interpreter gains control,
4067: the next word it finds in the input stream is @code{;} and so it
4068: terminates the definition of @code{greet}.
1.28 crook 4069:
4070:
4071: @comment ----------------------------------------------
1.29 crook 4072: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4073: @section Forth is written in Forth
4074: @cindex structure of Forth programs
4075:
4076: When you start up a Forth compiler, a large number of definitions
4077: already exist. In Forth, you develop a new application using bottom-up
4078: programming techniques to create new definitions that are defined in
4079: terms of existing definitions. As you create each definition you can
4080: test and debug it interactively.
4081:
4082: If you have tried out the examples in this section, you will probably
4083: have typed them in by hand; when you leave Gforth, your definitions will
4084: be lost. You can avoid this by using a text editor to enter Forth source
4085: code into a file, and then loading code from the file using
1.49 anton 4086: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4087: processed by the text interpreter, just as though you had typed it in by
4088: hand@footnote{Actually, there are some subtle differences -- see
4089: @ref{The Text Interpreter}.}.
4090:
4091: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4092: files for program entry (@pxref{Blocks}).
1.28 crook 4093:
1.29 crook 4094: In common with many, if not most, Forth compilers, most of Gforth is
4095: actually written in Forth. All of the @file{.fs} files in the
4096: installation directory@footnote{For example,
1.30 anton 4097: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4098: study to see examples of Forth programming.
1.28 crook 4099:
1.29 crook 4100: Gforth maintains a history file that records every line that you type to
4101: the text interpreter. This file is preserved between sessions, and is
4102: used to provide a command-line recall facility. If you enter long
4103: definitions by hand, you can use a text editor to paste them out of the
4104: history file into a Forth source file for reuse at a later time
1.49 anton 4105: (for more information @pxref{Command-line editing}).
1.28 crook 4106:
4107:
4108: @comment ----------------------------------------------
1.29 crook 4109: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4110: @section Review - elements of a Forth system
4111: @cindex elements of a Forth system
1.28 crook 4112:
1.29 crook 4113: To summarise this chapter:
1.28 crook 4114:
4115: @itemize @bullet
4116: @item
1.29 crook 4117: Forth programs use @dfn{factoring} to break a problem down into small
4118: fragments called @dfn{words} or @dfn{definitions}.
4119: @item
4120: Forth program development is an interactive process.
4121: @item
4122: The main command loop that accepts input, and controls both
4123: interpretation and compilation, is called the @dfn{text interpreter}
4124: (also known as the @dfn{outer interpreter}).
4125: @item
4126: Forth has a very simple syntax, consisting of words and numbers
4127: separated by spaces or carriage-return characters. Any additional syntax
4128: is imposed by @dfn{parsing words}.
4129: @item
4130: Forth uses a stack to pass parameters between words. As a result, it
4131: uses postfix notation.
4132: @item
4133: To use a word that has previously been defined, the text interpreter
4134: searches for the word in the @dfn{name dictionary}.
4135: @item
1.30 anton 4136: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4137: @item
1.29 crook 4138: The text interpreter uses the value of @code{state} to select between
4139: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4140: semantics} of a word that it encounters.
1.28 crook 4141: @item
1.30 anton 4142: The relationship between the @dfn{interpretation semantics} and
4143: @dfn{compilation semantics} for a word
1.29 crook 4144: depend upon the way in which the word was defined (for example, whether
4145: it is an @dfn{immediate} word).
1.28 crook 4146: @item
1.29 crook 4147: Forth definitions can be implemented in Forth (called @dfn{high-level
4148: definitions}) or in some other way (usually a lower-level language and
4149: as a result often called @dfn{low-level definitions}, @dfn{code
4150: definitions} or @dfn{primitives}).
1.28 crook 4151: @item
1.29 crook 4152: Many Forth systems are implemented mainly in Forth.
1.28 crook 4153: @end itemize
4154:
4155:
1.29 crook 4156: @comment ----------------------------------------------
1.48 anton 4157: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4158: @section Where To Go Next
4159: @cindex where to go next
1.28 crook 4160:
1.29 crook 4161: Amazing as it may seem, if you have read (and understood) this far, you
4162: know almost all the fundamentals about the inner workings of a Forth
4163: system. You certainly know enough to be able to read and understand the
4164: rest of this manual and the ANS Forth document, to learn more about the
4165: facilities that Forth in general and Gforth in particular provide. Even
4166: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4167: However, that's not a good idea just yet... better to try writing some
1.29 crook 4168: programs in Gforth.
1.28 crook 4169:
1.29 crook 4170: Forth has such a rich vocabulary that it can be hard to know where to
4171: start in learning it. This section suggests a few sets of words that are
4172: enough to write small but useful programs. Use the word index in this
4173: document to learn more about each word, then try it out and try to write
4174: small definitions using it. Start by experimenting with these words:
1.28 crook 4175:
4176: @itemize @bullet
4177: @item
1.29 crook 4178: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4179: @item
4180: Comparison: @code{MIN MAX =}
4181: @item
4182: Logic: @code{AND OR XOR NOT}
4183: @item
4184: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4185: @item
1.29 crook 4186: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4187: @item
1.29 crook 4188: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4189: @item
1.29 crook 4190: Defining words: @code{: ; CREATE}
1.28 crook 4191: @item
1.29 crook 4192: Memory allocation words: @code{ALLOT ,}
1.28 crook 4193: @item
1.29 crook 4194: Tools: @code{SEE WORDS .S MARKER}
4195: @end itemize
4196:
4197: When you have mastered those, go on to:
4198:
4199: @itemize @bullet
1.28 crook 4200: @item
1.29 crook 4201: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4202: @item
1.29 crook 4203: Memory access: @code{@@ !}
1.28 crook 4204: @end itemize
1.23 crook 4205:
1.29 crook 4206: When you have mastered these, there's nothing for it but to read through
4207: the whole of this manual and find out what you've missed.
4208:
4209: @comment ----------------------------------------------
1.48 anton 4210: @node Exercises, , Where to go next, Introduction
1.29 crook 4211: @section Exercises
4212: @cindex exercises
4213:
4214: TODO: provide a set of programming excercises linked into the stuff done
4215: already and into other sections of the manual. Provide solutions to all
4216: the exercises in a .fs file in the distribution.
4217:
4218: @c Get some inspiration from Starting Forth and Kelly&Spies.
4219:
4220: @c excercises:
4221: @c 1. take inches and convert to feet and inches.
4222: @c 2. take temperature and convert from fahrenheight to celcius;
4223: @c may need to care about symmetric vs floored??
4224: @c 3. take input line and do character substitution
4225: @c to encipher or decipher
4226: @c 4. as above but work on a file for in and out
4227: @c 5. take input line and convert to pig-latin
4228: @c
4229: @c thing of sets of things to exercise then come up with
4230: @c problems that need those things.
4231:
4232:
1.26 crook 4233: @c ******************************************************************
1.29 crook 4234: @node Words, Error messages, Introduction, Top
1.1 anton 4235: @chapter Forth Words
1.26 crook 4236: @cindex words
1.1 anton 4237:
4238: @menu
4239: * Notation::
1.65 anton 4240: * Case insensitivity::
4241: * Comments::
4242: * Boolean Flags::
1.1 anton 4243: * Arithmetic::
4244: * Stack Manipulation::
1.5 anton 4245: * Memory::
1.1 anton 4246: * Control Structures::
4247: * Defining Words::
1.65 anton 4248: * Interpretation and Compilation Semantics::
1.47 crook 4249: * Tokens for Words::
1.81 anton 4250: * Compiling words::
1.65 anton 4251: * The Text Interpreter::
1.111 anton 4252: * The Input Stream::
1.65 anton 4253: * Word Lists::
4254: * Environmental Queries::
1.12 anton 4255: * Files::
4256: * Blocks::
4257: * Other I/O::
1.121 anton 4258: * OS command line arguments::
1.78 anton 4259: * Locals::
4260: * Structures::
4261: * Object-oriented Forth::
1.12 anton 4262: * Programming Tools::
1.150 anton 4263: * C Interface::
1.12 anton 4264: * Assembler and Code Words::
4265: * Threading Words::
1.65 anton 4266: * Passing Commands to the OS::
4267: * Keeping track of Time::
4268: * Miscellaneous Words::
1.1 anton 4269: @end menu
4270:
1.65 anton 4271: @node Notation, Case insensitivity, Words, Words
1.1 anton 4272: @section Notation
4273: @cindex notation of glossary entries
4274: @cindex format of glossary entries
4275: @cindex glossary notation format
4276: @cindex word glossary entry format
4277:
4278: The Forth words are described in this section in the glossary notation
1.67 anton 4279: that has become a de-facto standard for Forth texts:
1.1 anton 4280:
4281: @format
1.29 crook 4282: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4283: @end format
1.29 crook 4284: @i{Description}
1.1 anton 4285:
4286: @table @var
4287: @item word
1.28 crook 4288: The name of the word.
1.1 anton 4289:
4290: @item Stack effect
4291: @cindex stack effect
1.29 crook 4292: The stack effect is written in the notation @code{@i{before} --
4293: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4294: stack entries before and after the execution of the word. The rest of
4295: the stack is not touched by the word. The top of stack is rightmost,
4296: i.e., a stack sequence is written as it is typed in. Note that Gforth
4297: uses a separate floating point stack, but a unified stack
1.29 crook 4298: notation. Also, return stack effects are not shown in @i{stack
4299: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4300: the type and/or the function of the item. See below for a discussion of
4301: the types.
4302:
4303: All words have two stack effects: A compile-time stack effect and a
4304: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4305: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4306: this standard behaviour, or the word does other unusual things at
4307: compile time, both stack effects are shown; otherwise only the run-time
4308: stack effect is shown.
4309:
4310: @cindex pronounciation of words
4311: @item pronunciation
4312: How the word is pronounced.
4313:
4314: @cindex wordset
1.67 anton 4315: @cindex environment wordset
1.1 anton 4316: @item wordset
1.21 crook 4317: The ANS Forth standard is divided into several word sets. A standard
4318: system need not support all of them. Therefore, in theory, the fewer
4319: word sets your program uses the more portable it will be. However, we
4320: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4321: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4322: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4323: describes words that will work in future releases of Gforth;
4324: @code{gforth-internal} words are more volatile. Environmental query
4325: strings are also displayed like words; you can recognize them by the
1.21 crook 4326: @code{environment} in the word set field.
1.1 anton 4327:
4328: @item Description
4329: A description of the behaviour of the word.
4330: @end table
4331:
4332: @cindex types of stack items
4333: @cindex stack item types
4334: The type of a stack item is specified by the character(s) the name
4335: starts with:
4336:
4337: @table @code
4338: @item f
4339: @cindex @code{f}, stack item type
4340: Boolean flags, i.e. @code{false} or @code{true}.
4341: @item c
4342: @cindex @code{c}, stack item type
4343: Char
4344: @item w
4345: @cindex @code{w}, stack item type
4346: Cell, can contain an integer or an address
4347: @item n
4348: @cindex @code{n}, stack item type
4349: signed integer
4350: @item u
4351: @cindex @code{u}, stack item type
4352: unsigned integer
4353: @item d
4354: @cindex @code{d}, stack item type
4355: double sized signed integer
4356: @item ud
4357: @cindex @code{ud}, stack item type
4358: double sized unsigned integer
4359: @item r
4360: @cindex @code{r}, stack item type
4361: Float (on the FP stack)
1.21 crook 4362: @item a-
1.1 anton 4363: @cindex @code{a_}, stack item type
4364: Cell-aligned address
1.21 crook 4365: @item c-
1.1 anton 4366: @cindex @code{c_}, stack item type
4367: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4368: @item f-
1.1 anton 4369: @cindex @code{f_}, stack item type
4370: Float-aligned address
1.21 crook 4371: @item df-
1.1 anton 4372: @cindex @code{df_}, stack item type
4373: Address aligned for IEEE double precision float
1.21 crook 4374: @item sf-
1.1 anton 4375: @cindex @code{sf_}, stack item type
4376: Address aligned for IEEE single precision float
4377: @item xt
4378: @cindex @code{xt}, stack item type
4379: Execution token, same size as Cell
4380: @item wid
4381: @cindex @code{wid}, stack item type
1.21 crook 4382: Word list ID, same size as Cell
1.68 anton 4383: @item ior, wior
4384: @cindex ior type description
4385: @cindex wior type description
4386: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4387: @item f83name
4388: @cindex @code{f83name}, stack item type
4389: Pointer to a name structure
4390: @item "
4391: @cindex @code{"}, stack item type
1.12 anton 4392: string in the input stream (not on the stack). The terminating character
4393: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4394: quotes.
4395: @end table
4396:
1.65 anton 4397: @comment ----------------------------------------------
4398: @node Case insensitivity, Comments, Notation, Words
4399: @section Case insensitivity
4400: @cindex case sensitivity
4401: @cindex upper and lower case
4402:
4403: Gforth is case-insensitive; you can enter definitions and invoke
4404: Standard words using upper, lower or mixed case (however,
4405: @pxref{core-idef, Implementation-defined options, Implementation-defined
4406: options}).
4407:
4408: ANS Forth only @i{requires} implementations to recognise Standard words
4409: when they are typed entirely in upper case. Therefore, a Standard
4410: program must use upper case for all Standard words. You can use whatever
4411: case you like for words that you define, but in a Standard program you
4412: have to use the words in the same case that you defined them.
4413:
4414: Gforth supports case sensitivity through @code{table}s (case-sensitive
4415: wordlists, @pxref{Word Lists}).
4416:
4417: Two people have asked how to convert Gforth to be case-sensitive; while
4418: we think this is a bad idea, you can change all wordlists into tables
4419: like this:
4420:
4421: @example
4422: ' table-find forth-wordlist wordlist-map @ !
4423: @end example
4424:
4425: Note that you now have to type the predefined words in the same case
4426: that we defined them, which are varying. You may want to convert them
4427: to your favourite case before doing this operation (I won't explain how,
4428: because if you are even contemplating doing this, you'd better have
4429: enough knowledge of Forth systems to know this already).
4430:
4431: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4432: @section Comments
1.26 crook 4433: @cindex comments
1.21 crook 4434:
1.29 crook 4435: Forth supports two styles of comment; the traditional @i{in-line} comment,
4436: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4437:
1.44 crook 4438:
1.23 crook 4439: doc-(
1.21 crook 4440: doc-\
1.23 crook 4441: doc-\G
1.21 crook 4442:
1.44 crook 4443:
1.21 crook 4444: @node Boolean Flags, Arithmetic, Comments, Words
4445: @section Boolean Flags
1.26 crook 4446: @cindex Boolean flags
1.21 crook 4447:
4448: A Boolean flag is cell-sized. A cell with all bits clear represents the
4449: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4450: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4451: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4452: @c on and off to Memory?
4453: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4454:
1.21 crook 4455: doc-true
4456: doc-false
1.29 crook 4457: doc-on
4458: doc-off
1.21 crook 4459:
1.44 crook 4460:
1.21 crook 4461: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4462: @section Arithmetic
4463: @cindex arithmetic words
4464:
4465: @cindex division with potentially negative operands
4466: Forth arithmetic is not checked, i.e., you will not hear about integer
4467: overflow on addition or multiplication, you may hear about division by
4468: zero if you are lucky. The operator is written after the operands, but
4469: the operands are still in the original order. I.e., the infix @code{2-1}
4470: corresponds to @code{2 1 -}. Forth offers a variety of division
4471: operators. If you perform division with potentially negative operands,
4472: you do not want to use @code{/} or @code{/mod} with its undefined
4473: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4474: former, @pxref{Mixed precision}).
1.26 crook 4475: @comment TODO discuss the different division forms and the std approach
1.1 anton 4476:
4477: @menu
4478: * Single precision::
1.67 anton 4479: * Double precision:: Double-cell integer arithmetic
1.1 anton 4480: * Bitwise operations::
1.67 anton 4481: * Numeric comparison::
1.29 crook 4482: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4483: * Floating Point::
4484: @end menu
4485:
1.67 anton 4486: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4487: @subsection Single precision
4488: @cindex single precision arithmetic words
4489:
1.67 anton 4490: @c !! cell undefined
4491:
4492: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4493: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4494: treat them. For the rules used by the text interpreter for recognising
4495: single-precision integers see @ref{Number Conversion}.
1.21 crook 4496:
1.67 anton 4497: These words are all defined for signed operands, but some of them also
4498: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4499: @code{*}.
1.44 crook 4500:
1.1 anton 4501: doc-+
1.21 crook 4502: doc-1+
1.128 anton 4503: doc-under+
1.1 anton 4504: doc--
1.21 crook 4505: doc-1-
1.1 anton 4506: doc-*
4507: doc-/
4508: doc-mod
4509: doc-/mod
4510: doc-negate
4511: doc-abs
4512: doc-min
4513: doc-max
1.27 crook 4514: doc-floored
1.1 anton 4515:
1.44 crook 4516:
1.67 anton 4517: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4518: @subsection Double precision
4519: @cindex double precision arithmetic words
4520:
1.49 anton 4521: For the rules used by the text interpreter for
4522: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4523:
4524: A double precision number is represented by a cell pair, with the most
1.67 anton 4525: significant cell at the TOS. It is trivial to convert an unsigned single
4526: to a double: simply push a @code{0} onto the TOS. Since numbers are
4527: represented by Gforth using 2's complement arithmetic, converting a
4528: signed single to a (signed) double requires sign-extension across the
4529: most significant cell. This can be achieved using @code{s>d}. The moral
4530: of the story is that you cannot convert a number without knowing whether
4531: it represents an unsigned or a signed number.
1.21 crook 4532:
1.67 anton 4533: These words are all defined for signed operands, but some of them also
4534: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4535:
1.21 crook 4536: doc-s>d
1.67 anton 4537: doc-d>s
1.21 crook 4538: doc-d+
4539: doc-d-
4540: doc-dnegate
4541: doc-dabs
4542: doc-dmin
4543: doc-dmax
4544:
1.44 crook 4545:
1.67 anton 4546: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4547: @subsection Bitwise operations
4548: @cindex bitwise operation words
4549:
4550:
4551: doc-and
4552: doc-or
4553: doc-xor
4554: doc-invert
4555: doc-lshift
4556: doc-rshift
4557: doc-2*
4558: doc-d2*
4559: doc-2/
4560: doc-d2/
4561:
4562:
4563: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4564: @subsection Numeric comparison
4565: @cindex numeric comparison words
4566:
1.67 anton 4567: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4568: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4569:
1.28 crook 4570: doc-<
4571: doc-<=
4572: doc-<>
4573: doc-=
4574: doc->
4575: doc->=
4576:
1.21 crook 4577: doc-0<
1.23 crook 4578: doc-0<=
1.21 crook 4579: doc-0<>
4580: doc-0=
1.23 crook 4581: doc-0>
4582: doc-0>=
1.28 crook 4583:
4584: doc-u<
4585: doc-u<=
1.44 crook 4586: @c u<> and u= exist but are the same as <> and =
1.31 anton 4587: @c doc-u<>
4588: @c doc-u=
1.28 crook 4589: doc-u>
4590: doc-u>=
4591:
4592: doc-within
4593:
4594: doc-d<
4595: doc-d<=
4596: doc-d<>
4597: doc-d=
4598: doc-d>
4599: doc-d>=
1.23 crook 4600:
1.21 crook 4601: doc-d0<
1.23 crook 4602: doc-d0<=
4603: doc-d0<>
1.21 crook 4604: doc-d0=
1.23 crook 4605: doc-d0>
4606: doc-d0>=
4607:
1.21 crook 4608: doc-du<
1.28 crook 4609: doc-du<=
1.44 crook 4610: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4611: @c doc-du<>
4612: @c doc-du=
1.28 crook 4613: doc-du>
4614: doc-du>=
1.1 anton 4615:
1.44 crook 4616:
1.21 crook 4617: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4618: @subsection Mixed precision
4619: @cindex mixed precision arithmetic words
4620:
1.44 crook 4621:
1.1 anton 4622: doc-m+
4623: doc-*/
4624: doc-*/mod
4625: doc-m*
4626: doc-um*
4627: doc-m*/
4628: doc-um/mod
4629: doc-fm/mod
4630: doc-sm/rem
4631:
1.44 crook 4632:
1.21 crook 4633: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4634: @subsection Floating Point
4635: @cindex floating point arithmetic words
4636:
1.49 anton 4637: For the rules used by the text interpreter for
4638: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4639:
1.67 anton 4640: Gforth has a separate floating point stack, but the documentation uses
4641: the unified notation.@footnote{It's easy to generate the separate
4642: notation from that by just separating the floating-point numbers out:
4643: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4644: r3 )}.}
1.1 anton 4645:
4646: @cindex floating-point arithmetic, pitfalls
4647: Floating point numbers have a number of unpleasant surprises for the
4648: unwary (e.g., floating point addition is not associative) and even a few
4649: for the wary. You should not use them unless you know what you are doing
4650: or you don't care that the results you get are totally bogus. If you
4651: want to learn about the problems of floating point numbers (and how to
1.66 anton 4652: avoid them), you might start with @cite{David Goldberg,
4653: @uref{http://www.validgh.com/goldberg/paper.ps,What Every Computer
4654: Scientist Should Know About Floating-Point Arithmetic}, ACM Computing
4655: Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4656:
1.44 crook 4657:
1.21 crook 4658: doc-d>f
4659: doc-f>d
1.1 anton 4660: doc-f+
4661: doc-f-
4662: doc-f*
4663: doc-f/
4664: doc-fnegate
4665: doc-fabs
4666: doc-fmax
4667: doc-fmin
4668: doc-floor
4669: doc-fround
4670: doc-f**
4671: doc-fsqrt
4672: doc-fexp
4673: doc-fexpm1
4674: doc-fln
4675: doc-flnp1
4676: doc-flog
4677: doc-falog
1.32 anton 4678: doc-f2*
4679: doc-f2/
4680: doc-1/f
4681: doc-precision
4682: doc-set-precision
4683:
4684: @cindex angles in trigonometric operations
4685: @cindex trigonometric operations
4686: Angles in floating point operations are given in radians (a full circle
4687: has 2 pi radians).
4688:
1.1 anton 4689: doc-fsin
4690: doc-fcos
4691: doc-fsincos
4692: doc-ftan
4693: doc-fasin
4694: doc-facos
4695: doc-fatan
4696: doc-fatan2
4697: doc-fsinh
4698: doc-fcosh
4699: doc-ftanh
4700: doc-fasinh
4701: doc-facosh
4702: doc-fatanh
1.21 crook 4703: doc-pi
1.28 crook 4704:
1.32 anton 4705: @cindex equality of floats
4706: @cindex floating-point comparisons
1.31 anton 4707: One particular problem with floating-point arithmetic is that comparison
4708: for equality often fails when you would expect it to succeed. For this
4709: reason approximate equality is often preferred (but you still have to
1.67 anton 4710: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4711: differently from what you might expect. The comparison words are:
1.31 anton 4712:
4713: doc-f~rel
4714: doc-f~abs
1.68 anton 4715: doc-f~
1.31 anton 4716: doc-f=
4717: doc-f<>
4718:
4719: doc-f<
4720: doc-f<=
4721: doc-f>
4722: doc-f>=
4723:
1.21 crook 4724: doc-f0<
1.28 crook 4725: doc-f0<=
4726: doc-f0<>
1.21 crook 4727: doc-f0=
1.28 crook 4728: doc-f0>
4729: doc-f0>=
4730:
1.1 anton 4731:
4732: @node Stack Manipulation, Memory, Arithmetic, Words
4733: @section Stack Manipulation
4734: @cindex stack manipulation words
4735:
4736: @cindex floating-point stack in the standard
1.21 crook 4737: Gforth maintains a number of separate stacks:
4738:
1.29 crook 4739: @cindex data stack
4740: @cindex parameter stack
1.21 crook 4741: @itemize @bullet
4742: @item
1.29 crook 4743: A data stack (also known as the @dfn{parameter stack}) -- for
4744: characters, cells, addresses, and double cells.
1.21 crook 4745:
1.29 crook 4746: @cindex floating-point stack
1.21 crook 4747: @item
1.44 crook 4748: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4749:
1.29 crook 4750: @cindex return stack
1.21 crook 4751: @item
1.44 crook 4752: A return stack -- for holding the return addresses of colon
1.32 anton 4753: definitions and other (non-FP) data.
1.21 crook 4754:
1.29 crook 4755: @cindex locals stack
1.21 crook 4756: @item
1.44 crook 4757: A locals stack -- for holding local variables.
1.21 crook 4758: @end itemize
4759:
1.1 anton 4760: @menu
4761: * Data stack::
4762: * Floating point stack::
4763: * Return stack::
4764: * Locals stack::
4765: * Stack pointer manipulation::
4766: @end menu
4767:
4768: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4769: @subsection Data stack
4770: @cindex data stack manipulation words
4771: @cindex stack manipulations words, data stack
4772:
1.44 crook 4773:
1.1 anton 4774: doc-drop
4775: doc-nip
4776: doc-dup
4777: doc-over
4778: doc-tuck
4779: doc-swap
1.21 crook 4780: doc-pick
1.1 anton 4781: doc-rot
4782: doc--rot
4783: doc-?dup
4784: doc-roll
4785: doc-2drop
4786: doc-2nip
4787: doc-2dup
4788: doc-2over
4789: doc-2tuck
4790: doc-2swap
4791: doc-2rot
4792:
1.44 crook 4793:
1.1 anton 4794: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4795: @subsection Floating point stack
4796: @cindex floating-point stack manipulation words
4797: @cindex stack manipulation words, floating-point stack
4798:
1.32 anton 4799: Whilst every sane Forth has a separate floating-point stack, it is not
4800: strictly required; an ANS Forth system could theoretically keep
4801: floating-point numbers on the data stack. As an additional difficulty,
4802: you don't know how many cells a floating-point number takes. It is
4803: reportedly possible to write words in a way that they work also for a
4804: unified stack model, but we do not recommend trying it. Instead, just
4805: say that your program has an environmental dependency on a separate
4806: floating-point stack.
4807:
4808: doc-floating-stack
4809:
1.1 anton 4810: doc-fdrop
4811: doc-fnip
4812: doc-fdup
4813: doc-fover
4814: doc-ftuck
4815: doc-fswap
1.21 crook 4816: doc-fpick
1.1 anton 4817: doc-frot
4818:
1.44 crook 4819:
1.1 anton 4820: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4821: @subsection Return stack
4822: @cindex return stack manipulation words
4823: @cindex stack manipulation words, return stack
4824:
1.32 anton 4825: @cindex return stack and locals
4826: @cindex locals and return stack
4827: A Forth system is allowed to keep local variables on the
4828: return stack. This is reasonable, as local variables usually eliminate
4829: the need to use the return stack explicitly. So, if you want to produce
4830: a standard compliant program and you are using local variables in a
4831: word, forget about return stack manipulations in that word (refer to the
4832: standard document for the exact rules).
4833:
1.1 anton 4834: doc->r
4835: doc-r>
4836: doc-r@
4837: doc-rdrop
4838: doc-2>r
4839: doc-2r>
4840: doc-2r@
4841: doc-2rdrop
4842:
1.44 crook 4843:
1.1 anton 4844: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4845: @subsection Locals stack
4846:
1.78 anton 4847: Gforth uses an extra locals stack. It is described, along with the
4848: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4849:
1.1 anton 4850: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4851: @subsection Stack pointer manipulation
4852: @cindex stack pointer manipulation words
4853:
1.44 crook 4854: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4855: doc-sp0
1.1 anton 4856: doc-sp@
4857: doc-sp!
1.21 crook 4858: doc-fp0
1.1 anton 4859: doc-fp@
4860: doc-fp!
1.21 crook 4861: doc-rp0
1.1 anton 4862: doc-rp@
4863: doc-rp!
1.21 crook 4864: doc-lp0
1.1 anton 4865: doc-lp@
4866: doc-lp!
4867:
1.44 crook 4868:
1.1 anton 4869: @node Memory, Control Structures, Stack Manipulation, Words
4870: @section Memory
1.26 crook 4871: @cindex memory words
1.1 anton 4872:
1.32 anton 4873: @menu
4874: * Memory model::
4875: * Dictionary allocation::
4876: * Heap Allocation::
4877: * Memory Access::
4878: * Address arithmetic::
4879: * Memory Blocks::
4880: @end menu
4881:
1.67 anton 4882: In addition to the standard Forth memory allocation words, there is also
4883: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4884: garbage collector}.
4885:
1.32 anton 4886: @node Memory model, Dictionary allocation, Memory, Memory
4887: @subsection ANS Forth and Gforth memory models
4888:
4889: @c The ANS Forth description is a mess (e.g., is the heap part of
4890: @c the dictionary?), so let's not stick to closely with it.
4891:
1.67 anton 4892: ANS Forth considers a Forth system as consisting of several address
4893: spaces, of which only @dfn{data space} is managed and accessible with
4894: the memory words. Memory not necessarily in data space includes the
4895: stacks, the code (called code space) and the headers (called name
4896: space). In Gforth everything is in data space, but the code for the
4897: primitives is usually read-only.
1.32 anton 4898:
4899: Data space is divided into a number of areas: The (data space portion of
4900: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4901: refer to the search data structure embodied in word lists and headers,
4902: because it is used for looking up names, just as you would in a
4903: conventional dictionary.}, the heap, and a number of system-allocated
4904: buffers.
4905:
1.68 anton 4906: @cindex address arithmetic restrictions, ANS vs. Gforth
4907: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 4908: In ANS Forth data space is also divided into contiguous regions. You
4909: can only use address arithmetic within a contiguous region, not between
4910: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 4911: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 4912: allocation}).
4913:
4914: Gforth provides one big address space, and address arithmetic can be
4915: performed between any addresses. However, in the dictionary headers or
4916: code are interleaved with data, so almost the only contiguous data space
4917: regions there are those described by ANS Forth as contiguous; but you
4918: can be sure that the dictionary is allocated towards increasing
4919: addresses even between contiguous regions. The memory order of
4920: allocations in the heap is platform-dependent (and possibly different
4921: from one run to the next).
4922:
1.27 crook 4923:
1.32 anton 4924: @node Dictionary allocation, Heap Allocation, Memory model, Memory
4925: @subsection Dictionary allocation
1.27 crook 4926: @cindex reserving data space
4927: @cindex data space - reserving some
4928:
1.32 anton 4929: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
4930: you want to deallocate X, you also deallocate everything
4931: allocated after X.
4932:
1.68 anton 4933: @cindex contiguous regions in dictionary allocation
1.32 anton 4934: The allocations using the words below are contiguous and grow the region
4935: towards increasing addresses. Other words that allocate dictionary
4936: memory of any kind (i.e., defining words including @code{:noname}) end
4937: the contiguous region and start a new one.
4938:
4939: In ANS Forth only @code{create}d words are guaranteed to produce an
4940: address that is the start of the following contiguous region. In
4941: particular, the cell allocated by @code{variable} is not guaranteed to
4942: be contiguous with following @code{allot}ed memory.
4943:
4944: You can deallocate memory by using @code{allot} with a negative argument
4945: (with some restrictions, see @code{allot}). For larger deallocations use
4946: @code{marker}.
1.27 crook 4947:
1.29 crook 4948:
1.27 crook 4949: doc-here
4950: doc-unused
4951: doc-allot
4952: doc-c,
1.29 crook 4953: doc-f,
1.27 crook 4954: doc-,
4955: doc-2,
4956:
1.32 anton 4957: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
4958: course you should allocate memory in an aligned way, too. I.e., before
4959: allocating allocating a cell, @code{here} must be cell-aligned, etc.
4960: The words below align @code{here} if it is not already. Basically it is
4961: only already aligned for a type, if the last allocation was a multiple
4962: of the size of this type and if @code{here} was aligned for this type
4963: before.
4964:
4965: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
4966: ANS Forth (@code{maxalign}ed in Gforth).
4967:
4968: doc-align
4969: doc-falign
4970: doc-sfalign
4971: doc-dfalign
4972: doc-maxalign
4973: doc-cfalign
4974:
4975:
4976: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
4977: @subsection Heap allocation
4978: @cindex heap allocation
4979: @cindex dynamic allocation of memory
4980: @cindex memory-allocation word set
4981:
1.68 anton 4982: @cindex contiguous regions and heap allocation
1.32 anton 4983: Heap allocation supports deallocation of allocated memory in any
4984: order. Dictionary allocation is not affected by it (i.e., it does not
4985: end a contiguous region). In Gforth, these words are implemented using
4986: the standard C library calls malloc(), free() and resize().
4987:
1.68 anton 4988: The memory region produced by one invocation of @code{allocate} or
4989: @code{resize} is internally contiguous. There is no contiguity between
4990: such a region and any other region (including others allocated from the
4991: heap).
4992:
1.32 anton 4993: doc-allocate
4994: doc-free
4995: doc-resize
4996:
1.27 crook 4997:
1.32 anton 4998: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 4999: @subsection Memory Access
5000: @cindex memory access words
5001:
5002: doc-@
5003: doc-!
5004: doc-+!
5005: doc-c@
5006: doc-c!
5007: doc-2@
5008: doc-2!
5009: doc-f@
5010: doc-f!
5011: doc-sf@
5012: doc-sf!
5013: doc-df@
5014: doc-df!
1.144 anton 5015: doc-sw@
5016: doc-uw@
5017: doc-w!
5018: doc-sl@
5019: doc-ul@
5020: doc-l!
1.68 anton 5021:
1.32 anton 5022: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5023: @subsection Address arithmetic
1.1 anton 5024: @cindex address arithmetic words
5025:
1.67 anton 5026: Address arithmetic is the foundation on which you can build data
5027: structures like arrays, records (@pxref{Structures}) and objects
5028: (@pxref{Object-oriented Forth}).
1.32 anton 5029:
1.68 anton 5030: @cindex address unit
5031: @cindex au (address unit)
1.1 anton 5032: ANS Forth does not specify the sizes of the data types. Instead, it
5033: offers a number of words for computing sizes and doing address
1.29 crook 5034: arithmetic. Address arithmetic is performed in terms of address units
5035: (aus); on most systems the address unit is one byte. Note that a
5036: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5037: platforms where it is a noop, it compiles to nothing).
1.1 anton 5038:
1.67 anton 5039: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5040: you have the address of a cell, perform @code{1 cells +}, and you will
5041: have the address of the next cell.
5042:
1.68 anton 5043: @cindex contiguous regions and address arithmetic
1.67 anton 5044: In ANS Forth you can perform address arithmetic only within a contiguous
5045: region, i.e., if you have an address into one region, you can only add
5046: and subtract such that the result is still within the region; you can
5047: only subtract or compare addresses from within the same contiguous
5048: region. Reasons: several contiguous regions can be arranged in memory
5049: in any way; on segmented systems addresses may have unusual
5050: representations, such that address arithmetic only works within a
5051: region. Gforth provides a few more guarantees (linear address space,
5052: dictionary grows upwards), but in general I have found it easy to stay
5053: within contiguous regions (exception: computing and comparing to the
5054: address just beyond the end of an array).
5055:
1.1 anton 5056: @cindex alignment of addresses for types
5057: ANS Forth also defines words for aligning addresses for specific
5058: types. Many computers require that accesses to specific data types
5059: must only occur at specific addresses; e.g., that cells may only be
5060: accessed at addresses divisible by 4. Even if a machine allows unaligned
5061: accesses, it can usually perform aligned accesses faster.
5062:
5063: For the performance-conscious: alignment operations are usually only
5064: necessary during the definition of a data structure, not during the
5065: (more frequent) accesses to it.
5066:
5067: ANS Forth defines no words for character-aligning addresses. This is not
5068: an oversight, but reflects the fact that addresses that are not
5069: char-aligned have no use in the standard and therefore will not be
5070: created.
5071:
5072: @cindex @code{CREATE} and alignment
1.29 crook 5073: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5074: are cell-aligned; in addition, Gforth guarantees that these addresses
5075: are aligned for all purposes.
5076:
1.26 crook 5077: Note that the ANS Forth word @code{char} has nothing to do with address
5078: arithmetic.
1.1 anton 5079:
1.44 crook 5080:
1.1 anton 5081: doc-chars
5082: doc-char+
5083: doc-cells
5084: doc-cell+
5085: doc-cell
5086: doc-aligned
5087: doc-floats
5088: doc-float+
5089: doc-float
5090: doc-faligned
5091: doc-sfloats
5092: doc-sfloat+
5093: doc-sfaligned
5094: doc-dfloats
5095: doc-dfloat+
5096: doc-dfaligned
5097: doc-maxaligned
5098: doc-cfaligned
5099: doc-address-unit-bits
1.145 anton 5100: doc-/w
5101: doc-/l
1.44 crook 5102:
1.32 anton 5103: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5104: @subsection Memory Blocks
5105: @cindex memory block words
1.27 crook 5106: @cindex character strings - moving and copying
5107:
1.49 anton 5108: Memory blocks often represent character strings; For ways of storing
5109: character strings in memory see @ref{String Formats}. For other
5110: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5111:
1.67 anton 5112: A few of these words work on address unit blocks. In that case, you
5113: usually have to insert @code{CHARS} before the word when working on
5114: character strings. Most words work on character blocks, and expect a
5115: char-aligned address.
5116:
5117: When copying characters between overlapping memory regions, use
5118: @code{chars move} or choose carefully between @code{cmove} and
5119: @code{cmove>}.
1.44 crook 5120:
1.1 anton 5121: doc-move
5122: doc-erase
5123: doc-cmove
5124: doc-cmove>
5125: doc-fill
5126: doc-blank
1.21 crook 5127: doc-compare
1.111 anton 5128: doc-str=
5129: doc-str<
5130: doc-string-prefix?
1.21 crook 5131: doc-search
1.27 crook 5132: doc--trailing
5133: doc-/string
1.82 anton 5134: doc-bounds
1.141 anton 5135: doc-pad
1.111 anton 5136:
1.27 crook 5137: @comment TODO examples
5138:
1.1 anton 5139:
1.26 crook 5140: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5141: @section Control Structures
5142: @cindex control structures
5143:
1.33 anton 5144: Control structures in Forth cannot be used interpretively, only in a
5145: colon definition@footnote{To be precise, they have no interpretation
5146: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5147: not like this limitation, but have not seen a satisfying way around it
5148: yet, although many schemes have been proposed.
1.1 anton 5149:
5150: @menu
1.33 anton 5151: * Selection:: IF ... ELSE ... ENDIF
5152: * Simple Loops:: BEGIN ...
1.29 crook 5153: * Counted Loops:: DO
1.67 anton 5154: * Arbitrary control structures::
5155: * Calls and returns::
1.1 anton 5156: * Exception Handling::
5157: @end menu
5158:
5159: @node Selection, Simple Loops, Control Structures, Control Structures
5160: @subsection Selection
5161: @cindex selection control structures
5162: @cindex control structures for selection
5163:
5164: @cindex @code{IF} control structure
5165: @example
1.29 crook 5166: @i{flag}
1.1 anton 5167: IF
1.29 crook 5168: @i{code}
1.1 anton 5169: ENDIF
5170: @end example
1.21 crook 5171: @noindent
1.33 anton 5172:
1.44 crook 5173: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5174: with any bit set represents truth) @i{code} is executed.
1.33 anton 5175:
1.1 anton 5176: @example
1.29 crook 5177: @i{flag}
1.1 anton 5178: IF
1.29 crook 5179: @i{code1}
1.1 anton 5180: ELSE
1.29 crook 5181: @i{code2}
1.1 anton 5182: ENDIF
5183: @end example
5184:
1.44 crook 5185: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5186: executed.
1.33 anton 5187:
1.1 anton 5188: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5189: standard, and @code{ENDIF} is not, although it is quite popular. We
5190: recommend using @code{ENDIF}, because it is less confusing for people
5191: who also know other languages (and is not prone to reinforcing negative
5192: prejudices against Forth in these people). Adding @code{ENDIF} to a
5193: system that only supplies @code{THEN} is simple:
5194: @example
1.82 anton 5195: : ENDIF POSTPONE then ; immediate
1.1 anton 5196: @end example
5197:
5198: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5199: (adv.)} has the following meanings:
5200: @quotation
5201: ... 2b: following next after in order ... 3d: as a necessary consequence
5202: (if you were there, then you saw them).
5203: @end quotation
5204: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5205: and many other programming languages has the meaning 3d.]
5206:
1.21 crook 5207: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5208: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5209: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5210: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5211: @file{compat/control.fs}.
5212:
5213: @cindex @code{CASE} control structure
5214: @example
1.29 crook 5215: @i{n}
1.1 anton 5216: CASE
1.29 crook 5217: @i{n1} OF @i{code1} ENDOF
5218: @i{n2} OF @i{code2} ENDOF
1.1 anton 5219: @dots{}
1.68 anton 5220: ( n ) @i{default-code} ( n )
1.131 anton 5221: ENDCASE ( )
1.1 anton 5222: @end example
5223:
1.131 anton 5224: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5225: no @i{ni} matches, the optional @i{default-code} is executed. The
5226: optional default case can be added by simply writing the code after
5227: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5228: but must not consume it. The value @i{n} is consumed by this
5229: construction (either by a OF that matches, or by the ENDCASE, if no OF
5230: matches).
1.1 anton 5231:
1.69 anton 5232: @progstyle
1.131 anton 5233: To keep the code understandable, you should ensure that you change the
5234: stack in the same way (wrt. number and types of stack items consumed
5235: and pushed) on all paths through a selection construct.
1.69 anton 5236:
1.1 anton 5237: @node Simple Loops, Counted Loops, Selection, Control Structures
5238: @subsection Simple Loops
5239: @cindex simple loops
5240: @cindex loops without count
5241:
5242: @cindex @code{WHILE} loop
5243: @example
5244: BEGIN
1.29 crook 5245: @i{code1}
5246: @i{flag}
1.1 anton 5247: WHILE
1.29 crook 5248: @i{code2}
1.1 anton 5249: REPEAT
5250: @end example
5251:
1.29 crook 5252: @i{code1} is executed and @i{flag} is computed. If it is true,
5253: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5254: false, execution continues after the @code{REPEAT}.
5255:
5256: @cindex @code{UNTIL} loop
5257: @example
5258: BEGIN
1.29 crook 5259: @i{code}
5260: @i{flag}
1.1 anton 5261: UNTIL
5262: @end example
5263:
1.29 crook 5264: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5265:
1.69 anton 5266: @progstyle
5267: To keep the code understandable, a complete iteration of the loop should
5268: not change the number and types of the items on the stacks.
5269:
1.1 anton 5270: @cindex endless loop
5271: @cindex loops, endless
5272: @example
5273: BEGIN
1.29 crook 5274: @i{code}
1.1 anton 5275: AGAIN
5276: @end example
5277:
5278: This is an endless loop.
5279:
5280: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5281: @subsection Counted Loops
5282: @cindex counted loops
5283: @cindex loops, counted
5284: @cindex @code{DO} loops
5285:
5286: The basic counted loop is:
5287: @example
1.29 crook 5288: @i{limit} @i{start}
1.1 anton 5289: ?DO
1.29 crook 5290: @i{body}
1.1 anton 5291: LOOP
5292: @end example
5293:
1.29 crook 5294: This performs one iteration for every integer, starting from @i{start}
5295: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5296: accessed with @code{i}. For example, the loop:
1.1 anton 5297: @example
5298: 10 0 ?DO
5299: i .
5300: LOOP
5301: @end example
1.21 crook 5302: @noindent
5303: prints @code{0 1 2 3 4 5 6 7 8 9}
5304:
1.1 anton 5305: The index of the innermost loop can be accessed with @code{i}, the index
5306: of the next loop with @code{j}, and the index of the third loop with
5307: @code{k}.
5308:
1.44 crook 5309:
1.1 anton 5310: doc-i
5311: doc-j
5312: doc-k
5313:
1.44 crook 5314:
1.1 anton 5315: The loop control data are kept on the return stack, so there are some
1.21 crook 5316: restrictions on mixing return stack accesses and counted loop words. In
5317: particuler, if you put values on the return stack outside the loop, you
5318: cannot read them inside the loop@footnote{well, not in a way that is
5319: portable.}. If you put values on the return stack within a loop, you
5320: have to remove them before the end of the loop and before accessing the
5321: index of the loop.
1.1 anton 5322:
5323: There are several variations on the counted loop:
5324:
1.21 crook 5325: @itemize @bullet
5326: @item
5327: @code{LEAVE} leaves the innermost counted loop immediately; execution
5328: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5329:
5330: @example
5331: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5332: @end example
5333: prints @code{0 1 2 3}
5334:
1.1 anton 5335:
1.21 crook 5336: @item
5337: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5338: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5339: return stack so @code{EXIT} can get to its return address. For example:
5340:
5341: @example
5342: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5343: @end example
5344: prints @code{0 1 2 3}
5345:
5346:
5347: @item
1.29 crook 5348: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5349: (and @code{LOOP} iterates until they become equal by wrap-around
5350: arithmetic). This behaviour is usually not what you want. Therefore,
5351: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5352: @code{?DO}), which do not enter the loop if @i{start} is greater than
5353: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5354: unsigned loop parameters.
5355:
1.21 crook 5356: @item
5357: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5358: the loop, independent of the loop parameters. Do not use @code{DO}, even
5359: if you know that the loop is entered in any case. Such knowledge tends
5360: to become invalid during maintenance of a program, and then the
5361: @code{DO} will make trouble.
5362:
5363: @item
1.29 crook 5364: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5365: index by @i{n} instead of by 1. The loop is terminated when the border
5366: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5367:
1.21 crook 5368: @example
5369: 4 0 +DO i . 2 +LOOP
5370: @end example
5371: @noindent
5372: prints @code{0 2}
5373:
5374: @example
5375: 4 1 +DO i . 2 +LOOP
5376: @end example
5377: @noindent
5378: prints @code{1 3}
1.1 anton 5379:
1.68 anton 5380: @item
1.1 anton 5381: @cindex negative increment for counted loops
5382: @cindex counted loops with negative increment
1.29 crook 5383: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5384:
1.21 crook 5385: @example
5386: -1 0 ?DO i . -1 +LOOP
5387: @end example
5388: @noindent
5389: prints @code{0 -1}
1.1 anton 5390:
1.21 crook 5391: @example
5392: 0 0 ?DO i . -1 +LOOP
5393: @end example
5394: prints nothing.
1.1 anton 5395:
1.29 crook 5396: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5397: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5398: index by @i{u} each iteration. The loop is terminated when the border
5399: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5400: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5401:
1.21 crook 5402: @example
5403: -2 0 -DO i . 1 -LOOP
5404: @end example
5405: @noindent
5406: prints @code{0 -1}
1.1 anton 5407:
1.21 crook 5408: @example
5409: -1 0 -DO i . 1 -LOOP
5410: @end example
5411: @noindent
5412: prints @code{0}
5413:
5414: @example
5415: 0 0 -DO i . 1 -LOOP
5416: @end example
5417: @noindent
5418: prints nothing.
1.1 anton 5419:
1.21 crook 5420: @end itemize
1.1 anton 5421:
5422: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5423: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5424: for these words that uses only standard words is provided in
5425: @file{compat/loops.fs}.
1.1 anton 5426:
5427:
5428: @cindex @code{FOR} loops
1.26 crook 5429: Another counted loop is:
1.1 anton 5430: @example
1.29 crook 5431: @i{n}
1.1 anton 5432: FOR
1.29 crook 5433: @i{body}
1.1 anton 5434: NEXT
5435: @end example
5436: This is the preferred loop of native code compiler writers who are too
1.26 crook 5437: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5438: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5439: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5440: Forth systems may behave differently, even if they support @code{FOR}
5441: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5442:
5443: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5444: @subsection Arbitrary control structures
5445: @cindex control structures, user-defined
5446:
5447: @cindex control-flow stack
5448: ANS Forth permits and supports using control structures in a non-nested
5449: way. Information about incomplete control structures is stored on the
5450: control-flow stack. This stack may be implemented on the Forth data
5451: stack, and this is what we have done in Gforth.
5452:
5453: @cindex @code{orig}, control-flow stack item
5454: @cindex @code{dest}, control-flow stack item
5455: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5456: entry represents a backward branch target. A few words are the basis for
5457: building any control structure possible (except control structures that
5458: need storage, like calls, coroutines, and backtracking).
5459:
1.44 crook 5460:
1.1 anton 5461: doc-if
5462: doc-ahead
5463: doc-then
5464: doc-begin
5465: doc-until
5466: doc-again
5467: doc-cs-pick
5468: doc-cs-roll
5469:
1.44 crook 5470:
1.21 crook 5471: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5472: manipulate the control-flow stack in a portable way. Without them, you
5473: would need to know how many stack items are occupied by a control-flow
5474: entry (many systems use one cell. In Gforth they currently take three,
5475: but this may change in the future).
5476:
1.1 anton 5477: Some standard control structure words are built from these words:
5478:
1.44 crook 5479:
1.1 anton 5480: doc-else
5481: doc-while
5482: doc-repeat
5483:
1.44 crook 5484:
5485: @noindent
1.1 anton 5486: Gforth adds some more control-structure words:
5487:
1.44 crook 5488:
1.1 anton 5489: doc-endif
5490: doc-?dup-if
5491: doc-?dup-0=-if
5492:
1.44 crook 5493:
5494: @noindent
1.1 anton 5495: Counted loop words constitute a separate group of words:
5496:
1.44 crook 5497:
1.1 anton 5498: doc-?do
5499: doc-+do
5500: doc-u+do
5501: doc--do
5502: doc-u-do
5503: doc-do
5504: doc-for
5505: doc-loop
5506: doc-+loop
5507: doc--loop
5508: doc-next
5509: doc-leave
5510: doc-?leave
5511: doc-unloop
5512: doc-done
5513:
1.44 crook 5514:
1.21 crook 5515: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5516: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5517: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5518: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5519: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5520: resolved (by using one of the loop-ending words or @code{DONE}).
5521:
1.44 crook 5522: @noindent
1.26 crook 5523: Another group of control structure words are:
1.1 anton 5524:
1.44 crook 5525:
1.1 anton 5526: doc-case
5527: doc-endcase
5528: doc-of
5529: doc-endof
5530:
1.44 crook 5531:
1.21 crook 5532: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5533: @code{CS-ROLL}.
1.1 anton 5534:
5535: @subsubsection Programming Style
1.47 crook 5536: @cindex control structures programming style
5537: @cindex programming style, arbitrary control structures
1.1 anton 5538:
5539: In order to ensure readability we recommend that you do not create
5540: arbitrary control structures directly, but define new control structure
5541: words for the control structure you want and use these words in your
1.26 crook 5542: program. For example, instead of writing:
1.1 anton 5543:
5544: @example
1.26 crook 5545: BEGIN
1.1 anton 5546: ...
1.26 crook 5547: IF [ 1 CS-ROLL ]
1.1 anton 5548: ...
1.26 crook 5549: AGAIN THEN
1.1 anton 5550: @end example
5551:
1.21 crook 5552: @noindent
1.1 anton 5553: we recommend defining control structure words, e.g.,
5554:
5555: @example
1.26 crook 5556: : WHILE ( DEST -- ORIG DEST )
5557: POSTPONE IF
5558: 1 CS-ROLL ; immediate
5559:
5560: : REPEAT ( orig dest -- )
5561: POSTPONE AGAIN
5562: POSTPONE THEN ; immediate
1.1 anton 5563: @end example
5564:
1.21 crook 5565: @noindent
1.1 anton 5566: and then using these to create the control structure:
5567:
5568: @example
1.26 crook 5569: BEGIN
1.1 anton 5570: ...
1.26 crook 5571: WHILE
1.1 anton 5572: ...
1.26 crook 5573: REPEAT
1.1 anton 5574: @end example
5575:
5576: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5577: @code{WHILE} are predefined, so in this example it would not be
5578: necessary to define them.
5579:
5580: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5581: @subsection Calls and returns
5582: @cindex calling a definition
5583: @cindex returning from a definition
5584:
1.3 anton 5585: @cindex recursive definitions
5586: A definition can be called simply be writing the name of the definition
1.26 crook 5587: to be called. Normally a definition is invisible during its own
1.3 anton 5588: definition. If you want to write a directly recursive definition, you
1.26 crook 5589: can use @code{recursive} to make the current definition visible, or
5590: @code{recurse} to call the current definition directly.
1.3 anton 5591:
1.44 crook 5592:
1.3 anton 5593: doc-recursive
5594: doc-recurse
5595:
1.44 crook 5596:
1.21 crook 5597: @comment TODO add example of the two recursion methods
1.12 anton 5598: @quotation
5599: @progstyle
5600: I prefer using @code{recursive} to @code{recurse}, because calling the
5601: definition by name is more descriptive (if the name is well-chosen) than
5602: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5603: implementation, it is much better to read (and think) ``now sort the
5604: partitions'' than to read ``now do a recursive call''.
5605: @end quotation
1.3 anton 5606:
1.29 crook 5607: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5608:
5609: @example
1.28 crook 5610: Defer foo
1.3 anton 5611:
5612: : bar ( ... -- ... )
5613: ... foo ... ;
5614:
5615: :noname ( ... -- ... )
5616: ... bar ... ;
5617: IS foo
5618: @end example
5619:
1.44 crook 5620: Deferred words are discussed in more detail in @ref{Deferred words}.
1.33 anton 5621:
1.26 crook 5622: The current definition returns control to the calling definition when
1.33 anton 5623: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5624:
5625: doc-exit
5626: doc-;s
5627:
1.44 crook 5628:
1.1 anton 5629: @node Exception Handling, , Calls and returns, Control Structures
5630: @subsection Exception Handling
1.26 crook 5631: @cindex exceptions
1.1 anton 5632:
1.68 anton 5633: @c quit is a very bad idea for error handling,
5634: @c because it does not translate into a THROW
5635: @c it also does not belong into this chapter
5636:
5637: If a word detects an error condition that it cannot handle, it can
5638: @code{throw} an exception. In the simplest case, this will terminate
5639: your program, and report an appropriate error.
1.21 crook 5640:
1.68 anton 5641: doc-throw
1.1 anton 5642:
1.69 anton 5643: @code{Throw} consumes a cell-sized error number on the stack. There are
5644: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5645: Gforth (and most other systems) you can use the iors produced by various
5646: words as error numbers (e.g., a typical use of @code{allocate} is
5647: @code{allocate throw}). Gforth also provides the word @code{exception}
5648: to define your own error numbers (with decent error reporting); an ANS
5649: Forth version of this word (but without the error messages) is available
5650: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5651: numbers (anything outside the range -4095..0), but won't get nice error
5652: messages, only numbers. For example, try:
5653:
5654: @example
1.69 anton 5655: -10 throw \ ANS defined
5656: -267 throw \ system defined
5657: s" my error" exception throw \ user defined
5658: 7 throw \ arbitrary number
1.68 anton 5659: @end example
5660:
5661: doc---exception-exception
1.1 anton 5662:
1.69 anton 5663: A common idiom to @code{THROW} a specific error if a flag is true is
5664: this:
5665:
5666: @example
5667: @code{( flag ) 0<> @i{errno} and throw}
5668: @end example
5669:
5670: Your program can provide exception handlers to catch exceptions. An
5671: exception handler can be used to correct the problem, or to clean up
5672: some data structures and just throw the exception to the next exception
5673: handler. Note that @code{throw} jumps to the dynamically innermost
5674: exception handler. The system's exception handler is outermost, and just
5675: prints an error and restarts command-line interpretation (or, in batch
5676: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5677:
1.68 anton 5678: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5679:
1.68 anton 5680: doc-catch
1.160 anton 5681: doc-nothrow
1.68 anton 5682:
5683: The most common use of exception handlers is to clean up the state when
5684: an error happens. E.g.,
1.1 anton 5685:
1.26 crook 5686: @example
1.68 anton 5687: base @ >r hex \ actually the hex should be inside foo, or we h
5688: ['] foo catch ( nerror|0 )
5689: r> base !
1.69 anton 5690: ( nerror|0 ) throw \ pass it on
1.26 crook 5691: @end example
1.1 anton 5692:
1.69 anton 5693: A use of @code{catch} for handling the error @code{myerror} might look
5694: like this:
1.44 crook 5695:
1.68 anton 5696: @example
1.69 anton 5697: ['] foo catch
5698: CASE
1.160 anton 5699: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5700: dup throw \ default: pass other errors on, do nothing on non-errors
5701: ENDCASE
1.68 anton 5702: @end example
1.44 crook 5703:
1.68 anton 5704: Having to wrap the code into a separate word is often cumbersome,
5705: therefore Gforth provides an alternative syntax:
1.1 anton 5706:
5707: @example
1.69 anton 5708: TRY
1.68 anton 5709: @i{code1}
1.160 anton 5710: RECOVER
1.68 anton 5711: @i{code2} \ optional
1.69 anton 5712: ENDTRY
1.1 anton 5713: @end example
5714:
1.68 anton 5715: This performs @i{Code1}. If @i{code1} completes normally, execution
5716: continues after the @code{endtry}. If @i{Code1} throws, the stacks are
5717: reset to the state during @code{try}, the throw value is pushed on the
5718: data stack, and execution constinues at @i{code2}, and finally falls
1.92 anton 5719: through the @code{endtry} into the following code.
1.26 crook 5720:
1.68 anton 5721: doc-try
5722: doc-recover
5723: doc-endtry
1.26 crook 5724:
1.69 anton 5725: The cleanup example from above in this syntax:
1.26 crook 5726:
1.68 anton 5727: @example
1.69 anton 5728: base @ >r TRY
1.68 anton 5729: hex foo \ now the hex is placed correctly
1.69 anton 5730: 0 \ value for throw
1.92 anton 5731: RECOVER ENDTRY
1.68 anton 5732: r> base ! throw
1.1 anton 5733: @end example
5734:
1.69 anton 5735: And here's the error handling example:
1.1 anton 5736:
1.68 anton 5737: @example
1.69 anton 5738: TRY
1.68 anton 5739: foo
1.69 anton 5740: RECOVER
5741: CASE
1.160 anton 5742: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5743: throw \ pass other errors on
5744: ENDCASE
5745: ENDTRY
1.68 anton 5746: @end example
1.1 anton 5747:
1.69 anton 5748: @progstyle
5749: As usual, you should ensure that the stack depth is statically known at
5750: the end: either after the @code{throw} for passing on errors, or after
5751: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5752: selection construct for handling the error).
5753:
1.68 anton 5754: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5755: and you can provide an error message. @code{Abort} just produces an
5756: ``Aborted'' error.
1.1 anton 5757:
1.68 anton 5758: The problem with these words is that exception handlers cannot
5759: differentiate between different @code{abort"}s; they just look like
5760: @code{-2 throw} to them (the error message cannot be accessed by
5761: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5762: exception handlers.
1.44 crook 5763:
1.68 anton 5764: doc-abort"
1.26 crook 5765: doc-abort
1.29 crook 5766:
5767:
1.44 crook 5768:
1.29 crook 5769: @c -------------------------------------------------------------
1.47 crook 5770: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5771: @section Defining Words
5772: @cindex defining words
5773:
1.47 crook 5774: Defining words are used to extend Forth by creating new entries in the dictionary.
5775:
1.29 crook 5776: @menu
1.67 anton 5777: * CREATE::
1.44 crook 5778: * Variables:: Variables and user variables
1.67 anton 5779: * Constants::
1.44 crook 5780: * Values:: Initialised variables
1.67 anton 5781: * Colon Definitions::
1.44 crook 5782: * Anonymous Definitions:: Definitions without names
1.69 anton 5783: * Supplying names:: Passing definition names as strings
1.67 anton 5784: * User-defined Defining Words::
1.44 crook 5785: * Deferred words:: Allow forward references
1.67 anton 5786: * Aliases::
1.29 crook 5787: @end menu
5788:
1.44 crook 5789: @node CREATE, Variables, Defining Words, Defining Words
5790: @subsection @code{CREATE}
1.29 crook 5791: @cindex simple defining words
5792: @cindex defining words, simple
5793:
5794: Defining words are used to create new entries in the dictionary. The
5795: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5796: this:
5797:
5798: @example
5799: CREATE new-word1
5800: @end example
5801:
1.69 anton 5802: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5803: input stream (@code{new-word1} in our example). It generates a
5804: dictionary entry for @code{new-word1}. When @code{new-word1} is
5805: executed, all that it does is leave an address on the stack. The address
5806: represents the value of the data space pointer (@code{HERE}) at the time
5807: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5808: associating a name with the address of a region of memory.
1.29 crook 5809:
1.34 anton 5810: doc-create
5811:
1.69 anton 5812: Note that in ANS Forth guarantees only for @code{create} that its body
5813: is in dictionary data space (i.e., where @code{here}, @code{allot}
5814: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5815: @code{create}d words can be modified with @code{does>}
5816: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5817: can only be applied to @code{create}d words.
5818:
1.29 crook 5819: By extending this example to reserve some memory in data space, we end
1.69 anton 5820: up with something like a @i{variable}. Here are two different ways to do
5821: it:
1.29 crook 5822:
5823: @example
5824: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5825: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5826: @end example
5827:
5828: The variable can be examined and modified using @code{@@} (``fetch'') and
5829: @code{!} (``store'') like this:
5830:
5831: @example
5832: new-word2 @@ . \ get address, fetch from it and display
5833: 1234 new-word2 ! \ new value, get address, store to it
5834: @end example
5835:
1.44 crook 5836: @cindex arrays
5837: A similar mechanism can be used to create arrays. For example, an
5838: 80-character text input buffer:
1.29 crook 5839:
5840: @example
1.44 crook 5841: CREATE text-buf 80 chars allot
5842:
5843: text-buf 0 chars c@@ \ the 1st character (offset 0)
5844: text-buf 3 chars c@@ \ the 4th character (offset 3)
5845: @end example
1.29 crook 5846:
1.44 crook 5847: You can build arbitrarily complex data structures by allocating
1.49 anton 5848: appropriate areas of memory. For further discussions of this, and to
1.66 anton 5849: learn about some Gforth tools that make it easier,
1.49 anton 5850: @xref{Structures}.
1.44 crook 5851:
5852:
5853: @node Variables, Constants, CREATE, Defining Words
5854: @subsection Variables
5855: @cindex variables
5856:
5857: The previous section showed how a sequence of commands could be used to
5858: generate a variable. As a final refinement, the whole code sequence can
5859: be wrapped up in a defining word (pre-empting the subject of the next
5860: section), making it easier to create new variables:
5861:
5862: @example
5863: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
5864: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
5865:
5866: myvariableX foo \ variable foo starts off with an unknown value
5867: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 5868:
5869: 45 3 * foo ! \ set foo to 135
5870: 1234 joe ! \ set joe to 1234
5871: 3 joe +! \ increment joe by 3.. to 1237
5872: @end example
5873:
5874: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 5875: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 5876: guarantee that a @code{Variable} is initialised when it is created
5877: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
5878: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
5879: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 5880: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 5881: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 5882: store a boolean, you can use @code{on} and @code{off} to toggle its
5883: state.
1.29 crook 5884:
1.34 anton 5885: doc-variable
5886: doc-2variable
5887: doc-fvariable
5888:
1.29 crook 5889: @cindex user variables
5890: @cindex user space
5891: The defining word @code{User} behaves in the same way as @code{Variable}.
5892: The difference is that it reserves space in @i{user (data) space} rather
5893: than normal data space. In a Forth system that has a multi-tasker, each
5894: task has its own set of user variables.
5895:
1.34 anton 5896: doc-user
1.67 anton 5897: @c doc-udp
5898: @c doc-uallot
1.34 anton 5899:
1.29 crook 5900: @comment TODO is that stuff about user variables strictly correct? Is it
5901: @comment just terminal tasks that have user variables?
5902: @comment should document tasker.fs (with some examples) elsewhere
5903: @comment in this manual, then expand on user space and user variables.
5904:
1.44 crook 5905: @node Constants, Values, Variables, Defining Words
5906: @subsection Constants
5907: @cindex constants
5908:
5909: @code{Constant} allows you to declare a fixed value and refer to it by
5910: name. For example:
1.29 crook 5911:
5912: @example
5913: 12 Constant INCHES-PER-FOOT
5914: 3E+08 fconstant SPEED-O-LIGHT
5915: @end example
5916:
5917: A @code{Variable} can be both read and written, so its run-time
5918: behaviour is to supply an address through which its current value can be
5919: manipulated. In contrast, the value of a @code{Constant} cannot be
5920: changed once it has been declared@footnote{Well, often it can be -- but
5921: not in a Standard, portable way. It's safer to use a @code{Value} (read
5922: on).} so it's not necessary to supply the address -- it is more
5923: efficient to return the value of the constant directly. That's exactly
5924: what happens; the run-time effect of a constant is to put its value on
1.49 anton 5925: the top of the stack (You can find one
5926: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 5927:
1.69 anton 5928: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 5929: double and floating-point constants, respectively.
5930:
1.34 anton 5931: doc-constant
5932: doc-2constant
5933: doc-fconstant
5934:
5935: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 5936: @c nac-> How could that not be true in an ANS Forth? You can't define a
5937: @c constant, use it and then delete the definition of the constant..
1.69 anton 5938:
5939: @c anton->An ANS Forth system can compile a constant to a literal; On
5940: @c decompilation you would see only the number, just as if it had been used
5941: @c in the first place. The word will stay, of course, but it will only be
5942: @c used by the text interpreter (no run-time duties, except when it is
5943: @c POSTPONEd or somesuch).
5944:
5945: @c nac:
1.44 crook 5946: @c I agree that it's rather deep, but IMO it is an important difference
5947: @c relative to other programming languages.. often it's annoying: it
5948: @c certainly changes my programming style relative to C.
5949:
1.69 anton 5950: @c anton: In what way?
5951:
1.29 crook 5952: Constants in Forth behave differently from their equivalents in other
5953: programming languages. In other languages, a constant (such as an EQU in
5954: assembler or a #define in C) only exists at compile-time; in the
5955: executable program the constant has been translated into an absolute
5956: number and, unless you are using a symbolic debugger, it's impossible to
5957: know what abstract thing that number represents. In Forth a constant has
1.44 crook 5958: an entry in the header space and remains there after the code that uses
5959: it has been defined. In fact, it must remain in the dictionary since it
5960: has run-time duties to perform. For example:
1.29 crook 5961:
5962: @example
5963: 12 Constant INCHES-PER-FOOT
5964: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
5965: @end example
5966:
5967: @cindex in-lining of constants
5968: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
5969: associated with the constant @code{INCHES-PER-FOOT}. If you use
5970: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
5971: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
5972: attempt to optimise constants by in-lining them where they are used. You
5973: can force Gforth to in-line a constant like this:
5974:
5975: @example
5976: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
5977: @end example
5978:
5979: If you use @code{see} to decompile @i{this} version of
5980: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 5981: longer present. To understand how this works, read
5982: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 5983:
5984: In-lining constants in this way might improve execution time
5985: fractionally, and can ensure that a constant is now only referenced at
5986: compile-time. However, the definition of the constant still remains in
5987: the dictionary. Some Forth compilers provide a mechanism for controlling
5988: a second dictionary for holding transient words such that this second
5989: dictionary can be deleted later in order to recover memory
5990: space. However, there is no standard way of doing this.
5991:
5992:
1.44 crook 5993: @node Values, Colon Definitions, Constants, Defining Words
5994: @subsection Values
5995: @cindex values
1.34 anton 5996:
1.69 anton 5997: A @code{Value} behaves like a @code{Constant}, but it can be changed.
5998: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
5999: (not in ANS Forth) you can access (and change) a @code{value} also with
6000: @code{>body}.
6001:
6002: Here are some
6003: examples:
1.29 crook 6004:
6005: @example
1.69 anton 6006: 12 Value APPLES \ Define APPLES with an initial value of 12
6007: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6008: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6009: APPLES \ puts 35 on the top of the stack.
1.29 crook 6010: @end example
6011:
1.44 crook 6012: doc-value
6013: doc-to
1.29 crook 6014:
1.35 anton 6015:
1.69 anton 6016:
1.44 crook 6017: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6018: @subsection Colon Definitions
6019: @cindex colon definitions
1.35 anton 6020:
6021: @example
1.44 crook 6022: : name ( ... -- ... )
6023: word1 word2 word3 ;
1.29 crook 6024: @end example
6025:
1.44 crook 6026: @noindent
6027: Creates a word called @code{name} that, upon execution, executes
6028: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6029:
1.49 anton 6030: The explanation above is somewhat superficial. For simple examples of
6031: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6032: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6033: Compilation Semantics}.
1.29 crook 6034:
1.44 crook 6035: doc-:
6036: doc-;
1.1 anton 6037:
1.34 anton 6038:
1.69 anton 6039: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6040: @subsection Anonymous Definitions
6041: @cindex colon definitions
6042: @cindex defining words without name
1.34 anton 6043:
1.44 crook 6044: Sometimes you want to define an @dfn{anonymous word}; a word without a
6045: name. You can do this with:
1.1 anton 6046:
1.44 crook 6047: doc-:noname
1.1 anton 6048:
1.44 crook 6049: This leaves the execution token for the word on the stack after the
6050: closing @code{;}. Here's an example in which a deferred word is
6051: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6052:
1.29 crook 6053: @example
1.44 crook 6054: Defer deferred
6055: :noname ( ... -- ... )
6056: ... ;
6057: IS deferred
1.29 crook 6058: @end example
1.26 crook 6059:
1.44 crook 6060: @noindent
6061: Gforth provides an alternative way of doing this, using two separate
6062: words:
1.27 crook 6063:
1.44 crook 6064: doc-noname
6065: @cindex execution token of last defined word
1.116 anton 6066: doc-latestxt
1.1 anton 6067:
1.44 crook 6068: @noindent
6069: The previous example can be rewritten using @code{noname} and
1.116 anton 6070: @code{latestxt}:
1.1 anton 6071:
1.26 crook 6072: @example
1.44 crook 6073: Defer deferred
6074: noname : ( ... -- ... )
6075: ... ;
1.116 anton 6076: latestxt IS deferred
1.26 crook 6077: @end example
1.1 anton 6078:
1.29 crook 6079: @noindent
1.44 crook 6080: @code{noname} works with any defining word, not just @code{:}.
6081:
1.116 anton 6082: @code{latestxt} also works when the last word was not defined as
1.71 anton 6083: @code{noname}. It does not work for combined words, though. It also has
6084: the useful property that is is valid as soon as the header for a
6085: definition has been built. Thus:
1.44 crook 6086:
6087: @example
1.116 anton 6088: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6089: @end example
1.1 anton 6090:
1.44 crook 6091: @noindent
6092: prints 3 numbers; the last two are the same.
1.26 crook 6093:
1.69 anton 6094: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6095: @subsection Supplying the name of a defined word
6096: @cindex names for defined words
6097: @cindex defining words, name given in a string
6098:
6099: By default, a defining word takes the name for the defined word from the
6100: input stream. Sometimes you want to supply the name from a string. You
6101: can do this with:
6102:
6103: doc-nextname
6104:
6105: For example:
6106:
6107: @example
6108: s" foo" nextname create
6109: @end example
6110:
6111: @noindent
6112: is equivalent to:
6113:
6114: @example
6115: create foo
6116: @end example
6117:
6118: @noindent
6119: @code{nextname} works with any defining word.
6120:
1.1 anton 6121:
1.69 anton 6122: @node User-defined Defining Words, Deferred words, Supplying names, Defining Words
1.26 crook 6123: @subsection User-defined Defining Words
6124: @cindex user-defined defining words
6125: @cindex defining words, user-defined
1.1 anton 6126:
1.29 crook 6127: You can create a new defining word by wrapping defining-time code around
6128: an existing defining word and putting the sequence in a colon
1.69 anton 6129: definition.
6130:
6131: @c anton: This example is very complex and leads in a quite different
6132: @c direction from the CREATE-DOES> stuff that follows. It should probably
6133: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6134: @c subsection of Defining Words)
6135:
6136: For example, suppose that you have a word @code{stats} that
1.29 crook 6137: gathers statistics about colon definitions given the @i{xt} of the
6138: definition, and you want every colon definition in your application to
6139: make a call to @code{stats}. You can define and use a new version of
6140: @code{:} like this:
6141:
6142: @example
6143: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6144: ... ; \ other code
6145:
1.116 anton 6146: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6147:
6148: my: foo + - ;
6149: @end example
6150:
6151: When @code{foo} is defined using @code{my:} these steps occur:
6152:
6153: @itemize @bullet
6154: @item
6155: @code{my:} is executed.
6156: @item
6157: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6158: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6159: the input stream for a name, builds a dictionary header for the name
6160: @code{foo} and switches @code{state} from interpret to compile.
6161: @item
1.116 anton 6162: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6163: being defined -- @code{foo} -- onto the stack.
6164: @item
6165: The code that was produced by @code{postpone literal} is executed; this
6166: causes the value on the stack to be compiled as a literal in the code
6167: area of @code{foo}.
6168: @item
6169: The code @code{['] stats} compiles a literal into the definition of
6170: @code{my:}. When @code{compile,} is executed, that literal -- the
6171: execution token for @code{stats} -- is layed down in the code area of
6172: @code{foo} , following the literal@footnote{Strictly speaking, the
6173: mechanism that @code{compile,} uses to convert an @i{xt} into something
6174: in the code area is implementation-dependent. A threaded implementation
6175: might spit out the execution token directly whilst another
6176: implementation might spit out a native code sequence.}.
6177: @item
6178: At this point, the execution of @code{my:} is complete, and control
6179: returns to the text interpreter. The text interpreter is in compile
6180: state, so subsequent text @code{+ -} is compiled into the definition of
6181: @code{foo} and the @code{;} terminates the definition as always.
6182: @end itemize
6183:
6184: You can use @code{see} to decompile a word that was defined using
6185: @code{my:} and see how it is different from a normal @code{:}
6186: definition. For example:
6187:
6188: @example
6189: : bar + - ; \ like foo but using : rather than my:
6190: see bar
6191: : bar
6192: + - ;
6193: see foo
6194: : foo
6195: 107645672 stats + - ;
6196:
1.140 anton 6197: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6198: @end example
6199:
6200: You can use techniques like this to make new defining words in terms of
6201: @i{any} existing defining word.
1.1 anton 6202:
6203:
1.29 crook 6204: @cindex defining defining words
1.26 crook 6205: @cindex @code{CREATE} ... @code{DOES>}
6206: If you want the words defined with your defining words to behave
6207: differently from words defined with standard defining words, you can
6208: write your defining word like this:
1.1 anton 6209:
6210: @example
1.26 crook 6211: : def-word ( "name" -- )
1.29 crook 6212: CREATE @i{code1}
1.26 crook 6213: DOES> ( ... -- ... )
1.29 crook 6214: @i{code2} ;
1.26 crook 6215:
6216: def-word name
1.1 anton 6217: @end example
6218:
1.29 crook 6219: @cindex child words
6220: This fragment defines a @dfn{defining word} @code{def-word} and then
6221: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6222: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6223: is not executed at this time. The word @code{name} is sometimes called a
6224: @dfn{child} of @code{def-word}.
6225:
6226: When you execute @code{name}, the address of the body of @code{name} is
6227: put on the data stack and @i{code2} is executed (the address of the body
6228: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6229: @code{CREATE}, i.e., the address a @code{create}d word returns by
6230: default).
6231:
6232: @c anton:
6233: @c www.dictionary.com says:
6234: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6235: @c several generations of absence, usually caused by the chance
6236: @c recombination of genes. 2.An individual or a part that exhibits
6237: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6238: @c of previous behavior after a period of absence.
6239: @c
6240: @c Doesn't seem to fit.
1.29 crook 6241:
1.69 anton 6242: @c @cindex atavism in child words
1.33 anton 6243: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6244: similarly; they all have a common run-time behaviour determined by
6245: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6246: body of the child word. The structure of the data is common to all
6247: children of @code{def-word}, but the data values are specific -- and
6248: private -- to each child word. When a child word is executed, the
6249: address of its private data area is passed as a parameter on TOS to be
6250: used and manipulated@footnote{It is legitimate both to read and write to
6251: this data area.} by @i{code2}.
1.29 crook 6252:
6253: The two fragments of code that make up the defining words act (are
6254: executed) at two completely separate times:
1.1 anton 6255:
1.29 crook 6256: @itemize @bullet
6257: @item
6258: At @i{define time}, the defining word executes @i{code1} to generate a
6259: child word
6260: @item
6261: At @i{child execution time}, when a child word is invoked, @i{code2}
6262: is executed, using parameters (data) that are private and specific to
6263: the child word.
6264: @end itemize
6265:
1.44 crook 6266: Another way of understanding the behaviour of @code{def-word} and
6267: @code{name} is to say that, if you make the following definitions:
1.33 anton 6268: @example
6269: : def-word1 ( "name" -- )
6270: CREATE @i{code1} ;
6271:
6272: : action1 ( ... -- ... )
6273: @i{code2} ;
6274:
6275: def-word1 name1
6276: @end example
6277:
1.44 crook 6278: @noindent
6279: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6280:
1.29 crook 6281: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6282:
1.1 anton 6283: @example
1.29 crook 6284: : CONSTANT ( w "name" -- )
6285: CREATE ,
1.26 crook 6286: DOES> ( -- w )
6287: @@ ;
1.1 anton 6288: @end example
6289:
1.29 crook 6290: @comment There is a beautiful description of how this works and what
6291: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6292: @comment commentary on the Counting Fruits problem.
6293:
6294: When you create a constant with @code{5 CONSTANT five}, a set of
6295: define-time actions take place; first a new word @code{five} is created,
6296: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6297: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6298: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6299: no code of its own; it simply contains a data field and a pointer to the
6300: code that follows @code{DOES>} in its defining word. That makes words
6301: created in this way very compact.
6302:
6303: The final example in this section is intended to remind you that space
6304: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6305: both read and written by a Standard program@footnote{Exercise: use this
6306: example as a starting point for your own implementation of @code{Value}
6307: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6308: @code{[']}.}:
6309:
6310: @example
6311: : foo ( "name" -- )
6312: CREATE -1 ,
6313: DOES> ( -- )
1.33 anton 6314: @@ . ;
1.29 crook 6315:
6316: foo first-word
6317: foo second-word
6318:
6319: 123 ' first-word >BODY !
6320: @end example
6321:
6322: If @code{first-word} had been a @code{CREATE}d word, we could simply
6323: have executed it to get the address of its data field. However, since it
6324: was defined to have @code{DOES>} actions, its execution semantics are to
6325: perform those @code{DOES>} actions. To get the address of its data field
6326: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6327: translate the xt into the address of the data field. When you execute
6328: @code{first-word}, it will display @code{123}. When you execute
6329: @code{second-word} it will display @code{-1}.
1.26 crook 6330:
6331: @cindex stack effect of @code{DOES>}-parts
6332: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6333: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6334: the stack effect of the defined words, not the stack effect of the
6335: following code (the following code expects the address of the body on
6336: the top of stack, which is not reflected in the stack comment). This is
6337: the convention that I use and recommend (it clashes a bit with using
6338: locals declarations for stack effect specification, though).
1.1 anton 6339:
1.53 anton 6340: @menu
6341: * CREATE..DOES> applications::
6342: * CREATE..DOES> details::
1.63 anton 6343: * Advanced does> usage example::
1.155 anton 6344: * Const-does>::
1.53 anton 6345: @end menu
6346:
6347: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6348: @subsubsection Applications of @code{CREATE..DOES>}
6349: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6350:
1.26 crook 6351: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6352:
1.26 crook 6353: @cindex factoring similar colon definitions
6354: When you see a sequence of code occurring several times, and you can
6355: identify a meaning, you will factor it out as a colon definition. When
6356: you see similar colon definitions, you can factor them using
6357: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6358: that look very similar:
1.1 anton 6359: @example
1.26 crook 6360: : ori, ( reg-target reg-source n -- )
6361: 0 asm-reg-reg-imm ;
6362: : andi, ( reg-target reg-source n -- )
6363: 1 asm-reg-reg-imm ;
1.1 anton 6364: @end example
6365:
1.26 crook 6366: @noindent
6367: This could be factored with:
6368: @example
6369: : reg-reg-imm ( op-code -- )
6370: CREATE ,
6371: DOES> ( reg-target reg-source n -- )
6372: @@ asm-reg-reg-imm ;
6373:
6374: 0 reg-reg-imm ori,
6375: 1 reg-reg-imm andi,
6376: @end example
1.1 anton 6377:
1.26 crook 6378: @cindex currying
6379: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6380: supply a part of the parameters for a word (known as @dfn{currying} in
6381: the functional language community). E.g., @code{+} needs two
6382: parameters. Creating versions of @code{+} with one parameter fixed can
6383: be done like this:
1.82 anton 6384:
1.1 anton 6385: @example
1.82 anton 6386: : curry+ ( n1 "name" -- )
1.26 crook 6387: CREATE ,
6388: DOES> ( n2 -- n1+n2 )
6389: @@ + ;
6390:
6391: 3 curry+ 3+
6392: -2 curry+ 2-
1.1 anton 6393: @end example
6394:
1.91 anton 6395:
1.63 anton 6396: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6397: @subsubsection The gory details of @code{CREATE..DOES>}
6398: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6399:
1.26 crook 6400: doc-does>
1.1 anton 6401:
1.26 crook 6402: @cindex @code{DOES>} in a separate definition
6403: This means that you need not use @code{CREATE} and @code{DOES>} in the
6404: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6405: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6406: @example
6407: : does1
6408: DOES> ( ... -- ... )
1.44 crook 6409: ... ;
6410:
6411: : does2
6412: DOES> ( ... -- ... )
6413: ... ;
6414:
6415: : def-word ( ... -- ... )
6416: create ...
6417: IF
6418: does1
6419: ELSE
6420: does2
6421: ENDIF ;
6422: @end example
6423:
6424: In this example, the selection of whether to use @code{does1} or
1.69 anton 6425: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6426: @code{CREATE}d.
6427:
6428: @cindex @code{DOES>} in interpretation state
6429: In a standard program you can apply a @code{DOES>}-part only if the last
6430: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6431: will override the behaviour of the last word defined in any case. In a
6432: standard program, you can use @code{DOES>} only in a colon
6433: definition. In Gforth, you can also use it in interpretation state, in a
6434: kind of one-shot mode; for example:
6435: @example
6436: CREATE name ( ... -- ... )
6437: @i{initialization}
6438: DOES>
6439: @i{code} ;
6440: @end example
6441:
6442: @noindent
6443: is equivalent to the standard:
6444: @example
6445: :noname
6446: DOES>
6447: @i{code} ;
6448: CREATE name EXECUTE ( ... -- ... )
6449: @i{initialization}
6450: @end example
6451:
1.53 anton 6452: doc->body
6453:
1.152 pazsan 6454: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6455: @subsubsection Advanced does> usage example
6456:
6457: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6458: for disassembling instructions, that follow a very repetetive scheme:
6459:
6460: @example
6461: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6462: @var{entry-num} cells @var{table} + !
6463: @end example
6464:
6465: Of course, this inspires the idea to factor out the commonalities to
6466: allow a definition like
6467:
6468: @example
6469: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6470: @end example
6471:
6472: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6473: correlated. Moreover, before I wrote the disassembler, there already
6474: existed code that defines instructions like this:
1.63 anton 6475:
6476: @example
6477: @var{entry-num} @var{inst-format} @var{inst-name}
6478: @end example
6479:
6480: This code comes from the assembler and resides in
6481: @file{arch/mips/insts.fs}.
6482:
6483: So I had to define the @var{inst-format} words that performed the scheme
6484: above when executed. At first I chose to use run-time code-generation:
6485:
6486: @example
6487: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6488: :noname Postpone @var{disasm-operands}
6489: name Postpone sliteral Postpone type Postpone ;
6490: swap cells @var{table} + ! ;
6491: @end example
6492:
6493: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6494:
1.63 anton 6495: An alternative would have been to write this using
6496: @code{create}/@code{does>}:
6497:
6498: @example
6499: : @var{inst-format} ( entry-num "name" -- )
6500: here name string, ( entry-num c-addr ) \ parse and save "name"
6501: noname create , ( entry-num )
1.116 anton 6502: latestxt swap cells @var{table} + !
1.63 anton 6503: does> ( addr w -- )
6504: \ disassemble instruction w at addr
6505: @@ >r
6506: @var{disasm-operands}
6507: r> count type ;
6508: @end example
6509:
6510: Somehow the first solution is simpler, mainly because it's simpler to
6511: shift a string from definition-time to use-time with @code{sliteral}
6512: than with @code{string,} and friends.
6513:
6514: I wrote a lot of words following this scheme and soon thought about
6515: factoring out the commonalities among them. Note that this uses a
6516: two-level defining word, i.e., a word that defines ordinary defining
6517: words.
6518:
6519: This time a solution involving @code{postpone} and friends seemed more
6520: difficult (try it as an exercise), so I decided to use a
6521: @code{create}/@code{does>} word; since I was already at it, I also used
6522: @code{create}/@code{does>} for the lower level (try using
6523: @code{postpone} etc. as an exercise), resulting in the following
6524: definition:
6525:
6526: @example
6527: : define-format ( disasm-xt table-xt -- )
6528: \ define an instruction format that uses disasm-xt for
6529: \ disassembling and enters the defined instructions into table
6530: \ table-xt
6531: create 2,
6532: does> ( u "inst" -- )
6533: \ defines an anonymous word for disassembling instruction inst,
6534: \ and enters it as u-th entry into table-xt
6535: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6536: noname create 2, \ define anonymous word
1.116 anton 6537: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6538: does> ( addr w -- )
6539: \ disassemble instruction w at addr
6540: 2@@ >r ( addr w disasm-xt R: c-addr )
6541: execute ( R: c-addr ) \ disassemble operands
6542: r> count type ; \ print name
6543: @end example
6544:
6545: Note that the tables here (in contrast to above) do the @code{cells +}
6546: by themselves (that's why you have to pass an xt). This word is used in
6547: the following way:
6548:
6549: @example
6550: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6551: @end example
6552:
1.71 anton 6553: As shown above, the defined instruction format is then used like this:
6554:
6555: @example
6556: @var{entry-num} @var{inst-format} @var{inst-name}
6557: @end example
6558:
1.63 anton 6559: In terms of currying, this kind of two-level defining word provides the
6560: parameters in three stages: first @var{disasm-operands} and @var{table},
6561: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6562: the instruction to be disassembled.
6563:
6564: Of course this did not quite fit all the instruction format names used
6565: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6566: the parameters into the right form.
6567:
6568: If you have trouble following this section, don't worry. First, this is
6569: involved and takes time (and probably some playing around) to
6570: understand; second, this is the first two-level
6571: @code{create}/@code{does>} word I have written in seventeen years of
6572: Forth; and if I did not have @file{insts.fs} to start with, I may well
6573: have elected to use just a one-level defining word (with some repeating
6574: of parameters when using the defining word). So it is not necessary to
6575: understand this, but it may improve your understanding of Forth.
1.44 crook 6576:
6577:
1.152 pazsan 6578: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6579: @subsubsection @code{Const-does>}
6580:
6581: A frequent use of @code{create}...@code{does>} is for transferring some
6582: values from definition-time to run-time. Gforth supports this use with
6583:
6584: doc-const-does>
6585:
6586: A typical use of this word is:
6587:
6588: @example
6589: : curry+ ( n1 "name" -- )
6590: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6591: + ;
6592:
6593: 3 curry+ 3+
6594: @end example
6595:
6596: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6597: definition to run-time.
6598:
6599: The advantages of using @code{const-does>} are:
6600:
6601: @itemize
6602:
6603: @item
6604: You don't have to deal with storing and retrieving the values, i.e.,
6605: your program becomes more writable and readable.
6606:
6607: @item
6608: When using @code{does>}, you have to introduce a @code{@@} that cannot
6609: be optimized away (because you could change the data using
6610: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6611:
6612: @end itemize
6613:
6614: An ANS Forth implementation of @code{const-does>} is available in
6615: @file{compat/const-does.fs}.
6616:
6617:
1.44 crook 6618: @node Deferred words, Aliases, User-defined Defining Words, Defining Words
6619: @subsection Deferred words
6620: @cindex deferred words
6621:
6622: The defining word @code{Defer} allows you to define a word by name
6623: without defining its behaviour; the definition of its behaviour is
6624: deferred. Here are two situation where this can be useful:
6625:
6626: @itemize @bullet
6627: @item
6628: Where you want to allow the behaviour of a word to be altered later, and
6629: for all precompiled references to the word to change when its behaviour
6630: is changed.
6631: @item
6632: For mutual recursion; @xref{Calls and returns}.
6633: @end itemize
6634:
6635: In the following example, @code{foo} always invokes the version of
6636: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6637: always invokes the version that prints ``@code{Hello}''. There is no way
6638: of getting @code{foo} to use the later version without re-ordering the
6639: source code and recompiling it.
6640:
6641: @example
6642: : greet ." Good morning" ;
6643: : foo ... greet ... ;
6644: : greet ." Hello" ;
6645: : bar ... greet ... ;
6646: @end example
6647:
6648: This problem can be solved by defining @code{greet} as a @code{Defer}red
6649: word. The behaviour of a @code{Defer}red word can be defined and
6650: redefined at any time by using @code{IS} to associate the xt of a
6651: previously-defined word with it. The previous example becomes:
6652:
6653: @example
1.69 anton 6654: Defer greet ( -- )
1.44 crook 6655: : foo ... greet ... ;
6656: : bar ... greet ... ;
1.69 anton 6657: : greet1 ( -- ) ." Good morning" ;
6658: : greet2 ( -- ) ." Hello" ;
1.132 anton 6659: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6660: @end example
6661:
1.69 anton 6662: @progstyle
6663: You should write a stack comment for every deferred word, and put only
6664: XTs into deferred words that conform to this stack effect. Otherwise
6665: it's too difficult to use the deferred word.
6666:
1.44 crook 6667: A deferred word can be used to improve the statistics-gathering example
6668: from @ref{User-defined Defining Words}; rather than edit the
6669: application's source code to change every @code{:} to a @code{my:}, do
6670: this:
6671:
6672: @example
6673: : real: : ; \ retain access to the original
6674: defer : \ redefine as a deferred word
1.132 anton 6675: ' my: IS : \ use special version of :
1.44 crook 6676: \
6677: \ load application here
6678: \
1.132 anton 6679: ' real: IS : \ go back to the original
1.44 crook 6680: @end example
6681:
6682:
1.132 anton 6683: One thing to note is that @code{IS} has special compilation semantics,
6684: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6685:
6686: @example
6687: : set-greet ( xt -- )
1.132 anton 6688: IS greet ;
1.44 crook 6689:
6690: ' greet1 set-greet
6691: @end example
6692:
1.132 anton 6693: In situations where @code{IS} does not fit, use @code{defer!} instead.
6694:
1.69 anton 6695: A deferred word can only inherit execution semantics from the xt
6696: (because that is all that an xt can represent -- for more discussion of
6697: this @pxref{Tokens for Words}); by default it will have default
6698: interpretation and compilation semantics deriving from this execution
6699: semantics. However, you can change the interpretation and compilation
6700: semantics of the deferred word in the usual ways:
1.44 crook 6701:
6702: @example
1.132 anton 6703: : bar .... ; immediate
1.44 crook 6704: Defer fred immediate
6705: Defer jim
6706:
1.132 anton 6707: ' bar IS jim \ jim has default semantics
6708: ' bar IS fred \ fred is immediate
1.44 crook 6709: @end example
6710:
6711: doc-defer
1.132 anton 6712: doc-defer!
1.44 crook 6713: doc-is
1.132 anton 6714: doc-defer@
6715: doc-action-of
1.44 crook 6716: @comment TODO document these: what's defers [is]
6717: doc-defers
6718:
6719: @c Use @code{words-deferred} to see a list of deferred words.
6720:
1.132 anton 6721: Definitions of these words (except @code{defers}) in ANS Forth are
6722: provided in @file{compat/defer.fs}.
1.44 crook 6723:
6724:
1.69 anton 6725: @node Aliases, , Deferred words, Defining Words
1.44 crook 6726: @subsection Aliases
6727: @cindex aliases
1.1 anton 6728:
1.44 crook 6729: The defining word @code{Alias} allows you to define a word by name that
6730: has the same behaviour as some other word. Here are two situation where
6731: this can be useful:
1.1 anton 6732:
1.44 crook 6733: @itemize @bullet
6734: @item
6735: When you want access to a word's definition from a different word list
6736: (for an example of this, see the definition of the @code{Root} word list
6737: in the Gforth source).
6738: @item
6739: When you want to create a synonym; a definition that can be known by
6740: either of two names (for example, @code{THEN} and @code{ENDIF} are
6741: aliases).
6742: @end itemize
1.1 anton 6743:
1.69 anton 6744: Like deferred words, an alias has default compilation and interpretation
6745: semantics at the beginning (not the modifications of the other word),
6746: but you can change them in the usual ways (@code{immediate},
6747: @code{compile-only}). For example:
1.1 anton 6748:
6749: @example
1.44 crook 6750: : foo ... ; immediate
6751:
6752: ' foo Alias bar \ bar is not an immediate word
6753: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6754: @end example
6755:
1.44 crook 6756: Words that are aliases have the same xt, different headers in the
6757: dictionary, and consequently different name tokens (@pxref{Tokens for
6758: Words}) and possibly different immediate flags. An alias can only have
6759: default or immediate compilation semantics; you can define aliases for
6760: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6761:
1.44 crook 6762: doc-alias
1.1 anton 6763:
6764:
1.47 crook 6765: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6766: @section Interpretation and Compilation Semantics
1.26 crook 6767: @cindex semantics, interpretation and compilation
1.1 anton 6768:
1.71 anton 6769: @c !! state and ' are used without explanation
6770: @c example for immediate/compile-only? or is the tutorial enough
6771:
1.26 crook 6772: @cindex interpretation semantics
1.71 anton 6773: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6774: interpreter does when it encounters the word in interpret state. It also
6775: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6776: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6777: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6778: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6779:
1.26 crook 6780: @cindex compilation semantics
1.71 anton 6781: The @dfn{compilation semantics} of a (named) word are what the text
6782: interpreter does when it encounters the word in compile state. It also
6783: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6784: compiles@footnote{In standard terminology, ``appends to the current
6785: definition''.} the compilation semantics of @i{word}.
1.1 anton 6786:
1.26 crook 6787: @cindex execution semantics
6788: The standard also talks about @dfn{execution semantics}. They are used
6789: only for defining the interpretation and compilation semantics of many
6790: words. By default, the interpretation semantics of a word are to
6791: @code{execute} its execution semantics, and the compilation semantics of
6792: a word are to @code{compile,} its execution semantics.@footnote{In
6793: standard terminology: The default interpretation semantics are its
6794: execution semantics; the default compilation semantics are to append its
6795: execution semantics to the execution semantics of the current
6796: definition.}
6797:
1.71 anton 6798: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6799: the text interpreter, ticked, or @code{postpone}d, so they have no
6800: interpretation or compilation semantics. Their behaviour is represented
6801: by their XT (@pxref{Tokens for Words}), and we call it execution
6802: semantics, too.
6803:
1.26 crook 6804: @comment TODO expand, make it co-operate with new sections on text interpreter.
6805:
6806: @cindex immediate words
6807: @cindex compile-only words
6808: You can change the semantics of the most-recently defined word:
6809:
1.44 crook 6810:
1.26 crook 6811: doc-immediate
6812: doc-compile-only
6813: doc-restrict
6814:
1.82 anton 6815: By convention, words with non-default compilation semantics (e.g.,
6816: immediate words) often have names surrounded with brackets (e.g.,
6817: @code{[']}, @pxref{Execution token}).
1.44 crook 6818:
1.26 crook 6819: Note that ticking (@code{'}) a compile-only word gives an error
6820: (``Interpreting a compile-only word'').
1.1 anton 6821:
1.47 crook 6822: @menu
1.67 anton 6823: * Combined words::
1.47 crook 6824: @end menu
1.44 crook 6825:
1.71 anton 6826:
1.48 anton 6827: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6828: @subsection Combined Words
6829: @cindex combined words
6830:
6831: Gforth allows you to define @dfn{combined words} -- words that have an
6832: arbitrary combination of interpretation and compilation semantics.
6833:
1.26 crook 6834: doc-interpret/compile:
1.1 anton 6835:
1.26 crook 6836: This feature was introduced for implementing @code{TO} and @code{S"}. I
6837: recommend that you do not define such words, as cute as they may be:
6838: they make it hard to get at both parts of the word in some contexts.
6839: E.g., assume you want to get an execution token for the compilation
6840: part. Instead, define two words, one that embodies the interpretation
6841: part, and one that embodies the compilation part. Once you have done
6842: that, you can define a combined word with @code{interpret/compile:} for
6843: the convenience of your users.
1.1 anton 6844:
1.26 crook 6845: You might try to use this feature to provide an optimizing
6846: implementation of the default compilation semantics of a word. For
6847: example, by defining:
1.1 anton 6848: @example
1.26 crook 6849: :noname
6850: foo bar ;
6851: :noname
6852: POSTPONE foo POSTPONE bar ;
1.29 crook 6853: interpret/compile: opti-foobar
1.1 anton 6854: @end example
1.26 crook 6855:
1.23 crook 6856: @noindent
1.26 crook 6857: as an optimizing version of:
6858:
1.1 anton 6859: @example
1.26 crook 6860: : foobar
6861: foo bar ;
1.1 anton 6862: @end example
6863:
1.26 crook 6864: Unfortunately, this does not work correctly with @code{[compile]},
6865: because @code{[compile]} assumes that the compilation semantics of all
6866: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 6867: opti-foobar} would compile compilation semantics, whereas
6868: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 6869:
1.26 crook 6870: @cindex state-smart words (are a bad idea)
1.82 anton 6871: @anchor{state-smartness}
1.29 crook 6872: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 6873: by @code{interpret/compile:} (words are state-smart if they check
6874: @code{STATE} during execution). E.g., they would try to code
6875: @code{foobar} like this:
1.1 anton 6876:
1.26 crook 6877: @example
6878: : foobar
6879: STATE @@
6880: IF ( compilation state )
6881: POSTPONE foo POSTPONE bar
6882: ELSE
6883: foo bar
6884: ENDIF ; immediate
6885: @end example
1.1 anton 6886:
1.26 crook 6887: Although this works if @code{foobar} is only processed by the text
6888: interpreter, it does not work in other contexts (like @code{'} or
6889: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
6890: for a state-smart word, not for the interpretation semantics of the
6891: original @code{foobar}; when you execute this execution token (directly
6892: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
6893: state, the result will not be what you expected (i.e., it will not
6894: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
6895: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 6896: M. Anton Ertl,
6897: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
6898: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 6899:
1.26 crook 6900: @cindex defining words with arbitrary semantics combinations
6901: It is also possible to write defining words that define words with
6902: arbitrary combinations of interpretation and compilation semantics. In
6903: general, they look like this:
1.1 anton 6904:
1.26 crook 6905: @example
6906: : def-word
6907: create-interpret/compile
1.29 crook 6908: @i{code1}
1.26 crook 6909: interpretation>
1.29 crook 6910: @i{code2}
1.26 crook 6911: <interpretation
6912: compilation>
1.29 crook 6913: @i{code3}
1.26 crook 6914: <compilation ;
6915: @end example
1.1 anton 6916:
1.29 crook 6917: For a @i{word} defined with @code{def-word}, the interpretation
6918: semantics are to push the address of the body of @i{word} and perform
6919: @i{code2}, and the compilation semantics are to push the address of
6920: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 6921: can also be defined like this (except that the defined constants don't
6922: behave correctly when @code{[compile]}d):
1.1 anton 6923:
1.26 crook 6924: @example
6925: : constant ( n "name" -- )
6926: create-interpret/compile
6927: ,
6928: interpretation> ( -- n )
6929: @@
6930: <interpretation
6931: compilation> ( compilation. -- ; run-time. -- n )
6932: @@ postpone literal
6933: <compilation ;
6934: @end example
1.1 anton 6935:
1.44 crook 6936:
1.26 crook 6937: doc-create-interpret/compile
6938: doc-interpretation>
6939: doc-<interpretation
6940: doc-compilation>
6941: doc-<compilation
1.1 anton 6942:
1.44 crook 6943:
1.29 crook 6944: Words defined with @code{interpret/compile:} and
1.26 crook 6945: @code{create-interpret/compile} have an extended header structure that
6946: differs from other words; however, unless you try to access them with
6947: plain address arithmetic, you should not notice this. Words for
6948: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 6949: @code{'} @i{word} @code{>body} also gives you the body of a word created
6950: with @code{create-interpret/compile}.
1.1 anton 6951:
1.44 crook 6952:
1.47 crook 6953: @c -------------------------------------------------------------
1.81 anton 6954: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 6955: @section Tokens for Words
6956: @cindex tokens for words
6957:
6958: This section describes the creation and use of tokens that represent
6959: words.
6960:
1.71 anton 6961: @menu
6962: * Execution token:: represents execution/interpretation semantics
6963: * Compilation token:: represents compilation semantics
6964: * Name token:: represents named words
6965: @end menu
1.47 crook 6966:
1.71 anton 6967: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
6968: @subsection Execution token
1.47 crook 6969:
6970: @cindex xt
6971: @cindex execution token
1.71 anton 6972: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
6973: You can use @code{execute} to invoke this behaviour.
1.47 crook 6974:
1.71 anton 6975: @cindex tick (')
6976: You can use @code{'} to get an execution token that represents the
6977: interpretation semantics of a named word:
1.47 crook 6978:
6979: @example
1.97 anton 6980: 5 ' . ( n xt )
6981: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 6982: @end example
1.47 crook 6983:
1.71 anton 6984: doc-'
6985:
6986: @code{'} parses at run-time; there is also a word @code{[']} that parses
6987: when it is compiled, and compiles the resulting XT:
6988:
6989: @example
6990: : foo ['] . execute ;
6991: 5 foo
6992: : bar ' execute ; \ by contrast,
6993: 5 bar . \ ' parses "." when bar executes
6994: @end example
6995:
6996: doc-[']
6997:
6998: If you want the execution token of @i{word}, write @code{['] @i{word}}
6999: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7000: @code{'} and @code{[']} behave somewhat unusually by complaining about
7001: compile-only words (because these words have no interpretation
7002: semantics). You might get what you want by using @code{COMP' @i{word}
7003: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7004: token}).
7005:
1.116 anton 7006: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7007: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7008: for the only behaviour the word has (the execution semantics). For
1.116 anton 7009: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7010: would produce if the word was defined anonymously.
7011:
7012: @example
7013: :noname ." hello" ;
7014: execute
1.47 crook 7015: @end example
7016:
1.71 anton 7017: An XT occupies one cell and can be manipulated like any other cell.
7018:
1.47 crook 7019: @cindex code field address
7020: @cindex CFA
1.71 anton 7021: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7022: operations that produce or consume it). For old hands: In Gforth, the
7023: XT is implemented as a code field address (CFA).
7024:
7025: doc-execute
7026: doc-perform
7027:
7028: @node Compilation token, Name token, Execution token, Tokens for Words
7029: @subsection Compilation token
1.47 crook 7030:
7031: @cindex compilation token
1.71 anton 7032: @cindex CT (compilation token)
7033: Gforth represents the compilation semantics of a named word by a
1.47 crook 7034: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7035: @i{xt} is an execution token. The compilation semantics represented by
7036: the compilation token can be performed with @code{execute}, which
7037: consumes the whole compilation token, with an additional stack effect
7038: determined by the represented compilation semantics.
7039:
7040: At present, the @i{w} part of a compilation token is an execution token,
7041: and the @i{xt} part represents either @code{execute} or
7042: @code{compile,}@footnote{Depending upon the compilation semantics of the
7043: word. If the word has default compilation semantics, the @i{xt} will
7044: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7045: @i{xt} will represent @code{execute}.}. However, don't rely on that
7046: knowledge, unless necessary; future versions of Gforth may introduce
7047: unusual compilation tokens (e.g., a compilation token that represents
7048: the compilation semantics of a literal).
7049:
1.71 anton 7050: You can perform the compilation semantics represented by the compilation
7051: token with @code{execute}. You can compile the compilation semantics
7052: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7053: equivalent to @code{postpone @i{word}}.
7054:
7055: doc-[comp']
7056: doc-comp'
7057: doc-postpone,
7058:
7059: @node Name token, , Compilation token, Tokens for Words
7060: @subsection Name token
1.47 crook 7061:
7062: @cindex name token
1.116 anton 7063: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7064: token is an abstract data type that occurs as argument or result of the
7065: words below.
7066:
7067: @c !! put this elswhere?
1.47 crook 7068: @cindex name field address
7069: @cindex NFA
1.116 anton 7070: The closest thing to the nt in older Forth systems is the name field
7071: address (NFA), but there are significant differences: in older Forth
7072: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7073: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7074: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7075: is a link field in the structure identified by the name token, but
7076: searching usually uses a hash table external to these structures; the
7077: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7078: implemented as the address of that count field.
1.47 crook 7079:
7080: doc-find-name
1.116 anton 7081: doc-latest
7082: doc->name
1.47 crook 7083: doc-name>int
7084: doc-name?int
7085: doc-name>comp
7086: doc-name>string
1.109 anton 7087: doc-id.
7088: doc-.name
7089: doc-.id
1.47 crook 7090:
1.81 anton 7091: @c ----------------------------------------------------------
7092: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7093: @section Compiling words
7094: @cindex compiling words
7095: @cindex macros
7096:
7097: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7098: between compilation and run-time. E.g., you can run arbitrary code
7099: between defining words (or for computing data used by defining words
7100: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7101: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7102: running arbitrary code while compiling a colon definition (exception:
7103: you must not allot dictionary space).
7104:
7105: @menu
7106: * Literals:: Compiling data values
7107: * Macros:: Compiling words
7108: @end menu
7109:
7110: @node Literals, Macros, Compiling words, Compiling words
7111: @subsection Literals
7112: @cindex Literals
7113:
7114: The simplest and most frequent example is to compute a literal during
7115: compilation. E.g., the following definition prints an array of strings,
7116: one string per line:
7117:
7118: @example
7119: : .strings ( addr u -- ) \ gforth
7120: 2* cells bounds U+DO
7121: cr i 2@@ type
7122: 2 cells +LOOP ;
7123: @end example
1.81 anton 7124:
1.82 anton 7125: With a simple-minded compiler like Gforth's, this computes @code{2
7126: cells} on every loop iteration. You can compute this value once and for
7127: all at compile time and compile it into the definition like this:
7128:
7129: @example
7130: : .strings ( addr u -- ) \ gforth
7131: 2* cells bounds U+DO
7132: cr i 2@@ type
7133: [ 2 cells ] literal +LOOP ;
7134: @end example
7135:
7136: @code{[} switches the text interpreter to interpret state (you will get
7137: an @code{ok} prompt if you type this example interactively and insert a
7138: newline between @code{[} and @code{]}), so it performs the
7139: interpretation semantics of @code{2 cells}; this computes a number.
7140: @code{]} switches the text interpreter back into compile state. It then
7141: performs @code{Literal}'s compilation semantics, which are to compile
7142: this number into the current word. You can decompile the word with
7143: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7144:
1.82 anton 7145: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7146: *} in this way.
1.81 anton 7147:
1.82 anton 7148: doc-[
7149: doc-]
1.81 anton 7150: doc-literal
7151: doc-]L
1.82 anton 7152:
7153: There are also words for compiling other data types than single cells as
7154: literals:
7155:
1.81 anton 7156: doc-2literal
7157: doc-fliteral
1.82 anton 7158: doc-sliteral
7159:
7160: @cindex colon-sys, passing data across @code{:}
7161: @cindex @code{:}, passing data across
7162: You might be tempted to pass data from outside a colon definition to the
7163: inside on the data stack. This does not work, because @code{:} puhes a
7164: colon-sys, making stuff below unaccessible. E.g., this does not work:
7165:
7166: @example
7167: 5 : foo literal ; \ error: "unstructured"
7168: @end example
7169:
7170: Instead, you have to pass the value in some other way, e.g., through a
7171: variable:
7172:
7173: @example
7174: variable temp
7175: 5 temp !
7176: : foo [ temp @@ ] literal ;
7177: @end example
7178:
7179:
7180: @node Macros, , Literals, Compiling words
7181: @subsection Macros
7182: @cindex Macros
7183: @cindex compiling compilation semantics
7184:
7185: @code{Literal} and friends compile data values into the current
7186: definition. You can also write words that compile other words into the
7187: current definition. E.g.,
7188:
7189: @example
7190: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7191: POSTPONE + ;
7192:
7193: : foo ( n1 n2 -- n )
7194: [ compile-+ ] ;
7195: 1 2 foo .
7196: @end example
7197:
7198: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7199: What happens in this example? @code{Postpone} compiles the compilation
7200: semantics of @code{+} into @code{compile-+}; later the text interpreter
7201: executes @code{compile-+} and thus the compilation semantics of +, which
7202: compile (the execution semantics of) @code{+} into
7203: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7204: should only be executed in compile state, so this example is not
7205: guaranteed to work on all standard systems, but on any decent system it
7206: will work.}
7207:
7208: doc-postpone
7209: doc-[compile]
7210:
7211: Compiling words like @code{compile-+} are usually immediate (or similar)
7212: so you do not have to switch to interpret state to execute them;
7213: mopifying the last example accordingly produces:
7214:
7215: @example
7216: : [compile-+] ( compilation: --; interpretation: -- )
7217: \ compiled code: ( n1 n2 -- n )
7218: POSTPONE + ; immediate
7219:
7220: : foo ( n1 n2 -- n )
7221: [compile-+] ;
7222: 1 2 foo .
7223: @end example
7224:
7225: Immediate compiling words are similar to macros in other languages (in
7226: particular, Lisp). The important differences to macros in, e.g., C are:
7227:
7228: @itemize @bullet
7229:
7230: @item
7231: You use the same language for defining and processing macros, not a
7232: separate preprocessing language and processor.
7233:
7234: @item
7235: Consequently, the full power of Forth is available in macro definitions.
7236: E.g., you can perform arbitrarily complex computations, or generate
7237: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7238: Tutorial}). This power is very useful when writing a parser generators
7239: or other code-generating software.
7240:
7241: @item
7242: Macros defined using @code{postpone} etc. deal with the language at a
7243: higher level than strings; name binding happens at macro definition
7244: time, so you can avoid the pitfalls of name collisions that can happen
7245: in C macros. Of course, Forth is a liberal language and also allows to
7246: shoot yourself in the foot with text-interpreted macros like
7247:
7248: @example
7249: : [compile-+] s" +" evaluate ; immediate
7250: @end example
7251:
7252: Apart from binding the name at macro use time, using @code{evaluate}
7253: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7254: @end itemize
7255:
7256: You may want the macro to compile a number into a word. The word to do
7257: it is @code{literal}, but you have to @code{postpone} it, so its
7258: compilation semantics take effect when the macro is executed, not when
7259: it is compiled:
7260:
7261: @example
7262: : [compile-5] ( -- ) \ compiled code: ( -- n )
7263: 5 POSTPONE literal ; immediate
7264:
7265: : foo [compile-5] ;
7266: foo .
7267: @end example
7268:
7269: You may want to pass parameters to a macro, that the macro should
7270: compile into the current definition. If the parameter is a number, then
7271: you can use @code{postpone literal} (similar for other values).
7272:
7273: If you want to pass a word that is to be compiled, the usual way is to
7274: pass an execution token and @code{compile,} it:
7275:
7276: @example
7277: : twice1 ( xt -- ) \ compiled code: ... -- ...
7278: dup compile, compile, ;
7279:
7280: : 2+ ( n1 -- n2 )
7281: [ ' 1+ twice1 ] ;
7282: @end example
7283:
7284: doc-compile,
7285:
7286: An alternative available in Gforth, that allows you to pass compile-only
7287: words as parameters is to use the compilation token (@pxref{Compilation
7288: token}). The same example in this technique:
7289:
7290: @example
7291: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7292: 2dup 2>r execute 2r> execute ;
7293:
7294: : 2+ ( n1 -- n2 )
7295: [ comp' 1+ twice ] ;
7296: @end example
7297:
7298: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7299: works even if the executed compilation semantics has an effect on the
7300: data stack.
7301:
7302: You can also define complete definitions with these words; this provides
7303: an alternative to using @code{does>} (@pxref{User-defined Defining
7304: Words}). E.g., instead of
7305:
7306: @example
7307: : curry+ ( n1 "name" -- )
7308: CREATE ,
7309: DOES> ( n2 -- n1+n2 )
7310: @@ + ;
7311: @end example
7312:
7313: you could define
7314:
7315: @example
7316: : curry+ ( n1 "name" -- )
7317: \ name execution: ( n2 -- n1+n2 )
7318: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7319:
1.82 anton 7320: -3 curry+ 3-
7321: see 3-
7322: @end example
1.81 anton 7323:
1.82 anton 7324: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7325: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7326:
1.82 anton 7327: This way of writing defining words is sometimes more, sometimes less
7328: convenient than using @code{does>} (@pxref{Advanced does> usage
7329: example}). One advantage of this method is that it can be optimized
7330: better, because the compiler knows that the value compiled with
7331: @code{literal} is fixed, whereas the data associated with a
7332: @code{create}d word can be changed.
1.47 crook 7333:
1.26 crook 7334: @c ----------------------------------------------------------
1.111 anton 7335: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7336: @section The Text Interpreter
7337: @cindex interpreter - outer
7338: @cindex text interpreter
7339: @cindex outer interpreter
1.1 anton 7340:
1.34 anton 7341: @c Should we really describe all these ugly details? IMO the text
7342: @c interpreter should be much cleaner, but that may not be possible within
7343: @c ANS Forth. - anton
1.44 crook 7344: @c nac-> I wanted to explain how it works to show how you can exploit
7345: @c it in your own programs. When I was writing a cross-compiler, figuring out
7346: @c some of these gory details was very helpful to me. None of the textbooks
7347: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7348: @c seems to positively avoid going into too much detail for some of
7349: @c the internals.
1.34 anton 7350:
1.71 anton 7351: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7352: @c it is; for the ugly details, I would prefer another place. I wonder
7353: @c whether we should have a chapter before "Words" that describes some
7354: @c basic concepts referred to in words, and a chapter after "Words" that
7355: @c describes implementation details.
7356:
1.29 crook 7357: The text interpreter@footnote{This is an expanded version of the
7358: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7359: that processes input from the current input device. It is also called
7360: the outer interpreter, in contrast to the inner interpreter
7361: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7362: implementations.
1.27 crook 7363:
1.29 crook 7364: @cindex interpret state
7365: @cindex compile state
7366: The text interpreter operates in one of two states: @dfn{interpret
7367: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7368: aptly-named variable @code{state}.
1.29 crook 7369:
7370: This section starts by describing how the text interpreter behaves when
7371: it is in interpret state, processing input from the user input device --
7372: the keyboard. This is the mode that a Forth system is in after it starts
7373: up.
7374:
7375: @cindex input buffer
7376: @cindex terminal input buffer
7377: The text interpreter works from an area of memory called the @dfn{input
7378: buffer}@footnote{When the text interpreter is processing input from the
7379: keyboard, this area of memory is called the @dfn{terminal input buffer}
7380: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7381: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7382: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7383: leading spaces (called @dfn{delimiters}) then parses a string (a
7384: sequence of non-space characters) until it reaches either a space
7385: character or the end of the buffer. Having parsed a string, it makes two
7386: attempts to process it:
1.27 crook 7387:
1.29 crook 7388: @cindex dictionary
1.27 crook 7389: @itemize @bullet
7390: @item
1.29 crook 7391: It looks for the string in a @dfn{dictionary} of definitions. If the
7392: string is found, the string names a @dfn{definition} (also known as a
7393: @dfn{word}) and the dictionary search returns information that allows
7394: the text interpreter to perform the word's @dfn{interpretation
7395: semantics}. In most cases, this simply means that the word will be
7396: executed.
1.27 crook 7397: @item
7398: If the string is not found in the dictionary, the text interpreter
1.29 crook 7399: attempts to treat it as a number, using the rules described in
7400: @ref{Number Conversion}. If the string represents a legal number in the
7401: current radix, the number is pushed onto a parameter stack (the data
7402: stack for integers, the floating-point stack for floating-point
7403: numbers).
7404: @end itemize
7405:
7406: If both attempts fail, or if the word is found in the dictionary but has
7407: no interpretation semantics@footnote{This happens if the word was
7408: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7409: remainder of the input buffer, issues an error message and waits for
7410: more input. If one of the attempts succeeds, the text interpreter
7411: repeats the parsing process until the whole of the input buffer has been
7412: processed, at which point it prints the status message ``@code{ ok}''
7413: and waits for more input.
7414:
1.71 anton 7415: @c anton: this should be in the input stream subsection (or below it)
7416:
1.29 crook 7417: @cindex parse area
7418: The text interpreter keeps track of its position in the input buffer by
7419: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7420: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7421: of the input buffer. The region from offset @code{>IN @@} to the end of
7422: the input buffer is called the @dfn{parse area}@footnote{In other words,
7423: the text interpreter processes the contents of the input buffer by
7424: parsing strings from the parse area until the parse area is empty.}.
7425: This example shows how @code{>IN} changes as the text interpreter parses
7426: the input buffer:
7427:
7428: @example
7429: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7430: CR ." ->" TYPE ." <-" ; IMMEDIATE
7431:
7432: 1 2 3 remaining + remaining .
7433:
7434: : foo 1 2 3 remaining SWAP remaining ;
7435: @end example
7436:
7437: @noindent
7438: The result is:
7439:
7440: @example
7441: ->+ remaining .<-
7442: ->.<-5 ok
7443:
7444: ->SWAP remaining ;-<
7445: ->;<- ok
7446: @end example
7447:
7448: @cindex parsing words
7449: The value of @code{>IN} can also be modified by a word in the input
7450: buffer that is executed by the text interpreter. This means that a word
7451: can ``trick'' the text interpreter into either skipping a section of the
7452: input buffer@footnote{This is how parsing words work.} or into parsing a
7453: section twice. For example:
1.27 crook 7454:
1.29 crook 7455: @example
1.71 anton 7456: : lat ." <<foo>>" ;
7457: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7458: @end example
7459:
7460: @noindent
7461: When @code{flat} is executed, this output is produced@footnote{Exercise
7462: for the reader: what would happen if the @code{3} were replaced with
7463: @code{4}?}:
7464:
7465: @example
1.71 anton 7466: <<bar>><<foo>>
1.29 crook 7467: @end example
7468:
1.71 anton 7469: This technique can be used to work around some of the interoperability
7470: problems of parsing words. Of course, it's better to avoid parsing
7471: words where possible.
7472:
1.29 crook 7473: @noindent
7474: Two important notes about the behaviour of the text interpreter:
1.27 crook 7475:
7476: @itemize @bullet
7477: @item
7478: It processes each input string to completion before parsing additional
1.29 crook 7479: characters from the input buffer.
7480: @item
7481: It treats the input buffer as a read-only region (and so must your code).
7482: @end itemize
7483:
7484: @noindent
7485: When the text interpreter is in compile state, its behaviour changes in
7486: these ways:
7487:
7488: @itemize @bullet
7489: @item
7490: If a parsed string is found in the dictionary, the text interpreter will
7491: perform the word's @dfn{compilation semantics}. In most cases, this
7492: simply means that the execution semantics of the word will be appended
7493: to the current definition.
1.27 crook 7494: @item
1.29 crook 7495: When a number is encountered, it is compiled into the current definition
7496: (as a literal) rather than being pushed onto a parameter stack.
7497: @item
7498: If an error occurs, @code{state} is modified to put the text interpreter
7499: back into interpret state.
7500: @item
7501: Each time a line is entered from the keyboard, Gforth prints
7502: ``@code{ compiled}'' rather than `` @code{ok}''.
7503: @end itemize
7504:
7505: @cindex text interpreter - input sources
7506: When the text interpreter is using an input device other than the
7507: keyboard, its behaviour changes in these ways:
7508:
7509: @itemize @bullet
7510: @item
7511: When the parse area is empty, the text interpreter attempts to refill
7512: the input buffer from the input source. When the input source is
1.71 anton 7513: exhausted, the input source is set back to the previous input source.
1.29 crook 7514: @item
7515: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7516: time the parse area is emptied.
7517: @item
7518: If an error occurs, the input source is set back to the user input
7519: device.
1.27 crook 7520: @end itemize
1.21 crook 7521:
1.49 anton 7522: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7523:
1.26 crook 7524: doc->in
1.27 crook 7525: doc-source
7526:
1.26 crook 7527: doc-tib
7528: doc-#tib
1.1 anton 7529:
1.44 crook 7530:
1.26 crook 7531: @menu
1.67 anton 7532: * Input Sources::
7533: * Number Conversion::
7534: * Interpret/Compile states::
7535: * Interpreter Directives::
1.26 crook 7536: @end menu
1.1 anton 7537:
1.29 crook 7538: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7539: @subsection Input Sources
7540: @cindex input sources
7541: @cindex text interpreter - input sources
7542:
1.44 crook 7543: By default, the text interpreter processes input from the user input
1.29 crook 7544: device (the keyboard) when Forth starts up. The text interpreter can
7545: process input from any of these sources:
7546:
7547: @itemize @bullet
7548: @item
7549: The user input device -- the keyboard.
7550: @item
7551: A file, using the words described in @ref{Forth source files}.
7552: @item
7553: A block, using the words described in @ref{Blocks}.
7554: @item
7555: A text string, using @code{evaluate}.
7556: @end itemize
7557:
7558: A program can identify the current input device from the values of
7559: @code{source-id} and @code{blk}.
7560:
1.44 crook 7561:
1.29 crook 7562: doc-source-id
7563: doc-blk
7564:
7565: doc-save-input
7566: doc-restore-input
7567:
7568: doc-evaluate
1.111 anton 7569: doc-query
1.1 anton 7570:
1.29 crook 7571:
1.44 crook 7572:
1.29 crook 7573: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7574: @subsection Number Conversion
7575: @cindex number conversion
7576: @cindex double-cell numbers, input format
7577: @cindex input format for double-cell numbers
7578: @cindex single-cell numbers, input format
7579: @cindex input format for single-cell numbers
7580: @cindex floating-point numbers, input format
7581: @cindex input format for floating-point numbers
1.1 anton 7582:
1.29 crook 7583: This section describes the rules that the text interpreter uses when it
7584: tries to convert a string into a number.
1.1 anton 7585:
1.26 crook 7586: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7587: number base@footnote{For example, 0-9 when the number base is decimal or
7588: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7589:
1.26 crook 7590: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7591:
1.29 crook 7592: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7593: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7594:
1.26 crook 7595: Let * represent any number of instances of the previous character
7596: (including none).
1.1 anton 7597:
1.26 crook 7598: Let any other character represent itself.
1.1 anton 7599:
1.29 crook 7600: @noindent
1.26 crook 7601: Now, the conversion rules are:
1.21 crook 7602:
1.26 crook 7603: @itemize @bullet
7604: @item
7605: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7606: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7607: @item
7608: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7609: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7610: arithmetic. Examples are -45 -5681 -0
7611: @item
7612: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7613: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7614: (all three of these represent the same number).
1.26 crook 7615: @item
7616: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7617: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7618: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7619: -34.65 (all three of these represent the same number).
1.26 crook 7620: @item
1.29 crook 7621: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7622: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7623: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7624: number) +12.E-4
1.26 crook 7625: @end itemize
1.1 anton 7626:
1.26 crook 7627: By default, the number base used for integer number conversion is given
1.35 anton 7628: by the contents of the variable @code{base}. Note that a lot of
7629: confusion can result from unexpected values of @code{base}. If you
7630: change @code{base} anywhere, make sure to save the old value and restore
7631: it afterwards. In general I recommend keeping @code{base} decimal, and
7632: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7633:
1.29 crook 7634: doc-dpl
1.26 crook 7635: doc-base
7636: doc-hex
7637: doc-decimal
1.1 anton 7638:
1.26 crook 7639: @cindex '-prefix for character strings
7640: @cindex &-prefix for decimal numbers
1.133 anton 7641: @cindex #-prefix for decimal numbers
1.26 crook 7642: @cindex %-prefix for binary numbers
7643: @cindex $-prefix for hexadecimal numbers
1.133 anton 7644: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7645: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7646: prefix@footnote{Some Forth implementations provide a similar scheme by
7647: implementing @code{$} etc. as parsing words that process the subsequent
7648: number in the input stream and push it onto the stack. For example, see
7649: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7650: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7651: is required between the prefix and the number.} before the first digit
1.133 anton 7652: of an (integer) number. The following prefixes are supported:
1.1 anton 7653:
1.26 crook 7654: @itemize @bullet
7655: @item
1.35 anton 7656: @code{&} -- decimal
1.26 crook 7657: @item
1.133 anton 7658: @code{#} -- decimal
7659: @item
1.35 anton 7660: @code{%} -- binary
1.26 crook 7661: @item
1.35 anton 7662: @code{$} -- hexadecimal
1.26 crook 7663: @item
1.133 anton 7664: @code{0x} -- hexadecimal, if base<33.
7665: @item
7666: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7667: optional @code{'} may be present after the character.
1.26 crook 7668: @end itemize
1.1 anton 7669:
1.26 crook 7670: Here are some examples, with the equivalent decimal number shown after
7671: in braces:
1.1 anton 7672:
1.26 crook 7673: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7674: 'A (65),
7675: -'a' (-97),
1.26 crook 7676: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7677:
1.26 crook 7678: @cindex number conversion - traps for the unwary
1.29 crook 7679: @noindent
1.26 crook 7680: Number conversion has a number of traps for the unwary:
1.1 anton 7681:
1.26 crook 7682: @itemize @bullet
7683: @item
7684: You cannot determine the current number base using the code sequence
1.35 anton 7685: @code{base @@ .} -- the number base is always 10 in the current number
7686: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7687: @item
7688: If the number base is set to a value greater than 14 (for example,
7689: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7690: it to be intepreted as either a single-precision integer or a
7691: floating-point number (Gforth treats it as an integer). The ambiguity
7692: can be resolved by explicitly stating the sign of the mantissa and/or
7693: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7694: ambiguity arises; either representation will be treated as a
7695: floating-point number.
7696: @item
1.29 crook 7697: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7698: It is used to specify file types.
7699: @item
1.72 anton 7700: ANS Forth requires the @code{.} of a double-precision number to be the
7701: final character in the string. Gforth allows the @code{.} to be
7702: anywhere after the first digit.
1.26 crook 7703: @item
7704: The number conversion process does not check for overflow.
7705: @item
1.72 anton 7706: In an ANS Forth program @code{base} is required to be decimal when
7707: converting floating-point numbers. In Gforth, number conversion to
7708: floating-point numbers always uses base &10, irrespective of the value
7709: of @code{base}.
1.26 crook 7710: @end itemize
1.1 anton 7711:
1.49 anton 7712: You can read numbers into your programs with the words described in
7713: @ref{Input}.
1.1 anton 7714:
1.82 anton 7715: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7716: @subsection Interpret/Compile states
7717: @cindex Interpret/Compile states
1.1 anton 7718:
1.29 crook 7719: A standard program is not permitted to change @code{state}
7720: explicitly. However, it can change @code{state} implicitly, using the
7721: words @code{[} and @code{]}. When @code{[} is executed it switches
7722: @code{state} to interpret state, and therefore the text interpreter
7723: starts interpreting. When @code{]} is executed it switches @code{state}
7724: to compile state and therefore the text interpreter starts
1.44 crook 7725: compiling. The most common usage for these words is for switching into
7726: interpret state and back from within a colon definition; this technique
1.49 anton 7727: can be used to compile a literal (for an example, @pxref{Literals}) or
7728: for conditional compilation (for an example, @pxref{Interpreter
7729: Directives}).
1.44 crook 7730:
1.35 anton 7731:
7732: @c This is a bad example: It's non-standard, and it's not necessary.
7733: @c However, I can't think of a good example for switching into compile
7734: @c state when there is no current word (@code{state}-smart words are not a
7735: @c good reason). So maybe we should use an example for switching into
7736: @c interpret @code{state} in a colon def. - anton
1.44 crook 7737: @c nac-> I agree. I started out by putting in the example, then realised
7738: @c that it was non-ANS, so wrote more words around it. I hope this
7739: @c re-written version is acceptable to you. I do want to keep the example
7740: @c as it is helpful for showing what is and what is not portable, particularly
7741: @c where it outlaws a style in common use.
7742:
1.72 anton 7743: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7744: @c that, we can also show what's not. In any case, I have written a
7745: @c section Compiling Words which also deals with [ ].
1.35 anton 7746:
1.95 anton 7747: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7748:
1.95 anton 7749: @c @code{[} and @code{]} also give you the ability to switch into compile
7750: @c state and back, but we cannot think of any useful Standard application
7751: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7752:
7753: @c @example
7754: @c : AA ." this is A" ;
7755: @c : BB ." this is B" ;
7756: @c : CC ." this is C" ;
7757:
7758: @c create table ] aa bb cc [
7759:
7760: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7761: @c cells table + @@ execute ;
7762: @c @end example
7763:
7764: @c This example builds a jump table; @code{0 go} will display ``@code{this
7765: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7766: @c defining @code{table} like this:
7767:
7768: @c @example
7769: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7770: @c @end example
7771:
7772: @c The problem with this code is that the definition of @code{table} is not
7773: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7774: @c @i{may} work on systems where code space and data space co-incide, the
7775: @c Standard only allows data space to be assigned for a @code{CREATE}d
7776: @c word. In addition, the Standard only allows @code{@@} to access data
7777: @c space, whilst this example is using it to access code space. The only
7778: @c portable, Standard way to build this table is to build it in data space,
7779: @c like this:
7780:
7781: @c @example
7782: @c create table ' aa , ' bb , ' cc ,
7783: @c @end example
1.29 crook 7784:
1.95 anton 7785: @c doc-state
1.44 crook 7786:
1.29 crook 7787:
1.82 anton 7788: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7789: @subsection Interpreter Directives
7790: @cindex interpreter directives
1.72 anton 7791: @cindex conditional compilation
1.1 anton 7792:
1.29 crook 7793: These words are usually used in interpret state; typically to control
7794: which parts of a source file are processed by the text
1.26 crook 7795: interpreter. There are only a few ANS Forth Standard words, but Gforth
7796: supplements these with a rich set of immediate control structure words
7797: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7798: used in compile state (@pxref{Control Structures}). Typical usages:
7799:
7800: @example
1.72 anton 7801: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7802: .
7803: .
1.72 anton 7804: HAVE-ASSEMBLER [IF]
1.29 crook 7805: : ASSEMBLER-FEATURE
7806: ...
7807: ;
7808: [ENDIF]
7809: .
7810: .
7811: : SEE
7812: ... \ general-purpose SEE code
1.72 anton 7813: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7814: ... \ assembler-specific SEE code
7815: [ [ENDIF] ]
7816: ;
7817: @end example
1.1 anton 7818:
1.44 crook 7819:
1.26 crook 7820: doc-[IF]
7821: doc-[ELSE]
7822: doc-[THEN]
7823: doc-[ENDIF]
1.1 anton 7824:
1.26 crook 7825: doc-[IFDEF]
7826: doc-[IFUNDEF]
1.1 anton 7827:
1.26 crook 7828: doc-[?DO]
7829: doc-[DO]
7830: doc-[FOR]
7831: doc-[LOOP]
7832: doc-[+LOOP]
7833: doc-[NEXT]
1.1 anton 7834:
1.26 crook 7835: doc-[BEGIN]
7836: doc-[UNTIL]
7837: doc-[AGAIN]
7838: doc-[WHILE]
7839: doc-[REPEAT]
1.1 anton 7840:
1.27 crook 7841:
1.26 crook 7842: @c -------------------------------------------------------------
1.111 anton 7843: @node The Input Stream, Word Lists, The Text Interpreter, Words
7844: @section The Input Stream
7845: @cindex input stream
7846:
7847: @c !! integrate this better with the "Text Interpreter" section
7848: The text interpreter reads from the input stream, which can come from
7849: several sources (@pxref{Input Sources}). Some words, in particular
7850: defining words, but also words like @code{'}, read parameters from the
7851: input stream instead of from the stack.
7852:
7853: Such words are called parsing words, because they parse the input
7854: stream. Parsing words are hard to use in other words, because it is
7855: hard to pass program-generated parameters through the input stream.
7856: They also usually have an unintuitive combination of interpretation and
7857: compilation semantics when implemented naively, leading to various
7858: approaches that try to produce a more intuitive behaviour
7859: (@pxref{Combined words}).
7860:
7861: It should be obvious by now that parsing words are a bad idea. If you
7862: want to implement a parsing word for convenience, also provide a factor
7863: of the word that does not parse, but takes the parameters on the stack.
7864: To implement the parsing word on top if it, you can use the following
7865: words:
7866:
7867: @c anton: these belong in the input stream section
7868: doc-parse
1.138 anton 7869: doc-parse-name
1.111 anton 7870: doc-parse-word
7871: doc-name
7872: doc-word
7873: doc-\"-parse
7874: doc-refill
7875:
7876: Conversely, if you have the bad luck (or lack of foresight) to have to
7877: deal with parsing words without having such factors, how do you pass a
7878: string that is not in the input stream to it?
7879:
7880: doc-execute-parsing
7881:
1.146 anton 7882: A definition of this word in ANS Forth is provided in
7883: @file{compat/execute-parsing.fs}.
7884:
1.111 anton 7885: If you want to run a parsing word on a file, the following word should
7886: help:
7887:
7888: doc-execute-parsing-file
7889:
7890: @c -------------------------------------------------------------
7891: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 7892: @section Word Lists
7893: @cindex word lists
1.32 anton 7894: @cindex header space
1.1 anton 7895:
1.36 anton 7896: A wordlist is a list of named words; you can add new words and look up
7897: words by name (and you can remove words in a restricted way with
7898: markers). Every named (and @code{reveal}ed) word is in one wordlist.
7899:
7900: @cindex search order stack
7901: The text interpreter searches the wordlists present in the search order
7902: (a stack of wordlists), from the top to the bottom. Within each
7903: wordlist, the search starts conceptually at the newest word; i.e., if
7904: two words in a wordlist have the same name, the newer word is found.
1.1 anton 7905:
1.26 crook 7906: @cindex compilation word list
1.36 anton 7907: New words are added to the @dfn{compilation wordlist} (aka current
7908: wordlist).
1.1 anton 7909:
1.36 anton 7910: @cindex wid
7911: A word list is identified by a cell-sized word list identifier (@i{wid})
7912: in much the same way as a file is identified by a file handle. The
7913: numerical value of the wid has no (portable) meaning, and might change
7914: from session to session.
1.1 anton 7915:
1.29 crook 7916: The ANS Forth ``Search order'' word set is intended to provide a set of
7917: low-level tools that allow various different schemes to be
1.74 anton 7918: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 7919: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 7920: Forth.
1.1 anton 7921:
1.27 crook 7922: @comment TODO: locals section refers to here, saying that every word list (aka
7923: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 7924: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 7925:
1.45 crook 7926: @comment TODO: document markers, reveal, tables, mappedwordlist
7927:
7928: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 7929: @comment word from the source files, rather than some alias.
1.44 crook 7930:
1.26 crook 7931: doc-forth-wordlist
7932: doc-definitions
7933: doc-get-current
7934: doc-set-current
7935: doc-get-order
1.45 crook 7936: doc---gforthman-set-order
1.26 crook 7937: doc-wordlist
1.30 anton 7938: doc-table
1.79 anton 7939: doc->order
1.36 anton 7940: doc-previous
1.26 crook 7941: doc-also
1.45 crook 7942: doc---gforthman-forth
1.26 crook 7943: doc-only
1.45 crook 7944: doc---gforthman-order
1.15 anton 7945:
1.26 crook 7946: doc-find
7947: doc-search-wordlist
1.15 anton 7948:
1.26 crook 7949: doc-words
7950: doc-vlist
1.44 crook 7951: @c doc-words-deferred
1.1 anton 7952:
1.74 anton 7953: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 7954: doc-root
7955: doc-vocabulary
7956: doc-seal
7957: doc-vocs
7958: doc-current
7959: doc-context
1.1 anton 7960:
1.44 crook 7961:
1.26 crook 7962: @menu
1.75 anton 7963: * Vocabularies::
1.67 anton 7964: * Why use word lists?::
1.75 anton 7965: * Word list example::
1.26 crook 7966: @end menu
7967:
1.75 anton 7968: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
7969: @subsection Vocabularies
7970: @cindex Vocabularies, detailed explanation
7971:
7972: Here is an example of creating and using a new wordlist using ANS
7973: Forth words:
7974:
7975: @example
7976: wordlist constant my-new-words-wordlist
7977: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
7978:
7979: \ add it to the search order
7980: also my-new-words
7981:
7982: \ alternatively, add it to the search order and make it
7983: \ the compilation word list
7984: also my-new-words definitions
7985: \ type "order" to see the problem
7986: @end example
7987:
7988: The problem with this example is that @code{order} has no way to
7989: associate the name @code{my-new-words} with the wid of the word list (in
7990: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
7991: that has no associated name). There is no Standard way of associating a
7992: name with a wid.
7993:
7994: In Gforth, this example can be re-coded using @code{vocabulary}, which
7995: associates a name with a wid:
7996:
7997: @example
7998: vocabulary my-new-words
7999:
8000: \ add it to the search order
8001: also my-new-words
8002:
8003: \ alternatively, add it to the search order and make it
8004: \ the compilation word list
8005: my-new-words definitions
8006: \ type "order" to see that the problem is solved
8007: @end example
8008:
8009:
8010: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8011: @subsection Why use word lists?
8012: @cindex word lists - why use them?
8013:
1.74 anton 8014: Here are some reasons why people use wordlists:
1.26 crook 8015:
8016: @itemize @bullet
1.74 anton 8017:
8018: @c anton: Gforth's hashing implementation makes the search speed
8019: @c independent from the number of words. But it is linear with the number
8020: @c of wordlists that have to be searched, so in effect using more wordlists
8021: @c actually slows down compilation.
8022:
8023: @c @item
8024: @c To improve compilation speed by reducing the number of header space
8025: @c entries that must be searched. This is achieved by creating a new
8026: @c word list that contains all of the definitions that are used in the
8027: @c definition of a Forth system but which would not usually be used by
8028: @c programs running on that system. That word list would be on the search
8029: @c list when the Forth system was compiled but would be removed from the
8030: @c search list for normal operation. This can be a useful technique for
8031: @c low-performance systems (for example, 8-bit processors in embedded
8032: @c systems) but is unlikely to be necessary in high-performance desktop
8033: @c systems.
8034:
1.26 crook 8035: @item
8036: To prevent a set of words from being used outside the context in which
8037: they are valid. Two classic examples of this are an integrated editor
8038: (all of the edit commands are defined in a separate word list; the
8039: search order is set to the editor word list when the editor is invoked;
8040: the old search order is restored when the editor is terminated) and an
8041: integrated assembler (the op-codes for the machine are defined in a
8042: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8043:
8044: @item
8045: To organize the words of an application or library into a user-visible
8046: set (in @code{forth-wordlist} or some other common wordlist) and a set
8047: of helper words used just for the implementation (hidden in a separate
1.75 anton 8048: wordlist). This keeps @code{words}' output smaller, separates
8049: implementation and interface, and reduces the chance of name conflicts
8050: within the common wordlist.
1.74 anton 8051:
1.26 crook 8052: @item
8053: To prevent a name-space clash between multiple definitions with the same
8054: name. For example, when building a cross-compiler you might have a word
8055: @code{IF} that generates conditional code for your target system. By
8056: placing this definition in a different word list you can control whether
8057: the host system's @code{IF} or the target system's @code{IF} get used in
8058: any particular context by controlling the order of the word lists on the
8059: search order stack.
1.74 anton 8060:
1.26 crook 8061: @end itemize
1.1 anton 8062:
1.74 anton 8063: The downsides of using wordlists are:
8064:
8065: @itemize
8066:
8067: @item
8068: Debugging becomes more cumbersome.
8069:
8070: @item
8071: Name conflicts worked around with wordlists are still there, and you
8072: have to arrange the search order carefully to get the desired results;
8073: if you forget to do that, you get hard-to-find errors (as in any case
8074: where you read the code differently from the compiler; @code{see} can
1.75 anton 8075: help seeing which of several possible words the name resolves to in such
8076: cases). @code{See} displays just the name of the words, not what
8077: wordlist they belong to, so it might be misleading. Using unique names
8078: is a better approach to avoid name conflicts.
1.74 anton 8079:
8080: @item
8081: You have to explicitly undo any changes to the search order. In many
8082: cases it would be more convenient if this happened implicitly. Gforth
8083: currently does not provide such a feature, but it may do so in the
8084: future.
8085: @end itemize
8086:
8087:
1.75 anton 8088: @node Word list example, , Why use word lists?, Word Lists
8089: @subsection Word list example
8090: @cindex word lists - example
1.1 anton 8091:
1.74 anton 8092: The following example is from the
8093: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8094: garbage collector} and uses wordlists to separate public words from
8095: helper words:
8096:
8097: @example
8098: get-current ( wid )
8099: vocabulary garbage-collector also garbage-collector definitions
8100: ... \ define helper words
8101: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8102: ... \ define the public (i.e., API) words
8103: \ they can refer to the helper words
8104: previous \ restore original search order (helper words become invisible)
8105: @end example
8106:
1.26 crook 8107: @c -------------------------------------------------------------
8108: @node Environmental Queries, Files, Word Lists, Words
8109: @section Environmental Queries
8110: @cindex environmental queries
1.21 crook 8111:
1.26 crook 8112: ANS Forth introduced the idea of ``environmental queries'' as a way
8113: for a program running on a system to determine certain characteristics of the system.
8114: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8115:
1.32 anton 8116: The Standard requires that the header space used for environmental queries
8117: be distinct from the header space used for definitions.
1.21 crook 8118:
1.26 crook 8119: Typically, environmental queries are supported by creating a set of
1.29 crook 8120: definitions in a word list that is @i{only} used during environmental
1.26 crook 8121: queries; that is what Gforth does. There is no Standard way of adding
8122: definitions to the set of recognised environmental queries, but any
8123: implementation that supports the loading of optional word sets must have
8124: some mechanism for doing this (after loading the word set, the
8125: associated environmental query string must return @code{true}). In
8126: Gforth, the word list used to honour environmental queries can be
8127: manipulated just like any other word list.
1.21 crook 8128:
1.44 crook 8129:
1.26 crook 8130: doc-environment?
8131: doc-environment-wordlist
1.21 crook 8132:
1.26 crook 8133: doc-gforth
8134: doc-os-class
1.21 crook 8135:
1.44 crook 8136:
1.26 crook 8137: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8138: returning two items on the stack, querying it using @code{environment?}
8139: will return an additional item; the @code{true} flag that shows that the
8140: string was recognised.
1.21 crook 8141:
1.26 crook 8142: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8143:
1.26 crook 8144: Here are some examples of using environmental queries:
1.21 crook 8145:
1.26 crook 8146: @example
8147: s" address-unit-bits" environment? 0=
8148: [IF]
8149: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8150: [ELSE]
8151: drop \ ensure balanced stack effect
1.26 crook 8152: [THEN]
1.21 crook 8153:
1.75 anton 8154: \ this might occur in the prelude of a standard program that uses THROW
8155: s" exception" environment? [IF]
8156: 0= [IF]
8157: : throw abort" exception thrown" ;
8158: [THEN]
8159: [ELSE] \ we don't know, so make sure
8160: : throw abort" exception thrown" ;
8161: [THEN]
1.21 crook 8162:
1.26 crook 8163: s" gforth" environment? [IF] .( Gforth version ) TYPE
8164: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8165:
8166: \ a program using v*
8167: s" gforth" environment? [IF]
8168: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8169: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8170: >r swap 2swap swap 0e r> 0 ?DO
8171: dup f@ over + 2swap dup f@ f* f+ over + 2swap
8172: LOOP
8173: 2drop 2drop ;
8174: [THEN]
8175: [ELSE] \
8176: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8177: ...
8178: [THEN]
1.26 crook 8179: @end example
1.21 crook 8180:
1.26 crook 8181: Here is an example of adding a definition to the environment word list:
1.21 crook 8182:
1.26 crook 8183: @example
8184: get-current environment-wordlist set-current
8185: true constant block
8186: true constant block-ext
8187: set-current
8188: @end example
1.21 crook 8189:
1.26 crook 8190: You can see what definitions are in the environment word list like this:
1.21 crook 8191:
1.26 crook 8192: @example
1.79 anton 8193: environment-wordlist >order words previous
1.26 crook 8194: @end example
1.21 crook 8195:
8196:
1.26 crook 8197: @c -------------------------------------------------------------
8198: @node Files, Blocks, Environmental Queries, Words
8199: @section Files
1.28 crook 8200: @cindex files
8201: @cindex I/O - file-handling
1.21 crook 8202:
1.26 crook 8203: Gforth provides facilities for accessing files that are stored in the
8204: host operating system's file-system. Files that are processed by Gforth
8205: can be divided into two categories:
1.21 crook 8206:
1.23 crook 8207: @itemize @bullet
8208: @item
1.29 crook 8209: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8210: @item
1.29 crook 8211: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8212: @end itemize
8213:
8214: @menu
1.48 anton 8215: * Forth source files::
8216: * General files::
8217: * Search Paths::
1.26 crook 8218: @end menu
8219:
8220: @c -------------------------------------------------------------
8221: @node Forth source files, General files, Files, Files
8222: @subsection Forth source files
8223: @cindex including files
8224: @cindex Forth source files
1.21 crook 8225:
1.26 crook 8226: The simplest way to interpret the contents of a file is to use one of
8227: these two formats:
1.21 crook 8228:
1.26 crook 8229: @example
8230: include mysource.fs
8231: s" mysource.fs" included
8232: @end example
1.21 crook 8233:
1.75 anton 8234: You usually want to include a file only if it is not included already
1.26 crook 8235: (by, say, another source file). In that case, you can use one of these
1.45 crook 8236: three formats:
1.21 crook 8237:
1.26 crook 8238: @example
8239: require mysource.fs
8240: needs mysource.fs
8241: s" mysource.fs" required
8242: @end example
1.21 crook 8243:
1.26 crook 8244: @cindex stack effect of included files
8245: @cindex including files, stack effect
1.45 crook 8246: It is good practice to write your source files such that interpreting them
8247: does not change the stack. Source files designed in this way can be used with
1.26 crook 8248: @code{required} and friends without complications. For example:
1.21 crook 8249:
1.26 crook 8250: @example
1.75 anton 8251: 1024 require foo.fs drop
1.26 crook 8252: @end example
1.21 crook 8253:
1.75 anton 8254: Here you want to pass the argument 1024 (e.g., a buffer size) to
8255: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8256: ), which allows its use with @code{require}. Of course with such
8257: parameters to required files, you have to ensure that the first
8258: @code{require} fits for all uses (i.e., @code{require} it early in the
8259: master load file).
1.44 crook 8260:
1.26 crook 8261: doc-include-file
8262: doc-included
1.28 crook 8263: doc-included?
1.26 crook 8264: doc-include
8265: doc-required
8266: doc-require
8267: doc-needs
1.75 anton 8268: @c doc-init-included-files @c internal
8269: doc-sourcefilename
8270: doc-sourceline#
1.44 crook 8271:
1.26 crook 8272: A definition in ANS Forth for @code{required} is provided in
8273: @file{compat/required.fs}.
1.21 crook 8274:
1.26 crook 8275: @c -------------------------------------------------------------
8276: @node General files, Search Paths, Forth source files, Files
8277: @subsection General files
8278: @cindex general files
8279: @cindex file-handling
1.21 crook 8280:
1.75 anton 8281: Files are opened/created by name and type. The following file access
8282: methods (FAMs) are recognised:
1.44 crook 8283:
1.75 anton 8284: @cindex fam (file access method)
1.26 crook 8285: doc-r/o
8286: doc-r/w
8287: doc-w/o
8288: doc-bin
1.1 anton 8289:
1.44 crook 8290:
1.26 crook 8291: When a file is opened/created, it returns a file identifier,
1.29 crook 8292: @i{wfileid} that is used for all other file commands. All file
8293: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8294: successful operation and an implementation-defined non-zero value in the
8295: case of an error.
1.21 crook 8296:
1.44 crook 8297:
1.26 crook 8298: doc-open-file
8299: doc-create-file
1.21 crook 8300:
1.26 crook 8301: doc-close-file
8302: doc-delete-file
8303: doc-rename-file
8304: doc-read-file
8305: doc-read-line
1.154 anton 8306: doc-key-file
8307: doc-key?-file
1.26 crook 8308: doc-write-file
8309: doc-write-line
8310: doc-emit-file
8311: doc-flush-file
1.21 crook 8312:
1.26 crook 8313: doc-file-status
8314: doc-file-position
8315: doc-reposition-file
8316: doc-file-size
8317: doc-resize-file
1.21 crook 8318:
1.93 anton 8319: doc-slurp-file
8320: doc-slurp-fid
1.112 anton 8321: doc-stdin
8322: doc-stdout
8323: doc-stderr
1.44 crook 8324:
1.26 crook 8325: @c ---------------------------------------------------------
1.48 anton 8326: @node Search Paths, , General files, Files
1.26 crook 8327: @subsection Search Paths
8328: @cindex path for @code{included}
8329: @cindex file search path
8330: @cindex @code{include} search path
8331: @cindex search path for files
1.21 crook 8332:
1.26 crook 8333: If you specify an absolute filename (i.e., a filename starting with
8334: @file{/} or @file{~}, or with @file{:} in the second position (as in
8335: @samp{C:...})) for @code{included} and friends, that file is included
8336: just as you would expect.
1.21 crook 8337:
1.75 anton 8338: If the filename starts with @file{./}, this refers to the directory that
8339: the present file was @code{included} from. This allows files to include
8340: other files relative to their own position (irrespective of the current
8341: working directory or the absolute position). This feature is essential
8342: for libraries consisting of several files, where a file may include
8343: other files from the library. It corresponds to @code{#include "..."}
8344: in C. If the current input source is not a file, @file{.} refers to the
8345: directory of the innermost file being included, or, if there is no file
8346: being included, to the current working directory.
8347:
8348: For relative filenames (not starting with @file{./}), Gforth uses a
8349: search path similar to Forth's search order (@pxref{Word Lists}). It
8350: tries to find the given filename in the directories present in the path,
8351: and includes the first one it finds. There are separate search paths for
8352: Forth source files and general files. If the search path contains the
8353: directory @file{.}, this refers to the directory of the current file, or
8354: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8355:
1.26 crook 8356: Use @file{~+} to refer to the current working directory (as in the
8357: @code{bash}).
1.1 anton 8358:
1.75 anton 8359: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8360:
1.48 anton 8361: @menu
1.75 anton 8362: * Source Search Paths::
1.48 anton 8363: * General Search Paths::
8364: @end menu
8365:
1.26 crook 8366: @c ---------------------------------------------------------
1.75 anton 8367: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8368: @subsubsection Source Search Paths
8369: @cindex search path control, source files
1.5 anton 8370:
1.26 crook 8371: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8372: Gforth}). You can display it and change it using @code{fpath} in
8373: combination with the general path handling words.
1.5 anton 8374:
1.75 anton 8375: doc-fpath
8376: @c the functionality of the following words is easily available through
8377: @c fpath and the general path words. The may go away.
8378: @c doc-.fpath
8379: @c doc-fpath+
8380: @c doc-fpath=
8381: @c doc-open-fpath-file
1.44 crook 8382:
8383: @noindent
1.26 crook 8384: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8385:
1.26 crook 8386: @example
1.75 anton 8387: fpath path= /usr/lib/forth/|./
1.26 crook 8388: require timer.fs
8389: @end example
1.5 anton 8390:
1.75 anton 8391:
1.26 crook 8392: @c ---------------------------------------------------------
1.75 anton 8393: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8394: @subsubsection General Search Paths
1.75 anton 8395: @cindex search path control, source files
1.5 anton 8396:
1.26 crook 8397: Your application may need to search files in several directories, like
8398: @code{included} does. To facilitate this, Gforth allows you to define
8399: and use your own search paths, by providing generic equivalents of the
8400: Forth search path words:
1.5 anton 8401:
1.75 anton 8402: doc-open-path-file
8403: doc-path-allot
8404: doc-clear-path
8405: doc-also-path
1.26 crook 8406: doc-.path
8407: doc-path+
8408: doc-path=
1.5 anton 8409:
1.75 anton 8410: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8411:
1.75 anton 8412: Here's an example of creating an empty search path:
8413: @c
1.26 crook 8414: @example
1.75 anton 8415: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8416: @end example
1.5 anton 8417:
1.26 crook 8418: @c -------------------------------------------------------------
8419: @node Blocks, Other I/O, Files, Words
8420: @section Blocks
1.28 crook 8421: @cindex I/O - blocks
8422: @cindex blocks
8423:
8424: When you run Gforth on a modern desk-top computer, it runs under the
8425: control of an operating system which provides certain services. One of
8426: these services is @var{file services}, which allows Forth source code
8427: and data to be stored in files and read into Gforth (@pxref{Files}).
8428:
8429: Traditionally, Forth has been an important programming language on
8430: systems where it has interfaced directly to the underlying hardware with
8431: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8432: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8433:
8434: A block is a 1024-byte data area, which can be used to hold data or
8435: Forth source code. No structure is imposed on the contents of the
8436: block. A block is identified by its number; blocks are numbered
8437: contiguously from 1 to an implementation-defined maximum.
8438:
8439: A typical system that used blocks but no operating system might use a
8440: single floppy-disk drive for mass storage, with the disks formatted to
8441: provide 256-byte sectors. Blocks would be implemented by assigning the
8442: first four sectors of the disk to block 1, the second four sectors to
8443: block 2 and so on, up to the limit of the capacity of the disk. The disk
8444: would not contain any file system information, just the set of blocks.
8445:
1.29 crook 8446: @cindex blocks file
1.28 crook 8447: On systems that do provide file services, blocks are typically
1.29 crook 8448: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8449: file}. The size of the blocks file will be an exact multiple of 1024
8450: bytes, corresponding to the number of blocks it contains. This is the
8451: mechanism that Gforth uses.
8452:
1.29 crook 8453: @cindex @file{blocks.fb}
1.75 anton 8454: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8455: having specified a blocks file, Gforth defaults to the blocks file
8456: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8457: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8458:
1.29 crook 8459: @cindex block buffers
1.28 crook 8460: When you read and write blocks under program control, Gforth uses a
1.29 crook 8461: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8462: not used when you use @code{load} to interpret the contents of a block.
8463:
1.75 anton 8464: The behaviour of the block buffers is analagous to that of a cache.
8465: Each block buffer has three states:
1.28 crook 8466:
8467: @itemize @bullet
8468: @item
8469: Unassigned
8470: @item
8471: Assigned-clean
8472: @item
8473: Assigned-dirty
8474: @end itemize
8475:
1.29 crook 8476: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8477: block, the block (specified by its block number) must be assigned to a
8478: block buffer.
8479:
8480: The assignment of a block to a block buffer is performed by @code{block}
8481: or @code{buffer}. Use @code{block} when you wish to modify the existing
8482: contents of a block. Use @code{buffer} when you don't care about the
8483: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8484: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8485: with the particular block is already stored in a block buffer due to an
8486: earlier @code{block} command, @code{buffer} will return that block
8487: buffer and the existing contents of the block will be
8488: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8489: block buffer for the block.}.
1.28 crook 8490:
1.47 crook 8491: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8492: @code{buffer}, that block buffer becomes the @i{current block
8493: buffer}. Data may only be manipulated (read or written) within the
8494: current block buffer.
1.47 crook 8495:
8496: When the contents of the current block buffer has been modified it is
1.48 anton 8497: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8498: either abandon the changes (by doing nothing) or mark the block as
8499: changed (assigned-dirty), using @code{update}. Using @code{update} does
8500: not change the blocks file; it simply changes a block buffer's state to
8501: @i{assigned-dirty}. The block will be written implicitly when it's
8502: buffer is needed for another block, or explicitly by @code{flush} or
8503: @code{save-buffers}.
8504:
8505: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8506: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8507: @code{flush}.
1.28 crook 8508:
1.29 crook 8509: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8510: algorithm to assign a block buffer to a block. That means that any
8511: particular block can only be assigned to one specific block buffer,
1.29 crook 8512: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8513: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8514: the new block immediately. If it is @i{assigned-dirty} its current
8515: contents are written back to the blocks file on disk before it is
1.28 crook 8516: allocated to the new block.
8517:
8518: Although no structure is imposed on the contents of a block, it is
8519: traditional to display the contents as 16 lines each of 64 characters. A
8520: block provides a single, continuous stream of input (for example, it
8521: acts as a single parse area) -- there are no end-of-line characters
8522: within a block, and no end-of-file character at the end of a
8523: block. There are two consequences of this:
1.26 crook 8524:
1.28 crook 8525: @itemize @bullet
8526: @item
8527: The last character of one line wraps straight into the first character
8528: of the following line
8529: @item
8530: The word @code{\} -- comment to end of line -- requires special
8531: treatment; in the context of a block it causes all characters until the
8532: end of the current 64-character ``line'' to be ignored.
8533: @end itemize
8534:
8535: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8536: the current blocks file will be extended to the appropriate size and the
1.28 crook 8537: block buffer will be initialised with spaces.
8538:
1.47 crook 8539: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8540: for details) but doesn't encourage the use of blocks; the mechanism is
8541: only provided for backward compatibility -- ANS Forth requires blocks to
8542: be available when files are.
1.28 crook 8543:
8544: Common techniques that are used when working with blocks include:
8545:
8546: @itemize @bullet
8547: @item
8548: A screen editor that allows you to edit blocks without leaving the Forth
8549: environment.
8550: @item
8551: Shadow screens; where every code block has an associated block
8552: containing comments (for example: code in odd block numbers, comments in
8553: even block numbers). Typically, the block editor provides a convenient
8554: mechanism to toggle between code and comments.
8555: @item
8556: Load blocks; a single block (typically block 1) contains a number of
8557: @code{thru} commands which @code{load} the whole of the application.
8558: @end itemize
1.26 crook 8559:
1.29 crook 8560: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8561: integrated into a Forth programming environment.
1.26 crook 8562:
8563: @comment TODO what about errors on open-blocks?
1.44 crook 8564:
1.26 crook 8565: doc-open-blocks
8566: doc-use
1.75 anton 8567: doc-block-offset
1.26 crook 8568: doc-get-block-fid
8569: doc-block-position
1.28 crook 8570:
1.75 anton 8571: doc-list
1.28 crook 8572: doc-scr
8573:
1.45 crook 8574: doc---gforthman-block
1.28 crook 8575: doc-buffer
8576:
1.75 anton 8577: doc-empty-buffers
8578: doc-empty-buffer
1.26 crook 8579: doc-update
1.28 crook 8580: doc-updated?
1.26 crook 8581: doc-save-buffers
1.75 anton 8582: doc-save-buffer
1.26 crook 8583: doc-flush
1.28 crook 8584:
1.26 crook 8585: doc-load
8586: doc-thru
8587: doc-+load
8588: doc-+thru
1.45 crook 8589: doc---gforthman--->
1.26 crook 8590: doc-block-included
8591:
1.44 crook 8592:
1.26 crook 8593: @c -------------------------------------------------------------
1.126 pazsan 8594: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8595: @section Other I/O
1.28 crook 8596: @cindex I/O - keyboard and display
1.26 crook 8597:
8598: @menu
8599: * Simple numeric output:: Predefined formats
8600: * Formatted numeric output:: Formatted (pictured) output
8601: * String Formats:: How Forth stores strings in memory
1.67 anton 8602: * Displaying characters and strings:: Other stuff
1.26 crook 8603: * Input:: Input
1.112 anton 8604: * Pipes:: How to create your own pipes
1.149 pazsan 8605: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8606: @end menu
8607:
8608: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8609: @subsection Simple numeric output
1.28 crook 8610: @cindex numeric output - simple/free-format
1.5 anton 8611:
1.26 crook 8612: The simplest output functions are those that display numbers from the
8613: data or floating-point stacks. Floating-point output is always displayed
8614: using base 10. Numbers displayed from the data stack use the value stored
8615: in @code{base}.
1.5 anton 8616:
1.44 crook 8617:
1.26 crook 8618: doc-.
8619: doc-dec.
8620: doc-hex.
8621: doc-u.
8622: doc-.r
8623: doc-u.r
8624: doc-d.
8625: doc-ud.
8626: doc-d.r
8627: doc-ud.r
8628: doc-f.
8629: doc-fe.
8630: doc-fs.
1.111 anton 8631: doc-f.rdp
1.44 crook 8632:
1.26 crook 8633: Examples of printing the number 1234.5678E23 in the different floating-point output
8634: formats are shown below:
1.5 anton 8635:
8636: @example
1.26 crook 8637: f. 123456779999999000000000000.
8638: fe. 123.456779999999E24
8639: fs. 1.23456779999999E26
1.5 anton 8640: @end example
8641:
8642:
1.26 crook 8643: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8644: @subsection Formatted numeric output
1.28 crook 8645: @cindex formatted numeric output
1.26 crook 8646: @cindex pictured numeric output
1.28 crook 8647: @cindex numeric output - formatted
1.26 crook 8648:
1.29 crook 8649: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8650: output} for formatted printing of integers. In this technique, digits
8651: are extracted from the number (using the current output radix defined by
8652: @code{base}), converted to ASCII codes and appended to a string that is
8653: built in a scratch-pad area of memory (@pxref{core-idef,
8654: Implementation-defined options, Implementation-defined
8655: options}). Arbitrary characters can be appended to the string during the
8656: extraction process. The completed string is specified by an address
8657: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8658: under program control.
1.5 anton 8659:
1.75 anton 8660: All of the integer output words described in the previous section
8661: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8662: numeric output.
1.5 anton 8663:
1.47 crook 8664: Three important things to remember about pictured numeric output:
1.5 anton 8665:
1.26 crook 8666: @itemize @bullet
8667: @item
1.28 crook 8668: It always operates on double-precision numbers; to display a
1.49 anton 8669: single-precision number, convert it first (for ways of doing this
8670: @pxref{Double precision}).
1.26 crook 8671: @item
1.28 crook 8672: It always treats the double-precision number as though it were
8673: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8674: @item
8675: The string is built up from right to left; least significant digit first.
8676: @end itemize
1.5 anton 8677:
1.44 crook 8678:
1.26 crook 8679: doc-<#
1.47 crook 8680: doc-<<#
1.26 crook 8681: doc-#
8682: doc-#s
8683: doc-hold
8684: doc-sign
8685: doc-#>
1.47 crook 8686: doc-#>>
1.5 anton 8687:
1.26 crook 8688: doc-represent
1.111 anton 8689: doc-f>str-rdp
8690: doc-f>buf-rdp
1.5 anton 8691:
1.44 crook 8692:
8693: @noindent
1.26 crook 8694: Here are some examples of using pictured numeric output:
1.5 anton 8695:
8696: @example
1.26 crook 8697: : my-u. ( u -- )
8698: \ Simplest use of pns.. behaves like Standard u.
8699: 0 \ convert to unsigned double
1.75 anton 8700: <<# \ start conversion
1.26 crook 8701: #s \ convert all digits
8702: #> \ complete conversion
1.75 anton 8703: TYPE SPACE \ display, with trailing space
8704: #>> ; \ release hold area
1.5 anton 8705:
1.26 crook 8706: : cents-only ( u -- )
8707: 0 \ convert to unsigned double
1.75 anton 8708: <<# \ start conversion
1.26 crook 8709: # # \ convert two least-significant digits
8710: #> \ complete conversion, discard other digits
1.75 anton 8711: TYPE SPACE \ display, with trailing space
8712: #>> ; \ release hold area
1.5 anton 8713:
1.26 crook 8714: : dollars-and-cents ( u -- )
8715: 0 \ convert to unsigned double
1.75 anton 8716: <<# \ start conversion
1.26 crook 8717: # # \ convert two least-significant digits
8718: [char] . hold \ insert decimal point
8719: #s \ convert remaining digits
8720: [char] $ hold \ append currency symbol
8721: #> \ complete conversion
1.75 anton 8722: TYPE SPACE \ display, with trailing space
8723: #>> ; \ release hold area
1.5 anton 8724:
1.26 crook 8725: : my-. ( n -- )
8726: \ handling negatives.. behaves like Standard .
8727: s>d \ convert to signed double
8728: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8729: <<# \ start conversion
1.26 crook 8730: #s \ convert all digits
8731: rot sign \ get at sign byte, append "-" if needed
8732: #> \ complete conversion
1.75 anton 8733: TYPE SPACE \ display, with trailing space
8734: #>> ; \ release hold area
1.5 anton 8735:
1.26 crook 8736: : account. ( n -- )
1.75 anton 8737: \ accountants don't like minus signs, they use parentheses
1.26 crook 8738: \ for negative numbers
8739: s>d \ convert to signed double
8740: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8741: <<# \ start conversion
1.26 crook 8742: 2 pick \ get copy of sign byte
8743: 0< IF [char] ) hold THEN \ right-most character of output
8744: #s \ convert all digits
8745: rot \ get at sign byte
8746: 0< IF [char] ( hold THEN
8747: #> \ complete conversion
1.75 anton 8748: TYPE SPACE \ display, with trailing space
8749: #>> ; \ release hold area
8750:
1.5 anton 8751: @end example
8752:
1.26 crook 8753: Here are some examples of using these words:
1.5 anton 8754:
8755: @example
1.26 crook 8756: 1 my-u. 1
8757: hex -1 my-u. decimal FFFFFFFF
8758: 1 cents-only 01
8759: 1234 cents-only 34
8760: 2 dollars-and-cents $0.02
8761: 1234 dollars-and-cents $12.34
8762: 123 my-. 123
8763: -123 my. -123
8764: 123 account. 123
8765: -456 account. (456)
1.5 anton 8766: @end example
8767:
8768:
1.26 crook 8769: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8770: @subsection String Formats
1.27 crook 8771: @cindex strings - see character strings
8772: @cindex character strings - formats
1.28 crook 8773: @cindex I/O - see character strings
1.75 anton 8774: @cindex counted strings
8775:
8776: @c anton: this does not really belong here; maybe the memory section,
8777: @c or the principles chapter
1.26 crook 8778:
1.27 crook 8779: Forth commonly uses two different methods for representing character
8780: strings:
1.26 crook 8781:
8782: @itemize @bullet
8783: @item
8784: @cindex address of counted string
1.45 crook 8785: @cindex counted string
1.29 crook 8786: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8787: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8788: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8789: memory.
8790: @item
1.29 crook 8791: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
8792: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 8793: first byte of the string.
8794: @end itemize
8795:
8796: ANS Forth encourages the use of the second format when representing
1.75 anton 8797: strings.
1.26 crook 8798:
1.44 crook 8799:
1.26 crook 8800: doc-count
8801:
1.44 crook 8802:
1.49 anton 8803: For words that move, copy and search for strings see @ref{Memory
8804: Blocks}. For words that display characters and strings see
8805: @ref{Displaying characters and strings}.
1.26 crook 8806:
8807: @node Displaying characters and strings, Input, String Formats, Other I/O
8808: @subsection Displaying characters and strings
1.27 crook 8809: @cindex characters - compiling and displaying
8810: @cindex character strings - compiling and displaying
1.26 crook 8811:
8812: This section starts with a glossary of Forth words and ends with a set
8813: of examples.
8814:
1.44 crook 8815:
1.26 crook 8816: doc-bl
8817: doc-space
8818: doc-spaces
8819: doc-emit
8820: doc-toupper
8821: doc-."
8822: doc-.(
1.98 anton 8823: doc-.\"
1.26 crook 8824: doc-type
1.44 crook 8825: doc-typewhite
1.26 crook 8826: doc-cr
1.27 crook 8827: @cindex cursor control
1.26 crook 8828: doc-at-xy
8829: doc-page
8830: doc-s"
1.98 anton 8831: doc-s\"
1.26 crook 8832: doc-c"
8833: doc-char
8834: doc-[char]
8835:
1.44 crook 8836:
8837: @noindent
1.26 crook 8838: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 8839:
8840: @example
1.26 crook 8841: .( text-1)
8842: : my-word
8843: ." text-2" cr
8844: .( text-3)
8845: ;
8846:
8847: ." text-4"
8848:
8849: : my-char
8850: [char] ALPHABET emit
8851: char emit
8852: ;
1.5 anton 8853: @end example
8854:
1.26 crook 8855: When you load this code into Gforth, the following output is generated:
1.5 anton 8856:
1.26 crook 8857: @example
1.30 anton 8858: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 8859: @end example
1.5 anton 8860:
1.26 crook 8861: @itemize @bullet
8862: @item
8863: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
8864: is an immediate word; it behaves in the same way whether it is used inside
8865: or outside a colon definition.
8866: @item
8867: Message @code{text-4} is displayed because of Gforth's added interpretation
8868: semantics for @code{."}.
8869: @item
1.29 crook 8870: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 8871: performs the compilation semantics for @code{."} within the definition of
8872: @code{my-word}.
8873: @end itemize
1.5 anton 8874:
1.26 crook 8875: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 8876:
1.26 crook 8877: @example
1.30 anton 8878: @kbd{my-word @key{RET}} text-2
1.26 crook 8879: ok
1.30 anton 8880: @kbd{my-char fred @key{RET}} Af ok
8881: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 8882: @end example
1.5 anton 8883:
8884: @itemize @bullet
8885: @item
1.26 crook 8886: Message @code{text-2} is displayed because of the run-time behaviour of
8887: @code{."}.
8888: @item
8889: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
8890: on the stack at run-time. @code{emit} always displays the character
8891: when @code{my-char} is executed.
8892: @item
8893: @code{char} parses a string at run-time and the second @code{emit} displays
8894: the first character of the string.
1.5 anton 8895: @item
1.26 crook 8896: If you type @code{see my-char} you can see that @code{[char]} discarded
8897: the text ``LPHABET'' and only compiled the display code for ``A'' into the
8898: definition of @code{my-char}.
1.5 anton 8899: @end itemize
8900:
8901:
8902:
1.112 anton 8903: @node Input, Pipes, Displaying characters and strings, Other I/O
1.26 crook 8904: @subsection Input
8905: @cindex input
1.28 crook 8906: @cindex I/O - see input
8907: @cindex parsing a string
1.5 anton 8908:
1.49 anton 8909: For ways of storing character strings in memory see @ref{String Formats}.
1.5 anton 8910:
1.27 crook 8911: @comment TODO examples for >number >float accept key key? pad parse word refill
1.29 crook 8912: @comment then index them
1.27 crook 8913:
1.44 crook 8914:
1.27 crook 8915: doc-key
8916: doc-key?
1.45 crook 8917: doc-ekey
1.141 anton 8918: doc-ekey>char
1.45 crook 8919: doc-ekey?
1.141 anton 8920:
8921: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
8922: you need the ANSI.SYS driver to get that behaviour). These are the
8923: keyboard events produced by various common keys:
8924:
8925: doc-k-left
8926: doc-k-right
8927: doc-k-up
8928: doc-k-down
8929: doc-k-home
8930: doc-k-end
8931: doc-k-prior
8932: doc-k-next
8933: doc-k-insert
8934: doc-k-delete
8935:
8936: The function keys (aka keypad keys) are:
8937:
8938: doc-k1
8939: doc-k2
8940: doc-k3
8941: doc-k4
8942: doc-k5
8943: doc-k6
8944: doc-k7
8945: doc-k8
8946: doc-k9
8947: doc-k10
8948: doc-k11
8949: doc-k12
8950:
8951: Note that K11 and K12 are not as widely available. The shifted
8952: function keys are also not very widely available:
8953:
8954: doc-s-k1
8955: doc-s-k2
8956: doc-s-k3
8957: doc-s-k4
8958: doc-s-k5
8959: doc-s-k6
8960: doc-s-k7
8961: doc-s-k8
8962: doc-s-k9
8963: doc-s-k10
8964: doc-s-k11
8965: doc-s-k12
8966:
8967: Words for inputting one line from the keyboard:
8968:
8969: doc-accept
8970: doc-edit-line
8971:
8972: Conversion words:
8973:
1.143 anton 8974: doc-s>number?
8975: doc-s>unumber?
1.26 crook 8976: doc->number
8977: doc->float
1.143 anton 8978:
1.141 anton 8979:
1.27 crook 8980: @comment obsolescent words..
1.141 anton 8981: Obsolescent input and conversion words:
8982:
1.27 crook 8983: doc-convert
1.26 crook 8984: doc-expect
1.27 crook 8985: doc-span
1.5 anton 8986:
8987:
1.149 pazsan 8988: @node Pipes, Xchars and Unicode, Input, Other I/O
1.112 anton 8989: @subsection Pipes
8990: @cindex pipes, creating your own
8991:
8992: In addition to using Gforth in pipes created by other processes
8993: (@pxref{Gforth in pipes}), you can create your own pipe with
8994: @code{open-pipe}, and read from or write to it.
8995:
8996: doc-open-pipe
8997: doc-close-pipe
8998:
8999: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9000: you don't catch this exception, Gforth will catch it and exit, usually
9001: silently (@pxref{Gforth in pipes}). Since you probably do not want
9002: this, you should wrap a @code{catch} or @code{try} block around the code
9003: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9004: problem yourself, and then return to regular processing.
9005:
9006: doc-broken-pipe-error
9007:
1.155 anton 9008: @node Xchars and Unicode, , Pipes, Other I/O
9009: @subsection Xchars and Unicode
1.149 pazsan 9010:
9011: This chapter needs completion
1.112 anton 9012:
1.121 anton 9013: @node OS command line arguments, Locals, Other I/O, Words
9014: @section OS command line arguments
9015: @cindex OS command line arguments
9016: @cindex command line arguments, OS
9017: @cindex arguments, OS command line
9018:
9019: The usual way to pass arguments to Gforth programs on the command line
9020: is via the @option{-e} option, e.g.
9021:
9022: @example
9023: gforth -e "123 456" foo.fs -e bye
9024: @end example
9025:
9026: However, you may want to interpret the command-line arguments directly.
9027: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9028: through @code{next-arg}:
1.121 anton 9029:
1.123 anton 9030: doc-next-arg
1.121 anton 9031:
1.123 anton 9032: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9033:
9034: @example
9035: : echo ( -- )
1.122 anton 9036: begin
1.123 anton 9037: next-arg 2dup 0 0 d<> while
9038: type space
9039: repeat
9040: 2drop ;
1.121 anton 9041:
9042: echo cr bye
9043: @end example
9044:
9045: This can be invoked with
9046:
9047: @example
9048: gforth echo.fs hello world
9049: @end example
1.123 anton 9050:
9051: and it will print
9052:
9053: @example
9054: hello world
9055: @end example
9056:
9057: The next lower level of dealing with the OS command line are the
9058: following words:
9059:
9060: doc-arg
9061: doc-shift-args
9062:
9063: Finally, at the lowest level Gforth provides the following words:
9064:
9065: doc-argc
9066: doc-argv
1.121 anton 9067:
1.78 anton 9068: @c -------------------------------------------------------------
1.126 pazsan 9069: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9070: @section Locals
9071: @cindex locals
9072:
9073: Local variables can make Forth programming more enjoyable and Forth
9074: programs easier to read. Unfortunately, the locals of ANS Forth are
9075: laden with restrictions. Therefore, we provide not only the ANS Forth
9076: locals wordset, but also our own, more powerful locals wordset (we
9077: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9078:
1.78 anton 9079: The ideas in this section have also been published in M. Anton Ertl,
9080: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9081: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9082:
9083: @menu
1.78 anton 9084: * Gforth locals::
9085: * ANS Forth locals::
1.5 anton 9086: @end menu
9087:
1.78 anton 9088: @node Gforth locals, ANS Forth locals, Locals, Locals
9089: @subsection Gforth locals
9090: @cindex Gforth locals
9091: @cindex locals, Gforth style
1.5 anton 9092:
1.78 anton 9093: Locals can be defined with
1.44 crook 9094:
1.78 anton 9095: @example
9096: @{ local1 local2 ... -- comment @}
9097: @end example
9098: or
9099: @example
9100: @{ local1 local2 ... @}
9101: @end example
1.5 anton 9102:
1.78 anton 9103: E.g.,
9104: @example
9105: : max @{ n1 n2 -- n3 @}
9106: n1 n2 > if
9107: n1
9108: else
9109: n2
9110: endif ;
9111: @end example
1.44 crook 9112:
1.78 anton 9113: The similarity of locals definitions with stack comments is intended. A
9114: locals definition often replaces the stack comment of a word. The order
9115: of the locals corresponds to the order in a stack comment and everything
9116: after the @code{--} is really a comment.
1.77 anton 9117:
1.78 anton 9118: This similarity has one disadvantage: It is too easy to confuse locals
9119: declarations with stack comments, causing bugs and making them hard to
9120: find. However, this problem can be avoided by appropriate coding
9121: conventions: Do not use both notations in the same program. If you do,
9122: they should be distinguished using additional means, e.g. by position.
1.77 anton 9123:
1.78 anton 9124: @cindex types of locals
9125: @cindex locals types
9126: The name of the local may be preceded by a type specifier, e.g.,
9127: @code{F:} for a floating point value:
1.5 anton 9128:
1.78 anton 9129: @example
9130: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9131: \ complex multiplication
9132: Ar Br f* Ai Bi f* f-
9133: Ar Bi f* Ai Br f* f+ ;
9134: @end example
1.44 crook 9135:
1.78 anton 9136: @cindex flavours of locals
9137: @cindex locals flavours
9138: @cindex value-flavoured locals
9139: @cindex variable-flavoured locals
9140: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9141: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9142: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9143: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9144: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9145: produces its address (which becomes invalid when the variable's scope is
9146: left). E.g., the standard word @code{emit} can be defined in terms of
9147: @code{type} like this:
1.5 anton 9148:
1.78 anton 9149: @example
9150: : emit @{ C^ char* -- @}
9151: char* 1 type ;
9152: @end example
1.5 anton 9153:
1.78 anton 9154: @cindex default type of locals
9155: @cindex locals, default type
9156: A local without type specifier is a @code{W:} local. Both flavours of
9157: locals are initialized with values from the data or FP stack.
1.44 crook 9158:
1.78 anton 9159: Currently there is no way to define locals with user-defined data
9160: structures, but we are working on it.
1.5 anton 9161:
1.78 anton 9162: Gforth allows defining locals everywhere in a colon definition. This
9163: poses the following questions:
1.5 anton 9164:
1.78 anton 9165: @menu
9166: * Where are locals visible by name?::
9167: * How long do locals live?::
9168: * Locals programming style::
9169: * Locals implementation::
9170: @end menu
1.44 crook 9171:
1.78 anton 9172: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9173: @subsubsection Where are locals visible by name?
9174: @cindex locals visibility
9175: @cindex visibility of locals
9176: @cindex scope of locals
1.5 anton 9177:
1.78 anton 9178: Basically, the answer is that locals are visible where you would expect
9179: it in block-structured languages, and sometimes a little longer. If you
9180: want to restrict the scope of a local, enclose its definition in
9181: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9182:
9183:
1.78 anton 9184: doc-scope
9185: doc-endscope
1.5 anton 9186:
9187:
1.78 anton 9188: These words behave like control structure words, so you can use them
9189: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9190: arbitrary ways.
1.77 anton 9191:
1.78 anton 9192: If you want a more exact answer to the visibility question, here's the
9193: basic principle: A local is visible in all places that can only be
9194: reached through the definition of the local@footnote{In compiler
9195: construction terminology, all places dominated by the definition of the
9196: local.}. In other words, it is not visible in places that can be reached
9197: without going through the definition of the local. E.g., locals defined
9198: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9199: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9200: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9201:
1.78 anton 9202: The reasoning behind this solution is: We want to have the locals
9203: visible as long as it is meaningful. The user can always make the
9204: visibility shorter by using explicit scoping. In a place that can
9205: only be reached through the definition of a local, the meaning of a
9206: local name is clear. In other places it is not: How is the local
9207: initialized at the control flow path that does not contain the
9208: definition? Which local is meant, if the same name is defined twice in
9209: two independent control flow paths?
1.77 anton 9210:
1.78 anton 9211: This should be enough detail for nearly all users, so you can skip the
9212: rest of this section. If you really must know all the gory details and
9213: options, read on.
1.77 anton 9214:
1.78 anton 9215: In order to implement this rule, the compiler has to know which places
9216: are unreachable. It knows this automatically after @code{AHEAD},
9217: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9218: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9219: compiler that the control flow never reaches that place. If
9220: @code{UNREACHABLE} is not used where it could, the only consequence is
9221: that the visibility of some locals is more limited than the rule above
9222: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9223: lie to the compiler), buggy code will be produced.
1.77 anton 9224:
1.5 anton 9225:
1.78 anton 9226: doc-unreachable
1.5 anton 9227:
1.23 crook 9228:
1.78 anton 9229: Another problem with this rule is that at @code{BEGIN}, the compiler
9230: does not know which locals will be visible on the incoming
9231: back-edge. All problems discussed in the following are due to this
9232: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9233: loops as examples; the discussion also applies to @code{?DO} and other
9234: loops). Perhaps the most insidious example is:
1.26 crook 9235: @example
1.78 anton 9236: AHEAD
9237: BEGIN
9238: x
9239: [ 1 CS-ROLL ] THEN
9240: @{ x @}
9241: ...
9242: UNTIL
1.26 crook 9243: @end example
1.23 crook 9244:
1.78 anton 9245: This should be legal according to the visibility rule. The use of
9246: @code{x} can only be reached through the definition; but that appears
9247: textually below the use.
9248:
9249: From this example it is clear that the visibility rules cannot be fully
9250: implemented without major headaches. Our implementation treats common
9251: cases as advertised and the exceptions are treated in a safe way: The
9252: compiler makes a reasonable guess about the locals visible after a
9253: @code{BEGIN}; if it is too pessimistic, the
9254: user will get a spurious error about the local not being defined; if the
9255: compiler is too optimistic, it will notice this later and issue a
9256: warning. In the case above the compiler would complain about @code{x}
9257: being undefined at its use. You can see from the obscure examples in
9258: this section that it takes quite unusual control structures to get the
9259: compiler into trouble, and even then it will often do fine.
1.23 crook 9260:
1.78 anton 9261: If the @code{BEGIN} is reachable from above, the most optimistic guess
9262: is that all locals visible before the @code{BEGIN} will also be
9263: visible after the @code{BEGIN}. This guess is valid for all loops that
9264: are entered only through the @code{BEGIN}, in particular, for normal
9265: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9266: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9267: compiler. When the branch to the @code{BEGIN} is finally generated by
9268: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9269: warns the user if it was too optimistic:
1.26 crook 9270: @example
1.78 anton 9271: IF
9272: @{ x @}
9273: BEGIN
9274: \ x ?
9275: [ 1 cs-roll ] THEN
9276: ...
9277: UNTIL
1.26 crook 9278: @end example
1.23 crook 9279:
1.78 anton 9280: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9281: optimistically assumes that it lives until the @code{THEN}. It notices
9282: this difference when it compiles the @code{UNTIL} and issues a
9283: warning. The user can avoid the warning, and make sure that @code{x}
9284: is not used in the wrong area by using explicit scoping:
9285: @example
9286: IF
9287: SCOPE
9288: @{ x @}
9289: ENDSCOPE
9290: BEGIN
9291: [ 1 cs-roll ] THEN
9292: ...
9293: UNTIL
9294: @end example
1.23 crook 9295:
1.78 anton 9296: Since the guess is optimistic, there will be no spurious error messages
9297: about undefined locals.
1.44 crook 9298:
1.78 anton 9299: If the @code{BEGIN} is not reachable from above (e.g., after
9300: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9301: optimistic guess, as the locals visible after the @code{BEGIN} may be
9302: defined later. Therefore, the compiler assumes that no locals are
9303: visible after the @code{BEGIN}. However, the user can use
9304: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9305: visible at the BEGIN as at the point where the top control-flow stack
9306: item was created.
1.23 crook 9307:
1.44 crook 9308:
1.78 anton 9309: doc-assume-live
1.26 crook 9310:
1.23 crook 9311:
1.78 anton 9312: @noindent
9313: E.g.,
9314: @example
9315: @{ x @}
9316: AHEAD
9317: ASSUME-LIVE
9318: BEGIN
9319: x
9320: [ 1 CS-ROLL ] THEN
9321: ...
9322: UNTIL
9323: @end example
1.44 crook 9324:
1.78 anton 9325: Other cases where the locals are defined before the @code{BEGIN} can be
9326: handled by inserting an appropriate @code{CS-ROLL} before the
9327: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9328: behind the @code{ASSUME-LIVE}).
1.23 crook 9329:
1.78 anton 9330: Cases where locals are defined after the @code{BEGIN} (but should be
9331: visible immediately after the @code{BEGIN}) can only be handled by
9332: rearranging the loop. E.g., the ``most insidious'' example above can be
9333: arranged into:
9334: @example
9335: BEGIN
9336: @{ x @}
9337: ... 0=
9338: WHILE
9339: x
9340: REPEAT
9341: @end example
1.44 crook 9342:
1.78 anton 9343: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9344: @subsubsection How long do locals live?
9345: @cindex locals lifetime
9346: @cindex lifetime of locals
1.23 crook 9347:
1.78 anton 9348: The right answer for the lifetime question would be: A local lives at
9349: least as long as it can be accessed. For a value-flavoured local this
9350: means: until the end of its visibility. However, a variable-flavoured
9351: local could be accessed through its address far beyond its visibility
9352: scope. Ultimately, this would mean that such locals would have to be
9353: garbage collected. Since this entails un-Forth-like implementation
9354: complexities, I adopted the same cowardly solution as some other
9355: languages (e.g., C): The local lives only as long as it is visible;
9356: afterwards its address is invalid (and programs that access it
9357: afterwards are erroneous).
1.23 crook 9358:
1.78 anton 9359: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9360: @subsubsection Locals programming style
9361: @cindex locals programming style
9362: @cindex programming style, locals
1.23 crook 9363:
1.78 anton 9364: The freedom to define locals anywhere has the potential to change
9365: programming styles dramatically. In particular, the need to use the
9366: return stack for intermediate storage vanishes. Moreover, all stack
9367: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9368: determined arguments) can be eliminated: If the stack items are in the
9369: wrong order, just write a locals definition for all of them; then
9370: write the items in the order you want.
1.23 crook 9371:
1.78 anton 9372: This seems a little far-fetched and eliminating stack manipulations is
9373: unlikely to become a conscious programming objective. Still, the number
9374: of stack manipulations will be reduced dramatically if local variables
9375: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9376: a traditional implementation of @code{max}).
1.23 crook 9377:
1.78 anton 9378: This shows one potential benefit of locals: making Forth programs more
9379: readable. Of course, this benefit will only be realized if the
9380: programmers continue to honour the principle of factoring instead of
9381: using the added latitude to make the words longer.
1.23 crook 9382:
1.78 anton 9383: @cindex single-assignment style for locals
9384: Using @code{TO} can and should be avoided. Without @code{TO},
9385: every value-flavoured local has only a single assignment and many
9386: advantages of functional languages apply to Forth. I.e., programs are
9387: easier to analyse, to optimize and to read: It is clear from the
9388: definition what the local stands for, it does not turn into something
9389: different later.
1.23 crook 9390:
1.78 anton 9391: E.g., a definition using @code{TO} might look like this:
9392: @example
9393: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9394: u1 u2 min 0
9395: ?do
9396: addr1 c@@ addr2 c@@ -
9397: ?dup-if
9398: unloop exit
9399: then
9400: addr1 char+ TO addr1
9401: addr2 char+ TO addr2
9402: loop
9403: u1 u2 - ;
1.26 crook 9404: @end example
1.78 anton 9405: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9406: every loop iteration. @code{strcmp} is a typical example of the
9407: readability problems of using @code{TO}. When you start reading
9408: @code{strcmp}, you think that @code{addr1} refers to the start of the
9409: string. Only near the end of the loop you realize that it is something
9410: else.
1.23 crook 9411:
1.78 anton 9412: This can be avoided by defining two locals at the start of the loop that
9413: are initialized with the right value for the current iteration.
9414: @example
9415: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9416: addr1 addr2
9417: u1 u2 min 0
9418: ?do @{ s1 s2 @}
9419: s1 c@@ s2 c@@ -
9420: ?dup-if
9421: unloop exit
9422: then
9423: s1 char+ s2 char+
9424: loop
9425: 2drop
9426: u1 u2 - ;
9427: @end example
9428: Here it is clear from the start that @code{s1} has a different value
9429: in every loop iteration.
1.23 crook 9430:
1.78 anton 9431: @node Locals implementation, , Locals programming style, Gforth locals
9432: @subsubsection Locals implementation
9433: @cindex locals implementation
9434: @cindex implementation of locals
1.23 crook 9435:
1.78 anton 9436: @cindex locals stack
9437: Gforth uses an extra locals stack. The most compelling reason for
9438: this is that the return stack is not float-aligned; using an extra stack
9439: also eliminates the problems and restrictions of using the return stack
9440: as locals stack. Like the other stacks, the locals stack grows toward
9441: lower addresses. A few primitives allow an efficient implementation:
9442:
9443:
9444: doc-@local#
9445: doc-f@local#
9446: doc-laddr#
9447: doc-lp+!#
9448: doc-lp!
9449: doc->l
9450: doc-f>l
9451:
9452:
9453: In addition to these primitives, some specializations of these
9454: primitives for commonly occurring inline arguments are provided for
9455: efficiency reasons, e.g., @code{@@local0} as specialization of
9456: @code{@@local#} for the inline argument 0. The following compiling words
9457: compile the right specialized version, or the general version, as
9458: appropriate:
1.23 crook 9459:
1.5 anton 9460:
1.107 dvdkhlng 9461: @c doc-compile-@local
9462: @c doc-compile-f@local
1.78 anton 9463: doc-compile-lp+!
1.5 anton 9464:
9465:
1.78 anton 9466: Combinations of conditional branches and @code{lp+!#} like
9467: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9468: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9469:
1.78 anton 9470: A special area in the dictionary space is reserved for keeping the
9471: local variable names. @code{@{} switches the dictionary pointer to this
9472: area and @code{@}} switches it back and generates the locals
9473: initializing code. @code{W:} etc.@ are normal defining words. This
9474: special area is cleared at the start of every colon definition.
1.5 anton 9475:
1.78 anton 9476: @cindex word list for defining locals
9477: A special feature of Gforth's dictionary is used to implement the
9478: definition of locals without type specifiers: every word list (aka
9479: vocabulary) has its own methods for searching
9480: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9481: with a special search method: When it is searched for a word, it
9482: actually creates that word using @code{W:}. @code{@{} changes the search
9483: order to first search the word list containing @code{@}}, @code{W:} etc.,
9484: and then the word list for defining locals without type specifiers.
1.5 anton 9485:
1.78 anton 9486: The lifetime rules support a stack discipline within a colon
9487: definition: The lifetime of a local is either nested with other locals
9488: lifetimes or it does not overlap them.
1.23 crook 9489:
1.78 anton 9490: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9491: pointer manipulation is generated. Between control structure words
9492: locals definitions can push locals onto the locals stack. @code{AGAIN}
9493: is the simplest of the other three control flow words. It has to
9494: restore the locals stack depth of the corresponding @code{BEGIN}
9495: before branching. The code looks like this:
9496: @format
9497: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9498: @code{branch} <begin>
9499: @end format
1.26 crook 9500:
1.78 anton 9501: @code{UNTIL} is a little more complicated: If it branches back, it
9502: must adjust the stack just like @code{AGAIN}. But if it falls through,
9503: the locals stack must not be changed. The compiler generates the
9504: following code:
9505: @format
9506: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9507: @end format
9508: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9509:
1.78 anton 9510: @code{THEN} can produce somewhat inefficient code:
9511: @format
9512: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9513: <orig target>:
9514: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9515: @end format
9516: The second @code{lp+!#} adjusts the locals stack pointer from the
9517: level at the @i{orig} point to the level after the @code{THEN}. The
9518: first @code{lp+!#} adjusts the locals stack pointer from the current
9519: level to the level at the orig point, so the complete effect is an
9520: adjustment from the current level to the right level after the
9521: @code{THEN}.
1.26 crook 9522:
1.78 anton 9523: @cindex locals information on the control-flow stack
9524: @cindex control-flow stack items, locals information
9525: In a conventional Forth implementation a dest control-flow stack entry
9526: is just the target address and an orig entry is just the address to be
9527: patched. Our locals implementation adds a word list to every orig or dest
9528: item. It is the list of locals visible (or assumed visible) at the point
9529: described by the entry. Our implementation also adds a tag to identify
9530: the kind of entry, in particular to differentiate between live and dead
9531: (reachable and unreachable) orig entries.
1.26 crook 9532:
1.78 anton 9533: A few unusual operations have to be performed on locals word lists:
1.44 crook 9534:
1.5 anton 9535:
1.78 anton 9536: doc-common-list
9537: doc-sub-list?
9538: doc-list-size
1.52 anton 9539:
9540:
1.78 anton 9541: Several features of our locals word list implementation make these
9542: operations easy to implement: The locals word lists are organised as
9543: linked lists; the tails of these lists are shared, if the lists
9544: contain some of the same locals; and the address of a name is greater
9545: than the address of the names behind it in the list.
1.5 anton 9546:
1.78 anton 9547: Another important implementation detail is the variable
9548: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9549: determine if they can be reached directly or only through the branch
9550: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9551: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9552: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9553:
1.78 anton 9554: Counted loops are similar to other loops in most respects, but
9555: @code{LEAVE} requires special attention: It performs basically the same
9556: service as @code{AHEAD}, but it does not create a control-flow stack
9557: entry. Therefore the information has to be stored elsewhere;
9558: traditionally, the information was stored in the target fields of the
9559: branches created by the @code{LEAVE}s, by organizing these fields into a
9560: linked list. Unfortunately, this clever trick does not provide enough
9561: space for storing our extended control flow information. Therefore, we
9562: introduce another stack, the leave stack. It contains the control-flow
9563: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9564:
1.78 anton 9565: Local names are kept until the end of the colon definition, even if
9566: they are no longer visible in any control-flow path. In a few cases
9567: this may lead to increased space needs for the locals name area, but
9568: usually less than reclaiming this space would cost in code size.
1.5 anton 9569:
1.44 crook 9570:
1.78 anton 9571: @node ANS Forth locals, , Gforth locals, Locals
9572: @subsection ANS Forth locals
9573: @cindex locals, ANS Forth style
1.5 anton 9574:
1.78 anton 9575: The ANS Forth locals wordset does not define a syntax for locals, but
9576: words that make it possible to define various syntaxes. One of the
9577: possible syntaxes is a subset of the syntax we used in the Gforth locals
9578: wordset, i.e.:
1.29 crook 9579:
9580: @example
1.78 anton 9581: @{ local1 local2 ... -- comment @}
9582: @end example
9583: @noindent
9584: or
9585: @example
9586: @{ local1 local2 ... @}
1.29 crook 9587: @end example
9588:
1.78 anton 9589: The order of the locals corresponds to the order in a stack comment. The
9590: restrictions are:
1.5 anton 9591:
1.78 anton 9592: @itemize @bullet
9593: @item
9594: Locals can only be cell-sized values (no type specifiers are allowed).
9595: @item
9596: Locals can be defined only outside control structures.
9597: @item
9598: Locals can interfere with explicit usage of the return stack. For the
9599: exact (and long) rules, see the standard. If you don't use return stack
9600: accessing words in a definition using locals, you will be all right. The
9601: purpose of this rule is to make locals implementation on the return
9602: stack easier.
9603: @item
9604: The whole definition must be in one line.
9605: @end itemize
1.5 anton 9606:
1.78 anton 9607: Locals defined in ANS Forth behave like @code{VALUE}s
9608: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9609: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9610:
1.78 anton 9611: Since the syntax above is supported by Gforth directly, you need not do
9612: anything to use it. If you want to port a program using this syntax to
9613: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9614: syntax on the other system.
1.5 anton 9615:
1.78 anton 9616: Note that a syntax shown in the standard, section A.13 looks
9617: similar, but is quite different in having the order of locals
9618: reversed. Beware!
1.5 anton 9619:
1.78 anton 9620: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9621:
1.78 anton 9622: doc-(local)
1.5 anton 9623:
1.78 anton 9624: The ANS Forth locals extension wordset defines a syntax using
9625: @code{locals|}, but it is so awful that we strongly recommend not to use
9626: it. We have implemented this syntax to make porting to Gforth easy, but
9627: do not document it here. The problem with this syntax is that the locals
9628: are defined in an order reversed with respect to the standard stack
9629: comment notation, making programs harder to read, and easier to misread
9630: and miswrite. The only merit of this syntax is that it is easy to
9631: implement using the ANS Forth locals wordset.
1.53 anton 9632:
9633:
1.78 anton 9634: @c ----------------------------------------------------------
9635: @node Structures, Object-oriented Forth, Locals, Words
9636: @section Structures
9637: @cindex structures
9638: @cindex records
1.53 anton 9639:
1.78 anton 9640: This section presents the structure package that comes with Gforth. A
9641: version of the package implemented in ANS Forth is available in
9642: @file{compat/struct.fs}. This package was inspired by a posting on
9643: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9644: possibly John Hayes). A version of this section has been published in
9645: M. Anton Ertl,
9646: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9647: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9648: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9649:
1.78 anton 9650: @menu
9651: * Why explicit structure support?::
9652: * Structure Usage::
9653: * Structure Naming Convention::
9654: * Structure Implementation::
9655: * Structure Glossary::
9656: @end menu
1.55 anton 9657:
1.78 anton 9658: @node Why explicit structure support?, Structure Usage, Structures, Structures
9659: @subsection Why explicit structure support?
1.53 anton 9660:
1.78 anton 9661: @cindex address arithmetic for structures
9662: @cindex structures using address arithmetic
9663: If we want to use a structure containing several fields, we could simply
9664: reserve memory for it, and access the fields using address arithmetic
9665: (@pxref{Address arithmetic}). As an example, consider a structure with
9666: the following fields
1.57 anton 9667:
1.78 anton 9668: @table @code
9669: @item a
9670: is a float
9671: @item b
9672: is a cell
9673: @item c
9674: is a float
9675: @end table
1.57 anton 9676:
1.78 anton 9677: Given the (float-aligned) base address of the structure we get the
9678: address of the field
1.52 anton 9679:
1.78 anton 9680: @table @code
9681: @item a
9682: without doing anything further.
9683: @item b
9684: with @code{float+}
9685: @item c
9686: with @code{float+ cell+ faligned}
9687: @end table
1.52 anton 9688:
1.78 anton 9689: It is easy to see that this can become quite tiring.
1.52 anton 9690:
1.78 anton 9691: Moreover, it is not very readable, because seeing a
9692: @code{cell+} tells us neither which kind of structure is
9693: accessed nor what field is accessed; we have to somehow infer the kind
9694: of structure, and then look up in the documentation, which field of
9695: that structure corresponds to that offset.
1.53 anton 9696:
1.78 anton 9697: Finally, this kind of address arithmetic also causes maintenance
9698: troubles: If you add or delete a field somewhere in the middle of the
9699: structure, you have to find and change all computations for the fields
9700: afterwards.
1.52 anton 9701:
1.78 anton 9702: So, instead of using @code{cell+} and friends directly, how
9703: about storing the offsets in constants:
1.52 anton 9704:
1.78 anton 9705: @example
9706: 0 constant a-offset
9707: 0 float+ constant b-offset
9708: 0 float+ cell+ faligned c-offset
9709: @end example
1.64 pazsan 9710:
1.78 anton 9711: Now we can get the address of field @code{x} with @code{x-offset
9712: +}. This is much better in all respects. Of course, you still
9713: have to change all later offset definitions if you add a field. You can
9714: fix this by declaring the offsets in the following way:
1.57 anton 9715:
1.78 anton 9716: @example
9717: 0 constant a-offset
9718: a-offset float+ constant b-offset
9719: b-offset cell+ faligned constant c-offset
9720: @end example
1.57 anton 9721:
1.78 anton 9722: Since we always use the offsets with @code{+}, we could use a defining
9723: word @code{cfield} that includes the @code{+} in the action of the
9724: defined word:
1.64 pazsan 9725:
1.78 anton 9726: @example
9727: : cfield ( n "name" -- )
9728: create ,
9729: does> ( name execution: addr1 -- addr2 )
9730: @@ + ;
1.64 pazsan 9731:
1.78 anton 9732: 0 cfield a
9733: 0 a float+ cfield b
9734: 0 b cell+ faligned cfield c
9735: @end example
1.64 pazsan 9736:
1.78 anton 9737: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 9738:
1.78 anton 9739: The structure field words now can be used quite nicely. However,
9740: their definition is still a bit cumbersome: We have to repeat the
9741: name, the information about size and alignment is distributed before
9742: and after the field definitions etc. The structure package presented
9743: here addresses these problems.
1.64 pazsan 9744:
1.78 anton 9745: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
9746: @subsection Structure Usage
9747: @cindex structure usage
1.57 anton 9748:
1.78 anton 9749: @cindex @code{field} usage
9750: @cindex @code{struct} usage
9751: @cindex @code{end-struct} usage
9752: You can define a structure for a (data-less) linked list with:
1.57 anton 9753: @example
1.78 anton 9754: struct
9755: cell% field list-next
9756: end-struct list%
1.57 anton 9757: @end example
9758:
1.78 anton 9759: With the address of the list node on the stack, you can compute the
9760: address of the field that contains the address of the next node with
9761: @code{list-next}. E.g., you can determine the length of a list
9762: with:
1.57 anton 9763:
9764: @example
1.78 anton 9765: : list-length ( list -- n )
9766: \ "list" is a pointer to the first element of a linked list
9767: \ "n" is the length of the list
9768: 0 BEGIN ( list1 n1 )
9769: over
9770: WHILE ( list1 n1 )
9771: 1+ swap list-next @@ swap
9772: REPEAT
9773: nip ;
1.57 anton 9774: @end example
9775:
1.78 anton 9776: You can reserve memory for a list node in the dictionary with
9777: @code{list% %allot}, which leaves the address of the list node on the
9778: stack. For the equivalent allocation on the heap you can use @code{list%
9779: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
9780: use @code{list% %allocate}). You can get the the size of a list
9781: node with @code{list% %size} and its alignment with @code{list%
9782: %alignment}.
9783:
9784: Note that in ANS Forth the body of a @code{create}d word is
9785: @code{aligned} but not necessarily @code{faligned};
9786: therefore, if you do a:
1.57 anton 9787:
9788: @example
1.78 anton 9789: create @emph{name} foo% %allot drop
1.57 anton 9790: @end example
9791:
1.78 anton 9792: @noindent
9793: then the memory alloted for @code{foo%} is guaranteed to start at the
9794: body of @code{@emph{name}} only if @code{foo%} contains only character,
9795: cell and double fields. Therefore, if your structure contains floats,
9796: better use
1.57 anton 9797:
9798: @example
1.78 anton 9799: foo% %allot constant @emph{name}
1.57 anton 9800: @end example
9801:
1.78 anton 9802: @cindex structures containing structures
9803: You can include a structure @code{foo%} as a field of
9804: another structure, like this:
1.65 anton 9805: @example
1.78 anton 9806: struct
9807: ...
9808: foo% field ...
9809: ...
9810: end-struct ...
1.65 anton 9811: @end example
1.52 anton 9812:
1.78 anton 9813: @cindex structure extension
9814: @cindex extended records
9815: Instead of starting with an empty structure, you can extend an
9816: existing structure. E.g., a plain linked list without data, as defined
9817: above, is hardly useful; You can extend it to a linked list of integers,
9818: like this:@footnote{This feature is also known as @emph{extended
9819: records}. It is the main innovation in the Oberon language; in other
9820: words, adding this feature to Modula-2 led Wirth to create a new
9821: language, write a new compiler etc. Adding this feature to Forth just
9822: required a few lines of code.}
1.52 anton 9823:
1.78 anton 9824: @example
9825: list%
9826: cell% field intlist-int
9827: end-struct intlist%
9828: @end example
1.55 anton 9829:
1.78 anton 9830: @code{intlist%} is a structure with two fields:
9831: @code{list-next} and @code{intlist-int}.
1.55 anton 9832:
1.78 anton 9833: @cindex structures containing arrays
9834: You can specify an array type containing @emph{n} elements of
9835: type @code{foo%} like this:
1.55 anton 9836:
9837: @example
1.78 anton 9838: foo% @emph{n} *
1.56 anton 9839: @end example
1.55 anton 9840:
1.78 anton 9841: You can use this array type in any place where you can use a normal
9842: type, e.g., when defining a @code{field}, or with
9843: @code{%allot}.
9844:
9845: @cindex first field optimization
9846: The first field is at the base address of a structure and the word for
9847: this field (e.g., @code{list-next}) actually does not change the address
9848: on the stack. You may be tempted to leave it away in the interest of
9849: run-time and space efficiency. This is not necessary, because the
9850: structure package optimizes this case: If you compile a first-field
9851: words, no code is generated. So, in the interest of readability and
9852: maintainability you should include the word for the field when accessing
9853: the field.
1.52 anton 9854:
9855:
1.78 anton 9856: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
9857: @subsection Structure Naming Convention
9858: @cindex structure naming convention
1.52 anton 9859:
1.78 anton 9860: The field names that come to (my) mind are often quite generic, and,
9861: if used, would cause frequent name clashes. E.g., many structures
9862: probably contain a @code{counter} field. The structure names
9863: that come to (my) mind are often also the logical choice for the names
9864: of words that create such a structure.
1.52 anton 9865:
1.78 anton 9866: Therefore, I have adopted the following naming conventions:
1.52 anton 9867:
1.78 anton 9868: @itemize @bullet
9869: @cindex field naming convention
9870: @item
9871: The names of fields are of the form
9872: @code{@emph{struct}-@emph{field}}, where
9873: @code{@emph{struct}} is the basic name of the structure, and
9874: @code{@emph{field}} is the basic name of the field. You can
9875: think of field words as converting the (address of the)
9876: structure into the (address of the) field.
1.52 anton 9877:
1.78 anton 9878: @cindex structure naming convention
9879: @item
9880: The names of structures are of the form
9881: @code{@emph{struct}%}, where
9882: @code{@emph{struct}} is the basic name of the structure.
9883: @end itemize
1.52 anton 9884:
1.78 anton 9885: This naming convention does not work that well for fields of extended
9886: structures; e.g., the integer list structure has a field
9887: @code{intlist-int}, but has @code{list-next}, not
9888: @code{intlist-next}.
1.53 anton 9889:
1.78 anton 9890: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
9891: @subsection Structure Implementation
9892: @cindex structure implementation
9893: @cindex implementation of structures
1.52 anton 9894:
1.78 anton 9895: The central idea in the implementation is to pass the data about the
9896: structure being built on the stack, not in some global
9897: variable. Everything else falls into place naturally once this design
9898: decision is made.
1.53 anton 9899:
1.78 anton 9900: The type description on the stack is of the form @emph{align
9901: size}. Keeping the size on the top-of-stack makes dealing with arrays
9902: very simple.
1.53 anton 9903:
1.78 anton 9904: @code{field} is a defining word that uses @code{Create}
9905: and @code{DOES>}. The body of the field contains the offset
9906: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 9907:
9908: @example
1.78 anton 9909: @@ +
1.53 anton 9910: @end example
9911:
1.78 anton 9912: @noindent
9913: i.e., add the offset to the address, giving the stack effect
9914: @i{addr1 -- addr2} for a field.
9915:
9916: @cindex first field optimization, implementation
9917: This simple structure is slightly complicated by the optimization
9918: for fields with offset 0, which requires a different
9919: @code{DOES>}-part (because we cannot rely on there being
9920: something on the stack if such a field is invoked during
9921: compilation). Therefore, we put the different @code{DOES>}-parts
9922: in separate words, and decide which one to invoke based on the
9923: offset. For a zero offset, the field is basically a noop; it is
9924: immediate, and therefore no code is generated when it is compiled.
1.53 anton 9925:
1.78 anton 9926: @node Structure Glossary, , Structure Implementation, Structures
9927: @subsection Structure Glossary
9928: @cindex structure glossary
1.53 anton 9929:
1.5 anton 9930:
1.78 anton 9931: doc-%align
9932: doc-%alignment
9933: doc-%alloc
9934: doc-%allocate
9935: doc-%allot
9936: doc-cell%
9937: doc-char%
9938: doc-dfloat%
9939: doc-double%
9940: doc-end-struct
9941: doc-field
9942: doc-float%
9943: doc-naligned
9944: doc-sfloat%
9945: doc-%size
9946: doc-struct
1.54 anton 9947:
9948:
1.26 crook 9949: @c -------------------------------------------------------------
1.78 anton 9950: @node Object-oriented Forth, Programming Tools, Structures, Words
9951: @section Object-oriented Forth
9952:
9953: Gforth comes with three packages for object-oriented programming:
9954: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
9955: is preloaded, so you have to @code{include} them before use. The most
9956: important differences between these packages (and others) are discussed
9957: in @ref{Comparison with other object models}. All packages are written
9958: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 9959:
1.78 anton 9960: @menu
9961: * Why object-oriented programming?::
9962: * Object-Oriented Terminology::
9963: * Objects::
9964: * OOF::
9965: * Mini-OOF::
9966: * Comparison with other object models::
9967: @end menu
1.5 anton 9968:
1.78 anton 9969: @c ----------------------------------------------------------------
9970: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
9971: @subsection Why object-oriented programming?
9972: @cindex object-oriented programming motivation
9973: @cindex motivation for object-oriented programming
1.44 crook 9974:
1.78 anton 9975: Often we have to deal with several data structures (@emph{objects}),
9976: that have to be treated similarly in some respects, but differently in
9977: others. Graphical objects are the textbook example: circles, triangles,
9978: dinosaurs, icons, and others, and we may want to add more during program
9979: development. We want to apply some operations to any graphical object,
9980: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
9981: has to do something different for every kind of object.
9982: @comment TODO add some other operations eg perimeter, area
9983: @comment and tie in to concrete examples later..
1.5 anton 9984:
1.78 anton 9985: We could implement @code{draw} as a big @code{CASE}
9986: control structure that executes the appropriate code depending on the
9987: kind of object to be drawn. This would be not be very elegant, and,
9988: moreover, we would have to change @code{draw} every time we add
9989: a new kind of graphical object (say, a spaceship).
1.44 crook 9990:
1.78 anton 9991: What we would rather do is: When defining spaceships, we would tell
9992: the system: ``Here's how you @code{draw} a spaceship; you figure
9993: out the rest''.
1.5 anton 9994:
1.78 anton 9995: This is the problem that all systems solve that (rightfully) call
9996: themselves object-oriented; the object-oriented packages presented here
9997: solve this problem (and not much else).
9998: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 9999:
1.78 anton 10000: @c ------------------------------------------------------------------------
10001: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10002: @subsection Object-Oriented Terminology
10003: @cindex object-oriented terminology
10004: @cindex terminology for object-oriented programming
1.5 anton 10005:
1.78 anton 10006: This section is mainly for reference, so you don't have to understand
10007: all of it right away. The terminology is mainly Smalltalk-inspired. In
10008: short:
1.44 crook 10009:
1.78 anton 10010: @table @emph
10011: @cindex class
10012: @item class
10013: a data structure definition with some extras.
1.5 anton 10014:
1.78 anton 10015: @cindex object
10016: @item object
10017: an instance of the data structure described by the class definition.
1.5 anton 10018:
1.78 anton 10019: @cindex instance variables
10020: @item instance variables
10021: fields of the data structure.
1.5 anton 10022:
1.78 anton 10023: @cindex selector
10024: @cindex method selector
10025: @cindex virtual function
10026: @item selector
10027: (or @emph{method selector}) a word (e.g.,
10028: @code{draw}) that performs an operation on a variety of data
10029: structures (classes). A selector describes @emph{what} operation to
10030: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10031:
1.78 anton 10032: @cindex method
10033: @item method
10034: the concrete definition that performs the operation
10035: described by the selector for a specific class. A method specifies
10036: @emph{how} the operation is performed for a specific class.
1.5 anton 10037:
1.78 anton 10038: @cindex selector invocation
10039: @cindex message send
10040: @cindex invoking a selector
10041: @item selector invocation
10042: a call of a selector. One argument of the call (the TOS (top-of-stack))
10043: is used for determining which method is used. In Smalltalk terminology:
10044: a message (consisting of the selector and the other arguments) is sent
10045: to the object.
1.5 anton 10046:
1.78 anton 10047: @cindex receiving object
10048: @item receiving object
10049: the object used for determining the method executed by a selector
10050: invocation. In the @file{objects.fs} model, it is the object that is on
10051: the TOS when the selector is invoked. (@emph{Receiving} comes from
10052: the Smalltalk @emph{message} terminology.)
1.5 anton 10053:
1.78 anton 10054: @cindex child class
10055: @cindex parent class
10056: @cindex inheritance
10057: @item child class
10058: a class that has (@emph{inherits}) all properties (instance variables,
10059: selectors, methods) from a @emph{parent class}. In Smalltalk
10060: terminology: The subclass inherits from the superclass. In C++
10061: terminology: The derived class inherits from the base class.
1.5 anton 10062:
1.78 anton 10063: @end table
1.5 anton 10064:
1.78 anton 10065: @c If you wonder about the message sending terminology, it comes from
10066: @c a time when each object had it's own task and objects communicated via
10067: @c message passing; eventually the Smalltalk developers realized that
10068: @c they can do most things through simple (indirect) calls. They kept the
10069: @c terminology.
1.5 anton 10070:
1.78 anton 10071: @c --------------------------------------------------------------
10072: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10073: @subsection The @file{objects.fs} model
10074: @cindex objects
10075: @cindex object-oriented programming
1.26 crook 10076:
1.78 anton 10077: @cindex @file{objects.fs}
10078: @cindex @file{oof.fs}
1.26 crook 10079:
1.78 anton 10080: This section describes the @file{objects.fs} package. This material also
10081: has been published in M. Anton Ertl,
10082: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10083: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10084: 37--43.
10085: @c McKewan's and Zsoter's packages
1.26 crook 10086:
1.78 anton 10087: This section assumes that you have read @ref{Structures}.
1.5 anton 10088:
1.78 anton 10089: The techniques on which this model is based have been used to implement
10090: the parser generator, Gray, and have also been used in Gforth for
10091: implementing the various flavours of word lists (hashed or not,
10092: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10093:
10094:
1.26 crook 10095: @menu
1.78 anton 10096: * Properties of the Objects model::
10097: * Basic Objects Usage::
10098: * The Objects base class::
10099: * Creating objects::
10100: * Object-Oriented Programming Style::
10101: * Class Binding::
10102: * Method conveniences::
10103: * Classes and Scoping::
10104: * Dividing classes::
10105: * Object Interfaces::
10106: * Objects Implementation::
10107: * Objects Glossary::
1.26 crook 10108: @end menu
1.5 anton 10109:
1.78 anton 10110: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10111:
1.78 anton 10112: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10113: @subsubsection Properties of the @file{objects.fs} model
10114: @cindex @file{objects.fs} properties
1.5 anton 10115:
1.78 anton 10116: @itemize @bullet
10117: @item
10118: It is straightforward to pass objects on the stack. Passing
10119: selectors on the stack is a little less convenient, but possible.
1.44 crook 10120:
1.78 anton 10121: @item
10122: Objects are just data structures in memory, and are referenced by their
10123: address. You can create words for objects with normal defining words
10124: like @code{constant}. Likewise, there is no difference between instance
10125: variables that contain objects and those that contain other data.
1.5 anton 10126:
1.78 anton 10127: @item
10128: Late binding is efficient and easy to use.
1.44 crook 10129:
1.78 anton 10130: @item
10131: It avoids parsing, and thus avoids problems with state-smartness
10132: and reduced extensibility; for convenience there are a few parsing
10133: words, but they have non-parsing counterparts. There are also a few
10134: defining words that parse. This is hard to avoid, because all standard
10135: defining words parse (except @code{:noname}); however, such
10136: words are not as bad as many other parsing words, because they are not
10137: state-smart.
1.5 anton 10138:
1.78 anton 10139: @item
10140: It does not try to incorporate everything. It does a few things and does
10141: them well (IMO). In particular, this model was not designed to support
10142: information hiding (although it has features that may help); you can use
10143: a separate package for achieving this.
1.5 anton 10144:
1.78 anton 10145: @item
10146: It is layered; you don't have to learn and use all features to use this
10147: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10148: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10149: are optional and independent of each other.
1.5 anton 10150:
1.78 anton 10151: @item
10152: An implementation in ANS Forth is available.
1.5 anton 10153:
1.78 anton 10154: @end itemize
1.5 anton 10155:
1.44 crook 10156:
1.78 anton 10157: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10158: @subsubsection Basic @file{objects.fs} Usage
10159: @cindex basic objects usage
10160: @cindex objects, basic usage
1.5 anton 10161:
1.78 anton 10162: You can define a class for graphical objects like this:
1.44 crook 10163:
1.78 anton 10164: @cindex @code{class} usage
10165: @cindex @code{end-class} usage
10166: @cindex @code{selector} usage
1.5 anton 10167: @example
1.78 anton 10168: object class \ "object" is the parent class
10169: selector draw ( x y graphical -- )
10170: end-class graphical
10171: @end example
10172:
10173: This code defines a class @code{graphical} with an
10174: operation @code{draw}. We can perform the operation
10175: @code{draw} on any @code{graphical} object, e.g.:
10176:
10177: @example
10178: 100 100 t-rex draw
1.26 crook 10179: @end example
1.5 anton 10180:
1.78 anton 10181: @noindent
10182: where @code{t-rex} is a word (say, a constant) that produces a
10183: graphical object.
10184:
10185: @comment TODO add a 2nd operation eg perimeter.. and use for
10186: @comment a concrete example
1.5 anton 10187:
1.78 anton 10188: @cindex abstract class
10189: How do we create a graphical object? With the present definitions,
10190: we cannot create a useful graphical object. The class
10191: @code{graphical} describes graphical objects in general, but not
10192: any concrete graphical object type (C++ users would call it an
10193: @emph{abstract class}); e.g., there is no method for the selector
10194: @code{draw} in the class @code{graphical}.
1.5 anton 10195:
1.78 anton 10196: For concrete graphical objects, we define child classes of the
10197: class @code{graphical}, e.g.:
1.5 anton 10198:
1.78 anton 10199: @cindex @code{overrides} usage
10200: @cindex @code{field} usage in class definition
1.26 crook 10201: @example
1.78 anton 10202: graphical class \ "graphical" is the parent class
10203: cell% field circle-radius
1.5 anton 10204:
1.78 anton 10205: :noname ( x y circle -- )
10206: circle-radius @@ draw-circle ;
10207: overrides draw
1.5 anton 10208:
1.78 anton 10209: :noname ( n-radius circle -- )
10210: circle-radius ! ;
10211: overrides construct
1.5 anton 10212:
1.78 anton 10213: end-class circle
10214: @end example
1.44 crook 10215:
1.78 anton 10216: Here we define a class @code{circle} as a child of @code{graphical},
10217: with field @code{circle-radius} (which behaves just like a field
10218: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10219: for the selectors @code{draw} and @code{construct} (@code{construct} is
10220: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10221:
1.78 anton 10222: Now we can create a circle on the heap (i.e.,
10223: @code{allocate}d memory) with:
1.44 crook 10224:
1.78 anton 10225: @cindex @code{heap-new} usage
1.5 anton 10226: @example
1.78 anton 10227: 50 circle heap-new constant my-circle
1.5 anton 10228: @end example
10229:
1.78 anton 10230: @noindent
10231: @code{heap-new} invokes @code{construct}, thus
10232: initializing the field @code{circle-radius} with 50. We can draw
10233: this new circle at (100,100) with:
1.5 anton 10234:
10235: @example
1.78 anton 10236: 100 100 my-circle draw
1.5 anton 10237: @end example
10238:
1.78 anton 10239: @cindex selector invocation, restrictions
10240: @cindex class definition, restrictions
10241: Note: You can only invoke a selector if the object on the TOS
10242: (the receiving object) belongs to the class where the selector was
10243: defined or one of its descendents; e.g., you can invoke
10244: @code{draw} only for objects belonging to @code{graphical}
10245: or its descendents (e.g., @code{circle}). Immediately before
10246: @code{end-class}, the search order has to be the same as
10247: immediately after @code{class}.
10248:
10249: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10250: @subsubsection The @file{object.fs} base class
10251: @cindex @code{object} class
10252:
10253: When you define a class, you have to specify a parent class. So how do
10254: you start defining classes? There is one class available from the start:
10255: @code{object}. It is ancestor for all classes and so is the
10256: only class that has no parent. It has two selectors: @code{construct}
10257: and @code{print}.
10258:
10259: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10260: @subsubsection Creating objects
10261: @cindex creating objects
10262: @cindex object creation
10263: @cindex object allocation options
10264:
10265: @cindex @code{heap-new} discussion
10266: @cindex @code{dict-new} discussion
10267: @cindex @code{construct} discussion
10268: You can create and initialize an object of a class on the heap with
10269: @code{heap-new} ( ... class -- object ) and in the dictionary
10270: (allocation with @code{allot}) with @code{dict-new} (
10271: ... class -- object ). Both words invoke @code{construct}, which
10272: consumes the stack items indicated by "..." above.
10273:
10274: @cindex @code{init-object} discussion
10275: @cindex @code{class-inst-size} discussion
10276: If you want to allocate memory for an object yourself, you can get its
10277: alignment and size with @code{class-inst-size 2@@} ( class --
10278: align size ). Once you have memory for an object, you can initialize
10279: it with @code{init-object} ( ... class object -- );
10280: @code{construct} does only a part of the necessary work.
10281:
10282: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10283: @subsubsection Object-Oriented Programming Style
10284: @cindex object-oriented programming style
10285: @cindex programming style, object-oriented
1.5 anton 10286:
1.78 anton 10287: This section is not exhaustive.
1.5 anton 10288:
1.78 anton 10289: @cindex stack effects of selectors
10290: @cindex selectors and stack effects
10291: In general, it is a good idea to ensure that all methods for the
10292: same selector have the same stack effect: when you invoke a selector,
10293: you often have no idea which method will be invoked, so, unless all
10294: methods have the same stack effect, you will not know the stack effect
10295: of the selector invocation.
1.5 anton 10296:
1.78 anton 10297: One exception to this rule is methods for the selector
10298: @code{construct}. We know which method is invoked, because we
10299: specify the class to be constructed at the same place. Actually, I
10300: defined @code{construct} as a selector only to give the users a
10301: convenient way to specify initialization. The way it is used, a
10302: mechanism different from selector invocation would be more natural
10303: (but probably would take more code and more space to explain).
1.5 anton 10304:
1.78 anton 10305: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10306: @subsubsection Class Binding
10307: @cindex class binding
10308: @cindex early binding
1.5 anton 10309:
1.78 anton 10310: @cindex late binding
10311: Normal selector invocations determine the method at run-time depending
10312: on the class of the receiving object. This run-time selection is called
10313: @i{late binding}.
1.5 anton 10314:
1.78 anton 10315: Sometimes it's preferable to invoke a different method. For example,
10316: you might want to use the simple method for @code{print}ing
10317: @code{object}s instead of the possibly long-winded @code{print} method
10318: of the receiver class. You can achieve this by replacing the invocation
10319: of @code{print} with:
1.5 anton 10320:
1.78 anton 10321: @cindex @code{[bind]} usage
1.5 anton 10322: @example
1.78 anton 10323: [bind] object print
1.5 anton 10324: @end example
10325:
1.78 anton 10326: @noindent
10327: in compiled code or:
10328:
10329: @cindex @code{bind} usage
1.5 anton 10330: @example
1.78 anton 10331: bind object print
1.5 anton 10332: @end example
10333:
1.78 anton 10334: @cindex class binding, alternative to
10335: @noindent
10336: in interpreted code. Alternatively, you can define the method with a
10337: name (e.g., @code{print-object}), and then invoke it through the
10338: name. Class binding is just a (often more convenient) way to achieve
10339: the same effect; it avoids name clutter and allows you to invoke
10340: methods directly without naming them first.
1.5 anton 10341:
1.78 anton 10342: @cindex superclass binding
10343: @cindex parent class binding
10344: A frequent use of class binding is this: When we define a method
10345: for a selector, we often want the method to do what the selector does
10346: in the parent class, and a little more. There is a special word for
10347: this purpose: @code{[parent]}; @code{[parent]
10348: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10349: selector}}, where @code{@emph{parent}} is the parent
10350: class of the current class. E.g., a method definition might look like:
1.44 crook 10351:
1.78 anton 10352: @cindex @code{[parent]} usage
10353: @example
10354: :noname
10355: dup [parent] foo \ do parent's foo on the receiving object
10356: ... \ do some more
10357: ; overrides foo
10358: @end example
1.6 pazsan 10359:
1.78 anton 10360: @cindex class binding as optimization
10361: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10362: March 1997), Andrew McKewan presents class binding as an optimization
10363: technique. I recommend not using it for this purpose unless you are in
10364: an emergency. Late binding is pretty fast with this model anyway, so the
10365: benefit of using class binding is small; the cost of using class binding
10366: where it is not appropriate is reduced maintainability.
1.44 crook 10367:
1.78 anton 10368: While we are at programming style questions: You should bind
10369: selectors only to ancestor classes of the receiving object. E.g., say,
10370: you know that the receiving object is of class @code{foo} or its
10371: descendents; then you should bind only to @code{foo} and its
10372: ancestors.
1.12 anton 10373:
1.78 anton 10374: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10375: @subsubsection Method conveniences
10376: @cindex method conveniences
1.44 crook 10377:
1.78 anton 10378: In a method you usually access the receiving object pretty often. If
10379: you define the method as a plain colon definition (e.g., with
10380: @code{:noname}), you may have to do a lot of stack
10381: gymnastics. To avoid this, you can define the method with @code{m:
10382: ... ;m}. E.g., you could define the method for
10383: @code{draw}ing a @code{circle} with
1.6 pazsan 10384:
1.78 anton 10385: @cindex @code{this} usage
10386: @cindex @code{m:} usage
10387: @cindex @code{;m} usage
10388: @example
10389: m: ( x y circle -- )
10390: ( x y ) this circle-radius @@ draw-circle ;m
10391: @end example
1.6 pazsan 10392:
1.78 anton 10393: @cindex @code{exit} in @code{m: ... ;m}
10394: @cindex @code{exitm} discussion
10395: @cindex @code{catch} in @code{m: ... ;m}
10396: When this method is executed, the receiver object is removed from the
10397: stack; you can access it with @code{this} (admittedly, in this
10398: example the use of @code{m: ... ;m} offers no advantage). Note
10399: that I specify the stack effect for the whole method (i.e. including
10400: the receiver object), not just for the code between @code{m:}
10401: and @code{;m}. You cannot use @code{exit} in
10402: @code{m:...;m}; instead, use
10403: @code{exitm}.@footnote{Moreover, for any word that calls
10404: @code{catch} and was defined before loading
10405: @code{objects.fs}, you have to redefine it like I redefined
10406: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10407:
1.78 anton 10408: @cindex @code{inst-var} usage
10409: You will frequently use sequences of the form @code{this
10410: @emph{field}} (in the example above: @code{this
10411: circle-radius}). If you use the field only in this way, you can
10412: define it with @code{inst-var} and eliminate the
10413: @code{this} before the field name. E.g., the @code{circle}
10414: class above could also be defined with:
1.6 pazsan 10415:
1.78 anton 10416: @example
10417: graphical class
10418: cell% inst-var radius
1.6 pazsan 10419:
1.78 anton 10420: m: ( x y circle -- )
10421: radius @@ draw-circle ;m
10422: overrides draw
1.6 pazsan 10423:
1.78 anton 10424: m: ( n-radius circle -- )
10425: radius ! ;m
10426: overrides construct
1.6 pazsan 10427:
1.78 anton 10428: end-class circle
10429: @end example
1.6 pazsan 10430:
1.78 anton 10431: @code{radius} can only be used in @code{circle} and its
10432: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10433:
1.78 anton 10434: @cindex @code{inst-value} usage
10435: You can also define fields with @code{inst-value}, which is
10436: to @code{inst-var} what @code{value} is to
10437: @code{variable}. You can change the value of such a field with
10438: @code{[to-inst]}. E.g., we could also define the class
10439: @code{circle} like this:
1.44 crook 10440:
1.78 anton 10441: @example
10442: graphical class
10443: inst-value radius
1.6 pazsan 10444:
1.78 anton 10445: m: ( x y circle -- )
10446: radius draw-circle ;m
10447: overrides draw
1.44 crook 10448:
1.78 anton 10449: m: ( n-radius circle -- )
10450: [to-inst] radius ;m
10451: overrides construct
1.6 pazsan 10452:
1.78 anton 10453: end-class circle
10454: @end example
1.6 pazsan 10455:
1.78 anton 10456: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10457:
1.78 anton 10458: @c Finally, you can define named methods with @code{:m}. One use of this
10459: @c feature is the definition of words that occur only in one class and are
10460: @c not intended to be overridden, but which still need method context
10461: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10462: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10463:
10464:
1.78 anton 10465: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10466: @subsubsection Classes and Scoping
10467: @cindex classes and scoping
10468: @cindex scoping and classes
1.6 pazsan 10469:
1.78 anton 10470: Inheritance is frequent, unlike structure extension. This exacerbates
10471: the problem with the field name convention (@pxref{Structure Naming
10472: Convention}): One always has to remember in which class the field was
10473: originally defined; changing a part of the class structure would require
10474: changes for renaming in otherwise unaffected code.
1.6 pazsan 10475:
1.78 anton 10476: @cindex @code{inst-var} visibility
10477: @cindex @code{inst-value} visibility
10478: To solve this problem, I added a scoping mechanism (which was not in my
10479: original charter): A field defined with @code{inst-var} (or
10480: @code{inst-value}) is visible only in the class where it is defined and in
10481: the descendent classes of this class. Using such fields only makes
10482: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10483:
1.78 anton 10484: This scoping mechanism allows us to use the unadorned field name,
10485: because name clashes with unrelated words become much less likely.
1.6 pazsan 10486:
1.78 anton 10487: @cindex @code{protected} discussion
10488: @cindex @code{private} discussion
10489: Once we have this mechanism, we can also use it for controlling the
10490: visibility of other words: All words defined after
10491: @code{protected} are visible only in the current class and its
10492: descendents. @code{public} restores the compilation
10493: (i.e. @code{current}) word list that was in effect before. If you
10494: have several @code{protected}s without an intervening
10495: @code{public} or @code{set-current}, @code{public}
10496: will restore the compilation word list in effect before the first of
10497: these @code{protected}s.
1.6 pazsan 10498:
1.78 anton 10499: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10500: @subsubsection Dividing classes
10501: @cindex Dividing classes
10502: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10503:
1.78 anton 10504: You may want to do the definition of methods separate from the
10505: definition of the class, its selectors, fields, and instance variables,
10506: i.e., separate the implementation from the definition. You can do this
10507: in the following way:
1.6 pazsan 10508:
1.78 anton 10509: @example
10510: graphical class
10511: inst-value radius
10512: end-class circle
1.6 pazsan 10513:
1.78 anton 10514: ... \ do some other stuff
1.6 pazsan 10515:
1.78 anton 10516: circle methods \ now we are ready
1.44 crook 10517:
1.78 anton 10518: m: ( x y circle -- )
10519: radius draw-circle ;m
10520: overrides draw
1.6 pazsan 10521:
1.78 anton 10522: m: ( n-radius circle -- )
10523: [to-inst] radius ;m
10524: overrides construct
1.44 crook 10525:
1.78 anton 10526: end-methods
10527: @end example
1.7 pazsan 10528:
1.78 anton 10529: You can use several @code{methods}...@code{end-methods} sections. The
10530: only things you can do to the class in these sections are: defining
10531: methods, and overriding the class's selectors. You must not define new
10532: selectors or fields.
1.7 pazsan 10533:
1.78 anton 10534: Note that you often have to override a selector before using it. In
10535: particular, you usually have to override @code{construct} with a new
10536: method before you can invoke @code{heap-new} and friends. E.g., you
10537: must not create a circle before the @code{overrides construct} sequence
10538: in the example above.
1.7 pazsan 10539:
1.78 anton 10540: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10541: @subsubsection Object Interfaces
10542: @cindex object interfaces
10543: @cindex interfaces for objects
1.7 pazsan 10544:
1.78 anton 10545: In this model you can only call selectors defined in the class of the
10546: receiving objects or in one of its ancestors. If you call a selector
10547: with a receiving object that is not in one of these classes, the
10548: result is undefined; if you are lucky, the program crashes
10549: immediately.
1.7 pazsan 10550:
1.78 anton 10551: @cindex selectors common to hardly-related classes
10552: Now consider the case when you want to have a selector (or several)
10553: available in two classes: You would have to add the selector to a
10554: common ancestor class, in the worst case to @code{object}. You
10555: may not want to do this, e.g., because someone else is responsible for
10556: this ancestor class.
1.7 pazsan 10557:
1.78 anton 10558: The solution for this problem is interfaces. An interface is a
10559: collection of selectors. If a class implements an interface, the
10560: selectors become available to the class and its descendents. A class
10561: can implement an unlimited number of interfaces. For the problem
10562: discussed above, we would define an interface for the selector(s), and
10563: both classes would implement the interface.
1.7 pazsan 10564:
1.78 anton 10565: As an example, consider an interface @code{storage} for
10566: writing objects to disk and getting them back, and a class
10567: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10568:
1.78 anton 10569: @cindex @code{interface} usage
10570: @cindex @code{end-interface} usage
10571: @cindex @code{implementation} usage
10572: @example
10573: interface
10574: selector write ( file object -- )
10575: selector read1 ( file object -- )
10576: end-interface storage
1.13 pazsan 10577:
1.78 anton 10578: bar class
10579: storage implementation
1.13 pazsan 10580:
1.78 anton 10581: ... overrides write
10582: ... overrides read1
10583: ...
10584: end-class foo
10585: @end example
1.13 pazsan 10586:
1.78 anton 10587: @noindent
10588: (I would add a word @code{read} @i{( file -- object )} that uses
10589: @code{read1} internally, but that's beyond the point illustrated
10590: here.)
1.13 pazsan 10591:
1.78 anton 10592: Note that you cannot use @code{protected} in an interface; and
10593: of course you cannot define fields.
1.13 pazsan 10594:
1.78 anton 10595: In the Neon model, all selectors are available for all classes;
10596: therefore it does not need interfaces. The price you pay in this model
10597: is slower late binding, and therefore, added complexity to avoid late
10598: binding.
1.13 pazsan 10599:
1.78 anton 10600: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10601: @subsubsection @file{objects.fs} Implementation
10602: @cindex @file{objects.fs} implementation
1.13 pazsan 10603:
1.78 anton 10604: @cindex @code{object-map} discussion
10605: An object is a piece of memory, like one of the data structures
10606: described with @code{struct...end-struct}. It has a field
10607: @code{object-map} that points to the method map for the object's
10608: class.
1.13 pazsan 10609:
1.78 anton 10610: @cindex method map
10611: @cindex virtual function table
10612: The @emph{method map}@footnote{This is Self terminology; in C++
10613: terminology: virtual function table.} is an array that contains the
10614: execution tokens (@i{xt}s) of the methods for the object's class. Each
10615: selector contains an offset into a method map.
1.13 pazsan 10616:
1.78 anton 10617: @cindex @code{selector} implementation, class
10618: @code{selector} is a defining word that uses
10619: @code{CREATE} and @code{DOES>}. The body of the
10620: selector contains the offset; the @code{DOES>} action for a
10621: class selector is, basically:
1.8 pazsan 10622:
10623: @example
1.78 anton 10624: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10625: @end example
10626:
1.78 anton 10627: Since @code{object-map} is the first field of the object, it
10628: does not generate any code. As you can see, calling a selector has a
10629: small, constant cost.
1.26 crook 10630:
1.78 anton 10631: @cindex @code{current-interface} discussion
10632: @cindex class implementation and representation
10633: A class is basically a @code{struct} combined with a method
10634: map. During the class definition the alignment and size of the class
10635: are passed on the stack, just as with @code{struct}s, so
10636: @code{field} can also be used for defining class
10637: fields. However, passing more items on the stack would be
10638: inconvenient, so @code{class} builds a data structure in memory,
10639: which is accessed through the variable
10640: @code{current-interface}. After its definition is complete, the
10641: class is represented on the stack by a pointer (e.g., as parameter for
10642: a child class definition).
1.26 crook 10643:
1.78 anton 10644: A new class starts off with the alignment and size of its parent,
10645: and a copy of the parent's method map. Defining new fields extends the
10646: size and alignment; likewise, defining new selectors extends the
10647: method map. @code{overrides} just stores a new @i{xt} in the method
10648: map at the offset given by the selector.
1.13 pazsan 10649:
1.78 anton 10650: @cindex class binding, implementation
10651: Class binding just gets the @i{xt} at the offset given by the selector
10652: from the class's method map and @code{compile,}s (in the case of
10653: @code{[bind]}) it.
1.13 pazsan 10654:
1.78 anton 10655: @cindex @code{this} implementation
10656: @cindex @code{catch} and @code{this}
10657: @cindex @code{this} and @code{catch}
10658: I implemented @code{this} as a @code{value}. At the
10659: start of an @code{m:...;m} method the old @code{this} is
10660: stored to the return stack and restored at the end; and the object on
10661: the TOS is stored @code{TO this}. This technique has one
10662: disadvantage: If the user does not leave the method via
10663: @code{;m}, but via @code{throw} or @code{exit},
10664: @code{this} is not restored (and @code{exit} may
10665: crash). To deal with the @code{throw} problem, I have redefined
10666: @code{catch} to save and restore @code{this}; the same
10667: should be done with any word that can catch an exception. As for
10668: @code{exit}, I simply forbid it (as a replacement, there is
10669: @code{exitm}).
1.13 pazsan 10670:
1.78 anton 10671: @cindex @code{inst-var} implementation
10672: @code{inst-var} is just the same as @code{field}, with
10673: a different @code{DOES>} action:
1.13 pazsan 10674: @example
1.78 anton 10675: @@ this +
1.8 pazsan 10676: @end example
1.78 anton 10677: Similar for @code{inst-value}.
1.8 pazsan 10678:
1.78 anton 10679: @cindex class scoping implementation
10680: Each class also has a word list that contains the words defined with
10681: @code{inst-var} and @code{inst-value}, and its protected
10682: words. It also has a pointer to its parent. @code{class} pushes
10683: the word lists of the class and all its ancestors onto the search order stack,
10684: and @code{end-class} drops them.
1.20 pazsan 10685:
1.78 anton 10686: @cindex interface implementation
10687: An interface is like a class without fields, parent and protected
10688: words; i.e., it just has a method map. If a class implements an
10689: interface, its method map contains a pointer to the method map of the
10690: interface. The positive offsets in the map are reserved for class
10691: methods, therefore interface map pointers have negative
10692: offsets. Interfaces have offsets that are unique throughout the
10693: system, unlike class selectors, whose offsets are only unique for the
10694: classes where the selector is available (invokable).
1.20 pazsan 10695:
1.78 anton 10696: This structure means that interface selectors have to perform one
10697: indirection more than class selectors to find their method. Their body
10698: contains the interface map pointer offset in the class method map, and
10699: the method offset in the interface method map. The
10700: @code{does>} action for an interface selector is, basically:
1.20 pazsan 10701:
10702: @example
1.78 anton 10703: ( object selector-body )
10704: 2dup selector-interface @@ ( object selector-body object interface-offset )
10705: swap object-map @@ + @@ ( object selector-body map )
10706: swap selector-offset @@ + @@ execute
1.20 pazsan 10707: @end example
10708:
1.78 anton 10709: where @code{object-map} and @code{selector-offset} are
10710: first fields and generate no code.
1.20 pazsan 10711:
1.78 anton 10712: As a concrete example, consider the following code:
1.20 pazsan 10713:
10714: @example
1.78 anton 10715: interface
10716: selector if1sel1
10717: selector if1sel2
10718: end-interface if1
1.20 pazsan 10719:
1.78 anton 10720: object class
10721: if1 implementation
10722: selector cl1sel1
10723: cell% inst-var cl1iv1
1.20 pazsan 10724:
1.78 anton 10725: ' m1 overrides construct
10726: ' m2 overrides if1sel1
10727: ' m3 overrides if1sel2
10728: ' m4 overrides cl1sel2
10729: end-class cl1
1.20 pazsan 10730:
1.78 anton 10731: create obj1 object dict-new drop
10732: create obj2 cl1 dict-new drop
10733: @end example
1.20 pazsan 10734:
1.78 anton 10735: The data structure created by this code (including the data structure
10736: for @code{object}) is shown in the
10737: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
10738: @comment TODO add this diagram..
1.20 pazsan 10739:
1.78 anton 10740: @node Objects Glossary, , Objects Implementation, Objects
10741: @subsubsection @file{objects.fs} Glossary
10742: @cindex @file{objects.fs} Glossary
1.20 pazsan 10743:
10744:
1.78 anton 10745: doc---objects-bind
10746: doc---objects-<bind>
10747: doc---objects-bind'
10748: doc---objects-[bind]
10749: doc---objects-class
10750: doc---objects-class->map
10751: doc---objects-class-inst-size
10752: doc---objects-class-override!
1.79 anton 10753: doc---objects-class-previous
10754: doc---objects-class>order
1.78 anton 10755: doc---objects-construct
10756: doc---objects-current'
10757: doc---objects-[current]
10758: doc---objects-current-interface
10759: doc---objects-dict-new
10760: doc---objects-end-class
10761: doc---objects-end-class-noname
10762: doc---objects-end-interface
10763: doc---objects-end-interface-noname
10764: doc---objects-end-methods
10765: doc---objects-exitm
10766: doc---objects-heap-new
10767: doc---objects-implementation
10768: doc---objects-init-object
10769: doc---objects-inst-value
10770: doc---objects-inst-var
10771: doc---objects-interface
10772: doc---objects-m:
10773: doc---objects-:m
10774: doc---objects-;m
10775: doc---objects-method
10776: doc---objects-methods
10777: doc---objects-object
10778: doc---objects-overrides
10779: doc---objects-[parent]
10780: doc---objects-print
10781: doc---objects-protected
10782: doc---objects-public
10783: doc---objects-selector
10784: doc---objects-this
10785: doc---objects-<to-inst>
10786: doc---objects-[to-inst]
10787: doc---objects-to-this
10788: doc---objects-xt-new
1.20 pazsan 10789:
10790:
1.78 anton 10791: @c -------------------------------------------------------------
10792: @node OOF, Mini-OOF, Objects, Object-oriented Forth
10793: @subsection The @file{oof.fs} model
10794: @cindex oof
10795: @cindex object-oriented programming
1.20 pazsan 10796:
1.78 anton 10797: @cindex @file{objects.fs}
10798: @cindex @file{oof.fs}
1.20 pazsan 10799:
1.78 anton 10800: This section describes the @file{oof.fs} package.
1.20 pazsan 10801:
1.78 anton 10802: The package described in this section has been used in bigFORTH since 1991, and
10803: used for two large applications: a chromatographic system used to
10804: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 10805:
1.78 anton 10806: You can find a description (in German) of @file{oof.fs} in @cite{Object
10807: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
10808: 10(2), 1994.
1.20 pazsan 10809:
1.78 anton 10810: @menu
10811: * Properties of the OOF model::
10812: * Basic OOF Usage::
10813: * The OOF base class::
10814: * Class Declaration::
10815: * Class Implementation::
10816: @end menu
1.20 pazsan 10817:
1.78 anton 10818: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
10819: @subsubsection Properties of the @file{oof.fs} model
10820: @cindex @file{oof.fs} properties
1.20 pazsan 10821:
1.78 anton 10822: @itemize @bullet
10823: @item
10824: This model combines object oriented programming with information
10825: hiding. It helps you writing large application, where scoping is
10826: necessary, because it provides class-oriented scoping.
1.20 pazsan 10827:
1.78 anton 10828: @item
10829: Named objects, object pointers, and object arrays can be created,
10830: selector invocation uses the ``object selector'' syntax. Selector invocation
10831: to objects and/or selectors on the stack is a bit less convenient, but
10832: possible.
1.44 crook 10833:
1.78 anton 10834: @item
10835: Selector invocation and instance variable usage of the active object is
10836: straightforward, since both make use of the active object.
1.44 crook 10837:
1.78 anton 10838: @item
10839: Late binding is efficient and easy to use.
1.20 pazsan 10840:
1.78 anton 10841: @item
10842: State-smart objects parse selectors. However, extensibility is provided
10843: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 10844:
1.78 anton 10845: @item
10846: An implementation in ANS Forth is available.
1.20 pazsan 10847:
1.78 anton 10848: @end itemize
1.23 crook 10849:
10850:
1.78 anton 10851: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
10852: @subsubsection Basic @file{oof.fs} Usage
10853: @cindex @file{oof.fs} usage
1.23 crook 10854:
1.78 anton 10855: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 10856:
1.78 anton 10857: You can define a class for graphical objects like this:
1.23 crook 10858:
1.78 anton 10859: @cindex @code{class} usage
10860: @cindex @code{class;} usage
10861: @cindex @code{method} usage
10862: @example
10863: object class graphical \ "object" is the parent class
1.139 pazsan 10864: method draw ( x y -- )
1.78 anton 10865: class;
10866: @end example
1.23 crook 10867:
1.78 anton 10868: This code defines a class @code{graphical} with an
10869: operation @code{draw}. We can perform the operation
10870: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 10871:
1.78 anton 10872: @example
10873: 100 100 t-rex draw
10874: @end example
1.23 crook 10875:
1.78 anton 10876: @noindent
10877: where @code{t-rex} is an object or object pointer, created with e.g.
10878: @code{graphical : t-rex}.
1.23 crook 10879:
1.78 anton 10880: @cindex abstract class
10881: How do we create a graphical object? With the present definitions,
10882: we cannot create a useful graphical object. The class
10883: @code{graphical} describes graphical objects in general, but not
10884: any concrete graphical object type (C++ users would call it an
10885: @emph{abstract class}); e.g., there is no method for the selector
10886: @code{draw} in the class @code{graphical}.
1.23 crook 10887:
1.78 anton 10888: For concrete graphical objects, we define child classes of the
10889: class @code{graphical}, e.g.:
1.23 crook 10890:
1.78 anton 10891: @example
10892: graphical class circle \ "graphical" is the parent class
10893: cell var circle-radius
10894: how:
10895: : draw ( x y -- )
10896: circle-radius @@ draw-circle ;
1.23 crook 10897:
1.139 pazsan 10898: : init ( n-radius -- )
1.78 anton 10899: circle-radius ! ;
10900: class;
10901: @end example
1.1 anton 10902:
1.78 anton 10903: Here we define a class @code{circle} as a child of @code{graphical},
10904: with a field @code{circle-radius}; it defines new methods for the
10905: selectors @code{draw} and @code{init} (@code{init} is defined in
10906: @code{object}, the parent class of @code{graphical}).
1.1 anton 10907:
1.78 anton 10908: Now we can create a circle in the dictionary with:
1.1 anton 10909:
1.78 anton 10910: @example
10911: 50 circle : my-circle
10912: @end example
1.21 crook 10913:
1.78 anton 10914: @noindent
10915: @code{:} invokes @code{init}, thus initializing the field
10916: @code{circle-radius} with 50. We can draw this new circle at (100,100)
10917: with:
1.1 anton 10918:
1.78 anton 10919: @example
10920: 100 100 my-circle draw
10921: @end example
1.1 anton 10922:
1.78 anton 10923: @cindex selector invocation, restrictions
10924: @cindex class definition, restrictions
10925: Note: You can only invoke a selector if the receiving object belongs to
10926: the class where the selector was defined or one of its descendents;
10927: e.g., you can invoke @code{draw} only for objects belonging to
10928: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
10929: mechanism will check if you try to invoke a selector that is not
10930: defined in this class hierarchy, so you'll get an error at compilation
10931: time.
1.1 anton 10932:
10933:
1.78 anton 10934: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
10935: @subsubsection The @file{oof.fs} base class
10936: @cindex @file{oof.fs} base class
1.1 anton 10937:
1.78 anton 10938: When you define a class, you have to specify a parent class. So how do
10939: you start defining classes? There is one class available from the start:
10940: @code{object}. You have to use it as ancestor for all classes. It is the
10941: only class that has no parent. Classes are also objects, except that
10942: they don't have instance variables; class manipulation such as
10943: inheritance or changing definitions of a class is handled through
10944: selectors of the class @code{object}.
1.1 anton 10945:
1.78 anton 10946: @code{object} provides a number of selectors:
1.1 anton 10947:
1.78 anton 10948: @itemize @bullet
10949: @item
10950: @code{class} for subclassing, @code{definitions} to add definitions
10951: later on, and @code{class?} to get type informations (is the class a
10952: subclass of the class passed on the stack?).
1.1 anton 10953:
1.78 anton 10954: doc---object-class
10955: doc---object-definitions
10956: doc---object-class?
1.1 anton 10957:
10958:
1.26 crook 10959: @item
1.78 anton 10960: @code{init} and @code{dispose} as constructor and destructor of the
10961: object. @code{init} is invocated after the object's memory is allocated,
10962: while @code{dispose} also handles deallocation. Thus if you redefine
10963: @code{dispose}, you have to call the parent's dispose with @code{super
10964: dispose}, too.
10965:
10966: doc---object-init
10967: doc---object-dispose
10968:
1.1 anton 10969:
1.26 crook 10970: @item
1.78 anton 10971: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
10972: @code{[]} to create named and unnamed objects and object arrays or
10973: object pointers.
10974:
10975: doc---object-new
10976: doc---object-new[]
10977: doc---object-:
10978: doc---object-ptr
10979: doc---object-asptr
10980: doc---object-[]
10981:
1.1 anton 10982:
1.26 crook 10983: @item
1.78 anton 10984: @code{::} and @code{super} for explicit scoping. You should use explicit
10985: scoping only for super classes or classes with the same set of instance
10986: variables. Explicitly-scoped selectors use early binding.
1.21 crook 10987:
1.78 anton 10988: doc---object-::
10989: doc---object-super
1.21 crook 10990:
10991:
1.26 crook 10992: @item
1.78 anton 10993: @code{self} to get the address of the object
1.21 crook 10994:
1.78 anton 10995: doc---object-self
1.21 crook 10996:
10997:
1.78 anton 10998: @item
10999: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11000: pointers and instance defers.
1.21 crook 11001:
1.78 anton 11002: doc---object-bind
11003: doc---object-bound
11004: doc---object-link
11005: doc---object-is
1.21 crook 11006:
11007:
1.78 anton 11008: @item
11009: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11010: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11011:
1.78 anton 11012: doc---object-'
11013: doc---object-postpone
1.21 crook 11014:
11015:
1.78 anton 11016: @item
11017: @code{with} and @code{endwith} to select the active object from the
11018: stack, and enable its scope. Using @code{with} and @code{endwith}
11019: also allows you to create code using selector @code{postpone} without being
11020: trapped by the state-smart objects.
1.21 crook 11021:
1.78 anton 11022: doc---object-with
11023: doc---object-endwith
1.21 crook 11024:
11025:
1.78 anton 11026: @end itemize
1.21 crook 11027:
1.78 anton 11028: @node Class Declaration, Class Implementation, The OOF base class, OOF
11029: @subsubsection Class Declaration
11030: @cindex class declaration
1.21 crook 11031:
1.78 anton 11032: @itemize @bullet
11033: @item
11034: Instance variables
1.21 crook 11035:
1.78 anton 11036: doc---oof-var
1.21 crook 11037:
11038:
1.78 anton 11039: @item
11040: Object pointers
1.21 crook 11041:
1.78 anton 11042: doc---oof-ptr
11043: doc---oof-asptr
1.21 crook 11044:
11045:
1.78 anton 11046: @item
11047: Instance defers
1.21 crook 11048:
1.78 anton 11049: doc---oof-defer
1.21 crook 11050:
11051:
1.78 anton 11052: @item
11053: Method selectors
1.21 crook 11054:
1.78 anton 11055: doc---oof-early
11056: doc---oof-method
1.21 crook 11057:
11058:
1.78 anton 11059: @item
11060: Class-wide variables
1.21 crook 11061:
1.78 anton 11062: doc---oof-static
1.21 crook 11063:
11064:
1.78 anton 11065: @item
11066: End declaration
1.1 anton 11067:
1.78 anton 11068: doc---oof-how:
11069: doc---oof-class;
1.21 crook 11070:
11071:
1.78 anton 11072: @end itemize
1.21 crook 11073:
1.78 anton 11074: @c -------------------------------------------------------------
11075: @node Class Implementation, , Class Declaration, OOF
11076: @subsubsection Class Implementation
11077: @cindex class implementation
1.21 crook 11078:
1.78 anton 11079: @c -------------------------------------------------------------
11080: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11081: @subsection The @file{mini-oof.fs} model
11082: @cindex mini-oof
1.21 crook 11083:
1.78 anton 11084: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11085: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11086: and reduces to the bare minimum of features. This is based on a posting
11087: of Bernd Paysan in comp.lang.forth.
1.21 crook 11088:
1.78 anton 11089: @menu
11090: * Basic Mini-OOF Usage::
11091: * Mini-OOF Example::
11092: * Mini-OOF Implementation::
11093: @end menu
1.21 crook 11094:
1.78 anton 11095: @c -------------------------------------------------------------
11096: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11097: @subsubsection Basic @file{mini-oof.fs} Usage
11098: @cindex mini-oof usage
1.21 crook 11099:
1.78 anton 11100: There is a base class (@code{class}, which allocates one cell for the
11101: object pointer) plus seven other words: to define a method, a variable,
11102: a class; to end a class, to resolve binding, to allocate an object and
11103: to compile a class method.
11104: @comment TODO better description of the last one
1.26 crook 11105:
1.21 crook 11106:
1.78 anton 11107: doc-object
11108: doc-method
11109: doc-var
11110: doc-class
11111: doc-end-class
11112: doc-defines
11113: doc-new
11114: doc-::
1.21 crook 11115:
11116:
11117:
1.78 anton 11118: @c -------------------------------------------------------------
11119: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11120: @subsubsection Mini-OOF Example
11121: @cindex mini-oof example
1.1 anton 11122:
1.78 anton 11123: A short example shows how to use this package. This example, in slightly
11124: extended form, is supplied as @file{moof-exm.fs}
11125: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11126:
1.26 crook 11127: @example
1.78 anton 11128: object class
11129: method init
11130: method draw
11131: end-class graphical
1.26 crook 11132: @end example
1.20 pazsan 11133:
1.78 anton 11134: This code defines a class @code{graphical} with an
11135: operation @code{draw}. We can perform the operation
11136: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11137:
1.26 crook 11138: @example
1.78 anton 11139: 100 100 t-rex draw
1.26 crook 11140: @end example
1.12 anton 11141:
1.78 anton 11142: where @code{t-rex} is an object or object pointer, created with e.g.
11143: @code{graphical new Constant t-rex}.
1.12 anton 11144:
1.78 anton 11145: For concrete graphical objects, we define child classes of the
11146: class @code{graphical}, e.g.:
1.12 anton 11147:
1.26 crook 11148: @example
11149: graphical class
1.78 anton 11150: cell var circle-radius
11151: end-class circle \ "graphical" is the parent class
1.12 anton 11152:
1.78 anton 11153: :noname ( x y -- )
11154: circle-radius @@ draw-circle ; circle defines draw
11155: :noname ( r -- )
11156: circle-radius ! ; circle defines init
11157: @end example
1.12 anton 11158:
1.78 anton 11159: There is no implicit init method, so we have to define one. The creation
11160: code of the object now has to call init explicitely.
1.21 crook 11161:
1.78 anton 11162: @example
11163: circle new Constant my-circle
11164: 50 my-circle init
1.12 anton 11165: @end example
11166:
1.78 anton 11167: It is also possible to add a function to create named objects with
11168: automatic call of @code{init}, given that all objects have @code{init}
11169: on the same place:
1.38 anton 11170:
1.78 anton 11171: @example
11172: : new: ( .. o "name" -- )
11173: new dup Constant init ;
11174: 80 circle new: large-circle
11175: @end example
1.12 anton 11176:
1.78 anton 11177: We can draw this new circle at (100,100) with:
1.12 anton 11178:
1.78 anton 11179: @example
11180: 100 100 my-circle draw
11181: @end example
1.12 anton 11182:
1.78 anton 11183: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11184: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11185:
1.78 anton 11186: Object-oriented systems with late binding typically use a
11187: ``vtable''-approach: the first variable in each object is a pointer to a
11188: table, which contains the methods as function pointers. The vtable
11189: may also contain other information.
1.12 anton 11190:
1.79 anton 11191: So first, let's declare selectors:
1.37 anton 11192:
11193: @example
1.79 anton 11194: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11195: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11196: @end example
1.37 anton 11197:
1.79 anton 11198: During selector declaration, the number of selectors and instance
11199: variables is on the stack (in address units). @code{method} creates one
11200: selector and increments the selector number. To execute a selector, it
1.78 anton 11201: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11202: executes the method @i{xt} stored there. Each selector takes the object
11203: it is invoked with as top of stack parameter; it passes the parameters
11204: (including the object) unchanged to the appropriate method which should
1.78 anton 11205: consume that object.
1.37 anton 11206:
1.78 anton 11207: Now, we also have to declare instance variables
1.37 anton 11208:
1.78 anton 11209: @example
1.79 anton 11210: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11211: DOES> ( o -- addr ) @@ + ;
1.37 anton 11212: @end example
11213:
1.78 anton 11214: As before, a word is created with the current offset. Instance
11215: variables can have different sizes (cells, floats, doubles, chars), so
11216: all we do is take the size and add it to the offset. If your machine
11217: has alignment restrictions, put the proper @code{aligned} or
11218: @code{faligned} before the variable, to adjust the variable
11219: offset. That's why it is on the top of stack.
1.37 anton 11220:
1.78 anton 11221: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11222:
1.78 anton 11223: @example
11224: Create object 1 cells , 2 cells ,
1.79 anton 11225: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11226: @end example
1.12 anton 11227:
1.78 anton 11228: For inheritance, the vtable of the parent object has to be
11229: copied when a new, derived class is declared. This gives all the
11230: methods of the parent class, which can be overridden, though.
1.12 anton 11231:
1.78 anton 11232: @example
1.79 anton 11233: : end-class ( class selectors vars "name" -- )
1.78 anton 11234: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11235: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11236: @end example
1.12 anton 11237:
1.78 anton 11238: The first line creates the vtable, initialized with
11239: @code{noop}s. The second line is the inheritance mechanism, it
11240: copies the xts from the parent vtable.
1.12 anton 11241:
1.78 anton 11242: We still have no way to define new methods, let's do that now:
1.12 anton 11243:
1.26 crook 11244: @example
1.79 anton 11245: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11246: @end example
1.12 anton 11247:
1.78 anton 11248: To allocate a new object, we need a word, too:
1.12 anton 11249:
1.78 anton 11250: @example
11251: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11252: @end example
11253:
1.78 anton 11254: Sometimes derived classes want to access the method of the
11255: parent object. There are two ways to achieve this with Mini-OOF:
11256: first, you could use named words, and second, you could look up the
11257: vtable of the parent object.
1.12 anton 11258:
1.78 anton 11259: @example
11260: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11261: @end example
1.12 anton 11262:
11263:
1.78 anton 11264: Nothing can be more confusing than a good example, so here is
11265: one. First let's declare a text object (called
11266: @code{button}), that stores text and position:
1.12 anton 11267:
1.78 anton 11268: @example
11269: object class
11270: cell var text
11271: cell var len
11272: cell var x
11273: cell var y
11274: method init
11275: method draw
11276: end-class button
11277: @end example
1.12 anton 11278:
1.78 anton 11279: @noindent
11280: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11281:
1.26 crook 11282: @example
1.78 anton 11283: :noname ( o -- )
11284: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11285: button defines draw
11286: :noname ( addr u o -- )
11287: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11288: button defines init
1.26 crook 11289: @end example
1.12 anton 11290:
1.78 anton 11291: @noindent
11292: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11293: new data and no new selectors:
1.78 anton 11294:
11295: @example
11296: button class
11297: end-class bold-button
1.12 anton 11298:
1.78 anton 11299: : bold 27 emit ." [1m" ;
11300: : normal 27 emit ." [0m" ;
11301: @end example
1.1 anton 11302:
1.78 anton 11303: @noindent
11304: The class @code{bold-button} has a different draw method to
11305: @code{button}, but the new method is defined in terms of the draw method
11306: for @code{button}:
1.20 pazsan 11307:
1.78 anton 11308: @example
11309: :noname bold [ button :: draw ] normal ; bold-button defines draw
11310: @end example
1.21 crook 11311:
1.78 anton 11312: @noindent
1.79 anton 11313: Finally, create two objects and apply selectors:
1.21 crook 11314:
1.26 crook 11315: @example
1.78 anton 11316: button new Constant foo
11317: s" thin foo" foo init
11318: page
11319: foo draw
11320: bold-button new Constant bar
11321: s" fat bar" bar init
11322: 1 bar y !
11323: bar draw
1.26 crook 11324: @end example
1.21 crook 11325:
11326:
1.78 anton 11327: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11328: @subsection Comparison with other object models
11329: @cindex comparison of object models
11330: @cindex object models, comparison
11331:
11332: Many object-oriented Forth extensions have been proposed (@cite{A survey
11333: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11334: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11335: relation of the object models described here to two well-known and two
11336: closely-related (by the use of method maps) models. Andras Zsoter
11337: helped us with this section.
11338:
11339: @cindex Neon model
11340: The most popular model currently seems to be the Neon model (see
11341: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11342: 1997) by Andrew McKewan) but this model has a number of limitations
11343: @footnote{A longer version of this critique can be
11344: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11345: Dimensions, May 1997) by Anton Ertl.}:
11346:
11347: @itemize @bullet
11348: @item
11349: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11350: to pass objects on the stack.
1.21 crook 11351:
1.78 anton 11352: @item
11353: It requires that the selector parses the input stream (at
1.79 anton 11354: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11355: hard to find.
1.21 crook 11356:
1.78 anton 11357: @item
1.79 anton 11358: It allows using every selector on every object; this eliminates the
11359: need for interfaces, but makes it harder to create efficient
11360: implementations.
1.78 anton 11361: @end itemize
1.21 crook 11362:
1.78 anton 11363: @cindex Pountain's object-oriented model
11364: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11365: Press, London, 1987) by Dick Pountain. However, it is not really about
11366: object-oriented programming, because it hardly deals with late
11367: binding. Instead, it focuses on features like information hiding and
11368: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11369:
1.78 anton 11370: @cindex Zsoter's object-oriented model
1.79 anton 11371: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11372: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11373: describes a model that makes heavy use of an active object (like
11374: @code{this} in @file{objects.fs}): The active object is not only used
11375: for accessing all fields, but also specifies the receiving object of
11376: every selector invocation; you have to change the active object
11377: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11378: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11379: the method entry point is unnecessary with Zsoter's model, because the
11380: receiving object is the active object already. On the other hand, the
11381: explicit change is absolutely necessary in that model, because otherwise
11382: no one could ever change the active object. An ANS Forth implementation
11383: of this model is available through
11384: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11385:
1.78 anton 11386: @cindex @file{oof.fs}, differences to other models
11387: The @file{oof.fs} model combines information hiding and overloading
11388: resolution (by keeping names in various word lists) with object-oriented
11389: programming. It sets the active object implicitly on method entry, but
11390: also allows explicit changing (with @code{>o...o>} or with
11391: @code{with...endwith}). It uses parsing and state-smart objects and
11392: classes for resolving overloading and for early binding: the object or
11393: class parses the selector and determines the method from this. If the
11394: selector is not parsed by an object or class, it performs a call to the
11395: selector for the active object (late binding), like Zsoter's model.
11396: Fields are always accessed through the active object. The big
11397: disadvantage of this model is the parsing and the state-smartness, which
11398: reduces extensibility and increases the opportunities for subtle bugs;
11399: essentially, you are only safe if you never tick or @code{postpone} an
11400: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11401:
1.78 anton 11402: @cindex @file{mini-oof.fs}, differences to other models
11403: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11404: version of the @file{objects.fs} model, but syntactically it is a
11405: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11406:
11407:
1.78 anton 11408: @c -------------------------------------------------------------
1.150 anton 11409: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11410: @section Programming Tools
11411: @cindex programming tools
1.21 crook 11412:
1.78 anton 11413: @c !! move this and assembler down below OO stuff.
1.21 crook 11414:
1.78 anton 11415: @menu
1.150 anton 11416: * Examining:: Data and Code.
11417: * Forgetting words:: Usually before reloading.
1.78 anton 11418: * Debugging:: Simple and quick.
11419: * Assertions:: Making your programs self-checking.
11420: * Singlestep Debugger:: Executing your program word by word.
11421: @end menu
1.21 crook 11422:
1.78 anton 11423: @node Examining, Forgetting words, Programming Tools, Programming Tools
11424: @subsection Examining data and code
11425: @cindex examining data and code
11426: @cindex data examination
11427: @cindex code examination
1.44 crook 11428:
1.78 anton 11429: The following words inspect the stack non-destructively:
1.21 crook 11430:
1.78 anton 11431: doc-.s
11432: doc-f.s
1.158 anton 11433: doc-maxdepth-.s
1.44 crook 11434:
1.78 anton 11435: There is a word @code{.r} but it does @i{not} display the return stack!
11436: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11437:
1.78 anton 11438: doc-depth
11439: doc-fdepth
11440: doc-clearstack
1.124 anton 11441: doc-clearstacks
1.21 crook 11442:
1.78 anton 11443: The following words inspect memory.
1.21 crook 11444:
1.78 anton 11445: doc-?
11446: doc-dump
1.21 crook 11447:
1.78 anton 11448: And finally, @code{see} allows to inspect code:
1.21 crook 11449:
1.78 anton 11450: doc-see
11451: doc-xt-see
1.111 anton 11452: doc-simple-see
11453: doc-simple-see-range
1.21 crook 11454:
1.78 anton 11455: @node Forgetting words, Debugging, Examining, Programming Tools
11456: @subsection Forgetting words
11457: @cindex words, forgetting
11458: @cindex forgeting words
1.21 crook 11459:
1.78 anton 11460: @c anton: other, maybe better places for this subsection: Defining Words;
11461: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11462:
1.78 anton 11463: Forth allows you to forget words (and everything that was alloted in the
11464: dictonary after them) in a LIFO manner.
1.21 crook 11465:
1.78 anton 11466: doc-marker
1.21 crook 11467:
1.78 anton 11468: The most common use of this feature is during progam development: when
11469: you change a source file, forget all the words it defined and load it
11470: again (since you also forget everything defined after the source file
11471: was loaded, you have to reload that, too). Note that effects like
11472: storing to variables and destroyed system words are not undone when you
11473: forget words. With a system like Gforth, that is fast enough at
11474: starting up and compiling, I find it more convenient to exit and restart
11475: Gforth, as this gives me a clean slate.
1.21 crook 11476:
1.78 anton 11477: Here's an example of using @code{marker} at the start of a source file
11478: that you are debugging; it ensures that you only ever have one copy of
11479: the file's definitions compiled at any time:
1.21 crook 11480:
1.78 anton 11481: @example
11482: [IFDEF] my-code
11483: my-code
11484: [ENDIF]
1.26 crook 11485:
1.78 anton 11486: marker my-code
11487: init-included-files
1.21 crook 11488:
1.78 anton 11489: \ .. definitions start here
11490: \ .
11491: \ .
11492: \ end
11493: @end example
1.21 crook 11494:
1.26 crook 11495:
1.78 anton 11496: @node Debugging, Assertions, Forgetting words, Programming Tools
11497: @subsection Debugging
11498: @cindex debugging
1.21 crook 11499:
1.78 anton 11500: Languages with a slow edit/compile/link/test development loop tend to
11501: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11502:
1.78 anton 11503: A much better (faster) way in fast-compiling languages is to add
11504: printing code at well-selected places, let the program run, look at
11505: the output, see where things went wrong, add more printing code, etc.,
11506: until the bug is found.
1.21 crook 11507:
1.78 anton 11508: The simple debugging aids provided in @file{debugs.fs}
11509: are meant to support this style of debugging.
1.21 crook 11510:
1.78 anton 11511: The word @code{~~} prints debugging information (by default the source
11512: location and the stack contents). It is easy to insert. If you use Emacs
11513: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11514: query-replace them with nothing). The deferred words
1.101 anton 11515: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11516: @code{~~}. The default source location output format works well with
11517: Emacs' compilation mode, so you can step through the program at the
11518: source level using @kbd{C-x `} (the advantage over a stepping debugger
11519: is that you can step in any direction and you know where the crash has
11520: happened or where the strange data has occurred).
1.21 crook 11521:
1.78 anton 11522: doc-~~
11523: doc-printdebugdata
1.101 anton 11524: doc-.debugline
1.21 crook 11525:
1.106 anton 11526: @cindex filenames in @code{~~} output
11527: @code{~~} (and assertions) will usually print the wrong file name if a
11528: marker is executed in the same file after their occurance. They will
11529: print @samp{*somewhere*} as file name if a marker is executed in the
11530: same file before their occurance.
11531:
11532:
1.78 anton 11533: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11534: @subsection Assertions
11535: @cindex assertions
1.21 crook 11536:
1.78 anton 11537: It is a good idea to make your programs self-checking, especially if you
11538: make an assumption that may become invalid during maintenance (for
11539: example, that a certain field of a data structure is never zero). Gforth
11540: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11541:
11542: @example
1.78 anton 11543: assert( @i{flag} )
1.26 crook 11544: @end example
11545:
1.78 anton 11546: The code between @code{assert(} and @code{)} should compute a flag, that
11547: should be true if everything is alright and false otherwise. It should
11548: not change anything else on the stack. The overall stack effect of the
11549: assertion is @code{( -- )}. E.g.
1.21 crook 11550:
1.26 crook 11551: @example
1.78 anton 11552: assert( 1 1 + 2 = ) \ what we learn in school
11553: assert( dup 0<> ) \ assert that the top of stack is not zero
11554: assert( false ) \ this code should not be reached
1.21 crook 11555: @end example
11556:
1.78 anton 11557: The need for assertions is different at different times. During
11558: debugging, we want more checking, in production we sometimes care more
11559: for speed. Therefore, assertions can be turned off, i.e., the assertion
11560: becomes a comment. Depending on the importance of an assertion and the
11561: time it takes to check it, you may want to turn off some assertions and
11562: keep others turned on. Gforth provides several levels of assertions for
11563: this purpose:
11564:
11565:
11566: doc-assert0(
11567: doc-assert1(
11568: doc-assert2(
11569: doc-assert3(
11570: doc-assert(
11571: doc-)
1.21 crook 11572:
11573:
1.78 anton 11574: The variable @code{assert-level} specifies the highest assertions that
11575: are turned on. I.e., at the default @code{assert-level} of one,
11576: @code{assert0(} and @code{assert1(} assertions perform checking, while
11577: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11578:
1.78 anton 11579: The value of @code{assert-level} is evaluated at compile-time, not at
11580: run-time. Therefore you cannot turn assertions on or off at run-time;
11581: you have to set the @code{assert-level} appropriately before compiling a
11582: piece of code. You can compile different pieces of code at different
11583: @code{assert-level}s (e.g., a trusted library at level 1 and
11584: newly-written code at level 3).
1.26 crook 11585:
11586:
1.78 anton 11587: doc-assert-level
1.26 crook 11588:
11589:
1.78 anton 11590: If an assertion fails, a message compatible with Emacs' compilation mode
11591: is produced and the execution is aborted (currently with @code{ABORT"}.
11592: If there is interest, we will introduce a special throw code. But if you
11593: intend to @code{catch} a specific condition, using @code{throw} is
11594: probably more appropriate than an assertion).
1.106 anton 11595:
11596: @cindex filenames in assertion output
11597: Assertions (and @code{~~}) will usually print the wrong file name if a
11598: marker is executed in the same file after their occurance. They will
11599: print @samp{*somewhere*} as file name if a marker is executed in the
11600: same file before their occurance.
1.44 crook 11601:
1.78 anton 11602: Definitions in ANS Forth for these assertion words are provided
11603: in @file{compat/assert.fs}.
1.26 crook 11604:
1.44 crook 11605:
1.78 anton 11606: @node Singlestep Debugger, , Assertions, Programming Tools
11607: @subsection Singlestep Debugger
11608: @cindex singlestep Debugger
11609: @cindex debugging Singlestep
1.44 crook 11610:
1.159 anton 11611: The singlestep debugger works only with the engine @code{gforth-ditc}.
1.112 anton 11612:
1.78 anton 11613: When you create a new word there's often the need to check whether it
11614: behaves correctly or not. You can do this by typing @code{dbg
11615: badword}. A debug session might look like this:
1.26 crook 11616:
1.78 anton 11617: @example
11618: : badword 0 DO i . LOOP ; ok
11619: 2 dbg badword
11620: : badword
11621: Scanning code...
1.44 crook 11622:
1.78 anton 11623: Nesting debugger ready!
1.44 crook 11624:
1.78 anton 11625: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11626: 400D4740 8049F68 DO -> [ 0 ]
11627: 400D4744 804A0C8 i -> [ 1 ] 00000
11628: 400D4748 400C5E60 . -> 0 [ 0 ]
11629: 400D474C 8049D0C LOOP -> [ 0 ]
11630: 400D4744 804A0C8 i -> [ 1 ] 00001
11631: 400D4748 400C5E60 . -> 1 [ 0 ]
11632: 400D474C 8049D0C LOOP -> [ 0 ]
11633: 400D4758 804B384 ; -> ok
11634: @end example
1.21 crook 11635:
1.78 anton 11636: Each line displayed is one step. You always have to hit return to
11637: execute the next word that is displayed. If you don't want to execute
11638: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
11639: an overview what keys are available:
1.44 crook 11640:
1.78 anton 11641: @table @i
1.44 crook 11642:
1.78 anton 11643: @item @key{RET}
11644: Next; Execute the next word.
1.21 crook 11645:
1.78 anton 11646: @item n
11647: Nest; Single step through next word.
1.44 crook 11648:
1.78 anton 11649: @item u
11650: Unnest; Stop debugging and execute rest of word. If we got to this word
11651: with nest, continue debugging with the calling word.
1.44 crook 11652:
1.78 anton 11653: @item d
11654: Done; Stop debugging and execute rest.
1.21 crook 11655:
1.78 anton 11656: @item s
11657: Stop; Abort immediately.
1.44 crook 11658:
1.78 anton 11659: @end table
1.44 crook 11660:
1.78 anton 11661: Debugging large application with this mechanism is very difficult, because
11662: you have to nest very deeply into the program before the interesting part
11663: begins. This takes a lot of time.
1.26 crook 11664:
1.78 anton 11665: To do it more directly put a @code{BREAK:} command into your source code.
11666: When program execution reaches @code{BREAK:} the single step debugger is
11667: invoked and you have all the features described above.
1.44 crook 11668:
1.78 anton 11669: If you have more than one part to debug it is useful to know where the
11670: program has stopped at the moment. You can do this by the
11671: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
11672: string is typed out when the ``breakpoint'' is reached.
1.44 crook 11673:
1.26 crook 11674:
1.78 anton 11675: doc-dbg
11676: doc-break:
11677: doc-break"
1.44 crook 11678:
1.150 anton 11679: @c ------------------------------------------------------------
11680: @node C Interface, Assembler and Code Words, Programming Tools, Words
11681: @section C Interface
11682: @cindex C interface
11683: @cindex foreign language interface
11684: @cindex interface to C functions
11685:
11686: Note that the C interface is not yet complete; a better way of
11687: declaring C functions is planned, as well as a way of declaring
11688: structs, unions, and their fields.
11689:
11690: @menu
11691: * Calling C Functions::
11692: * Declaring C Functions::
11693: * Callbacks::
1.155 anton 11694: * Low-Level C Interface Words::
1.150 anton 11695: @end menu
11696:
1.151 pazsan 11697: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 11698: @subsection Calling C functions
1.155 anton 11699: @cindex C functions, calls to
11700: @cindex calling C functions
1.150 anton 11701:
1.151 pazsan 11702: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 11703: can call it as follows: You push the arguments on the stack(s), and
11704: then call the word for the C function. The arguments have to be
11705: pushed in the same order as the arguments appear in the C
11706: documentation (i.e., the first argument is deepest on the stack).
11707: Integer and pointer arguments have to be pushed on the data stack,
11708: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 11709: by the called C function.
1.150 anton 11710:
1.155 anton 11711: On returning from the C function, the return value, if any, resides on
11712: the appropriate stack: an integer return value is pushed on the data
11713: stack, an FP return value on the FP stack, and a void return value
11714: results in not pushing anything. Note that most C functions have a
11715: return value, even if that is often not used in C; in Forth, you have
11716: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 11717:
11718: By default, an integer argument or return value corresponds to a
11719: single cell, and a floating-point argument or return value corresponds
11720: to a Forth float value; the C interface performs the appropriate
11721: conversions where necessary, on a best-effort basis (in some cases,
11722: there may be some loss).
11723:
11724: As an example, consider the POSIX function @code{lseek()}:
11725:
11726: @example
11727: off_t lseek(int fd, off_t offset, int whence);
11728: @end example
11729:
11730: This function takes three integer arguments, and returns an integer
11731: argument, so a Forth call for setting the current file offset to the
11732: start of the file could look like this:
11733:
11734: @example
11735: fd @@ 0 SEEK_SET lseek -1 = if
11736: ... \ error handling
11737: then
11738: @end example
11739:
11740: You might be worried that an @code{off_t} does not fit into a cell, so
11741: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 11742: of the return values. In that case, in your declaration of the
11743: function (@pxref{Declaring C Functions}) you should declare it to use
11744: double-cells for the off_t argument and return value, and maybe give
11745: the resulting Forth word a different name, like @code{dlseek}; the
11746: result could be called like this:
1.150 anton 11747:
11748: @example
11749: fd @@ 0. SEEK_SET dlseek -1. d= if
11750: ... \ error handling
11751: then
11752: @end example
11753:
11754: Passing and returning structs or unions is currently not supported by
11755: our interface@footnote{If you know the calling convention of your C
11756: compiler, you usually can call such functions in some way, but that
11757: way is usually not portable between platforms, and sometimes not even
11758: between C compilers.}.
11759:
11760: Calling functions with a variable number of arguments (e.g.,
11761: @code{printf()}) is currently only supported by having you declare one
11762: function-calling word for each argument pattern, and calling the
11763: appropriate word for the desired pattern.
11764:
1.155 anton 11765:
1.151 pazsan 11766: @node Declaring C Functions, Callbacks, Calling C Functions, C Interface
1.150 anton 11767: @subsection Declaring C Functions
1.155 anton 11768: @cindex C functions, declarations
11769: @cindex declaring C functions
1.150 anton 11770:
11771: Before you can call @code{lseek} or @code{dlseek}, you have to declare
11772: it. You have to look up in your system what the concrete type for the
11773: abstract type @code{off_t} is; let's assume it is @code{long}. Then
11774: the declarations for these words are:
11775:
11776: @example
11777: library libc libc.so.6
11778: libc lseek int long int (long) lseek ( fd noffset whence -- noffset2 )
11779: libc dlseek int dlong int (dlong) lseek ( fd doffset whence -- doffset2 )
11780: @end example
11781:
11782: The first line defines a Forth word @code{libc} for accessing the C
11783: functions in the shared library @file{libc.so.6} (the name of the
11784: shared library depends on the library and the OS; this example is the
11785: standard C library (containing most of the standard C and Unix
11786: functions) for GNU/Linux systems since about 1998).
11787:
11788: The next two lines define two Forth words for the same C function
11789: @code{lseek()}; the middle line defines @code{lseek ( n1 n2 n3 -- n
1.155 anton 11790: )}, and the last line defines @code{dlseek ( n1 d2 n3 -- d )}.
1.150 anton 11791:
11792: As you can see, the declarations are relatively platform-dependent
11793: (e.g., on one platform @code{off_t} may be a @code{long}, whereas on
11794: another platform it may be a @code{long long}; actually, in this case
11795: you can have this difference even on the same platform), while the
11796: resulting function-calling words are platform-independent, and calls
11797: to them are portable.
11798:
11799: At some point in the future this interface will be superseded by a
11800: more convenient one with fewer portability issues. But the resulting
1.155 anton 11801: words for calling the C function will still have the same interface,
1.156 anton 11802: so you will not need to change the calls.
1.155 anton 11803:
11804: Anyway, here are the words for the current interface:
1.150 anton 11805:
1.155 anton 11806: doc-library
11807: doc-int
11808: doc-dint
11809: doc-uint
11810: doc-udint
11811: doc-long
11812: doc-dlong
11813: doc-ulong
11814: doc-udlong
11815: doc-longlong
11816: doc-dlonglong
11817: doc-ulonglong
11818: doc-udlonglong
1.156 anton 11819: doc-ptr
1.155 anton 11820: doc-cfloat
11821: doc-cdouble
11822: doc-clongdouble
11823: doc-(int)
11824: doc-(dint)
11825: doc-(uint)
11826: doc-(udint)
11827: doc-(long)
11828: doc-(dlong)
11829: doc-(ulong)
11830: doc-(udlong)
11831: doc-(longlong)
11832: doc-(dlonglong)
11833: doc-(ulonglong)
11834: doc-(udlonglong)
1.156 anton 11835: doc-(ptr)
1.155 anton 11836: doc-(cfloat)
11837: doc-(cdouble)
11838: doc-(clongdouble)
1.150 anton 11839:
1.155 anton 11840:
11841: @node Callbacks, Low-Level C Interface Words, Declaring C Functions, C Interface
1.150 anton 11842: @subsection Callbacks
1.155 anton 11843: @cindex Callback functions written in Forth
11844: @cindex C function pointers to Forth words
11845:
11846: In some cases you have to pass a function pointer to a C function,
11847: i.e., the library wants to call back to your application (and the
11848: pointed-to function is called a callback function). You can pass the
11849: address of an existing C function (that you get with @code{lib-sym},
11850: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
11851: function, you probably want to define the function as a Forth word.
11852:
11853: !!!
11854: @c I don't understand the existing callback interface from the example - anton
11855:
11856: doc-callback
11857: doc-callback;
11858: doc-fptr
1.150 anton 11859:
1.155 anton 11860: @node Low-Level C Interface Words, , Callbacks, C Interface
11861: @subsection Low-Level C Interface Words
1.44 crook 11862:
1.155 anton 11863: doc-open-lib
11864: doc-lib-sym
1.26 crook 11865:
1.78 anton 11866: @c -------------------------------------------------------------
1.150 anton 11867: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 11868: @section Assembler and Code Words
11869: @cindex assembler
11870: @cindex code words
1.44 crook 11871:
1.78 anton 11872: @menu
11873: * Code and ;code::
11874: * Common Assembler:: Assembler Syntax
11875: * Common Disassembler::
11876: * 386 Assembler:: Deviations and special cases
11877: * Alpha Assembler:: Deviations and special cases
11878: * MIPS assembler:: Deviations and special cases
1.161 anton 11879: * PowerPC assembler:: Deviations and special cases
1.78 anton 11880: * Other assemblers:: How to write them
11881: @end menu
1.21 crook 11882:
1.78 anton 11883: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
11884: @subsection @code{Code} and @code{;code}
1.26 crook 11885:
1.78 anton 11886: Gforth provides some words for defining primitives (words written in
11887: machine code), and for defining the machine-code equivalent of
11888: @code{DOES>}-based defining words. However, the machine-independent
11889: nature of Gforth poses a few problems: First of all, Gforth runs on
11890: several architectures, so it can provide no standard assembler. What's
11891: worse is that the register allocation not only depends on the processor,
11892: but also on the @code{gcc} version and options used.
1.44 crook 11893:
1.78 anton 11894: The words that Gforth offers encapsulate some system dependences (e.g.,
11895: the header structure), so a system-independent assembler may be used in
11896: Gforth. If you do not have an assembler, you can compile machine code
11897: directly with @code{,} and @code{c,}@footnote{This isn't portable,
11898: because these words emit stuff in @i{data} space; it works because
11899: Gforth has unified code/data spaces. Assembler isn't likely to be
11900: portable anyway.}.
1.21 crook 11901:
1.44 crook 11902:
1.78 anton 11903: doc-assembler
11904: doc-init-asm
11905: doc-code
11906: doc-end-code
11907: doc-;code
11908: doc-flush-icache
1.44 crook 11909:
1.21 crook 11910:
1.78 anton 11911: If @code{flush-icache} does not work correctly, @code{code} words
11912: etc. will not work (reliably), either.
1.44 crook 11913:
1.78 anton 11914: The typical usage of these @code{code} words can be shown most easily by
11915: analogy to the equivalent high-level defining words:
1.44 crook 11916:
1.78 anton 11917: @example
11918: : foo code foo
11919: <high-level Forth words> <assembler>
11920: ; end-code
11921:
11922: : bar : bar
11923: <high-level Forth words> <high-level Forth words>
11924: CREATE CREATE
11925: <high-level Forth words> <high-level Forth words>
11926: DOES> ;code
11927: <high-level Forth words> <assembler>
11928: ; end-code
11929: @end example
1.21 crook 11930:
1.78 anton 11931: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 11932:
1.78 anton 11933: @cindex registers of the inner interpreter
11934: In the assembly code you will want to refer to the inner interpreter's
11935: registers (e.g., the data stack pointer) and you may want to use other
11936: registers for temporary storage. Unfortunately, the register allocation
11937: is installation-dependent.
1.44 crook 11938:
1.78 anton 11939: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 11940: (return stack pointer) may be in different places in @code{gforth} and
11941: @code{gforth-fast}, or different installations. This means that you
11942: cannot write a @code{NEXT} routine that works reliably on both versions
11943: or different installations; so for doing @code{NEXT}, I recommend
11944: jumping to @code{' noop >code-address}, which contains nothing but a
11945: @code{NEXT}.
1.21 crook 11946:
1.78 anton 11947: For general accesses to the inner interpreter's registers, the easiest
11948: solution is to use explicit register declarations (@pxref{Explicit Reg
11949: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
11950: all of the inner interpreter's registers: You have to compile Gforth
11951: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
11952: the appropriate declarations must be present in the @code{machine.h}
11953: file (see @code{mips.h} for an example; you can find a full list of all
11954: declarable register symbols with @code{grep register engine.c}). If you
11955: give explicit registers to all variables that are declared at the
11956: beginning of @code{engine()}, you should be able to use the other
11957: caller-saved registers for temporary storage. Alternatively, you can use
11958: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
11959: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
11960: reserve a register (however, this restriction on register allocation may
11961: slow Gforth significantly).
1.44 crook 11962:
1.78 anton 11963: If this solution is not viable (e.g., because @code{gcc} does not allow
11964: you to explicitly declare all the registers you need), you have to find
11965: out by looking at the code where the inner interpreter's registers
11966: reside and which registers can be used for temporary storage. You can
11967: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 11968:
1.78 anton 11969: In any case, it is good practice to abstract your assembly code from the
11970: actual register allocation. E.g., if the data stack pointer resides in
11971: register @code{$17}, create an alias for this register called @code{sp},
11972: and use that in your assembly code.
1.21 crook 11973:
1.78 anton 11974: @cindex code words, portable
11975: Another option for implementing normal and defining words efficiently
11976: is to add the desired functionality to the source of Gforth. For normal
11977: words you just have to edit @file{primitives} (@pxref{Automatic
11978: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
11979: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
11980: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 11981:
1.78 anton 11982: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
11983: @subsection Common Assembler
1.44 crook 11984:
1.78 anton 11985: The assemblers in Gforth generally use a postfix syntax, i.e., the
11986: instruction name follows the operands.
1.21 crook 11987:
1.78 anton 11988: The operands are passed in the usual order (the same that is used in the
11989: manual of the architecture). Since they all are Forth words, they have
11990: to be separated by spaces; you can also use Forth words to compute the
11991: operands.
1.44 crook 11992:
1.78 anton 11993: The instruction names usually end with a @code{,}. This makes it easier
11994: to visually separate instructions if you put several of them on one
11995: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 11996:
1.78 anton 11997: Registers are usually specified by number; e.g., (decimal) @code{11}
11998: specifies registers R11 and F11 on the Alpha architecture (which one,
11999: depends on the instruction). The usual names are also available, e.g.,
12000: @code{s2} for R11 on Alpha.
1.21 crook 12001:
1.78 anton 12002: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12003: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12004: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12005: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12006: conditions are specified in a way specific to each assembler.
1.1 anton 12007:
1.78 anton 12008: Note that the register assignments of the Gforth engine can change
12009: between Gforth versions, or even between different compilations of the
12010: same Gforth version (e.g., if you use a different GCC version). So if
12011: you want to refer to Gforth's registers (e.g., the stack pointer or
12012: TOS), I recommend defining your own words for refering to these
12013: registers, and using them later on; then you can easily adapt to a
12014: changed register assignment. The stability of the register assignment
12015: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12016:
1.100 anton 12017: The most common use of these registers is to dispatch to the next word
12018: (the @code{next} routine). A portable way to do this is to jump to
12019: @code{' noop >code-address} (of course, this is less efficient than
12020: integrating the @code{next} code and scheduling it well).
1.1 anton 12021:
1.96 anton 12022: Another difference between Gforth version is that the top of stack is
12023: kept in memory in @code{gforth} and, on most platforms, in a register in
12024: @code{gforth-fast}.
12025:
1.78 anton 12026: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12027: @subsection Common Disassembler
1.127 anton 12028: @cindex disassembler, general
12029: @cindex gdb disassembler
1.1 anton 12030:
1.78 anton 12031: You can disassemble a @code{code} word with @code{see}
12032: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12033:
1.127 anton 12034: doc-discode
1.44 crook 12035:
1.127 anton 12036: There are two kinds of disassembler for Gforth: The Forth disassembler
12037: (available on some CPUs) and the gdb disassembler (available on
12038: platforms with @command{gdb} and @command{mktemp}). If both are
12039: available, the Forth disassembler is used by default. If you prefer
12040: the gdb disassembler, say
12041:
12042: @example
12043: ' disasm-gdb is discode
12044: @end example
12045:
12046: If neither is available, @code{discode} performs @code{dump}.
12047:
12048: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12049: assembler (i.e., same syntax, etc.). It also includes additional
12050: information in comments. In particular, the address of the instruction
12051: is given in a comment before the instruction.
1.1 anton 12052:
1.127 anton 12053: The gdb disassembler produces output in the same format as the gdb
12054: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12055: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12056: the 386 and AMD64 architectures).
12057:
1.78 anton 12058: @code{See} may display more or less than the actual code of the word,
12059: because the recognition of the end of the code is unreliable. You can
1.127 anton 12060: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12061: the code word is not immediately followed by a named word. If you have
1.116 anton 12062: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12063: to ensure that the end is recognized.
1.21 crook 12064:
1.78 anton 12065: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12066: @subsection 386 Assembler
1.44 crook 12067:
1.78 anton 12068: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12069: available under GPL, and originally part of bigFORTH.
1.21 crook 12070:
1.78 anton 12071: The 386 disassembler included in Gforth was written by Andrew McKewan
12072: and is in the public domain.
1.21 crook 12073:
1.91 anton 12074: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12075:
1.78 anton 12076: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12077:
1.78 anton 12078: The assembler includes all instruction of the Athlon, i.e. 486 core
12079: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12080: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12081: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12082:
1.78 anton 12083: There are several prefixes to switch between different operation sizes,
12084: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12085: double-word accesses. Addressing modes can be switched with @code{.wa}
12086: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12087: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12088:
1.78 anton 12089: For floating point operations, the prefixes are @code{.fs} (IEEE
12090: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12091: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12092:
1.78 anton 12093: The MMX opcodes don't have size prefixes, they are spelled out like in
12094: the Intel assembler. Instead of move from and to memory, there are
12095: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12096:
1.78 anton 12097: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12098: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12099: e.g., @code{3 #}. Here are some examples of addressing modes in various
12100: syntaxes:
1.21 crook 12101:
1.26 crook 12102: @example
1.91 anton 12103: Gforth Intel (NASM) AT&T (gas) Name
12104: .w ax ax %ax register (16 bit)
12105: ax eax %eax register (32 bit)
12106: 3 # offset 3 $3 immediate
12107: 1000 #) byte ptr 1000 1000 displacement
12108: bx ) [ebx] (%ebx) base
12109: 100 di d) 100[edi] 100(%edi) base+displacement
12110: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12111: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12112: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12113: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12114: @end example
12115:
12116: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12117: @code{DI)} to enforce 32-bit displacement fields (useful for
12118: later patching).
1.21 crook 12119:
1.78 anton 12120: Some example of instructions are:
1.1 anton 12121:
12122: @example
1.78 anton 12123: ax bx mov \ move ebx,eax
12124: 3 # ax mov \ mov eax,3
1.137 pazsan 12125: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12126: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12127: .w ax bx mov \ mov bx,ax
1.1 anton 12128: @end example
12129:
1.78 anton 12130: The following forms are supported for binary instructions:
1.1 anton 12131:
12132: @example
1.78 anton 12133: <reg> <reg> <inst>
12134: <n> # <reg> <inst>
12135: <mem> <reg> <inst>
12136: <reg> <mem> <inst>
1.136 pazsan 12137: <n> # <mem> <inst>
1.1 anton 12138: @end example
12139:
1.136 pazsan 12140: The shift/rotate syntax is:
1.1 anton 12141:
1.26 crook 12142: @example
1.78 anton 12143: <reg/mem> 1 # shl \ shortens to shift without immediate
12144: <reg/mem> 4 # shl
12145: <reg/mem> cl shl
1.26 crook 12146: @end example
1.1 anton 12147:
1.78 anton 12148: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12149: the byte version.
1.1 anton 12150:
1.78 anton 12151: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12152: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12153: pc < >= <= >}. (Note that most of these words shadow some Forth words
12154: when @code{assembler} is in front of @code{forth} in the search path,
12155: e.g., in @code{code} words). Currently the control structure words use
12156: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12157: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12158:
1.78 anton 12159: Here is an example of a @code{code} word (assumes that the stack pointer
12160: is in esi and the TOS is in ebx):
1.21 crook 12161:
1.26 crook 12162: @example
1.78 anton 12163: code my+ ( n1 n2 -- n )
12164: 4 si D) bx add
12165: 4 # si add
12166: Next
12167: end-code
1.26 crook 12168: @end example
1.21 crook 12169:
1.161 anton 12170:
1.78 anton 12171: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12172: @subsection Alpha Assembler
1.21 crook 12173:
1.78 anton 12174: The Alpha assembler and disassembler were originally written by Bernd
12175: Thallner.
1.26 crook 12176:
1.78 anton 12177: The register names @code{a0}--@code{a5} are not available to avoid
12178: shadowing hex numbers.
1.2 jwilke 12179:
1.78 anton 12180: Immediate forms of arithmetic instructions are distinguished by a
12181: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12182: does not count as arithmetic instruction).
1.2 jwilke 12183:
1.78 anton 12184: You have to specify all operands to an instruction, even those that
12185: other assemblers consider optional, e.g., the destination register for
12186: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12187:
1.78 anton 12188: You can specify conditions for @code{if,} by removing the first @code{b}
12189: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12190:
1.26 crook 12191: @example
1.78 anton 12192: 11 fgt if, \ if F11>0e
12193: ...
12194: endif,
1.26 crook 12195: @end example
1.2 jwilke 12196:
1.78 anton 12197: @code{fbgt,} gives @code{fgt}.
12198:
1.161 anton 12199: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12200: @subsection MIPS assembler
1.2 jwilke 12201:
1.78 anton 12202: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12203:
1.78 anton 12204: Currently the assembler and disassembler only cover the MIPS-I
12205: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12206:
1.78 anton 12207: The register names @code{$a0}--@code{$a3} are not available to avoid
12208: shadowing hex numbers.
1.2 jwilke 12209:
1.78 anton 12210: Because there is no way to distinguish registers from immediate values,
12211: you have to explicitly use the immediate forms of instructions, i.e.,
12212: @code{addiu,}, not just @code{addu,} (@command{as} does this
12213: implicitly).
1.2 jwilke 12214:
1.78 anton 12215: If the architecture manual specifies several formats for the instruction
12216: (e.g., for @code{jalr,}), you usually have to use the one with more
12217: arguments (i.e., two for @code{jalr,}). When in doubt, see
12218: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12219:
1.78 anton 12220: Branches and jumps in the MIPS architecture have a delay slot. You have
12221: to fill it yourself (the simplest way is to use @code{nop,}), the
12222: assembler does not do it for you (unlike @command{as}). Even
12223: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12224: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12225: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12226:
1.78 anton 12227: Note that you must not put branches, jumps, or @code{li,} into the delay
12228: slot: @code{li,} may expand to several instructions, and control flow
12229: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12230:
1.78 anton 12231: For branches the argument specifying the target is a relative address;
12232: You have to add the address of the delay slot to get the absolute
12233: address.
1.1 anton 12234:
1.78 anton 12235: The MIPS architecture also has load delay slots and restrictions on
12236: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12237: yourself to satisfy these restrictions, the assembler does not do it for
12238: you.
1.1 anton 12239:
1.78 anton 12240: You can specify the conditions for @code{if,} etc. by taking a
12241: conditional branch and leaving away the @code{b} at the start and the
12242: @code{,} at the end. E.g.,
1.1 anton 12243:
1.26 crook 12244: @example
1.78 anton 12245: 4 5 eq if,
12246: ... \ do something if $4 equals $5
12247: then,
1.26 crook 12248: @end example
1.1 anton 12249:
1.161 anton 12250:
12251: @node PowerPC assembler, Other assemblers, MIPS assembler, Assembler and Code Words
12252: @subsection PowerPC assembler
12253:
1.162 ! anton 12254: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12255: Revucky.
12256:
1.162 ! anton 12257: This assembler does not follow the convention of ending mnemonic names
! 12258: with a ``,'', so some mnemonic names shadow regular Forth words (in
! 12259: particular: @code{and or xor fabs}); so if you want to use the Forth
! 12260: words, you have to make them visible first, e.g., with @code{also
! 12261: forth}.
! 12262:
1.161 anton 12263: Registers are referred to by their number, e.g., @code{9} means the
12264: integer register 9 or the FP register 9 (depending on the
12265: instruction).
12266:
12267: Because there is no way to distinguish registers from immediate values,
12268: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 ! anton 12269: @code{addi,}, not just @code{add,}.
1.161 anton 12270:
1.162 ! anton 12271: The assembler and disassembler usually support the most general form
1.161 anton 12272: of an instruction, but usually not the shorter forms (especially for
12273: branches).
12274:
12275:
12276:
12277: @node Other assemblers, , PowerPC assembler, Assembler and Code Words
1.78 anton 12278: @subsection Other assemblers
12279:
12280: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12281: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12282: an assembler already. If you are writing them from scratch, please use
12283: a similar syntax style as the one we use (i.e., postfix, commas at the
12284: end of the instruction names, @pxref{Common Assembler}); make the output
12285: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12286: similar to the style we used.
12287:
12288: Hints on implementation: The most important part is to have a good test
12289: suite that contains all instructions. Once you have that, the rest is
12290: easy. For actual coding you can take a look at
12291: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12292: the assembler and disassembler, avoiding redundancy and some potential
12293: bugs. You can also look at that file (and @pxref{Advanced does> usage
12294: example}) to get ideas how to factor a disassembler.
12295:
12296: Start with the disassembler, because it's easier to reuse data from the
12297: disassembler for the assembler than the other way round.
1.1 anton 12298:
1.78 anton 12299: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12300: how simple it can be.
1.1 anton 12301:
1.161 anton 12302:
12303:
12304:
1.78 anton 12305: @c -------------------------------------------------------------
12306: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12307: @section Threading Words
12308: @cindex threading words
1.1 anton 12309:
1.78 anton 12310: @cindex code address
12311: These words provide access to code addresses and other threading stuff
12312: in Gforth (and, possibly, other interpretive Forths). It more or less
12313: abstracts away the differences between direct and indirect threading
12314: (and, for direct threading, the machine dependences). However, at
12315: present this wordset is still incomplete. It is also pretty low-level;
12316: some day it will hopefully be made unnecessary by an internals wordset
12317: that abstracts implementation details away completely.
1.1 anton 12318:
1.78 anton 12319: The terminology used here stems from indirect threaded Forth systems; in
12320: such a system, the XT of a word is represented by the CFA (code field
12321: address) of a word; the CFA points to a cell that contains the code
12322: address. The code address is the address of some machine code that
12323: performs the run-time action of invoking the word (e.g., the
12324: @code{dovar:} routine pushes the address of the body of the word (a
12325: variable) on the stack
12326: ).
1.1 anton 12327:
1.78 anton 12328: @cindex code address
12329: @cindex code field address
12330: In an indirect threaded Forth, you can get the code address of @i{name}
12331: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12332: >code-address}, independent of the threading method.
1.1 anton 12333:
1.78 anton 12334: doc-threading-method
12335: doc->code-address
12336: doc-code-address!
1.1 anton 12337:
1.78 anton 12338: @cindex @code{does>}-handler
12339: @cindex @code{does>}-code
12340: For a word defined with @code{DOES>}, the code address usually points to
12341: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12342: routine (in Gforth on some platforms, it can also point to the dodoes
12343: routine itself). What you are typically interested in, though, is
12344: whether a word is a @code{DOES>}-defined word, and what Forth code it
12345: executes; @code{>does-code} tells you that.
1.1 anton 12346:
1.78 anton 12347: doc->does-code
1.1 anton 12348:
1.78 anton 12349: To create a @code{DOES>}-defined word with the following basic words,
12350: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12351: @code{/does-handler} aus behind you have to place your executable Forth
12352: code. Finally you have to create a word and modify its behaviour with
12353: @code{does-handler!}.
1.1 anton 12354:
1.78 anton 12355: doc-does-code!
12356: doc-does-handler!
12357: doc-/does-handler
1.1 anton 12358:
1.78 anton 12359: The code addresses produced by various defining words are produced by
12360: the following words:
1.1 anton 12361:
1.78 anton 12362: doc-docol:
12363: doc-docon:
12364: doc-dovar:
12365: doc-douser:
12366: doc-dodefer:
12367: doc-dofield:
1.1 anton 12368:
1.99 anton 12369: @cindex definer
12370: The following two words generalize @code{>code-address},
12371: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12372:
12373: doc->definer
12374: doc-definer!
12375:
1.26 crook 12376: @c -------------------------------------------------------------
1.78 anton 12377: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12378: @section Passing Commands to the Operating System
12379: @cindex operating system - passing commands
12380: @cindex shell commands
12381:
12382: Gforth allows you to pass an arbitrary string to the host operating
12383: system shell (if such a thing exists) for execution.
12384:
12385: doc-sh
12386: doc-system
12387: doc-$?
1.23 crook 12388: doc-getenv
1.44 crook 12389:
1.26 crook 12390: @c -------------------------------------------------------------
1.47 crook 12391: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12392: @section Keeping track of Time
12393: @cindex time-related words
12394:
12395: doc-ms
12396: doc-time&date
1.79 anton 12397: doc-utime
12398: doc-cputime
1.47 crook 12399:
12400:
12401: @c -------------------------------------------------------------
12402: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12403: @section Miscellaneous Words
12404: @cindex miscellaneous words
12405:
1.29 crook 12406: @comment TODO find homes for these
12407:
1.26 crook 12408: These section lists the ANS Forth words that are not documented
1.21 crook 12409: elsewhere in this manual. Ultimately, they all need proper homes.
12410:
1.68 anton 12411: doc-quit
1.44 crook 12412:
1.26 crook 12413: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12414: (@pxref{ANS conformance}):
1.21 crook 12415:
12416: @code{EDITOR}
12417: @code{EMIT?}
12418: @code{FORGET}
12419:
1.24 anton 12420: @c ******************************************************************
12421: @node Error messages, Tools, Words, Top
12422: @chapter Error messages
12423: @cindex error messages
12424: @cindex backtrace
12425:
12426: A typical Gforth error message looks like this:
12427:
12428: @example
1.86 anton 12429: in file included from \evaluated string/:-1
1.24 anton 12430: in file included from ./yyy.fs:1
12431: ./xxx.fs:4: Invalid memory address
1.134 anton 12432: >>>bar<<<
1.79 anton 12433: Backtrace:
1.25 anton 12434: $400E664C @@
12435: $400E6664 foo
1.24 anton 12436: @end example
12437:
12438: The message identifying the error is @code{Invalid memory address}. The
12439: error happened when text-interpreting line 4 of the file
12440: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
12441: word on the line where the error happened, is pointed out (with
1.134 anton 12442: @code{>>>} and @code{<<<}).
1.24 anton 12443:
12444: The file containing the error was included in line 1 of @file{./yyy.fs},
12445: and @file{yyy.fs} was included from a non-file (in this case, by giving
12446: @file{yyy.fs} as command-line parameter to Gforth).
12447:
12448: At the end of the error message you find a return stack dump that can be
12449: interpreted as a backtrace (possibly empty). On top you find the top of
12450: the return stack when the @code{throw} happened, and at the bottom you
12451: find the return stack entry just above the return stack of the topmost
12452: text interpreter.
12453:
12454: To the right of most return stack entries you see a guess for the word
12455: that pushed that return stack entry as its return address. This gives a
12456: backtrace. In our case we see that @code{bar} called @code{foo}, and
12457: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
12458: address} exception).
12459:
12460: Note that the backtrace is not perfect: We don't know which return stack
12461: entries are return addresses (so we may get false positives); and in
12462: some cases (e.g., for @code{abort"}) we cannot determine from the return
12463: address the word that pushed the return address, so for some return
12464: addresses you see no names in the return stack dump.
1.25 anton 12465:
12466: @cindex @code{catch} and backtraces
12467: The return stack dump represents the return stack at the time when a
12468: specific @code{throw} was executed. In programs that make use of
12469: @code{catch}, it is not necessarily clear which @code{throw} should be
12470: used for the return stack dump (e.g., consider one @code{throw} that
12471: indicates an error, which is caught, and during recovery another error
1.160 anton 12472: happens; which @code{throw} should be used for the stack dump?).
12473: Gforth presents the return stack dump for the first @code{throw} after
12474: the last executed (not returned-to) @code{catch} or @code{nothrow};
12475: this works well in the usual case. To get the right backtrace, you
12476: usually want to insert @code{nothrow} or @code{['] false catch drop}
12477: after a @code{catch} if the error is not rethrown.
1.25 anton 12478:
12479: @cindex @code{gforth-fast} and backtraces
12480: @cindex @code{gforth-fast}, difference from @code{gforth}
12481: @cindex backtraces with @code{gforth-fast}
12482: @cindex return stack dump with @code{gforth-fast}
1.79 anton 12483: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 12484: from primitives (e.g., invalid memory address, stack empty etc.);
12485: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 12486: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 12487: exception caused by a primitive in @code{gforth-fast}, you will
12488: typically see no return stack dump at all; however, if the exception is
12489: caught by @code{catch} (e.g., for restoring some state), and then
12490: @code{throw}n again, the return stack dump will be for the first such
12491: @code{throw}.
1.2 jwilke 12492:
1.5 anton 12493: @c ******************************************************************
1.24 anton 12494: @node Tools, ANS conformance, Error messages, Top
1.1 anton 12495: @chapter Tools
12496:
12497: @menu
12498: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 12499: * Stack depth changes:: Where does this stack item come from?
1.1 anton 12500: @end menu
12501:
12502: See also @ref{Emacs and Gforth}.
12503:
1.126 pazsan 12504: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 12505: @section @file{ans-report.fs}: Report the words used, sorted by wordset
12506: @cindex @file{ans-report.fs}
12507: @cindex report the words used in your program
12508: @cindex words used in your program
12509:
12510: If you want to label a Forth program as ANS Forth Program, you must
12511: document which wordsets the program uses; for extension wordsets, it is
12512: helpful to list the words the program requires from these wordsets
12513: (because Forth systems are allowed to provide only some words of them).
12514:
12515: The @file{ans-report.fs} tool makes it easy for you to determine which
12516: words from which wordset and which non-ANS words your application
12517: uses. You simply have to include @file{ans-report.fs} before loading the
12518: program you want to check. After loading your program, you can get the
12519: report with @code{print-ans-report}. A typical use is to run this as
12520: batch job like this:
12521: @example
12522: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
12523: @end example
12524:
12525: The output looks like this (for @file{compat/control.fs}):
12526: @example
12527: The program uses the following words
12528: from CORE :
12529: : POSTPONE THEN ; immediate ?dup IF 0=
12530: from BLOCK-EXT :
12531: \
12532: from FILE :
12533: (
12534: @end example
12535:
12536: @subsection Caveats
12537:
12538: Note that @file{ans-report.fs} just checks which words are used, not whether
12539: they are used in an ANS Forth conforming way!
12540:
12541: Some words are defined in several wordsets in the
12542: standard. @file{ans-report.fs} reports them for only one of the
12543: wordsets, and not necessarily the one you expect. It depends on usage
12544: which wordset is the right one to specify. E.g., if you only use the
12545: compilation semantics of @code{S"}, it is a Core word; if you also use
12546: its interpretation semantics, it is a File word.
1.124 anton 12547:
12548:
1.127 anton 12549: @node Stack depth changes, , ANS Report, Tools
1.124 anton 12550: @section Stack depth changes during interpretation
12551: @cindex @file{depth-changes.fs}
12552: @cindex depth changes during interpretation
12553: @cindex stack depth changes during interpretation
12554: @cindex items on the stack after interpretation
12555:
12556: Sometimes you notice that, after loading a file, there are items left
12557: on the stack. The tool @file{depth-changes.fs} helps you find out
12558: quickly where in the file these stack items are coming from.
12559:
12560: The simplest way of using @file{depth-changes.fs} is to include it
12561: before the file(s) you want to check, e.g.:
12562:
12563: @example
12564: gforth depth-changes.fs my-file.fs
12565: @end example
12566:
12567: This will compare the stack depths of the data and FP stack at every
12568: empty line (in interpretation state) against these depths at the last
12569: empty line (in interpretation state). If the depths are not equal,
12570: the position in the file and the stack contents are printed with
12571: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
12572: change has occured in the paragraph of non-empty lines before the
12573: indicated line. It is a good idea to leave an empty line at the end
12574: of the file, so the last paragraph is checked, too.
12575:
12576: Checking only at empty lines usually works well, but sometimes you
12577: have big blocks of non-empty lines (e.g., when building a big table),
12578: and you want to know where in this block the stack depth changed. You
12579: can check all interpreted lines with
12580:
12581: @example
12582: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
12583: @end example
12584:
12585: This checks the stack depth at every end-of-line. So the depth change
12586: occured in the line reported by the @code{~~} (not in the line
12587: before).
12588:
12589: Note that, while this offers better accuracy in indicating where the
12590: stack depth changes, it will often report many intentional stack depth
12591: changes (e.g., when an interpreted computation stretches across
12592: several lines). You can suppress the checking of some lines by
12593: putting backslashes at the end of these lines (not followed by white
12594: space), and using
12595:
12596: @example
12597: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
12598: @end example
1.1 anton 12599:
12600: @c ******************************************************************
1.65 anton 12601: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 12602: @chapter ANS conformance
12603: @cindex ANS conformance of Gforth
12604:
12605: To the best of our knowledge, Gforth is an
12606:
12607: ANS Forth System
12608: @itemize @bullet
12609: @item providing the Core Extensions word set
12610: @item providing the Block word set
12611: @item providing the Block Extensions word set
12612: @item providing the Double-Number word set
12613: @item providing the Double-Number Extensions word set
12614: @item providing the Exception word set
12615: @item providing the Exception Extensions word set
12616: @item providing the Facility word set
1.40 anton 12617: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 12618: @item providing the File Access word set
12619: @item providing the File Access Extensions word set
12620: @item providing the Floating-Point word set
12621: @item providing the Floating-Point Extensions word set
12622: @item providing the Locals word set
12623: @item providing the Locals Extensions word set
12624: @item providing the Memory-Allocation word set
12625: @item providing the Memory-Allocation Extensions word set (that one's easy)
12626: @item providing the Programming-Tools word set
12627: @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
12628: @item providing the Search-Order word set
12629: @item providing the Search-Order Extensions word set
12630: @item providing the String word set
12631: @item providing the String Extensions word set (another easy one)
12632: @end itemize
12633:
1.118 anton 12634: Gforth has the following environmental restrictions:
12635:
12636: @cindex environmental restrictions
12637: @itemize @bullet
12638: @item
12639: While processing the OS command line, if an exception is not caught,
12640: Gforth exits with a non-zero exit code instyead of performing QUIT.
12641:
12642: @item
12643: When an @code{throw} is performed after a @code{query}, Gforth does not
12644: allways restore the input source specification in effect at the
12645: corresponding catch.
12646:
12647: @end itemize
12648:
12649:
1.1 anton 12650: @cindex system documentation
12651: In addition, ANS Forth systems are required to document certain
12652: implementation choices. This chapter tries to meet these
12653: requirements. In many cases it gives a way to ask the system for the
12654: information instead of providing the information directly, in
12655: particular, if the information depends on the processor, the operating
12656: system or the installation options chosen, or if they are likely to
12657: change during the maintenance of Gforth.
12658:
12659: @comment The framework for the rest has been taken from pfe.
12660:
12661: @menu
12662: * The Core Words::
12663: * The optional Block word set::
12664: * The optional Double Number word set::
12665: * The optional Exception word set::
12666: * The optional Facility word set::
12667: * The optional File-Access word set::
12668: * The optional Floating-Point word set::
12669: * The optional Locals word set::
12670: * The optional Memory-Allocation word set::
12671: * The optional Programming-Tools word set::
12672: * The optional Search-Order word set::
12673: @end menu
12674:
12675:
12676: @c =====================================================================
12677: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
12678: @comment node-name, next, previous, up
12679: @section The Core Words
12680: @c =====================================================================
12681: @cindex core words, system documentation
12682: @cindex system documentation, core words
12683:
12684: @menu
12685: * core-idef:: Implementation Defined Options
12686: * core-ambcond:: Ambiguous Conditions
12687: * core-other:: Other System Documentation
12688: @end menu
12689:
12690: @c ---------------------------------------------------------------------
12691: @node core-idef, core-ambcond, The Core Words, The Core Words
12692: @subsection Implementation Defined Options
12693: @c ---------------------------------------------------------------------
12694: @cindex core words, implementation-defined options
12695: @cindex implementation-defined options, core words
12696:
12697:
12698: @table @i
12699: @item (Cell) aligned addresses:
12700: @cindex cell-aligned addresses
12701: @cindex aligned addresses
12702: processor-dependent. Gforth's alignment words perform natural alignment
12703: (e.g., an address aligned for a datum of size 8 is divisible by
12704: 8). Unaligned accesses usually result in a @code{-23 THROW}.
12705:
12706: @item @code{EMIT} and non-graphic characters:
12707: @cindex @code{EMIT} and non-graphic characters
12708: @cindex non-graphic characters and @code{EMIT}
12709: The character is output using the C library function (actually, macro)
12710: @code{putc}.
12711:
12712: @item character editing of @code{ACCEPT} and @code{EXPECT}:
12713: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
12714: @cindex editing in @code{ACCEPT} and @code{EXPECT}
12715: @cindex @code{ACCEPT}, editing
12716: @cindex @code{EXPECT}, editing
12717: This is modeled on the GNU readline library (@pxref{Readline
12718: Interaction, , Command Line Editing, readline, The GNU Readline
12719: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
12720: producing a full word completion every time you type it (instead of
1.28 crook 12721: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 12722:
12723: @item character set:
12724: @cindex character set
12725: The character set of your computer and display device. Gforth is
12726: 8-bit-clean (but some other component in your system may make trouble).
12727:
12728: @item Character-aligned address requirements:
12729: @cindex character-aligned address requirements
12730: installation-dependent. Currently a character is represented by a C
12731: @code{unsigned char}; in the future we might switch to @code{wchar_t}
12732: (Comments on that requested).
12733:
12734: @item character-set extensions and matching of names:
12735: @cindex character-set extensions and matching of names
1.26 crook 12736: @cindex case-sensitivity for name lookup
12737: @cindex name lookup, case-sensitivity
12738: @cindex locale and case-sensitivity
1.21 crook 12739: Any character except the ASCII NUL character can be used in a
1.1 anton 12740: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 12741: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 12742: function is probably influenced by the locale. E.g., the @code{C} locale
12743: does not know about accents and umlauts, so they are matched
12744: case-sensitively in that locale. For portability reasons it is best to
12745: write programs such that they work in the @code{C} locale. Then one can
12746: use libraries written by a Polish programmer (who might use words
12747: containing ISO Latin-2 encoded characters) and by a French programmer
12748: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
12749: funny results for some of the words (which ones, depends on the font you
12750: are using)). Also, the locale you prefer may not be available in other
12751: operating systems. Hopefully, Unicode will solve these problems one day.
12752:
12753: @item conditions under which control characters match a space delimiter:
12754: @cindex space delimiters
12755: @cindex control characters as delimiters
1.117 anton 12756: If @code{word} is called with the space character as a delimiter, all
1.1 anton 12757: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 12758: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 12759: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 12760: interpreter (aka text interpreter) by default, treats all white-space
12761: characters as delimiters.
12762:
1.26 crook 12763: @item format of the control-flow stack:
12764: @cindex control-flow stack, format
12765: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 12766: stack item in cells is given by the constant @code{cs-item-size}. At the
12767: time of this writing, an item consists of a (pointer to a) locals list
12768: (third), an address in the code (second), and a tag for identifying the
12769: item (TOS). The following tags are used: @code{defstart},
12770: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
12771: @code{scopestart}.
12772:
12773: @item conversion of digits > 35
12774: @cindex digits > 35
12775: The characters @code{[\]^_'} are the digits with the decimal value
12776: 36@minus{}41. There is no way to input many of the larger digits.
12777:
12778: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
12779: @cindex @code{EXPECT}, display after end of input
12780: @cindex @code{ACCEPT}, display after end of input
12781: The cursor is moved to the end of the entered string. If the input is
12782: terminated using the @kbd{Return} key, a space is typed.
12783:
12784: @item exception abort sequence of @code{ABORT"}:
12785: @cindex exception abort sequence of @code{ABORT"}
12786: @cindex @code{ABORT"}, exception abort sequence
12787: The error string is stored into the variable @code{"error} and a
12788: @code{-2 throw} is performed.
12789:
12790: @item input line terminator:
12791: @cindex input line terminator
12792: @cindex line terminator on input
1.26 crook 12793: @cindex newline character on input
1.1 anton 12794: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
12795: lines. One of these characters is typically produced when you type the
12796: @kbd{Enter} or @kbd{Return} key.
12797:
12798: @item maximum size of a counted string:
12799: @cindex maximum size of a counted string
12800: @cindex counted string, maximum size
12801: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 12802: on all platforms, but this may change.
1.1 anton 12803:
12804: @item maximum size of a parsed string:
12805: @cindex maximum size of a parsed string
12806: @cindex parsed string, maximum size
12807: Given by the constant @code{/line}. Currently 255 characters.
12808:
12809: @item maximum size of a definition name, in characters:
12810: @cindex maximum size of a definition name, in characters
12811: @cindex name, maximum length
1.113 anton 12812: MAXU/8
1.1 anton 12813:
12814: @item maximum string length for @code{ENVIRONMENT?}, in characters:
12815: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
12816: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 12817: MAXU/8
1.1 anton 12818:
12819: @item method of selecting the user input device:
12820: @cindex user input device, method of selecting
12821: The user input device is the standard input. There is currently no way to
12822: change it from within Gforth. However, the input can typically be
12823: redirected in the command line that starts Gforth.
12824:
12825: @item method of selecting the user output device:
12826: @cindex user output device, method of selecting
12827: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 12828: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
12829: output when the user output device is a terminal, otherwise the output
12830: is buffered.
1.1 anton 12831:
12832: @item methods of dictionary compilation:
12833: What are we expected to document here?
12834:
12835: @item number of bits in one address unit:
12836: @cindex number of bits in one address unit
12837: @cindex address unit, size in bits
12838: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 12839: platforms.
1.1 anton 12840:
12841: @item number representation and arithmetic:
12842: @cindex number representation and arithmetic
1.79 anton 12843: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 12844:
12845: @item ranges for integer types:
12846: @cindex ranges for integer types
12847: @cindex integer types, ranges
12848: Installation-dependent. Make environmental queries for @code{MAX-N},
12849: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
12850: unsigned (and positive) types is 0. The lower bound for signed types on
12851: two's complement and one's complement machines machines can be computed
12852: by adding 1 to the upper bound.
12853:
12854: @item read-only data space regions:
12855: @cindex read-only data space regions
12856: @cindex data-space, read-only regions
12857: The whole Forth data space is writable.
12858:
12859: @item size of buffer at @code{WORD}:
12860: @cindex size of buffer at @code{WORD}
12861: @cindex @code{WORD} buffer size
12862: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12863: shared with the pictured numeric output string. If overwriting
12864: @code{PAD} is acceptable, it is as large as the remaining dictionary
12865: space, although only as much can be sensibly used as fits in a counted
12866: string.
12867:
12868: @item size of one cell in address units:
12869: @cindex cell size
12870: @code{1 cells .}.
12871:
12872: @item size of one character in address units:
12873: @cindex char size
1.79 anton 12874: @code{1 chars .}. 1 on all current platforms.
1.1 anton 12875:
12876: @item size of the keyboard terminal buffer:
12877: @cindex size of the keyboard terminal buffer
12878: @cindex terminal buffer, size
12879: Varies. You can determine the size at a specific time using @code{lp@@
12880: tib - .}. It is shared with the locals stack and TIBs of files that
12881: include the current file. You can change the amount of space for TIBs
12882: and locals stack at Gforth startup with the command line option
12883: @code{-l}.
12884:
12885: @item size of the pictured numeric output buffer:
12886: @cindex size of the pictured numeric output buffer
12887: @cindex pictured numeric output buffer, size
12888: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
12889: shared with @code{WORD}.
12890:
12891: @item size of the scratch area returned by @code{PAD}:
12892: @cindex size of the scratch area returned by @code{PAD}
12893: @cindex @code{PAD} size
12894: The remainder of dictionary space. @code{unused pad here - - .}.
12895:
12896: @item system case-sensitivity characteristics:
12897: @cindex case-sensitivity characteristics
1.26 crook 12898: Dictionary searches are case-insensitive (except in
1.1 anton 12899: @code{TABLE}s). However, as explained above under @i{character-set
12900: extensions}, the matching for non-ASCII characters is determined by the
12901: locale you are using. In the default @code{C} locale all non-ASCII
12902: characters are matched case-sensitively.
12903:
12904: @item system prompt:
12905: @cindex system prompt
12906: @cindex prompt
12907: @code{ ok} in interpret state, @code{ compiled} in compile state.
12908:
12909: @item division rounding:
12910: @cindex division rounding
12911: installation dependent. @code{s" floored" environment? drop .}. We leave
12912: the choice to @code{gcc} (what to use for @code{/}) and to you (whether
12913: to use @code{fm/mod}, @code{sm/rem} or simply @code{/}).
12914:
12915: @item values of @code{STATE} when true:
12916: @cindex @code{STATE} values
12917: -1.
12918:
12919: @item values returned after arithmetic overflow:
12920: On two's complement machines, arithmetic is performed modulo
12921: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
12922: arithmetic (with appropriate mapping for signed types). Division by zero
12923: typically results in a @code{-55 throw} (Floating-point unidentified
1.80 anton 12924: fault) or @code{-10 throw} (divide by zero).
1.1 anton 12925:
12926: @item whether the current definition can be found after @t{DOES>}:
12927: @cindex @t{DOES>}, visibility of current definition
12928: No.
12929:
12930: @end table
12931:
12932: @c ---------------------------------------------------------------------
12933: @node core-ambcond, core-other, core-idef, The Core Words
12934: @subsection Ambiguous conditions
12935: @c ---------------------------------------------------------------------
12936: @cindex core words, ambiguous conditions
12937: @cindex ambiguous conditions, core words
12938:
12939: @table @i
12940:
12941: @item a name is neither a word nor a number:
12942: @cindex name not found
1.26 crook 12943: @cindex undefined word
1.80 anton 12944: @code{-13 throw} (Undefined word).
1.1 anton 12945:
12946: @item a definition name exceeds the maximum length allowed:
1.26 crook 12947: @cindex word name too long
1.1 anton 12948: @code{-19 throw} (Word name too long)
12949:
12950: @item addressing a region not inside the various data spaces of the forth system:
12951: @cindex Invalid memory address
1.32 anton 12952: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 12953: typically readable. Accessing other addresses gives results dependent on
12954: the operating system. On decent systems: @code{-9 throw} (Invalid memory
12955: address).
12956:
12957: @item argument type incompatible with parameter:
1.26 crook 12958: @cindex argument type mismatch
1.1 anton 12959: This is usually not caught. Some words perform checks, e.g., the control
12960: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
12961: mismatch).
12962:
12963: @item attempting to obtain the execution token of a word with undefined execution semantics:
12964: @cindex Interpreting a compile-only word, for @code{'} etc.
12965: @cindex execution token of words with undefined execution semantics
12966: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
12967: get an execution token for @code{compile-only-error} (which performs a
12968: @code{-14 throw} when executed).
12969:
12970: @item dividing by zero:
12971: @cindex dividing by zero
12972: @cindex floating point unidentified fault, integer division
1.80 anton 12973: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 12974: zero); on other systems, this typically results in a @code{-55 throw}
12975: (Floating-point unidentified fault).
1.1 anton 12976:
12977: @item insufficient data stack or return stack space:
12978: @cindex insufficient data stack or return stack space
12979: @cindex stack overflow
1.26 crook 12980: @cindex address alignment exception, stack overflow
1.1 anton 12981: @cindex Invalid memory address, stack overflow
12982: Depending on the operating system, the installation, and the invocation
12983: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 12984: it is not checked. If it is checked, you typically get a @code{-3 throw}
12985: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
12986: throw} (Invalid memory address) (depending on the platform and how you
12987: achieved the overflow) as soon as the overflow happens. If it is not
12988: checked, overflows typically result in mysterious illegal memory
12989: accesses, producing @code{-9 throw} (Invalid memory address) or
12990: @code{-23 throw} (Address alignment exception); they might also destroy
12991: the internal data structure of @code{ALLOCATE} and friends, resulting in
12992: various errors in these words.
1.1 anton 12993:
12994: @item insufficient space for loop control parameters:
12995: @cindex insufficient space for loop control parameters
1.80 anton 12996: Like other return stack overflows.
1.1 anton 12997:
12998: @item insufficient space in the dictionary:
12999: @cindex insufficient space in the dictionary
13000: @cindex dictionary overflow
1.12 anton 13001: If you try to allot (either directly with @code{allot}, or indirectly
13002: with @code{,}, @code{create} etc.) more memory than available in the
13003: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13004: to access memory beyond the end of the dictionary, the results are
13005: similar to stack overflows.
1.1 anton 13006:
13007: @item interpreting a word with undefined interpretation semantics:
13008: @cindex interpreting a word with undefined interpretation semantics
13009: @cindex Interpreting a compile-only word
13010: For some words, we have defined interpretation semantics. For the
13011: others: @code{-14 throw} (Interpreting a compile-only word).
13012:
13013: @item modifying the contents of the input buffer or a string literal:
13014: @cindex modifying the contents of the input buffer or a string literal
13015: These are located in writable memory and can be modified.
13016:
13017: @item overflow of the pictured numeric output string:
13018: @cindex overflow of the pictured numeric output string
13019: @cindex pictured numeric output string, overflow
1.24 anton 13020: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13021:
13022: @item parsed string overflow:
13023: @cindex parsed string overflow
13024: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13025:
13026: @item producing a result out of range:
13027: @cindex result out of range
13028: On two's complement machines, arithmetic is performed modulo
13029: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
13030: arithmetic (with appropriate mapping for signed types). Division by zero
1.24 anton 13031: typically results in a @code{-10 throw} (divide by zero) or @code{-55
13032: throw} (floating point unidentified fault). @code{convert} and
13033: @code{>number} currently overflow silently.
1.1 anton 13034:
13035: @item reading from an empty data or return stack:
13036: @cindex stack empty
13037: @cindex stack underflow
1.24 anton 13038: @cindex return stack underflow
1.1 anton 13039: The data stack is checked by the outer (aka text) interpreter after
13040: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13041: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13042: depending on operating system, installation, and invocation. If they are
13043: caught by a check, they typically result in @code{-4 throw} (Stack
13044: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13045: (Invalid memory address), depending on the platform and which stack
13046: underflows and by how much. Note that even if the system uses checking
13047: (through the MMU), your program may have to underflow by a significant
13048: number of stack items to trigger the reaction (the reason for this is
13049: that the MMU, and therefore the checking, works with a page-size
13050: granularity). If there is no checking, the symptoms resulting from an
13051: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13052: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13053: (Invalid memory address) and Illegal Instruction (typically @code{-260
13054: throw}).
1.1 anton 13055:
13056: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13057: @cindex unexpected end of the input buffer
13058: @cindex zero-length string as a name
13059: @cindex Attempt to use zero-length string as a name
13060: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13061: use zero-length string as a name). Words like @code{'} probably will not
13062: find what they search. Note that it is possible to create zero-length
13063: names with @code{nextname} (should it not?).
13064:
13065: @item @code{>IN} greater than input buffer:
13066: @cindex @code{>IN} greater than input buffer
13067: The next invocation of a parsing word returns a string with length 0.
13068:
13069: @item @code{RECURSE} appears after @code{DOES>}:
13070: @cindex @code{RECURSE} appears after @code{DOES>}
13071: Compiles a recursive call to the defining word, not to the defined word.
13072:
13073: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13074: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13075: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13076: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13077: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13078: the end of the file was reached), its source-id may be
13079: reused. Therefore, restoring an input source specification referencing a
13080: closed file may lead to unpredictable results instead of a @code{-12
13081: THROW}.
13082:
13083: In the future, Gforth may be able to restore input source specifications
13084: from other than the current input source.
13085:
13086: @item data space containing definitions gets de-allocated:
13087: @cindex data space containing definitions gets de-allocated
13088: Deallocation with @code{allot} is not checked. This typically results in
13089: memory access faults or execution of illegal instructions.
13090:
13091: @item data space read/write with incorrect alignment:
13092: @cindex data space read/write with incorrect alignment
13093: @cindex alignment faults
1.26 crook 13094: @cindex address alignment exception
1.1 anton 13095: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13096: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13097: alignment turned on, incorrect alignment results in a @code{-9 throw}
13098: (Invalid memory address). There are reportedly some processors with
1.12 anton 13099: alignment restrictions that do not report violations.
1.1 anton 13100:
13101: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13102: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13103: Like other alignment errors.
13104:
13105: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13106: Like other stack underflows.
13107:
13108: @item loop control parameters not available:
13109: @cindex loop control parameters not available
13110: Not checked. The counted loop words simply assume that the top of return
13111: stack items are loop control parameters and behave accordingly.
13112:
13113: @item most recent definition does not have a name (@code{IMMEDIATE}):
13114: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13115: @cindex last word was headerless
13116: @code{abort" last word was headerless"}.
13117:
13118: @item name not defined by @code{VALUE} used by @code{TO}:
13119: @cindex name not defined by @code{VALUE} used by @code{TO}
13120: @cindex @code{TO} on non-@code{VALUE}s
13121: @cindex Invalid name argument, @code{TO}
13122: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13123: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13124:
13125: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13126: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13127: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13128: @code{-13 throw} (Undefined word)
13129:
13130: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13131: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13132: Gforth behaves as if they were of the same type. I.e., you can predict
13133: the behaviour by interpreting all parameters as, e.g., signed.
13134:
13135: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13136: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13137: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13138: compilation semantics of @code{TO}.
13139:
13140: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13141: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13142: @cindex @code{WORD}, string overflow
13143: Not checked. The string will be ok, but the count will, of course,
13144: contain only the least significant bits of the length.
13145:
13146: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13147: @cindex @code{LSHIFT}, large shift counts
13148: @cindex @code{RSHIFT}, large shift counts
13149: Processor-dependent. Typical behaviours are returning 0 and using only
13150: the low bits of the shift count.
13151:
13152: @item word not defined via @code{CREATE}:
13153: @cindex @code{>BODY} of non-@code{CREATE}d words
13154: @code{>BODY} produces the PFA of the word no matter how it was defined.
13155:
13156: @cindex @code{DOES>} of non-@code{CREATE}d words
13157: @code{DOES>} changes the execution semantics of the last defined word no
13158: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13159: @code{CREATE , DOES>}.
13160:
13161: @item words improperly used outside @code{<#} and @code{#>}:
13162: Not checked. As usual, you can expect memory faults.
13163:
13164: @end table
13165:
13166:
13167: @c ---------------------------------------------------------------------
13168: @node core-other, , core-ambcond, The Core Words
13169: @subsection Other system documentation
13170: @c ---------------------------------------------------------------------
13171: @cindex other system documentation, core words
13172: @cindex core words, other system documentation
13173:
13174: @table @i
13175: @item nonstandard words using @code{PAD}:
13176: @cindex @code{PAD} use by nonstandard words
13177: None.
13178:
13179: @item operator's terminal facilities available:
13180: @cindex operator's terminal facilities available
1.80 anton 13181: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13182: and you can give commands to Gforth interactively. The actual facilities
13183: available depend on how you invoke Gforth.
13184:
13185: @item program data space available:
13186: @cindex program data space available
13187: @cindex data space available
13188: @code{UNUSED .} gives the remaining dictionary space. The total
13189: dictionary space can be specified with the @code{-m} switch
13190: (@pxref{Invoking Gforth}) when Gforth starts up.
13191:
13192: @item return stack space available:
13193: @cindex return stack space available
13194: You can compute the total return stack space in cells with
13195: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13196: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13197:
13198: @item stack space available:
13199: @cindex stack space available
13200: You can compute the total data stack space in cells with
13201: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13202: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13203:
13204: @item system dictionary space required, in address units:
13205: @cindex system dictionary space required, in address units
13206: Type @code{here forthstart - .} after startup. At the time of this
13207: writing, this gives 80080 (bytes) on a 32-bit system.
13208: @end table
13209:
13210:
13211: @c =====================================================================
13212: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13213: @section The optional Block word set
13214: @c =====================================================================
13215: @cindex system documentation, block words
13216: @cindex block words, system documentation
13217:
13218: @menu
13219: * block-idef:: Implementation Defined Options
13220: * block-ambcond:: Ambiguous Conditions
13221: * block-other:: Other System Documentation
13222: @end menu
13223:
13224:
13225: @c ---------------------------------------------------------------------
13226: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13227: @subsection Implementation Defined Options
13228: @c ---------------------------------------------------------------------
13229: @cindex implementation-defined options, block words
13230: @cindex block words, implementation-defined options
13231:
13232: @table @i
13233: @item the format for display by @code{LIST}:
13234: @cindex @code{LIST} display format
13235: First the screen number is displayed, then 16 lines of 64 characters,
13236: each line preceded by the line number.
13237:
13238: @item the length of a line affected by @code{\}:
13239: @cindex length of a line affected by @code{\}
13240: @cindex @code{\}, line length in blocks
13241: 64 characters.
13242: @end table
13243:
13244:
13245: @c ---------------------------------------------------------------------
13246: @node block-ambcond, block-other, block-idef, The optional Block word set
13247: @subsection Ambiguous conditions
13248: @c ---------------------------------------------------------------------
13249: @cindex block words, ambiguous conditions
13250: @cindex ambiguous conditions, block words
13251:
13252: @table @i
13253: @item correct block read was not possible:
13254: @cindex block read not possible
13255: Typically results in a @code{throw} of some OS-derived value (between
13256: -512 and -2048). If the blocks file was just not long enough, blanks are
13257: supplied for the missing portion.
13258:
13259: @item I/O exception in block transfer:
13260: @cindex I/O exception in block transfer
13261: @cindex block transfer, I/O exception
13262: Typically results in a @code{throw} of some OS-derived value (between
13263: -512 and -2048).
13264:
13265: @item invalid block number:
13266: @cindex invalid block number
13267: @cindex block number invalid
13268: @code{-35 throw} (Invalid block number)
13269:
13270: @item a program directly alters the contents of @code{BLK}:
13271: @cindex @code{BLK}, altering @code{BLK}
13272: The input stream is switched to that other block, at the same
13273: position. If the storing to @code{BLK} happens when interpreting
13274: non-block input, the system will get quite confused when the block ends.
13275:
13276: @item no current block buffer for @code{UPDATE}:
13277: @cindex @code{UPDATE}, no current block buffer
13278: @code{UPDATE} has no effect.
13279:
13280: @end table
13281:
13282: @c ---------------------------------------------------------------------
13283: @node block-other, , block-ambcond, The optional Block word set
13284: @subsection Other system documentation
13285: @c ---------------------------------------------------------------------
13286: @cindex other system documentation, block words
13287: @cindex block words, other system documentation
13288:
13289: @table @i
13290: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13291: No restrictions (yet).
13292:
13293: @item the number of blocks available for source and data:
13294: depends on your disk space.
13295:
13296: @end table
13297:
13298:
13299: @c =====================================================================
13300: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13301: @section The optional Double Number word set
13302: @c =====================================================================
13303: @cindex system documentation, double words
13304: @cindex double words, system documentation
13305:
13306: @menu
13307: * double-ambcond:: Ambiguous Conditions
13308: @end menu
13309:
13310:
13311: @c ---------------------------------------------------------------------
13312: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13313: @subsection Ambiguous conditions
13314: @c ---------------------------------------------------------------------
13315: @cindex double words, ambiguous conditions
13316: @cindex ambiguous conditions, double words
13317:
13318: @table @i
1.29 crook 13319: @item @i{d} outside of range of @i{n} in @code{D>S}:
13320: @cindex @code{D>S}, @i{d} out of range of @i{n}
13321: The least significant cell of @i{d} is produced.
1.1 anton 13322:
13323: @end table
13324:
13325:
13326: @c =====================================================================
13327: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13328: @section The optional Exception word set
13329: @c =====================================================================
13330: @cindex system documentation, exception words
13331: @cindex exception words, system documentation
13332:
13333: @menu
13334: * exception-idef:: Implementation Defined Options
13335: @end menu
13336:
13337:
13338: @c ---------------------------------------------------------------------
13339: @node exception-idef, , The optional Exception word set, The optional Exception word set
13340: @subsection Implementation Defined Options
13341: @c ---------------------------------------------------------------------
13342: @cindex implementation-defined options, exception words
13343: @cindex exception words, implementation-defined options
13344:
13345: @table @i
13346: @item @code{THROW}-codes used in the system:
13347: @cindex @code{THROW}-codes used in the system
13348: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13349: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13350: codes -512@minus{}-2047 are used for OS errors (for file and memory
13351: allocation operations). The mapping from OS error numbers to throw codes
13352: is -512@minus{}@code{errno}. One side effect of this mapping is that
13353: undefined OS errors produce a message with a strange number; e.g.,
13354: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13355: @end table
13356:
13357: @c =====================================================================
13358: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13359: @section The optional Facility word set
13360: @c =====================================================================
13361: @cindex system documentation, facility words
13362: @cindex facility words, system documentation
13363:
13364: @menu
13365: * facility-idef:: Implementation Defined Options
13366: * facility-ambcond:: Ambiguous Conditions
13367: @end menu
13368:
13369:
13370: @c ---------------------------------------------------------------------
13371: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13372: @subsection Implementation Defined Options
13373: @c ---------------------------------------------------------------------
13374: @cindex implementation-defined options, facility words
13375: @cindex facility words, implementation-defined options
13376:
13377: @table @i
13378: @item encoding of keyboard events (@code{EKEY}):
13379: @cindex keyboard events, encoding in @code{EKEY}
13380: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13381: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13382: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13383: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13384: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13385: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13386:
1.1 anton 13387:
13388: @item duration of a system clock tick:
13389: @cindex duration of a system clock tick
13390: @cindex clock tick duration
13391: System dependent. With respect to @code{MS}, the time is specified in
13392: microseconds. How well the OS and the hardware implement this, is
13393: another question.
13394:
13395: @item repeatability to be expected from the execution of @code{MS}:
13396: @cindex repeatability to be expected from the execution of @code{MS}
13397: @cindex @code{MS}, repeatability to be expected
13398: System dependent. On Unix, a lot depends on load. If the system is
13399: lightly loaded, and the delay is short enough that Gforth does not get
13400: swapped out, the performance should be acceptable. Under MS-DOS and
13401: other single-tasking systems, it should be good.
13402:
13403: @end table
13404:
13405:
13406: @c ---------------------------------------------------------------------
13407: @node facility-ambcond, , facility-idef, The optional Facility word set
13408: @subsection Ambiguous conditions
13409: @c ---------------------------------------------------------------------
13410: @cindex facility words, ambiguous conditions
13411: @cindex ambiguous conditions, facility words
13412:
13413: @table @i
13414: @item @code{AT-XY} can't be performed on user output device:
13415: @cindex @code{AT-XY} can't be performed on user output device
13416: Largely terminal dependent. No range checks are done on the arguments.
13417: No errors are reported. You may see some garbage appearing, you may see
13418: simply nothing happen.
13419:
13420: @end table
13421:
13422:
13423: @c =====================================================================
13424: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
13425: @section The optional File-Access word set
13426: @c =====================================================================
13427: @cindex system documentation, file words
13428: @cindex file words, system documentation
13429:
13430: @menu
13431: * file-idef:: Implementation Defined Options
13432: * file-ambcond:: Ambiguous Conditions
13433: @end menu
13434:
13435: @c ---------------------------------------------------------------------
13436: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
13437: @subsection Implementation Defined Options
13438: @c ---------------------------------------------------------------------
13439: @cindex implementation-defined options, file words
13440: @cindex file words, implementation-defined options
13441:
13442: @table @i
13443: @item file access methods used:
13444: @cindex file access methods used
13445: @code{R/O}, @code{R/W} and @code{BIN} work as you would
13446: expect. @code{W/O} translates into the C file opening mode @code{w} (or
13447: @code{wb}): The file is cleared, if it exists, and created, if it does
13448: not (with both @code{open-file} and @code{create-file}). Under Unix
13449: @code{create-file} creates a file with 666 permissions modified by your
13450: umask.
13451:
13452: @item file exceptions:
13453: @cindex file exceptions
13454: The file words do not raise exceptions (except, perhaps, memory access
13455: faults when you pass illegal addresses or file-ids).
13456:
13457: @item file line terminator:
13458: @cindex file line terminator
13459: System-dependent. Gforth uses C's newline character as line
13460: terminator. What the actual character code(s) of this are is
13461: system-dependent.
13462:
13463: @item file name format:
13464: @cindex file name format
13465: System dependent. Gforth just uses the file name format of your OS.
13466:
13467: @item information returned by @code{FILE-STATUS}:
13468: @cindex @code{FILE-STATUS}, returned information
13469: @code{FILE-STATUS} returns the most powerful file access mode allowed
13470: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
13471: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
13472: along with the returned mode.
13473:
13474: @item input file state after an exception when including source:
13475: @cindex exception when including source
13476: All files that are left via the exception are closed.
13477:
1.29 crook 13478: @item @i{ior} values and meaning:
13479: @cindex @i{ior} values and meaning
1.68 anton 13480: @cindex @i{wior} values and meaning
1.29 crook 13481: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13482: intended as throw codes. They typically are in the range
13483: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13484: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13485:
13486: @item maximum depth of file input nesting:
13487: @cindex maximum depth of file input nesting
13488: @cindex file input nesting, maximum depth
13489: limited by the amount of return stack, locals/TIB stack, and the number
13490: of open files available. This should not give you troubles.
13491:
13492: @item maximum size of input line:
13493: @cindex maximum size of input line
13494: @cindex input line size, maximum
13495: @code{/line}. Currently 255.
13496:
13497: @item methods of mapping block ranges to files:
13498: @cindex mapping block ranges to files
13499: @cindex files containing blocks
13500: @cindex blocks in files
13501: By default, blocks are accessed in the file @file{blocks.fb} in the
13502: current working directory. The file can be switched with @code{USE}.
13503:
13504: @item number of string buffers provided by @code{S"}:
13505: @cindex @code{S"}, number of string buffers
13506: 1
13507:
13508: @item size of string buffer used by @code{S"}:
13509: @cindex @code{S"}, size of string buffer
13510: @code{/line}. currently 255.
13511:
13512: @end table
13513:
13514: @c ---------------------------------------------------------------------
13515: @node file-ambcond, , file-idef, The optional File-Access word set
13516: @subsection Ambiguous conditions
13517: @c ---------------------------------------------------------------------
13518: @cindex file words, ambiguous conditions
13519: @cindex ambiguous conditions, file words
13520:
13521: @table @i
13522: @item attempting to position a file outside its boundaries:
13523: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
13524: @code{REPOSITION-FILE} is performed as usual: Afterwards,
13525: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
13526:
13527: @item attempting to read from file positions not yet written:
13528: @cindex reading from file positions not yet written
13529: End-of-file, i.e., zero characters are read and no error is reported.
13530:
1.29 crook 13531: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
13532: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 13533: An appropriate exception may be thrown, but a memory fault or other
13534: problem is more probable.
13535:
1.29 crook 13536: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
13537: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
13538: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
13539: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 13540: thrown.
13541:
13542: @item named file cannot be opened (@code{INCLUDED}):
13543: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 13544: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 13545:
13546: @item requesting an unmapped block number:
13547: @cindex unmapped block numbers
13548: There are no unmapped legal block numbers. On some operating systems,
13549: writing a block with a large number may overflow the file system and
13550: have an error message as consequence.
13551:
13552: @item using @code{source-id} when @code{blk} is non-zero:
13553: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
13554: @code{source-id} performs its function. Typically it will give the id of
13555: the source which loaded the block. (Better ideas?)
13556:
13557: @end table
13558:
13559:
13560: @c =====================================================================
13561: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
13562: @section The optional Floating-Point word set
13563: @c =====================================================================
13564: @cindex system documentation, floating-point words
13565: @cindex floating-point words, system documentation
13566:
13567: @menu
13568: * floating-idef:: Implementation Defined Options
13569: * floating-ambcond:: Ambiguous Conditions
13570: @end menu
13571:
13572:
13573: @c ---------------------------------------------------------------------
13574: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
13575: @subsection Implementation Defined Options
13576: @c ---------------------------------------------------------------------
13577: @cindex implementation-defined options, floating-point words
13578: @cindex floating-point words, implementation-defined options
13579:
13580: @table @i
13581: @item format and range of floating point numbers:
13582: @cindex format and range of floating point numbers
13583: @cindex floating point numbers, format and range
13584: System-dependent; the @code{double} type of C.
13585:
1.29 crook 13586: @item results of @code{REPRESENT} when @i{float} is out of range:
13587: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 13588: System dependent; @code{REPRESENT} is implemented using the C library
13589: function @code{ecvt()} and inherits its behaviour in this respect.
13590:
13591: @item rounding or truncation of floating-point numbers:
13592: @cindex rounding of floating-point numbers
13593: @cindex truncation of floating-point numbers
13594: @cindex floating-point numbers, rounding or truncation
13595: System dependent; the rounding behaviour is inherited from the hosting C
13596: compiler. IEEE-FP-based (i.e., most) systems by default round to
13597: nearest, and break ties by rounding to even (i.e., such that the last
13598: bit of the mantissa is 0).
13599:
13600: @item size of floating-point stack:
13601: @cindex floating-point stack size
13602: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
13603: the floating-point stack (in floats). You can specify this on startup
13604: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
13605:
13606: @item width of floating-point stack:
13607: @cindex floating-point stack width
13608: @code{1 floats}.
13609:
13610: @end table
13611:
13612:
13613: @c ---------------------------------------------------------------------
13614: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
13615: @subsection Ambiguous conditions
13616: @c ---------------------------------------------------------------------
13617: @cindex floating-point words, ambiguous conditions
13618: @cindex ambiguous conditions, floating-point words
13619:
13620: @table @i
13621: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
13622: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
13623: System-dependent. Typically results in a @code{-23 THROW} like other
13624: alignment violations.
13625:
13626: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
13627: @cindex @code{f@@} used with an address that is not float aligned
13628: @cindex @code{f!} used with an address that is not float aligned
13629: System-dependent. Typically results in a @code{-23 THROW} like other
13630: alignment violations.
13631:
13632: @item floating-point result out of range:
13633: @cindex floating-point result out of range
1.80 anton 13634: System-dependent. Can result in a @code{-43 throw} (floating point
13635: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
13636: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 13637: unidentified fault), or can produce a special value representing, e.g.,
13638: Infinity.
13639:
13640: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
13641: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
13642: System-dependent. Typically results in an alignment fault like other
13643: alignment violations.
13644:
1.35 anton 13645: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
13646: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 13647: The floating-point number is converted into decimal nonetheless.
13648:
13649: @item Both arguments are equal to zero (@code{FATAN2}):
13650: @cindex @code{FATAN2}, both arguments are equal to zero
13651: System-dependent. @code{FATAN2} is implemented using the C library
13652: function @code{atan2()}.
13653:
1.29 crook 13654: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
13655: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
13656: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 13657: because of small errors and the tan will be a very large (or very small)
13658: but finite number.
13659:
1.29 crook 13660: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
13661: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 13662: The result is rounded to the nearest float.
13663:
13664: @item dividing by zero:
13665: @cindex dividing by zero, floating-point
13666: @cindex floating-point dividing by zero
13667: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 13668: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
13669: (floating point divide by zero) or @code{-55 throw} (Floating-point
13670: unidentified fault).
1.1 anton 13671:
13672: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
13673: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
13674: System dependent. On IEEE-FP based systems the number is converted into
13675: an infinity.
13676:
1.29 crook 13677: @item @i{float}<1 (@code{FACOSH}):
13678: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 13679: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 13680: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 13681:
1.29 crook 13682: @item @i{float}=<-1 (@code{FLNP1}):
13683: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 13684: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 13685: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13686: negative infinity for @i{float}=-1).
1.1 anton 13687:
1.29 crook 13688: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
13689: @cindex @code{FLN}, @i{float}=<0
13690: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 13691: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 13692: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
13693: negative infinity for @i{float}=0).
1.1 anton 13694:
1.29 crook 13695: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
13696: @cindex @code{FASINH}, @i{float}<0
13697: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 13698: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 13699: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
13700: @code{fasinh} some platforms produce a NaN, others a number (bug in the
13701: C library?).
1.1 anton 13702:
1.29 crook 13703: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
13704: @cindex @code{FACOS}, |@i{float}|>1
13705: @cindex @code{FASIN}, |@i{float}|>1
13706: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 13707: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 13708: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 13709:
1.29 crook 13710: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
13711: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 13712: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 13713: Platform-dependent; typically, some double number is produced and no
13714: error is reported.
1.1 anton 13715:
13716: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
13717: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 13718: @code{Precision} characters of the numeric output area are used. If
13719: @code{precision} is too high, these words will smash the data or code
13720: close to @code{here}.
1.1 anton 13721: @end table
13722:
13723: @c =====================================================================
13724: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
13725: @section The optional Locals word set
13726: @c =====================================================================
13727: @cindex system documentation, locals words
13728: @cindex locals words, system documentation
13729:
13730: @menu
13731: * locals-idef:: Implementation Defined Options
13732: * locals-ambcond:: Ambiguous Conditions
13733: @end menu
13734:
13735:
13736: @c ---------------------------------------------------------------------
13737: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
13738: @subsection Implementation Defined Options
13739: @c ---------------------------------------------------------------------
13740: @cindex implementation-defined options, locals words
13741: @cindex locals words, implementation-defined options
13742:
13743: @table @i
13744: @item maximum number of locals in a definition:
13745: @cindex maximum number of locals in a definition
13746: @cindex locals, maximum number in a definition
13747: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
13748: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
13749: characters. The number of locals in a definition is bounded by the size
13750: of locals-buffer, which contains the names of the locals.
13751:
13752: @end table
13753:
13754:
13755: @c ---------------------------------------------------------------------
13756: @node locals-ambcond, , locals-idef, The optional Locals word set
13757: @subsection Ambiguous conditions
13758: @c ---------------------------------------------------------------------
13759: @cindex locals words, ambiguous conditions
13760: @cindex ambiguous conditions, locals words
13761:
13762: @table @i
13763: @item executing a named local in interpretation state:
13764: @cindex local in interpretation state
13765: @cindex Interpreting a compile-only word, for a local
13766: Locals have no interpretation semantics. If you try to perform the
13767: interpretation semantics, you will get a @code{-14 throw} somewhere
13768: (Interpreting a compile-only word). If you perform the compilation
13769: semantics, the locals access will be compiled (irrespective of state).
13770:
1.29 crook 13771: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 13772: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
13773: @cindex @code{TO} on non-@code{VALUE}s and non-locals
13774: @cindex Invalid name argument, @code{TO}
13775: @code{-32 throw} (Invalid name argument)
13776:
13777: @end table
13778:
13779:
13780: @c =====================================================================
13781: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
13782: @section The optional Memory-Allocation word set
13783: @c =====================================================================
13784: @cindex system documentation, memory-allocation words
13785: @cindex memory-allocation words, system documentation
13786:
13787: @menu
13788: * memory-idef:: Implementation Defined Options
13789: @end menu
13790:
13791:
13792: @c ---------------------------------------------------------------------
13793: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
13794: @subsection Implementation Defined Options
13795: @c ---------------------------------------------------------------------
13796: @cindex implementation-defined options, memory-allocation words
13797: @cindex memory-allocation words, implementation-defined options
13798:
13799: @table @i
1.29 crook 13800: @item values and meaning of @i{ior}:
13801: @cindex @i{ior} values and meaning
13802: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 13803: intended as throw codes. They typically are in the range
13804: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 13805: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 13806:
13807: @end table
13808:
13809: @c =====================================================================
13810: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
13811: @section The optional Programming-Tools word set
13812: @c =====================================================================
13813: @cindex system documentation, programming-tools words
13814: @cindex programming-tools words, system documentation
13815:
13816: @menu
13817: * programming-idef:: Implementation Defined Options
13818: * programming-ambcond:: Ambiguous Conditions
13819: @end menu
13820:
13821:
13822: @c ---------------------------------------------------------------------
13823: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
13824: @subsection Implementation Defined Options
13825: @c ---------------------------------------------------------------------
13826: @cindex implementation-defined options, programming-tools words
13827: @cindex programming-tools words, implementation-defined options
13828:
13829: @table @i
13830: @item ending sequence for input following @code{;CODE} and @code{CODE}:
13831: @cindex @code{;CODE} ending sequence
13832: @cindex @code{CODE} ending sequence
13833: @code{END-CODE}
13834:
13835: @item manner of processing input following @code{;CODE} and @code{CODE}:
13836: @cindex @code{;CODE}, processing input
13837: @cindex @code{CODE}, processing input
13838: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
13839: the input is processed by the text interpreter, (starting) in interpret
13840: state.
13841:
13842: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
13843: @cindex @code{ASSEMBLER}, search order capability
13844: The ANS Forth search order word set.
13845:
13846: @item source and format of display by @code{SEE}:
13847: @cindex @code{SEE}, source and format of output
1.80 anton 13848: The source for @code{see} is the executable code used by the inner
1.1 anton 13849: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 13850: (and on some platforms, assembly code for primitives) as well as
13851: possible.
1.1 anton 13852:
13853: @end table
13854:
13855: @c ---------------------------------------------------------------------
13856: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
13857: @subsection Ambiguous conditions
13858: @c ---------------------------------------------------------------------
13859: @cindex programming-tools words, ambiguous conditions
13860: @cindex ambiguous conditions, programming-tools words
13861:
13862: @table @i
13863:
1.21 crook 13864: @item deleting the compilation word list (@code{FORGET}):
13865: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 13866: Not implemented (yet).
13867:
1.29 crook 13868: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
13869: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
13870: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 13871: @cindex control-flow stack underflow
13872: This typically results in an @code{abort"} with a descriptive error
13873: message (may change into a @code{-22 throw} (Control structure mismatch)
13874: in the future). You may also get a memory access error. If you are
13875: unlucky, this ambiguous condition is not caught.
13876:
1.29 crook 13877: @item @i{name} can't be found (@code{FORGET}):
13878: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 13879: Not implemented (yet).
13880:
1.29 crook 13881: @item @i{name} not defined via @code{CREATE}:
13882: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 13883: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
13884: the execution semantics of the last defined word no matter how it was
13885: defined.
13886:
13887: @item @code{POSTPONE} applied to @code{[IF]}:
13888: @cindex @code{POSTPONE} applied to @code{[IF]}
13889: @cindex @code{[IF]} and @code{POSTPONE}
13890: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
13891: equivalent to @code{[IF]}.
13892:
13893: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
13894: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
13895: Continue in the same state of conditional compilation in the next outer
13896: input source. Currently there is no warning to the user about this.
13897:
13898: @item removing a needed definition (@code{FORGET}):
13899: @cindex @code{FORGET}, removing a needed definition
13900: Not implemented (yet).
13901:
13902: @end table
13903:
13904:
13905: @c =====================================================================
13906: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
13907: @section The optional Search-Order word set
13908: @c =====================================================================
13909: @cindex system documentation, search-order words
13910: @cindex search-order words, system documentation
13911:
13912: @menu
13913: * search-idef:: Implementation Defined Options
13914: * search-ambcond:: Ambiguous Conditions
13915: @end menu
13916:
13917:
13918: @c ---------------------------------------------------------------------
13919: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
13920: @subsection Implementation Defined Options
13921: @c ---------------------------------------------------------------------
13922: @cindex implementation-defined options, search-order words
13923: @cindex search-order words, implementation-defined options
13924:
13925: @table @i
13926: @item maximum number of word lists in search order:
13927: @cindex maximum number of word lists in search order
13928: @cindex search order, maximum depth
13929: @code{s" wordlists" environment? drop .}. Currently 16.
13930:
13931: @item minimum search order:
13932: @cindex minimum search order
13933: @cindex search order, minimum
13934: @code{root root}.
13935:
13936: @end table
13937:
13938: @c ---------------------------------------------------------------------
13939: @node search-ambcond, , search-idef, The optional Search-Order word set
13940: @subsection Ambiguous conditions
13941: @c ---------------------------------------------------------------------
13942: @cindex search-order words, ambiguous conditions
13943: @cindex ambiguous conditions, search-order words
13944:
13945: @table @i
1.21 crook 13946: @item changing the compilation word list (during compilation):
13947: @cindex changing the compilation word list (during compilation)
13948: @cindex compilation word list, change before definition ends
13949: The word is entered into the word list that was the compilation word list
1.1 anton 13950: at the start of the definition. Any changes to the name field (e.g.,
13951: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 13952: are applied to the latest defined word (as reported by @code{latest} or
13953: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 13954:
13955: @item search order empty (@code{previous}):
13956: @cindex @code{previous}, search order empty
1.26 crook 13957: @cindex vocstack empty, @code{previous}
1.1 anton 13958: @code{abort" Vocstack empty"}.
13959:
13960: @item too many word lists in search order (@code{also}):
13961: @cindex @code{also}, too many word lists in search order
1.26 crook 13962: @cindex vocstack full, @code{also}
1.1 anton 13963: @code{abort" Vocstack full"}.
13964:
13965: @end table
13966:
13967: @c ***************************************************************
1.65 anton 13968: @node Standard vs Extensions, Model, ANS conformance, Top
13969: @chapter Should I use Gforth extensions?
13970: @cindex Gforth extensions
13971:
13972: As you read through the rest of this manual, you will see documentation
13973: for @i{Standard} words, and documentation for some appealing Gforth
13974: @i{extensions}. You might ask yourself the question: @i{``Should I
13975: restrict myself to the standard, or should I use the extensions?''}
13976:
13977: The answer depends on the goals you have for the program you are working
13978: on:
13979:
13980: @itemize @bullet
13981:
13982: @item Is it just for yourself or do you want to share it with others?
13983:
13984: @item
13985: If you want to share it, do the others all use Gforth?
13986:
13987: @item
13988: If it is just for yourself, do you want to restrict yourself to Gforth?
13989:
13990: @end itemize
13991:
13992: If restricting the program to Gforth is ok, then there is no reason not
13993: to use extensions. It is still a good idea to keep to the standard
13994: where it is easy, in case you want to reuse these parts in another
13995: program that you want to be portable.
13996:
13997: If you want to be able to port the program to other Forth systems, there
13998: are the following points to consider:
13999:
14000: @itemize @bullet
14001:
14002: @item
14003: Most Forth systems that are being maintained support the ANS Forth
14004: standard. So if your program complies with the standard, it will be
14005: portable among many systems.
14006:
14007: @item
14008: A number of the Gforth extensions can be implemented in ANS Forth using
14009: public-domain files provided in the @file{compat/} directory. These are
14010: mentioned in the text in passing. There is no reason not to use these
14011: extensions, your program will still be ANS Forth compliant; just include
14012: the appropriate compat files with your program.
14013:
14014: @item
14015: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14016: analyse your program and determine what non-Standard words it relies
14017: upon. However, it does not check whether you use standard words in a
14018: non-standard way.
14019:
14020: @item
14021: Some techniques are not standardized by ANS Forth, and are hard or
14022: impossible to implement in a standard way, but can be implemented in
14023: most Forth systems easily, and usually in similar ways (e.g., accessing
14024: word headers). Forth has a rich historical precedent for programmers
14025: taking advantage of implementation-dependent features of their tools
14026: (for example, relying on a knowledge of the dictionary
14027: structure). Sometimes these techniques are necessary to extract every
14028: last bit of performance from the hardware, sometimes they are just a
14029: programming shorthand.
14030:
14031: @item
14032: Does using a Gforth extension save more work than the porting this part
14033: to other Forth systems (if any) will cost?
14034:
14035: @item
14036: Is the additional functionality worth the reduction in portability and
14037: the additional porting problems?
14038:
14039: @end itemize
14040:
14041: In order to perform these consideratios, you need to know what's
14042: standard and what's not. This manual generally states if something is
1.81 anton 14043: non-standard, but the authoritative source is the
14044: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14045: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14046: into the thought processes of the technical committee.
14047:
14048: Note also that portability between Forth systems is not the only
14049: portability issue; there is also the issue of portability between
14050: different platforms (processor/OS combinations).
14051:
14052: @c ***************************************************************
14053: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14054: @chapter Model
14055:
14056: This chapter has yet to be written. It will contain information, on
14057: which internal structures you can rely.
14058:
14059: @c ***************************************************************
14060: @node Integrating Gforth, Emacs and Gforth, Model, Top
14061: @chapter Integrating Gforth into C programs
14062:
14063: This is not yet implemented.
14064:
14065: Several people like to use Forth as scripting language for applications
14066: that are otherwise written in C, C++, or some other language.
14067:
14068: The Forth system ATLAST provides facilities for embedding it into
14069: applications; unfortunately it has several disadvantages: most
14070: importantly, it is not based on ANS Forth, and it is apparently dead
14071: (i.e., not developed further and not supported). The facilities
1.21 crook 14072: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14073: making the switch should not be hard.
14074:
14075: We also tried to design the interface such that it can easily be
14076: implemented by other Forth systems, so that we may one day arrive at a
14077: standardized interface. Such a standard interface would allow you to
14078: replace the Forth system without having to rewrite C code.
14079:
14080: You embed the Gforth interpreter by linking with the library
14081: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14082: global symbols in this library that belong to the interface, have the
14083: prefix @code{forth_}. (Global symbols that are used internally have the
14084: prefix @code{gforth_}).
14085:
14086: You can include the declarations of Forth types and the functions and
14087: variables of the interface with @code{#include <forth.h>}.
14088:
14089: Types.
14090:
14091: Variables.
14092:
14093: Data and FP Stack pointer. Area sizes.
14094:
14095: functions.
14096:
14097: forth_init(imagefile)
14098: forth_evaluate(string) exceptions?
14099: forth_goto(address) (or forth_execute(xt)?)
14100: forth_continue() (a corountining mechanism)
14101:
14102: Adding primitives.
14103:
14104: No checking.
14105:
14106: Signals?
14107:
14108: Accessing the Stacks
14109:
1.26 crook 14110: @c ******************************************************************
1.1 anton 14111: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14112: @chapter Emacs and Gforth
14113: @cindex Emacs and Gforth
14114:
14115: @cindex @file{gforth.el}
14116: @cindex @file{forth.el}
14117: @cindex Rydqvist, Goran
1.107 dvdkhlng 14118: @cindex Kuehling, David
1.1 anton 14119: @cindex comment editing commands
14120: @cindex @code{\}, editing with Emacs
14121: @cindex debug tracer editing commands
14122: @cindex @code{~~}, removal with Emacs
14123: @cindex Forth mode in Emacs
1.107 dvdkhlng 14124:
1.1 anton 14125: Gforth comes with @file{gforth.el}, an improved version of
14126: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14127: improvements are:
14128:
14129: @itemize @bullet
14130: @item
1.107 dvdkhlng 14131: A better handling of indentation.
14132: @item
14133: A custom hilighting engine for Forth-code.
1.26 crook 14134: @item
14135: Comment paragraph filling (@kbd{M-q})
14136: @item
14137: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14138: @item
14139: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14140: @item
14141: Support of the @code{info-lookup} feature for looking up the
14142: documentation of a word.
1.107 dvdkhlng 14143: @item
14144: Support for reading and writing blocks files.
1.26 crook 14145: @end itemize
14146:
1.107 dvdkhlng 14147: To get a basic description of these features, enter Forth mode and
14148: type @kbd{C-h m}.
1.1 anton 14149:
14150: @cindex source location of error or debugging output in Emacs
14151: @cindex error output, finding the source location in Emacs
14152: @cindex debugging output, finding the source location in Emacs
14153: In addition, Gforth supports Emacs quite well: The source code locations
14154: given in error messages, debugging output (from @code{~~}) and failed
14155: assertion messages are in the right format for Emacs' compilation mode
14156: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14157: Manual}) so the source location corresponding to an error or other
14158: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14159: @kbd{C-c C-c} for the error under the cursor).
14160:
1.107 dvdkhlng 14161: @cindex viewing the documentation of a word in Emacs
14162: @cindex context-sensitive help
14163: Moreover, for words documented in this manual, you can look up the
14164: glossary entry quickly by using @kbd{C-h TAB}
14165: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14166: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14167: later and does not work for words containing @code{:}.
14168:
14169: @menu
14170: * Installing gforth.el:: Making Emacs aware of Forth.
14171: * Emacs Tags:: Viewing the source of a word in Emacs.
14172: * Hilighting:: Making Forth code look prettier.
14173: * Auto-Indentation:: Customizing auto-indentation.
14174: * Blocks Files:: Reading and writing blocks files.
14175: @end menu
14176:
14177: @c ----------------------------------
1.109 anton 14178: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14179: @section Installing gforth.el
14180: @cindex @file{.emacs}
14181: @cindex @file{gforth.el}, installation
14182: To make the features from @file{gforth.el} available in Emacs, add
14183: the following lines to your @file{.emacs} file:
14184:
14185: @example
14186: (autoload 'forth-mode "gforth.el")
14187: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14188: auto-mode-alist))
14189: (autoload 'forth-block-mode "gforth.el")
14190: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14191: auto-mode-alist))
14192: (add-hook 'forth-mode-hook (function (lambda ()
14193: ;; customize variables here:
14194: (setq forth-indent-level 4)
14195: (setq forth-minor-indent-level 2)
14196: (setq forth-hilight-level 3)
14197: ;;; ...
14198: )))
14199: @end example
14200:
14201: @c ----------------------------------
14202: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14203: @section Emacs Tags
1.1 anton 14204: @cindex @file{TAGS} file
14205: @cindex @file{etags.fs}
14206: @cindex viewing the source of a word in Emacs
1.43 anton 14207: @cindex @code{require}, placement in files
14208: @cindex @code{include}, placement in files
1.107 dvdkhlng 14209: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14210: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14211: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14212: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14213: several tags files at the same time (e.g., one for the Gforth sources
14214: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14215: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14216: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14217: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14218: with @file{etags.fs}, you should avoid putting definitions both before
14219: and after @code{require} etc., otherwise you will see the same file
14220: visited several times by commands like @code{tags-search}.
1.1 anton 14221:
1.107 dvdkhlng 14222: @c ----------------------------------
14223: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14224: @section Hilighting
14225: @cindex hilighting Forth code in Emacs
14226: @cindex highlighting Forth code in Emacs
14227: @file{gforth.el} comes with a custom source hilighting engine. When
14228: you open a file in @code{forth-mode}, it will be completely parsed,
14229: assigning faces to keywords, comments, strings etc. While you edit
14230: the file, modified regions get parsed and updated on-the-fly.
14231:
14232: Use the variable `forth-hilight-level' to change the level of
14233: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14234: you set the hilighting level to 0, the parser will still work in the
14235: background, collecting information about whether regions of text are
14236: ``compiled'' or ``interpreted''. Those information are required for
14237: auto-indentation to work properly. Set `forth-disable-parser' to
14238: non-nil if your computer is too slow to handle parsing. This will
14239: have an impact on the smartness of the auto-indentation engine,
14240: though.
14241:
14242: Sometimes Forth sources define new features that should be hilighted,
14243: new control structures, defining-words etc. You can use the variable
14244: `forth-custom-words' to make @code{forth-mode} hilight additional
14245: words and constructs. See the docstring of `forth-words' for details
14246: (in Emacs, type @kbd{C-h v forth-words}).
14247:
14248: `forth-custom-words' is meant to be customized in your
14249: @file{.emacs} file. To customize hilighing in a file-specific manner,
14250: set `forth-local-words' in a local-variables section at the end of
14251: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14252:
14253: Example:
14254: @example
14255: 0 [IF]
14256: Local Variables:
14257: forth-local-words:
14258: ((("t:") definition-starter (font-lock-keyword-face . 1)
14259: "[ \t\n]" t name (font-lock-function-name-face . 3))
14260: ((";t") definition-ender (font-lock-keyword-face . 1)))
14261: End:
14262: [THEN]
14263: @end example
14264:
14265: @c ----------------------------------
14266: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14267: @section Auto-Indentation
14268: @cindex auto-indentation of Forth code in Emacs
14269: @cindex indentation of Forth code in Emacs
14270: @code{forth-mode} automatically tries to indent lines in a smart way,
14271: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14272:
14273: Simple customization can be achieved by setting
14274: `forth-indent-level' and `forth-minor-indent-level' in your
14275: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14276: per default by multiples of 4 columns. To use the more traditional
14277: 3-column indentation, add the following lines to your @file{.emacs}:
14278:
14279: @example
14280: (add-hook 'forth-mode-hook (function (lambda ()
14281: ;; customize variables here:
14282: (setq forth-indent-level 3)
14283: (setq forth-minor-indent-level 1)
14284: )))
14285: @end example
14286:
14287: If you want indentation to recognize non-default words, customize it
14288: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14289: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14290: v forth-indent-words}).
14291:
14292: To customize indentation in a file-specific manner, set
14293: `forth-local-indent-words' in a local-variables section at the end of
14294: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14295: Emacs Manual}).
14296:
14297: Example:
14298: @example
14299: 0 [IF]
14300: Local Variables:
14301: forth-local-indent-words:
14302: ((("t:") (0 . 2) (0 . 2))
14303: ((";t") (-2 . 0) (0 . -2)))
14304: End:
14305: [THEN]
14306: @end example
14307:
14308: @c ----------------------------------
1.109 anton 14309: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14310: @section Blocks Files
14311: @cindex blocks files, use with Emacs
14312: @code{forth-mode} Autodetects blocks files by checking whether the
14313: length of the first line exceeds 1023 characters. It then tries to
14314: convert the file into normal text format. When you save the file, it
14315: will be written to disk as normal stream-source file.
14316:
14317: If you want to write blocks files, use @code{forth-blocks-mode}. It
14318: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14319:
1.107 dvdkhlng 14320: @itemize @bullet
14321: @item
14322: Files are written to disk in blocks file format.
14323: @item
14324: Screen numbers are displayed in the mode line (enumerated beginning
14325: with the value of `forth-block-base')
14326: @item
14327: Warnings are displayed when lines exceed 64 characters.
14328: @item
14329: The beginning of the currently edited block is marked with an
14330: overlay-arrow.
14331: @end itemize
1.41 anton 14332:
1.107 dvdkhlng 14333: There are some restrictions you should be aware of. When you open a
14334: blocks file that contains tabulator or newline characters, these
14335: characters will be translated into spaces when the file is written
14336: back to disk. If tabs or newlines are encountered during blocks file
14337: reading, an error is output to the echo area. So have a look at the
14338: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14339:
1.107 dvdkhlng 14340: Please consult the docstring of @code{forth-blocks-mode} for more
14341: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14342:
1.26 crook 14343: @c ******************************************************************
1.1 anton 14344: @node Image Files, Engine, Emacs and Gforth, Top
14345: @chapter Image Files
1.26 crook 14346: @cindex image file
14347: @cindex @file{.fi} files
1.1 anton 14348: @cindex precompiled Forth code
14349: @cindex dictionary in persistent form
14350: @cindex persistent form of dictionary
14351:
14352: An image file is a file containing an image of the Forth dictionary,
14353: i.e., compiled Forth code and data residing in the dictionary. By
14354: convention, we use the extension @code{.fi} for image files.
14355:
14356: @menu
1.18 anton 14357: * Image Licensing Issues:: Distribution terms for images.
14358: * Image File Background:: Why have image files?
1.67 anton 14359: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14360: * Data-Relocatable Image Files:: are better.
1.67 anton 14361: * Fully Relocatable Image Files:: better yet.
1.18 anton 14362: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14363: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14364: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14365: @end menu
14366:
1.18 anton 14367: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14368: @section Image Licensing Issues
14369: @cindex license for images
14370: @cindex image license
14371:
14372: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14373: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14374: original image; i.e., according to copyright law it is a derived work of
14375: the original image.
14376:
14377: Since Gforth is distributed under the GNU GPL, the newly created image
14378: falls under the GNU GPL, too. In particular, this means that if you
14379: distribute the image, you have to make all of the sources for the image
1.113 anton 14380: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14381: GNU General Public License (Section 3)}.
14382:
14383: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14384: contains only code compiled from the sources you gave it; if none of
14385: these sources is under the GPL, the terms discussed above do not apply
14386: to the image. However, if your image needs an engine (a gforth binary)
14387: that is under the GPL, you should make sure that you distribute both in
14388: a way that is at most a @emph{mere aggregation}, if you don't want the
14389: terms of the GPL to apply to the image.
14390:
14391: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14392: @section Image File Background
14393: @cindex image file background
14394:
1.80 anton 14395: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14396: definitions written in Forth. Since the Forth compiler itself belongs to
14397: those definitions, it is not possible to start the system with the
1.80 anton 14398: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14399: code as an image file in nearly executable form. When Gforth starts up,
14400: a C routine loads the image file into memory, optionally relocates the
14401: addresses, then sets up the memory (stacks etc.) according to
14402: information in the image file, and (finally) starts executing Forth
14403: code.
1.1 anton 14404:
14405: The image file variants represent different compromises between the
14406: goals of making it easy to generate image files and making them
14407: portable.
14408:
14409: @cindex relocation at run-time
1.26 crook 14410: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 14411: run-time. This avoids many of the complications discussed below (image
14412: files are data relocatable without further ado), but costs performance
14413: (one addition per memory access).
14414:
14415: @cindex relocation at load-time
1.26 crook 14416: By contrast, the Gforth loader performs relocation at image load time. The
14417: loader also has to replace tokens that represent primitive calls with the
1.1 anton 14418: appropriate code-field addresses (or code addresses in the case of
14419: direct threading).
14420:
14421: There are three kinds of image files, with different degrees of
14422: relocatability: non-relocatable, data-relocatable, and fully relocatable
14423: image files.
14424:
14425: @cindex image file loader
14426: @cindex relocating loader
14427: @cindex loader for image files
14428: These image file variants have several restrictions in common; they are
14429: caused by the design of the image file loader:
14430:
14431: @itemize @bullet
14432: @item
14433: There is only one segment; in particular, this means, that an image file
14434: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 14435: them). The contents of the stacks are not represented, either.
1.1 anton 14436:
14437: @item
14438: The only kinds of relocation supported are: adding the same offset to
14439: all cells that represent data addresses; and replacing special tokens
14440: with code addresses or with pieces of machine code.
14441:
14442: If any complex computations involving addresses are performed, the
14443: results cannot be represented in the image file. Several applications that
14444: use such computations come to mind:
14445: @itemize @minus
14446: @item
14447: Hashing addresses (or data structures which contain addresses) for table
14448: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
14449: purpose, you will have no problem, because the hash tables are
14450: recomputed automatically when the system is started. If you use your own
14451: hash tables, you will have to do something similar.
14452:
14453: @item
14454: There's a cute implementation of doubly-linked lists that uses
14455: @code{XOR}ed addresses. You could represent such lists as singly-linked
14456: in the image file, and restore the doubly-linked representation on
14457: startup.@footnote{In my opinion, though, you should think thrice before
14458: using a doubly-linked list (whatever implementation).}
14459:
14460: @item
14461: The code addresses of run-time routines like @code{docol:} cannot be
14462: represented in the image file (because their tokens would be replaced by
14463: machine code in direct threaded implementations). As a workaround,
14464: compute these addresses at run-time with @code{>code-address} from the
14465: executions tokens of appropriate words (see the definitions of
1.80 anton 14466: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 14467:
14468: @item
14469: On many architectures addresses are represented in machine code in some
14470: shifted or mangled form. You cannot put @code{CODE} words that contain
14471: absolute addresses in this form in a relocatable image file. Workarounds
14472: are representing the address in some relative form (e.g., relative to
14473: the CFA, which is present in some register), or loading the address from
14474: a place where it is stored in a non-mangled form.
14475: @end itemize
14476: @end itemize
14477:
14478: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
14479: @section Non-Relocatable Image Files
14480: @cindex non-relocatable image files
1.26 crook 14481: @cindex image file, non-relocatable
1.1 anton 14482:
14483: These files are simple memory dumps of the dictionary. They are specific
14484: to the executable (i.e., @file{gforth} file) they were created
14485: with. What's worse, they are specific to the place on which the
14486: dictionary resided when the image was created. Now, there is no
14487: guarantee that the dictionary will reside at the same place the next
14488: time you start Gforth, so there's no guarantee that a non-relocatable
14489: image will work the next time (Gforth will complain instead of crashing,
14490: though).
14491:
14492: You can create a non-relocatable image file with
14493:
1.44 crook 14494:
1.1 anton 14495: doc-savesystem
14496:
1.44 crook 14497:
1.1 anton 14498: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
14499: @section Data-Relocatable Image Files
14500: @cindex data-relocatable image files
1.26 crook 14501: @cindex image file, data-relocatable
1.1 anton 14502:
14503: These files contain relocatable data addresses, but fixed code addresses
14504: (instead of tokens). They are specific to the executable (i.e.,
14505: @file{gforth} file) they were created with. For direct threading on some
14506: architectures (e.g., the i386), data-relocatable images do not work. You
14507: get a data-relocatable image, if you use @file{gforthmi} with a
14508: Gforth binary that is not doubly indirect threaded (@pxref{Fully
14509: Relocatable Image Files}).
14510:
14511: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
14512: @section Fully Relocatable Image Files
14513: @cindex fully relocatable image files
1.26 crook 14514: @cindex image file, fully relocatable
1.1 anton 14515:
14516: @cindex @file{kern*.fi}, relocatability
14517: @cindex @file{gforth.fi}, relocatability
14518: These image files have relocatable data addresses, and tokens for code
14519: addresses. They can be used with different binaries (e.g., with and
14520: without debugging) on the same machine, and even across machines with
14521: the same data formats (byte order, cell size, floating point
14522: format). However, they are usually specific to the version of Gforth
14523: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
14524: are fully relocatable.
14525:
14526: There are two ways to create a fully relocatable image file:
14527:
14528: @menu
1.29 crook 14529: * gforthmi:: The normal way
1.1 anton 14530: * cross.fs:: The hard way
14531: @end menu
14532:
14533: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
14534: @subsection @file{gforthmi}
14535: @cindex @file{comp-i.fs}
14536: @cindex @file{gforthmi}
14537:
14538: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 14539: image @i{file} that contains everything you would load by invoking
14540: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 14541: @example
1.29 crook 14542: gforthmi @i{file} @i{options}
1.1 anton 14543: @end example
14544:
14545: E.g., if you want to create an image @file{asm.fi} that has the file
14546: @file{asm.fs} loaded in addition to the usual stuff, you could do it
14547: like this:
14548:
14549: @example
14550: gforthmi asm.fi asm.fs
14551: @end example
14552:
1.27 crook 14553: @file{gforthmi} is implemented as a sh script and works like this: It
14554: produces two non-relocatable images for different addresses and then
14555: compares them. Its output reflects this: first you see the output (if
1.62 crook 14556: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 14557: files, then you see the output of the comparing program: It displays the
14558: offset used for data addresses and the offset used for code addresses;
1.1 anton 14559: moreover, for each cell that cannot be represented correctly in the
1.44 crook 14560: image files, it displays a line like this:
1.1 anton 14561:
14562: @example
14563: 78DC BFFFFA50 BFFFFA40
14564: @end example
14565:
14566: This means that at offset $78dc from @code{forthstart}, one input image
14567: contains $bffffa50, and the other contains $bffffa40. Since these cells
14568: cannot be represented correctly in the output image, you should examine
14569: these places in the dictionary and verify that these cells are dead
14570: (i.e., not read before they are written).
1.39 anton 14571:
14572: @cindex --application, @code{gforthmi} option
14573: If you insert the option @code{--application} in front of the image file
14574: name, you will get an image that uses the @code{--appl-image} option
14575: instead of the @code{--image-file} option (@pxref{Invoking
14576: Gforth}). When you execute such an image on Unix (by typing the image
14577: name as command), the Gforth engine will pass all options to the image
14578: instead of trying to interpret them as engine options.
1.1 anton 14579:
1.27 crook 14580: If you type @file{gforthmi} with no arguments, it prints some usage
14581: instructions.
14582:
1.1 anton 14583: @cindex @code{savesystem} during @file{gforthmi}
14584: @cindex @code{bye} during @file{gforthmi}
14585: @cindex doubly indirect threaded code
1.44 crook 14586: @cindex environment variables
14587: @cindex @code{GFORTHD} -- environment variable
14588: @cindex @code{GFORTH} -- environment variable
1.1 anton 14589: @cindex @code{gforth-ditc}
1.29 crook 14590: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 14591: words @code{savesystem} and @code{bye} must be visible. A special doubly
14592: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 14593: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 14594: this executable through the environment variable @code{GFORTHD}
14595: (default: @file{gforth-ditc}); if you pass a version that is not doubly
14596: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 14597: data-relocatable image (because there is no code address offset). The
14598: normal @file{gforth} executable is used for creating the relocatable
14599: image; you can pass the exact filename of this executable through the
14600: environment variable @code{GFORTH}.
1.1 anton 14601:
14602: @node cross.fs, , gforthmi, Fully Relocatable Image Files
14603: @subsection @file{cross.fs}
14604: @cindex @file{cross.fs}
14605: @cindex cross-compiler
14606: @cindex metacompiler
1.47 crook 14607: @cindex target compiler
1.1 anton 14608:
14609: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 14610: programming language (@pxref{Cross Compiler}).
1.1 anton 14611:
1.47 crook 14612: @code{cross} allows you to create image files for machines with
1.1 anton 14613: different data sizes and data formats than the one used for generating
14614: the image file. You can also use it to create an application image that
14615: does not contain a Forth compiler. These features are bought with
14616: restrictions and inconveniences in programming. E.g., addresses have to
14617: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
14618: order to make the code relocatable.
14619:
14620:
14621: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
14622: @section Stack and Dictionary Sizes
14623: @cindex image file, stack and dictionary sizes
14624: @cindex dictionary size default
14625: @cindex stack size default
14626:
14627: If you invoke Gforth with a command line flag for the size
14628: (@pxref{Invoking Gforth}), the size you specify is stored in the
14629: dictionary. If you save the dictionary with @code{savesystem} or create
14630: an image with @file{gforthmi}, this size will become the default
14631: for the resulting image file. E.g., the following will create a
1.21 crook 14632: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 14633:
14634: @example
14635: gforthmi gforth.fi -m 1M
14636: @end example
14637:
14638: In other words, if you want to set the default size for the dictionary
14639: and the stacks of an image, just invoke @file{gforthmi} with the
14640: appropriate options when creating the image.
14641:
14642: @cindex stack size, cache-friendly
14643: Note: For cache-friendly behaviour (i.e., good performance), you should
14644: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
14645: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
14646: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
14647:
14648: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
14649: @section Running Image Files
14650: @cindex running image files
14651: @cindex invoking image files
14652: @cindex image file invocation
14653:
14654: @cindex -i, invoke image file
14655: @cindex --image file, invoke image file
1.29 crook 14656: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 14657: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
14658: @example
1.29 crook 14659: gforth -i @i{image}
1.1 anton 14660: @end example
14661:
14662: @cindex executable image file
1.26 crook 14663: @cindex image file, executable
1.1 anton 14664: If your operating system supports starting scripts with a line of the
14665: form @code{#! ...}, you just have to type the image file name to start
14666: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 14667: just a convention). I.e., to run Gforth with the image file @i{image},
14668: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 14669: This works because every @code{.fi} file starts with a line of this
14670: format:
14671:
14672: @example
14673: #! /usr/local/bin/gforth-0.4.0 -i
14674: @end example
14675:
14676: The file and pathname for the Gforth engine specified on this line is
14677: the specific Gforth executable that it was built against; i.e. the value
14678: of the environment variable @code{GFORTH} at the time that
14679: @file{gforthmi} was executed.
1.1 anton 14680:
1.27 crook 14681: You can make use of the same shell capability to make a Forth source
14682: file into an executable. For example, if you place this text in a file:
1.26 crook 14683:
14684: @example
14685: #! /usr/local/bin/gforth
14686:
14687: ." Hello, world" CR
14688: bye
14689: @end example
14690:
14691: @noindent
1.27 crook 14692: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 14693: directly from the command line. The sequence @code{#!} is used in two
14694: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 14695: system@footnote{The Unix kernel actually recognises two types of files:
14696: executable files and files of data, where the data is processed by an
14697: interpreter that is specified on the ``interpreter line'' -- the first
14698: line of the file, starting with the sequence #!. There may be a small
14699: limit (e.g., 32) on the number of characters that may be specified on
14700: the interpreter line.} secondly it is treated as a comment character by
14701: Gforth. Because of the second usage, a space is required between
1.80 anton 14702: @code{#!} and the path to the executable (moreover, some Unixes
14703: require the sequence @code{#! /}).
1.27 crook 14704:
14705: The disadvantage of this latter technique, compared with using
1.80 anton 14706: @file{gforthmi}, is that it is slightly slower; the Forth source code is
14707: compiled on-the-fly, each time the program is invoked.
1.26 crook 14708:
1.1 anton 14709: doc-#!
14710:
1.44 crook 14711:
1.1 anton 14712: @node Modifying the Startup Sequence, , Running Image Files, Image Files
14713: @section Modifying the Startup Sequence
14714: @cindex startup sequence for image file
14715: @cindex image file initialization sequence
14716: @cindex initialization sequence of image file
14717:
1.120 anton 14718: You can add your own initialization to the startup sequence of an image
14719: through the deferred word @code{'cold}. @code{'cold} is invoked just
14720: before the image-specific command line processing (i.e., loading files
14721: and evaluating (@code{-e}) strings) starts.
1.1 anton 14722:
14723: A sequence for adding your initialization usually looks like this:
14724:
14725: @example
14726: :noname
14727: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
14728: ... \ your stuff
14729: ; IS 'cold
14730: @end example
14731:
1.157 anton 14732: After @code{'cold}, Gforth processes the image options
14733: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
14734: another deferred word. This normally prints Gforth's startup message
14735: and does nothing else.
14736:
1.1 anton 14737: @cindex turnkey image files
1.26 crook 14738: @cindex image file, turnkey applications
1.157 anton 14739: So, if you want to make a turnkey image (i.e., an image for an
14740: application instead of an extended Forth system), you can do this in
14741: two ways:
14742:
14743: @itemize @bullet
14744:
14745: @item
14746: If you want to do your interpretation of the OS command-line
14747: arguments, hook into @code{'cold}. In that case you probably also
14748: want to build the image with @code{gforthmi --application}
14749: (@pxref{gforthmi}) to keep the engine from processing OS command line
14750: options. You can then do your own command-line processing with
14751: @code{next-arg}
14752:
14753: @item
14754: If you want to have the normal Gforth processing of OS command-line
14755: arguments, hook into @code{bootmessage}.
14756:
14757: @end itemize
14758:
14759: In either case, you probably do not want the word that you execute in
14760: these hooks to exit normally, but use @code{bye} or @code{throw}.
14761: Otherwise the Gforth startup process would continue and eventually
14762: present the Forth command line to the user.
1.26 crook 14763:
14764: doc-'cold
1.157 anton 14765: doc-bootmessage
1.44 crook 14766:
1.1 anton 14767: @c ******************************************************************
1.113 anton 14768: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 14769: @chapter Engine
14770: @cindex engine
14771: @cindex virtual machine
14772:
1.26 crook 14773: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 14774: may be helpful for finding your way in the Gforth sources.
14775:
1.109 anton 14776: The ideas in this section have also been published in the following
14777: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
14778: Forth-Tagung '93; M. Anton Ertl,
14779: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
14780: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
14781: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
14782: Threaded code variations and optimizations (extended version)}},
14783: Forth-Tagung '02.
1.1 anton 14784:
14785: @menu
14786: * Portability::
14787: * Threading::
14788: * Primitives::
14789: * Performance::
14790: @end menu
14791:
14792: @node Portability, Threading, Engine, Engine
14793: @section Portability
14794: @cindex engine portability
14795:
1.26 crook 14796: An important goal of the Gforth Project is availability across a wide
14797: range of personal machines. fig-Forth, and, to a lesser extent, F83,
14798: achieved this goal by manually coding the engine in assembly language
14799: for several then-popular processors. This approach is very
14800: labor-intensive and the results are short-lived due to progress in
14801: computer architecture.
1.1 anton 14802:
14803: @cindex C, using C for the engine
14804: Others have avoided this problem by coding in C, e.g., Mitch Bradley
14805: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
14806: particularly popular for UNIX-based Forths due to the large variety of
14807: architectures of UNIX machines. Unfortunately an implementation in C
14808: does not mix well with the goals of efficiency and with using
14809: traditional techniques: Indirect or direct threading cannot be expressed
14810: in C, and switch threading, the fastest technique available in C, is
14811: significantly slower. Another problem with C is that it is very
14812: cumbersome to express double integer arithmetic.
14813:
14814: @cindex GNU C for the engine
14815: @cindex long long
14816: Fortunately, there is a portable language that does not have these
14817: limitations: GNU C, the version of C processed by the GNU C compiler
14818: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
14819: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
14820: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
14821: threading possible, its @code{long long} type (@pxref{Long Long, ,
14822: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 14823: double numbers on many systems. GNU C is freely available on all
1.1 anton 14824: important (and many unimportant) UNIX machines, VMS, 80386s running
14825: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
14826: on all these machines.
14827:
14828: Writing in a portable language has the reputation of producing code that
14829: is slower than assembly. For our Forth engine we repeatedly looked at
14830: the code produced by the compiler and eliminated most compiler-induced
14831: inefficiencies by appropriate changes in the source code.
14832:
14833: @cindex explicit register declarations
14834: @cindex --enable-force-reg, configuration flag
14835: @cindex -DFORCE_REG
14836: However, register allocation cannot be portably influenced by the
14837: programmer, leading to some inefficiencies on register-starved
14838: machines. We use explicit register declarations (@pxref{Explicit Reg
14839: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
14840: improve the speed on some machines. They are turned on by using the
14841: configuration flag @code{--enable-force-reg} (@code{gcc} switch
14842: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
14843: machine, but also on the compiler version: On some machines some
14844: compiler versions produce incorrect code when certain explicit register
14845: declarations are used. So by default @code{-DFORCE_REG} is not used.
14846:
14847: @node Threading, Primitives, Portability, Engine
14848: @section Threading
14849: @cindex inner interpreter implementation
14850: @cindex threaded code implementation
14851:
14852: @cindex labels as values
14853: GNU C's labels as values extension (available since @code{gcc-2.0},
14854: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 14855: makes it possible to take the address of @i{label} by writing
14856: @code{&&@i{label}}. This address can then be used in a statement like
14857: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 14858: @code{goto x}.
14859:
1.26 crook 14860: @cindex @code{NEXT}, indirect threaded
1.1 anton 14861: @cindex indirect threaded inner interpreter
14862: @cindex inner interpreter, indirect threaded
1.26 crook 14863: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 14864: @example
14865: cfa = *ip++;
14866: ca = *cfa;
14867: goto *ca;
14868: @end example
14869: @cindex instruction pointer
14870: For those unfamiliar with the names: @code{ip} is the Forth instruction
14871: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
14872: execution token and points to the code field of the next word to be
14873: executed; The @code{ca} (code address) fetched from there points to some
14874: executable code, e.g., a primitive or the colon definition handler
14875: @code{docol}.
14876:
1.26 crook 14877: @cindex @code{NEXT}, direct threaded
1.1 anton 14878: @cindex direct threaded inner interpreter
14879: @cindex inner interpreter, direct threaded
14880: Direct threading is even simpler:
14881: @example
14882: ca = *ip++;
14883: goto *ca;
14884: @end example
14885:
14886: Of course we have packaged the whole thing neatly in macros called
1.26 crook 14887: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 14888:
14889: @menu
14890: * Scheduling::
14891: * Direct or Indirect Threaded?::
1.109 anton 14892: * Dynamic Superinstructions::
1.1 anton 14893: * DOES>::
14894: @end menu
14895:
14896: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
14897: @subsection Scheduling
14898: @cindex inner interpreter optimization
14899:
14900: There is a little complication: Pipelined and superscalar processors,
14901: i.e., RISC and some modern CISC machines can process independent
14902: instructions while waiting for the results of an instruction. The
14903: compiler usually reorders (schedules) the instructions in a way that
14904: achieves good usage of these delay slots. However, on our first tries
14905: the compiler did not do well on scheduling primitives. E.g., for
14906: @code{+} implemented as
14907: @example
14908: n=sp[0]+sp[1];
14909: sp++;
14910: sp[0]=n;
14911: NEXT;
14912: @end example
1.81 anton 14913: the @code{NEXT} comes strictly after the other code, i.e., there is
14914: nearly no scheduling. After a little thought the problem becomes clear:
14915: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 14916: addresses (and the version of @code{gcc} we used would not know it even
14917: if it was possible), so it could not move the load of the cfa above the
14918: store to the TOS. Indeed the pointers could be the same, if code on or
14919: very near the top of stack were executed. In the interest of speed we
14920: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 14921: in scheduling: @code{NEXT} is divided into several parts:
14922: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
14923: like:
1.1 anton 14924: @example
1.81 anton 14925: NEXT_P0;
1.1 anton 14926: n=sp[0]+sp[1];
14927: sp++;
14928: NEXT_P1;
14929: sp[0]=n;
14930: NEXT_P2;
14931: @end example
14932:
1.81 anton 14933: There are various schemes that distribute the different operations of
14934: NEXT between these parts in several ways; in general, different schemes
14935: perform best on different processors. We use a scheme for most
14936: architectures that performs well for most processors of this
1.109 anton 14937: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 14938: the scheme on installation time.
14939:
1.1 anton 14940:
1.109 anton 14941: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 14942: @subsection Direct or Indirect Threaded?
14943: @cindex threading, direct or indirect?
14944:
1.109 anton 14945: Threaded forth code consists of references to primitives (simple machine
14946: code routines like @code{+}) and to non-primitives (e.g., colon
14947: definitions, variables, constants); for a specific class of
14948: non-primitives (e.g., variables) there is one code routine (e.g.,
14949: @code{dovar}), but each variable needs a separate reference to its data.
14950:
14951: Traditionally Forth has been implemented as indirect threaded code,
14952: because this allows to use only one cell to reference a non-primitive
14953: (basically you point to the data, and find the code address there).
14954:
14955: @cindex primitive-centric threaded code
14956: However, threaded code in Gforth (since 0.6.0) uses two cells for
14957: non-primitives, one for the code address, and one for the data address;
14958: the data pointer is an immediate argument for the virtual machine
14959: instruction represented by the code address. We call this
14960: @emph{primitive-centric} threaded code, because all code addresses point
14961: to simple primitives. E.g., for a variable, the code address is for
14962: @code{lit} (also used for integer literals like @code{99}).
14963:
14964: Primitive-centric threaded code allows us to use (faster) direct
14965: threading as dispatch method, completely portably (direct threaded code
14966: in Gforth before 0.6.0 required architecture-specific code). It also
14967: eliminates the performance problems related to I-cache consistency that
14968: 386 implementations have with direct threaded code, and allows
14969: additional optimizations.
14970:
14971: @cindex hybrid direct/indirect threaded code
14972: There is a catch, however: the @var{xt} parameter of @code{execute} can
14973: occupy only one cell, so how do we pass non-primitives with their code
14974: @emph{and} data addresses to them? Our answer is to use indirect
14975: threaded dispatch for @code{execute} and other words that use a
14976: single-cell xt. So, normal threaded code in colon definitions uses
14977: direct threading, and @code{execute} and similar words, which dispatch
14978: to xts on the data stack, use indirect threaded code. We call this
14979: @emph{hybrid direct/indirect} threaded code.
14980:
14981: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
14982: @cindex gforth engine
14983: @cindex gforth-fast engine
14984: The engines @command{gforth} and @command{gforth-fast} use hybrid
14985: direct/indirect threaded code. This means that with these engines you
14986: cannot use @code{,} to compile an xt. Instead, you have to use
14987: @code{compile,}.
14988:
14989: @cindex gforth-itc engine
1.115 anton 14990: If you want to compile xts with @code{,}, use @command{gforth-itc}.
14991: This engine uses plain old indirect threaded code. It still compiles in
14992: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 14993: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 14994: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 14995: and execute @code{' , is compile,}. Your program can check if it is
14996: running on a hybrid direct/indirect threaded engine or a pure indirect
14997: threaded engine with @code{threading-method} (@pxref{Threading Words}).
14998:
14999:
15000: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15001: @subsection Dynamic Superinstructions
15002: @cindex Dynamic superinstructions with replication
15003: @cindex Superinstructions
15004: @cindex Replication
15005:
15006: The engines @command{gforth} and @command{gforth-fast} use another
15007: optimization: Dynamic superinstructions with replication. As an
15008: example, consider the following colon definition:
15009:
15010: @example
15011: : squared ( n1 -- n2 )
15012: dup * ;
15013: @end example
15014:
15015: Gforth compiles this into the threaded code sequence
15016:
15017: @example
15018: dup
15019: *
15020: ;s
15021: @end example
15022:
15023: In normal direct threaded code there is a code address occupying one
15024: cell for each of these primitives. Each code address points to a
15025: machine code routine, and the interpreter jumps to this machine code in
15026: order to execute the primitive. The routines for these three
15027: primitives are (in @command{gforth-fast} on the 386):
15028:
15029: @example
15030: Code dup
15031: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15032: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15033: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15034: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15035: end-code
15036: Code *
15037: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15038: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15039: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15040: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15041: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15042: end-code
15043: Code ;s
15044: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15045: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15046: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15047: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15048: end-code
15049: @end example
15050:
15051: With dynamic superinstructions and replication the compiler does not
15052: just lay down the threaded code, but also copies the machine code
15053: fragments, usually without the jump at the end.
15054:
15055: @example
15056: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15057: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15058: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15059: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15060: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15061: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15062: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15063: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15064: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15065: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15066: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15067: @end example
15068:
15069: Only when a threaded-code control-flow change happens (e.g., in
15070: @code{;s}), the jump is appended. This optimization eliminates many of
15071: these jumps and makes the rest much more predictable. The speedup
15072: depends on the processor and the application; on the Athlon and Pentium
15073: III this optimization typically produces a speedup by a factor of 2.
15074:
15075: The code addresses in the direct-threaded code are set to point to the
15076: appropriate points in the copied machine code, in this example like
15077: this:
1.1 anton 15078:
1.109 anton 15079: @example
15080: primitive code address
15081: dup $4057D27D
15082: * $4057D286
15083: ;s $4057D292
15084: @end example
15085:
15086: Thus there can be threaded-code jumps to any place in this piece of
15087: code. This also simplifies decompilation quite a bit.
15088:
15089: @cindex --no-dynamic command-line option
15090: @cindex --no-super command-line option
15091: You can disable this optimization with @option{--no-dynamic}. You can
15092: use the copying without eliminating the jumps (i.e., dynamic
15093: replication, but without superinstructions) with @option{--no-super};
15094: this gives the branch prediction benefit alone; the effect on
1.110 anton 15095: performance depends on the CPU; on the Athlon and Pentium III the
15096: speedup is a little less than for dynamic superinstructions with
15097: replication.
15098:
15099: @cindex patching threaded code
15100: One use of these options is if you want to patch the threaded code.
15101: With superinstructions, many of the dispatch jumps are eliminated, so
15102: patching often has no effect. These options preserve all the dispatch
15103: jumps.
1.109 anton 15104:
15105: @cindex --dynamic command-line option
1.110 anton 15106: On some machines dynamic superinstructions are disabled by default,
15107: because it is unsafe on these machines. However, if you feel
15108: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15109:
15110: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15111: @subsection DOES>
15112: @cindex @code{DOES>} implementation
15113:
1.26 crook 15114: @cindex @code{dodoes} routine
15115: @cindex @code{DOES>}-code
1.1 anton 15116: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15117: the chunk of code executed by every word defined by a
1.109 anton 15118: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15119: this is only needed if the xt of the word is @code{execute}d. The main
15120: problem here is: How to find the Forth code to be executed, i.e. the
15121: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15122: solutions:
1.1 anton 15123:
1.21 crook 15124: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15125: @code{DOES>}-code address is stored in the cell after the code address
15126: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15127: illegal in the Forth-79 and all later standards, because in fig-Forth
15128: this address lies in the body (which is illegal in these
15129: standards). However, by making the code field larger for all words this
15130: solution becomes legal again. We use this approach. Leaving a cell
15131: unused in most words is a bit wasteful, but on the machines we are
15132: targeting this is hardly a problem.
15133:
1.1 anton 15134:
15135: @node Primitives, Performance, Threading, Engine
15136: @section Primitives
15137: @cindex primitives, implementation
15138: @cindex virtual machine instructions, implementation
15139:
15140: @menu
15141: * Automatic Generation::
15142: * TOS Optimization::
15143: * Produced code::
15144: @end menu
15145:
15146: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15147: @subsection Automatic Generation
15148: @cindex primitives, automatic generation
15149:
15150: @cindex @file{prims2x.fs}
1.109 anton 15151:
1.1 anton 15152: Since the primitives are implemented in a portable language, there is no
15153: longer any need to minimize the number of primitives. On the contrary,
15154: having many primitives has an advantage: speed. In order to reduce the
15155: number of errors in primitives and to make programming them easier, we
1.109 anton 15156: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15157: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15158: generates most (and sometimes all) of the C code for a primitive from
15159: the stack effect notation. The source for a primitive has the following
15160: form:
1.1 anton 15161:
15162: @cindex primitive source format
15163: @format
1.58 anton 15164: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15165: [@code{""}@i{glossary entry}@code{""}]
15166: @i{C code}
1.1 anton 15167: [@code{:}
1.29 crook 15168: @i{Forth code}]
1.1 anton 15169: @end format
15170:
15171: The items in brackets are optional. The category and glossary fields
15172: are there for generating the documentation, the Forth code is there
15173: for manual implementations on machines without GNU C. E.g., the source
15174: for the primitive @code{+} is:
15175: @example
1.58 anton 15176: + ( n1 n2 -- n ) core plus
1.1 anton 15177: n = n1+n2;
15178: @end example
15179:
15180: This looks like a specification, but in fact @code{n = n1+n2} is C
15181: code. Our primitive generation tool extracts a lot of information from
15182: the stack effect notations@footnote{We use a one-stack notation, even
15183: though we have separate data and floating-point stacks; The separate
15184: notation can be generated easily from the unified notation.}: The number
15185: of items popped from and pushed on the stack, their type, and by what
15186: name they are referred to in the C code. It then generates a C code
15187: prelude and postlude for each primitive. The final C code for @code{+}
15188: looks like this:
15189:
15190: @example
1.46 pazsan 15191: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15192: /* */ /* documentation */
1.81 anton 15193: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15194: @{
15195: DEF_CA /* definition of variable ca (indirect threading) */
15196: Cell n1; /* definitions of variables */
15197: Cell n2;
15198: Cell n;
1.81 anton 15199: NEXT_P0; /* NEXT part 0 */
1.1 anton 15200: n1 = (Cell) sp[1]; /* input */
15201: n2 = (Cell) TOS;
15202: sp += 1; /* stack adjustment */
15203: @{
15204: n = n1+n2; /* C code taken from the source */
15205: @}
15206: NEXT_P1; /* NEXT part 1 */
15207: TOS = (Cell)n; /* output */
15208: NEXT_P2; /* NEXT part 2 */
15209: @}
15210: @end example
15211:
15212: This looks long and inefficient, but the GNU C compiler optimizes quite
15213: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15214: HP RISC machines: Defining the @code{n}s does not produce any code, and
15215: using them as intermediate storage also adds no cost.
15216:
1.26 crook 15217: There are also other optimizations that are not illustrated by this
15218: example: assignments between simple variables are usually for free (copy
1.1 anton 15219: propagation). If one of the stack items is not used by the primitive
15220: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15221: (dead code elimination). On the other hand, there are some things that
15222: the compiler does not do, therefore they are performed by
15223: @file{prims2x.fs}: The compiler does not optimize code away that stores
15224: a stack item to the place where it just came from (e.g., @code{over}).
15225:
15226: While programming a primitive is usually easy, there are a few cases
15227: where the programmer has to take the actions of the generator into
15228: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15229: fall through to @code{NEXT}.
1.109 anton 15230:
15231: For more information
1.1 anton 15232:
15233: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15234: @subsection TOS Optimization
15235: @cindex TOS optimization for primitives
15236: @cindex primitives, keeping the TOS in a register
15237:
15238: An important optimization for stack machine emulators, e.g., Forth
15239: engines, is keeping one or more of the top stack items in
1.29 crook 15240: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15241: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15242: @itemize @bullet
15243: @item
1.29 crook 15244: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15245: due to fewer loads from and stores to the stack.
1.29 crook 15246: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15247: @i{y<n}, due to additional moves between registers.
1.1 anton 15248: @end itemize
15249:
15250: @cindex -DUSE_TOS
15251: @cindex -DUSE_NO_TOS
15252: In particular, keeping one item in a register is never a disadvantage,
15253: if there are enough registers. Keeping two items in registers is a
15254: disadvantage for frequent words like @code{?branch}, constants,
15255: variables, literals and @code{i}. Therefore our generator only produces
15256: code that keeps zero or one items in registers. The generated C code
15257: covers both cases; the selection between these alternatives is made at
15258: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15259: code for @code{+} is just a simple variable name in the one-item case,
15260: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15261: GNU C compiler tries to keep simple variables like @code{TOS} in
15262: registers, and it usually succeeds, if there are enough registers.
15263:
15264: @cindex -DUSE_FTOS
15265: @cindex -DUSE_NO_FTOS
15266: The primitive generator performs the TOS optimization for the
15267: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15268: operations the benefit of this optimization is even larger:
15269: floating-point operations take quite long on most processors, but can be
15270: performed in parallel with other operations as long as their results are
15271: not used. If the FP-TOS is kept in a register, this works. If
15272: it is kept on the stack, i.e., in memory, the store into memory has to
15273: wait for the result of the floating-point operation, lengthening the
15274: execution time of the primitive considerably.
15275:
15276: The TOS optimization makes the automatic generation of primitives a
15277: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15278: @code{TOS} is not sufficient. There are some special cases to
15279: consider:
15280: @itemize @bullet
15281: @item In the case of @code{dup ( w -- w w )} the generator must not
15282: eliminate the store to the original location of the item on the stack,
15283: if the TOS optimization is turned on.
15284: @item Primitives with stack effects of the form @code{--}
1.29 crook 15285: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15286: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15287: must load the TOS from the stack at the end. But for the null stack
15288: effect @code{--} no stores or loads should be generated.
15289: @end itemize
15290:
15291: @node Produced code, , TOS Optimization, Primitives
15292: @subsection Produced code
15293: @cindex primitives, assembly code listing
15294:
15295: @cindex @file{engine.s}
15296: To see what assembly code is produced for the primitives on your machine
15297: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15298: look at the resulting file @file{engine.s}. Alternatively, you can also
15299: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15300:
15301: @node Performance, , Primitives, Engine
15302: @section Performance
15303: @cindex performance of some Forth interpreters
15304: @cindex engine performance
15305: @cindex benchmarking Forth systems
15306: @cindex Gforth performance
15307:
15308: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15309: impossible to write a significantly faster threaded-code engine.
1.1 anton 15310:
15311: On register-starved machines like the 386 architecture processors
15312: improvements are possible, because @code{gcc} does not utilize the
15313: registers as well as a human, even with explicit register declarations;
15314: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15315: and hand-tuned it for the 486; this system is 1.19 times faster on the
15316: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15317: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15318: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15319: registers fit in real registers (and we can even afford to use the TOS
15320: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15321: earlier results. And dynamic superinstructions provide another speedup
15322: (but only around a factor 1.2 on the 486).
1.1 anton 15323:
15324: @cindex Win32Forth performance
15325: @cindex NT Forth performance
15326: @cindex eforth performance
15327: @cindex ThisForth performance
15328: @cindex PFE performance
15329: @cindex TILE performance
1.81 anton 15330: The potential advantage of assembly language implementations is not
1.112 anton 15331: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15332: (direct threaded, compiled with @code{gcc-2.95.1} and
15333: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15334: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15335: (with and without peephole (aka pinhole) optimization of the threaded
15336: code); all these systems were written in assembly language. We also
15337: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15338: with @code{gcc-2.6.3} with the default configuration for Linux:
15339: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15340: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15341: employs peephole optimization of the threaded code) and TILE (compiled
15342: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15343: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15344: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15345: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15346: then extended it to run the benchmarks, added the peephole optimizer,
15347: ran the benchmarks and reported the results.
1.40 anton 15348:
1.1 anton 15349: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15350: matrix multiplication come from the Stanford integer benchmarks and have
15351: been translated into Forth by Martin Fraeman; we used the versions
15352: included in the TILE Forth package, but with bigger data set sizes; and
15353: a recursive Fibonacci number computation for benchmarking calling
15354: performance. The following table shows the time taken for the benchmarks
15355: scaled by the time taken by Gforth (in other words, it shows the speedup
15356: factor that Gforth achieved over the other systems).
15357:
15358: @example
1.112 anton 15359: relative Win32- NT eforth This-
15360: time Gforth Forth Forth eforth +opt PFE Forth TILE
15361: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15362: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15363: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15364: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15365: @end example
15366:
1.26 crook 15367: You may be quite surprised by the good performance of Gforth when
15368: compared with systems written in assembly language. One important reason
15369: for the disappointing performance of these other systems is probably
15370: that they are not written optimally for the 486 (e.g., they use the
15371: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15372: but costly method for relocating the Forth image: like @code{cforth}, it
15373: computes the actual addresses at run time, resulting in two address
15374: computations per @code{NEXT} (@pxref{Image File Background}).
15375:
1.1 anton 15376: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15377: explained with the self-imposed restriction of the latter systems to
15378: standard C, which makes efficient threading impossible (however, the
1.4 anton 15379: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15380: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15381: Moreover, current C compilers have a hard time optimizing other aspects
15382: of the ThisForth and the TILE source.
15383:
1.26 crook 15384: The performance of Gforth on 386 architecture processors varies widely
15385: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15386: allocate any of the virtual machine registers into real machine
15387: registers by itself and would not work correctly with explicit register
1.112 anton 15388: declarations, giving a significantly slower engine (on a 486DX2/66
15389: running the Sieve) than the one measured above.
1.1 anton 15390:
1.26 crook 15391: Note that there have been several releases of Win32Forth since the
15392: release presented here, so the results presented above may have little
1.40 anton 15393: predictive value for the performance of Win32Forth today (results for
15394: the current release on an i486DX2/66 are welcome).
1.1 anton 15395:
15396: @cindex @file{Benchres}
1.66 anton 15397: In
15398: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15399: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15400: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15401: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15402: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15403: than the version used here. You can find a newer version of these
15404: measurements at
1.47 crook 15405: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15406: find numbers for Gforth on various machines in @file{Benchres}.
15407:
1.26 crook 15408: @c ******************************************************************
1.113 anton 15409: @c @node Binding to System Library, Cross Compiler, Engine, Top
15410: @c @chapter Binding to System Library
1.13 pazsan 15411:
1.113 anton 15412: @c ****************************************************************
15413: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 15414: @chapter Cross Compiler
1.47 crook 15415: @cindex @file{cross.fs}
15416: @cindex cross-compiler
15417: @cindex metacompiler
15418: @cindex target compiler
1.13 pazsan 15419:
1.46 pazsan 15420: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
15421: mostly written in Forth, including crucial parts like the outer
15422: interpreter and compiler, it needs compiled Forth code to get
15423: started. The cross compiler allows to create new images for other
15424: architectures, even running under another Forth system.
1.13 pazsan 15425:
15426: @menu
1.67 anton 15427: * Using the Cross Compiler::
15428: * How the Cross Compiler Works::
1.13 pazsan 15429: @end menu
15430:
1.21 crook 15431: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 15432: @section Using the Cross Compiler
1.46 pazsan 15433:
15434: The cross compiler uses a language that resembles Forth, but isn't. The
15435: main difference is that you can execute Forth code after definition,
15436: while you usually can't execute the code compiled by cross, because the
15437: code you are compiling is typically for a different computer than the
15438: one you are compiling on.
15439:
1.81 anton 15440: @c anton: This chapter is somewhat different from waht I would expect: I
15441: @c would expect an explanation of the cross language and how to create an
15442: @c application image with it. The section explains some aspects of
15443: @c creating a Gforth kernel.
15444:
1.46 pazsan 15445: The Makefile is already set up to allow you to create kernels for new
15446: architectures with a simple make command. The generic kernels using the
15447: GCC compiled virtual machine are created in the normal build process
15448: with @code{make}. To create a embedded Gforth executable for e.g. the
15449: 8086 processor (running on a DOS machine), type
15450:
15451: @example
15452: make kernl-8086.fi
15453: @end example
15454:
15455: This will use the machine description from the @file{arch/8086}
15456: directory to create a new kernel. A machine file may look like that:
15457:
15458: @example
15459: \ Parameter for target systems 06oct92py
15460:
15461: 4 Constant cell \ cell size in bytes
15462: 2 Constant cell<< \ cell shift to bytes
15463: 5 Constant cell>bit \ cell shift to bits
15464: 8 Constant bits/char \ bits per character
15465: 8 Constant bits/byte \ bits per byte [default: 8]
15466: 8 Constant float \ bytes per float
15467: 8 Constant /maxalign \ maximum alignment in bytes
15468: false Constant bigendian \ byte order
15469: ( true=big, false=little )
15470:
15471: include machpc.fs \ feature list
15472: @end example
15473:
15474: This part is obligatory for the cross compiler itself, the feature list
15475: is used by the kernel to conditionally compile some features in and out,
15476: depending on whether the target supports these features.
15477:
15478: There are some optional features, if you define your own primitives,
15479: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 15480: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 15481: @code{prims-include} includes primitives, and @code{>boot} prepares for
15482: booting.
15483:
15484: @example
15485: : asm-include ." Include assembler" cr
15486: s" arch/8086/asm.fs" included ;
15487:
15488: : prims-include ." Include primitives" cr
15489: s" arch/8086/prim.fs" included ;
15490:
15491: : >boot ." Prepare booting" cr
15492: s" ' boot >body into-forth 1+ !" evaluate ;
15493: @end example
15494:
15495: These words are used as sort of macro during the cross compilation in
1.81 anton 15496: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 15497: be possible --- but more complicated --- to write a new kernel project
15498: file, too.
15499:
15500: @file{kernel/main.fs} expects the machine description file name on the
15501: stack; the cross compiler itself (@file{cross.fs}) assumes that either
15502: @code{mach-file} leaves a counted string on the stack, or
15503: @code{machine-file} leaves an address, count pair of the filename on the
15504: stack.
15505:
15506: The feature list is typically controlled using @code{SetValue}, generic
15507: files that are used by several projects can use @code{DefaultValue}
15508: instead. Both functions work like @code{Value}, when the value isn't
15509: defined, but @code{SetValue} works like @code{to} if the value is
15510: defined, and @code{DefaultValue} doesn't set anything, if the value is
15511: defined.
15512:
15513: @example
15514: \ generic mach file for pc gforth 03sep97jaw
15515:
15516: true DefaultValue NIL \ relocating
15517:
15518: >ENVIRON
15519:
15520: true DefaultValue file \ controls the presence of the
15521: \ file access wordset
15522: true DefaultValue OS \ flag to indicate a operating system
15523:
15524: true DefaultValue prims \ true: primitives are c-code
15525:
15526: true DefaultValue floating \ floating point wordset is present
15527:
15528: true DefaultValue glocals \ gforth locals are present
15529: \ will be loaded
15530: true DefaultValue dcomps \ double number comparisons
15531:
15532: true DefaultValue hash \ hashing primitives are loaded/present
15533:
15534: true DefaultValue xconds \ used together with glocals,
15535: \ special conditionals supporting gforths'
15536: \ local variables
15537: true DefaultValue header \ save a header information
15538:
15539: true DefaultValue backtrace \ enables backtrace code
15540:
15541: false DefaultValue ec
15542: false DefaultValue crlf
15543:
15544: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
15545:
15546: &16 KB DefaultValue stack-size
15547: &15 KB &512 + DefaultValue fstack-size
15548: &15 KB DefaultValue rstack-size
15549: &14 KB &512 + DefaultValue lstack-size
15550: @end example
1.13 pazsan 15551:
1.48 anton 15552: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 15553: @section How the Cross Compiler Works
1.13 pazsan 15554:
15555: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 15556: @appendix Bugs
1.1 anton 15557: @cindex bug reporting
15558:
1.21 crook 15559: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 15560:
1.103 anton 15561: If you find a bug, please submit a bug report through
15562: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 15563:
15564: @itemize @bullet
15565: @item
1.81 anton 15566: A program (or a sequence of keyboard commands) that reproduces the bug.
15567: @item
15568: A description of what you think constitutes the buggy behaviour.
15569: @item
1.21 crook 15570: The Gforth version used (it is announced at the start of an
15571: interactive Gforth session).
15572: @item
15573: The machine and operating system (on Unix
15574: systems @code{uname -a} will report this information).
15575: @item
1.81 anton 15576: The installation options (you can find the configure options at the
15577: start of @file{config.status}) and configuration (@code{configure}
15578: output or @file{config.cache}).
1.21 crook 15579: @item
15580: A complete list of changes (if any) you (or your installer) have made to the
15581: Gforth sources.
15582: @end itemize
1.1 anton 15583:
15584: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
15585: to Report Bugs, gcc.info, GNU C Manual}.
15586:
15587:
1.21 crook 15588: @node Origin, Forth-related information, Bugs, Top
15589: @appendix Authors and Ancestors of Gforth
1.1 anton 15590:
15591: @section Authors and Contributors
15592: @cindex authors of Gforth
15593: @cindex contributors to Gforth
15594:
15595: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 15596: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
15597: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 15598: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
15599: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
15600: and Stuart Ramsden inspired us with their continuous feedback. Lennart
15601: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
15602: working on automatic support for calling C libraries. Helpful comments
15603: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
15604: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
15605: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
15606: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
15607: comments from many others; thank you all, sorry for not listing you
15608: here (but digging through my mailbox to extract your names is on my
15609: to-do list).
1.1 anton 15610:
15611: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
15612: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 15613: was developed across the Internet, and its authors did not meet
1.20 pazsan 15614: physically for the first 4 years of development.
1.1 anton 15615:
15616: @section Pedigree
1.26 crook 15617: @cindex pedigree of Gforth
1.1 anton 15618:
1.81 anton 15619: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
15620: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 15621:
1.20 pazsan 15622: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 15623: 32 bit native code version of VolksForth for the Atari ST, written
15624: mostly by Dietrich Weineck.
15625:
1.81 anton 15626: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
15627: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 15628: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 15629:
1.147 anton 15630: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
15631: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 15632:
15633: A team led by Bill Ragsdale implemented fig-Forth on many processors in
15634: 1979. Robert Selzer and Bill Ragsdale developed the original
15635: implementation of fig-Forth for the 6502 based on microForth.
15636:
15637: The principal architect of microForth was Dean Sanderson. microForth was
15638: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
15639: the 1802, and subsequently implemented on the 8080, the 6800 and the
15640: Z80.
15641:
15642: All earlier Forth systems were custom-made, usually by Charles Moore,
15643: who discovered (as he puts it) Forth during the late 60s. The first full
15644: Forth existed in 1971.
15645:
1.81 anton 15646: A part of the information in this section comes from
15647: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
15648: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 15649: Charles H. Moore, presented at the HOPL-II conference and preprinted
15650: in SIGPLAN Notices 28(3), 1993. You can find more historical and
15651: genealogical information about Forth there. For a more general (and
15652: graphical) Forth family tree look see
15653: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
15654: Forth Family Tree and Timeline}.
1.1 anton 15655:
1.81 anton 15656: @c ------------------------------------------------------------------
1.113 anton 15657: @node Forth-related information, Licenses, Origin, Top
1.21 crook 15658: @appendix Other Forth-related information
15659: @cindex Forth-related information
15660:
1.81 anton 15661: @c anton: I threw most of this stuff out, because it can be found through
15662: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 15663:
15664: @cindex comp.lang.forth
15665: @cindex frequently asked questions
1.81 anton 15666: There is an active news group (comp.lang.forth) discussing Forth
15667: (including Gforth) and Forth-related issues. Its
15668: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
15669: (frequently asked questions and their answers) contains a lot of
15670: information on Forth. You should read it before posting to
15671: comp.lang.forth.
1.21 crook 15672:
1.81 anton 15673: The ANS Forth standard is most usable in its
15674: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 15675:
1.113 anton 15676: @c ---------------------------------------------------
15677: @node Licenses, Word Index, Forth-related information, Top
15678: @appendix Licenses
15679:
15680: @menu
15681: * GNU Free Documentation License:: License for copying this manual.
15682: * Copying:: GPL (for copying this software).
15683: @end menu
15684:
15685: @include fdl.texi
15686:
15687: @include gpl.texi
15688:
15689:
15690:
1.81 anton 15691: @c ------------------------------------------------------------------
1.113 anton 15692: @node Word Index, Concept Index, Licenses, Top
1.1 anton 15693: @unnumbered Word Index
15694:
1.26 crook 15695: This index is a list of Forth words that have ``glossary'' entries
15696: within this manual. Each word is listed with its stack effect and
15697: wordset.
1.1 anton 15698:
15699: @printindex fn
15700:
1.81 anton 15701: @c anton: the name index seems superfluous given the word and concept indices.
15702:
15703: @c @node Name Index, Concept Index, Word Index, Top
15704: @c @unnumbered Name Index
1.41 anton 15705:
1.81 anton 15706: @c This index is a list of Forth words that have ``glossary'' entries
15707: @c within this manual.
1.41 anton 15708:
1.81 anton 15709: @c @printindex ky
1.41 anton 15710:
1.113 anton 15711: @c -------------------------------------------------------
1.81 anton 15712: @node Concept Index, , Word Index, Top
1.1 anton 15713: @unnumbered Concept and Word Index
15714:
1.26 crook 15715: Not all entries listed in this index are present verbatim in the
15716: text. This index also duplicates, in abbreviated form, all of the words
15717: listed in the Word Index (only the names are listed for the words here).
1.1 anton 15718:
15719: @printindex cp
15720:
15721: @bye
1.81 anton 15722:
15723:
1.1 anton 15724:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>