Annotation of gforth/doc/gforth.ds, revision 1.194
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.191 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007 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.190 anton 177: * Floating Point Tutorial::
1.87 anton 178: * Files Tutorial::
1.48 anton 179: * Interpretation and Compilation Semantics and Immediacy Tutorial::
180: * Execution Tokens Tutorial::
181: * Exceptions Tutorial::
182: * Defining Words Tutorial::
183: * Arrays and Records Tutorial::
184: * POSTPONE Tutorial::
185: * Literal Tutorial::
186: * Advanced macros Tutorial::
187: * Compilation Tokens Tutorial::
188: * Wordlists and Search Order Tutorial::
1.29 crook 189:
1.24 anton 190: An Introduction to ANS Forth
191:
1.67 anton 192: * Introducing the Text Interpreter::
193: * Stacks and Postfix notation::
194: * Your first definition::
195: * How does that work?::
196: * Forth is written in Forth::
197: * Review - elements of a Forth system::
198: * Where to go next::
199: * Exercises::
1.24 anton 200:
1.12 anton 201: Forth Words
202:
203: * Notation::
1.65 anton 204: * Case insensitivity::
205: * Comments::
206: * Boolean Flags::
1.12 anton 207: * Arithmetic::
208: * Stack Manipulation::
209: * Memory::
210: * Control Structures::
211: * Defining Words::
1.65 anton 212: * Interpretation and Compilation Semantics::
1.47 crook 213: * Tokens for Words::
1.81 anton 214: * Compiling words::
1.65 anton 215: * The Text Interpreter::
1.111 anton 216: * The Input Stream::
1.65 anton 217: * Word Lists::
218: * Environmental Queries::
1.12 anton 219: * Files::
220: * Blocks::
221: * Other I/O::
1.121 anton 222: * OS command line arguments::
1.78 anton 223: * Locals::
224: * Structures::
225: * Object-oriented Forth::
1.12 anton 226: * Programming Tools::
1.150 anton 227: * C Interface::
1.12 anton 228: * Assembler and Code Words::
229: * Threading Words::
1.65 anton 230: * Passing Commands to the OS::
231: * Keeping track of Time::
232: * Miscellaneous Words::
1.12 anton 233:
234: Arithmetic
235:
236: * Single precision::
1.67 anton 237: * Double precision:: Double-cell integer arithmetic
1.12 anton 238: * Bitwise operations::
1.67 anton 239: * Numeric comparison::
1.32 anton 240: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 241: * Floating Point::
242:
243: Stack Manipulation
244:
245: * Data stack::
246: * Floating point stack::
247: * Return stack::
248: * Locals stack::
249: * Stack pointer manipulation::
250:
251: Memory
252:
1.32 anton 253: * Memory model::
254: * Dictionary allocation::
255: * Heap Allocation::
256: * Memory Access::
257: * Address arithmetic::
258: * Memory Blocks::
1.12 anton 259:
260: Control Structures
261:
1.41 anton 262: * Selection:: IF ... ELSE ... ENDIF
263: * Simple Loops:: BEGIN ...
1.32 anton 264: * Counted Loops:: DO
1.67 anton 265: * Arbitrary control structures::
266: * Calls and returns::
1.12 anton 267: * Exception Handling::
268:
269: Defining Words
270:
1.67 anton 271: * CREATE::
1.44 crook 272: * Variables:: Variables and user variables
1.67 anton 273: * Constants::
1.44 crook 274: * Values:: Initialised variables
1.67 anton 275: * Colon Definitions::
1.44 crook 276: * Anonymous Definitions:: Definitions without names
1.71 anton 277: * Supplying names:: Passing definition names as strings
1.67 anton 278: * User-defined Defining Words::
1.170 pazsan 279: * Deferred Words:: Allow forward references
1.67 anton 280: * Aliases::
1.47 crook 281:
1.63 anton 282: User-defined Defining Words
283:
284: * CREATE..DOES> applications::
285: * CREATE..DOES> details::
286: * Advanced does> usage example::
1.155 anton 287: * Const-does>::
1.63 anton 288:
1.47 crook 289: Interpretation and Compilation Semantics
290:
1.67 anton 291: * Combined words::
1.12 anton 292:
1.71 anton 293: Tokens for Words
294:
295: * Execution token:: represents execution/interpretation semantics
296: * Compilation token:: represents compilation semantics
297: * Name token:: represents named words
298:
1.82 anton 299: Compiling words
300:
301: * Literals:: Compiling data values
302: * Macros:: Compiling words
303:
1.21 crook 304: The Text Interpreter
305:
1.67 anton 306: * Input Sources::
307: * Number Conversion::
308: * Interpret/Compile states::
309: * Interpreter Directives::
1.21 crook 310:
1.26 crook 311: Word Lists
312:
1.75 anton 313: * Vocabularies::
1.67 anton 314: * Why use word lists?::
1.75 anton 315: * Word list example::
1.26 crook 316:
317: Files
318:
1.48 anton 319: * Forth source files::
320: * General files::
1.167 anton 321: * Redirection::
1.48 anton 322: * Search Paths::
323:
324: Search Paths
325:
1.75 anton 326: * Source Search Paths::
1.26 crook 327: * General Search Paths::
328:
329: Other I/O
330:
1.32 anton 331: * Simple numeric output:: Predefined formats
332: * Formatted numeric output:: Formatted (pictured) output
333: * String Formats:: How Forth stores strings in memory
1.67 anton 334: * Displaying characters and strings:: Other stuff
1.178 anton 335: * Terminal output:: Cursor positioning etc.
1.181 anton 336: * Single-key input::
337: * Line input and conversion::
1.112 anton 338: * Pipes:: How to create your own pipes
1.149 pazsan 339: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 340:
341: Locals
342:
343: * Gforth locals::
344: * ANS Forth locals::
345:
346: Gforth locals
347:
348: * Where are locals visible by name?::
349: * How long do locals live?::
1.78 anton 350: * Locals programming style::
351: * Locals implementation::
1.26 crook 352:
1.12 anton 353: Structures
354:
355: * Why explicit structure support?::
356: * Structure Usage::
357: * Structure Naming Convention::
358: * Structure Implementation::
359: * Structure Glossary::
1.183 anton 360: * Forth200x Structures::
1.12 anton 361:
362: Object-oriented Forth
363:
1.48 anton 364: * Why object-oriented programming?::
365: * Object-Oriented Terminology::
366: * Objects::
367: * OOF::
368: * Mini-OOF::
1.23 crook 369: * Comparison with other object models::
1.12 anton 370:
1.24 anton 371: The @file{objects.fs} model
1.12 anton 372:
373: * Properties of the Objects model::
374: * Basic Objects Usage::
1.41 anton 375: * The Objects base class::
1.12 anton 376: * Creating objects::
377: * Object-Oriented Programming Style::
378: * Class Binding::
379: * Method conveniences::
380: * Classes and Scoping::
1.41 anton 381: * Dividing classes::
1.12 anton 382: * Object Interfaces::
383: * Objects Implementation::
384: * Objects Glossary::
385:
1.24 anton 386: The @file{oof.fs} model
1.12 anton 387:
1.67 anton 388: * Properties of the OOF model::
389: * Basic OOF Usage::
390: * The OOF base class::
391: * Class Declaration::
392: * Class Implementation::
1.12 anton 393:
1.24 anton 394: The @file{mini-oof.fs} model
1.23 crook 395:
1.48 anton 396: * Basic Mini-OOF Usage::
397: * Mini-OOF Example::
398: * Mini-OOF Implementation::
1.23 crook 399:
1.78 anton 400: Programming Tools
401:
1.150 anton 402: * Examining:: Data and Code.
403: * Forgetting words:: Usually before reloading.
1.78 anton 404: * Debugging:: Simple and quick.
405: * Assertions:: Making your programs self-checking.
406: * Singlestep Debugger:: Executing your program word by word.
407:
1.155 anton 408: C Interface
409:
410: * Calling C Functions::
411: * Declaring C Functions::
1.180 anton 412: * Calling C function pointers::
1.155 anton 413: * Callbacks::
1.178 anton 414: * C interface internals::
1.155 anton 415: * Low-Level C Interface Words::
416:
1.78 anton 417: Assembler and Code Words
418:
419: * Code and ;code::
420: * Common Assembler:: Assembler Syntax
421: * Common Disassembler::
422: * 386 Assembler:: Deviations and special cases
423: * Alpha Assembler:: Deviations and special cases
424: * MIPS assembler:: Deviations and special cases
1.167 anton 425: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 426: * ARM Assembler:: Deviations and special cases
1.78 anton 427: * Other assemblers:: How to write them
428:
1.12 anton 429: Tools
430:
431: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 432: * Stack depth changes:: Where does this stack item come from?
1.12 anton 433:
434: ANS conformance
435:
436: * The Core Words::
437: * The optional Block word set::
438: * The optional Double Number word set::
439: * The optional Exception word set::
440: * The optional Facility word set::
441: * The optional File-Access word set::
442: * The optional Floating-Point word set::
443: * The optional Locals word set::
444: * The optional Memory-Allocation word set::
445: * The optional Programming-Tools word set::
446: * The optional Search-Order word set::
447:
448: The Core Words
449:
450: * core-idef:: Implementation Defined Options
451: * core-ambcond:: Ambiguous Conditions
452: * core-other:: Other System Documentation
453:
454: The optional Block word set
455:
456: * block-idef:: Implementation Defined Options
457: * block-ambcond:: Ambiguous Conditions
458: * block-other:: Other System Documentation
459:
460: The optional Double Number word set
461:
462: * double-ambcond:: Ambiguous Conditions
463:
464: The optional Exception word set
465:
466: * exception-idef:: Implementation Defined Options
467:
468: The optional Facility word set
469:
470: * facility-idef:: Implementation Defined Options
471: * facility-ambcond:: Ambiguous Conditions
472:
473: The optional File-Access word set
474:
475: * file-idef:: Implementation Defined Options
476: * file-ambcond:: Ambiguous Conditions
477:
478: The optional Floating-Point word set
479:
480: * floating-idef:: Implementation Defined Options
481: * floating-ambcond:: Ambiguous Conditions
482:
483: The optional Locals word set
484:
485: * locals-idef:: Implementation Defined Options
486: * locals-ambcond:: Ambiguous Conditions
487:
488: The optional Memory-Allocation word set
489:
490: * memory-idef:: Implementation Defined Options
491:
492: The optional Programming-Tools word set
493:
494: * programming-idef:: Implementation Defined Options
495: * programming-ambcond:: Ambiguous Conditions
496:
497: The optional Search-Order word set
498:
499: * search-idef:: Implementation Defined Options
500: * search-ambcond:: Ambiguous Conditions
501:
1.109 anton 502: Emacs and Gforth
503:
504: * Installing gforth.el:: Making Emacs aware of Forth.
505: * Emacs Tags:: Viewing the source of a word in Emacs.
506: * Hilighting:: Making Forth code look prettier.
507: * Auto-Indentation:: Customizing auto-indentation.
508: * Blocks Files:: Reading and writing blocks files.
509:
1.12 anton 510: Image Files
511:
1.24 anton 512: * Image Licensing Issues:: Distribution terms for images.
513: * Image File Background:: Why have image files?
1.67 anton 514: * Non-Relocatable Image Files:: don't always work.
1.24 anton 515: * Data-Relocatable Image Files:: are better.
1.67 anton 516: * Fully Relocatable Image Files:: better yet.
1.24 anton 517: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 518: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 519: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 520:
521: Fully Relocatable Image Files
522:
1.27 crook 523: * gforthmi:: The normal way
1.12 anton 524: * cross.fs:: The hard way
525:
526: Engine
527:
528: * Portability::
529: * Threading::
530: * Primitives::
531: * Performance::
532:
533: Threading
534:
535: * Scheduling::
536: * Direct or Indirect Threaded?::
1.109 anton 537: * Dynamic Superinstructions::
1.12 anton 538: * DOES>::
539:
540: Primitives
541:
542: * Automatic Generation::
543: * TOS Optimization::
544: * Produced code::
1.13 pazsan 545:
546: Cross Compiler
547:
1.67 anton 548: * Using the Cross Compiler::
549: * How the Cross Compiler Works::
1.13 pazsan 550:
1.113 anton 551: Licenses
552:
553: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 554: * Copying:: GPL (for copying this software).
1.113 anton 555:
1.24 anton 556: @end detailmenu
1.1 anton 557: @end menu
558:
1.113 anton 559: @c ----------------------------------------------------------
1.1 anton 560: @iftex
561: @unnumbered Preface
562: @cindex Preface
1.21 crook 563: This manual documents Gforth. Some introductory material is provided for
564: readers who are unfamiliar with Forth or who are migrating to Gforth
565: from other Forth compilers. However, this manual is primarily a
566: reference manual.
1.1 anton 567: @end iftex
568:
1.28 crook 569: @comment TODO much more blurb here.
1.26 crook 570:
571: @c ******************************************************************
1.113 anton 572: @node Goals, Gforth Environment, Top, Top
1.26 crook 573: @comment node-name, next, previous, up
574: @chapter Goals of Gforth
575: @cindex goals of the Gforth project
576: The goal of the Gforth Project is to develop a standard model for
577: ANS Forth. This can be split into several subgoals:
578:
579: @itemize @bullet
580: @item
581: Gforth should conform to the ANS Forth Standard.
582: @item
583: It should be a model, i.e. it should define all the
584: implementation-dependent things.
585: @item
586: It should become standard, i.e. widely accepted and used. This goal
587: is the most difficult one.
588: @end itemize
589:
590: To achieve these goals Gforth should be
591: @itemize @bullet
592: @item
593: Similar to previous models (fig-Forth, F83)
594: @item
595: Powerful. It should provide for all the things that are considered
596: necessary today and even some that are not yet considered necessary.
597: @item
598: Efficient. It should not get the reputation of being exceptionally
599: slow.
600: @item
601: Free.
602: @item
603: Available on many machines/easy to port.
604: @end itemize
605:
606: Have we achieved these goals? Gforth conforms to the ANS Forth
607: standard. It may be considered a model, but we have not yet documented
608: which parts of the model are stable and which parts we are likely to
609: change. It certainly has not yet become a de facto standard, but it
610: appears to be quite popular. It has some similarities to and some
611: differences from previous models. It has some powerful features, but not
612: yet everything that we envisioned. We certainly have achieved our
1.65 anton 613: execution speed goals (@pxref{Performance})@footnote{However, in 1998
614: the bar was raised when the major commercial Forth vendors switched to
615: native code compilers.}. It is free and available on many machines.
1.29 crook 616:
1.26 crook 617: @c ******************************************************************
1.48 anton 618: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 619: @chapter Gforth Environment
620: @cindex Gforth environment
1.21 crook 621:
1.45 crook 622: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 623: material in this chapter.
1.21 crook 624:
625: @menu
1.29 crook 626: * Invoking Gforth:: Getting in
627: * Leaving Gforth:: Getting out
628: * Command-line editing::
1.48 anton 629: * Environment variables:: that affect how Gforth starts up
1.29 crook 630: * Gforth Files:: What gets installed and where
1.112 anton 631: * Gforth in pipes::
1.48 anton 632: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 633: @end menu
634:
1.49 anton 635: For related information about the creation of images see @ref{Image Files}.
1.29 crook 636:
1.21 crook 637: @comment ----------------------------------------------
1.48 anton 638: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 639: @section Invoking Gforth
640: @cindex invoking Gforth
641: @cindex running Gforth
642: @cindex command-line options
643: @cindex options on the command line
644: @cindex flags on the command line
1.21 crook 645:
1.30 anton 646: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 647: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 648: will usually just say @code{gforth} -- this automatically loads the
649: default image file @file{gforth.fi}. In many other cases the default
650: Gforth image will be invoked like this:
1.21 crook 651: @example
1.30 anton 652: gforth [file | -e forth-code] ...
1.21 crook 653: @end example
1.29 crook 654: @noindent
655: This interprets the contents of the files and the Forth code in the order they
656: are given.
1.21 crook 657:
1.109 anton 658: In addition to the @command{gforth} engine, there is also an engine
659: called @command{gforth-fast}, which is faster, but gives less
660: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 661: errors (in particular, stack underflows and integer division errors)
662: later or not at all. You should use it for debugged,
1.109 anton 663: performance-critical programs.
664:
665: Moreover, there is an engine called @command{gforth-itc}, which is
666: useful in some backwards-compatibility situations (@pxref{Direct or
667: Indirect Threaded?}).
1.30 anton 668:
1.29 crook 669: In general, the command line looks like this:
1.21 crook 670:
671: @example
1.30 anton 672: gforth[-fast] [engine options] [image options]
1.21 crook 673: @end example
674:
1.30 anton 675: The engine options must come before the rest of the command
1.29 crook 676: line. They are:
1.26 crook 677:
1.29 crook 678: @table @code
679: @cindex -i, command-line option
680: @cindex --image-file, command-line option
681: @item --image-file @i{file}
682: @itemx -i @i{file}
683: Loads the Forth image @i{file} instead of the default
684: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 685:
1.39 anton 686: @cindex --appl-image, command-line option
687: @item --appl-image @i{file}
688: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 689: to the image (instead of processing them as engine options). This is
690: useful for building executable application images on Unix, built with
1.39 anton 691: @code{gforthmi --application ...}.
692:
1.29 crook 693: @cindex --path, command-line option
694: @cindex -p, command-line option
695: @item --path @i{path}
696: @itemx -p @i{path}
697: Uses @i{path} for searching the image file and Forth source code files
698: instead of the default in the environment variable @code{GFORTHPATH} or
699: the path specified at installation time (e.g.,
700: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
701: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 702:
1.29 crook 703: @cindex --dictionary-size, command-line option
704: @cindex -m, command-line option
705: @cindex @i{size} parameters for command-line options
706: @cindex size of the dictionary and the stacks
707: @item --dictionary-size @i{size}
708: @itemx -m @i{size}
709: Allocate @i{size} space for the Forth dictionary space instead of
710: using the default specified in the image (typically 256K). The
711: @i{size} specification for this and subsequent options consists of
712: an integer and a unit (e.g.,
713: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
714: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
715: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
716: @code{e} is used.
1.21 crook 717:
1.29 crook 718: @cindex --data-stack-size, command-line option
719: @cindex -d, command-line option
720: @item --data-stack-size @i{size}
721: @itemx -d @i{size}
722: Allocate @i{size} space for the data stack instead of using the
723: default specified in the image (typically 16K).
1.21 crook 724:
1.29 crook 725: @cindex --return-stack-size, command-line option
726: @cindex -r, command-line option
727: @item --return-stack-size @i{size}
728: @itemx -r @i{size}
729: Allocate @i{size} space for the return stack instead of using the
730: default specified in the image (typically 15K).
1.21 crook 731:
1.29 crook 732: @cindex --fp-stack-size, command-line option
733: @cindex -f, command-line option
734: @item --fp-stack-size @i{size}
735: @itemx -f @i{size}
736: Allocate @i{size} space for the floating point stack instead of
737: using the default specified in the image (typically 15.5K). In this case
738: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 739:
1.48 anton 740: @cindex --locals-stack-size, command-line option
741: @cindex -l, command-line option
742: @item --locals-stack-size @i{size}
743: @itemx -l @i{size}
744: Allocate @i{size} space for the locals stack instead of using the
745: default specified in the image (typically 14.5K).
746:
1.176 anton 747: @cindex --vm-commit, command-line option
748: @cindex overcommit memory for dictionary and stacks
749: @cindex memory overcommit for dictionary and stacks
750: @item --vm-commit
751: Normally, Gforth tries to start up even if there is not enough virtual
752: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
753: on OSs that support it); so you can ask for a really big dictionary
754: and/or stacks, and as long as you don't use more virtual memory than
755: is available, everything will be fine (but if you use more, processes
756: get killed). With this option you just use the default allocation
757: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
758: means that you cannot and should not ask for as big dictionary and
759: stacks, but once Gforth successfully starts up, out-of-memory won't
760: kill it.
761:
1.48 anton 762: @cindex -h, command-line option
763: @cindex --help, command-line option
764: @item --help
765: @itemx -h
766: Print a message about the command-line options
767:
768: @cindex -v, command-line option
769: @cindex --version, command-line option
770: @item --version
771: @itemx -v
772: Print version and exit
773:
774: @cindex --debug, command-line option
775: @item --debug
776: Print some information useful for debugging on startup.
777:
778: @cindex --offset-image, command-line option
779: @item --offset-image
780: Start the dictionary at a slightly different position than would be used
781: otherwise (useful for creating data-relocatable images,
782: @pxref{Data-Relocatable Image Files}).
783:
784: @cindex --no-offset-im, command-line option
785: @item --no-offset-im
786: Start the dictionary at the normal position.
787:
788: @cindex --clear-dictionary, command-line option
789: @item --clear-dictionary
790: Initialize all bytes in the dictionary to 0 before loading the image
791: (@pxref{Data-Relocatable Image Files}).
792:
793: @cindex --die-on-signal, command-line-option
794: @item --die-on-signal
795: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
796: or the segmentation violation SIGSEGV) by translating it into a Forth
797: @code{THROW}. With this option, Gforth exits if it receives such a
798: signal. This option is useful when the engine and/or the image might be
799: severely broken (such that it causes another signal before recovering
800: from the first); this option avoids endless loops in such cases.
1.109 anton 801:
1.119 anton 802: @cindex --no-dynamic, command-line option
803: @cindex --dynamic, command-line option
1.109 anton 804: @item --no-dynamic
805: @item --dynamic
806: Disable or enable dynamic superinstructions with replication
807: (@pxref{Dynamic Superinstructions}).
808:
1.119 anton 809: @cindex --no-super, command-line option
1.109 anton 810: @item --no-super
1.110 anton 811: Disable dynamic superinstructions, use just dynamic replication; this is
812: useful if you want to patch threaded code (@pxref{Dynamic
813: Superinstructions}).
1.119 anton 814:
815: @cindex --ss-number, command-line option
816: @item --ss-number=@var{N}
817: Use only the first @var{N} static superinstructions compiled into the
818: engine (default: use them all; note that only @code{gforth-fast} has
819: any). This option is useful for measuring the performance impact of
820: static superinstructions.
821:
822: @cindex --ss-min-..., command-line options
823: @item --ss-min-codesize
824: @item --ss-min-ls
825: @item --ss-min-lsu
826: @item --ss-min-nexts
827: Use specified metric for determining the cost of a primitive or static
828: superinstruction for static superinstruction selection. @code{Codesize}
829: is the native code size of the primive or static superinstruction,
830: @code{ls} is the number of loads and stores, @code{lsu} is the number of
831: loads, stores, and updates, and @code{nexts} is the number of dispatches
832: (not taking dynamic superinstructions into account), i.e. every
833: primitive or static superinstruction has cost 1. Default:
834: @code{codesize} if you use dynamic code generation, otherwise
835: @code{nexts}.
836:
837: @cindex --ss-greedy, command-line option
838: @item --ss-greedy
839: This option is useful for measuring the performance impact of static
840: superinstructions. By default, an optimal shortest-path algorithm is
841: used for selecting static superinstructions. With @option{--ss-greedy}
842: this algorithm is modified to assume that anything after the static
843: superinstruction currently under consideration is not combined into
844: static superinstructions. With @option{--ss-min-nexts} this produces
845: the same result as a greedy algorithm that always selects the longest
846: superinstruction available at the moment. E.g., if there are
847: superinstructions AB and BCD, then for the sequence A B C D the optimal
848: algorithm will select A BCD and the greedy algorithm will select AB C D.
849:
850: @cindex --print-metrics, command-line option
851: @item --print-metrics
852: Prints some metrics used during static superinstruction selection:
853: @code{code size} is the actual size of the dynamically generated code.
854: @code{Metric codesize} is the sum of the codesize metrics as seen by
855: static superinstruction selection; there is a difference from @code{code
856: size}, because not all primitives and static superinstructions are
857: compiled into dynamically generated code, and because of markers. The
858: other metrics correspond to the @option{ss-min-...} options. This
859: option is useful for evaluating the effects of the @option{--ss-...}
860: options.
1.109 anton 861:
1.48 anton 862: @end table
863:
864: @cindex loading files at startup
865: @cindex executing code on startup
866: @cindex batch processing with Gforth
867: As explained above, the image-specific command-line arguments for the
868: default image @file{gforth.fi} consist of a sequence of filenames and
869: @code{-e @var{forth-code}} options that are interpreted in the sequence
870: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 871: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
872: option takes only one argument; if you want to evaluate more Forth
873: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 874: after processing the command line (instead of entering interactive mode)
1.121 anton 875: append @code{-e bye} to the command line. You can also process the
876: command-line arguments with a Forth program (@pxref{OS command line
877: arguments}).
1.48 anton 878:
879: @cindex versions, invoking other versions of Gforth
880: If you have several versions of Gforth installed, @code{gforth} will
881: invoke the version that was installed last. @code{gforth-@i{version}}
882: invokes a specific version. If your environment contains the variable
883: @code{GFORTHPATH}, you may want to override it by using the
884: @code{--path} option.
885:
886: Not yet implemented:
887: On startup the system first executes the system initialization file
888: (unless the option @code{--no-init-file} is given; note that the system
889: resulting from using this option may not be ANS Forth conformant). Then
890: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 891: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 892: then in @file{~}, then in the normal path (see above).
893:
894:
895:
896: @comment ----------------------------------------------
897: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
898: @section Leaving Gforth
899: @cindex Gforth - leaving
900: @cindex leaving Gforth
901:
902: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
903: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
904: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 905: data are discarded. For ways of saving the state of the system before
906: leaving Gforth see @ref{Image Files}.
1.48 anton 907:
908: doc-bye
909:
910:
911: @comment ----------------------------------------------
1.65 anton 912: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 913: @section Command-line editing
914: @cindex command-line editing
915:
916: Gforth maintains a history file that records every line that you type to
917: the text interpreter. This file is preserved between sessions, and is
918: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
919: repeatedly you can recall successively older commands from this (or
920: previous) session(s). The full list of command-line editing facilities is:
921:
922: @itemize @bullet
923: @item
924: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
925: commands from the history buffer.
926: @item
927: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
928: from the history buffer.
929: @item
930: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
931: @item
932: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
933: @item
934: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
935: closing up the line.
936: @item
937: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
938: @item
939: @kbd{Ctrl-a} to move the cursor to the start of the line.
940: @item
941: @kbd{Ctrl-e} to move the cursor to the end of the line.
942: @item
943: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
944: line.
945: @item
946: @key{TAB} to step through all possible full-word completions of the word
947: currently being typed.
948: @item
1.65 anton 949: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
950: using @code{bye}).
951: @item
952: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
953: character under the cursor.
1.48 anton 954: @end itemize
955:
956: When editing, displayable characters are inserted to the left of the
957: cursor position; the line is always in ``insert'' (as opposed to
958: ``overstrike'') mode.
959:
960: @cindex history file
961: @cindex @file{.gforth-history}
962: On Unix systems, the history file is @file{~/.gforth-history} by
963: default@footnote{i.e. it is stored in the user's home directory.}. You
964: can find out the name and location of your history file using:
965:
966: @example
967: history-file type \ Unix-class systems
968:
969: history-file type \ Other systems
970: history-dir type
971: @end example
972:
973: If you enter long definitions by hand, you can use a text editor to
974: paste them out of the history file into a Forth source file for reuse at
975: a later time.
976:
977: Gforth never trims the size of the history file, so you should do this
978: periodically, if necessary.
979:
980: @comment this is all defined in history.fs
981: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
982: @comment chosen?
983:
984:
985: @comment ----------------------------------------------
1.65 anton 986: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 987: @section Environment variables
988: @cindex environment variables
989:
990: Gforth uses these environment variables:
991:
992: @itemize @bullet
993: @item
994: @cindex @code{GFORTHHIST} -- environment variable
995: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
996: open/create the history file, @file{.gforth-history}. Default:
997: @code{$HOME}.
998:
999: @item
1000: @cindex @code{GFORTHPATH} -- environment variable
1001: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1002: for Forth source-code files.
1003:
1004: @item
1.147 anton 1005: @cindex @code{LANG} -- environment variable
1006: @code{LANG} -- see @code{LC_CTYPE}
1007:
1008: @item
1009: @cindex @code{LC_ALL} -- environment variable
1010: @code{LC_ALL} -- see @code{LC_CTYPE}
1011:
1012: @item
1013: @cindex @code{LC_CTYPE} -- environment variable
1014: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1015: startup, Gforth uses the UTF-8 encoding for strings internally and
1016: expects its input and produces its output in UTF-8 encoding, otherwise
1017: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1018: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1019: that is unset, in @code{LANG}.
1020:
1021: @item
1.129 anton 1022: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1023:
1024: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1025: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1026: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1027: and the command are directly concatenated, so if a space between them is
1028: necessary, append it to the prefix.
1029:
1030: @item
1.48 anton 1031: @cindex @code{GFORTH} -- environment variable
1.49 anton 1032: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1033:
1034: @item
1035: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1036: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1037:
1038: @item
1039: @cindex @code{TMP}, @code{TEMP} - environment variable
1040: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1041: location for the history file.
1042: @end itemize
1043:
1044: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1045: @comment mentioning these.
1046:
1047: All the Gforth environment variables default to sensible values if they
1048: are not set.
1049:
1050:
1051: @comment ----------------------------------------------
1.112 anton 1052: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1053: @section Gforth files
1054: @cindex Gforth files
1055:
1056: When you install Gforth on a Unix system, it installs files in these
1057: locations by default:
1058:
1059: @itemize @bullet
1060: @item
1061: @file{/usr/local/bin/gforth}
1062: @item
1063: @file{/usr/local/bin/gforthmi}
1064: @item
1065: @file{/usr/local/man/man1/gforth.1} - man page.
1066: @item
1067: @file{/usr/local/info} - the Info version of this manual.
1068: @item
1069: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1070: @item
1071: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1072: @item
1073: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1074: @item
1075: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1076: @end itemize
1077:
1078: You can select different places for installation by using
1079: @code{configure} options (listed with @code{configure --help}).
1080:
1081: @comment ----------------------------------------------
1.112 anton 1082: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1083: @section Gforth in pipes
1084: @cindex pipes, Gforth as part of
1085:
1086: Gforth can be used in pipes created elsewhere (described here). It can
1087: also create pipes on its own (@pxref{Pipes}).
1088:
1089: @cindex input from pipes
1090: If you pipe into Gforth, your program should read with @code{read-file}
1091: or @code{read-line} from @code{stdin} (@pxref{General files}).
1092: @code{Key} does not recognize the end of input. Words like
1093: @code{accept} echo the input and are therefore usually not useful for
1094: reading from a pipe. You have to invoke the Forth program with an OS
1095: command-line option, as you have no chance to use the Forth command line
1096: (the text interpreter would try to interpret the pipe input).
1097:
1098: @cindex output in pipes
1099: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1100:
1101: @cindex silent exiting from Gforth
1102: When you write to a pipe that has been closed at the other end, Gforth
1103: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1104: into the exception @code{broken-pipe-error}. If your application does
1105: not catch that exception, the system catches it and exits, usually
1106: silently (unless you were working on the Forth command line; then it
1107: prints an error message and exits). This is usually the desired
1108: behaviour.
1109:
1110: If you do not like this behaviour, you have to catch the exception
1111: yourself, and react to it.
1112:
1113: Here's an example of an invocation of Gforth that is usable in a pipe:
1114:
1115: @example
1116: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1117: type repeat ; foo bye"
1118: @end example
1119:
1120: This example just copies the input verbatim to the output. A very
1121: simple pipe containing this example looks like this:
1122:
1123: @example
1124: cat startup.fs |
1125: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1126: type repeat ; foo bye"|
1127: head
1128: @end example
1129:
1130: @cindex stderr and pipes
1131: Pipes involving Gforth's @code{stderr} output do not work.
1132:
1133: @comment ----------------------------------------------
1134: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1135: @section Startup speed
1136: @cindex Startup speed
1137: @cindex speed, startup
1138:
1139: If Gforth is used for CGI scripts or in shell scripts, its startup
1140: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1141: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1142: system time.
1143:
1144: If startup speed is a problem, you may consider the following ways to
1145: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1146: (for example, by using Fast-CGI).
1.48 anton 1147:
1.112 anton 1148: An easy step that influences Gforth startup speed is the use of the
1149: @option{--no-dynamic} option; this decreases image loading speed, but
1150: increases compile-time and run-time.
1151:
1152: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1153: building it with @code{XLDFLAGS=-static}. This requires more memory for
1154: the code and will therefore slow down the first invocation, but
1155: subsequent invocations avoid the dynamic linking overhead. Another
1156: disadvantage is that Gforth won't profit from library upgrades. As a
1157: result, @code{gforth-static -e bye} takes about 17.1ms user and
1158: 8.2ms system time.
1159:
1160: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1161: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1162: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1163: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1164: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1165: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1166: address for the dictionary, for whatever reason; so you better provide a
1167: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1168: bye} takes about 15.3ms user and 7.5ms system time.
1169:
1170: The final step is to disable dictionary hashing in Gforth. Gforth
1171: builds the hash table on startup, which takes much of the startup
1172: overhead. You can do this by commenting out the @code{include hash.fs}
1173: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1174: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1175: The disadvantages are that functionality like @code{table} and
1176: @code{ekey} is missing and that text interpretation (e.g., compiling)
1177: now takes much longer. So, you should only use this method if there is
1178: no significant text interpretation to perform (the script should be
1.62 crook 1179: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1180: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1181:
1182: @c ******************************************************************
1183: @node Tutorial, Introduction, Gforth Environment, Top
1184: @chapter Forth Tutorial
1185: @cindex Tutorial
1186: @cindex Forth Tutorial
1187:
1.67 anton 1188: @c Topics from nac's Introduction that could be mentioned:
1189: @c press <ret> after each line
1190: @c Prompt
1191: @c numbers vs. words in dictionary on text interpretation
1192: @c what happens on redefinition
1193: @c parsing words (in particular, defining words)
1194:
1.83 anton 1195: The difference of this chapter from the Introduction
1196: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1197: be used while sitting in front of a computer, and covers much more
1198: material, but does not explain how the Forth system works.
1199:
1.62 crook 1200: This tutorial can be used with any ANS-compliant Forth; any
1201: Gforth-specific features are marked as such and you can skip them if you
1202: work with another Forth. This tutorial does not explain all features of
1203: Forth, just enough to get you started and give you some ideas about the
1204: facilities available in Forth. Read the rest of the manual and the
1205: standard when you are through this.
1.48 anton 1206:
1207: The intended way to use this tutorial is that you work through it while
1208: sitting in front of the console, take a look at the examples and predict
1209: what they will do, then try them out; if the outcome is not as expected,
1210: find out why (e.g., by trying out variations of the example), so you
1211: understand what's going on. There are also some assignments that you
1212: should solve.
1213:
1214: This tutorial assumes that you have programmed before and know what,
1215: e.g., a loop is.
1216:
1217: @c !! explain compat library
1218:
1219: @menu
1220: * Starting Gforth Tutorial::
1221: * Syntax Tutorial::
1222: * Crash Course Tutorial::
1223: * Stack Tutorial::
1224: * Arithmetics Tutorial::
1225: * Stack Manipulation Tutorial::
1226: * Using files for Forth code Tutorial::
1227: * Comments Tutorial::
1228: * Colon Definitions Tutorial::
1229: * Decompilation Tutorial::
1230: * Stack-Effect Comments Tutorial::
1231: * Types Tutorial::
1232: * Factoring Tutorial::
1233: * Designing the stack effect Tutorial::
1234: * Local Variables Tutorial::
1235: * Conditional execution Tutorial::
1236: * Flags and Comparisons Tutorial::
1237: * General Loops Tutorial::
1238: * Counted loops Tutorial::
1239: * Recursion Tutorial::
1240: * Leaving definitions or loops Tutorial::
1241: * Return Stack Tutorial::
1242: * Memory Tutorial::
1243: * Characters and Strings Tutorial::
1244: * Alignment Tutorial::
1.190 anton 1245: * Floating Point Tutorial::
1.87 anton 1246: * Files Tutorial::
1.48 anton 1247: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1248: * Execution Tokens Tutorial::
1249: * Exceptions Tutorial::
1250: * Defining Words Tutorial::
1251: * Arrays and Records Tutorial::
1252: * POSTPONE Tutorial::
1253: * Literal Tutorial::
1254: * Advanced macros Tutorial::
1255: * Compilation Tokens Tutorial::
1256: * Wordlists and Search Order Tutorial::
1257: @end menu
1258:
1259: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1260: @section Starting Gforth
1.66 anton 1261: @cindex starting Gforth tutorial
1.48 anton 1262: You can start Gforth by typing its name:
1263:
1264: @example
1265: gforth
1266: @end example
1267:
1268: That puts you into interactive mode; you can leave Gforth by typing
1269: @code{bye}. While in Gforth, you can edit the command line and access
1270: the command line history with cursor keys, similar to bash.
1271:
1272:
1273: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1274: @section Syntax
1.66 anton 1275: @cindex syntax tutorial
1.48 anton 1276:
1.171 anton 1277: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1278: space). Words are separated by white space. E.g., each of the
1279: following lines contains exactly one word:
1280:
1281: @example
1282: word
1283: !@@#$%^&*()
1284: 1234567890
1285: 5!a
1286: @end example
1287:
1288: A frequent beginner's error is to leave away necessary white space,
1289: resulting in an error like @samp{Undefined word}; so if you see such an
1290: error, check if you have put spaces wherever necessary.
1291:
1292: @example
1293: ." hello, world" \ correct
1294: ."hello, world" \ gives an "Undefined word" error
1295: @end example
1296:
1.65 anton 1297: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1298: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1299: your system is case-sensitive, you may have to type all the examples
1300: given here in upper case.
1301:
1302:
1303: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1304: @section Crash Course
1305:
1306: Type
1307:
1308: @example
1309: 0 0 !
1310: here execute
1311: ' catch >body 20 erase abort
1312: ' (quit) >body 20 erase
1313: @end example
1314:
1315: The last two examples are guaranteed to destroy parts of Gforth (and
1316: most other systems), so you better leave Gforth afterwards (if it has
1317: not finished by itself). On some systems you may have to kill gforth
1318: from outside (e.g., in Unix with @code{kill}).
1319:
1320: Now that you know how to produce crashes (and that there's not much to
1321: them), let's learn how to produce meaningful programs.
1322:
1323:
1324: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1325: @section Stack
1.66 anton 1326: @cindex stack tutorial
1.48 anton 1327:
1328: The most obvious feature of Forth is the stack. When you type in a
1329: number, it is pushed on the stack. You can display the content of the
1330: stack with @code{.s}.
1331:
1332: @example
1333: 1 2 .s
1334: 3 .s
1335: @end example
1336:
1337: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1338: appear in @code{.s} output as they appeared in the input.
1339:
1340: You can print the top of stack element with @code{.}.
1341:
1342: @example
1343: 1 2 3 . . .
1344: @end example
1345:
1346: In general, words consume their stack arguments (@code{.s} is an
1347: exception).
1348:
1.141 anton 1349: @quotation Assignment
1.48 anton 1350: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1351: @end quotation
1.48 anton 1352:
1353:
1354: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1355: @section Arithmetics
1.66 anton 1356: @cindex arithmetics tutorial
1.48 anton 1357:
1358: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1359: operate on the top two stack items:
1360:
1361: @example
1.67 anton 1362: 2 2 .s
1363: + .s
1364: .
1.48 anton 1365: 2 1 - .
1366: 7 3 mod .
1367: @end example
1368:
1369: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1370: as in the corresponding infix expression (this is generally the case in
1371: Forth).
1372:
1373: Parentheses are superfluous (and not available), because the order of
1374: the words unambiguously determines the order of evaluation and the
1375: operands:
1376:
1377: @example
1378: 3 4 + 5 * .
1379: 3 4 5 * + .
1380: @end example
1381:
1.141 anton 1382: @quotation Assignment
1.48 anton 1383: What are the infix expressions corresponding to the Forth code above?
1384: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1385: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1386: @end quotation
1.48 anton 1387:
1388: To change the sign, use @code{negate}:
1389:
1390: @example
1391: 2 negate .
1392: @end example
1393:
1.141 anton 1394: @quotation Assignment
1.48 anton 1395: Convert -(-3)*4-5 to Forth.
1.141 anton 1396: @end quotation
1.48 anton 1397:
1398: @code{/mod} performs both @code{/} and @code{mod}.
1399:
1400: @example
1401: 7 3 /mod . .
1402: @end example
1403:
1.66 anton 1404: Reference: @ref{Arithmetic}.
1405:
1406:
1.48 anton 1407: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1408: @section Stack Manipulation
1.66 anton 1409: @cindex stack manipulation tutorial
1.48 anton 1410:
1411: Stack manipulation words rearrange the data on the stack.
1412:
1413: @example
1414: 1 .s drop .s
1415: 1 .s dup .s drop drop .s
1416: 1 2 .s over .s drop drop drop
1417: 1 2 .s swap .s drop drop
1418: 1 2 3 .s rot .s drop drop drop
1419: @end example
1420:
1421: These are the most important stack manipulation words. There are also
1422: variants that manipulate twice as many stack items:
1423:
1424: @example
1425: 1 2 3 4 .s 2swap .s 2drop 2drop
1426: @end example
1427:
1428: Two more stack manipulation words are:
1429:
1430: @example
1431: 1 2 .s nip .s drop
1432: 1 2 .s tuck .s 2drop drop
1433: @end example
1434:
1.141 anton 1435: @quotation Assignment
1.48 anton 1436: Replace @code{nip} and @code{tuck} with combinations of other stack
1437: manipulation words.
1438:
1439: @example
1440: Given: How do you get:
1441: 1 2 3 3 2 1
1442: 1 2 3 1 2 3 2
1443: 1 2 3 1 2 3 3
1444: 1 2 3 1 3 3
1445: 1 2 3 2 1 3
1446: 1 2 3 4 4 3 2 1
1447: 1 2 3 1 2 3 1 2 3
1448: 1 2 3 4 1 2 3 4 1 2
1449: 1 2 3
1450: 1 2 3 1 2 3 4
1451: 1 2 3 1 3
1452: @end example
1.141 anton 1453: @end quotation
1.48 anton 1454:
1455: @example
1456: 5 dup * .
1457: @end example
1458:
1.141 anton 1459: @quotation Assignment
1.48 anton 1460: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1461: Write a piece of Forth code that expects two numbers on the stack
1462: (@var{a} and @var{b}, with @var{b} on top) and computes
1463: @code{(a-b)(a+1)}.
1.141 anton 1464: @end quotation
1.48 anton 1465:
1.66 anton 1466: Reference: @ref{Stack Manipulation}.
1467:
1468:
1.48 anton 1469: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1470: @section Using files for Forth code
1.66 anton 1471: @cindex loading Forth code, tutorial
1472: @cindex files containing Forth code, tutorial
1.48 anton 1473:
1474: While working at the Forth command line is convenient for one-line
1475: examples and short one-off code, you probably want to store your source
1476: code in files for convenient editing and persistence. You can use your
1477: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1478: Gforth}) to create @var{file.fs} and use
1.48 anton 1479:
1480: @example
1.102 anton 1481: s" @var{file.fs}" included
1.48 anton 1482: @end example
1483:
1484: to load it into your Forth system. The file name extension I use for
1485: Forth files is @samp{.fs}.
1486:
1487: You can easily start Gforth with some files loaded like this:
1488:
1489: @example
1.102 anton 1490: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1491: @end example
1492:
1493: If an error occurs during loading these files, Gforth terminates,
1494: whereas an error during @code{INCLUDED} within Gforth usually gives you
1495: a Gforth command line. Starting the Forth system every time gives you a
1496: clean start every time, without interference from the results of earlier
1497: tries.
1498:
1499: I often put all the tests in a file, then load the code and run the
1500: tests with
1501:
1502: @example
1.102 anton 1503: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1504: @end example
1505:
1506: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1507: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1508: restart this command without ado.
1509:
1510: The advantage of this approach is that the tests can be repeated easily
1511: every time the program ist changed, making it easy to catch bugs
1512: introduced by the change.
1513:
1.66 anton 1514: Reference: @ref{Forth source files}.
1515:
1.48 anton 1516:
1517: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1518: @section Comments
1.66 anton 1519: @cindex comments tutorial
1.48 anton 1520:
1521: @example
1522: \ That's a comment; it ends at the end of the line
1523: ( Another comment; it ends here: ) .s
1524: @end example
1525:
1526: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1527: separated with white space from the following text.
1528:
1529: @example
1530: \This gives an "Undefined word" error
1531: @end example
1532:
1533: The first @code{)} ends a comment started with @code{(}, so you cannot
1534: nest @code{(}-comments; and you cannot comment out text containing a
1535: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1536: avoid @code{)} in word names.}.
1537:
1538: I use @code{\}-comments for descriptive text and for commenting out code
1539: of one or more line; I use @code{(}-comments for describing the stack
1540: effect, the stack contents, or for commenting out sub-line pieces of
1541: code.
1542:
1543: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1544: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1545: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1546: with @kbd{M-q}.
1547:
1.66 anton 1548: Reference: @ref{Comments}.
1549:
1.48 anton 1550:
1551: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1552: @section Colon Definitions
1.66 anton 1553: @cindex colon definitions, tutorial
1554: @cindex definitions, tutorial
1555: @cindex procedures, tutorial
1556: @cindex functions, tutorial
1.48 anton 1557:
1558: are similar to procedures and functions in other programming languages.
1559:
1560: @example
1561: : squared ( n -- n^2 )
1562: dup * ;
1563: 5 squared .
1564: 7 squared .
1565: @end example
1566:
1567: @code{:} starts the colon definition; its name is @code{squared}. The
1568: following comment describes its stack effect. The words @code{dup *}
1569: are not executed, but compiled into the definition. @code{;} ends the
1570: colon definition.
1571:
1572: The newly-defined word can be used like any other word, including using
1573: it in other definitions:
1574:
1575: @example
1576: : cubed ( n -- n^3 )
1577: dup squared * ;
1578: -5 cubed .
1579: : fourth-power ( n -- n^4 )
1580: squared squared ;
1581: 3 fourth-power .
1582: @end example
1583:
1.141 anton 1584: @quotation Assignment
1.48 anton 1585: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1586: @code{/mod} in terms of other Forth words, and check if they work (hint:
1587: test your tests on the originals first). Don't let the
1588: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1589: @end quotation
1.48 anton 1590:
1.66 anton 1591: Reference: @ref{Colon Definitions}.
1592:
1.48 anton 1593:
1594: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1595: @section Decompilation
1.66 anton 1596: @cindex decompilation tutorial
1597: @cindex see tutorial
1.48 anton 1598:
1599: You can decompile colon definitions with @code{see}:
1600:
1601: @example
1602: see squared
1603: see cubed
1604: @end example
1605:
1606: In Gforth @code{see} shows you a reconstruction of the source code from
1607: the executable code. Informations that were present in the source, but
1608: not in the executable code, are lost (e.g., comments).
1609:
1.65 anton 1610: You can also decompile the predefined words:
1611:
1612: @example
1613: see .
1614: see +
1615: @end example
1616:
1617:
1.48 anton 1618: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1619: @section Stack-Effect Comments
1.66 anton 1620: @cindex stack-effect comments, tutorial
1621: @cindex --, tutorial
1.48 anton 1622: By convention the comment after the name of a definition describes the
1.171 anton 1623: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1624: the stack before the execution of the definition, i.e., the parameters
1625: that are passed into the colon definition; the part behind the @samp{--}
1626: is the state of the stack after the execution of the definition, i.e.,
1627: the results of the definition. The stack comment only shows the top
1628: stack items that the definition accesses and/or changes.
1629:
1630: You should put a correct stack effect on every definition, even if it is
1631: just @code{( -- )}. You should also add some descriptive comment to
1632: more complicated words (I usually do this in the lines following
1633: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1634: you have to work through every definition before you can understand
1.48 anton 1635: any).
1636:
1.141 anton 1637: @quotation Assignment
1.48 anton 1638: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1639: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1640: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1641: are done, you can compare your stack effects to those in this manual
1.48 anton 1642: (@pxref{Word Index}).
1.141 anton 1643: @end quotation
1.48 anton 1644:
1645: Sometimes programmers put comments at various places in colon
1646: definitions that describe the contents of the stack at that place (stack
1647: comments); i.e., they are like the first part of a stack-effect
1648: comment. E.g.,
1649:
1650: @example
1651: : cubed ( n -- n^3 )
1652: dup squared ( n n^2 ) * ;
1653: @end example
1654:
1655: In this case the stack comment is pretty superfluous, because the word
1656: is simple enough. If you think it would be a good idea to add such a
1657: comment to increase readability, you should also consider factoring the
1658: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1659: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1660: however, if you decide not to refactor it, then having such a comment is
1661: better than not having it.
1662:
1663: The names of the stack items in stack-effect and stack comments in the
1664: standard, in this manual, and in many programs specify the type through
1665: a type prefix, similar to Fortran and Hungarian notation. The most
1666: frequent prefixes are:
1667:
1668: @table @code
1669: @item n
1670: signed integer
1671: @item u
1672: unsigned integer
1673: @item c
1674: character
1675: @item f
1676: Boolean flags, i.e. @code{false} or @code{true}.
1677: @item a-addr,a-
1678: Cell-aligned address
1679: @item c-addr,c-
1680: Char-aligned address (note that a Char may have two bytes in Windows NT)
1681: @item xt
1682: Execution token, same size as Cell
1683: @item w,x
1684: Cell, can contain an integer or an address. It usually takes 32, 64 or
1685: 16 bits (depending on your platform and Forth system). A cell is more
1686: commonly known as machine word, but the term @emph{word} already means
1687: something different in Forth.
1688: @item d
1689: signed double-cell integer
1690: @item ud
1691: unsigned double-cell integer
1692: @item r
1693: Float (on the FP stack)
1694: @end table
1695:
1696: You can find a more complete list in @ref{Notation}.
1697:
1.141 anton 1698: @quotation Assignment
1.48 anton 1699: Write stack-effect comments for all definitions you have written up to
1700: now.
1.141 anton 1701: @end quotation
1.48 anton 1702:
1703:
1704: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1705: @section Types
1.66 anton 1706: @cindex types tutorial
1.48 anton 1707:
1708: In Forth the names of the operations are not overloaded; so similar
1709: operations on different types need different names; e.g., @code{+} adds
1710: integers, and you have to use @code{f+} to add floating-point numbers.
1711: The following prefixes are often used for related operations on
1712: different types:
1713:
1714: @table @code
1715: @item (none)
1716: signed integer
1717: @item u
1718: unsigned integer
1719: @item c
1720: character
1721: @item d
1722: signed double-cell integer
1723: @item ud, du
1724: unsigned double-cell integer
1725: @item 2
1726: two cells (not-necessarily double-cell numbers)
1727: @item m, um
1728: mixed single-cell and double-cell operations
1729: @item f
1730: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1731: and @samp{r} represents FP numbers).
1.48 anton 1732: @end table
1733:
1734: If there are no differences between the signed and the unsigned variant
1735: (e.g., for @code{+}), there is only the prefix-less variant.
1736:
1737: Forth does not perform type checking, neither at compile time, nor at
1738: run time. If you use the wrong oeration, the data are interpreted
1739: incorrectly:
1740:
1741: @example
1742: -1 u.
1743: @end example
1744:
1745: If you have only experience with type-checked languages until now, and
1746: have heard how important type-checking is, don't panic! In my
1747: experience (and that of other Forthers), type errors in Forth code are
1748: usually easy to find (once you get used to it), the increased vigilance
1749: of the programmer tends to catch some harder errors in addition to most
1750: type errors, and you never have to work around the type system, so in
1751: most situations the lack of type-checking seems to be a win (projects to
1752: add type checking to Forth have not caught on).
1753:
1754:
1755: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1756: @section Factoring
1.66 anton 1757: @cindex factoring tutorial
1.48 anton 1758:
1759: If you try to write longer definitions, you will soon find it hard to
1760: keep track of the stack contents. Therefore, good Forth programmers
1761: tend to write only short definitions (e.g., three lines). The art of
1762: finding meaningful short definitions is known as factoring (as in
1763: factoring polynomials).
1764:
1765: Well-factored programs offer additional advantages: smaller, more
1766: general words, are easier to test and debug and can be reused more and
1767: better than larger, specialized words.
1768:
1769: So, if you run into difficulties with stack management, when writing
1770: code, try to define meaningful factors for the word, and define the word
1771: in terms of those. Even if a factor contains only two words, it is
1772: often helpful.
1773:
1.65 anton 1774: Good factoring is not easy, and it takes some practice to get the knack
1775: for it; but even experienced Forth programmers often don't find the
1776: right solution right away, but only when rewriting the program. So, if
1777: you don't come up with a good solution immediately, keep trying, don't
1778: despair.
1.48 anton 1779:
1780: @c example !!
1781:
1782:
1783: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1784: @section Designing the stack effect
1.66 anton 1785: @cindex Stack effect design, tutorial
1786: @cindex design of stack effects, tutorial
1.48 anton 1787:
1788: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1789: function; and since there is only one result, you don't have to deal with
1.48 anton 1790: the order of results, either.
1791:
1.117 anton 1792: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1793: parameter and result order of a definition is important and should be
1794: designed well. The general guideline is to design the stack effect such
1795: that the word is simple to use in most cases, even if that complicates
1796: the implementation of the word. Some concrete rules are:
1797:
1798: @itemize @bullet
1799:
1800: @item
1801: Words consume all of their parameters (e.g., @code{.}).
1802:
1803: @item
1804: If there is a convention on the order of parameters (e.g., from
1805: mathematics or another programming language), stick with it (e.g.,
1806: @code{-}).
1807:
1808: @item
1809: If one parameter usually requires only a short computation (e.g., it is
1810: a constant), pass it on the top of the stack. Conversely, parameters
1811: that usually require a long sequence of code to compute should be passed
1812: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1813: read, because the reader does not need to keep track of the bottom item
1.48 anton 1814: through a long sequence of code (or, alternatively, through stack
1.49 anton 1815: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1816: address on top of the stack because it is usually simpler to compute
1817: than the stored value (often the address is just a variable).
1818:
1819: @item
1820: Similarly, results that are usually consumed quickly should be returned
1821: on the top of stack, whereas a result that is often used in long
1822: computations should be passed as bottom result. E.g., the file words
1823: like @code{open-file} return the error code on the top of stack, because
1824: it is usually consumed quickly by @code{throw}; moreover, the error code
1825: has to be checked before doing anything with the other results.
1826:
1827: @end itemize
1828:
1829: These rules are just general guidelines, don't lose sight of the overall
1830: goal to make the words easy to use. E.g., if the convention rule
1831: conflicts with the computation-length rule, you might decide in favour
1832: of the convention if the word will be used rarely, and in favour of the
1833: computation-length rule if the word will be used frequently (because
1834: with frequent use the cost of breaking the computation-length rule would
1835: be quite high, and frequent use makes it easier to remember an
1836: unconventional order).
1837:
1838: @c example !! structure package
1839:
1.65 anton 1840:
1.48 anton 1841: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1842: @section Local Variables
1.66 anton 1843: @cindex local variables, tutorial
1.48 anton 1844:
1845: You can define local variables (@emph{locals}) in a colon definition:
1846:
1847: @example
1848: : swap @{ a b -- b a @}
1849: b a ;
1850: 1 2 swap .s 2drop
1851: @end example
1852:
1853: (If your Forth system does not support this syntax, include
1.187 anton 1854: @file{compat/anslocal.fs} first).
1.48 anton 1855:
1856: In this example @code{@{ a b -- b a @}} is the locals definition; it
1857: takes two cells from the stack, puts the top of stack in @code{b} and
1858: the next stack element in @code{a}. @code{--} starts a comment ending
1859: with @code{@}}. After the locals definition, using the name of the
1860: local will push its value on the stack. You can leave the comment
1861: part (@code{-- b a}) away:
1862:
1863: @example
1864: : swap ( x1 x2 -- x2 x1 )
1865: @{ a b @} b a ;
1866: @end example
1867:
1868: In Gforth you can have several locals definitions, anywhere in a colon
1869: definition; in contrast, in a standard program you can have only one
1870: locals definition per colon definition, and that locals definition must
1.163 anton 1871: be outside any control structure.
1.48 anton 1872:
1873: With locals you can write slightly longer definitions without running
1874: into stack trouble. However, I recommend trying to write colon
1875: definitions without locals for exercise purposes to help you gain the
1876: essential factoring skills.
1877:
1.141 anton 1878: @quotation Assignment
1.48 anton 1879: Rewrite your definitions until now with locals
1.141 anton 1880: @end quotation
1.48 anton 1881:
1.66 anton 1882: Reference: @ref{Locals}.
1883:
1.48 anton 1884:
1885: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1886: @section Conditional execution
1.66 anton 1887: @cindex conditionals, tutorial
1888: @cindex if, tutorial
1.48 anton 1889:
1890: In Forth you can use control structures only inside colon definitions.
1891: An @code{if}-structure looks like this:
1892:
1893: @example
1894: : abs ( n1 -- +n2 )
1895: dup 0 < if
1896: negate
1897: endif ;
1898: 5 abs .
1899: -5 abs .
1900: @end example
1901:
1902: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1903: the following code is performed, otherwise execution continues after the
1.51 pazsan 1904: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1905: elements and produces a flag:
1.48 anton 1906:
1907: @example
1908: 1 2 < .
1909: 2 1 < .
1910: 1 1 < .
1911: @end example
1912:
1913: Actually the standard name for @code{endif} is @code{then}. This
1914: tutorial presents the examples using @code{endif}, because this is often
1915: less confusing for people familiar with other programming languages
1916: where @code{then} has a different meaning. If your system does not have
1917: @code{endif}, define it with
1918:
1919: @example
1920: : endif postpone then ; immediate
1921: @end example
1922:
1923: You can optionally use an @code{else}-part:
1924:
1925: @example
1926: : min ( n1 n2 -- n )
1927: 2dup < if
1928: drop
1929: else
1930: nip
1931: endif ;
1932: 2 3 min .
1933: 3 2 min .
1934: @end example
1935:
1.141 anton 1936: @quotation Assignment
1.48 anton 1937: Write @code{min} without @code{else}-part (hint: what's the definition
1938: of @code{nip}?).
1.141 anton 1939: @end quotation
1.48 anton 1940:
1.66 anton 1941: Reference: @ref{Selection}.
1942:
1.48 anton 1943:
1944: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1945: @section Flags and Comparisons
1.66 anton 1946: @cindex flags tutorial
1947: @cindex comparison tutorial
1.48 anton 1948:
1949: In a false-flag all bits are clear (0 when interpreted as integer). In
1950: a canonical true-flag all bits are set (-1 as a twos-complement signed
1951: integer); in many contexts (e.g., @code{if}) any non-zero value is
1952: treated as true flag.
1953:
1954: @example
1955: false .
1956: true .
1957: true hex u. decimal
1958: @end example
1959:
1960: Comparison words produce canonical flags:
1961:
1962: @example
1963: 1 1 = .
1964: 1 0= .
1965: 0 1 < .
1966: 0 0 < .
1967: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1968: -1 1 < .
1969: @end example
1970:
1.66 anton 1971: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1972: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1973: these combinations are standard (for details see the standard,
1974: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1975:
1.171 anton 1976: You can use @code{and or xor invert} as operations on canonical flags.
1977: Actually they are bitwise operations:
1.48 anton 1978:
1979: @example
1980: 1 2 and .
1981: 1 2 or .
1982: 1 3 xor .
1983: 1 invert .
1984: @end example
1985:
1986: You can convert a zero/non-zero flag into a canonical flag with
1987: @code{0<>} (and complement it on the way with @code{0=}).
1988:
1989: @example
1990: 1 0= .
1991: 1 0<> .
1992: @end example
1993:
1.65 anton 1994: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1995: operation of the Boolean operations to avoid @code{if}s:
1996:
1997: @example
1998: : foo ( n1 -- n2 )
1999: 0= if
2000: 14
2001: else
2002: 0
2003: endif ;
2004: 0 foo .
2005: 1 foo .
2006:
2007: : foo ( n1 -- n2 )
2008: 0= 14 and ;
2009: 0 foo .
2010: 1 foo .
2011: @end example
2012:
1.141 anton 2013: @quotation Assignment
1.48 anton 2014: Write @code{min} without @code{if}.
1.141 anton 2015: @end quotation
1.48 anton 2016:
1.66 anton 2017: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2018: @ref{Bitwise operations}.
2019:
1.48 anton 2020:
2021: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2022: @section General Loops
1.66 anton 2023: @cindex loops, indefinite, tutorial
1.48 anton 2024:
2025: The endless loop is the most simple one:
2026:
2027: @example
2028: : endless ( -- )
2029: 0 begin
2030: dup . 1+
2031: again ;
2032: endless
2033: @end example
2034:
2035: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2036: does nothing at run-time, @code{again} jumps back to @code{begin}.
2037:
2038: A loop with one exit at any place looks like this:
2039:
2040: @example
2041: : log2 ( +n1 -- n2 )
2042: \ logarithmus dualis of n1>0, rounded down to the next integer
2043: assert( dup 0> )
2044: 2/ 0 begin
2045: over 0> while
2046: 1+ swap 2/ swap
2047: repeat
2048: nip ;
2049: 7 log2 .
2050: 8 log2 .
2051: @end example
2052:
2053: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2054: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2055: continues behind the @code{while}. @code{Repeat} jumps back to
2056: @code{begin}, just like @code{again}.
2057:
2058: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2059: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2060: one bit (arithmetic shift right):
2061:
2062: @example
2063: -5 2 / .
2064: -5 2/ .
2065: @end example
2066:
2067: @code{assert(} is no standard word, but you can get it on systems other
2068: then Gforth by including @file{compat/assert.fs}. You can see what it
2069: does by trying
2070:
2071: @example
2072: 0 log2 .
2073: @end example
2074:
2075: Here's a loop with an exit at the end:
2076:
2077: @example
2078: : log2 ( +n1 -- n2 )
2079: \ logarithmus dualis of n1>0, rounded down to the next integer
2080: assert( dup 0 > )
2081: -1 begin
2082: 1+ swap 2/ swap
2083: over 0 <=
2084: until
2085: nip ;
2086: @end example
2087:
2088: @code{Until} consumes a flag; if it is non-zero, execution continues at
2089: the @code{begin}, otherwise after the @code{until}.
2090:
1.141 anton 2091: @quotation Assignment
1.48 anton 2092: Write a definition for computing the greatest common divisor.
1.141 anton 2093: @end quotation
1.48 anton 2094:
1.66 anton 2095: Reference: @ref{Simple Loops}.
2096:
1.48 anton 2097:
2098: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2099: @section Counted loops
1.66 anton 2100: @cindex loops, counted, tutorial
1.48 anton 2101:
2102: @example
2103: : ^ ( n1 u -- n )
1.171 anton 2104: \ n = the uth power of n1
1.48 anton 2105: 1 swap 0 u+do
2106: over *
2107: loop
2108: nip ;
2109: 3 2 ^ .
2110: 4 3 ^ .
2111: @end example
2112:
2113: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2114: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2115: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2116: times (or not at all, if @code{u3-u4<0}).
2117:
2118: You can see the stack effect design rules at work in the stack effect of
2119: the loop start words: Since the start value of the loop is more
2120: frequently constant than the end value, the start value is passed on
2121: the top-of-stack.
2122:
2123: You can access the counter of a counted loop with @code{i}:
2124:
2125: @example
2126: : fac ( u -- u! )
2127: 1 swap 1+ 1 u+do
2128: i *
2129: loop ;
2130: 5 fac .
2131: 7 fac .
2132: @end example
2133:
2134: There is also @code{+do}, which expects signed numbers (important for
2135: deciding whether to enter the loop).
2136:
1.141 anton 2137: @quotation Assignment
1.48 anton 2138: Write a definition for computing the nth Fibonacci number.
1.141 anton 2139: @end quotation
1.48 anton 2140:
1.65 anton 2141: You can also use increments other than 1:
2142:
2143: @example
2144: : up2 ( n1 n2 -- )
2145: +do
2146: i .
2147: 2 +loop ;
2148: 10 0 up2
2149:
2150: : down2 ( n1 n2 -- )
2151: -do
2152: i .
2153: 2 -loop ;
2154: 0 10 down2
2155: @end example
1.48 anton 2156:
1.66 anton 2157: Reference: @ref{Counted Loops}.
2158:
1.48 anton 2159:
2160: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2161: @section Recursion
1.66 anton 2162: @cindex recursion tutorial
1.48 anton 2163:
2164: Usually the name of a definition is not visible in the definition; but
2165: earlier definitions are usually visible:
2166:
2167: @example
1.166 anton 2168: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2169: : / ( n1 n2 -- n )
2170: dup 0= if
2171: -10 throw \ report division by zero
2172: endif
2173: / \ old version
2174: ;
2175: 1 0 /
2176: @end example
2177:
2178: For recursive definitions you can use @code{recursive} (non-standard) or
2179: @code{recurse}:
2180:
2181: @example
2182: : fac1 ( n -- n! ) recursive
2183: dup 0> if
2184: dup 1- fac1 *
2185: else
2186: drop 1
2187: endif ;
2188: 7 fac1 .
2189:
2190: : fac2 ( n -- n! )
2191: dup 0> if
2192: dup 1- recurse *
2193: else
2194: drop 1
2195: endif ;
2196: 8 fac2 .
2197: @end example
2198:
1.141 anton 2199: @quotation Assignment
1.48 anton 2200: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2201: @end quotation
1.48 anton 2202:
1.66 anton 2203: Reference (including indirect recursion): @xref{Calls and returns}.
2204:
1.48 anton 2205:
2206: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2207: @section Leaving definitions or loops
1.66 anton 2208: @cindex leaving definitions, tutorial
2209: @cindex leaving loops, tutorial
1.48 anton 2210:
2211: @code{EXIT} exits the current definition right away. For every counted
2212: loop that is left in this way, an @code{UNLOOP} has to be performed
2213: before the @code{EXIT}:
2214:
2215: @c !! real examples
2216: @example
2217: : ...
2218: ... u+do
2219: ... if
2220: ... unloop exit
2221: endif
2222: ...
2223: loop
2224: ... ;
2225: @end example
2226:
2227: @code{LEAVE} leaves the innermost counted loop right away:
2228:
2229: @example
2230: : ...
2231: ... u+do
2232: ... if
2233: ... leave
2234: endif
2235: ...
2236: loop
2237: ... ;
2238: @end example
2239:
1.65 anton 2240: @c !! example
1.48 anton 2241:
1.66 anton 2242: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2243:
2244:
1.48 anton 2245: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2246: @section Return Stack
1.66 anton 2247: @cindex return stack tutorial
1.48 anton 2248:
2249: In addition to the data stack Forth also has a second stack, the return
2250: stack; most Forth systems store the return addresses of procedure calls
2251: there (thus its name). Programmers can also use this stack:
2252:
2253: @example
2254: : foo ( n1 n2 -- )
2255: .s
2256: >r .s
1.50 anton 2257: r@@ .
1.48 anton 2258: >r .s
1.50 anton 2259: r@@ .
1.48 anton 2260: r> .
1.50 anton 2261: r@@ .
1.48 anton 2262: r> . ;
2263: 1 2 foo
2264: @end example
2265:
2266: @code{>r} takes an element from the data stack and pushes it onto the
2267: return stack; conversely, @code{r>} moves an elementm from the return to
2268: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2269: on the data stack.
1.48 anton 2270:
2271: Forth programmers usually use the return stack for storing data
2272: temporarily, if using the data stack alone would be too complex, and
2273: factoring and locals are not an option:
2274:
2275: @example
2276: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2277: rot >r rot r> ;
2278: @end example
2279:
2280: The return address of the definition and the loop control parameters of
2281: counted loops usually reside on the return stack, so you have to take
2282: all items, that you have pushed on the return stack in a colon
2283: definition or counted loop, from the return stack before the definition
2284: or loop ends. You cannot access items that you pushed on the return
2285: stack outside some definition or loop within the definition of loop.
2286:
2287: If you miscount the return stack items, this usually ends in a crash:
2288:
2289: @example
2290: : crash ( n -- )
2291: >r ;
2292: 5 crash
2293: @end example
2294:
2295: You cannot mix using locals and using the return stack (according to the
2296: standard; Gforth has no problem). However, they solve the same
2297: problems, so this shouldn't be an issue.
2298:
1.141 anton 2299: @quotation Assignment
1.48 anton 2300: Can you rewrite any of the definitions you wrote until now in a better
2301: way using the return stack?
1.141 anton 2302: @end quotation
1.48 anton 2303:
1.66 anton 2304: Reference: @ref{Return stack}.
2305:
1.48 anton 2306:
2307: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2308: @section Memory
1.66 anton 2309: @cindex memory access/allocation tutorial
1.48 anton 2310:
2311: You can create a global variable @code{v} with
2312:
2313: @example
2314: variable v ( -- addr )
2315: @end example
2316:
2317: @code{v} pushes the address of a cell in memory on the stack. This cell
2318: was reserved by @code{variable}. You can use @code{!} (store) to store
2319: values into this cell and @code{@@} (fetch) to load the value from the
2320: stack into memory:
2321:
2322: @example
2323: v .
2324: 5 v ! .s
1.50 anton 2325: v @@ .
1.48 anton 2326: @end example
2327:
1.65 anton 2328: You can see a raw dump of memory with @code{dump}:
2329:
2330: @example
2331: v 1 cells .s dump
2332: @end example
2333:
2334: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2335: generally, address units (aus)) that @code{n1 cells} occupy. You can
2336: also reserve more memory:
1.48 anton 2337:
2338: @example
2339: create v2 20 cells allot
1.65 anton 2340: v2 20 cells dump
1.48 anton 2341: @end example
2342:
1.65 anton 2343: creates a word @code{v2} and reserves 20 uninitialized cells; the
2344: address pushed by @code{v2} points to the start of these 20 cells. You
2345: can use address arithmetic to access these cells:
1.48 anton 2346:
2347: @example
2348: 3 v2 5 cells + !
1.65 anton 2349: v2 20 cells dump
1.48 anton 2350: @end example
2351:
2352: You can reserve and initialize memory with @code{,}:
2353:
2354: @example
2355: create v3
2356: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2357: v3 @@ .
2358: v3 cell+ @@ .
2359: v3 2 cells + @@ .
1.65 anton 2360: v3 5 cells dump
1.48 anton 2361: @end example
2362:
1.141 anton 2363: @quotation Assignment
1.48 anton 2364: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2365: @code{u} cells, with the first of these cells at @code{addr}, the next
2366: one at @code{addr cell+} etc.
1.141 anton 2367: @end quotation
1.48 anton 2368:
2369: You can also reserve memory without creating a new word:
2370:
2371: @example
1.60 anton 2372: here 10 cells allot .
2373: here .
1.48 anton 2374: @end example
2375:
2376: @code{Here} pushes the start address of the memory area. You should
2377: store it somewhere, or you will have a hard time finding the memory area
2378: again.
2379:
2380: @code{Allot} manages dictionary memory. The dictionary memory contains
2381: the system's data structures for words etc. on Gforth and most other
2382: Forth systems. It is managed like a stack: You can free the memory that
2383: you have just @code{allot}ed with
2384:
2385: @example
2386: -10 cells allot
1.60 anton 2387: here .
1.48 anton 2388: @end example
2389:
2390: Note that you cannot do this if you have created a new word in the
2391: meantime (because then your @code{allot}ed memory is no longer on the
2392: top of the dictionary ``stack'').
2393:
2394: Alternatively, you can use @code{allocate} and @code{free} which allow
2395: freeing memory in any order:
2396:
2397: @example
2398: 10 cells allocate throw .s
2399: 20 cells allocate throw .s
2400: swap
2401: free throw
2402: free throw
2403: @end example
2404:
2405: The @code{throw}s deal with errors (e.g., out of memory).
2406:
1.65 anton 2407: And there is also a
2408: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2409: garbage collector}, which eliminates the need to @code{free} memory
2410: explicitly.
1.48 anton 2411:
1.66 anton 2412: Reference: @ref{Memory}.
2413:
1.48 anton 2414:
2415: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2416: @section Characters and Strings
1.66 anton 2417: @cindex strings tutorial
2418: @cindex characters tutorial
1.48 anton 2419:
2420: On the stack characters take up a cell, like numbers. In memory they
2421: have their own size (one 8-bit byte on most systems), and therefore
2422: require their own words for memory access:
2423:
2424: @example
2425: create v4
2426: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2427: v4 4 chars + c@@ .
1.65 anton 2428: v4 5 chars dump
1.48 anton 2429: @end example
2430:
2431: The preferred representation of strings on the stack is @code{addr
2432: u-count}, where @code{addr} is the address of the first character and
2433: @code{u-count} is the number of characters in the string.
2434:
2435: @example
2436: v4 5 type
2437: @end example
2438:
2439: You get a string constant with
2440:
2441: @example
2442: s" hello, world" .s
2443: type
2444: @end example
2445:
2446: Make sure you have a space between @code{s"} and the string; @code{s"}
2447: is a normal Forth word and must be delimited with white space (try what
2448: happens when you remove the space).
2449:
2450: However, this interpretive use of @code{s"} is quite restricted: the
2451: string exists only until the next call of @code{s"} (some Forth systems
2452: keep more than one of these strings, but usually they still have a
1.62 crook 2453: limited lifetime).
1.48 anton 2454:
2455: @example
2456: s" hello," s" world" .s
2457: type
2458: type
2459: @end example
2460:
1.62 crook 2461: You can also use @code{s"} in a definition, and the resulting
2462: strings then live forever (well, for as long as the definition):
1.48 anton 2463:
2464: @example
2465: : foo s" hello," s" world" ;
2466: foo .s
2467: type
2468: type
2469: @end example
2470:
1.141 anton 2471: @quotation Assignment
1.48 anton 2472: @code{Emit ( c -- )} types @code{c} as character (not a number).
2473: Implement @code{type ( addr u -- )}.
1.141 anton 2474: @end quotation
1.48 anton 2475:
1.66 anton 2476: Reference: @ref{Memory Blocks}.
2477:
2478:
1.190 anton 2479: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2480: @section Alignment
1.66 anton 2481: @cindex alignment tutorial
2482: @cindex memory alignment tutorial
1.48 anton 2483:
2484: On many processors cells have to be aligned in memory, if you want to
2485: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2486: not require alignment, access to aligned cells is faster).
1.48 anton 2487:
2488: @code{Create} aligns @code{here} (i.e., the place where the next
2489: allocation will occur, and that the @code{create}d word points to).
2490: Likewise, the memory produced by @code{allocate} starts at an aligned
2491: address. Adding a number of @code{cells} to an aligned address produces
2492: another aligned address.
2493:
2494: However, address arithmetic involving @code{char+} and @code{chars} can
2495: create an address that is not cell-aligned. @code{Aligned ( addr --
2496: a-addr )} produces the next aligned address:
2497:
2498: @example
1.50 anton 2499: v3 char+ aligned .s @@ .
2500: v3 char+ .s @@ .
1.48 anton 2501: @end example
2502:
2503: Similarly, @code{align} advances @code{here} to the next aligned
2504: address:
2505:
2506: @example
2507: create v5 97 c,
2508: here .
2509: align here .
2510: 1000 ,
2511: @end example
2512:
2513: Note that you should use aligned addresses even if your processor does
2514: not require them, if you want your program to be portable.
2515:
1.66 anton 2516: Reference: @ref{Address arithmetic}.
2517:
1.190 anton 2518: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2519: @section Floating Point
2520: @cindex floating point tutorial
2521: @cindex FP tutorial
2522:
2523: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2524: might expect, but there are a few things worth noting:
2525:
2526: The first point is not specific to Forth, but so important and yet not
2527: universally known that I mention it here: FP numbers are not reals.
2528: Many properties (e.g., arithmetic laws) that reals have and that one
2529: expects of all kinds of numbers do not hold for FP numbers. If you
2530: want to use FP computations, you should learn about their problems and
2531: how to avoid them; a good starting point is @cite{David Goldberg,
2532: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2533: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2534: Computing Surveys 23(1):5@minus{}48, March 1991}.
2535:
2536: In Forth source code literal FP numbers need an exponent, e.g.,
2537: @code{1e0}; this can also be written shorter as @code{1e},
2538: @code{+1.0e+0}, and many variations in between. The reason for this
2539: is that, for historical reasons, Forth interprets a decimal point
2540: alone (e.g., @code{1.}) as indicating a double-cell integer. Another
2541: requirement for literal FP numbers is that the current base is
2542: decimal; with a hex base @code{1e} is interpreted as an integer.
2543:
2544: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2545: ANS Forth system may implement the FP stack on the data stack, but
2546: virtually all systems implement a separate FP stack; and programming
2547: in a way that accommodates all models is so cumbersome that nobody
2548: does it.} One advantage of this model is that cells are not in the
2549: way when accessing FP values, and vice versa. Forth has a set of
2550: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2551: frot} and (non-standard) @code{fnip ftuck fpick}.
2552:
2553: FP arithmetic words are prefixed with @code{F}. There is the usual
2554: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2555: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2556: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2557: computation results are usually inaccurate, so exact comparison is
2558: usually a mistake, and one should use approximate comparison.
2559: Unfortunately, @code{f~}, the standard word for that purpose, is not
2560: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2561: well.
2562:
2563: And of course there are words for accessing FP numbers in memory
2564: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2565: faligned}). There are also variants of these words with an @code{sf}
2566: and @code{df} prefix for accessing IEEE format single-precision and
2567: double-precision numbers in memory; their main purpose is for
2568: accessing external FP data (e.g., that has been read from or will be
2569: written to a file).
2570:
2571: Here is an example of a dot-product word and its use:
2572:
2573: @example
2574: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2575: >r swap 2swap swap 0e r> 0 ?DO
2576: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2577: LOOP
2578: 2drop 2drop ;
1.48 anton 2579:
1.190 anton 2580: create v 1.23e f, 4.56e f, 7.89e f,
2581:
2582: v 1 floats v 1 floats 3 v* f.
2583: @end example
2584:
2585: @quotation Assignment
2586: Write a program to solve a quadratic equation. Then read @cite{Henry
2587: G. Baker,
2588: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2589: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2590: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2591: program. Finally, find a test case where the original and the
2592: improved version produce different results.
2593: @end quotation
2594:
2595: Reference: @ref{Floating Point}; @ref{Floating point stack};
2596: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2597: arithmetic}.
2598:
2599: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2600: @section Files
2601: @cindex files tutorial
2602:
2603: This section gives a short introduction into how to use files inside
2604: Forth. It's broken up into five easy steps:
2605:
2606: @enumerate 1
2607: @item Opened an ASCII text file for input
2608: @item Opened a file for output
2609: @item Read input file until string matched (or some other condition matched)
2610: @item Wrote some lines from input ( modified or not) to output
2611: @item Closed the files.
2612: @end enumerate
2613:
1.153 anton 2614: Reference: @ref{General files}.
2615:
1.84 pazsan 2616: @subsection Open file for input
2617:
2618: @example
2619: s" foo.in" r/o open-file throw Value fd-in
2620: @end example
2621:
2622: @subsection Create file for output
2623:
2624: @example
2625: s" foo.out" w/o create-file throw Value fd-out
2626: @end example
2627:
2628: The available file modes are r/o for read-only access, r/w for
2629: read-write access, and w/o for write-only access. You could open both
2630: files with r/w, too, if you like. All file words return error codes; for
2631: most applications, it's best to pass there error codes with @code{throw}
2632: to the outer error handler.
2633:
2634: If you want words for opening and assigning, define them as follows:
2635:
2636: @example
2637: 0 Value fd-in
2638: 0 Value fd-out
2639: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2640: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2641: @end example
2642:
2643: Usage example:
2644:
2645: @example
2646: s" foo.in" open-input
2647: s" foo.out" open-output
2648: @end example
2649:
2650: @subsection Scan file for a particular line
2651:
2652: @example
2653: 256 Constant max-line
2654: Create line-buffer max-line 2 + allot
2655:
2656: : scan-file ( addr u -- )
2657: begin
2658: line-buffer max-line fd-in read-line throw
2659: while
2660: >r 2dup line-buffer r> compare 0=
2661: until
2662: else
2663: drop
2664: then
2665: 2drop ;
2666: @end example
2667:
2668: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2669: the buffer at addr, and returns the number of bytes read, a flag that is
2670: false when the end of file is reached, and an error code.
1.84 pazsan 2671:
2672: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2673: returns zero if both strings are equal. It returns a positive number if
2674: the first string is lexically greater, a negative if the second string
2675: is lexically greater.
2676:
2677: We haven't seen this loop here; it has two exits. Since the @code{while}
2678: exits with the number of bytes read on the stack, we have to clean up
2679: that separately; that's after the @code{else}.
2680:
2681: Usage example:
2682:
2683: @example
2684: s" The text I search is here" scan-file
2685: @end example
2686:
2687: @subsection Copy input to output
2688:
2689: @example
2690: : copy-file ( -- )
2691: begin
2692: line-buffer max-line fd-in read-line throw
2693: while
1.194 ! anton 2694: line-buffer swap fd-out write-line throw
1.84 pazsan 2695: repeat ;
2696: @end example
1.194 ! anton 2697: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2698:
2699: @subsection Close files
2700:
2701: @example
2702: fd-in close-file throw
2703: fd-out close-file throw
2704: @end example
2705:
2706: Likewise, you can put that into definitions, too:
2707:
2708: @example
2709: : close-input ( -- ) fd-in close-file throw ;
2710: : close-output ( -- ) fd-out close-file throw ;
2711: @end example
2712:
1.141 anton 2713: @quotation Assignment
1.84 pazsan 2714: How could you modify @code{copy-file} so that it copies until a second line is
2715: matched? Can you write a program that extracts a section of a text file,
2716: given the line that starts and the line that terminates that section?
1.141 anton 2717: @end quotation
1.84 pazsan 2718:
2719: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2720: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2721: @cindex semantics tutorial
2722: @cindex interpretation semantics tutorial
2723: @cindex compilation semantics tutorial
2724: @cindex immediate, tutorial
1.48 anton 2725:
2726: When a word is compiled, it behaves differently from being interpreted.
2727: E.g., consider @code{+}:
2728:
2729: @example
2730: 1 2 + .
2731: : foo + ;
2732: @end example
2733:
2734: These two behaviours are known as compilation and interpretation
2735: semantics. For normal words (e.g., @code{+}), the compilation semantics
2736: is to append the interpretation semantics to the currently defined word
2737: (@code{foo} in the example above). I.e., when @code{foo} is executed
2738: later, the interpretation semantics of @code{+} (i.e., adding two
2739: numbers) will be performed.
2740:
2741: However, there are words with non-default compilation semantics, e.g.,
2742: the control-flow words like @code{if}. You can use @code{immediate} to
2743: change the compilation semantics of the last defined word to be equal to
2744: the interpretation semantics:
2745:
2746: @example
2747: : [FOO] ( -- )
2748: 5 . ; immediate
2749:
2750: [FOO]
2751: : bar ( -- )
2752: [FOO] ;
2753: bar
2754: see bar
2755: @end example
2756:
2757: Two conventions to mark words with non-default compilation semnatics are
2758: names with brackets (more frequently used) and to write them all in
2759: upper case (less frequently used).
2760:
2761: In Gforth (and many other systems) you can also remove the
2762: interpretation semantics with @code{compile-only} (the compilation
2763: semantics is derived from the original interpretation semantics):
2764:
2765: @example
2766: : flip ( -- )
2767: 6 . ; compile-only \ but not immediate
2768: flip
2769:
2770: : flop ( -- )
2771: flip ;
2772: flop
2773: @end example
2774:
2775: In this example the interpretation semantics of @code{flop} is equal to
2776: the original interpretation semantics of @code{flip}.
2777:
2778: The text interpreter has two states: in interpret state, it performs the
2779: interpretation semantics of words it encounters; in compile state, it
2780: performs the compilation semantics of these words.
2781:
2782: Among other things, @code{:} switches into compile state, and @code{;}
2783: switches back to interpret state. They contain the factors @code{]}
2784: (switch to compile state) and @code{[} (switch to interpret state), that
2785: do nothing but switch the state.
2786:
2787: @example
2788: : xxx ( -- )
2789: [ 5 . ]
2790: ;
2791:
2792: xxx
2793: see xxx
2794: @end example
2795:
2796: These brackets are also the source of the naming convention mentioned
2797: above.
2798:
1.66 anton 2799: Reference: @ref{Interpretation and Compilation Semantics}.
2800:
1.48 anton 2801:
2802: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2803: @section Execution Tokens
1.66 anton 2804: @cindex execution tokens tutorial
2805: @cindex XT tutorial
1.48 anton 2806:
2807: @code{' word} gives you the execution token (XT) of a word. The XT is a
2808: cell representing the interpretation semantics of a word. You can
2809: execute this semantics with @code{execute}:
2810:
2811: @example
2812: ' + .s
2813: 1 2 rot execute .
2814: @end example
2815:
2816: The XT is similar to a function pointer in C. However, parameter
2817: passing through the stack makes it a little more flexible:
2818:
2819: @example
2820: : map-array ( ... addr u xt -- ... )
1.50 anton 2821: \ executes xt ( ... x -- ... ) for every element of the array starting
2822: \ at addr and containing u elements
1.48 anton 2823: @{ xt @}
2824: cells over + swap ?do
1.50 anton 2825: i @@ xt execute
1.48 anton 2826: 1 cells +loop ;
2827:
2828: create a 3 , 4 , 2 , -1 , 4 ,
2829: a 5 ' . map-array .s
2830: 0 a 5 ' + map-array .
2831: s" max-n" environment? drop .s
2832: a 5 ' min map-array .
2833: @end example
2834:
2835: You can use map-array with the XTs of words that consume one element
2836: more than they produce. In theory you can also use it with other XTs,
2837: but the stack effect then depends on the size of the array, which is
2838: hard to understand.
2839:
1.51 pazsan 2840: Since XTs are cell-sized, you can store them in memory and manipulate
2841: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2842: word with @code{compile,}:
2843:
2844: @example
2845: : foo1 ( n1 n2 -- n )
2846: [ ' + compile, ] ;
2847: see foo
2848: @end example
2849:
2850: This is non-standard, because @code{compile,} has no compilation
2851: semantics in the standard, but it works in good Forth systems. For the
2852: broken ones, use
2853:
2854: @example
2855: : [compile,] compile, ; immediate
2856:
2857: : foo1 ( n1 n2 -- n )
2858: [ ' + ] [compile,] ;
2859: see foo
2860: @end example
2861:
2862: @code{'} is a word with default compilation semantics; it parses the
2863: next word when its interpretation semantics are executed, not during
2864: compilation:
2865:
2866: @example
2867: : foo ( -- xt )
2868: ' ;
2869: see foo
2870: : bar ( ... "word" -- ... )
2871: ' execute ;
2872: see bar
1.60 anton 2873: 1 2 bar + .
1.48 anton 2874: @end example
2875:
2876: You often want to parse a word during compilation and compile its XT so
2877: it will be pushed on the stack at run-time. @code{[']} does this:
2878:
2879: @example
2880: : xt-+ ( -- xt )
2881: ['] + ;
2882: see xt-+
2883: 1 2 xt-+ execute .
2884: @end example
2885:
2886: Many programmers tend to see @code{'} and the word it parses as one
2887: unit, and expect it to behave like @code{[']} when compiled, and are
2888: confused by the actual behaviour. If you are, just remember that the
2889: Forth system just takes @code{'} as one unit and has no idea that it is
2890: a parsing word (attempts to convenience programmers in this issue have
2891: usually resulted in even worse pitfalls, see
1.66 anton 2892: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2893: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2894:
2895: Note that the state of the interpreter does not come into play when
1.51 pazsan 2896: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2897: compile state, it still gives you the interpretation semantics. And
2898: whatever that state is, @code{execute} performs the semantics
1.66 anton 2899: represented by the XT (i.e., for XTs produced with @code{'} the
2900: interpretation semantics).
2901:
2902: Reference: @ref{Tokens for Words}.
1.48 anton 2903:
2904:
2905: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2906: @section Exceptions
1.66 anton 2907: @cindex exceptions tutorial
1.48 anton 2908:
2909: @code{throw ( n -- )} causes an exception unless n is zero.
2910:
2911: @example
2912: 100 throw .s
2913: 0 throw .s
2914: @end example
2915:
2916: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2917: it catches exceptions and pushes the number of the exception on the
2918: stack (or 0, if the xt executed without exception). If there was an
2919: exception, the stacks have the same depth as when entering @code{catch}:
2920:
2921: @example
2922: .s
2923: 3 0 ' / catch .s
2924: 3 2 ' / catch .s
2925: @end example
2926:
1.141 anton 2927: @quotation Assignment
1.48 anton 2928: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2929: @end quotation
1.48 anton 2930:
2931: @code{Throw} always jumps to the dynamically next enclosing
2932: @code{catch}, even if it has to leave several call levels to achieve
2933: this:
2934:
2935: @example
2936: : foo 100 throw ;
2937: : foo1 foo ." after foo" ;
1.51 pazsan 2938: : bar ['] foo1 catch ;
1.60 anton 2939: bar .
1.48 anton 2940: @end example
2941:
2942: It is often important to restore a value upon leaving a definition, even
2943: if the definition is left through an exception. You can ensure this
2944: like this:
2945:
2946: @example
2947: : ...
2948: save-x
1.51 pazsan 2949: ['] word-changing-x catch ( ... n )
1.48 anton 2950: restore-x
2951: ( ... n ) throw ;
2952: @end example
2953:
1.172 anton 2954: However, this is still not safe against, e.g., the user pressing
2955: @kbd{Ctrl-C} when execution is between the @code{catch} and
2956: @code{restore-x}.
2957:
2958: Gforth provides an alternative exception handling syntax that is safe
2959: against such cases: @code{try ... restore ... endtry}. If the code
2960: between @code{try} and @code{endtry} has an exception, the stack
2961: depths are restored, the exception number is pushed on the stack, and
2962: the execution continues right after @code{restore}.
1.48 anton 2963:
1.172 anton 2964: The safer equivalent to the restoration code above is
1.48 anton 2965:
2966: @example
2967: : ...
2968: save-x
2969: try
1.92 anton 2970: word-changing-x 0
1.172 anton 2971: restore
2972: restore-x
2973: endtry
1.48 anton 2974: throw ;
2975: @end example
2976:
1.66 anton 2977: Reference: @ref{Exception Handling}.
2978:
1.48 anton 2979:
2980: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2981: @section Defining Words
1.66 anton 2982: @cindex defining words tutorial
2983: @cindex does> tutorial
2984: @cindex create...does> tutorial
2985:
2986: @c before semantics?
1.48 anton 2987:
2988: @code{:}, @code{create}, and @code{variable} are definition words: They
2989: define other words. @code{Constant} is another definition word:
2990:
2991: @example
2992: 5 constant foo
2993: foo .
2994: @end example
2995:
2996: You can also use the prefixes @code{2} (double-cell) and @code{f}
2997: (floating point) with @code{variable} and @code{constant}.
2998:
2999: You can also define your own defining words. E.g.:
3000:
3001: @example
3002: : variable ( "name" -- )
3003: create 0 , ;
3004: @end example
3005:
3006: You can also define defining words that create words that do something
3007: other than just producing their address:
3008:
3009: @example
3010: : constant ( n "name" -- )
3011: create ,
3012: does> ( -- n )
1.50 anton 3013: ( addr ) @@ ;
1.48 anton 3014:
3015: 5 constant foo
3016: foo .
3017: @end example
3018:
3019: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3020: @code{does>} replaces @code{;}, but it also does something else: It
3021: changes the last defined word such that it pushes the address of the
3022: body of the word and then performs the code after the @code{does>}
3023: whenever it is called.
3024:
3025: In the example above, @code{constant} uses @code{,} to store 5 into the
3026: body of @code{foo}. When @code{foo} executes, it pushes the address of
3027: the body onto the stack, then (in the code after the @code{does>})
3028: fetches the 5 from there.
3029:
3030: The stack comment near the @code{does>} reflects the stack effect of the
3031: defined word, not the stack effect of the code after the @code{does>}
3032: (the difference is that the code expects the address of the body that
3033: the stack comment does not show).
3034:
3035: You can use these definition words to do factoring in cases that involve
3036: (other) definition words. E.g., a field offset is always added to an
3037: address. Instead of defining
3038:
3039: @example
3040: 2 cells constant offset-field1
3041: @end example
3042:
3043: and using this like
3044:
3045: @example
3046: ( addr ) offset-field1 +
3047: @end example
3048:
3049: you can define a definition word
3050:
3051: @example
3052: : simple-field ( n "name" -- )
3053: create ,
3054: does> ( n1 -- n1+n )
1.50 anton 3055: ( addr ) @@ + ;
1.48 anton 3056: @end example
1.21 crook 3057:
1.48 anton 3058: Definition and use of field offsets now look like this:
1.21 crook 3059:
1.48 anton 3060: @example
3061: 2 cells simple-field field1
1.60 anton 3062: create mystruct 4 cells allot
3063: mystruct .s field1 .s drop
1.48 anton 3064: @end example
1.21 crook 3065:
1.48 anton 3066: If you want to do something with the word without performing the code
3067: after the @code{does>}, you can access the body of a @code{create}d word
3068: with @code{>body ( xt -- addr )}:
1.21 crook 3069:
1.48 anton 3070: @example
3071: : value ( n "name" -- )
3072: create ,
3073: does> ( -- n1 )
1.50 anton 3074: @@ ;
1.48 anton 3075: : to ( n "name" -- )
3076: ' >body ! ;
1.21 crook 3077:
1.48 anton 3078: 5 value foo
3079: foo .
3080: 7 to foo
3081: foo .
3082: @end example
1.21 crook 3083:
1.141 anton 3084: @quotation Assignment
1.48 anton 3085: Define @code{defer ( "name" -- )}, which creates a word that stores an
3086: XT (at the start the XT of @code{abort}), and upon execution
3087: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3088: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3089: recursion is one application of @code{defer}.
1.141 anton 3090: @end quotation
1.29 crook 3091:
1.66 anton 3092: Reference: @ref{User-defined Defining Words}.
3093:
3094:
1.48 anton 3095: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3096: @section Arrays and Records
1.66 anton 3097: @cindex arrays tutorial
3098: @cindex records tutorial
3099: @cindex structs tutorial
1.29 crook 3100:
1.48 anton 3101: Forth has no standard words for defining data structures such as arrays
3102: and records (structs in C terminology), but you can build them yourself
3103: based on address arithmetic. You can also define words for defining
3104: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3105:
1.48 anton 3106: One of the first projects a Forth newcomer sets out upon when learning
3107: about defining words is an array defining word (possibly for
3108: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3109: learn something from it. However, don't be disappointed when you later
3110: learn that you have little use for these words (inappropriate use would
3111: be even worse). I have not yet found a set of useful array words yet;
3112: the needs are just too diverse, and named, global arrays (the result of
3113: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3114: consider how to pass them as parameters). Another such project is a set
3115: of words to help dealing with strings.
1.29 crook 3116:
1.48 anton 3117: On the other hand, there is a useful set of record words, and it has
3118: been defined in @file{compat/struct.fs}; these words are predefined in
3119: Gforth. They are explained in depth elsewhere in this manual (see
3120: @pxref{Structures}). The @code{simple-field} example above is
3121: simplified variant of fields in this package.
1.21 crook 3122:
3123:
1.48 anton 3124: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3125: @section @code{POSTPONE}
1.66 anton 3126: @cindex postpone tutorial
1.21 crook 3127:
1.48 anton 3128: You can compile the compilation semantics (instead of compiling the
3129: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3130:
1.48 anton 3131: @example
3132: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3133: POSTPONE + ; immediate
1.48 anton 3134: : foo ( n1 n2 -- n )
3135: MY-+ ;
3136: 1 2 foo .
3137: see foo
3138: @end example
1.21 crook 3139:
1.48 anton 3140: During the definition of @code{foo} the text interpreter performs the
3141: compilation semantics of @code{MY-+}, which performs the compilation
3142: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3143:
3144: This example also displays separate stack comments for the compilation
3145: semantics and for the stack effect of the compiled code. For words with
3146: default compilation semantics these stack effects are usually not
3147: displayed; the stack effect of the compilation semantics is always
3148: @code{( -- )} for these words, the stack effect for the compiled code is
3149: the stack effect of the interpretation semantics.
3150:
3151: Note that the state of the interpreter does not come into play when
3152: performing the compilation semantics in this way. You can also perform
3153: it interpretively, e.g.:
3154:
3155: @example
3156: : foo2 ( n1 n2 -- n )
3157: [ MY-+ ] ;
3158: 1 2 foo .
3159: see foo
3160: @end example
1.21 crook 3161:
1.48 anton 3162: However, there are some broken Forth systems where this does not always
1.62 crook 3163: work, and therefore this practice was been declared non-standard in
1.48 anton 3164: 1999.
3165: @c !! repair.fs
3166:
3167: Here is another example for using @code{POSTPONE}:
1.44 crook 3168:
1.48 anton 3169: @example
3170: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3171: POSTPONE negate POSTPONE + ; immediate compile-only
3172: : bar ( n1 n2 -- n )
3173: MY-- ;
3174: 2 1 bar .
3175: see bar
3176: @end example
1.21 crook 3177:
1.48 anton 3178: You can define @code{ENDIF} in this way:
1.21 crook 3179:
1.48 anton 3180: @example
3181: : ENDIF ( Compilation: orig -- )
3182: POSTPONE then ; immediate
3183: @end example
1.21 crook 3184:
1.141 anton 3185: @quotation Assignment
1.48 anton 3186: Write @code{MY-2DUP} that has compilation semantics equivalent to
3187: @code{2dup}, but compiles @code{over over}.
1.141 anton 3188: @end quotation
1.29 crook 3189:
1.66 anton 3190: @c !! @xref{Macros} for reference
3191:
3192:
1.48 anton 3193: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3194: @section @code{Literal}
1.66 anton 3195: @cindex literal tutorial
1.29 crook 3196:
1.48 anton 3197: You cannot @code{POSTPONE} numbers:
1.21 crook 3198:
1.48 anton 3199: @example
3200: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3201: @end example
3202:
1.48 anton 3203: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3204:
1.48 anton 3205: @example
3206: : [FOO] ( compilation: --; run-time: -- n )
3207: 500 POSTPONE literal ; immediate
1.29 crook 3208:
1.60 anton 3209: : flip [FOO] ;
1.48 anton 3210: flip .
3211: see flip
3212: @end example
1.29 crook 3213:
1.48 anton 3214: @code{LITERAL} consumes a number at compile-time (when it's compilation
3215: semantics are executed) and pushes it at run-time (when the code it
3216: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3217: number computed at compile time into the current word:
1.29 crook 3218:
1.48 anton 3219: @example
3220: : bar ( -- n )
3221: [ 2 2 + ] literal ;
3222: see bar
3223: @end example
1.29 crook 3224:
1.141 anton 3225: @quotation Assignment
1.48 anton 3226: Write @code{]L} which allows writing the example above as @code{: bar (
3227: -- n ) [ 2 2 + ]L ;}
1.141 anton 3228: @end quotation
1.48 anton 3229:
1.66 anton 3230: @c !! @xref{Macros} for reference
3231:
1.48 anton 3232:
3233: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3234: @section Advanced macros
1.66 anton 3235: @cindex macros, advanced tutorial
3236: @cindex run-time code generation, tutorial
1.48 anton 3237:
1.66 anton 3238: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3239: Execution Tokens}. It frequently performs @code{execute}, a relatively
3240: expensive operation in some Forth implementations. You can use
1.48 anton 3241: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3242: and produce a word that contains the word to be performed directly:
3243:
3244: @c use ]] ... [[
3245: @example
3246: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3247: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3248: \ array beginning at addr and containing u elements
3249: @{ xt @}
3250: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3251: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3252: 1 cells POSTPONE literal POSTPONE +loop ;
3253:
3254: : sum-array ( addr u -- n )
3255: 0 rot rot [ ' + compile-map-array ] ;
3256: see sum-array
3257: a 5 sum-array .
3258: @end example
3259:
3260: You can use the full power of Forth for generating the code; here's an
3261: example where the code is generated in a loop:
3262:
3263: @example
3264: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3265: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3266: POSTPONE tuck POSTPONE @@
1.48 anton 3267: POSTPONE literal POSTPONE * POSTPONE +
3268: POSTPONE swap POSTPONE cell+ ;
3269:
3270: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3271: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3272: 0 postpone literal postpone swap
3273: [ ' compile-vmul-step compile-map-array ]
3274: postpone drop ;
3275: see compile-vmul
3276:
3277: : a-vmul ( addr -- n )
1.51 pazsan 3278: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3279: [ a 5 compile-vmul ] ;
3280: see a-vmul
3281: a a-vmul .
3282: @end example
3283:
3284: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3285: also use @code{map-array} instead (try it now!).
1.48 anton 3286:
3287: You can use this technique for efficient multiplication of large
3288: matrices. In matrix multiplication, you multiply every line of one
3289: matrix with every column of the other matrix. You can generate the code
3290: for one line once, and use it for every column. The only downside of
3291: this technique is that it is cumbersome to recover the memory consumed
3292: by the generated code when you are done (and in more complicated cases
3293: it is not possible portably).
3294:
1.66 anton 3295: @c !! @xref{Macros} for reference
3296:
3297:
1.48 anton 3298: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3299: @section Compilation Tokens
1.66 anton 3300: @cindex compilation tokens, tutorial
3301: @cindex CT, tutorial
1.48 anton 3302:
3303: This section is Gforth-specific. You can skip it.
3304:
3305: @code{' word compile,} compiles the interpretation semantics. For words
3306: with default compilation semantics this is the same as performing the
3307: compilation semantics. To represent the compilation semantics of other
3308: words (e.g., words like @code{if} that have no interpretation
3309: semantics), Gforth has the concept of a compilation token (CT,
3310: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3311: You can perform the compilation semantics represented by a CT with
3312: @code{execute}:
1.29 crook 3313:
1.48 anton 3314: @example
3315: : foo2 ( n1 n2 -- n )
3316: [ comp' + execute ] ;
3317: see foo
3318: @end example
1.29 crook 3319:
1.48 anton 3320: You can compile the compilation semantics represented by a CT with
3321: @code{postpone,}:
1.30 anton 3322:
1.48 anton 3323: @example
3324: : foo3 ( -- )
3325: [ comp' + postpone, ] ;
3326: see foo3
3327: @end example
1.30 anton 3328:
1.51 pazsan 3329: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3330: @code{comp'} is particularly useful for words that have no
3331: interpretation semantics:
1.29 crook 3332:
1.30 anton 3333: @example
1.48 anton 3334: ' if
1.60 anton 3335: comp' if .s 2drop
1.30 anton 3336: @end example
3337:
1.66 anton 3338: Reference: @ref{Tokens for Words}.
3339:
1.29 crook 3340:
1.48 anton 3341: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3342: @section Wordlists and Search Order
1.66 anton 3343: @cindex wordlists tutorial
3344: @cindex search order, tutorial
1.48 anton 3345:
3346: The dictionary is not just a memory area that allows you to allocate
3347: memory with @code{allot}, it also contains the Forth words, arranged in
3348: several wordlists. When searching for a word in a wordlist,
3349: conceptually you start searching at the youngest and proceed towards
3350: older words (in reality most systems nowadays use hash-tables); i.e., if
3351: you define a word with the same name as an older word, the new word
3352: shadows the older word.
3353:
3354: Which wordlists are searched in which order is determined by the search
3355: order. You can display the search order with @code{order}. It displays
3356: first the search order, starting with the wordlist searched first, then
3357: it displays the wordlist that will contain newly defined words.
1.21 crook 3358:
1.48 anton 3359: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3360:
1.48 anton 3361: @example
3362: wordlist constant mywords
3363: @end example
1.21 crook 3364:
1.48 anton 3365: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3366: defined words (the @emph{current} wordlist):
1.21 crook 3367:
1.48 anton 3368: @example
3369: mywords set-current
3370: order
3371: @end example
1.26 crook 3372:
1.48 anton 3373: Gforth does not display a name for the wordlist in @code{mywords}
3374: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3375:
1.48 anton 3376: You can get the current wordlist with @code{get-current ( -- wid)}. If
3377: you want to put something into a specific wordlist without overall
3378: effect on the current wordlist, this typically looks like this:
1.21 crook 3379:
1.48 anton 3380: @example
3381: get-current mywords set-current ( wid )
3382: create someword
3383: ( wid ) set-current
3384: @end example
1.21 crook 3385:
1.48 anton 3386: You can write the search order with @code{set-order ( wid1 .. widn n --
3387: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3388: searched wordlist is topmost.
1.21 crook 3389:
1.48 anton 3390: @example
3391: get-order mywords swap 1+ set-order
3392: order
3393: @end example
1.21 crook 3394:
1.48 anton 3395: Yes, the order of wordlists in the output of @code{order} is reversed
3396: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3397:
1.141 anton 3398: @quotation Assignment
1.48 anton 3399: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3400: wordlist to the search order. Define @code{previous ( -- )}, which
3401: removes the first searched wordlist from the search order. Experiment
3402: with boundary conditions (you will see some crashes or situations that
3403: are hard or impossible to leave).
1.141 anton 3404: @end quotation
1.21 crook 3405:
1.48 anton 3406: The search order is a powerful foundation for providing features similar
3407: to Modula-2 modules and C++ namespaces. However, trying to modularize
3408: programs in this way has disadvantages for debugging and reuse/factoring
3409: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3410: though). These disadvantages are not so clear in other
1.82 anton 3411: languages/programming environments, because these languages are not so
1.48 anton 3412: strong in debugging and reuse.
1.21 crook 3413:
1.66 anton 3414: @c !! example
3415:
3416: Reference: @ref{Word Lists}.
1.21 crook 3417:
1.29 crook 3418: @c ******************************************************************
1.48 anton 3419: @node Introduction, Words, Tutorial, Top
1.29 crook 3420: @comment node-name, next, previous, up
3421: @chapter An Introduction to ANS Forth
3422: @cindex Forth - an introduction
1.21 crook 3423:
1.83 anton 3424: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3425: that it is slower-paced in its examples, but uses them to dive deep into
3426: explaining Forth internals (not covered by the Tutorial). Apart from
3427: that, this chapter covers far less material. It is suitable for reading
3428: without using a computer.
3429:
1.29 crook 3430: The primary purpose of this manual is to document Gforth. However, since
3431: Forth is not a widely-known language and there is a lack of up-to-date
3432: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3433: material. For other sources of Forth-related
3434: information, see @ref{Forth-related information}.
1.21 crook 3435:
1.29 crook 3436: The examples in this section should work on any ANS Forth; the
3437: output shown was produced using Gforth. Each example attempts to
3438: reproduce the exact output that Gforth produces. If you try out the
3439: examples (and you should), what you should type is shown @kbd{like this}
3440: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3441: that, where the example shows @key{RET} it means that you should
1.29 crook 3442: press the ``carriage return'' key. Unfortunately, some output formats for
3443: this manual cannot show the difference between @kbd{this} and
3444: @code{this} which will make trying out the examples harder (but not
3445: impossible).
1.21 crook 3446:
1.29 crook 3447: Forth is an unusual language. It provides an interactive development
3448: environment which includes both an interpreter and compiler. Forth
3449: programming style encourages you to break a problem down into many
3450: @cindex factoring
3451: small fragments (@dfn{factoring}), and then to develop and test each
3452: fragment interactively. Forth advocates assert that breaking the
3453: edit-compile-test cycle used by conventional programming languages can
3454: lead to great productivity improvements.
1.21 crook 3455:
1.29 crook 3456: @menu
1.67 anton 3457: * Introducing the Text Interpreter::
3458: * Stacks and Postfix notation::
3459: * Your first definition::
3460: * How does that work?::
3461: * Forth is written in Forth::
3462: * Review - elements of a Forth system::
3463: * Where to go next::
3464: * Exercises::
1.29 crook 3465: @end menu
1.21 crook 3466:
1.29 crook 3467: @comment ----------------------------------------------
3468: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3469: @section Introducing the Text Interpreter
3470: @cindex text interpreter
3471: @cindex outer interpreter
1.21 crook 3472:
1.30 anton 3473: @c IMO this is too detailed and the pace is too slow for
3474: @c an introduction. If you know German, take a look at
3475: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3476: @c to see how I do it - anton
3477:
1.44 crook 3478: @c nac-> Where I have accepted your comments 100% and modified the text
3479: @c accordingly, I have deleted your comments. Elsewhere I have added a
3480: @c response like this to attempt to rationalise what I have done. Of
3481: @c course, this is a very clumsy mechanism for something that would be
3482: @c done far more efficiently over a beer. Please delete any dialogue
3483: @c you consider closed.
3484:
1.29 crook 3485: When you invoke the Forth image, you will see a startup banner printed
3486: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3487: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3488: its command line interpreter, which is called the @dfn{Text Interpreter}
3489: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3490: about the text interpreter as you read through this chapter, for more
3491: detail @pxref{The Text Interpreter}).
1.21 crook 3492:
1.29 crook 3493: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3494: input. Type a number and press the @key{RET} key:
1.21 crook 3495:
1.26 crook 3496: @example
1.30 anton 3497: @kbd{45@key{RET}} ok
1.26 crook 3498: @end example
1.21 crook 3499:
1.29 crook 3500: Rather than give you a prompt to invite you to input something, the text
3501: interpreter prints a status message @i{after} it has processed a line
3502: of input. The status message in this case (``@code{ ok}'' followed by
3503: carriage-return) indicates that the text interpreter was able to process
3504: all of your input successfully. Now type something illegal:
3505:
3506: @example
1.30 anton 3507: @kbd{qwer341@key{RET}}
1.134 anton 3508: *the terminal*:2: Undefined word
3509: >>>qwer341<<<
3510: Backtrace:
3511: $2A95B42A20 throw
3512: $2A95B57FB8 no.extensions
1.29 crook 3513: @end example
1.23 crook 3514:
1.134 anton 3515: The exact text, other than the ``Undefined word'' may differ slightly
3516: on your system, but the effect is the same; when the text interpreter
1.29 crook 3517: detects an error, it discards any remaining text on a line, resets
1.134 anton 3518: certain internal state and prints an error message. For a detailed
3519: description of error messages see @ref{Error messages}.
1.23 crook 3520:
1.29 crook 3521: The text interpreter waits for you to press carriage-return, and then
3522: processes your input line. Starting at the beginning of the line, it
3523: breaks the line into groups of characters separated by spaces. For each
3524: group of characters in turn, it makes two attempts to do something:
1.23 crook 3525:
1.29 crook 3526: @itemize @bullet
3527: @item
1.44 crook 3528: @cindex name dictionary
1.29 crook 3529: It tries to treat it as a command. It does this by searching a @dfn{name
3530: dictionary}. If the group of characters matches an entry in the name
3531: dictionary, the name dictionary provides the text interpreter with
3532: information that allows the text interpreter perform some actions. In
3533: Forth jargon, we say that the group
3534: @cindex word
3535: @cindex definition
3536: @cindex execution token
3537: @cindex xt
3538: of characters names a @dfn{word}, that the dictionary search returns an
3539: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3540: word, and that the text interpreter executes the xt. Often, the terms
3541: @dfn{word} and @dfn{definition} are used interchangeably.
3542: @item
3543: If the text interpreter fails to find a match in the name dictionary, it
3544: tries to treat the group of characters as a number in the current number
3545: base (when you start up Forth, the current number base is base 10). If
3546: the group of characters legitimately represents a number, the text
3547: interpreter pushes the number onto a stack (we'll learn more about that
3548: in the next section).
3549: @end itemize
1.23 crook 3550:
1.29 crook 3551: If the text interpreter is unable to do either of these things with any
3552: group of characters, it discards the group of characters and the rest of
3553: the line, then prints an error message. If the text interpreter reaches
3554: the end of the line without error, it prints the status message ``@code{ ok}''
3555: followed by carriage-return.
1.21 crook 3556:
1.29 crook 3557: This is the simplest command we can give to the text interpreter:
1.23 crook 3558:
3559: @example
1.30 anton 3560: @key{RET} ok
1.23 crook 3561: @end example
1.21 crook 3562:
1.29 crook 3563: The text interpreter did everything we asked it to do (nothing) without
3564: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3565: command:
1.21 crook 3566:
1.23 crook 3567: @example
1.30 anton 3568: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3569: *the terminal*:3: Undefined word
3570: 12 dup >>>fred<<< dup
3571: Backtrace:
3572: $2A95B42A20 throw
3573: $2A95B57FB8 no.extensions
1.23 crook 3574: @end example
1.21 crook 3575:
1.29 crook 3576: When you press the carriage-return key, the text interpreter starts to
3577: work its way along the line:
1.21 crook 3578:
1.29 crook 3579: @itemize @bullet
3580: @item
3581: When it gets to the space after the @code{2}, it takes the group of
3582: characters @code{12} and looks them up in the name
3583: dictionary@footnote{We can't tell if it found them or not, but assume
3584: for now that it did not}. There is no match for this group of characters
3585: in the name dictionary, so it tries to treat them as a number. It is
3586: able to do this successfully, so it puts the number, 12, ``on the stack''
3587: (whatever that means).
3588: @item
3589: The text interpreter resumes scanning the line and gets the next group
3590: of characters, @code{dup}. It looks it up in the name dictionary and
3591: (you'll have to take my word for this) finds it, and executes the word
3592: @code{dup} (whatever that means).
3593: @item
3594: Once again, the text interpreter resumes scanning the line and gets the
3595: group of characters @code{fred}. It looks them up in the name
3596: dictionary, but can't find them. It tries to treat them as a number, but
3597: they don't represent any legal number.
3598: @end itemize
1.21 crook 3599:
1.29 crook 3600: At this point, the text interpreter gives up and prints an error
3601: message. The error message shows exactly how far the text interpreter
3602: got in processing the line. In particular, it shows that the text
3603: interpreter made no attempt to do anything with the final character
3604: group, @code{dup}, even though we have good reason to believe that the
3605: text interpreter would have no problem looking that word up and
3606: executing it a second time.
1.21 crook 3607:
3608:
1.29 crook 3609: @comment ----------------------------------------------
3610: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3611: @section Stacks, postfix notation and parameter passing
3612: @cindex text interpreter
3613: @cindex outer interpreter
1.21 crook 3614:
1.29 crook 3615: In procedural programming languages (like C and Pascal), the
3616: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3617: functions or procedures are called with @dfn{explicit parameters}. For
3618: example, in C we might write:
1.21 crook 3619:
1.23 crook 3620: @example
1.29 crook 3621: total = total + new_volume(length,height,depth);
1.23 crook 3622: @end example
1.21 crook 3623:
1.23 crook 3624: @noindent
1.29 crook 3625: where new_volume is a function-call to another piece of code, and total,
3626: length, height and depth are all variables. length, height and depth are
3627: parameters to the function-call.
1.21 crook 3628:
1.29 crook 3629: In Forth, the equivalent of the function or procedure is the
3630: @dfn{definition} and parameters are implicitly passed between
3631: definitions using a shared stack that is visible to the
3632: programmer. Although Forth does support variables, the existence of the
3633: stack means that they are used far less often than in most other
3634: programming languages. When the text interpreter encounters a number, it
3635: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3636: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3637: used for any operation is implied unambiguously by the operation being
3638: performed. The stack used for all integer operations is called the @dfn{data
3639: stack} and, since this is the stack used most commonly, references to
3640: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3641:
1.29 crook 3642: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3643:
1.23 crook 3644: @example
1.30 anton 3645: @kbd{1 2 3@key{RET}} ok
1.23 crook 3646: @end example
1.21 crook 3647:
1.29 crook 3648: Then this instructs the text interpreter to placed three numbers on the
3649: (data) stack. An analogy for the behaviour of the stack is to take a
3650: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3651: the table. The 3 was the last card onto the pile (``last-in'') and if
3652: you take a card off the pile then, unless you're prepared to fiddle a
3653: bit, the card that you take off will be the 3 (``first-out''). The
3654: number that will be first-out of the stack is called the @dfn{top of
3655: stack}, which
3656: @cindex TOS definition
3657: is often abbreviated to @dfn{TOS}.
1.21 crook 3658:
1.29 crook 3659: To understand how parameters are passed in Forth, consider the
3660: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3661: be surprised to learn that this definition performs addition. More
3662: precisely, it adds two number together and produces a result. Where does
3663: it get the two numbers from? It takes the top two numbers off the
3664: stack. Where does it place the result? On the stack. You can act-out the
3665: behaviour of @code{+} with your playing cards like this:
1.21 crook 3666:
3667: @itemize @bullet
3668: @item
1.29 crook 3669: Pick up two cards from the stack on the table
1.21 crook 3670: @item
1.29 crook 3671: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3672: numbers''
1.21 crook 3673: @item
1.29 crook 3674: Decide that the answer is 5
1.21 crook 3675: @item
1.29 crook 3676: Shuffle the two cards back into the pack and find a 5
1.21 crook 3677: @item
1.29 crook 3678: Put a 5 on the remaining ace that's on the table.
1.21 crook 3679: @end itemize
3680:
1.29 crook 3681: If you don't have a pack of cards handy but you do have Forth running,
3682: you can use the definition @code{.s} to show the current state of the stack,
3683: without affecting the stack. Type:
1.21 crook 3684:
3685: @example
1.124 anton 3686: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3687: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3688: @end example
3689:
1.124 anton 3690: The text interpreter looks up the word @code{clearstacks} and executes
3691: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3692: left on it by earlier examples. The text interpreter pushes each of the
3693: three numbers in turn onto the stack. Finally, the text interpreter
3694: looks up the word @code{.s} and executes it. The effect of executing
3695: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3696: followed by a list of all the items on the stack; the item on the far
3697: right-hand side is the TOS.
1.21 crook 3698:
1.29 crook 3699: You can now type:
1.21 crook 3700:
1.29 crook 3701: @example
1.30 anton 3702: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3703: @end example
1.21 crook 3704:
1.29 crook 3705: @noindent
3706: which is correct; there are now 2 items on the stack and the result of
3707: the addition is 5.
1.23 crook 3708:
1.29 crook 3709: If you're playing with cards, try doing a second addition: pick up the
3710: two cards, work out that their sum is 6, shuffle them into the pack,
3711: look for a 6 and place that on the table. You now have just one item on
3712: the stack. What happens if you try to do a third addition? Pick up the
3713: first card, pick up the second card -- ah! There is no second card. This
3714: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3715: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3716: Underflow or an Invalid Memory Address error).
1.23 crook 3717:
1.29 crook 3718: The opposite situation to a stack underflow is a @dfn{stack overflow},
3719: which simply accepts that there is a finite amount of storage space
3720: reserved for the stack. To stretch the playing card analogy, if you had
3721: enough packs of cards and you piled the cards up on the table, you would
3722: eventually be unable to add another card; you'd hit the ceiling. Gforth
3723: allows you to set the maximum size of the stacks. In general, the only
3724: time that you will get a stack overflow is because a definition has a
3725: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3726:
1.29 crook 3727: There's one final use for the playing card analogy. If you model your
3728: stack using a pack of playing cards, the maximum number of items on
3729: your stack will be 52 (I assume you didn't use the Joker). The maximum
3730: @i{value} of any item on the stack is 13 (the King). In fact, the only
3731: possible numbers are positive integer numbers 1 through 13; you can't
3732: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3733: think about some of the cards, you can accommodate different
3734: numbers. For example, you could think of the Jack as representing 0,
3735: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3736: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3737: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3738:
1.29 crook 3739: In that analogy, the limit was the amount of information that a single
3740: stack entry could hold, and Forth has a similar limit. In Forth, the
3741: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3742: implementation dependent and affects the maximum value that a stack
3743: entry can hold. A Standard Forth provides a cell size of at least
3744: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3745:
1.29 crook 3746: Forth does not do any type checking for you, so you are free to
3747: manipulate and combine stack items in any way you wish. A convenient way
3748: of treating stack items is as 2's complement signed integers, and that
3749: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3750:
1.29 crook 3751: @example
1.30 anton 3752: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3753: @end example
1.21 crook 3754:
1.29 crook 3755: If you use numbers and definitions like @code{+} in order to turn Forth
3756: into a great big pocket calculator, you will realise that it's rather
3757: different from a normal calculator. Rather than typing 2 + 3 = you had
3758: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3759: result). The terminology used to describe this difference is to say that
3760: your calculator uses @dfn{Infix Notation} (parameters and operators are
3761: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3762: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3763:
1.29 crook 3764: Whilst postfix notation might look confusing to begin with, it has
3765: several important advantages:
1.21 crook 3766:
1.23 crook 3767: @itemize @bullet
3768: @item
1.29 crook 3769: it is unambiguous
1.23 crook 3770: @item
1.29 crook 3771: it is more concise
1.23 crook 3772: @item
1.29 crook 3773: it fits naturally with a stack-based system
1.23 crook 3774: @end itemize
1.21 crook 3775:
1.29 crook 3776: To examine these claims in more detail, consider these sums:
1.21 crook 3777:
1.29 crook 3778: @example
3779: 6 + 5 * 4 =
3780: 4 * 5 + 6 =
3781: @end example
1.21 crook 3782:
1.29 crook 3783: If you're just learning maths or your maths is very rusty, you will
3784: probably come up with the answer 44 for the first and 26 for the
3785: second. If you are a bit of a whizz at maths you will remember the
3786: @i{convention} that multiplication takes precendence over addition, and
3787: you'd come up with the answer 26 both times. To explain the answer 26
3788: to someone who got the answer 44, you'd probably rewrite the first sum
3789: like this:
1.21 crook 3790:
1.29 crook 3791: @example
3792: 6 + (5 * 4) =
3793: @end example
1.21 crook 3794:
1.29 crook 3795: If what you really wanted was to perform the addition before the
3796: multiplication, you would have to use parentheses to force it.
1.21 crook 3797:
1.29 crook 3798: If you did the first two sums on a pocket calculator you would probably
3799: get the right answers, unless you were very cautious and entered them using
3800: these keystroke sequences:
1.21 crook 3801:
1.29 crook 3802: 6 + 5 = * 4 =
3803: 4 * 5 = + 6 =
1.21 crook 3804:
1.29 crook 3805: Postfix notation is unambiguous because the order that the operators
3806: are applied is always explicit; that also means that parentheses are
3807: never required. The operators are @i{active} (the act of quoting the
3808: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3809:
1.29 crook 3810: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3811: equivalent ways:
1.26 crook 3812:
3813: @example
1.29 crook 3814: 6 5 4 * + or:
3815: 5 4 * 6 +
1.26 crook 3816: @end example
1.23 crook 3817:
1.29 crook 3818: An important thing that you should notice about this notation is that
3819: the @i{order} of the numbers does not change; if you want to subtract
3820: 2 from 10 you type @code{10 2 -}.
1.1 anton 3821:
1.29 crook 3822: The reason that Forth uses postfix notation is very simple to explain: it
3823: makes the implementation extremely simple, and it follows naturally from
3824: using the stack as a mechanism for passing parameters. Another way of
3825: thinking about this is to realise that all Forth definitions are
3826: @i{active}; they execute as they are encountered by the text
3827: interpreter. The result of this is that the syntax of Forth is trivially
3828: simple.
1.1 anton 3829:
3830:
3831:
1.29 crook 3832: @comment ----------------------------------------------
3833: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3834: @section Your first Forth definition
3835: @cindex first definition
1.1 anton 3836:
1.29 crook 3837: Until now, the examples we've seen have been trivial; we've just been
3838: using Forth as a bigger-than-pocket calculator. Also, each calculation
3839: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3840: again@footnote{That's not quite true. If you press the up-arrow key on
3841: your keyboard you should be able to scroll back to any earlier command,
3842: edit it and re-enter it.} In this section we'll see how to add new
3843: words to Forth's vocabulary.
1.1 anton 3844:
1.29 crook 3845: The easiest way to create a new word is to use a @dfn{colon
3846: definition}. We'll define a few and try them out before worrying too
3847: much about how they work. Try typing in these examples; be careful to
3848: copy the spaces accurately:
1.1 anton 3849:
1.29 crook 3850: @example
3851: : add-two 2 + . ;
3852: : greet ." Hello and welcome" ;
3853: : demo 5 add-two ;
3854: @end example
1.1 anton 3855:
1.29 crook 3856: @noindent
3857: Now try them out:
1.1 anton 3858:
1.29 crook 3859: @example
1.30 anton 3860: @kbd{greet@key{RET}} Hello and welcome ok
3861: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3862: @kbd{4 add-two@key{RET}} 6 ok
3863: @kbd{demo@key{RET}} 7 ok
3864: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3865: @end example
1.1 anton 3866:
1.29 crook 3867: The first new thing that we've introduced here is the pair of words
3868: @code{:} and @code{;}. These are used to start and terminate a new
3869: definition, respectively. The first word after the @code{:} is the name
3870: for the new definition.
1.1 anton 3871:
1.29 crook 3872: As you can see from the examples, a definition is built up of words that
3873: have already been defined; Forth makes no distinction between
3874: definitions that existed when you started the system up, and those that
3875: you define yourself.
1.1 anton 3876:
1.29 crook 3877: The examples also introduce the words @code{.} (dot), @code{."}
3878: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3879: the stack and displays it. It's like @code{.s} except that it only
3880: displays the top item of the stack and it is destructive; after it has
3881: executed, the number is no longer on the stack. There is always one
3882: space printed after the number, and no spaces before it. Dot-quote
3883: defines a string (a sequence of characters) that will be printed when
3884: the word is executed. The string can contain any printable characters
3885: except @code{"}. A @code{"} has a special function; it is not a Forth
3886: word but it acts as a delimiter (the way that delimiters work is
3887: described in the next section). Finally, @code{dup} duplicates the value
3888: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3889:
1.29 crook 3890: We already know that the text interpreter searches through the
3891: dictionary to locate names. If you've followed the examples earlier, you
3892: will already have a definition called @code{add-two}. Lets try modifying
3893: it by typing in a new definition:
1.1 anton 3894:
1.29 crook 3895: @example
1.30 anton 3896: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3897: @end example
1.5 anton 3898:
1.29 crook 3899: Forth recognised that we were defining a word that already exists, and
3900: printed a message to warn us of that fact. Let's try out the new
3901: definition:
1.5 anton 3902:
1.29 crook 3903: @example
1.30 anton 3904: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3905: @end example
1.1 anton 3906:
1.29 crook 3907: @noindent
3908: All that we've actually done here, though, is to create a new
3909: definition, with a particular name. The fact that there was already a
3910: definition with the same name did not make any difference to the way
3911: that the new definition was created (except that Forth printed a warning
3912: message). The old definition of add-two still exists (try @code{demo}
3913: again to see that this is true). Any new definition will use the new
3914: definition of @code{add-two}, but old definitions continue to use the
3915: version that already existed at the time that they were @code{compiled}.
1.1 anton 3916:
1.29 crook 3917: Before you go on to the next section, try defining and redefining some
3918: words of your own.
1.1 anton 3919:
1.29 crook 3920: @comment ----------------------------------------------
3921: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3922: @section How does that work?
3923: @cindex parsing words
1.1 anton 3924:
1.30 anton 3925: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3926:
3927: @c Is it a good idea to talk about the interpretation semantics of a
3928: @c number? We don't have an xt to go along with it. - anton
3929:
3930: @c Now that I have eliminated execution semantics, I wonder if it would not
3931: @c be better to keep them (or add run-time semantics), to make it easier to
3932: @c explain what compilation semantics usually does. - anton
3933:
1.44 crook 3934: @c nac-> I removed the term ``default compilation sematics'' from the
3935: @c introductory chapter. Removing ``execution semantics'' was making
3936: @c everything simpler to explain, then I think the use of this term made
3937: @c everything more complex again. I replaced it with ``default
3938: @c semantics'' (which is used elsewhere in the manual) by which I mean
3939: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3940: @c flag set''.
3941:
3942: @c anton: I have eliminated default semantics (except in one place where it
3943: @c means "default interpretation and compilation semantics"), because it
3944: @c makes no sense in the presence of combined words. I reverted to
3945: @c "execution semantics" where necessary.
3946:
3947: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3948: @c section (and, unusually for me, I think I even made it shorter!). See
3949: @c what you think -- I know I have not addressed your primary concern
3950: @c that it is too heavy-going for an introduction. From what I understood
3951: @c of your course notes it looks as though they might be a good framework.
3952: @c Things that I've tried to capture here are some things that came as a
3953: @c great revelation here when I first understood them. Also, I like the
3954: @c fact that a very simple code example shows up almost all of the issues
3955: @c that you need to understand to see how Forth works. That's unique and
3956: @c worthwhile to emphasise.
3957:
1.83 anton 3958: @c anton: I think it's a good idea to present the details, especially those
3959: @c that you found to be a revelation, and probably the tutorial tries to be
3960: @c too superficial and does not get some of the things across that make
3961: @c Forth special. I do believe that most of the time these things should
3962: @c be discussed at the end of a section or in separate sections instead of
3963: @c in the middle of a section (e.g., the stuff you added in "User-defined
3964: @c defining words" leads in a completely different direction from the rest
3965: @c of the section).
3966:
1.29 crook 3967: Now we're going to take another look at the definition of @code{add-two}
3968: from the previous section. From our knowledge of the way that the text
3969: interpreter works, we would have expected this result when we tried to
3970: define @code{add-two}:
1.21 crook 3971:
1.29 crook 3972: @example
1.44 crook 3973: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3974: *the terminal*:4: Undefined word
3975: : >>>add-two<<< 2 + . ;
1.29 crook 3976: @end example
1.28 crook 3977:
1.29 crook 3978: The reason that this didn't happen is bound up in the way that @code{:}
3979: works. The word @code{:} does two special things. The first special
3980: thing that it does prevents the text interpreter from ever seeing the
3981: characters @code{add-two}. The text interpreter uses a variable called
3982: @cindex modifying >IN
1.44 crook 3983: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3984: input line. When it encounters the word @code{:} it behaves in exactly
3985: the same way as it does for any other word; it looks it up in the name
3986: dictionary, finds its xt and executes it. When @code{:} executes, it
3987: looks at the input buffer, finds the word @code{add-two} and advances the
3988: value of @code{>IN} to point past it. It then does some other stuff
3989: associated with creating the new definition (including creating an entry
3990: for @code{add-two} in the name dictionary). When the execution of @code{:}
3991: completes, control returns to the text interpreter, which is oblivious
3992: to the fact that it has been tricked into ignoring part of the input
3993: line.
1.21 crook 3994:
1.29 crook 3995: @cindex parsing words
3996: Words like @code{:} -- words that advance the value of @code{>IN} and so
3997: prevent the text interpreter from acting on the whole of the input line
3998: -- are called @dfn{parsing words}.
1.21 crook 3999:
1.29 crook 4000: @cindex @code{state} - effect on the text interpreter
4001: @cindex text interpreter - effect of state
4002: The second special thing that @code{:} does is change the value of a
4003: variable called @code{state}, which affects the way that the text
4004: interpreter behaves. When Gforth starts up, @code{state} has the value
4005: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4006: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4007: the text interpreter is said to be @dfn{compiling}.
4008:
4009: In this example, the text interpreter is compiling when it processes the
4010: string ``@code{2 + . ;}''. It still breaks the string down into
4011: character sequences in the same way. However, instead of pushing the
4012: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4013: into the definition of @code{add-two} that will make the number @code{2} get
4014: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4015: the behaviours of @code{+} and @code{.} are also compiled into the
4016: definition.
4017:
4018: One category of words don't get compiled. These so-called @dfn{immediate
4019: words} get executed (performed @i{now}) regardless of whether the text
4020: interpreter is interpreting or compiling. The word @code{;} is an
4021: immediate word. Rather than being compiled into the definition, it
4022: executes. Its effect is to terminate the current definition, which
4023: includes changing the value of @code{state} back to 0.
4024:
4025: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4026: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4027: definition.
1.28 crook 4028:
1.30 anton 4029: In Forth, every word or number can be described in terms of two
1.29 crook 4030: properties:
1.28 crook 4031:
4032: @itemize @bullet
4033: @item
1.29 crook 4034: @cindex interpretation semantics
1.44 crook 4035: Its @dfn{interpretation semantics} describe how it will behave when the
4036: text interpreter encounters it in @dfn{interpret} state. The
4037: interpretation semantics of a word are represented by an @dfn{execution
4038: token}.
1.28 crook 4039: @item
1.29 crook 4040: @cindex compilation semantics
1.44 crook 4041: Its @dfn{compilation semantics} describe how it will behave when the
4042: text interpreter encounters it in @dfn{compile} state. The compilation
4043: semantics of a word are represented in an implementation-dependent way;
4044: Gforth uses a @dfn{compilation token}.
1.29 crook 4045: @end itemize
4046:
4047: @noindent
4048: Numbers are always treated in a fixed way:
4049:
4050: @itemize @bullet
1.28 crook 4051: @item
1.44 crook 4052: When the number is @dfn{interpreted}, its behaviour is to push the
4053: number onto the stack.
1.28 crook 4054: @item
1.30 anton 4055: When the number is @dfn{compiled}, a piece of code is appended to the
4056: current definition that pushes the number when it runs. (In other words,
4057: the compilation semantics of a number are to postpone its interpretation
4058: semantics until the run-time of the definition that it is being compiled
4059: into.)
1.29 crook 4060: @end itemize
4061:
1.44 crook 4062: Words don't behave in such a regular way, but most have @i{default
4063: semantics} which means that they behave like this:
1.29 crook 4064:
4065: @itemize @bullet
1.28 crook 4066: @item
1.30 anton 4067: The @dfn{interpretation semantics} of the word are to do something useful.
4068: @item
1.29 crook 4069: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4070: @dfn{interpretation semantics} to the current definition (so that its
4071: run-time behaviour is to do something useful).
1.28 crook 4072: @end itemize
4073:
1.30 anton 4074: @cindex immediate words
1.44 crook 4075: The actual behaviour of any particular word can be controlled by using
4076: the words @code{immediate} and @code{compile-only} when the word is
4077: defined. These words set flags in the name dictionary entry of the most
4078: recently defined word, and these flags are retrieved by the text
4079: interpreter when it finds the word in the name dictionary.
4080:
4081: A word that is marked as @dfn{immediate} has compilation semantics that
4082: are identical to its interpretation semantics. In other words, it
4083: behaves like this:
1.29 crook 4084:
4085: @itemize @bullet
4086: @item
1.30 anton 4087: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4088: @item
1.30 anton 4089: The @dfn{compilation semantics} of the word are to do something useful
4090: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4091: @end itemize
1.28 crook 4092:
1.44 crook 4093: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4094: performing the interpretation semantics of the word directly; an attempt
4095: to do so will generate an error. It is never necessary to use
4096: @code{compile-only} (and it is not even part of ANS Forth, though it is
4097: provided by many implementations) but it is good etiquette to apply it
4098: to a word that will not behave correctly (and might have unexpected
4099: side-effects) in interpret state. For example, it is only legal to use
4100: the conditional word @code{IF} within a definition. If you forget this
4101: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4102: @code{compile-only} allows the text interpreter to generate a helpful
4103: error message rather than subjecting you to the consequences of your
4104: folly.
4105:
1.29 crook 4106: This example shows the difference between an immediate and a
4107: non-immediate word:
1.28 crook 4108:
1.29 crook 4109: @example
4110: : show-state state @@ . ;
4111: : show-state-now show-state ; immediate
4112: : word1 show-state ;
4113: : word2 show-state-now ;
1.28 crook 4114: @end example
1.23 crook 4115:
1.29 crook 4116: The word @code{immediate} after the definition of @code{show-state-now}
4117: makes that word an immediate word. These definitions introduce a new
4118: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4119: variable, and leaves it on the stack. Therefore, the behaviour of
4120: @code{show-state} is to print a number that represents the current value
4121: of @code{state}.
1.28 crook 4122:
1.29 crook 4123: When you execute @code{word1}, it prints the number 0, indicating that
4124: the system is interpreting. When the text interpreter compiled the
4125: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4126: compilation semantics are to append its interpretation semantics to the
1.29 crook 4127: current definition. When you execute @code{word1}, it performs the
1.30 anton 4128: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4129: (and therefore @code{show-state}) are executed, the system is
4130: interpreting.
1.28 crook 4131:
1.30 anton 4132: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4133: you should have seen the number -1 printed, followed by ``@code{
4134: ok}''. When the text interpreter compiled the definition of
4135: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4136: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4137: semantics. It is executed straight away (even before the text
4138: interpreter has moved on to process another group of characters; the
4139: @code{;} in this example). The effect of executing it are to display the
4140: value of @code{state} @i{at the time that the definition of}
4141: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4142: system is compiling at this time. If you execute @code{word2} it does
4143: nothing at all.
1.28 crook 4144:
1.29 crook 4145: @cindex @code{."}, how it works
4146: Before leaving the subject of immediate words, consider the behaviour of
4147: @code{."} in the definition of @code{greet}, in the previous
4148: section. This word is both a parsing word and an immediate word. Notice
4149: that there is a space between @code{."} and the start of the text
4150: @code{Hello and welcome}, but that there is no space between the last
4151: letter of @code{welcome} and the @code{"} character. The reason for this
4152: is that @code{."} is a Forth word; it must have a space after it so that
4153: the text interpreter can identify it. The @code{"} is not a Forth word;
4154: it is a @dfn{delimiter}. The examples earlier show that, when the string
4155: is displayed, there is neither a space before the @code{H} nor after the
4156: @code{e}. Since @code{."} is an immediate word, it executes at the time
4157: that @code{greet} is defined. When it executes, its behaviour is to
4158: search forward in the input line looking for the delimiter. When it
4159: finds the delimiter, it updates @code{>IN} to point past the
4160: delimiter. It also compiles some magic code into the definition of
4161: @code{greet}; the xt of a run-time routine that prints a text string. It
4162: compiles the string @code{Hello and welcome} into memory so that it is
4163: available to be printed later. When the text interpreter gains control,
4164: the next word it finds in the input stream is @code{;} and so it
4165: terminates the definition of @code{greet}.
1.28 crook 4166:
4167:
4168: @comment ----------------------------------------------
1.29 crook 4169: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4170: @section Forth is written in Forth
4171: @cindex structure of Forth programs
4172:
4173: When you start up a Forth compiler, a large number of definitions
4174: already exist. In Forth, you develop a new application using bottom-up
4175: programming techniques to create new definitions that are defined in
4176: terms of existing definitions. As you create each definition you can
4177: test and debug it interactively.
4178:
4179: If you have tried out the examples in this section, you will probably
4180: have typed them in by hand; when you leave Gforth, your definitions will
4181: be lost. You can avoid this by using a text editor to enter Forth source
4182: code into a file, and then loading code from the file using
1.49 anton 4183: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4184: processed by the text interpreter, just as though you had typed it in by
4185: hand@footnote{Actually, there are some subtle differences -- see
4186: @ref{The Text Interpreter}.}.
4187:
4188: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4189: files for program entry (@pxref{Blocks}).
1.28 crook 4190:
1.29 crook 4191: In common with many, if not most, Forth compilers, most of Gforth is
4192: actually written in Forth. All of the @file{.fs} files in the
4193: installation directory@footnote{For example,
1.30 anton 4194: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4195: study to see examples of Forth programming.
1.28 crook 4196:
1.29 crook 4197: Gforth maintains a history file that records every line that you type to
4198: the text interpreter. This file is preserved between sessions, and is
4199: used to provide a command-line recall facility. If you enter long
4200: definitions by hand, you can use a text editor to paste them out of the
4201: history file into a Forth source file for reuse at a later time
1.49 anton 4202: (for more information @pxref{Command-line editing}).
1.28 crook 4203:
4204:
4205: @comment ----------------------------------------------
1.29 crook 4206: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4207: @section Review - elements of a Forth system
4208: @cindex elements of a Forth system
1.28 crook 4209:
1.29 crook 4210: To summarise this chapter:
1.28 crook 4211:
4212: @itemize @bullet
4213: @item
1.29 crook 4214: Forth programs use @dfn{factoring} to break a problem down into small
4215: fragments called @dfn{words} or @dfn{definitions}.
4216: @item
4217: Forth program development is an interactive process.
4218: @item
4219: The main command loop that accepts input, and controls both
4220: interpretation and compilation, is called the @dfn{text interpreter}
4221: (also known as the @dfn{outer interpreter}).
4222: @item
4223: Forth has a very simple syntax, consisting of words and numbers
4224: separated by spaces or carriage-return characters. Any additional syntax
4225: is imposed by @dfn{parsing words}.
4226: @item
4227: Forth uses a stack to pass parameters between words. As a result, it
4228: uses postfix notation.
4229: @item
4230: To use a word that has previously been defined, the text interpreter
4231: searches for the word in the @dfn{name dictionary}.
4232: @item
1.30 anton 4233: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4234: @item
1.29 crook 4235: The text interpreter uses the value of @code{state} to select between
4236: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4237: semantics} of a word that it encounters.
1.28 crook 4238: @item
1.30 anton 4239: The relationship between the @dfn{interpretation semantics} and
4240: @dfn{compilation semantics} for a word
1.29 crook 4241: depend upon the way in which the word was defined (for example, whether
4242: it is an @dfn{immediate} word).
1.28 crook 4243: @item
1.29 crook 4244: Forth definitions can be implemented in Forth (called @dfn{high-level
4245: definitions}) or in some other way (usually a lower-level language and
4246: as a result often called @dfn{low-level definitions}, @dfn{code
4247: definitions} or @dfn{primitives}).
1.28 crook 4248: @item
1.29 crook 4249: Many Forth systems are implemented mainly in Forth.
1.28 crook 4250: @end itemize
4251:
4252:
1.29 crook 4253: @comment ----------------------------------------------
1.48 anton 4254: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4255: @section Where To Go Next
4256: @cindex where to go next
1.28 crook 4257:
1.29 crook 4258: Amazing as it may seem, if you have read (and understood) this far, you
4259: know almost all the fundamentals about the inner workings of a Forth
4260: system. You certainly know enough to be able to read and understand the
4261: rest of this manual and the ANS Forth document, to learn more about the
4262: facilities that Forth in general and Gforth in particular provide. Even
4263: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4264: However, that's not a good idea just yet... better to try writing some
1.29 crook 4265: programs in Gforth.
1.28 crook 4266:
1.29 crook 4267: Forth has such a rich vocabulary that it can be hard to know where to
4268: start in learning it. This section suggests a few sets of words that are
4269: enough to write small but useful programs. Use the word index in this
4270: document to learn more about each word, then try it out and try to write
4271: small definitions using it. Start by experimenting with these words:
1.28 crook 4272:
4273: @itemize @bullet
4274: @item
1.29 crook 4275: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4276: @item
4277: Comparison: @code{MIN MAX =}
4278: @item
4279: Logic: @code{AND OR XOR NOT}
4280: @item
4281: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4282: @item
1.29 crook 4283: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4284: @item
1.29 crook 4285: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4286: @item
1.29 crook 4287: Defining words: @code{: ; CREATE}
1.28 crook 4288: @item
1.29 crook 4289: Memory allocation words: @code{ALLOT ,}
1.28 crook 4290: @item
1.29 crook 4291: Tools: @code{SEE WORDS .S MARKER}
4292: @end itemize
4293:
4294: When you have mastered those, go on to:
4295:
4296: @itemize @bullet
1.28 crook 4297: @item
1.29 crook 4298: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4299: @item
1.29 crook 4300: Memory access: @code{@@ !}
1.28 crook 4301: @end itemize
1.23 crook 4302:
1.29 crook 4303: When you have mastered these, there's nothing for it but to read through
4304: the whole of this manual and find out what you've missed.
4305:
4306: @comment ----------------------------------------------
1.48 anton 4307: @node Exercises, , Where to go next, Introduction
1.29 crook 4308: @section Exercises
4309: @cindex exercises
4310:
4311: TODO: provide a set of programming excercises linked into the stuff done
4312: already and into other sections of the manual. Provide solutions to all
4313: the exercises in a .fs file in the distribution.
4314:
4315: @c Get some inspiration from Starting Forth and Kelly&Spies.
4316:
4317: @c excercises:
4318: @c 1. take inches and convert to feet and inches.
4319: @c 2. take temperature and convert from fahrenheight to celcius;
4320: @c may need to care about symmetric vs floored??
4321: @c 3. take input line and do character substitution
4322: @c to encipher or decipher
4323: @c 4. as above but work on a file for in and out
4324: @c 5. take input line and convert to pig-latin
4325: @c
4326: @c thing of sets of things to exercise then come up with
4327: @c problems that need those things.
4328:
4329:
1.26 crook 4330: @c ******************************************************************
1.29 crook 4331: @node Words, Error messages, Introduction, Top
1.1 anton 4332: @chapter Forth Words
1.26 crook 4333: @cindex words
1.1 anton 4334:
4335: @menu
4336: * Notation::
1.65 anton 4337: * Case insensitivity::
4338: * Comments::
4339: * Boolean Flags::
1.1 anton 4340: * Arithmetic::
4341: * Stack Manipulation::
1.5 anton 4342: * Memory::
1.1 anton 4343: * Control Structures::
4344: * Defining Words::
1.65 anton 4345: * Interpretation and Compilation Semantics::
1.47 crook 4346: * Tokens for Words::
1.81 anton 4347: * Compiling words::
1.65 anton 4348: * The Text Interpreter::
1.111 anton 4349: * The Input Stream::
1.65 anton 4350: * Word Lists::
4351: * Environmental Queries::
1.12 anton 4352: * Files::
4353: * Blocks::
4354: * Other I/O::
1.121 anton 4355: * OS command line arguments::
1.78 anton 4356: * Locals::
4357: * Structures::
4358: * Object-oriented Forth::
1.12 anton 4359: * Programming Tools::
1.150 anton 4360: * C Interface::
1.12 anton 4361: * Assembler and Code Words::
4362: * Threading Words::
1.65 anton 4363: * Passing Commands to the OS::
4364: * Keeping track of Time::
4365: * Miscellaneous Words::
1.1 anton 4366: @end menu
4367:
1.65 anton 4368: @node Notation, Case insensitivity, Words, Words
1.1 anton 4369: @section Notation
4370: @cindex notation of glossary entries
4371: @cindex format of glossary entries
4372: @cindex glossary notation format
4373: @cindex word glossary entry format
4374:
4375: The Forth words are described in this section in the glossary notation
1.67 anton 4376: that has become a de-facto standard for Forth texts:
1.1 anton 4377:
4378: @format
1.29 crook 4379: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4380: @end format
1.29 crook 4381: @i{Description}
1.1 anton 4382:
4383: @table @var
4384: @item word
1.28 crook 4385: The name of the word.
1.1 anton 4386:
4387: @item Stack effect
4388: @cindex stack effect
1.29 crook 4389: The stack effect is written in the notation @code{@i{before} --
4390: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4391: stack entries before and after the execution of the word. The rest of
4392: the stack is not touched by the word. The top of stack is rightmost,
4393: i.e., a stack sequence is written as it is typed in. Note that Gforth
4394: uses a separate floating point stack, but a unified stack
1.29 crook 4395: notation. Also, return stack effects are not shown in @i{stack
4396: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4397: the type and/or the function of the item. See below for a discussion of
4398: the types.
4399:
4400: All words have two stack effects: A compile-time stack effect and a
4401: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4402: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4403: this standard behaviour, or the word does other unusual things at
4404: compile time, both stack effects are shown; otherwise only the run-time
4405: stack effect is shown.
4406:
4407: @cindex pronounciation of words
4408: @item pronunciation
4409: How the word is pronounced.
4410:
4411: @cindex wordset
1.67 anton 4412: @cindex environment wordset
1.1 anton 4413: @item wordset
1.21 crook 4414: The ANS Forth standard is divided into several word sets. A standard
4415: system need not support all of them. Therefore, in theory, the fewer
4416: word sets your program uses the more portable it will be. However, we
4417: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4418: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4419: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4420: describes words that will work in future releases of Gforth;
4421: @code{gforth-internal} words are more volatile. Environmental query
4422: strings are also displayed like words; you can recognize them by the
1.21 crook 4423: @code{environment} in the word set field.
1.1 anton 4424:
4425: @item Description
4426: A description of the behaviour of the word.
4427: @end table
4428:
4429: @cindex types of stack items
4430: @cindex stack item types
4431: The type of a stack item is specified by the character(s) the name
4432: starts with:
4433:
4434: @table @code
4435: @item f
4436: @cindex @code{f}, stack item type
4437: Boolean flags, i.e. @code{false} or @code{true}.
4438: @item c
4439: @cindex @code{c}, stack item type
4440: Char
4441: @item w
4442: @cindex @code{w}, stack item type
4443: Cell, can contain an integer or an address
4444: @item n
4445: @cindex @code{n}, stack item type
4446: signed integer
4447: @item u
4448: @cindex @code{u}, stack item type
4449: unsigned integer
4450: @item d
4451: @cindex @code{d}, stack item type
4452: double sized signed integer
4453: @item ud
4454: @cindex @code{ud}, stack item type
4455: double sized unsigned integer
4456: @item r
4457: @cindex @code{r}, stack item type
4458: Float (on the FP stack)
1.21 crook 4459: @item a-
1.1 anton 4460: @cindex @code{a_}, stack item type
4461: Cell-aligned address
1.21 crook 4462: @item c-
1.1 anton 4463: @cindex @code{c_}, stack item type
4464: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4465: @item f-
1.1 anton 4466: @cindex @code{f_}, stack item type
4467: Float-aligned address
1.21 crook 4468: @item df-
1.1 anton 4469: @cindex @code{df_}, stack item type
4470: Address aligned for IEEE double precision float
1.21 crook 4471: @item sf-
1.1 anton 4472: @cindex @code{sf_}, stack item type
4473: Address aligned for IEEE single precision float
4474: @item xt
4475: @cindex @code{xt}, stack item type
4476: Execution token, same size as Cell
4477: @item wid
4478: @cindex @code{wid}, stack item type
1.21 crook 4479: Word list ID, same size as Cell
1.68 anton 4480: @item ior, wior
4481: @cindex ior type description
4482: @cindex wior type description
4483: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4484: @item f83name
4485: @cindex @code{f83name}, stack item type
4486: Pointer to a name structure
4487: @item "
4488: @cindex @code{"}, stack item type
1.12 anton 4489: string in the input stream (not on the stack). The terminating character
4490: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4491: quotes.
4492: @end table
4493:
1.65 anton 4494: @comment ----------------------------------------------
4495: @node Case insensitivity, Comments, Notation, Words
4496: @section Case insensitivity
4497: @cindex case sensitivity
4498: @cindex upper and lower case
4499:
4500: Gforth is case-insensitive; you can enter definitions and invoke
4501: Standard words using upper, lower or mixed case (however,
4502: @pxref{core-idef, Implementation-defined options, Implementation-defined
4503: options}).
4504:
4505: ANS Forth only @i{requires} implementations to recognise Standard words
4506: when they are typed entirely in upper case. Therefore, a Standard
4507: program must use upper case for all Standard words. You can use whatever
4508: case you like for words that you define, but in a Standard program you
4509: have to use the words in the same case that you defined them.
4510:
4511: Gforth supports case sensitivity through @code{table}s (case-sensitive
4512: wordlists, @pxref{Word Lists}).
4513:
4514: Two people have asked how to convert Gforth to be case-sensitive; while
4515: we think this is a bad idea, you can change all wordlists into tables
4516: like this:
4517:
4518: @example
4519: ' table-find forth-wordlist wordlist-map @ !
4520: @end example
4521:
4522: Note that you now have to type the predefined words in the same case
4523: that we defined them, which are varying. You may want to convert them
4524: to your favourite case before doing this operation (I won't explain how,
4525: because if you are even contemplating doing this, you'd better have
4526: enough knowledge of Forth systems to know this already).
4527:
4528: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4529: @section Comments
1.26 crook 4530: @cindex comments
1.21 crook 4531:
1.29 crook 4532: Forth supports two styles of comment; the traditional @i{in-line} comment,
4533: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4534:
1.44 crook 4535:
1.23 crook 4536: doc-(
1.21 crook 4537: doc-\
1.23 crook 4538: doc-\G
1.21 crook 4539:
1.44 crook 4540:
1.21 crook 4541: @node Boolean Flags, Arithmetic, Comments, Words
4542: @section Boolean Flags
1.26 crook 4543: @cindex Boolean flags
1.21 crook 4544:
4545: A Boolean flag is cell-sized. A cell with all bits clear represents the
4546: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4547: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4548: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4549: @c on and off to Memory?
4550: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4551:
1.21 crook 4552: doc-true
4553: doc-false
1.29 crook 4554: doc-on
4555: doc-off
1.21 crook 4556:
1.44 crook 4557:
1.21 crook 4558: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4559: @section Arithmetic
4560: @cindex arithmetic words
4561:
4562: @cindex division with potentially negative operands
4563: Forth arithmetic is not checked, i.e., you will not hear about integer
4564: overflow on addition or multiplication, you may hear about division by
4565: zero if you are lucky. The operator is written after the operands, but
4566: the operands are still in the original order. I.e., the infix @code{2-1}
4567: corresponds to @code{2 1 -}. Forth offers a variety of division
4568: operators. If you perform division with potentially negative operands,
4569: you do not want to use @code{/} or @code{/mod} with its undefined
4570: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4571: former, @pxref{Mixed precision}).
1.26 crook 4572: @comment TODO discuss the different division forms and the std approach
1.1 anton 4573:
4574: @menu
4575: * Single precision::
1.67 anton 4576: * Double precision:: Double-cell integer arithmetic
1.1 anton 4577: * Bitwise operations::
1.67 anton 4578: * Numeric comparison::
1.29 crook 4579: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4580: * Floating Point::
4581: @end menu
4582:
1.67 anton 4583: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4584: @subsection Single precision
4585: @cindex single precision arithmetic words
4586:
1.67 anton 4587: @c !! cell undefined
4588:
4589: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4590: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4591: treat them. For the rules used by the text interpreter for recognising
4592: single-precision integers see @ref{Number Conversion}.
1.21 crook 4593:
1.67 anton 4594: These words are all defined for signed operands, but some of them also
4595: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4596: @code{*}.
1.44 crook 4597:
1.1 anton 4598: doc-+
1.21 crook 4599: doc-1+
1.128 anton 4600: doc-under+
1.1 anton 4601: doc--
1.21 crook 4602: doc-1-
1.1 anton 4603: doc-*
4604: doc-/
4605: doc-mod
4606: doc-/mod
4607: doc-negate
4608: doc-abs
4609: doc-min
4610: doc-max
1.27 crook 4611: doc-floored
1.1 anton 4612:
1.44 crook 4613:
1.67 anton 4614: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4615: @subsection Double precision
4616: @cindex double precision arithmetic words
4617:
1.49 anton 4618: For the rules used by the text interpreter for
4619: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4620:
4621: A double precision number is represented by a cell pair, with the most
1.67 anton 4622: significant cell at the TOS. It is trivial to convert an unsigned single
4623: to a double: simply push a @code{0} onto the TOS. Since numbers are
4624: represented by Gforth using 2's complement arithmetic, converting a
4625: signed single to a (signed) double requires sign-extension across the
4626: most significant cell. This can be achieved using @code{s>d}. The moral
4627: of the story is that you cannot convert a number without knowing whether
4628: it represents an unsigned or a signed number.
1.21 crook 4629:
1.67 anton 4630: These words are all defined for signed operands, but some of them also
4631: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4632:
1.21 crook 4633: doc-s>d
1.67 anton 4634: doc-d>s
1.21 crook 4635: doc-d+
4636: doc-d-
4637: doc-dnegate
4638: doc-dabs
4639: doc-dmin
4640: doc-dmax
4641:
1.44 crook 4642:
1.67 anton 4643: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4644: @subsection Bitwise operations
4645: @cindex bitwise operation words
4646:
4647:
4648: doc-and
4649: doc-or
4650: doc-xor
4651: doc-invert
4652: doc-lshift
4653: doc-rshift
4654: doc-2*
4655: doc-d2*
4656: doc-2/
4657: doc-d2/
4658:
4659:
4660: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4661: @subsection Numeric comparison
4662: @cindex numeric comparison words
4663:
1.67 anton 4664: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4665: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4666:
1.28 crook 4667: doc-<
4668: doc-<=
4669: doc-<>
4670: doc-=
4671: doc->
4672: doc->=
4673:
1.21 crook 4674: doc-0<
1.23 crook 4675: doc-0<=
1.21 crook 4676: doc-0<>
4677: doc-0=
1.23 crook 4678: doc-0>
4679: doc-0>=
1.28 crook 4680:
4681: doc-u<
4682: doc-u<=
1.44 crook 4683: @c u<> and u= exist but are the same as <> and =
1.31 anton 4684: @c doc-u<>
4685: @c doc-u=
1.28 crook 4686: doc-u>
4687: doc-u>=
4688:
4689: doc-within
4690:
4691: doc-d<
4692: doc-d<=
4693: doc-d<>
4694: doc-d=
4695: doc-d>
4696: doc-d>=
1.23 crook 4697:
1.21 crook 4698: doc-d0<
1.23 crook 4699: doc-d0<=
4700: doc-d0<>
1.21 crook 4701: doc-d0=
1.23 crook 4702: doc-d0>
4703: doc-d0>=
4704:
1.21 crook 4705: doc-du<
1.28 crook 4706: doc-du<=
1.44 crook 4707: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4708: @c doc-du<>
4709: @c doc-du=
1.28 crook 4710: doc-du>
4711: doc-du>=
1.1 anton 4712:
1.44 crook 4713:
1.21 crook 4714: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4715: @subsection Mixed precision
4716: @cindex mixed precision arithmetic words
4717:
1.44 crook 4718:
1.1 anton 4719: doc-m+
4720: doc-*/
4721: doc-*/mod
4722: doc-m*
4723: doc-um*
4724: doc-m*/
4725: doc-um/mod
4726: doc-fm/mod
4727: doc-sm/rem
4728:
1.44 crook 4729:
1.21 crook 4730: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4731: @subsection Floating Point
4732: @cindex floating point arithmetic words
4733:
1.49 anton 4734: For the rules used by the text interpreter for
4735: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4736:
1.67 anton 4737: Gforth has a separate floating point stack, but the documentation uses
4738: the unified notation.@footnote{It's easy to generate the separate
4739: notation from that by just separating the floating-point numbers out:
4740: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4741: r3 )}.}
1.1 anton 4742:
4743: @cindex floating-point arithmetic, pitfalls
4744: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4745: unwary (e.g., floating point addition is not associative) and even a
4746: few for the wary. You should not use them unless you know what you are
4747: doing or you don't care that the results you get are totally bogus. If
4748: you want to learn about the problems of floating point numbers (and
4749: how to avoid them), you might start with @cite{David Goldberg,
4750: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4751: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4752: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4753:
1.44 crook 4754:
1.21 crook 4755: doc-d>f
4756: doc-f>d
1.1 anton 4757: doc-f+
4758: doc-f-
4759: doc-f*
4760: doc-f/
4761: doc-fnegate
4762: doc-fabs
4763: doc-fmax
4764: doc-fmin
4765: doc-floor
4766: doc-fround
4767: doc-f**
4768: doc-fsqrt
4769: doc-fexp
4770: doc-fexpm1
4771: doc-fln
4772: doc-flnp1
4773: doc-flog
4774: doc-falog
1.32 anton 4775: doc-f2*
4776: doc-f2/
4777: doc-1/f
4778: doc-precision
4779: doc-set-precision
4780:
4781: @cindex angles in trigonometric operations
4782: @cindex trigonometric operations
4783: Angles in floating point operations are given in radians (a full circle
4784: has 2 pi radians).
4785:
1.1 anton 4786: doc-fsin
4787: doc-fcos
4788: doc-fsincos
4789: doc-ftan
4790: doc-fasin
4791: doc-facos
4792: doc-fatan
4793: doc-fatan2
4794: doc-fsinh
4795: doc-fcosh
4796: doc-ftanh
4797: doc-fasinh
4798: doc-facosh
4799: doc-fatanh
1.21 crook 4800: doc-pi
1.28 crook 4801:
1.32 anton 4802: @cindex equality of floats
4803: @cindex floating-point comparisons
1.31 anton 4804: One particular problem with floating-point arithmetic is that comparison
4805: for equality often fails when you would expect it to succeed. For this
4806: reason approximate equality is often preferred (but you still have to
1.67 anton 4807: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4808: differently from what you might expect. The comparison words are:
1.31 anton 4809:
4810: doc-f~rel
4811: doc-f~abs
1.68 anton 4812: doc-f~
1.31 anton 4813: doc-f=
4814: doc-f<>
4815:
4816: doc-f<
4817: doc-f<=
4818: doc-f>
4819: doc-f>=
4820:
1.21 crook 4821: doc-f0<
1.28 crook 4822: doc-f0<=
4823: doc-f0<>
1.21 crook 4824: doc-f0=
1.28 crook 4825: doc-f0>
4826: doc-f0>=
4827:
1.1 anton 4828:
4829: @node Stack Manipulation, Memory, Arithmetic, Words
4830: @section Stack Manipulation
4831: @cindex stack manipulation words
4832:
4833: @cindex floating-point stack in the standard
1.21 crook 4834: Gforth maintains a number of separate stacks:
4835:
1.29 crook 4836: @cindex data stack
4837: @cindex parameter stack
1.21 crook 4838: @itemize @bullet
4839: @item
1.29 crook 4840: A data stack (also known as the @dfn{parameter stack}) -- for
4841: characters, cells, addresses, and double cells.
1.21 crook 4842:
1.29 crook 4843: @cindex floating-point stack
1.21 crook 4844: @item
1.44 crook 4845: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4846:
1.29 crook 4847: @cindex return stack
1.21 crook 4848: @item
1.44 crook 4849: A return stack -- for holding the return addresses of colon
1.32 anton 4850: definitions and other (non-FP) data.
1.21 crook 4851:
1.29 crook 4852: @cindex locals stack
1.21 crook 4853: @item
1.44 crook 4854: A locals stack -- for holding local variables.
1.21 crook 4855: @end itemize
4856:
1.1 anton 4857: @menu
4858: * Data stack::
4859: * Floating point stack::
4860: * Return stack::
4861: * Locals stack::
4862: * Stack pointer manipulation::
4863: @end menu
4864:
4865: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4866: @subsection Data stack
4867: @cindex data stack manipulation words
4868: @cindex stack manipulations words, data stack
4869:
1.44 crook 4870:
1.1 anton 4871: doc-drop
4872: doc-nip
4873: doc-dup
4874: doc-over
4875: doc-tuck
4876: doc-swap
1.21 crook 4877: doc-pick
1.1 anton 4878: doc-rot
4879: doc--rot
4880: doc-?dup
4881: doc-roll
4882: doc-2drop
4883: doc-2nip
4884: doc-2dup
4885: doc-2over
4886: doc-2tuck
4887: doc-2swap
4888: doc-2rot
4889:
1.44 crook 4890:
1.1 anton 4891: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4892: @subsection Floating point stack
4893: @cindex floating-point stack manipulation words
4894: @cindex stack manipulation words, floating-point stack
4895:
1.32 anton 4896: Whilst every sane Forth has a separate floating-point stack, it is not
4897: strictly required; an ANS Forth system could theoretically keep
4898: floating-point numbers on the data stack. As an additional difficulty,
4899: you don't know how many cells a floating-point number takes. It is
4900: reportedly possible to write words in a way that they work also for a
4901: unified stack model, but we do not recommend trying it. Instead, just
4902: say that your program has an environmental dependency on a separate
4903: floating-point stack.
4904:
4905: doc-floating-stack
4906:
1.1 anton 4907: doc-fdrop
4908: doc-fnip
4909: doc-fdup
4910: doc-fover
4911: doc-ftuck
4912: doc-fswap
1.21 crook 4913: doc-fpick
1.1 anton 4914: doc-frot
4915:
1.44 crook 4916:
1.1 anton 4917: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4918: @subsection Return stack
4919: @cindex return stack manipulation words
4920: @cindex stack manipulation words, return stack
4921:
1.32 anton 4922: @cindex return stack and locals
4923: @cindex locals and return stack
4924: A Forth system is allowed to keep local variables on the
4925: return stack. This is reasonable, as local variables usually eliminate
4926: the need to use the return stack explicitly. So, if you want to produce
4927: a standard compliant program and you are using local variables in a
4928: word, forget about return stack manipulations in that word (refer to the
4929: standard document for the exact rules).
4930:
1.1 anton 4931: doc->r
4932: doc-r>
4933: doc-r@
4934: doc-rdrop
4935: doc-2>r
4936: doc-2r>
4937: doc-2r@
4938: doc-2rdrop
4939:
1.44 crook 4940:
1.1 anton 4941: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4942: @subsection Locals stack
4943:
1.78 anton 4944: Gforth uses an extra locals stack. It is described, along with the
4945: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4946:
1.1 anton 4947: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4948: @subsection Stack pointer manipulation
4949: @cindex stack pointer manipulation words
4950:
1.44 crook 4951: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4952: doc-sp0
1.1 anton 4953: doc-sp@
4954: doc-sp!
1.21 crook 4955: doc-fp0
1.1 anton 4956: doc-fp@
4957: doc-fp!
1.21 crook 4958: doc-rp0
1.1 anton 4959: doc-rp@
4960: doc-rp!
1.21 crook 4961: doc-lp0
1.1 anton 4962: doc-lp@
4963: doc-lp!
4964:
1.44 crook 4965:
1.1 anton 4966: @node Memory, Control Structures, Stack Manipulation, Words
4967: @section Memory
1.26 crook 4968: @cindex memory words
1.1 anton 4969:
1.32 anton 4970: @menu
4971: * Memory model::
4972: * Dictionary allocation::
4973: * Heap Allocation::
4974: * Memory Access::
4975: * Address arithmetic::
4976: * Memory Blocks::
4977: @end menu
4978:
1.67 anton 4979: In addition to the standard Forth memory allocation words, there is also
4980: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4981: garbage collector}.
4982:
1.32 anton 4983: @node Memory model, Dictionary allocation, Memory, Memory
4984: @subsection ANS Forth and Gforth memory models
4985:
4986: @c The ANS Forth description is a mess (e.g., is the heap part of
4987: @c the dictionary?), so let's not stick to closely with it.
4988:
1.67 anton 4989: ANS Forth considers a Forth system as consisting of several address
4990: spaces, of which only @dfn{data space} is managed and accessible with
4991: the memory words. Memory not necessarily in data space includes the
4992: stacks, the code (called code space) and the headers (called name
4993: space). In Gforth everything is in data space, but the code for the
4994: primitives is usually read-only.
1.32 anton 4995:
4996: Data space is divided into a number of areas: The (data space portion of
4997: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4998: refer to the search data structure embodied in word lists and headers,
4999: because it is used for looking up names, just as you would in a
5000: conventional dictionary.}, the heap, and a number of system-allocated
5001: buffers.
5002:
1.68 anton 5003: @cindex address arithmetic restrictions, ANS vs. Gforth
5004: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5005: In ANS Forth data space is also divided into contiguous regions. You
5006: can only use address arithmetic within a contiguous region, not between
5007: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5008: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5009: allocation}).
5010:
5011: Gforth provides one big address space, and address arithmetic can be
5012: performed between any addresses. However, in the dictionary headers or
5013: code are interleaved with data, so almost the only contiguous data space
5014: regions there are those described by ANS Forth as contiguous; but you
5015: can be sure that the dictionary is allocated towards increasing
5016: addresses even between contiguous regions. The memory order of
5017: allocations in the heap is platform-dependent (and possibly different
5018: from one run to the next).
5019:
1.27 crook 5020:
1.32 anton 5021: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5022: @subsection Dictionary allocation
1.27 crook 5023: @cindex reserving data space
5024: @cindex data space - reserving some
5025:
1.32 anton 5026: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5027: you want to deallocate X, you also deallocate everything
5028: allocated after X.
5029:
1.68 anton 5030: @cindex contiguous regions in dictionary allocation
1.32 anton 5031: The allocations using the words below are contiguous and grow the region
5032: towards increasing addresses. Other words that allocate dictionary
5033: memory of any kind (i.e., defining words including @code{:noname}) end
5034: the contiguous region and start a new one.
5035:
5036: In ANS Forth only @code{create}d words are guaranteed to produce an
5037: address that is the start of the following contiguous region. In
5038: particular, the cell allocated by @code{variable} is not guaranteed to
5039: be contiguous with following @code{allot}ed memory.
5040:
5041: You can deallocate memory by using @code{allot} with a negative argument
5042: (with some restrictions, see @code{allot}). For larger deallocations use
5043: @code{marker}.
1.27 crook 5044:
1.29 crook 5045:
1.27 crook 5046: doc-here
5047: doc-unused
5048: doc-allot
5049: doc-c,
1.29 crook 5050: doc-f,
1.27 crook 5051: doc-,
5052: doc-2,
5053:
1.32 anton 5054: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5055: course you should allocate memory in an aligned way, too. I.e., before
5056: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5057: The words below align @code{here} if it is not already. Basically it is
5058: only already aligned for a type, if the last allocation was a multiple
5059: of the size of this type and if @code{here} was aligned for this type
5060: before.
5061:
5062: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5063: ANS Forth (@code{maxalign}ed in Gforth).
5064:
5065: doc-align
5066: doc-falign
5067: doc-sfalign
5068: doc-dfalign
5069: doc-maxalign
5070: doc-cfalign
5071:
5072:
5073: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5074: @subsection Heap allocation
5075: @cindex heap allocation
5076: @cindex dynamic allocation of memory
5077: @cindex memory-allocation word set
5078:
1.68 anton 5079: @cindex contiguous regions and heap allocation
1.32 anton 5080: Heap allocation supports deallocation of allocated memory in any
5081: order. Dictionary allocation is not affected by it (i.e., it does not
5082: end a contiguous region). In Gforth, these words are implemented using
5083: the standard C library calls malloc(), free() and resize().
5084:
1.68 anton 5085: The memory region produced by one invocation of @code{allocate} or
5086: @code{resize} is internally contiguous. There is no contiguity between
5087: such a region and any other region (including others allocated from the
5088: heap).
5089:
1.32 anton 5090: doc-allocate
5091: doc-free
5092: doc-resize
5093:
1.27 crook 5094:
1.32 anton 5095: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5096: @subsection Memory Access
5097: @cindex memory access words
5098:
5099: doc-@
5100: doc-!
5101: doc-+!
5102: doc-c@
5103: doc-c!
5104: doc-2@
5105: doc-2!
5106: doc-f@
5107: doc-f!
5108: doc-sf@
5109: doc-sf!
5110: doc-df@
5111: doc-df!
1.144 anton 5112: doc-sw@
5113: doc-uw@
5114: doc-w!
5115: doc-sl@
5116: doc-ul@
5117: doc-l!
1.68 anton 5118:
1.32 anton 5119: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5120: @subsection Address arithmetic
1.1 anton 5121: @cindex address arithmetic words
5122:
1.67 anton 5123: Address arithmetic is the foundation on which you can build data
5124: structures like arrays, records (@pxref{Structures}) and objects
5125: (@pxref{Object-oriented Forth}).
1.32 anton 5126:
1.68 anton 5127: @cindex address unit
5128: @cindex au (address unit)
1.1 anton 5129: ANS Forth does not specify the sizes of the data types. Instead, it
5130: offers a number of words for computing sizes and doing address
1.29 crook 5131: arithmetic. Address arithmetic is performed in terms of address units
5132: (aus); on most systems the address unit is one byte. Note that a
5133: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5134: platforms where it is a noop, it compiles to nothing).
1.1 anton 5135:
1.67 anton 5136: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5137: you have the address of a cell, perform @code{1 cells +}, and you will
5138: have the address of the next cell.
5139:
1.68 anton 5140: @cindex contiguous regions and address arithmetic
1.67 anton 5141: In ANS Forth you can perform address arithmetic only within a contiguous
5142: region, i.e., if you have an address into one region, you can only add
5143: and subtract such that the result is still within the region; you can
5144: only subtract or compare addresses from within the same contiguous
5145: region. Reasons: several contiguous regions can be arranged in memory
5146: in any way; on segmented systems addresses may have unusual
5147: representations, such that address arithmetic only works within a
5148: region. Gforth provides a few more guarantees (linear address space,
5149: dictionary grows upwards), but in general I have found it easy to stay
5150: within contiguous regions (exception: computing and comparing to the
5151: address just beyond the end of an array).
5152:
1.1 anton 5153: @cindex alignment of addresses for types
5154: ANS Forth also defines words for aligning addresses for specific
5155: types. Many computers require that accesses to specific data types
5156: must only occur at specific addresses; e.g., that cells may only be
5157: accessed at addresses divisible by 4. Even if a machine allows unaligned
5158: accesses, it can usually perform aligned accesses faster.
5159:
5160: For the performance-conscious: alignment operations are usually only
5161: necessary during the definition of a data structure, not during the
5162: (more frequent) accesses to it.
5163:
5164: ANS Forth defines no words for character-aligning addresses. This is not
5165: an oversight, but reflects the fact that addresses that are not
5166: char-aligned have no use in the standard and therefore will not be
5167: created.
5168:
5169: @cindex @code{CREATE} and alignment
1.29 crook 5170: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5171: are cell-aligned; in addition, Gforth guarantees that these addresses
5172: are aligned for all purposes.
5173:
1.26 crook 5174: Note that the ANS Forth word @code{char} has nothing to do with address
5175: arithmetic.
1.1 anton 5176:
1.44 crook 5177:
1.1 anton 5178: doc-chars
5179: doc-char+
5180: doc-cells
5181: doc-cell+
5182: doc-cell
5183: doc-aligned
5184: doc-floats
5185: doc-float+
5186: doc-float
5187: doc-faligned
5188: doc-sfloats
5189: doc-sfloat+
5190: doc-sfaligned
5191: doc-dfloats
5192: doc-dfloat+
5193: doc-dfaligned
5194: doc-maxaligned
5195: doc-cfaligned
5196: doc-address-unit-bits
1.145 anton 5197: doc-/w
5198: doc-/l
1.44 crook 5199:
1.32 anton 5200: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5201: @subsection Memory Blocks
5202: @cindex memory block words
1.27 crook 5203: @cindex character strings - moving and copying
5204:
1.49 anton 5205: Memory blocks often represent character strings; For ways of storing
5206: character strings in memory see @ref{String Formats}. For other
5207: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5208:
1.67 anton 5209: A few of these words work on address unit blocks. In that case, you
5210: usually have to insert @code{CHARS} before the word when working on
5211: character strings. Most words work on character blocks, and expect a
5212: char-aligned address.
5213:
5214: When copying characters between overlapping memory regions, use
5215: @code{chars move} or choose carefully between @code{cmove} and
5216: @code{cmove>}.
1.44 crook 5217:
1.1 anton 5218: doc-move
5219: doc-erase
5220: doc-cmove
5221: doc-cmove>
5222: doc-fill
5223: doc-blank
1.21 crook 5224: doc-compare
1.111 anton 5225: doc-str=
5226: doc-str<
5227: doc-string-prefix?
1.21 crook 5228: doc-search
1.27 crook 5229: doc--trailing
5230: doc-/string
1.82 anton 5231: doc-bounds
1.141 anton 5232: doc-pad
1.111 anton 5233:
1.27 crook 5234: @comment TODO examples
5235:
1.1 anton 5236:
1.26 crook 5237: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5238: @section Control Structures
5239: @cindex control structures
5240:
1.33 anton 5241: Control structures in Forth cannot be used interpretively, only in a
5242: colon definition@footnote{To be precise, they have no interpretation
5243: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5244: not like this limitation, but have not seen a satisfying way around it
5245: yet, although many schemes have been proposed.
1.1 anton 5246:
5247: @menu
1.33 anton 5248: * Selection:: IF ... ELSE ... ENDIF
5249: * Simple Loops:: BEGIN ...
1.29 crook 5250: * Counted Loops:: DO
1.67 anton 5251: * Arbitrary control structures::
5252: * Calls and returns::
1.1 anton 5253: * Exception Handling::
5254: @end menu
5255:
5256: @node Selection, Simple Loops, Control Structures, Control Structures
5257: @subsection Selection
5258: @cindex selection control structures
5259: @cindex control structures for selection
5260:
5261: @cindex @code{IF} control structure
5262: @example
1.29 crook 5263: @i{flag}
1.1 anton 5264: IF
1.29 crook 5265: @i{code}
1.1 anton 5266: ENDIF
5267: @end example
1.21 crook 5268: @noindent
1.33 anton 5269:
1.44 crook 5270: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5271: with any bit set represents truth) @i{code} is executed.
1.33 anton 5272:
1.1 anton 5273: @example
1.29 crook 5274: @i{flag}
1.1 anton 5275: IF
1.29 crook 5276: @i{code1}
1.1 anton 5277: ELSE
1.29 crook 5278: @i{code2}
1.1 anton 5279: ENDIF
5280: @end example
5281:
1.44 crook 5282: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5283: executed.
1.33 anton 5284:
1.1 anton 5285: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5286: standard, and @code{ENDIF} is not, although it is quite popular. We
5287: recommend using @code{ENDIF}, because it is less confusing for people
5288: who also know other languages (and is not prone to reinforcing negative
5289: prejudices against Forth in these people). Adding @code{ENDIF} to a
5290: system that only supplies @code{THEN} is simple:
5291: @example
1.82 anton 5292: : ENDIF POSTPONE then ; immediate
1.1 anton 5293: @end example
5294:
5295: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5296: (adv.)} has the following meanings:
5297: @quotation
5298: ... 2b: following next after in order ... 3d: as a necessary consequence
5299: (if you were there, then you saw them).
5300: @end quotation
5301: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5302: and many other programming languages has the meaning 3d.]
5303:
1.21 crook 5304: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5305: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5306: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5307: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5308: @file{compat/control.fs}.
5309:
5310: @cindex @code{CASE} control structure
5311: @example
1.29 crook 5312: @i{n}
1.1 anton 5313: CASE
1.29 crook 5314: @i{n1} OF @i{code1} ENDOF
5315: @i{n2} OF @i{code2} ENDOF
1.1 anton 5316: @dots{}
1.68 anton 5317: ( n ) @i{default-code} ( n )
1.131 anton 5318: ENDCASE ( )
1.1 anton 5319: @end example
5320:
1.131 anton 5321: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5322: no @i{ni} matches, the optional @i{default-code} is executed. The
5323: optional default case can be added by simply writing the code after
5324: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5325: but must not consume it. The value @i{n} is consumed by this
5326: construction (either by a OF that matches, or by the ENDCASE, if no OF
5327: matches).
1.1 anton 5328:
1.69 anton 5329: @progstyle
1.131 anton 5330: To keep the code understandable, you should ensure that you change the
5331: stack in the same way (wrt. number and types of stack items consumed
5332: and pushed) on all paths through a selection construct.
1.69 anton 5333:
1.1 anton 5334: @node Simple Loops, Counted Loops, Selection, Control Structures
5335: @subsection Simple Loops
5336: @cindex simple loops
5337: @cindex loops without count
5338:
5339: @cindex @code{WHILE} loop
5340: @example
5341: BEGIN
1.29 crook 5342: @i{code1}
5343: @i{flag}
1.1 anton 5344: WHILE
1.29 crook 5345: @i{code2}
1.1 anton 5346: REPEAT
5347: @end example
5348:
1.29 crook 5349: @i{code1} is executed and @i{flag} is computed. If it is true,
5350: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5351: false, execution continues after the @code{REPEAT}.
5352:
5353: @cindex @code{UNTIL} loop
5354: @example
5355: BEGIN
1.29 crook 5356: @i{code}
5357: @i{flag}
1.1 anton 5358: UNTIL
5359: @end example
5360:
1.29 crook 5361: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5362:
1.69 anton 5363: @progstyle
5364: To keep the code understandable, a complete iteration of the loop should
5365: not change the number and types of the items on the stacks.
5366:
1.1 anton 5367: @cindex endless loop
5368: @cindex loops, endless
5369: @example
5370: BEGIN
1.29 crook 5371: @i{code}
1.1 anton 5372: AGAIN
5373: @end example
5374:
5375: This is an endless loop.
5376:
5377: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5378: @subsection Counted Loops
5379: @cindex counted loops
5380: @cindex loops, counted
5381: @cindex @code{DO} loops
5382:
5383: The basic counted loop is:
5384: @example
1.29 crook 5385: @i{limit} @i{start}
1.1 anton 5386: ?DO
1.29 crook 5387: @i{body}
1.1 anton 5388: LOOP
5389: @end example
5390:
1.29 crook 5391: This performs one iteration for every integer, starting from @i{start}
5392: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5393: accessed with @code{i}. For example, the loop:
1.1 anton 5394: @example
5395: 10 0 ?DO
5396: i .
5397: LOOP
5398: @end example
1.21 crook 5399: @noindent
5400: prints @code{0 1 2 3 4 5 6 7 8 9}
5401:
1.1 anton 5402: The index of the innermost loop can be accessed with @code{i}, the index
5403: of the next loop with @code{j}, and the index of the third loop with
5404: @code{k}.
5405:
1.44 crook 5406:
1.1 anton 5407: doc-i
5408: doc-j
5409: doc-k
5410:
1.44 crook 5411:
1.1 anton 5412: The loop control data are kept on the return stack, so there are some
1.21 crook 5413: restrictions on mixing return stack accesses and counted loop words. In
5414: particuler, if you put values on the return stack outside the loop, you
5415: cannot read them inside the loop@footnote{well, not in a way that is
5416: portable.}. If you put values on the return stack within a loop, you
5417: have to remove them before the end of the loop and before accessing the
5418: index of the loop.
1.1 anton 5419:
5420: There are several variations on the counted loop:
5421:
1.21 crook 5422: @itemize @bullet
5423: @item
5424: @code{LEAVE} leaves the innermost counted loop immediately; execution
5425: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5426:
5427: @example
5428: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5429: @end example
5430: prints @code{0 1 2 3}
5431:
1.1 anton 5432:
1.21 crook 5433: @item
5434: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5435: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5436: return stack so @code{EXIT} can get to its return address. For example:
5437:
5438: @example
5439: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5440: @end example
5441: prints @code{0 1 2 3}
5442:
5443:
5444: @item
1.29 crook 5445: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5446: (and @code{LOOP} iterates until they become equal by wrap-around
5447: arithmetic). This behaviour is usually not what you want. Therefore,
5448: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5449: @code{?DO}), which do not enter the loop if @i{start} is greater than
5450: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5451: unsigned loop parameters.
5452:
1.21 crook 5453: @item
5454: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5455: the loop, independent of the loop parameters. Do not use @code{DO}, even
5456: if you know that the loop is entered in any case. Such knowledge tends
5457: to become invalid during maintenance of a program, and then the
5458: @code{DO} will make trouble.
5459:
5460: @item
1.29 crook 5461: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5462: index by @i{n} instead of by 1. The loop is terminated when the border
5463: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5464:
1.21 crook 5465: @example
5466: 4 0 +DO i . 2 +LOOP
5467: @end example
5468: @noindent
5469: prints @code{0 2}
5470:
5471: @example
5472: 4 1 +DO i . 2 +LOOP
5473: @end example
5474: @noindent
5475: prints @code{1 3}
1.1 anton 5476:
1.68 anton 5477: @item
1.1 anton 5478: @cindex negative increment for counted loops
5479: @cindex counted loops with negative increment
1.29 crook 5480: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5481:
1.21 crook 5482: @example
5483: -1 0 ?DO i . -1 +LOOP
5484: @end example
5485: @noindent
5486: prints @code{0 -1}
1.1 anton 5487:
1.21 crook 5488: @example
5489: 0 0 ?DO i . -1 +LOOP
5490: @end example
5491: prints nothing.
1.1 anton 5492:
1.29 crook 5493: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5494: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5495: index by @i{u} each iteration. The loop is terminated when the border
5496: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5497: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5498:
1.21 crook 5499: @example
5500: -2 0 -DO i . 1 -LOOP
5501: @end example
5502: @noindent
5503: prints @code{0 -1}
1.1 anton 5504:
1.21 crook 5505: @example
5506: -1 0 -DO i . 1 -LOOP
5507: @end example
5508: @noindent
5509: prints @code{0}
5510:
5511: @example
5512: 0 0 -DO i . 1 -LOOP
5513: @end example
5514: @noindent
5515: prints nothing.
1.1 anton 5516:
1.21 crook 5517: @end itemize
1.1 anton 5518:
5519: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5520: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5521: for these words that uses only standard words is provided in
5522: @file{compat/loops.fs}.
1.1 anton 5523:
5524:
5525: @cindex @code{FOR} loops
1.26 crook 5526: Another counted loop is:
1.1 anton 5527: @example
1.29 crook 5528: @i{n}
1.1 anton 5529: FOR
1.29 crook 5530: @i{body}
1.1 anton 5531: NEXT
5532: @end example
5533: This is the preferred loop of native code compiler writers who are too
1.26 crook 5534: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5535: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5536: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5537: Forth systems may behave differently, even if they support @code{FOR}
5538: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5539:
5540: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5541: @subsection Arbitrary control structures
5542: @cindex control structures, user-defined
5543:
5544: @cindex control-flow stack
5545: ANS Forth permits and supports using control structures in a non-nested
5546: way. Information about incomplete control structures is stored on the
5547: control-flow stack. This stack may be implemented on the Forth data
5548: stack, and this is what we have done in Gforth.
5549:
5550: @cindex @code{orig}, control-flow stack item
5551: @cindex @code{dest}, control-flow stack item
5552: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5553: entry represents a backward branch target. A few words are the basis for
5554: building any control structure possible (except control structures that
5555: need storage, like calls, coroutines, and backtracking).
5556:
1.44 crook 5557:
1.1 anton 5558: doc-if
5559: doc-ahead
5560: doc-then
5561: doc-begin
5562: doc-until
5563: doc-again
5564: doc-cs-pick
5565: doc-cs-roll
5566:
1.44 crook 5567:
1.21 crook 5568: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5569: manipulate the control-flow stack in a portable way. Without them, you
5570: would need to know how many stack items are occupied by a control-flow
5571: entry (many systems use one cell. In Gforth they currently take three,
5572: but this may change in the future).
5573:
1.1 anton 5574: Some standard control structure words are built from these words:
5575:
1.44 crook 5576:
1.1 anton 5577: doc-else
5578: doc-while
5579: doc-repeat
5580:
1.44 crook 5581:
5582: @noindent
1.1 anton 5583: Gforth adds some more control-structure words:
5584:
1.44 crook 5585:
1.1 anton 5586: doc-endif
5587: doc-?dup-if
5588: doc-?dup-0=-if
5589:
1.44 crook 5590:
5591: @noindent
1.1 anton 5592: Counted loop words constitute a separate group of words:
5593:
1.44 crook 5594:
1.1 anton 5595: doc-?do
5596: doc-+do
5597: doc-u+do
5598: doc--do
5599: doc-u-do
5600: doc-do
5601: doc-for
5602: doc-loop
5603: doc-+loop
5604: doc--loop
5605: doc-next
5606: doc-leave
5607: doc-?leave
5608: doc-unloop
5609: doc-done
5610:
1.44 crook 5611:
1.21 crook 5612: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5613: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5614: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5615: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5616: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5617: resolved (by using one of the loop-ending words or @code{DONE}).
5618:
1.44 crook 5619: @noindent
1.26 crook 5620: Another group of control structure words are:
1.1 anton 5621:
1.44 crook 5622:
1.1 anton 5623: doc-case
5624: doc-endcase
5625: doc-of
5626: doc-endof
5627:
1.44 crook 5628:
1.21 crook 5629: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5630: @code{CS-ROLL}.
1.1 anton 5631:
5632: @subsubsection Programming Style
1.47 crook 5633: @cindex control structures programming style
5634: @cindex programming style, arbitrary control structures
1.1 anton 5635:
5636: In order to ensure readability we recommend that you do not create
5637: arbitrary control structures directly, but define new control structure
5638: words for the control structure you want and use these words in your
1.26 crook 5639: program. For example, instead of writing:
1.1 anton 5640:
5641: @example
1.26 crook 5642: BEGIN
1.1 anton 5643: ...
1.26 crook 5644: IF [ 1 CS-ROLL ]
1.1 anton 5645: ...
1.26 crook 5646: AGAIN THEN
1.1 anton 5647: @end example
5648:
1.21 crook 5649: @noindent
1.1 anton 5650: we recommend defining control structure words, e.g.,
5651:
5652: @example
1.26 crook 5653: : WHILE ( DEST -- ORIG DEST )
5654: POSTPONE IF
5655: 1 CS-ROLL ; immediate
5656:
5657: : REPEAT ( orig dest -- )
5658: POSTPONE AGAIN
5659: POSTPONE THEN ; immediate
1.1 anton 5660: @end example
5661:
1.21 crook 5662: @noindent
1.1 anton 5663: and then using these to create the control structure:
5664:
5665: @example
1.26 crook 5666: BEGIN
1.1 anton 5667: ...
1.26 crook 5668: WHILE
1.1 anton 5669: ...
1.26 crook 5670: REPEAT
1.1 anton 5671: @end example
5672:
5673: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5674: @code{WHILE} are predefined, so in this example it would not be
5675: necessary to define them.
5676:
5677: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5678: @subsection Calls and returns
5679: @cindex calling a definition
5680: @cindex returning from a definition
5681:
1.3 anton 5682: @cindex recursive definitions
5683: A definition can be called simply be writing the name of the definition
1.26 crook 5684: to be called. Normally a definition is invisible during its own
1.3 anton 5685: definition. If you want to write a directly recursive definition, you
1.26 crook 5686: can use @code{recursive} to make the current definition visible, or
5687: @code{recurse} to call the current definition directly.
1.3 anton 5688:
1.44 crook 5689:
1.3 anton 5690: doc-recursive
5691: doc-recurse
5692:
1.44 crook 5693:
1.21 crook 5694: @comment TODO add example of the two recursion methods
1.12 anton 5695: @quotation
5696: @progstyle
5697: I prefer using @code{recursive} to @code{recurse}, because calling the
5698: definition by name is more descriptive (if the name is well-chosen) than
5699: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5700: implementation, it is much better to read (and think) ``now sort the
5701: partitions'' than to read ``now do a recursive call''.
5702: @end quotation
1.3 anton 5703:
1.29 crook 5704: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5705:
5706: @example
1.28 crook 5707: Defer foo
1.3 anton 5708:
5709: : bar ( ... -- ... )
5710: ... foo ... ;
5711:
5712: :noname ( ... -- ... )
5713: ... bar ... ;
5714: IS foo
5715: @end example
5716:
1.170 pazsan 5717: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5718:
1.26 crook 5719: The current definition returns control to the calling definition when
1.33 anton 5720: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5721:
5722: doc-exit
5723: doc-;s
5724:
1.44 crook 5725:
1.1 anton 5726: @node Exception Handling, , Calls and returns, Control Structures
5727: @subsection Exception Handling
1.26 crook 5728: @cindex exceptions
1.1 anton 5729:
1.68 anton 5730: @c quit is a very bad idea for error handling,
5731: @c because it does not translate into a THROW
5732: @c it also does not belong into this chapter
5733:
5734: If a word detects an error condition that it cannot handle, it can
5735: @code{throw} an exception. In the simplest case, this will terminate
5736: your program, and report an appropriate error.
1.21 crook 5737:
1.68 anton 5738: doc-throw
1.1 anton 5739:
1.69 anton 5740: @code{Throw} consumes a cell-sized error number on the stack. There are
5741: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5742: Gforth (and most other systems) you can use the iors produced by various
5743: words as error numbers (e.g., a typical use of @code{allocate} is
5744: @code{allocate throw}). Gforth also provides the word @code{exception}
5745: to define your own error numbers (with decent error reporting); an ANS
5746: Forth version of this word (but without the error messages) is available
5747: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5748: numbers (anything outside the range -4095..0), but won't get nice error
5749: messages, only numbers. For example, try:
5750:
5751: @example
1.69 anton 5752: -10 throw \ ANS defined
5753: -267 throw \ system defined
5754: s" my error" exception throw \ user defined
5755: 7 throw \ arbitrary number
1.68 anton 5756: @end example
5757:
5758: doc---exception-exception
1.1 anton 5759:
1.69 anton 5760: A common idiom to @code{THROW} a specific error if a flag is true is
5761: this:
5762:
5763: @example
5764: @code{( flag ) 0<> @i{errno} and throw}
5765: @end example
5766:
5767: Your program can provide exception handlers to catch exceptions. An
5768: exception handler can be used to correct the problem, or to clean up
5769: some data structures and just throw the exception to the next exception
5770: handler. Note that @code{throw} jumps to the dynamically innermost
5771: exception handler. The system's exception handler is outermost, and just
5772: prints an error and restarts command-line interpretation (or, in batch
5773: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5774:
1.68 anton 5775: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5776:
1.68 anton 5777: doc-catch
1.160 anton 5778: doc-nothrow
1.68 anton 5779:
5780: The most common use of exception handlers is to clean up the state when
5781: an error happens. E.g.,
1.1 anton 5782:
1.26 crook 5783: @example
1.68 anton 5784: base @ >r hex \ actually the hex should be inside foo, or we h
5785: ['] foo catch ( nerror|0 )
5786: r> base !
1.69 anton 5787: ( nerror|0 ) throw \ pass it on
1.26 crook 5788: @end example
1.1 anton 5789:
1.69 anton 5790: A use of @code{catch} for handling the error @code{myerror} might look
5791: like this:
1.44 crook 5792:
1.68 anton 5793: @example
1.69 anton 5794: ['] foo catch
5795: CASE
1.160 anton 5796: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5797: dup throw \ default: pass other errors on, do nothing on non-errors
5798: ENDCASE
1.68 anton 5799: @end example
1.44 crook 5800:
1.68 anton 5801: Having to wrap the code into a separate word is often cumbersome,
5802: therefore Gforth provides an alternative syntax:
1.1 anton 5803:
5804: @example
1.69 anton 5805: TRY
1.68 anton 5806: @i{code1}
1.172 anton 5807: IFERROR
5808: @i{code2}
5809: THEN
5810: @i{code3}
1.69 anton 5811: ENDTRY
1.1 anton 5812: @end example
5813:
1.172 anton 5814: This performs @i{code1}. If @i{code1} completes normally, execution
5815: continues with @i{code3}. If @i{code1} or there is an exception
5816: before @code{endtry}, the stacks are reset to the state during
5817: @code{try}, the throw value is pushed on the data stack, and execution
5818: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5819:
1.68 anton 5820: doc-try
5821: doc-endtry
1.172 anton 5822: doc-iferror
5823:
5824: If you don't need @i{code2}, you can write @code{restore} instead of
5825: @code{iferror then}:
5826:
5827: @example
5828: TRY
5829: @i{code1}
5830: RESTORE
5831: @i{code3}
5832: ENDTRY
5833: @end example
1.26 crook 5834:
1.172 anton 5835: @cindex unwind-protect
1.69 anton 5836: The cleanup example from above in this syntax:
1.26 crook 5837:
1.68 anton 5838: @example
1.174 anton 5839: base @@ @{ oldbase @}
1.172 anton 5840: TRY
1.68 anton 5841: hex foo \ now the hex is placed correctly
1.69 anton 5842: 0 \ value for throw
1.172 anton 5843: RESTORE
5844: oldbase base !
5845: ENDTRY
5846: throw
1.1 anton 5847: @end example
5848:
1.172 anton 5849: An additional advantage of this variant is that an exception between
5850: @code{restore} and @code{endtry} (e.g., from the user pressing
5851: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5852: so the base will be restored under all circumstances.
5853:
5854: However, you have to ensure that this code does not cause an exception
5855: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5856: Moreover, you should also make sure that the stack contents needed by
5857: the @code{iferror}/@code{restore} code exist everywhere between
5858: @code{try} and @code{endtry}; in our example this is achived by
5859: putting the data in a local before the @code{try} (you cannot use the
5860: return stack because the exception frame (@i{sys1}) is in the way
5861: there).
5862:
5863: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5864:
5865: @cindex @code{recover} (old Gforth versions)
5866: If you do not want this exception-restarting behaviour, you achieve
5867: this as follows:
5868:
5869: @example
5870: TRY
5871: @i{code1}
5872: ENDTRY-IFERROR
5873: @i{code2}
5874: THEN
5875: @end example
5876:
5877: If there is an exception in @i{code1}, then @i{code2} is executed,
5878: otherwise execution continues behind the @code{then} (or in a possible
5879: @code{else} branch). This corresponds to the construct
5880:
5881: @example
5882: TRY
5883: @i{code1}
5884: RECOVER
5885: @i{code2}
5886: ENDTRY
5887: @end example
5888:
5889: in Gforth before version 0.7. So you can directly replace
5890: @code{recover}-using code; however, we recommend that you check if it
5891: would not be better to use one of the other @code{try} variants while
5892: you are at it.
5893:
1.173 anton 5894: To ease the transition, Gforth provides two compatibility files:
5895: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5896: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5897: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5898: ... endtry} syntax on new systems, so you can use that file as a
5899: stopgap to run old programs. Both files work on any system (they just
5900: do nothing if the system already has the syntax it implements), so you
5901: can unconditionally @code{require} one of these files, even if you use
5902: a mix old and new systems.
5903:
1.172 anton 5904: doc-restore
5905: doc-endtry-iferror
5906:
5907: Here's the error handling example:
1.1 anton 5908:
1.68 anton 5909: @example
1.69 anton 5910: TRY
1.68 anton 5911: foo
1.172 anton 5912: ENDTRY-IFERROR
1.69 anton 5913: CASE
1.160 anton 5914: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5915: throw \ pass other errors on
5916: ENDCASE
1.172 anton 5917: THEN
1.68 anton 5918: @end example
1.1 anton 5919:
1.69 anton 5920: @progstyle
5921: As usual, you should ensure that the stack depth is statically known at
5922: the end: either after the @code{throw} for passing on errors, or after
5923: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5924: selection construct for handling the error).
5925:
1.68 anton 5926: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5927: and you can provide an error message. @code{Abort} just produces an
5928: ``Aborted'' error.
1.1 anton 5929:
1.68 anton 5930: The problem with these words is that exception handlers cannot
5931: differentiate between different @code{abort"}s; they just look like
5932: @code{-2 throw} to them (the error message cannot be accessed by
5933: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5934: exception handlers.
1.44 crook 5935:
1.68 anton 5936: doc-abort"
1.26 crook 5937: doc-abort
1.29 crook 5938:
5939:
1.44 crook 5940:
1.29 crook 5941: @c -------------------------------------------------------------
1.47 crook 5942: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5943: @section Defining Words
5944: @cindex defining words
5945:
1.47 crook 5946: Defining words are used to extend Forth by creating new entries in the dictionary.
5947:
1.29 crook 5948: @menu
1.67 anton 5949: * CREATE::
1.44 crook 5950: * Variables:: Variables and user variables
1.67 anton 5951: * Constants::
1.44 crook 5952: * Values:: Initialised variables
1.67 anton 5953: * Colon Definitions::
1.44 crook 5954: * Anonymous Definitions:: Definitions without names
1.69 anton 5955: * Supplying names:: Passing definition names as strings
1.67 anton 5956: * User-defined Defining Words::
1.170 pazsan 5957: * Deferred Words:: Allow forward references
1.67 anton 5958: * Aliases::
1.29 crook 5959: @end menu
5960:
1.44 crook 5961: @node CREATE, Variables, Defining Words, Defining Words
5962: @subsection @code{CREATE}
1.29 crook 5963: @cindex simple defining words
5964: @cindex defining words, simple
5965:
5966: Defining words are used to create new entries in the dictionary. The
5967: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5968: this:
5969:
5970: @example
5971: CREATE new-word1
5972: @end example
5973:
1.69 anton 5974: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5975: input stream (@code{new-word1} in our example). It generates a
5976: dictionary entry for @code{new-word1}. When @code{new-word1} is
5977: executed, all that it does is leave an address on the stack. The address
5978: represents the value of the data space pointer (@code{HERE}) at the time
5979: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5980: associating a name with the address of a region of memory.
1.29 crook 5981:
1.34 anton 5982: doc-create
5983:
1.69 anton 5984: Note that in ANS Forth guarantees only for @code{create} that its body
5985: is in dictionary data space (i.e., where @code{here}, @code{allot}
5986: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5987: @code{create}d words can be modified with @code{does>}
5988: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5989: can only be applied to @code{create}d words.
5990:
1.29 crook 5991: By extending this example to reserve some memory in data space, we end
1.69 anton 5992: up with something like a @i{variable}. Here are two different ways to do
5993: it:
1.29 crook 5994:
5995: @example
5996: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5997: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5998: @end example
5999:
6000: The variable can be examined and modified using @code{@@} (``fetch'') and
6001: @code{!} (``store'') like this:
6002:
6003: @example
6004: new-word2 @@ . \ get address, fetch from it and display
6005: 1234 new-word2 ! \ new value, get address, store to it
6006: @end example
6007:
1.44 crook 6008: @cindex arrays
6009: A similar mechanism can be used to create arrays. For example, an
6010: 80-character text input buffer:
1.29 crook 6011:
6012: @example
1.44 crook 6013: CREATE text-buf 80 chars allot
6014:
1.168 anton 6015: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6016: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6017: @end example
1.29 crook 6018:
1.44 crook 6019: You can build arbitrarily complex data structures by allocating
1.49 anton 6020: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6021: learn about some Gforth tools that make it easier,
1.49 anton 6022: @xref{Structures}.
1.44 crook 6023:
6024:
6025: @node Variables, Constants, CREATE, Defining Words
6026: @subsection Variables
6027: @cindex variables
6028:
6029: The previous section showed how a sequence of commands could be used to
6030: generate a variable. As a final refinement, the whole code sequence can
6031: be wrapped up in a defining word (pre-empting the subject of the next
6032: section), making it easier to create new variables:
6033:
6034: @example
6035: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6036: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6037:
6038: myvariableX foo \ variable foo starts off with an unknown value
6039: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6040:
6041: 45 3 * foo ! \ set foo to 135
6042: 1234 joe ! \ set joe to 1234
6043: 3 joe +! \ increment joe by 3.. to 1237
6044: @end example
6045:
6046: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6047: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6048: guarantee that a @code{Variable} is initialised when it is created
6049: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6050: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6051: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6052: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6053: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6054: store a boolean, you can use @code{on} and @code{off} to toggle its
6055: state.
1.29 crook 6056:
1.34 anton 6057: doc-variable
6058: doc-2variable
6059: doc-fvariable
6060:
1.29 crook 6061: @cindex user variables
6062: @cindex user space
6063: The defining word @code{User} behaves in the same way as @code{Variable}.
6064: The difference is that it reserves space in @i{user (data) space} rather
6065: than normal data space. In a Forth system that has a multi-tasker, each
6066: task has its own set of user variables.
6067:
1.34 anton 6068: doc-user
1.67 anton 6069: @c doc-udp
6070: @c doc-uallot
1.34 anton 6071:
1.29 crook 6072: @comment TODO is that stuff about user variables strictly correct? Is it
6073: @comment just terminal tasks that have user variables?
6074: @comment should document tasker.fs (with some examples) elsewhere
6075: @comment in this manual, then expand on user space and user variables.
6076:
1.44 crook 6077: @node Constants, Values, Variables, Defining Words
6078: @subsection Constants
6079: @cindex constants
6080:
6081: @code{Constant} allows you to declare a fixed value and refer to it by
6082: name. For example:
1.29 crook 6083:
6084: @example
6085: 12 Constant INCHES-PER-FOOT
6086: 3E+08 fconstant SPEED-O-LIGHT
6087: @end example
6088:
6089: A @code{Variable} can be both read and written, so its run-time
6090: behaviour is to supply an address through which its current value can be
6091: manipulated. In contrast, the value of a @code{Constant} cannot be
6092: changed once it has been declared@footnote{Well, often it can be -- but
6093: not in a Standard, portable way. It's safer to use a @code{Value} (read
6094: on).} so it's not necessary to supply the address -- it is more
6095: efficient to return the value of the constant directly. That's exactly
6096: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6097: the top of the stack (You can find one
6098: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6099:
1.69 anton 6100: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6101: double and floating-point constants, respectively.
6102:
1.34 anton 6103: doc-constant
6104: doc-2constant
6105: doc-fconstant
6106:
6107: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6108: @c nac-> How could that not be true in an ANS Forth? You can't define a
6109: @c constant, use it and then delete the definition of the constant..
1.69 anton 6110:
6111: @c anton->An ANS Forth system can compile a constant to a literal; On
6112: @c decompilation you would see only the number, just as if it had been used
6113: @c in the first place. The word will stay, of course, but it will only be
6114: @c used by the text interpreter (no run-time duties, except when it is
6115: @c POSTPONEd or somesuch).
6116:
6117: @c nac:
1.44 crook 6118: @c I agree that it's rather deep, but IMO it is an important difference
6119: @c relative to other programming languages.. often it's annoying: it
6120: @c certainly changes my programming style relative to C.
6121:
1.69 anton 6122: @c anton: In what way?
6123:
1.29 crook 6124: Constants in Forth behave differently from their equivalents in other
6125: programming languages. In other languages, a constant (such as an EQU in
6126: assembler or a #define in C) only exists at compile-time; in the
6127: executable program the constant has been translated into an absolute
6128: number and, unless you are using a symbolic debugger, it's impossible to
6129: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6130: an entry in the header space and remains there after the code that uses
6131: it has been defined. In fact, it must remain in the dictionary since it
6132: has run-time duties to perform. For example:
1.29 crook 6133:
6134: @example
6135: 12 Constant INCHES-PER-FOOT
6136: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6137: @end example
6138:
6139: @cindex in-lining of constants
6140: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6141: associated with the constant @code{INCHES-PER-FOOT}. If you use
6142: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6143: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6144: attempt to optimise constants by in-lining them where they are used. You
6145: can force Gforth to in-line a constant like this:
6146:
6147: @example
6148: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6149: @end example
6150:
6151: If you use @code{see} to decompile @i{this} version of
6152: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6153: longer present. To understand how this works, read
6154: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6155:
6156: In-lining constants in this way might improve execution time
6157: fractionally, and can ensure that a constant is now only referenced at
6158: compile-time. However, the definition of the constant still remains in
6159: the dictionary. Some Forth compilers provide a mechanism for controlling
6160: a second dictionary for holding transient words such that this second
6161: dictionary can be deleted later in order to recover memory
6162: space. However, there is no standard way of doing this.
6163:
6164:
1.44 crook 6165: @node Values, Colon Definitions, Constants, Defining Words
6166: @subsection Values
6167: @cindex values
1.34 anton 6168:
1.69 anton 6169: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6170: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6171: (not in ANS Forth) you can access (and change) a @code{value} also with
6172: @code{>body}.
6173:
6174: Here are some
6175: examples:
1.29 crook 6176:
6177: @example
1.69 anton 6178: 12 Value APPLES \ Define APPLES with an initial value of 12
6179: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6180: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6181: APPLES \ puts 35 on the top of the stack.
1.29 crook 6182: @end example
6183:
1.44 crook 6184: doc-value
6185: doc-to
1.29 crook 6186:
1.35 anton 6187:
1.69 anton 6188:
1.44 crook 6189: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6190: @subsection Colon Definitions
6191: @cindex colon definitions
1.35 anton 6192:
6193: @example
1.44 crook 6194: : name ( ... -- ... )
6195: word1 word2 word3 ;
1.29 crook 6196: @end example
6197:
1.44 crook 6198: @noindent
6199: Creates a word called @code{name} that, upon execution, executes
6200: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6201:
1.49 anton 6202: The explanation above is somewhat superficial. For simple examples of
6203: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6204: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6205: Compilation Semantics}.
1.29 crook 6206:
1.44 crook 6207: doc-:
6208: doc-;
1.1 anton 6209:
1.34 anton 6210:
1.69 anton 6211: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6212: @subsection Anonymous Definitions
6213: @cindex colon definitions
6214: @cindex defining words without name
1.34 anton 6215:
1.44 crook 6216: Sometimes you want to define an @dfn{anonymous word}; a word without a
6217: name. You can do this with:
1.1 anton 6218:
1.44 crook 6219: doc-:noname
1.1 anton 6220:
1.44 crook 6221: This leaves the execution token for the word on the stack after the
6222: closing @code{;}. Here's an example in which a deferred word is
6223: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6224:
1.29 crook 6225: @example
1.44 crook 6226: Defer deferred
6227: :noname ( ... -- ... )
6228: ... ;
6229: IS deferred
1.29 crook 6230: @end example
1.26 crook 6231:
1.44 crook 6232: @noindent
6233: Gforth provides an alternative way of doing this, using two separate
6234: words:
1.27 crook 6235:
1.44 crook 6236: doc-noname
6237: @cindex execution token of last defined word
1.116 anton 6238: doc-latestxt
1.1 anton 6239:
1.44 crook 6240: @noindent
6241: The previous example can be rewritten using @code{noname} and
1.116 anton 6242: @code{latestxt}:
1.1 anton 6243:
1.26 crook 6244: @example
1.44 crook 6245: Defer deferred
6246: noname : ( ... -- ... )
6247: ... ;
1.116 anton 6248: latestxt IS deferred
1.26 crook 6249: @end example
1.1 anton 6250:
1.29 crook 6251: @noindent
1.44 crook 6252: @code{noname} works with any defining word, not just @code{:}.
6253:
1.116 anton 6254: @code{latestxt} also works when the last word was not defined as
1.71 anton 6255: @code{noname}. It does not work for combined words, though. It also has
6256: the useful property that is is valid as soon as the header for a
6257: definition has been built. Thus:
1.44 crook 6258:
6259: @example
1.116 anton 6260: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6261: @end example
1.1 anton 6262:
1.44 crook 6263: @noindent
6264: prints 3 numbers; the last two are the same.
1.26 crook 6265:
1.69 anton 6266: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6267: @subsection Supplying the name of a defined word
6268: @cindex names for defined words
6269: @cindex defining words, name given in a string
6270:
6271: By default, a defining word takes the name for the defined word from the
6272: input stream. Sometimes you want to supply the name from a string. You
6273: can do this with:
6274:
6275: doc-nextname
6276:
6277: For example:
6278:
6279: @example
6280: s" foo" nextname create
6281: @end example
6282:
6283: @noindent
6284: is equivalent to:
6285:
6286: @example
6287: create foo
6288: @end example
6289:
6290: @noindent
6291: @code{nextname} works with any defining word.
6292:
1.1 anton 6293:
1.170 pazsan 6294: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6295: @subsection User-defined Defining Words
6296: @cindex user-defined defining words
6297: @cindex defining words, user-defined
1.1 anton 6298:
1.29 crook 6299: You can create a new defining word by wrapping defining-time code around
6300: an existing defining word and putting the sequence in a colon
1.69 anton 6301: definition.
6302:
6303: @c anton: This example is very complex and leads in a quite different
6304: @c direction from the CREATE-DOES> stuff that follows. It should probably
6305: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6306: @c subsection of Defining Words)
6307:
6308: For example, suppose that you have a word @code{stats} that
1.29 crook 6309: gathers statistics about colon definitions given the @i{xt} of the
6310: definition, and you want every colon definition in your application to
6311: make a call to @code{stats}. You can define and use a new version of
6312: @code{:} like this:
6313:
6314: @example
6315: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6316: ... ; \ other code
6317:
1.116 anton 6318: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6319:
6320: my: foo + - ;
6321: @end example
6322:
6323: When @code{foo} is defined using @code{my:} these steps occur:
6324:
6325: @itemize @bullet
6326: @item
6327: @code{my:} is executed.
6328: @item
6329: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6330: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6331: the input stream for a name, builds a dictionary header for the name
6332: @code{foo} and switches @code{state} from interpret to compile.
6333: @item
1.116 anton 6334: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6335: being defined -- @code{foo} -- onto the stack.
6336: @item
6337: The code that was produced by @code{postpone literal} is executed; this
6338: causes the value on the stack to be compiled as a literal in the code
6339: area of @code{foo}.
6340: @item
6341: The code @code{['] stats} compiles a literal into the definition of
6342: @code{my:}. When @code{compile,} is executed, that literal -- the
6343: execution token for @code{stats} -- is layed down in the code area of
6344: @code{foo} , following the literal@footnote{Strictly speaking, the
6345: mechanism that @code{compile,} uses to convert an @i{xt} into something
6346: in the code area is implementation-dependent. A threaded implementation
6347: might spit out the execution token directly whilst another
6348: implementation might spit out a native code sequence.}.
6349: @item
6350: At this point, the execution of @code{my:} is complete, and control
6351: returns to the text interpreter. The text interpreter is in compile
6352: state, so subsequent text @code{+ -} is compiled into the definition of
6353: @code{foo} and the @code{;} terminates the definition as always.
6354: @end itemize
6355:
6356: You can use @code{see} to decompile a word that was defined using
6357: @code{my:} and see how it is different from a normal @code{:}
6358: definition. For example:
6359:
6360: @example
6361: : bar + - ; \ like foo but using : rather than my:
6362: see bar
6363: : bar
6364: + - ;
6365: see foo
6366: : foo
6367: 107645672 stats + - ;
6368:
1.140 anton 6369: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6370: @end example
6371:
6372: You can use techniques like this to make new defining words in terms of
6373: @i{any} existing defining word.
1.1 anton 6374:
6375:
1.29 crook 6376: @cindex defining defining words
1.26 crook 6377: @cindex @code{CREATE} ... @code{DOES>}
6378: If you want the words defined with your defining words to behave
6379: differently from words defined with standard defining words, you can
6380: write your defining word like this:
1.1 anton 6381:
6382: @example
1.26 crook 6383: : def-word ( "name" -- )
1.29 crook 6384: CREATE @i{code1}
1.26 crook 6385: DOES> ( ... -- ... )
1.29 crook 6386: @i{code2} ;
1.26 crook 6387:
6388: def-word name
1.1 anton 6389: @end example
6390:
1.29 crook 6391: @cindex child words
6392: This fragment defines a @dfn{defining word} @code{def-word} and then
6393: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6394: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6395: is not executed at this time. The word @code{name} is sometimes called a
6396: @dfn{child} of @code{def-word}.
6397:
6398: When you execute @code{name}, the address of the body of @code{name} is
6399: put on the data stack and @i{code2} is executed (the address of the body
6400: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6401: @code{CREATE}, i.e., the address a @code{create}d word returns by
6402: default).
6403:
6404: @c anton:
6405: @c www.dictionary.com says:
6406: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6407: @c several generations of absence, usually caused by the chance
6408: @c recombination of genes. 2.An individual or a part that exhibits
6409: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6410: @c of previous behavior after a period of absence.
6411: @c
6412: @c Doesn't seem to fit.
1.29 crook 6413:
1.69 anton 6414: @c @cindex atavism in child words
1.33 anton 6415: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6416: similarly; they all have a common run-time behaviour determined by
6417: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6418: body of the child word. The structure of the data is common to all
6419: children of @code{def-word}, but the data values are specific -- and
6420: private -- to each child word. When a child word is executed, the
6421: address of its private data area is passed as a parameter on TOS to be
6422: used and manipulated@footnote{It is legitimate both to read and write to
6423: this data area.} by @i{code2}.
1.29 crook 6424:
6425: The two fragments of code that make up the defining words act (are
6426: executed) at two completely separate times:
1.1 anton 6427:
1.29 crook 6428: @itemize @bullet
6429: @item
6430: At @i{define time}, the defining word executes @i{code1} to generate a
6431: child word
6432: @item
6433: At @i{child execution time}, when a child word is invoked, @i{code2}
6434: is executed, using parameters (data) that are private and specific to
6435: the child word.
6436: @end itemize
6437:
1.44 crook 6438: Another way of understanding the behaviour of @code{def-word} and
6439: @code{name} is to say that, if you make the following definitions:
1.33 anton 6440: @example
6441: : def-word1 ( "name" -- )
6442: CREATE @i{code1} ;
6443:
6444: : action1 ( ... -- ... )
6445: @i{code2} ;
6446:
6447: def-word1 name1
6448: @end example
6449:
1.44 crook 6450: @noindent
6451: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6452:
1.29 crook 6453: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6454:
1.1 anton 6455: @example
1.29 crook 6456: : CONSTANT ( w "name" -- )
6457: CREATE ,
1.26 crook 6458: DOES> ( -- w )
6459: @@ ;
1.1 anton 6460: @end example
6461:
1.29 crook 6462: @comment There is a beautiful description of how this works and what
6463: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6464: @comment commentary on the Counting Fruits problem.
6465:
6466: When you create a constant with @code{5 CONSTANT five}, a set of
6467: define-time actions take place; first a new word @code{five} is created,
6468: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6469: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6470: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6471: no code of its own; it simply contains a data field and a pointer to the
6472: code that follows @code{DOES>} in its defining word. That makes words
6473: created in this way very compact.
6474:
6475: The final example in this section is intended to remind you that space
6476: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6477: both read and written by a Standard program@footnote{Exercise: use this
6478: example as a starting point for your own implementation of @code{Value}
6479: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6480: @code{[']}.}:
6481:
6482: @example
6483: : foo ( "name" -- )
6484: CREATE -1 ,
6485: DOES> ( -- )
1.33 anton 6486: @@ . ;
1.29 crook 6487:
6488: foo first-word
6489: foo second-word
6490:
6491: 123 ' first-word >BODY !
6492: @end example
6493:
6494: If @code{first-word} had been a @code{CREATE}d word, we could simply
6495: have executed it to get the address of its data field. However, since it
6496: was defined to have @code{DOES>} actions, its execution semantics are to
6497: perform those @code{DOES>} actions. To get the address of its data field
6498: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6499: translate the xt into the address of the data field. When you execute
6500: @code{first-word}, it will display @code{123}. When you execute
6501: @code{second-word} it will display @code{-1}.
1.26 crook 6502:
6503: @cindex stack effect of @code{DOES>}-parts
6504: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6505: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6506: the stack effect of the defined words, not the stack effect of the
6507: following code (the following code expects the address of the body on
6508: the top of stack, which is not reflected in the stack comment). This is
6509: the convention that I use and recommend (it clashes a bit with using
6510: locals declarations for stack effect specification, though).
1.1 anton 6511:
1.53 anton 6512: @menu
6513: * CREATE..DOES> applications::
6514: * CREATE..DOES> details::
1.63 anton 6515: * Advanced does> usage example::
1.155 anton 6516: * Const-does>::
1.53 anton 6517: @end menu
6518:
6519: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6520: @subsubsection Applications of @code{CREATE..DOES>}
6521: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6522:
1.26 crook 6523: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6524:
1.26 crook 6525: @cindex factoring similar colon definitions
6526: When you see a sequence of code occurring several times, and you can
6527: identify a meaning, you will factor it out as a colon definition. When
6528: you see similar colon definitions, you can factor them using
6529: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6530: that look very similar:
1.1 anton 6531: @example
1.26 crook 6532: : ori, ( reg-target reg-source n -- )
6533: 0 asm-reg-reg-imm ;
6534: : andi, ( reg-target reg-source n -- )
6535: 1 asm-reg-reg-imm ;
1.1 anton 6536: @end example
6537:
1.26 crook 6538: @noindent
6539: This could be factored with:
6540: @example
6541: : reg-reg-imm ( op-code -- )
6542: CREATE ,
6543: DOES> ( reg-target reg-source n -- )
6544: @@ asm-reg-reg-imm ;
6545:
6546: 0 reg-reg-imm ori,
6547: 1 reg-reg-imm andi,
6548: @end example
1.1 anton 6549:
1.26 crook 6550: @cindex currying
6551: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6552: supply a part of the parameters for a word (known as @dfn{currying} in
6553: the functional language community). E.g., @code{+} needs two
6554: parameters. Creating versions of @code{+} with one parameter fixed can
6555: be done like this:
1.82 anton 6556:
1.1 anton 6557: @example
1.82 anton 6558: : curry+ ( n1 "name" -- )
1.26 crook 6559: CREATE ,
6560: DOES> ( n2 -- n1+n2 )
6561: @@ + ;
6562:
6563: 3 curry+ 3+
6564: -2 curry+ 2-
1.1 anton 6565: @end example
6566:
1.91 anton 6567:
1.63 anton 6568: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6569: @subsubsection The gory details of @code{CREATE..DOES>}
6570: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6571:
1.26 crook 6572: doc-does>
1.1 anton 6573:
1.26 crook 6574: @cindex @code{DOES>} in a separate definition
6575: This means that you need not use @code{CREATE} and @code{DOES>} in the
6576: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6577: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6578: @example
6579: : does1
6580: DOES> ( ... -- ... )
1.44 crook 6581: ... ;
6582:
6583: : does2
6584: DOES> ( ... -- ... )
6585: ... ;
6586:
6587: : def-word ( ... -- ... )
6588: create ...
6589: IF
6590: does1
6591: ELSE
6592: does2
6593: ENDIF ;
6594: @end example
6595:
6596: In this example, the selection of whether to use @code{does1} or
1.69 anton 6597: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6598: @code{CREATE}d.
6599:
6600: @cindex @code{DOES>} in interpretation state
6601: In a standard program you can apply a @code{DOES>}-part only if the last
6602: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6603: will override the behaviour of the last word defined in any case. In a
6604: standard program, you can use @code{DOES>} only in a colon
6605: definition. In Gforth, you can also use it in interpretation state, in a
6606: kind of one-shot mode; for example:
6607: @example
6608: CREATE name ( ... -- ... )
6609: @i{initialization}
6610: DOES>
6611: @i{code} ;
6612: @end example
6613:
6614: @noindent
6615: is equivalent to the standard:
6616: @example
6617: :noname
6618: DOES>
6619: @i{code} ;
6620: CREATE name EXECUTE ( ... -- ... )
6621: @i{initialization}
6622: @end example
6623:
1.53 anton 6624: doc->body
6625:
1.152 pazsan 6626: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6627: @subsubsection Advanced does> usage example
6628:
6629: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6630: for disassembling instructions, that follow a very repetetive scheme:
6631:
6632: @example
6633: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6634: @var{entry-num} cells @var{table} + !
6635: @end example
6636:
6637: Of course, this inspires the idea to factor out the commonalities to
6638: allow a definition like
6639:
6640: @example
6641: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6642: @end example
6643:
6644: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6645: correlated. Moreover, before I wrote the disassembler, there already
6646: existed code that defines instructions like this:
1.63 anton 6647:
6648: @example
6649: @var{entry-num} @var{inst-format} @var{inst-name}
6650: @end example
6651:
6652: This code comes from the assembler and resides in
6653: @file{arch/mips/insts.fs}.
6654:
6655: So I had to define the @var{inst-format} words that performed the scheme
6656: above when executed. At first I chose to use run-time code-generation:
6657:
6658: @example
6659: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6660: :noname Postpone @var{disasm-operands}
6661: name Postpone sliteral Postpone type Postpone ;
6662: swap cells @var{table} + ! ;
6663: @end example
6664:
6665: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6666:
1.63 anton 6667: An alternative would have been to write this using
6668: @code{create}/@code{does>}:
6669:
6670: @example
6671: : @var{inst-format} ( entry-num "name" -- )
6672: here name string, ( entry-num c-addr ) \ parse and save "name"
6673: noname create , ( entry-num )
1.116 anton 6674: latestxt swap cells @var{table} + !
1.63 anton 6675: does> ( addr w -- )
6676: \ disassemble instruction w at addr
6677: @@ >r
6678: @var{disasm-operands}
6679: r> count type ;
6680: @end example
6681:
6682: Somehow the first solution is simpler, mainly because it's simpler to
6683: shift a string from definition-time to use-time with @code{sliteral}
6684: than with @code{string,} and friends.
6685:
6686: I wrote a lot of words following this scheme and soon thought about
6687: factoring out the commonalities among them. Note that this uses a
6688: two-level defining word, i.e., a word that defines ordinary defining
6689: words.
6690:
6691: This time a solution involving @code{postpone} and friends seemed more
6692: difficult (try it as an exercise), so I decided to use a
6693: @code{create}/@code{does>} word; since I was already at it, I also used
6694: @code{create}/@code{does>} for the lower level (try using
6695: @code{postpone} etc. as an exercise), resulting in the following
6696: definition:
6697:
6698: @example
6699: : define-format ( disasm-xt table-xt -- )
6700: \ define an instruction format that uses disasm-xt for
6701: \ disassembling and enters the defined instructions into table
6702: \ table-xt
6703: create 2,
6704: does> ( u "inst" -- )
6705: \ defines an anonymous word for disassembling instruction inst,
6706: \ and enters it as u-th entry into table-xt
6707: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6708: noname create 2, \ define anonymous word
1.116 anton 6709: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6710: does> ( addr w -- )
6711: \ disassemble instruction w at addr
6712: 2@@ >r ( addr w disasm-xt R: c-addr )
6713: execute ( R: c-addr ) \ disassemble operands
6714: r> count type ; \ print name
6715: @end example
6716:
6717: Note that the tables here (in contrast to above) do the @code{cells +}
6718: by themselves (that's why you have to pass an xt). This word is used in
6719: the following way:
6720:
6721: @example
6722: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6723: @end example
6724:
1.71 anton 6725: As shown above, the defined instruction format is then used like this:
6726:
6727: @example
6728: @var{entry-num} @var{inst-format} @var{inst-name}
6729: @end example
6730:
1.63 anton 6731: In terms of currying, this kind of two-level defining word provides the
6732: parameters in three stages: first @var{disasm-operands} and @var{table},
6733: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6734: the instruction to be disassembled.
6735:
6736: Of course this did not quite fit all the instruction format names used
6737: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6738: the parameters into the right form.
6739:
6740: If you have trouble following this section, don't worry. First, this is
6741: involved and takes time (and probably some playing around) to
6742: understand; second, this is the first two-level
6743: @code{create}/@code{does>} word I have written in seventeen years of
6744: Forth; and if I did not have @file{insts.fs} to start with, I may well
6745: have elected to use just a one-level defining word (with some repeating
6746: of parameters when using the defining word). So it is not necessary to
6747: understand this, but it may improve your understanding of Forth.
1.44 crook 6748:
6749:
1.152 pazsan 6750: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6751: @subsubsection @code{Const-does>}
6752:
6753: A frequent use of @code{create}...@code{does>} is for transferring some
6754: values from definition-time to run-time. Gforth supports this use with
6755:
6756: doc-const-does>
6757:
6758: A typical use of this word is:
6759:
6760: @example
6761: : curry+ ( n1 "name" -- )
6762: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6763: + ;
6764:
6765: 3 curry+ 3+
6766: @end example
6767:
6768: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6769: definition to run-time.
6770:
6771: The advantages of using @code{const-does>} are:
6772:
6773: @itemize
6774:
6775: @item
6776: You don't have to deal with storing and retrieving the values, i.e.,
6777: your program becomes more writable and readable.
6778:
6779: @item
6780: When using @code{does>}, you have to introduce a @code{@@} that cannot
6781: be optimized away (because you could change the data using
6782: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6783:
6784: @end itemize
6785:
6786: An ANS Forth implementation of @code{const-does>} is available in
6787: @file{compat/const-does.fs}.
6788:
6789:
1.170 pazsan 6790: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6791: @subsection Deferred Words
1.44 crook 6792: @cindex deferred words
6793:
6794: The defining word @code{Defer} allows you to define a word by name
6795: without defining its behaviour; the definition of its behaviour is
6796: deferred. Here are two situation where this can be useful:
6797:
6798: @itemize @bullet
6799: @item
6800: Where you want to allow the behaviour of a word to be altered later, and
6801: for all precompiled references to the word to change when its behaviour
6802: is changed.
6803: @item
6804: For mutual recursion; @xref{Calls and returns}.
6805: @end itemize
6806:
6807: In the following example, @code{foo} always invokes the version of
6808: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6809: always invokes the version that prints ``@code{Hello}''. There is no way
6810: of getting @code{foo} to use the later version without re-ordering the
6811: source code and recompiling it.
6812:
6813: @example
6814: : greet ." Good morning" ;
6815: : foo ... greet ... ;
6816: : greet ." Hello" ;
6817: : bar ... greet ... ;
6818: @end example
6819:
6820: This problem can be solved by defining @code{greet} as a @code{Defer}red
6821: word. The behaviour of a @code{Defer}red word can be defined and
6822: redefined at any time by using @code{IS} to associate the xt of a
6823: previously-defined word with it. The previous example becomes:
6824:
6825: @example
1.69 anton 6826: Defer greet ( -- )
1.44 crook 6827: : foo ... greet ... ;
6828: : bar ... greet ... ;
1.69 anton 6829: : greet1 ( -- ) ." Good morning" ;
6830: : greet2 ( -- ) ." Hello" ;
1.132 anton 6831: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6832: @end example
6833:
1.69 anton 6834: @progstyle
6835: You should write a stack comment for every deferred word, and put only
6836: XTs into deferred words that conform to this stack effect. Otherwise
6837: it's too difficult to use the deferred word.
6838:
1.44 crook 6839: A deferred word can be used to improve the statistics-gathering example
6840: from @ref{User-defined Defining Words}; rather than edit the
6841: application's source code to change every @code{:} to a @code{my:}, do
6842: this:
6843:
6844: @example
6845: : real: : ; \ retain access to the original
6846: defer : \ redefine as a deferred word
1.132 anton 6847: ' my: IS : \ use special version of :
1.44 crook 6848: \
6849: \ load application here
6850: \
1.132 anton 6851: ' real: IS : \ go back to the original
1.44 crook 6852: @end example
6853:
6854:
1.132 anton 6855: One thing to note is that @code{IS} has special compilation semantics,
6856: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6857:
6858: @example
6859: : set-greet ( xt -- )
1.132 anton 6860: IS greet ;
1.44 crook 6861:
6862: ' greet1 set-greet
6863: @end example
6864:
1.132 anton 6865: In situations where @code{IS} does not fit, use @code{defer!} instead.
6866:
1.69 anton 6867: A deferred word can only inherit execution semantics from the xt
6868: (because that is all that an xt can represent -- for more discussion of
6869: this @pxref{Tokens for Words}); by default it will have default
6870: interpretation and compilation semantics deriving from this execution
6871: semantics. However, you can change the interpretation and compilation
6872: semantics of the deferred word in the usual ways:
1.44 crook 6873:
6874: @example
1.132 anton 6875: : bar .... ; immediate
1.44 crook 6876: Defer fred immediate
6877: Defer jim
6878:
1.132 anton 6879: ' bar IS jim \ jim has default semantics
6880: ' bar IS fred \ fred is immediate
1.44 crook 6881: @end example
6882:
6883: doc-defer
1.132 anton 6884: doc-defer!
1.44 crook 6885: doc-is
1.132 anton 6886: doc-defer@
6887: doc-action-of
1.44 crook 6888: @comment TODO document these: what's defers [is]
6889: doc-defers
6890:
6891: @c Use @code{words-deferred} to see a list of deferred words.
6892:
1.132 anton 6893: Definitions of these words (except @code{defers}) in ANS Forth are
6894: provided in @file{compat/defer.fs}.
1.44 crook 6895:
6896:
1.170 pazsan 6897: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6898: @subsection Aliases
6899: @cindex aliases
1.1 anton 6900:
1.44 crook 6901: The defining word @code{Alias} allows you to define a word by name that
6902: has the same behaviour as some other word. Here are two situation where
6903: this can be useful:
1.1 anton 6904:
1.44 crook 6905: @itemize @bullet
6906: @item
6907: When you want access to a word's definition from a different word list
6908: (for an example of this, see the definition of the @code{Root} word list
6909: in the Gforth source).
6910: @item
6911: When you want to create a synonym; a definition that can be known by
6912: either of two names (for example, @code{THEN} and @code{ENDIF} are
6913: aliases).
6914: @end itemize
1.1 anton 6915:
1.69 anton 6916: Like deferred words, an alias has default compilation and interpretation
6917: semantics at the beginning (not the modifications of the other word),
6918: but you can change them in the usual ways (@code{immediate},
6919: @code{compile-only}). For example:
1.1 anton 6920:
6921: @example
1.44 crook 6922: : foo ... ; immediate
6923:
6924: ' foo Alias bar \ bar is not an immediate word
6925: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6926: @end example
6927:
1.44 crook 6928: Words that are aliases have the same xt, different headers in the
6929: dictionary, and consequently different name tokens (@pxref{Tokens for
6930: Words}) and possibly different immediate flags. An alias can only have
6931: default or immediate compilation semantics; you can define aliases for
6932: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6933:
1.44 crook 6934: doc-alias
1.1 anton 6935:
6936:
1.47 crook 6937: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6938: @section Interpretation and Compilation Semantics
1.26 crook 6939: @cindex semantics, interpretation and compilation
1.1 anton 6940:
1.71 anton 6941: @c !! state and ' are used without explanation
6942: @c example for immediate/compile-only? or is the tutorial enough
6943:
1.26 crook 6944: @cindex interpretation semantics
1.71 anton 6945: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6946: interpreter does when it encounters the word in interpret state. It also
6947: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6948: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6949: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6950: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6951:
1.26 crook 6952: @cindex compilation semantics
1.71 anton 6953: The @dfn{compilation semantics} of a (named) word are what the text
6954: interpreter does when it encounters the word in compile state. It also
6955: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6956: compiles@footnote{In standard terminology, ``appends to the current
6957: definition''.} the compilation semantics of @i{word}.
1.1 anton 6958:
1.26 crook 6959: @cindex execution semantics
6960: The standard also talks about @dfn{execution semantics}. They are used
6961: only for defining the interpretation and compilation semantics of many
6962: words. By default, the interpretation semantics of a word are to
6963: @code{execute} its execution semantics, and the compilation semantics of
6964: a word are to @code{compile,} its execution semantics.@footnote{In
6965: standard terminology: The default interpretation semantics are its
6966: execution semantics; the default compilation semantics are to append its
6967: execution semantics to the execution semantics of the current
6968: definition.}
6969:
1.71 anton 6970: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6971: the text interpreter, ticked, or @code{postpone}d, so they have no
6972: interpretation or compilation semantics. Their behaviour is represented
6973: by their XT (@pxref{Tokens for Words}), and we call it execution
6974: semantics, too.
6975:
1.26 crook 6976: @comment TODO expand, make it co-operate with new sections on text interpreter.
6977:
6978: @cindex immediate words
6979: @cindex compile-only words
6980: You can change the semantics of the most-recently defined word:
6981:
1.44 crook 6982:
1.26 crook 6983: doc-immediate
6984: doc-compile-only
6985: doc-restrict
6986:
1.82 anton 6987: By convention, words with non-default compilation semantics (e.g.,
6988: immediate words) often have names surrounded with brackets (e.g.,
6989: @code{[']}, @pxref{Execution token}).
1.44 crook 6990:
1.26 crook 6991: Note that ticking (@code{'}) a compile-only word gives an error
6992: (``Interpreting a compile-only word'').
1.1 anton 6993:
1.47 crook 6994: @menu
1.67 anton 6995: * Combined words::
1.47 crook 6996: @end menu
1.44 crook 6997:
1.71 anton 6998:
1.48 anton 6999: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7000: @subsection Combined Words
7001: @cindex combined words
7002:
7003: Gforth allows you to define @dfn{combined words} -- words that have an
7004: arbitrary combination of interpretation and compilation semantics.
7005:
1.26 crook 7006: doc-interpret/compile:
1.1 anton 7007:
1.26 crook 7008: This feature was introduced for implementing @code{TO} and @code{S"}. I
7009: recommend that you do not define such words, as cute as they may be:
7010: they make it hard to get at both parts of the word in some contexts.
7011: E.g., assume you want to get an execution token for the compilation
7012: part. Instead, define two words, one that embodies the interpretation
7013: part, and one that embodies the compilation part. Once you have done
7014: that, you can define a combined word with @code{interpret/compile:} for
7015: the convenience of your users.
1.1 anton 7016:
1.26 crook 7017: You might try to use this feature to provide an optimizing
7018: implementation of the default compilation semantics of a word. For
7019: example, by defining:
1.1 anton 7020: @example
1.26 crook 7021: :noname
7022: foo bar ;
7023: :noname
7024: POSTPONE foo POSTPONE bar ;
1.29 crook 7025: interpret/compile: opti-foobar
1.1 anton 7026: @end example
1.26 crook 7027:
1.23 crook 7028: @noindent
1.26 crook 7029: as an optimizing version of:
7030:
1.1 anton 7031: @example
1.26 crook 7032: : foobar
7033: foo bar ;
1.1 anton 7034: @end example
7035:
1.26 crook 7036: Unfortunately, this does not work correctly with @code{[compile]},
7037: because @code{[compile]} assumes that the compilation semantics of all
7038: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7039: opti-foobar} would compile compilation semantics, whereas
7040: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7041:
1.26 crook 7042: @cindex state-smart words (are a bad idea)
1.82 anton 7043: @anchor{state-smartness}
1.29 crook 7044: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7045: by @code{interpret/compile:} (words are state-smart if they check
7046: @code{STATE} during execution). E.g., they would try to code
7047: @code{foobar} like this:
1.1 anton 7048:
1.26 crook 7049: @example
7050: : foobar
7051: STATE @@
7052: IF ( compilation state )
7053: POSTPONE foo POSTPONE bar
7054: ELSE
7055: foo bar
7056: ENDIF ; immediate
7057: @end example
1.1 anton 7058:
1.26 crook 7059: Although this works if @code{foobar} is only processed by the text
7060: interpreter, it does not work in other contexts (like @code{'} or
7061: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7062: for a state-smart word, not for the interpretation semantics of the
7063: original @code{foobar}; when you execute this execution token (directly
7064: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7065: state, the result will not be what you expected (i.e., it will not
7066: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7067: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7068: M. Anton Ertl,
7069: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7070: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7071:
1.26 crook 7072: @cindex defining words with arbitrary semantics combinations
7073: It is also possible to write defining words that define words with
7074: arbitrary combinations of interpretation and compilation semantics. In
7075: general, they look like this:
1.1 anton 7076:
1.26 crook 7077: @example
7078: : def-word
7079: create-interpret/compile
1.29 crook 7080: @i{code1}
1.26 crook 7081: interpretation>
1.29 crook 7082: @i{code2}
1.26 crook 7083: <interpretation
7084: compilation>
1.29 crook 7085: @i{code3}
1.26 crook 7086: <compilation ;
7087: @end example
1.1 anton 7088:
1.29 crook 7089: For a @i{word} defined with @code{def-word}, the interpretation
7090: semantics are to push the address of the body of @i{word} and perform
7091: @i{code2}, and the compilation semantics are to push the address of
7092: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7093: can also be defined like this (except that the defined constants don't
7094: behave correctly when @code{[compile]}d):
1.1 anton 7095:
1.26 crook 7096: @example
7097: : constant ( n "name" -- )
7098: create-interpret/compile
7099: ,
7100: interpretation> ( -- n )
7101: @@
7102: <interpretation
7103: compilation> ( compilation. -- ; run-time. -- n )
7104: @@ postpone literal
7105: <compilation ;
7106: @end example
1.1 anton 7107:
1.44 crook 7108:
1.26 crook 7109: doc-create-interpret/compile
7110: doc-interpretation>
7111: doc-<interpretation
7112: doc-compilation>
7113: doc-<compilation
1.1 anton 7114:
1.44 crook 7115:
1.29 crook 7116: Words defined with @code{interpret/compile:} and
1.26 crook 7117: @code{create-interpret/compile} have an extended header structure that
7118: differs from other words; however, unless you try to access them with
7119: plain address arithmetic, you should not notice this. Words for
7120: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7121: @code{'} @i{word} @code{>body} also gives you the body of a word created
7122: with @code{create-interpret/compile}.
1.1 anton 7123:
1.44 crook 7124:
1.47 crook 7125: @c -------------------------------------------------------------
1.81 anton 7126: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7127: @section Tokens for Words
7128: @cindex tokens for words
7129:
7130: This section describes the creation and use of tokens that represent
7131: words.
7132:
1.71 anton 7133: @menu
7134: * Execution token:: represents execution/interpretation semantics
7135: * Compilation token:: represents compilation semantics
7136: * Name token:: represents named words
7137: @end menu
1.47 crook 7138:
1.71 anton 7139: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7140: @subsection Execution token
1.47 crook 7141:
7142: @cindex xt
7143: @cindex execution token
1.71 anton 7144: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7145: You can use @code{execute} to invoke this behaviour.
1.47 crook 7146:
1.71 anton 7147: @cindex tick (')
7148: You can use @code{'} to get an execution token that represents the
7149: interpretation semantics of a named word:
1.47 crook 7150:
7151: @example
1.97 anton 7152: 5 ' . ( n xt )
7153: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7154: @end example
1.47 crook 7155:
1.71 anton 7156: doc-'
7157:
7158: @code{'} parses at run-time; there is also a word @code{[']} that parses
7159: when it is compiled, and compiles the resulting XT:
7160:
7161: @example
7162: : foo ['] . execute ;
7163: 5 foo
7164: : bar ' execute ; \ by contrast,
7165: 5 bar . \ ' parses "." when bar executes
7166: @end example
7167:
7168: doc-[']
7169:
7170: If you want the execution token of @i{word}, write @code{['] @i{word}}
7171: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7172: @code{'} and @code{[']} behave somewhat unusually by complaining about
7173: compile-only words (because these words have no interpretation
7174: semantics). You might get what you want by using @code{COMP' @i{word}
7175: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7176: token}).
7177:
1.116 anton 7178: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7179: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7180: for the only behaviour the word has (the execution semantics). For
1.116 anton 7181: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7182: would produce if the word was defined anonymously.
7183:
7184: @example
7185: :noname ." hello" ;
7186: execute
1.47 crook 7187: @end example
7188:
1.71 anton 7189: An XT occupies one cell and can be manipulated like any other cell.
7190:
1.47 crook 7191: @cindex code field address
7192: @cindex CFA
1.71 anton 7193: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7194: operations that produce or consume it). For old hands: In Gforth, the
7195: XT is implemented as a code field address (CFA).
7196:
7197: doc-execute
7198: doc-perform
7199:
7200: @node Compilation token, Name token, Execution token, Tokens for Words
7201: @subsection Compilation token
1.47 crook 7202:
7203: @cindex compilation token
1.71 anton 7204: @cindex CT (compilation token)
7205: Gforth represents the compilation semantics of a named word by a
1.47 crook 7206: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7207: @i{xt} is an execution token. The compilation semantics represented by
7208: the compilation token can be performed with @code{execute}, which
7209: consumes the whole compilation token, with an additional stack effect
7210: determined by the represented compilation semantics.
7211:
7212: At present, the @i{w} part of a compilation token is an execution token,
7213: and the @i{xt} part represents either @code{execute} or
7214: @code{compile,}@footnote{Depending upon the compilation semantics of the
7215: word. If the word has default compilation semantics, the @i{xt} will
7216: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7217: @i{xt} will represent @code{execute}.}. However, don't rely on that
7218: knowledge, unless necessary; future versions of Gforth may introduce
7219: unusual compilation tokens (e.g., a compilation token that represents
7220: the compilation semantics of a literal).
7221:
1.71 anton 7222: You can perform the compilation semantics represented by the compilation
7223: token with @code{execute}. You can compile the compilation semantics
7224: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7225: equivalent to @code{postpone @i{word}}.
7226:
7227: doc-[comp']
7228: doc-comp'
7229: doc-postpone,
7230:
7231: @node Name token, , Compilation token, Tokens for Words
7232: @subsection Name token
1.47 crook 7233:
7234: @cindex name token
1.116 anton 7235: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7236: token is an abstract data type that occurs as argument or result of the
7237: words below.
7238:
7239: @c !! put this elswhere?
1.47 crook 7240: @cindex name field address
7241: @cindex NFA
1.116 anton 7242: The closest thing to the nt in older Forth systems is the name field
7243: address (NFA), but there are significant differences: in older Forth
7244: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7245: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7246: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7247: is a link field in the structure identified by the name token, but
7248: searching usually uses a hash table external to these structures; the
7249: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7250: implemented as the address of that count field.
1.47 crook 7251:
7252: doc-find-name
1.116 anton 7253: doc-latest
7254: doc->name
1.47 crook 7255: doc-name>int
7256: doc-name?int
7257: doc-name>comp
7258: doc-name>string
1.109 anton 7259: doc-id.
7260: doc-.name
7261: doc-.id
1.47 crook 7262:
1.81 anton 7263: @c ----------------------------------------------------------
7264: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7265: @section Compiling words
7266: @cindex compiling words
7267: @cindex macros
7268:
7269: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7270: between compilation and run-time. E.g., you can run arbitrary code
7271: between defining words (or for computing data used by defining words
7272: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7273: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7274: running arbitrary code while compiling a colon definition (exception:
7275: you must not allot dictionary space).
7276:
7277: @menu
7278: * Literals:: Compiling data values
7279: * Macros:: Compiling words
7280: @end menu
7281:
7282: @node Literals, Macros, Compiling words, Compiling words
7283: @subsection Literals
7284: @cindex Literals
7285:
7286: The simplest and most frequent example is to compute a literal during
7287: compilation. E.g., the following definition prints an array of strings,
7288: one string per line:
7289:
7290: @example
7291: : .strings ( addr u -- ) \ gforth
7292: 2* cells bounds U+DO
7293: cr i 2@@ type
7294: 2 cells +LOOP ;
7295: @end example
1.81 anton 7296:
1.82 anton 7297: With a simple-minded compiler like Gforth's, this computes @code{2
7298: cells} on every loop iteration. You can compute this value once and for
7299: all at compile time and compile it into the definition like this:
7300:
7301: @example
7302: : .strings ( addr u -- ) \ gforth
7303: 2* cells bounds U+DO
7304: cr i 2@@ type
7305: [ 2 cells ] literal +LOOP ;
7306: @end example
7307:
7308: @code{[} switches the text interpreter to interpret state (you will get
7309: an @code{ok} prompt if you type this example interactively and insert a
7310: newline between @code{[} and @code{]}), so it performs the
7311: interpretation semantics of @code{2 cells}; this computes a number.
7312: @code{]} switches the text interpreter back into compile state. It then
7313: performs @code{Literal}'s compilation semantics, which are to compile
7314: this number into the current word. You can decompile the word with
7315: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7316:
1.82 anton 7317: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7318: *} in this way.
1.81 anton 7319:
1.82 anton 7320: doc-[
7321: doc-]
1.81 anton 7322: doc-literal
7323: doc-]L
1.82 anton 7324:
7325: There are also words for compiling other data types than single cells as
7326: literals:
7327:
1.81 anton 7328: doc-2literal
7329: doc-fliteral
1.82 anton 7330: doc-sliteral
7331:
7332: @cindex colon-sys, passing data across @code{:}
7333: @cindex @code{:}, passing data across
7334: You might be tempted to pass data from outside a colon definition to the
7335: inside on the data stack. This does not work, because @code{:} puhes a
7336: colon-sys, making stuff below unaccessible. E.g., this does not work:
7337:
7338: @example
7339: 5 : foo literal ; \ error: "unstructured"
7340: @end example
7341:
7342: Instead, you have to pass the value in some other way, e.g., through a
7343: variable:
7344:
7345: @example
7346: variable temp
7347: 5 temp !
7348: : foo [ temp @@ ] literal ;
7349: @end example
7350:
7351:
7352: @node Macros, , Literals, Compiling words
7353: @subsection Macros
7354: @cindex Macros
7355: @cindex compiling compilation semantics
7356:
7357: @code{Literal} and friends compile data values into the current
7358: definition. You can also write words that compile other words into the
7359: current definition. E.g.,
7360:
7361: @example
7362: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7363: POSTPONE + ;
7364:
7365: : foo ( n1 n2 -- n )
7366: [ compile-+ ] ;
7367: 1 2 foo .
7368: @end example
7369:
7370: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7371: What happens in this example? @code{Postpone} compiles the compilation
7372: semantics of @code{+} into @code{compile-+}; later the text interpreter
7373: executes @code{compile-+} and thus the compilation semantics of +, which
7374: compile (the execution semantics of) @code{+} into
7375: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7376: should only be executed in compile state, so this example is not
7377: guaranteed to work on all standard systems, but on any decent system it
7378: will work.}
7379:
7380: doc-postpone
7381: doc-[compile]
7382:
7383: Compiling words like @code{compile-+} are usually immediate (or similar)
7384: so you do not have to switch to interpret state to execute them;
7385: mopifying the last example accordingly produces:
7386:
7387: @example
7388: : [compile-+] ( compilation: --; interpretation: -- )
7389: \ compiled code: ( n1 n2 -- n )
7390: POSTPONE + ; immediate
7391:
7392: : foo ( n1 n2 -- n )
7393: [compile-+] ;
7394: 1 2 foo .
7395: @end example
7396:
7397: Immediate compiling words are similar to macros in other languages (in
7398: particular, Lisp). The important differences to macros in, e.g., C are:
7399:
7400: @itemize @bullet
7401:
7402: @item
7403: You use the same language for defining and processing macros, not a
7404: separate preprocessing language and processor.
7405:
7406: @item
7407: Consequently, the full power of Forth is available in macro definitions.
7408: E.g., you can perform arbitrarily complex computations, or generate
7409: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7410: Tutorial}). This power is very useful when writing a parser generators
7411: or other code-generating software.
7412:
7413: @item
7414: Macros defined using @code{postpone} etc. deal with the language at a
7415: higher level than strings; name binding happens at macro definition
7416: time, so you can avoid the pitfalls of name collisions that can happen
7417: in C macros. Of course, Forth is a liberal language and also allows to
7418: shoot yourself in the foot with text-interpreted macros like
7419:
7420: @example
7421: : [compile-+] s" +" evaluate ; immediate
7422: @end example
7423:
7424: Apart from binding the name at macro use time, using @code{evaluate}
7425: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7426: @end itemize
7427:
7428: You may want the macro to compile a number into a word. The word to do
7429: it is @code{literal}, but you have to @code{postpone} it, so its
7430: compilation semantics take effect when the macro is executed, not when
7431: it is compiled:
7432:
7433: @example
7434: : [compile-5] ( -- ) \ compiled code: ( -- n )
7435: 5 POSTPONE literal ; immediate
7436:
7437: : foo [compile-5] ;
7438: foo .
7439: @end example
7440:
7441: You may want to pass parameters to a macro, that the macro should
7442: compile into the current definition. If the parameter is a number, then
7443: you can use @code{postpone literal} (similar for other values).
7444:
7445: If you want to pass a word that is to be compiled, the usual way is to
7446: pass an execution token and @code{compile,} it:
7447:
7448: @example
7449: : twice1 ( xt -- ) \ compiled code: ... -- ...
7450: dup compile, compile, ;
7451:
7452: : 2+ ( n1 -- n2 )
7453: [ ' 1+ twice1 ] ;
7454: @end example
7455:
7456: doc-compile,
7457:
7458: An alternative available in Gforth, that allows you to pass compile-only
7459: words as parameters is to use the compilation token (@pxref{Compilation
7460: token}). The same example in this technique:
7461:
7462: @example
7463: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7464: 2dup 2>r execute 2r> execute ;
7465:
7466: : 2+ ( n1 -- n2 )
7467: [ comp' 1+ twice ] ;
7468: @end example
7469:
7470: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7471: works even if the executed compilation semantics has an effect on the
7472: data stack.
7473:
7474: You can also define complete definitions with these words; this provides
7475: an alternative to using @code{does>} (@pxref{User-defined Defining
7476: Words}). E.g., instead of
7477:
7478: @example
7479: : curry+ ( n1 "name" -- )
7480: CREATE ,
7481: DOES> ( n2 -- n1+n2 )
7482: @@ + ;
7483: @end example
7484:
7485: you could define
7486:
7487: @example
7488: : curry+ ( n1 "name" -- )
7489: \ name execution: ( n2 -- n1+n2 )
7490: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7491:
1.82 anton 7492: -3 curry+ 3-
7493: see 3-
7494: @end example
1.81 anton 7495:
1.82 anton 7496: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7497: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7498:
1.82 anton 7499: This way of writing defining words is sometimes more, sometimes less
7500: convenient than using @code{does>} (@pxref{Advanced does> usage
7501: example}). One advantage of this method is that it can be optimized
7502: better, because the compiler knows that the value compiled with
7503: @code{literal} is fixed, whereas the data associated with a
7504: @code{create}d word can be changed.
1.47 crook 7505:
1.26 crook 7506: @c ----------------------------------------------------------
1.111 anton 7507: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7508: @section The Text Interpreter
7509: @cindex interpreter - outer
7510: @cindex text interpreter
7511: @cindex outer interpreter
1.1 anton 7512:
1.34 anton 7513: @c Should we really describe all these ugly details? IMO the text
7514: @c interpreter should be much cleaner, but that may not be possible within
7515: @c ANS Forth. - anton
1.44 crook 7516: @c nac-> I wanted to explain how it works to show how you can exploit
7517: @c it in your own programs. When I was writing a cross-compiler, figuring out
7518: @c some of these gory details was very helpful to me. None of the textbooks
7519: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7520: @c seems to positively avoid going into too much detail for some of
7521: @c the internals.
1.34 anton 7522:
1.71 anton 7523: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7524: @c it is; for the ugly details, I would prefer another place. I wonder
7525: @c whether we should have a chapter before "Words" that describes some
7526: @c basic concepts referred to in words, and a chapter after "Words" that
7527: @c describes implementation details.
7528:
1.29 crook 7529: The text interpreter@footnote{This is an expanded version of the
7530: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7531: that processes input from the current input device. It is also called
7532: the outer interpreter, in contrast to the inner interpreter
7533: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7534: implementations.
1.27 crook 7535:
1.29 crook 7536: @cindex interpret state
7537: @cindex compile state
7538: The text interpreter operates in one of two states: @dfn{interpret
7539: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7540: aptly-named variable @code{state}.
1.29 crook 7541:
7542: This section starts by describing how the text interpreter behaves when
7543: it is in interpret state, processing input from the user input device --
7544: the keyboard. This is the mode that a Forth system is in after it starts
7545: up.
7546:
7547: @cindex input buffer
7548: @cindex terminal input buffer
7549: The text interpreter works from an area of memory called the @dfn{input
7550: buffer}@footnote{When the text interpreter is processing input from the
7551: keyboard, this area of memory is called the @dfn{terminal input buffer}
7552: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7553: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7554: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7555: leading spaces (called @dfn{delimiters}) then parses a string (a
7556: sequence of non-space characters) until it reaches either a space
7557: character or the end of the buffer. Having parsed a string, it makes two
7558: attempts to process it:
1.27 crook 7559:
1.29 crook 7560: @cindex dictionary
1.27 crook 7561: @itemize @bullet
7562: @item
1.29 crook 7563: It looks for the string in a @dfn{dictionary} of definitions. If the
7564: string is found, the string names a @dfn{definition} (also known as a
7565: @dfn{word}) and the dictionary search returns information that allows
7566: the text interpreter to perform the word's @dfn{interpretation
7567: semantics}. In most cases, this simply means that the word will be
7568: executed.
1.27 crook 7569: @item
7570: If the string is not found in the dictionary, the text interpreter
1.29 crook 7571: attempts to treat it as a number, using the rules described in
7572: @ref{Number Conversion}. If the string represents a legal number in the
7573: current radix, the number is pushed onto a parameter stack (the data
7574: stack for integers, the floating-point stack for floating-point
7575: numbers).
7576: @end itemize
7577:
7578: If both attempts fail, or if the word is found in the dictionary but has
7579: no interpretation semantics@footnote{This happens if the word was
7580: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7581: remainder of the input buffer, issues an error message and waits for
7582: more input. If one of the attempts succeeds, the text interpreter
7583: repeats the parsing process until the whole of the input buffer has been
7584: processed, at which point it prints the status message ``@code{ ok}''
7585: and waits for more input.
7586:
1.71 anton 7587: @c anton: this should be in the input stream subsection (or below it)
7588:
1.29 crook 7589: @cindex parse area
7590: The text interpreter keeps track of its position in the input buffer by
7591: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7592: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7593: of the input buffer. The region from offset @code{>IN @@} to the end of
7594: the input buffer is called the @dfn{parse area}@footnote{In other words,
7595: the text interpreter processes the contents of the input buffer by
7596: parsing strings from the parse area until the parse area is empty.}.
7597: This example shows how @code{>IN} changes as the text interpreter parses
7598: the input buffer:
7599:
7600: @example
7601: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7602: CR ." ->" TYPE ." <-" ; IMMEDIATE
7603:
7604: 1 2 3 remaining + remaining .
7605:
7606: : foo 1 2 3 remaining SWAP remaining ;
7607: @end example
7608:
7609: @noindent
7610: The result is:
7611:
7612: @example
7613: ->+ remaining .<-
7614: ->.<-5 ok
7615:
7616: ->SWAP remaining ;-<
7617: ->;<- ok
7618: @end example
7619:
7620: @cindex parsing words
7621: The value of @code{>IN} can also be modified by a word in the input
7622: buffer that is executed by the text interpreter. This means that a word
7623: can ``trick'' the text interpreter into either skipping a section of the
7624: input buffer@footnote{This is how parsing words work.} or into parsing a
7625: section twice. For example:
1.27 crook 7626:
1.29 crook 7627: @example
1.71 anton 7628: : lat ." <<foo>>" ;
7629: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7630: @end example
7631:
7632: @noindent
7633: When @code{flat} is executed, this output is produced@footnote{Exercise
7634: for the reader: what would happen if the @code{3} were replaced with
7635: @code{4}?}:
7636:
7637: @example
1.71 anton 7638: <<bar>><<foo>>
1.29 crook 7639: @end example
7640:
1.71 anton 7641: This technique can be used to work around some of the interoperability
7642: problems of parsing words. Of course, it's better to avoid parsing
7643: words where possible.
7644:
1.29 crook 7645: @noindent
7646: Two important notes about the behaviour of the text interpreter:
1.27 crook 7647:
7648: @itemize @bullet
7649: @item
7650: It processes each input string to completion before parsing additional
1.29 crook 7651: characters from the input buffer.
7652: @item
7653: It treats the input buffer as a read-only region (and so must your code).
7654: @end itemize
7655:
7656: @noindent
7657: When the text interpreter is in compile state, its behaviour changes in
7658: these ways:
7659:
7660: @itemize @bullet
7661: @item
7662: If a parsed string is found in the dictionary, the text interpreter will
7663: perform the word's @dfn{compilation semantics}. In most cases, this
7664: simply means that the execution semantics of the word will be appended
7665: to the current definition.
1.27 crook 7666: @item
1.29 crook 7667: When a number is encountered, it is compiled into the current definition
7668: (as a literal) rather than being pushed onto a parameter stack.
7669: @item
7670: If an error occurs, @code{state} is modified to put the text interpreter
7671: back into interpret state.
7672: @item
7673: Each time a line is entered from the keyboard, Gforth prints
7674: ``@code{ compiled}'' rather than `` @code{ok}''.
7675: @end itemize
7676:
7677: @cindex text interpreter - input sources
7678: When the text interpreter is using an input device other than the
7679: keyboard, its behaviour changes in these ways:
7680:
7681: @itemize @bullet
7682: @item
7683: When the parse area is empty, the text interpreter attempts to refill
7684: the input buffer from the input source. When the input source is
1.71 anton 7685: exhausted, the input source is set back to the previous input source.
1.29 crook 7686: @item
7687: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7688: time the parse area is emptied.
7689: @item
7690: If an error occurs, the input source is set back to the user input
7691: device.
1.27 crook 7692: @end itemize
1.21 crook 7693:
1.49 anton 7694: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7695:
1.26 crook 7696: doc->in
1.27 crook 7697: doc-source
7698:
1.26 crook 7699: doc-tib
7700: doc-#tib
1.1 anton 7701:
1.44 crook 7702:
1.26 crook 7703: @menu
1.67 anton 7704: * Input Sources::
7705: * Number Conversion::
7706: * Interpret/Compile states::
7707: * Interpreter Directives::
1.26 crook 7708: @end menu
1.1 anton 7709:
1.29 crook 7710: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7711: @subsection Input Sources
7712: @cindex input sources
7713: @cindex text interpreter - input sources
7714:
1.44 crook 7715: By default, the text interpreter processes input from the user input
1.29 crook 7716: device (the keyboard) when Forth starts up. The text interpreter can
7717: process input from any of these sources:
7718:
7719: @itemize @bullet
7720: @item
7721: The user input device -- the keyboard.
7722: @item
7723: A file, using the words described in @ref{Forth source files}.
7724: @item
7725: A block, using the words described in @ref{Blocks}.
7726: @item
7727: A text string, using @code{evaluate}.
7728: @end itemize
7729:
7730: A program can identify the current input device from the values of
7731: @code{source-id} and @code{blk}.
7732:
1.44 crook 7733:
1.29 crook 7734: doc-source-id
7735: doc-blk
7736:
7737: doc-save-input
7738: doc-restore-input
7739:
7740: doc-evaluate
1.111 anton 7741: doc-query
1.1 anton 7742:
1.29 crook 7743:
1.44 crook 7744:
1.29 crook 7745: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7746: @subsection Number Conversion
7747: @cindex number conversion
7748: @cindex double-cell numbers, input format
7749: @cindex input format for double-cell numbers
7750: @cindex single-cell numbers, input format
7751: @cindex input format for single-cell numbers
7752: @cindex floating-point numbers, input format
7753: @cindex input format for floating-point numbers
1.1 anton 7754:
1.29 crook 7755: This section describes the rules that the text interpreter uses when it
7756: tries to convert a string into a number.
1.1 anton 7757:
1.26 crook 7758: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7759: number base@footnote{For example, 0-9 when the number base is decimal or
7760: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7761:
1.26 crook 7762: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7763:
1.29 crook 7764: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7765: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7766:
1.26 crook 7767: Let * represent any number of instances of the previous character
7768: (including none).
1.1 anton 7769:
1.26 crook 7770: Let any other character represent itself.
1.1 anton 7771:
1.29 crook 7772: @noindent
1.26 crook 7773: Now, the conversion rules are:
1.21 crook 7774:
1.26 crook 7775: @itemize @bullet
7776: @item
7777: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7778: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7779: @item
7780: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7781: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7782: arithmetic. Examples are -45 -5681 -0
7783: @item
7784: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7785: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7786: (all three of these represent the same number).
1.26 crook 7787: @item
7788: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7789: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7790: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7791: -34.65 (all three of these represent the same number).
1.26 crook 7792: @item
1.29 crook 7793: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7794: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7795: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7796: number) +12.E-4
1.26 crook 7797: @end itemize
1.1 anton 7798:
1.174 anton 7799: By default, the number base used for integer number conversion is
7800: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7801: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7802: change @code{base} anywhere, make sure to save the old value and
7803: restore it afterwards; better yet, use @code{base-execute}, which does
7804: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7805: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7806:
1.29 crook 7807: doc-dpl
1.174 anton 7808: doc-base-execute
1.26 crook 7809: doc-base
7810: doc-hex
7811: doc-decimal
1.1 anton 7812:
1.26 crook 7813: @cindex '-prefix for character strings
7814: @cindex &-prefix for decimal numbers
1.133 anton 7815: @cindex #-prefix for decimal numbers
1.26 crook 7816: @cindex %-prefix for binary numbers
7817: @cindex $-prefix for hexadecimal numbers
1.133 anton 7818: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7819: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7820: prefix@footnote{Some Forth implementations provide a similar scheme by
7821: implementing @code{$} etc. as parsing words that process the subsequent
7822: number in the input stream and push it onto the stack. For example, see
7823: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7824: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7825: is required between the prefix and the number.} before the first digit
1.133 anton 7826: of an (integer) number. The following prefixes are supported:
1.1 anton 7827:
1.26 crook 7828: @itemize @bullet
7829: @item
1.35 anton 7830: @code{&} -- decimal
1.26 crook 7831: @item
1.133 anton 7832: @code{#} -- decimal
7833: @item
1.35 anton 7834: @code{%} -- binary
1.26 crook 7835: @item
1.35 anton 7836: @code{$} -- hexadecimal
1.26 crook 7837: @item
1.133 anton 7838: @code{0x} -- hexadecimal, if base<33.
7839: @item
7840: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7841: optional @code{'} may be present after the character.
1.26 crook 7842: @end itemize
1.1 anton 7843:
1.26 crook 7844: Here are some examples, with the equivalent decimal number shown after
7845: in braces:
1.1 anton 7846:
1.26 crook 7847: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7848: 'A (65),
7849: -'a' (-97),
1.26 crook 7850: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7851:
1.26 crook 7852: @cindex number conversion - traps for the unwary
1.29 crook 7853: @noindent
1.26 crook 7854: Number conversion has a number of traps for the unwary:
1.1 anton 7855:
1.26 crook 7856: @itemize @bullet
7857: @item
7858: You cannot determine the current number base using the code sequence
1.35 anton 7859: @code{base @@ .} -- the number base is always 10 in the current number
7860: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7861: @item
7862: If the number base is set to a value greater than 14 (for example,
7863: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7864: it to be intepreted as either a single-precision integer or a
7865: floating-point number (Gforth treats it as an integer). The ambiguity
7866: can be resolved by explicitly stating the sign of the mantissa and/or
7867: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7868: ambiguity arises; either representation will be treated as a
7869: floating-point number.
7870: @item
1.29 crook 7871: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7872: It is used to specify file types.
7873: @item
1.72 anton 7874: ANS Forth requires the @code{.} of a double-precision number to be the
7875: final character in the string. Gforth allows the @code{.} to be
7876: anywhere after the first digit.
1.26 crook 7877: @item
7878: The number conversion process does not check for overflow.
7879: @item
1.72 anton 7880: In an ANS Forth program @code{base} is required to be decimal when
7881: converting floating-point numbers. In Gforth, number conversion to
7882: floating-point numbers always uses base &10, irrespective of the value
7883: of @code{base}.
1.26 crook 7884: @end itemize
1.1 anton 7885:
1.49 anton 7886: You can read numbers into your programs with the words described in
1.181 anton 7887: @ref{Line input and conversion}.
1.1 anton 7888:
1.82 anton 7889: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7890: @subsection Interpret/Compile states
7891: @cindex Interpret/Compile states
1.1 anton 7892:
1.29 crook 7893: A standard program is not permitted to change @code{state}
7894: explicitly. However, it can change @code{state} implicitly, using the
7895: words @code{[} and @code{]}. When @code{[} is executed it switches
7896: @code{state} to interpret state, and therefore the text interpreter
7897: starts interpreting. When @code{]} is executed it switches @code{state}
7898: to compile state and therefore the text interpreter starts
1.44 crook 7899: compiling. The most common usage for these words is for switching into
7900: interpret state and back from within a colon definition; this technique
1.49 anton 7901: can be used to compile a literal (for an example, @pxref{Literals}) or
7902: for conditional compilation (for an example, @pxref{Interpreter
7903: Directives}).
1.44 crook 7904:
1.35 anton 7905:
7906: @c This is a bad example: It's non-standard, and it's not necessary.
7907: @c However, I can't think of a good example for switching into compile
7908: @c state when there is no current word (@code{state}-smart words are not a
7909: @c good reason). So maybe we should use an example for switching into
7910: @c interpret @code{state} in a colon def. - anton
1.44 crook 7911: @c nac-> I agree. I started out by putting in the example, then realised
7912: @c that it was non-ANS, so wrote more words around it. I hope this
7913: @c re-written version is acceptable to you. I do want to keep the example
7914: @c as it is helpful for showing what is and what is not portable, particularly
7915: @c where it outlaws a style in common use.
7916:
1.72 anton 7917: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7918: @c that, we can also show what's not. In any case, I have written a
7919: @c section Compiling Words which also deals with [ ].
1.35 anton 7920:
1.95 anton 7921: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7922:
1.95 anton 7923: @c @code{[} and @code{]} also give you the ability to switch into compile
7924: @c state and back, but we cannot think of any useful Standard application
7925: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7926:
7927: @c @example
7928: @c : AA ." this is A" ;
7929: @c : BB ." this is B" ;
7930: @c : CC ." this is C" ;
7931:
7932: @c create table ] aa bb cc [
7933:
7934: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7935: @c cells table + @@ execute ;
7936: @c @end example
7937:
7938: @c This example builds a jump table; @code{0 go} will display ``@code{this
7939: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7940: @c defining @code{table} like this:
7941:
7942: @c @example
7943: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7944: @c @end example
7945:
7946: @c The problem with this code is that the definition of @code{table} is not
7947: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7948: @c @i{may} work on systems where code space and data space co-incide, the
7949: @c Standard only allows data space to be assigned for a @code{CREATE}d
7950: @c word. In addition, the Standard only allows @code{@@} to access data
7951: @c space, whilst this example is using it to access code space. The only
7952: @c portable, Standard way to build this table is to build it in data space,
7953: @c like this:
7954:
7955: @c @example
7956: @c create table ' aa , ' bb , ' cc ,
7957: @c @end example
1.29 crook 7958:
1.95 anton 7959: @c doc-state
1.44 crook 7960:
1.29 crook 7961:
1.82 anton 7962: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7963: @subsection Interpreter Directives
7964: @cindex interpreter directives
1.72 anton 7965: @cindex conditional compilation
1.1 anton 7966:
1.29 crook 7967: These words are usually used in interpret state; typically to control
7968: which parts of a source file are processed by the text
1.26 crook 7969: interpreter. There are only a few ANS Forth Standard words, but Gforth
7970: supplements these with a rich set of immediate control structure words
7971: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7972: used in compile state (@pxref{Control Structures}). Typical usages:
7973:
7974: @example
1.72 anton 7975: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7976: .
7977: .
1.72 anton 7978: HAVE-ASSEMBLER [IF]
1.29 crook 7979: : ASSEMBLER-FEATURE
7980: ...
7981: ;
7982: [ENDIF]
7983: .
7984: .
7985: : SEE
7986: ... \ general-purpose SEE code
1.72 anton 7987: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7988: ... \ assembler-specific SEE code
7989: [ [ENDIF] ]
7990: ;
7991: @end example
1.1 anton 7992:
1.44 crook 7993:
1.26 crook 7994: doc-[IF]
7995: doc-[ELSE]
7996: doc-[THEN]
7997: doc-[ENDIF]
1.1 anton 7998:
1.26 crook 7999: doc-[IFDEF]
8000: doc-[IFUNDEF]
1.1 anton 8001:
1.26 crook 8002: doc-[?DO]
8003: doc-[DO]
8004: doc-[FOR]
8005: doc-[LOOP]
8006: doc-[+LOOP]
8007: doc-[NEXT]
1.1 anton 8008:
1.26 crook 8009: doc-[BEGIN]
8010: doc-[UNTIL]
8011: doc-[AGAIN]
8012: doc-[WHILE]
8013: doc-[REPEAT]
1.1 anton 8014:
1.27 crook 8015:
1.26 crook 8016: @c -------------------------------------------------------------
1.111 anton 8017: @node The Input Stream, Word Lists, The Text Interpreter, Words
8018: @section The Input Stream
8019: @cindex input stream
8020:
8021: @c !! integrate this better with the "Text Interpreter" section
8022: The text interpreter reads from the input stream, which can come from
8023: several sources (@pxref{Input Sources}). Some words, in particular
8024: defining words, but also words like @code{'}, read parameters from the
8025: input stream instead of from the stack.
8026:
8027: Such words are called parsing words, because they parse the input
8028: stream. Parsing words are hard to use in other words, because it is
8029: hard to pass program-generated parameters through the input stream.
8030: They also usually have an unintuitive combination of interpretation and
8031: compilation semantics when implemented naively, leading to various
8032: approaches that try to produce a more intuitive behaviour
8033: (@pxref{Combined words}).
8034:
8035: It should be obvious by now that parsing words are a bad idea. If you
8036: want to implement a parsing word for convenience, also provide a factor
8037: of the word that does not parse, but takes the parameters on the stack.
8038: To implement the parsing word on top if it, you can use the following
8039: words:
8040:
8041: @c anton: these belong in the input stream section
8042: doc-parse
1.138 anton 8043: doc-parse-name
1.111 anton 8044: doc-parse-word
8045: doc-name
8046: doc-word
8047: doc-refill
8048:
8049: Conversely, if you have the bad luck (or lack of foresight) to have to
8050: deal with parsing words without having such factors, how do you pass a
8051: string that is not in the input stream to it?
8052:
8053: doc-execute-parsing
8054:
1.146 anton 8055: A definition of this word in ANS Forth is provided in
8056: @file{compat/execute-parsing.fs}.
8057:
1.111 anton 8058: If you want to run a parsing word on a file, the following word should
8059: help:
8060:
8061: doc-execute-parsing-file
8062:
8063: @c -------------------------------------------------------------
8064: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8065: @section Word Lists
8066: @cindex word lists
1.32 anton 8067: @cindex header space
1.1 anton 8068:
1.36 anton 8069: A wordlist is a list of named words; you can add new words and look up
8070: words by name (and you can remove words in a restricted way with
8071: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8072:
8073: @cindex search order stack
8074: The text interpreter searches the wordlists present in the search order
8075: (a stack of wordlists), from the top to the bottom. Within each
8076: wordlist, the search starts conceptually at the newest word; i.e., if
8077: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8078:
1.26 crook 8079: @cindex compilation word list
1.36 anton 8080: New words are added to the @dfn{compilation wordlist} (aka current
8081: wordlist).
1.1 anton 8082:
1.36 anton 8083: @cindex wid
8084: A word list is identified by a cell-sized word list identifier (@i{wid})
8085: in much the same way as a file is identified by a file handle. The
8086: numerical value of the wid has no (portable) meaning, and might change
8087: from session to session.
1.1 anton 8088:
1.29 crook 8089: The ANS Forth ``Search order'' word set is intended to provide a set of
8090: low-level tools that allow various different schemes to be
1.74 anton 8091: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8092: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8093: Forth.
1.1 anton 8094:
1.27 crook 8095: @comment TODO: locals section refers to here, saying that every word list (aka
8096: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8097: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8098:
1.45 crook 8099: @comment TODO: document markers, reveal, tables, mappedwordlist
8100:
8101: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8102: @comment word from the source files, rather than some alias.
1.44 crook 8103:
1.26 crook 8104: doc-forth-wordlist
8105: doc-definitions
8106: doc-get-current
8107: doc-set-current
8108: doc-get-order
1.185 anton 8109: doc-set-order
1.26 crook 8110: doc-wordlist
1.30 anton 8111: doc-table
1.79 anton 8112: doc->order
1.36 anton 8113: doc-previous
1.26 crook 8114: doc-also
1.185 anton 8115: doc-forth
1.26 crook 8116: doc-only
1.185 anton 8117: doc-order
1.15 anton 8118:
1.26 crook 8119: doc-find
8120: doc-search-wordlist
1.15 anton 8121:
1.26 crook 8122: doc-words
8123: doc-vlist
1.44 crook 8124: @c doc-words-deferred
1.1 anton 8125:
1.74 anton 8126: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8127: doc-root
8128: doc-vocabulary
8129: doc-seal
8130: doc-vocs
8131: doc-current
8132: doc-context
1.1 anton 8133:
1.44 crook 8134:
1.26 crook 8135: @menu
1.75 anton 8136: * Vocabularies::
1.67 anton 8137: * Why use word lists?::
1.75 anton 8138: * Word list example::
1.26 crook 8139: @end menu
8140:
1.75 anton 8141: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8142: @subsection Vocabularies
8143: @cindex Vocabularies, detailed explanation
8144:
8145: Here is an example of creating and using a new wordlist using ANS
8146: Forth words:
8147:
8148: @example
8149: wordlist constant my-new-words-wordlist
8150: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8151:
8152: \ add it to the search order
8153: also my-new-words
8154:
8155: \ alternatively, add it to the search order and make it
8156: \ the compilation word list
8157: also my-new-words definitions
8158: \ type "order" to see the problem
8159: @end example
8160:
8161: The problem with this example is that @code{order} has no way to
8162: associate the name @code{my-new-words} with the wid of the word list (in
8163: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8164: that has no associated name). There is no Standard way of associating a
8165: name with a wid.
8166:
8167: In Gforth, this example can be re-coded using @code{vocabulary}, which
8168: associates a name with a wid:
8169:
8170: @example
8171: vocabulary my-new-words
8172:
8173: \ add it to the search order
8174: also my-new-words
8175:
8176: \ alternatively, add it to the search order and make it
8177: \ the compilation word list
8178: my-new-words definitions
8179: \ type "order" to see that the problem is solved
8180: @end example
8181:
8182:
8183: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8184: @subsection Why use word lists?
8185: @cindex word lists - why use them?
8186:
1.74 anton 8187: Here are some reasons why people use wordlists:
1.26 crook 8188:
8189: @itemize @bullet
1.74 anton 8190:
8191: @c anton: Gforth's hashing implementation makes the search speed
8192: @c independent from the number of words. But it is linear with the number
8193: @c of wordlists that have to be searched, so in effect using more wordlists
8194: @c actually slows down compilation.
8195:
8196: @c @item
8197: @c To improve compilation speed by reducing the number of header space
8198: @c entries that must be searched. This is achieved by creating a new
8199: @c word list that contains all of the definitions that are used in the
8200: @c definition of a Forth system but which would not usually be used by
8201: @c programs running on that system. That word list would be on the search
8202: @c list when the Forth system was compiled but would be removed from the
8203: @c search list for normal operation. This can be a useful technique for
8204: @c low-performance systems (for example, 8-bit processors in embedded
8205: @c systems) but is unlikely to be necessary in high-performance desktop
8206: @c systems.
8207:
1.26 crook 8208: @item
8209: To prevent a set of words from being used outside the context in which
8210: they are valid. Two classic examples of this are an integrated editor
8211: (all of the edit commands are defined in a separate word list; the
8212: search order is set to the editor word list when the editor is invoked;
8213: the old search order is restored when the editor is terminated) and an
8214: integrated assembler (the op-codes for the machine are defined in a
8215: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8216:
8217: @item
8218: To organize the words of an application or library into a user-visible
8219: set (in @code{forth-wordlist} or some other common wordlist) and a set
8220: of helper words used just for the implementation (hidden in a separate
1.75 anton 8221: wordlist). This keeps @code{words}' output smaller, separates
8222: implementation and interface, and reduces the chance of name conflicts
8223: within the common wordlist.
1.74 anton 8224:
1.26 crook 8225: @item
8226: To prevent a name-space clash between multiple definitions with the same
8227: name. For example, when building a cross-compiler you might have a word
8228: @code{IF} that generates conditional code for your target system. By
8229: placing this definition in a different word list you can control whether
8230: the host system's @code{IF} or the target system's @code{IF} get used in
8231: any particular context by controlling the order of the word lists on the
8232: search order stack.
1.74 anton 8233:
1.26 crook 8234: @end itemize
1.1 anton 8235:
1.74 anton 8236: The downsides of using wordlists are:
8237:
8238: @itemize
8239:
8240: @item
8241: Debugging becomes more cumbersome.
8242:
8243: @item
8244: Name conflicts worked around with wordlists are still there, and you
8245: have to arrange the search order carefully to get the desired results;
8246: if you forget to do that, you get hard-to-find errors (as in any case
8247: where you read the code differently from the compiler; @code{see} can
1.75 anton 8248: help seeing which of several possible words the name resolves to in such
8249: cases). @code{See} displays just the name of the words, not what
8250: wordlist they belong to, so it might be misleading. Using unique names
8251: is a better approach to avoid name conflicts.
1.74 anton 8252:
8253: @item
8254: You have to explicitly undo any changes to the search order. In many
8255: cases it would be more convenient if this happened implicitly. Gforth
8256: currently does not provide such a feature, but it may do so in the
8257: future.
8258: @end itemize
8259:
8260:
1.75 anton 8261: @node Word list example, , Why use word lists?, Word Lists
8262: @subsection Word list example
8263: @cindex word lists - example
1.1 anton 8264:
1.74 anton 8265: The following example is from the
8266: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8267: garbage collector} and uses wordlists to separate public words from
8268: helper words:
8269:
8270: @example
8271: get-current ( wid )
8272: vocabulary garbage-collector also garbage-collector definitions
8273: ... \ define helper words
8274: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8275: ... \ define the public (i.e., API) words
8276: \ they can refer to the helper words
8277: previous \ restore original search order (helper words become invisible)
8278: @end example
8279:
1.26 crook 8280: @c -------------------------------------------------------------
8281: @node Environmental Queries, Files, Word Lists, Words
8282: @section Environmental Queries
8283: @cindex environmental queries
1.21 crook 8284:
1.26 crook 8285: ANS Forth introduced the idea of ``environmental queries'' as a way
8286: for a program running on a system to determine certain characteristics of the system.
8287: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8288:
1.32 anton 8289: The Standard requires that the header space used for environmental queries
8290: be distinct from the header space used for definitions.
1.21 crook 8291:
1.26 crook 8292: Typically, environmental queries are supported by creating a set of
1.29 crook 8293: definitions in a word list that is @i{only} used during environmental
1.26 crook 8294: queries; that is what Gforth does. There is no Standard way of adding
8295: definitions to the set of recognised environmental queries, but any
8296: implementation that supports the loading of optional word sets must have
8297: some mechanism for doing this (after loading the word set, the
8298: associated environmental query string must return @code{true}). In
8299: Gforth, the word list used to honour environmental queries can be
8300: manipulated just like any other word list.
1.21 crook 8301:
1.44 crook 8302:
1.26 crook 8303: doc-environment?
8304: doc-environment-wordlist
1.21 crook 8305:
1.26 crook 8306: doc-gforth
8307: doc-os-class
1.21 crook 8308:
1.44 crook 8309:
1.26 crook 8310: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8311: returning two items on the stack, querying it using @code{environment?}
8312: will return an additional item; the @code{true} flag that shows that the
8313: string was recognised.
1.21 crook 8314:
1.26 crook 8315: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8316:
1.26 crook 8317: Here are some examples of using environmental queries:
1.21 crook 8318:
1.26 crook 8319: @example
8320: s" address-unit-bits" environment? 0=
8321: [IF]
8322: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8323: [ELSE]
8324: drop \ ensure balanced stack effect
1.26 crook 8325: [THEN]
1.21 crook 8326:
1.75 anton 8327: \ this might occur in the prelude of a standard program that uses THROW
8328: s" exception" environment? [IF]
8329: 0= [IF]
8330: : throw abort" exception thrown" ;
8331: [THEN]
8332: [ELSE] \ we don't know, so make sure
8333: : throw abort" exception thrown" ;
8334: [THEN]
1.21 crook 8335:
1.26 crook 8336: s" gforth" environment? [IF] .( Gforth version ) TYPE
8337: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8338:
8339: \ a program using v*
8340: s" gforth" environment? [IF]
8341: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8342: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8343: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8344: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8345: LOOP
8346: 2drop 2drop ;
8347: [THEN]
8348: [ELSE] \
8349: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8350: ...
8351: [THEN]
1.26 crook 8352: @end example
1.21 crook 8353:
1.26 crook 8354: Here is an example of adding a definition to the environment word list:
1.21 crook 8355:
1.26 crook 8356: @example
8357: get-current environment-wordlist set-current
8358: true constant block
8359: true constant block-ext
8360: set-current
8361: @end example
1.21 crook 8362:
1.26 crook 8363: You can see what definitions are in the environment word list like this:
1.21 crook 8364:
1.26 crook 8365: @example
1.79 anton 8366: environment-wordlist >order words previous
1.26 crook 8367: @end example
1.21 crook 8368:
8369:
1.26 crook 8370: @c -------------------------------------------------------------
8371: @node Files, Blocks, Environmental Queries, Words
8372: @section Files
1.28 crook 8373: @cindex files
8374: @cindex I/O - file-handling
1.21 crook 8375:
1.26 crook 8376: Gforth provides facilities for accessing files that are stored in the
8377: host operating system's file-system. Files that are processed by Gforth
8378: can be divided into two categories:
1.21 crook 8379:
1.23 crook 8380: @itemize @bullet
8381: @item
1.29 crook 8382: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8383: @item
1.29 crook 8384: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8385: @end itemize
8386:
8387: @menu
1.48 anton 8388: * Forth source files::
8389: * General files::
1.167 anton 8390: * Redirection::
1.48 anton 8391: * Search Paths::
1.26 crook 8392: @end menu
8393:
8394: @c -------------------------------------------------------------
8395: @node Forth source files, General files, Files, Files
8396: @subsection Forth source files
8397: @cindex including files
8398: @cindex Forth source files
1.21 crook 8399:
1.26 crook 8400: The simplest way to interpret the contents of a file is to use one of
8401: these two formats:
1.21 crook 8402:
1.26 crook 8403: @example
8404: include mysource.fs
8405: s" mysource.fs" included
8406: @end example
1.21 crook 8407:
1.75 anton 8408: You usually want to include a file only if it is not included already
1.26 crook 8409: (by, say, another source file). In that case, you can use one of these
1.45 crook 8410: three formats:
1.21 crook 8411:
1.26 crook 8412: @example
8413: require mysource.fs
8414: needs mysource.fs
8415: s" mysource.fs" required
8416: @end example
1.21 crook 8417:
1.26 crook 8418: @cindex stack effect of included files
8419: @cindex including files, stack effect
1.45 crook 8420: It is good practice to write your source files such that interpreting them
8421: does not change the stack. Source files designed in this way can be used with
1.26 crook 8422: @code{required} and friends without complications. For example:
1.21 crook 8423:
1.26 crook 8424: @example
1.75 anton 8425: 1024 require foo.fs drop
1.26 crook 8426: @end example
1.21 crook 8427:
1.75 anton 8428: Here you want to pass the argument 1024 (e.g., a buffer size) to
8429: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8430: ), which allows its use with @code{require}. Of course with such
8431: parameters to required files, you have to ensure that the first
8432: @code{require} fits for all uses (i.e., @code{require} it early in the
8433: master load file).
1.44 crook 8434:
1.26 crook 8435: doc-include-file
8436: doc-included
1.28 crook 8437: doc-included?
1.26 crook 8438: doc-include
8439: doc-required
8440: doc-require
8441: doc-needs
1.75 anton 8442: @c doc-init-included-files @c internal
8443: doc-sourcefilename
8444: doc-sourceline#
1.44 crook 8445:
1.26 crook 8446: A definition in ANS Forth for @code{required} is provided in
8447: @file{compat/required.fs}.
1.21 crook 8448:
1.26 crook 8449: @c -------------------------------------------------------------
1.167 anton 8450: @node General files, Redirection, Forth source files, Files
1.26 crook 8451: @subsection General files
8452: @cindex general files
8453: @cindex file-handling
1.21 crook 8454:
1.75 anton 8455: Files are opened/created by name and type. The following file access
8456: methods (FAMs) are recognised:
1.44 crook 8457:
1.75 anton 8458: @cindex fam (file access method)
1.26 crook 8459: doc-r/o
8460: doc-r/w
8461: doc-w/o
8462: doc-bin
1.1 anton 8463:
1.44 crook 8464:
1.26 crook 8465: When a file is opened/created, it returns a file identifier,
1.29 crook 8466: @i{wfileid} that is used for all other file commands. All file
8467: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8468: successful operation and an implementation-defined non-zero value in the
8469: case of an error.
1.21 crook 8470:
1.44 crook 8471:
1.26 crook 8472: doc-open-file
8473: doc-create-file
1.21 crook 8474:
1.26 crook 8475: doc-close-file
8476: doc-delete-file
8477: doc-rename-file
8478: doc-read-file
8479: doc-read-line
1.154 anton 8480: doc-key-file
8481: doc-key?-file
1.26 crook 8482: doc-write-file
8483: doc-write-line
8484: doc-emit-file
8485: doc-flush-file
1.21 crook 8486:
1.26 crook 8487: doc-file-status
8488: doc-file-position
8489: doc-reposition-file
8490: doc-file-size
8491: doc-resize-file
1.21 crook 8492:
1.93 anton 8493: doc-slurp-file
8494: doc-slurp-fid
1.112 anton 8495: doc-stdin
8496: doc-stdout
8497: doc-stderr
1.44 crook 8498:
1.26 crook 8499: @c ---------------------------------------------------------
1.167 anton 8500: @node Redirection, Search Paths, General files, Files
8501: @subsection Redirection
8502: @cindex Redirection
8503: @cindex Input Redirection
8504: @cindex Output Redirection
8505:
8506: You can redirect the output of @code{type} and @code{emit} and all the
8507: words that use them (all output words that don't have an explicit
1.174 anton 8508: target file) to an arbitrary file with the @code{outfile-execute},
8509: used like this:
1.167 anton 8510:
8511: @example
1.174 anton 8512: : some-warning ( n -- )
8513: cr ." warning# " . ;
8514:
1.167 anton 8515: : print-some-warning ( n -- )
1.174 anton 8516: ['] some-warning stderr outfile-execute ;
1.167 anton 8517: @end example
8518:
1.174 anton 8519: After @code{some-warning} is executed, the original output direction
8520: is restored; this construct is safe against exceptions. Similarly,
8521: there is @code{infile-execute} for redirecting the input of @code{key}
8522: and its users (any input word that does not take a file explicitly).
8523:
8524: doc-outfile-execute
8525: doc-infile-execute
1.167 anton 8526:
8527: If you do not want to redirect the input or output to a file, you can
8528: also make use of the fact that @code{key}, @code{emit} and @code{type}
8529: are deferred words (@pxref{Deferred Words}). However, in that case
8530: you have to worry about the restoration and the protection against
8531: exceptions yourself; also, note that for redirecting the output in
8532: this way, you have to redirect both @code{emit} and @code{type}.
8533:
8534: @c ---------------------------------------------------------
8535: @node Search Paths, , Redirection, Files
1.26 crook 8536: @subsection Search Paths
8537: @cindex path for @code{included}
8538: @cindex file search path
8539: @cindex @code{include} search path
8540: @cindex search path for files
1.21 crook 8541:
1.26 crook 8542: If you specify an absolute filename (i.e., a filename starting with
8543: @file{/} or @file{~}, or with @file{:} in the second position (as in
8544: @samp{C:...})) for @code{included} and friends, that file is included
8545: just as you would expect.
1.21 crook 8546:
1.75 anton 8547: If the filename starts with @file{./}, this refers to the directory that
8548: the present file was @code{included} from. This allows files to include
8549: other files relative to their own position (irrespective of the current
8550: working directory or the absolute position). This feature is essential
8551: for libraries consisting of several files, where a file may include
8552: other files from the library. It corresponds to @code{#include "..."}
8553: in C. If the current input source is not a file, @file{.} refers to the
8554: directory of the innermost file being included, or, if there is no file
8555: being included, to the current working directory.
8556:
8557: For relative filenames (not starting with @file{./}), Gforth uses a
8558: search path similar to Forth's search order (@pxref{Word Lists}). It
8559: tries to find the given filename in the directories present in the path,
8560: and includes the first one it finds. There are separate search paths for
8561: Forth source files and general files. If the search path contains the
8562: directory @file{.}, this refers to the directory of the current file, or
8563: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8564:
1.26 crook 8565: Use @file{~+} to refer to the current working directory (as in the
8566: @code{bash}).
1.1 anton 8567:
1.75 anton 8568: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8569:
1.48 anton 8570: @menu
1.75 anton 8571: * Source Search Paths::
1.48 anton 8572: * General Search Paths::
8573: @end menu
8574:
1.26 crook 8575: @c ---------------------------------------------------------
1.75 anton 8576: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8577: @subsubsection Source Search Paths
8578: @cindex search path control, source files
1.5 anton 8579:
1.26 crook 8580: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8581: Gforth}). You can display it and change it using @code{fpath} in
8582: combination with the general path handling words.
1.5 anton 8583:
1.75 anton 8584: doc-fpath
8585: @c the functionality of the following words is easily available through
8586: @c fpath and the general path words. The may go away.
8587: @c doc-.fpath
8588: @c doc-fpath+
8589: @c doc-fpath=
8590: @c doc-open-fpath-file
1.44 crook 8591:
8592: @noindent
1.26 crook 8593: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8594:
1.26 crook 8595: @example
1.75 anton 8596: fpath path= /usr/lib/forth/|./
1.26 crook 8597: require timer.fs
8598: @end example
1.5 anton 8599:
1.75 anton 8600:
1.26 crook 8601: @c ---------------------------------------------------------
1.75 anton 8602: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8603: @subsubsection General Search Paths
1.75 anton 8604: @cindex search path control, source files
1.5 anton 8605:
1.26 crook 8606: Your application may need to search files in several directories, like
8607: @code{included} does. To facilitate this, Gforth allows you to define
8608: and use your own search paths, by providing generic equivalents of the
8609: Forth search path words:
1.5 anton 8610:
1.75 anton 8611: doc-open-path-file
8612: doc-path-allot
8613: doc-clear-path
8614: doc-also-path
1.26 crook 8615: doc-.path
8616: doc-path+
8617: doc-path=
1.5 anton 8618:
1.75 anton 8619: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8620:
1.75 anton 8621: Here's an example of creating an empty search path:
8622: @c
1.26 crook 8623: @example
1.75 anton 8624: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8625: @end example
1.5 anton 8626:
1.26 crook 8627: @c -------------------------------------------------------------
8628: @node Blocks, Other I/O, Files, Words
8629: @section Blocks
1.28 crook 8630: @cindex I/O - blocks
8631: @cindex blocks
8632:
8633: When you run Gforth on a modern desk-top computer, it runs under the
8634: control of an operating system which provides certain services. One of
8635: these services is @var{file services}, which allows Forth source code
8636: and data to be stored in files and read into Gforth (@pxref{Files}).
8637:
8638: Traditionally, Forth has been an important programming language on
8639: systems where it has interfaced directly to the underlying hardware with
8640: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8641: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8642:
8643: A block is a 1024-byte data area, which can be used to hold data or
8644: Forth source code. No structure is imposed on the contents of the
8645: block. A block is identified by its number; blocks are numbered
8646: contiguously from 1 to an implementation-defined maximum.
8647:
8648: A typical system that used blocks but no operating system might use a
8649: single floppy-disk drive for mass storage, with the disks formatted to
8650: provide 256-byte sectors. Blocks would be implemented by assigning the
8651: first four sectors of the disk to block 1, the second four sectors to
8652: block 2 and so on, up to the limit of the capacity of the disk. The disk
8653: would not contain any file system information, just the set of blocks.
8654:
1.29 crook 8655: @cindex blocks file
1.28 crook 8656: On systems that do provide file services, blocks are typically
1.29 crook 8657: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8658: file}. The size of the blocks file will be an exact multiple of 1024
8659: bytes, corresponding to the number of blocks it contains. This is the
8660: mechanism that Gforth uses.
8661:
1.29 crook 8662: @cindex @file{blocks.fb}
1.75 anton 8663: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8664: having specified a blocks file, Gforth defaults to the blocks file
8665: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8666: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8667:
1.29 crook 8668: @cindex block buffers
1.28 crook 8669: When you read and write blocks under program control, Gforth uses a
1.29 crook 8670: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8671: not used when you use @code{load} to interpret the contents of a block.
8672:
1.75 anton 8673: The behaviour of the block buffers is analagous to that of a cache.
8674: Each block buffer has three states:
1.28 crook 8675:
8676: @itemize @bullet
8677: @item
8678: Unassigned
8679: @item
8680: Assigned-clean
8681: @item
8682: Assigned-dirty
8683: @end itemize
8684:
1.29 crook 8685: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8686: block, the block (specified by its block number) must be assigned to a
8687: block buffer.
8688:
8689: The assignment of a block to a block buffer is performed by @code{block}
8690: or @code{buffer}. Use @code{block} when you wish to modify the existing
8691: contents of a block. Use @code{buffer} when you don't care about the
8692: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8693: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8694: with the particular block is already stored in a block buffer due to an
8695: earlier @code{block} command, @code{buffer} will return that block
8696: buffer and the existing contents of the block will be
8697: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8698: block buffer for the block.}.
1.28 crook 8699:
1.47 crook 8700: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8701: @code{buffer}, that block buffer becomes the @i{current block
8702: buffer}. Data may only be manipulated (read or written) within the
8703: current block buffer.
1.47 crook 8704:
8705: When the contents of the current block buffer has been modified it is
1.48 anton 8706: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8707: either abandon the changes (by doing nothing) or mark the block as
8708: changed (assigned-dirty), using @code{update}. Using @code{update} does
8709: not change the blocks file; it simply changes a block buffer's state to
8710: @i{assigned-dirty}. The block will be written implicitly when it's
8711: buffer is needed for another block, or explicitly by @code{flush} or
8712: @code{save-buffers}.
8713:
8714: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8715: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8716: @code{flush}.
1.28 crook 8717:
1.29 crook 8718: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8719: algorithm to assign a block buffer to a block. That means that any
8720: particular block can only be assigned to one specific block buffer,
1.29 crook 8721: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8722: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8723: the new block immediately. If it is @i{assigned-dirty} its current
8724: contents are written back to the blocks file on disk before it is
1.28 crook 8725: allocated to the new block.
8726:
8727: Although no structure is imposed on the contents of a block, it is
8728: traditional to display the contents as 16 lines each of 64 characters. A
8729: block provides a single, continuous stream of input (for example, it
8730: acts as a single parse area) -- there are no end-of-line characters
8731: within a block, and no end-of-file character at the end of a
8732: block. There are two consequences of this:
1.26 crook 8733:
1.28 crook 8734: @itemize @bullet
8735: @item
8736: The last character of one line wraps straight into the first character
8737: of the following line
8738: @item
8739: The word @code{\} -- comment to end of line -- requires special
8740: treatment; in the context of a block it causes all characters until the
8741: end of the current 64-character ``line'' to be ignored.
8742: @end itemize
8743:
8744: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8745: the current blocks file will be extended to the appropriate size and the
1.28 crook 8746: block buffer will be initialised with spaces.
8747:
1.47 crook 8748: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8749: for details) but doesn't encourage the use of blocks; the mechanism is
8750: only provided for backward compatibility -- ANS Forth requires blocks to
8751: be available when files are.
1.28 crook 8752:
8753: Common techniques that are used when working with blocks include:
8754:
8755: @itemize @bullet
8756: @item
8757: A screen editor that allows you to edit blocks without leaving the Forth
8758: environment.
8759: @item
8760: Shadow screens; where every code block has an associated block
8761: containing comments (for example: code in odd block numbers, comments in
8762: even block numbers). Typically, the block editor provides a convenient
8763: mechanism to toggle between code and comments.
8764: @item
8765: Load blocks; a single block (typically block 1) contains a number of
8766: @code{thru} commands which @code{load} the whole of the application.
8767: @end itemize
1.26 crook 8768:
1.29 crook 8769: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8770: integrated into a Forth programming environment.
1.26 crook 8771:
8772: @comment TODO what about errors on open-blocks?
1.44 crook 8773:
1.26 crook 8774: doc-open-blocks
8775: doc-use
1.75 anton 8776: doc-block-offset
1.26 crook 8777: doc-get-block-fid
8778: doc-block-position
1.28 crook 8779:
1.75 anton 8780: doc-list
1.28 crook 8781: doc-scr
8782:
1.184 anton 8783: doc-block
1.28 crook 8784: doc-buffer
8785:
1.75 anton 8786: doc-empty-buffers
8787: doc-empty-buffer
1.26 crook 8788: doc-update
1.28 crook 8789: doc-updated?
1.26 crook 8790: doc-save-buffers
1.75 anton 8791: doc-save-buffer
1.26 crook 8792: doc-flush
1.28 crook 8793:
1.26 crook 8794: doc-load
8795: doc-thru
8796: doc-+load
8797: doc-+thru
1.45 crook 8798: doc---gforthman--->
1.26 crook 8799: doc-block-included
8800:
1.44 crook 8801:
1.26 crook 8802: @c -------------------------------------------------------------
1.126 pazsan 8803: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8804: @section Other I/O
1.28 crook 8805: @cindex I/O - keyboard and display
1.26 crook 8806:
8807: @menu
8808: * Simple numeric output:: Predefined formats
8809: * Formatted numeric output:: Formatted (pictured) output
8810: * String Formats:: How Forth stores strings in memory
1.67 anton 8811: * Displaying characters and strings:: Other stuff
1.175 anton 8812: * Terminal output:: Cursor positioning etc.
1.181 anton 8813: * Single-key input::
8814: * Line input and conversion::
1.112 anton 8815: * Pipes:: How to create your own pipes
1.149 pazsan 8816: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8817: @end menu
8818:
8819: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8820: @subsection Simple numeric output
1.28 crook 8821: @cindex numeric output - simple/free-format
1.5 anton 8822:
1.26 crook 8823: The simplest output functions are those that display numbers from the
8824: data or floating-point stacks. Floating-point output is always displayed
8825: using base 10. Numbers displayed from the data stack use the value stored
8826: in @code{base}.
1.5 anton 8827:
1.44 crook 8828:
1.26 crook 8829: doc-.
8830: doc-dec.
8831: doc-hex.
8832: doc-u.
8833: doc-.r
8834: doc-u.r
8835: doc-d.
8836: doc-ud.
8837: doc-d.r
8838: doc-ud.r
8839: doc-f.
8840: doc-fe.
8841: doc-fs.
1.111 anton 8842: doc-f.rdp
1.44 crook 8843:
1.26 crook 8844: Examples of printing the number 1234.5678E23 in the different floating-point output
8845: formats are shown below:
1.5 anton 8846:
8847: @example
1.26 crook 8848: f. 123456779999999000000000000.
8849: fe. 123.456779999999E24
8850: fs. 1.23456779999999E26
1.5 anton 8851: @end example
8852:
8853:
1.26 crook 8854: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8855: @subsection Formatted numeric output
1.28 crook 8856: @cindex formatted numeric output
1.26 crook 8857: @cindex pictured numeric output
1.28 crook 8858: @cindex numeric output - formatted
1.26 crook 8859:
1.29 crook 8860: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8861: output} for formatted printing of integers. In this technique, digits
8862: are extracted from the number (using the current output radix defined by
8863: @code{base}), converted to ASCII codes and appended to a string that is
8864: built in a scratch-pad area of memory (@pxref{core-idef,
8865: Implementation-defined options, Implementation-defined
8866: options}). Arbitrary characters can be appended to the string during the
8867: extraction process. The completed string is specified by an address
8868: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8869: under program control.
1.5 anton 8870:
1.75 anton 8871: All of the integer output words described in the previous section
8872: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8873: numeric output.
1.5 anton 8874:
1.47 crook 8875: Three important things to remember about pictured numeric output:
1.5 anton 8876:
1.26 crook 8877: @itemize @bullet
8878: @item
1.28 crook 8879: It always operates on double-precision numbers; to display a
1.49 anton 8880: single-precision number, convert it first (for ways of doing this
8881: @pxref{Double precision}).
1.26 crook 8882: @item
1.28 crook 8883: It always treats the double-precision number as though it were
8884: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8885: @item
8886: The string is built up from right to left; least significant digit first.
8887: @end itemize
1.5 anton 8888:
1.44 crook 8889:
1.26 crook 8890: doc-<#
1.47 crook 8891: doc-<<#
1.26 crook 8892: doc-#
8893: doc-#s
8894: doc-hold
8895: doc-sign
8896: doc-#>
1.47 crook 8897: doc-#>>
1.5 anton 8898:
1.26 crook 8899: doc-represent
1.111 anton 8900: doc-f>str-rdp
8901: doc-f>buf-rdp
1.5 anton 8902:
1.44 crook 8903:
8904: @noindent
1.26 crook 8905: Here are some examples of using pictured numeric output:
1.5 anton 8906:
8907: @example
1.26 crook 8908: : my-u. ( u -- )
8909: \ Simplest use of pns.. behaves like Standard u.
8910: 0 \ convert to unsigned double
1.75 anton 8911: <<# \ start conversion
1.26 crook 8912: #s \ convert all digits
8913: #> \ complete conversion
1.75 anton 8914: TYPE SPACE \ display, with trailing space
8915: #>> ; \ release hold area
1.5 anton 8916:
1.26 crook 8917: : cents-only ( u -- )
8918: 0 \ convert to unsigned double
1.75 anton 8919: <<# \ start conversion
1.26 crook 8920: # # \ convert two least-significant digits
8921: #> \ complete conversion, discard other digits
1.75 anton 8922: TYPE SPACE \ display, with trailing space
8923: #>> ; \ release hold area
1.5 anton 8924:
1.26 crook 8925: : dollars-and-cents ( u -- )
8926: 0 \ convert to unsigned double
1.75 anton 8927: <<# \ start conversion
1.26 crook 8928: # # \ convert two least-significant digits
8929: [char] . hold \ insert decimal point
8930: #s \ convert remaining digits
8931: [char] $ hold \ append currency symbol
8932: #> \ complete conversion
1.75 anton 8933: TYPE SPACE \ display, with trailing space
8934: #>> ; \ release hold area
1.5 anton 8935:
1.26 crook 8936: : my-. ( n -- )
8937: \ handling negatives.. behaves like Standard .
8938: s>d \ convert to signed double
8939: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8940: <<# \ start conversion
1.26 crook 8941: #s \ convert all digits
8942: rot sign \ get at sign byte, append "-" if needed
8943: #> \ complete conversion
1.75 anton 8944: TYPE SPACE \ display, with trailing space
8945: #>> ; \ release hold area
1.5 anton 8946:
1.26 crook 8947: : account. ( n -- )
1.75 anton 8948: \ accountants don't like minus signs, they use parentheses
1.26 crook 8949: \ for negative numbers
8950: s>d \ convert to signed double
8951: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8952: <<# \ start conversion
1.26 crook 8953: 2 pick \ get copy of sign byte
8954: 0< IF [char] ) hold THEN \ right-most character of output
8955: #s \ convert all digits
8956: rot \ get at sign byte
8957: 0< IF [char] ( hold THEN
8958: #> \ complete conversion
1.75 anton 8959: TYPE SPACE \ display, with trailing space
8960: #>> ; \ release hold area
8961:
1.5 anton 8962: @end example
8963:
1.26 crook 8964: Here are some examples of using these words:
1.5 anton 8965:
8966: @example
1.26 crook 8967: 1 my-u. 1
8968: hex -1 my-u. decimal FFFFFFFF
8969: 1 cents-only 01
8970: 1234 cents-only 34
8971: 2 dollars-and-cents $0.02
8972: 1234 dollars-and-cents $12.34
8973: 123 my-. 123
8974: -123 my. -123
8975: 123 account. 123
8976: -456 account. (456)
1.5 anton 8977: @end example
8978:
8979:
1.26 crook 8980: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8981: @subsection String Formats
1.27 crook 8982: @cindex strings - see character strings
8983: @cindex character strings - formats
1.28 crook 8984: @cindex I/O - see character strings
1.75 anton 8985: @cindex counted strings
8986:
8987: @c anton: this does not really belong here; maybe the memory section,
8988: @c or the principles chapter
1.26 crook 8989:
1.27 crook 8990: Forth commonly uses two different methods for representing character
8991: strings:
1.26 crook 8992:
8993: @itemize @bullet
8994: @item
8995: @cindex address of counted string
1.45 crook 8996: @cindex counted string
1.29 crook 8997: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8998: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8999: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9000: memory.
9001: @item
1.29 crook 9002: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9003: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9004: first byte of the string.
9005: @end itemize
9006:
9007: ANS Forth encourages the use of the second format when representing
1.75 anton 9008: strings.
1.26 crook 9009:
1.44 crook 9010:
1.26 crook 9011: doc-count
9012:
1.44 crook 9013:
1.49 anton 9014: For words that move, copy and search for strings see @ref{Memory
9015: Blocks}. For words that display characters and strings see
9016: @ref{Displaying characters and strings}.
1.26 crook 9017:
1.175 anton 9018: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9019: @subsection Displaying characters and strings
1.27 crook 9020: @cindex characters - compiling and displaying
9021: @cindex character strings - compiling and displaying
1.26 crook 9022:
9023: This section starts with a glossary of Forth words and ends with a set
9024: of examples.
9025:
9026: doc-bl
9027: doc-space
9028: doc-spaces
9029: doc-emit
9030: doc-toupper
9031: doc-."
9032: doc-.(
1.98 anton 9033: doc-.\"
1.26 crook 9034: doc-type
1.44 crook 9035: doc-typewhite
1.26 crook 9036: doc-cr
1.27 crook 9037: @cindex cursor control
1.26 crook 9038: doc-s"
1.98 anton 9039: doc-s\"
1.26 crook 9040: doc-c"
9041: doc-char
9042: doc-[char]
9043:
1.44 crook 9044:
9045: @noindent
1.26 crook 9046: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9047:
9048: @example
1.26 crook 9049: .( text-1)
9050: : my-word
9051: ." text-2" cr
9052: .( text-3)
9053: ;
9054:
9055: ." text-4"
9056:
9057: : my-char
9058: [char] ALPHABET emit
9059: char emit
9060: ;
1.5 anton 9061: @end example
9062:
1.26 crook 9063: When you load this code into Gforth, the following output is generated:
1.5 anton 9064:
1.26 crook 9065: @example
1.30 anton 9066: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9067: @end example
1.5 anton 9068:
1.26 crook 9069: @itemize @bullet
9070: @item
9071: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9072: is an immediate word; it behaves in the same way whether it is used inside
9073: or outside a colon definition.
9074: @item
9075: Message @code{text-4} is displayed because of Gforth's added interpretation
9076: semantics for @code{."}.
9077: @item
1.29 crook 9078: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9079: performs the compilation semantics for @code{."} within the definition of
9080: @code{my-word}.
9081: @end itemize
1.5 anton 9082:
1.26 crook 9083: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9084:
1.26 crook 9085: @example
1.30 anton 9086: @kbd{my-word @key{RET}} text-2
1.26 crook 9087: ok
1.30 anton 9088: @kbd{my-char fred @key{RET}} Af ok
9089: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9090: @end example
1.5 anton 9091:
9092: @itemize @bullet
9093: @item
1.26 crook 9094: Message @code{text-2} is displayed because of the run-time behaviour of
9095: @code{."}.
9096: @item
9097: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9098: on the stack at run-time. @code{emit} always displays the character
9099: when @code{my-char} is executed.
9100: @item
9101: @code{char} parses a string at run-time and the second @code{emit} displays
9102: the first character of the string.
1.5 anton 9103: @item
1.26 crook 9104: If you type @code{see my-char} you can see that @code{[char]} discarded
9105: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9106: definition of @code{my-char}.
1.5 anton 9107: @end itemize
9108:
9109:
1.181 anton 9110: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9111: @subsection Terminal output
9112: @cindex output to terminal
9113: @cindex terminal output
9114:
9115: If you are outputting to a terminal, you may want to control the
9116: positioning of the cursor:
9117: @cindex cursor positioning
9118:
9119: doc-at-xy
9120:
9121: In order to know where to position the cursor, it is often helpful to
9122: know the size of the screen:
9123: @cindex terminal size
9124:
9125: doc-form
9126:
9127: And sometimes you want to use:
9128: @cindex clear screen
9129:
9130: doc-page
9131:
9132: Note that on non-terminals you should use @code{12 emit}, not
9133: @code{page}, to get a form feed.
9134:
1.5 anton 9135:
1.181 anton 9136: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9137: @subsection Single-key input
9138: @cindex single-key input
9139: @cindex input, single-key
9140:
9141: If you want to get a single printable character, you can use
9142: @code{key}; to check whether a character is available for @code{key},
9143: you can use @code{key?}.
1.5 anton 9144:
1.181 anton 9145: doc-key
9146: doc-key?
1.27 crook 9147:
1.181 anton 9148: If you want to process a mix of printable and non-printable
9149: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9150: produces a keyboard event that you have to convert into a character
9151: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9152:
9153: Typical code for using EKEY looks like this:
9154:
9155: @example
9156: ekey ekey>char if ( c )
9157: ... \ do something with the character
9158: else ekey>fkey if ( key-id )
9159: case
9160: k-up of ... endof
9161: k-f1 of ... endof
9162: k-left k-shift-mask or k-ctrl-mask or of ... endof
9163: ...
9164: endcase
9165: else ( keyboard-event )
9166: drop \ just ignore an unknown keyboard event type
9167: then then
9168: @end example
1.44 crook 9169:
1.45 crook 9170: doc-ekey
1.141 anton 9171: doc-ekey>char
1.181 anton 9172: doc-ekey>fkey
1.45 crook 9173: doc-ekey?
1.141 anton 9174:
1.181 anton 9175: The key identifiers for cursor keys are:
1.141 anton 9176:
9177: doc-k-left
9178: doc-k-right
1.185 anton 9179: doc-k-up
9180: doc-k-down
9181: doc-k-home
9182: doc-k-end
1.141 anton 9183: doc-k-prior
9184: doc-k-next
9185: doc-k-insert
9186: doc-k-delete
9187:
1.181 anton 9188: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9189:
1.181 anton 9190: doc-k-f1
9191: doc-k-f2
9192: doc-k-f3
9193: doc-k-f4
9194: doc-k-f5
9195: doc-k-f6
9196: doc-k-f7
9197: doc-k-f8
9198: doc-k-f9
9199: doc-k-f10
9200: doc-k-f11
9201: doc-k-f12
9202:
9203: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9204:
9205: You can combine these key identifiers with masks for various shift keys:
9206:
9207: doc-k-shift-mask
9208: doc-k-ctrl-mask
9209: doc-k-alt-mask
9210:
9211: Note that, even if a Forth system has @code{ekey>fkey} and the key
9212: identifier words, the keys are not necessarily available or it may not
9213: necessarily be able to report all the keys and all the possible
9214: combinations with shift masks. Therefore, write your programs in such
9215: a way that they are still useful even if the keys and key combinations
9216: cannot be pressed or are not recognized.
9217:
9218: Examples: Older keyboards often do not have an F11 and F12 key. If
9219: you run Gforth in an xterm, the xterm catches a number of combinations
9220: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9221: Gforth currently does not recognize and report combinations with
9222: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9223: above would never be entered).
9224:
9225: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9226: you need the ANSI.SYS driver to get that behaviour); it works by
9227: recognizing the escape sequences that ANSI terminals send when such a
9228: key is pressed. If you have a terminal that sends other escape
9229: sequences, you will not get useful results on Gforth. Other Forth
9230: systems may work in a different way.
9231:
9232:
9233: @node Line input and conversion, Pipes, Single-key input, Other I/O
9234: @subsection Line input and conversion
9235: @cindex line input from terminal
9236: @cindex input, linewise from terminal
9237: @cindex convertin strings to numbers
9238: @cindex I/O - see input
9239:
9240: For ways of storing character strings in memory see @ref{String Formats}.
9241:
9242: @comment TODO examples for >number >float accept key key? pad parse word refill
9243: @comment then index them
1.141 anton 9244:
9245: Words for inputting one line from the keyboard:
9246:
9247: doc-accept
9248: doc-edit-line
9249:
9250: Conversion words:
9251:
1.143 anton 9252: doc-s>number?
9253: doc-s>unumber?
1.26 crook 9254: doc->number
9255: doc->float
1.143 anton 9256:
1.141 anton 9257:
1.27 crook 9258: @comment obsolescent words..
1.141 anton 9259: Obsolescent input and conversion words:
9260:
1.27 crook 9261: doc-convert
1.26 crook 9262: doc-expect
1.27 crook 9263: doc-span
1.5 anton 9264:
9265:
1.181 anton 9266: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9267: @subsection Pipes
9268: @cindex pipes, creating your own
9269:
9270: In addition to using Gforth in pipes created by other processes
9271: (@pxref{Gforth in pipes}), you can create your own pipe with
9272: @code{open-pipe}, and read from or write to it.
9273:
9274: doc-open-pipe
9275: doc-close-pipe
9276:
9277: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9278: you don't catch this exception, Gforth will catch it and exit, usually
9279: silently (@pxref{Gforth in pipes}). Since you probably do not want
9280: this, you should wrap a @code{catch} or @code{try} block around the code
9281: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9282: problem yourself, and then return to regular processing.
9283:
9284: doc-broken-pipe-error
9285:
1.155 anton 9286: @node Xchars and Unicode, , Pipes, Other I/O
9287: @subsection Xchars and Unicode
1.149 pazsan 9288:
1.188 pazsan 9289: ASCII is only appropriate for the English language. Most western
9290: languages however fit somewhat into the Forth frame, since a byte is
9291: sufficient to encode the few special characters in each (though not
9292: always the same encoding can be used; latin-1 is most widely used,
9293: though). For other languages, different char-sets have to be used,
9294: several of them variable-width. Most prominent representant is
9295: UTF-8. Let's call these extended characters xchars. The primitive
9296: fixed-size characters stored as bytes are called pchars in this
9297: section.
9298:
9299: The xchar words add a few data types:
9300:
9301: @itemize
9302:
9303: @item
9304: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9305: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9306: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9307: character set can be used.
9308:
9309: @item
9310: @var{xc-addr} is the address of an xchar in memory. Alignment
9311: requirements are the same as @var{c-addr}. The memory representation of an
9312: xchar differs from the stack representation, and depends on the
9313: encoding used. An xchar may use a variable number of pchars in memory.
9314:
9315: @item
9316: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9317: @var{xc-addr}, @var{u} pchars long.
9318:
9319: @end itemize
9320:
9321: doc-xc-size
9322: doc-x-size
9323: doc-xc@+
9324: doc-xc!+
9325: doc-xc!+?
9326: doc-xchar+
9327: doc-xchar-
9328: doc-+x/string
9329: doc-x\string-
9330: doc--trailing-garbage
9331: doc-x-width
9332: doc-xkey
9333: doc-xemit
9334:
9335: There's a new environment query
9336:
9337: doc-xchar-encoding
1.112 anton 9338:
1.121 anton 9339: @node OS command line arguments, Locals, Other I/O, Words
9340: @section OS command line arguments
9341: @cindex OS command line arguments
9342: @cindex command line arguments, OS
9343: @cindex arguments, OS command line
9344:
9345: The usual way to pass arguments to Gforth programs on the command line
9346: is via the @option{-e} option, e.g.
9347:
9348: @example
9349: gforth -e "123 456" foo.fs -e bye
9350: @end example
9351:
9352: However, you may want to interpret the command-line arguments directly.
9353: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9354: through @code{next-arg}:
1.121 anton 9355:
1.123 anton 9356: doc-next-arg
1.121 anton 9357:
1.123 anton 9358: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9359:
9360: @example
9361: : echo ( -- )
1.122 anton 9362: begin
1.123 anton 9363: next-arg 2dup 0 0 d<> while
9364: type space
9365: repeat
9366: 2drop ;
1.121 anton 9367:
9368: echo cr bye
9369: @end example
9370:
9371: This can be invoked with
9372:
9373: @example
9374: gforth echo.fs hello world
9375: @end example
1.123 anton 9376:
9377: and it will print
9378:
9379: @example
9380: hello world
9381: @end example
9382:
9383: The next lower level of dealing with the OS command line are the
9384: following words:
9385:
9386: doc-arg
9387: doc-shift-args
9388:
9389: Finally, at the lowest level Gforth provides the following words:
9390:
9391: doc-argc
9392: doc-argv
1.121 anton 9393:
1.78 anton 9394: @c -------------------------------------------------------------
1.126 pazsan 9395: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9396: @section Locals
9397: @cindex locals
9398:
9399: Local variables can make Forth programming more enjoyable and Forth
9400: programs easier to read. Unfortunately, the locals of ANS Forth are
9401: laden with restrictions. Therefore, we provide not only the ANS Forth
9402: locals wordset, but also our own, more powerful locals wordset (we
9403: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9404:
1.78 anton 9405: The ideas in this section have also been published in M. Anton Ertl,
9406: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9407: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9408:
9409: @menu
1.78 anton 9410: * Gforth locals::
9411: * ANS Forth locals::
1.5 anton 9412: @end menu
9413:
1.78 anton 9414: @node Gforth locals, ANS Forth locals, Locals, Locals
9415: @subsection Gforth locals
9416: @cindex Gforth locals
9417: @cindex locals, Gforth style
1.5 anton 9418:
1.78 anton 9419: Locals can be defined with
1.44 crook 9420:
1.78 anton 9421: @example
9422: @{ local1 local2 ... -- comment @}
9423: @end example
9424: or
9425: @example
9426: @{ local1 local2 ... @}
9427: @end example
1.5 anton 9428:
1.78 anton 9429: E.g.,
9430: @example
9431: : max @{ n1 n2 -- n3 @}
9432: n1 n2 > if
9433: n1
9434: else
9435: n2
9436: endif ;
9437: @end example
1.44 crook 9438:
1.78 anton 9439: The similarity of locals definitions with stack comments is intended. A
9440: locals definition often replaces the stack comment of a word. The order
9441: of the locals corresponds to the order in a stack comment and everything
9442: after the @code{--} is really a comment.
1.77 anton 9443:
1.78 anton 9444: This similarity has one disadvantage: It is too easy to confuse locals
9445: declarations with stack comments, causing bugs and making them hard to
9446: find. However, this problem can be avoided by appropriate coding
9447: conventions: Do not use both notations in the same program. If you do,
9448: they should be distinguished using additional means, e.g. by position.
1.77 anton 9449:
1.78 anton 9450: @cindex types of locals
9451: @cindex locals types
9452: The name of the local may be preceded by a type specifier, e.g.,
9453: @code{F:} for a floating point value:
1.5 anton 9454:
1.78 anton 9455: @example
9456: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9457: \ complex multiplication
9458: Ar Br f* Ai Bi f* f-
9459: Ar Bi f* Ai Br f* f+ ;
9460: @end example
1.44 crook 9461:
1.78 anton 9462: @cindex flavours of locals
9463: @cindex locals flavours
9464: @cindex value-flavoured locals
9465: @cindex variable-flavoured locals
9466: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9467: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9468: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9469: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9470: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9471: produces its address (which becomes invalid when the variable's scope is
9472: left). E.g., the standard word @code{emit} can be defined in terms of
9473: @code{type} like this:
1.5 anton 9474:
1.78 anton 9475: @example
9476: : emit @{ C^ char* -- @}
9477: char* 1 type ;
9478: @end example
1.5 anton 9479:
1.78 anton 9480: @cindex default type of locals
9481: @cindex locals, default type
9482: A local without type specifier is a @code{W:} local. Both flavours of
9483: locals are initialized with values from the data or FP stack.
1.44 crook 9484:
1.78 anton 9485: Currently there is no way to define locals with user-defined data
9486: structures, but we are working on it.
1.5 anton 9487:
1.78 anton 9488: Gforth allows defining locals everywhere in a colon definition. This
9489: poses the following questions:
1.5 anton 9490:
1.78 anton 9491: @menu
9492: * Where are locals visible by name?::
9493: * How long do locals live?::
9494: * Locals programming style::
9495: * Locals implementation::
9496: @end menu
1.44 crook 9497:
1.78 anton 9498: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9499: @subsubsection Where are locals visible by name?
9500: @cindex locals visibility
9501: @cindex visibility of locals
9502: @cindex scope of locals
1.5 anton 9503:
1.78 anton 9504: Basically, the answer is that locals are visible where you would expect
9505: it in block-structured languages, and sometimes a little longer. If you
9506: want to restrict the scope of a local, enclose its definition in
9507: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9508:
9509:
1.78 anton 9510: doc-scope
9511: doc-endscope
1.5 anton 9512:
9513:
1.78 anton 9514: These words behave like control structure words, so you can use them
9515: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9516: arbitrary ways.
1.77 anton 9517:
1.78 anton 9518: If you want a more exact answer to the visibility question, here's the
9519: basic principle: A local is visible in all places that can only be
9520: reached through the definition of the local@footnote{In compiler
9521: construction terminology, all places dominated by the definition of the
9522: local.}. In other words, it is not visible in places that can be reached
9523: without going through the definition of the local. E.g., locals defined
9524: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9525: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9526: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9527:
1.78 anton 9528: The reasoning behind this solution is: We want to have the locals
9529: visible as long as it is meaningful. The user can always make the
9530: visibility shorter by using explicit scoping. In a place that can
9531: only be reached through the definition of a local, the meaning of a
9532: local name is clear. In other places it is not: How is the local
9533: initialized at the control flow path that does not contain the
9534: definition? Which local is meant, if the same name is defined twice in
9535: two independent control flow paths?
1.77 anton 9536:
1.78 anton 9537: This should be enough detail for nearly all users, so you can skip the
9538: rest of this section. If you really must know all the gory details and
9539: options, read on.
1.77 anton 9540:
1.78 anton 9541: In order to implement this rule, the compiler has to know which places
9542: are unreachable. It knows this automatically after @code{AHEAD},
9543: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9544: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9545: compiler that the control flow never reaches that place. If
9546: @code{UNREACHABLE} is not used where it could, the only consequence is
9547: that the visibility of some locals is more limited than the rule above
9548: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9549: lie to the compiler), buggy code will be produced.
1.77 anton 9550:
1.5 anton 9551:
1.78 anton 9552: doc-unreachable
1.5 anton 9553:
1.23 crook 9554:
1.78 anton 9555: Another problem with this rule is that at @code{BEGIN}, the compiler
9556: does not know which locals will be visible on the incoming
9557: back-edge. All problems discussed in the following are due to this
9558: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9559: loops as examples; the discussion also applies to @code{?DO} and other
9560: loops). Perhaps the most insidious example is:
1.26 crook 9561: @example
1.78 anton 9562: AHEAD
9563: BEGIN
9564: x
9565: [ 1 CS-ROLL ] THEN
9566: @{ x @}
9567: ...
9568: UNTIL
1.26 crook 9569: @end example
1.23 crook 9570:
1.78 anton 9571: This should be legal according to the visibility rule. The use of
9572: @code{x} can only be reached through the definition; but that appears
9573: textually below the use.
9574:
9575: From this example it is clear that the visibility rules cannot be fully
9576: implemented without major headaches. Our implementation treats common
9577: cases as advertised and the exceptions are treated in a safe way: The
9578: compiler makes a reasonable guess about the locals visible after a
9579: @code{BEGIN}; if it is too pessimistic, the
9580: user will get a spurious error about the local not being defined; if the
9581: compiler is too optimistic, it will notice this later and issue a
9582: warning. In the case above the compiler would complain about @code{x}
9583: being undefined at its use. You can see from the obscure examples in
9584: this section that it takes quite unusual control structures to get the
9585: compiler into trouble, and even then it will often do fine.
1.23 crook 9586:
1.78 anton 9587: If the @code{BEGIN} is reachable from above, the most optimistic guess
9588: is that all locals visible before the @code{BEGIN} will also be
9589: visible after the @code{BEGIN}. This guess is valid for all loops that
9590: are entered only through the @code{BEGIN}, in particular, for normal
9591: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9592: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9593: compiler. When the branch to the @code{BEGIN} is finally generated by
9594: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9595: warns the user if it was too optimistic:
1.26 crook 9596: @example
1.78 anton 9597: IF
9598: @{ x @}
9599: BEGIN
9600: \ x ?
9601: [ 1 cs-roll ] THEN
9602: ...
9603: UNTIL
1.26 crook 9604: @end example
1.23 crook 9605:
1.78 anton 9606: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9607: optimistically assumes that it lives until the @code{THEN}. It notices
9608: this difference when it compiles the @code{UNTIL} and issues a
9609: warning. The user can avoid the warning, and make sure that @code{x}
9610: is not used in the wrong area by using explicit scoping:
9611: @example
9612: IF
9613: SCOPE
9614: @{ x @}
9615: ENDSCOPE
9616: BEGIN
9617: [ 1 cs-roll ] THEN
9618: ...
9619: UNTIL
9620: @end example
1.23 crook 9621:
1.78 anton 9622: Since the guess is optimistic, there will be no spurious error messages
9623: about undefined locals.
1.44 crook 9624:
1.78 anton 9625: If the @code{BEGIN} is not reachable from above (e.g., after
9626: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9627: optimistic guess, as the locals visible after the @code{BEGIN} may be
9628: defined later. Therefore, the compiler assumes that no locals are
9629: visible after the @code{BEGIN}. However, the user can use
9630: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9631: visible at the BEGIN as at the point where the top control-flow stack
9632: item was created.
1.23 crook 9633:
1.44 crook 9634:
1.78 anton 9635: doc-assume-live
1.26 crook 9636:
1.23 crook 9637:
1.78 anton 9638: @noindent
9639: E.g.,
9640: @example
9641: @{ x @}
9642: AHEAD
9643: ASSUME-LIVE
9644: BEGIN
9645: x
9646: [ 1 CS-ROLL ] THEN
9647: ...
9648: UNTIL
9649: @end example
1.44 crook 9650:
1.78 anton 9651: Other cases where the locals are defined before the @code{BEGIN} can be
9652: handled by inserting an appropriate @code{CS-ROLL} before the
9653: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9654: behind the @code{ASSUME-LIVE}).
1.23 crook 9655:
1.78 anton 9656: Cases where locals are defined after the @code{BEGIN} (but should be
9657: visible immediately after the @code{BEGIN}) can only be handled by
9658: rearranging the loop. E.g., the ``most insidious'' example above can be
9659: arranged into:
9660: @example
9661: BEGIN
9662: @{ x @}
9663: ... 0=
9664: WHILE
9665: x
9666: REPEAT
9667: @end example
1.44 crook 9668:
1.78 anton 9669: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9670: @subsubsection How long do locals live?
9671: @cindex locals lifetime
9672: @cindex lifetime of locals
1.23 crook 9673:
1.78 anton 9674: The right answer for the lifetime question would be: A local lives at
9675: least as long as it can be accessed. For a value-flavoured local this
9676: means: until the end of its visibility. However, a variable-flavoured
9677: local could be accessed through its address far beyond its visibility
9678: scope. Ultimately, this would mean that such locals would have to be
9679: garbage collected. Since this entails un-Forth-like implementation
9680: complexities, I adopted the same cowardly solution as some other
9681: languages (e.g., C): The local lives only as long as it is visible;
9682: afterwards its address is invalid (and programs that access it
9683: afterwards are erroneous).
1.23 crook 9684:
1.78 anton 9685: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9686: @subsubsection Locals programming style
9687: @cindex locals programming style
9688: @cindex programming style, locals
1.23 crook 9689:
1.78 anton 9690: The freedom to define locals anywhere has the potential to change
9691: programming styles dramatically. In particular, the need to use the
9692: return stack for intermediate storage vanishes. Moreover, all stack
9693: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9694: determined arguments) can be eliminated: If the stack items are in the
9695: wrong order, just write a locals definition for all of them; then
9696: write the items in the order you want.
1.23 crook 9697:
1.78 anton 9698: This seems a little far-fetched and eliminating stack manipulations is
9699: unlikely to become a conscious programming objective. Still, the number
9700: of stack manipulations will be reduced dramatically if local variables
9701: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9702: a traditional implementation of @code{max}).
1.23 crook 9703:
1.78 anton 9704: This shows one potential benefit of locals: making Forth programs more
9705: readable. Of course, this benefit will only be realized if the
9706: programmers continue to honour the principle of factoring instead of
9707: using the added latitude to make the words longer.
1.23 crook 9708:
1.78 anton 9709: @cindex single-assignment style for locals
9710: Using @code{TO} can and should be avoided. Without @code{TO},
9711: every value-flavoured local has only a single assignment and many
9712: advantages of functional languages apply to Forth. I.e., programs are
9713: easier to analyse, to optimize and to read: It is clear from the
9714: definition what the local stands for, it does not turn into something
9715: different later.
1.23 crook 9716:
1.78 anton 9717: E.g., a definition using @code{TO} might look like this:
9718: @example
9719: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9720: u1 u2 min 0
9721: ?do
9722: addr1 c@@ addr2 c@@ -
9723: ?dup-if
9724: unloop exit
9725: then
9726: addr1 char+ TO addr1
9727: addr2 char+ TO addr2
9728: loop
9729: u1 u2 - ;
1.26 crook 9730: @end example
1.78 anton 9731: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9732: every loop iteration. @code{strcmp} is a typical example of the
9733: readability problems of using @code{TO}. When you start reading
9734: @code{strcmp}, you think that @code{addr1} refers to the start of the
9735: string. Only near the end of the loop you realize that it is something
9736: else.
1.23 crook 9737:
1.78 anton 9738: This can be avoided by defining two locals at the start of the loop that
9739: are initialized with the right value for the current iteration.
9740: @example
9741: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9742: addr1 addr2
9743: u1 u2 min 0
9744: ?do @{ s1 s2 @}
9745: s1 c@@ s2 c@@ -
9746: ?dup-if
9747: unloop exit
9748: then
9749: s1 char+ s2 char+
9750: loop
9751: 2drop
9752: u1 u2 - ;
9753: @end example
9754: Here it is clear from the start that @code{s1} has a different value
9755: in every loop iteration.
1.23 crook 9756:
1.78 anton 9757: @node Locals implementation, , Locals programming style, Gforth locals
9758: @subsubsection Locals implementation
9759: @cindex locals implementation
9760: @cindex implementation of locals
1.23 crook 9761:
1.78 anton 9762: @cindex locals stack
9763: Gforth uses an extra locals stack. The most compelling reason for
9764: this is that the return stack is not float-aligned; using an extra stack
9765: also eliminates the problems and restrictions of using the return stack
9766: as locals stack. Like the other stacks, the locals stack grows toward
9767: lower addresses. A few primitives allow an efficient implementation:
9768:
9769:
9770: doc-@local#
9771: doc-f@local#
9772: doc-laddr#
9773: doc-lp+!#
9774: doc-lp!
9775: doc->l
9776: doc-f>l
9777:
9778:
9779: In addition to these primitives, some specializations of these
9780: primitives for commonly occurring inline arguments are provided for
9781: efficiency reasons, e.g., @code{@@local0} as specialization of
9782: @code{@@local#} for the inline argument 0. The following compiling words
9783: compile the right specialized version, or the general version, as
9784: appropriate:
1.23 crook 9785:
1.5 anton 9786:
1.107 dvdkhlng 9787: @c doc-compile-@local
9788: @c doc-compile-f@local
1.78 anton 9789: doc-compile-lp+!
1.5 anton 9790:
9791:
1.78 anton 9792: Combinations of conditional branches and @code{lp+!#} like
9793: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9794: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9795:
1.78 anton 9796: A special area in the dictionary space is reserved for keeping the
9797: local variable names. @code{@{} switches the dictionary pointer to this
9798: area and @code{@}} switches it back and generates the locals
9799: initializing code. @code{W:} etc.@ are normal defining words. This
9800: special area is cleared at the start of every colon definition.
1.5 anton 9801:
1.78 anton 9802: @cindex word list for defining locals
9803: A special feature of Gforth's dictionary is used to implement the
9804: definition of locals without type specifiers: every word list (aka
9805: vocabulary) has its own methods for searching
9806: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9807: with a special search method: When it is searched for a word, it
9808: actually creates that word using @code{W:}. @code{@{} changes the search
9809: order to first search the word list containing @code{@}}, @code{W:} etc.,
9810: and then the word list for defining locals without type specifiers.
1.5 anton 9811:
1.78 anton 9812: The lifetime rules support a stack discipline within a colon
9813: definition: The lifetime of a local is either nested with other locals
9814: lifetimes or it does not overlap them.
1.23 crook 9815:
1.78 anton 9816: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9817: pointer manipulation is generated. Between control structure words
9818: locals definitions can push locals onto the locals stack. @code{AGAIN}
9819: is the simplest of the other three control flow words. It has to
9820: restore the locals stack depth of the corresponding @code{BEGIN}
9821: before branching. The code looks like this:
9822: @format
9823: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9824: @code{branch} <begin>
9825: @end format
1.26 crook 9826:
1.78 anton 9827: @code{UNTIL} is a little more complicated: If it branches back, it
9828: must adjust the stack just like @code{AGAIN}. But if it falls through,
9829: the locals stack must not be changed. The compiler generates the
9830: following code:
9831: @format
9832: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9833: @end format
9834: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9835:
1.78 anton 9836: @code{THEN} can produce somewhat inefficient code:
9837: @format
9838: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9839: <orig target>:
9840: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9841: @end format
9842: The second @code{lp+!#} adjusts the locals stack pointer from the
9843: level at the @i{orig} point to the level after the @code{THEN}. The
9844: first @code{lp+!#} adjusts the locals stack pointer from the current
9845: level to the level at the orig point, so the complete effect is an
9846: adjustment from the current level to the right level after the
9847: @code{THEN}.
1.26 crook 9848:
1.78 anton 9849: @cindex locals information on the control-flow stack
9850: @cindex control-flow stack items, locals information
9851: In a conventional Forth implementation a dest control-flow stack entry
9852: is just the target address and an orig entry is just the address to be
9853: patched. Our locals implementation adds a word list to every orig or dest
9854: item. It is the list of locals visible (or assumed visible) at the point
9855: described by the entry. Our implementation also adds a tag to identify
9856: the kind of entry, in particular to differentiate between live and dead
9857: (reachable and unreachable) orig entries.
1.26 crook 9858:
1.78 anton 9859: A few unusual operations have to be performed on locals word lists:
1.44 crook 9860:
1.5 anton 9861:
1.78 anton 9862: doc-common-list
9863: doc-sub-list?
9864: doc-list-size
1.52 anton 9865:
9866:
1.78 anton 9867: Several features of our locals word list implementation make these
9868: operations easy to implement: The locals word lists are organised as
9869: linked lists; the tails of these lists are shared, if the lists
9870: contain some of the same locals; and the address of a name is greater
9871: than the address of the names behind it in the list.
1.5 anton 9872:
1.78 anton 9873: Another important implementation detail is the variable
9874: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9875: determine if they can be reached directly or only through the branch
9876: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9877: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9878: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9879:
1.78 anton 9880: Counted loops are similar to other loops in most respects, but
9881: @code{LEAVE} requires special attention: It performs basically the same
9882: service as @code{AHEAD}, but it does not create a control-flow stack
9883: entry. Therefore the information has to be stored elsewhere;
9884: traditionally, the information was stored in the target fields of the
9885: branches created by the @code{LEAVE}s, by organizing these fields into a
9886: linked list. Unfortunately, this clever trick does not provide enough
9887: space for storing our extended control flow information. Therefore, we
9888: introduce another stack, the leave stack. It contains the control-flow
9889: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9890:
1.78 anton 9891: Local names are kept until the end of the colon definition, even if
9892: they are no longer visible in any control-flow path. In a few cases
9893: this may lead to increased space needs for the locals name area, but
9894: usually less than reclaiming this space would cost in code size.
1.5 anton 9895:
1.44 crook 9896:
1.78 anton 9897: @node ANS Forth locals, , Gforth locals, Locals
9898: @subsection ANS Forth locals
9899: @cindex locals, ANS Forth style
1.5 anton 9900:
1.78 anton 9901: The ANS Forth locals wordset does not define a syntax for locals, but
9902: words that make it possible to define various syntaxes. One of the
9903: possible syntaxes is a subset of the syntax we used in the Gforth locals
9904: wordset, i.e.:
1.29 crook 9905:
9906: @example
1.78 anton 9907: @{ local1 local2 ... -- comment @}
9908: @end example
9909: @noindent
9910: or
9911: @example
9912: @{ local1 local2 ... @}
1.29 crook 9913: @end example
9914:
1.78 anton 9915: The order of the locals corresponds to the order in a stack comment. The
9916: restrictions are:
1.5 anton 9917:
1.78 anton 9918: @itemize @bullet
9919: @item
9920: Locals can only be cell-sized values (no type specifiers are allowed).
9921: @item
9922: Locals can be defined only outside control structures.
9923: @item
9924: Locals can interfere with explicit usage of the return stack. For the
9925: exact (and long) rules, see the standard. If you don't use return stack
9926: accessing words in a definition using locals, you will be all right. The
9927: purpose of this rule is to make locals implementation on the return
9928: stack easier.
9929: @item
9930: The whole definition must be in one line.
9931: @end itemize
1.5 anton 9932:
1.78 anton 9933: Locals defined in ANS Forth behave like @code{VALUE}s
9934: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9935: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9936:
1.78 anton 9937: Since the syntax above is supported by Gforth directly, you need not do
9938: anything to use it. If you want to port a program using this syntax to
9939: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9940: syntax on the other system.
1.5 anton 9941:
1.78 anton 9942: Note that a syntax shown in the standard, section A.13 looks
9943: similar, but is quite different in having the order of locals
9944: reversed. Beware!
1.5 anton 9945:
1.78 anton 9946: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9947:
1.78 anton 9948: doc-(local)
1.5 anton 9949:
1.78 anton 9950: The ANS Forth locals extension wordset defines a syntax using
9951: @code{locals|}, but it is so awful that we strongly recommend not to use
9952: it. We have implemented this syntax to make porting to Gforth easy, but
9953: do not document it here. The problem with this syntax is that the locals
9954: are defined in an order reversed with respect to the standard stack
9955: comment notation, making programs harder to read, and easier to misread
9956: and miswrite. The only merit of this syntax is that it is easy to
9957: implement using the ANS Forth locals wordset.
1.53 anton 9958:
9959:
1.78 anton 9960: @c ----------------------------------------------------------
9961: @node Structures, Object-oriented Forth, Locals, Words
9962: @section Structures
9963: @cindex structures
9964: @cindex records
1.53 anton 9965:
1.78 anton 9966: This section presents the structure package that comes with Gforth. A
9967: version of the package implemented in ANS Forth is available in
9968: @file{compat/struct.fs}. This package was inspired by a posting on
9969: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9970: possibly John Hayes). A version of this section has been published in
9971: M. Anton Ertl,
9972: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9973: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9974: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9975:
1.78 anton 9976: @menu
9977: * Why explicit structure support?::
9978: * Structure Usage::
9979: * Structure Naming Convention::
9980: * Structure Implementation::
9981: * Structure Glossary::
1.183 anton 9982: * Forth200x Structures::
1.78 anton 9983: @end menu
1.55 anton 9984:
1.78 anton 9985: @node Why explicit structure support?, Structure Usage, Structures, Structures
9986: @subsection Why explicit structure support?
1.53 anton 9987:
1.78 anton 9988: @cindex address arithmetic for structures
9989: @cindex structures using address arithmetic
9990: If we want to use a structure containing several fields, we could simply
9991: reserve memory for it, and access the fields using address arithmetic
9992: (@pxref{Address arithmetic}). As an example, consider a structure with
9993: the following fields
1.57 anton 9994:
1.78 anton 9995: @table @code
9996: @item a
9997: is a float
9998: @item b
9999: is a cell
10000: @item c
10001: is a float
10002: @end table
1.57 anton 10003:
1.78 anton 10004: Given the (float-aligned) base address of the structure we get the
10005: address of the field
1.52 anton 10006:
1.78 anton 10007: @table @code
10008: @item a
10009: without doing anything further.
10010: @item b
10011: with @code{float+}
10012: @item c
10013: with @code{float+ cell+ faligned}
10014: @end table
1.52 anton 10015:
1.78 anton 10016: It is easy to see that this can become quite tiring.
1.52 anton 10017:
1.78 anton 10018: Moreover, it is not very readable, because seeing a
10019: @code{cell+} tells us neither which kind of structure is
10020: accessed nor what field is accessed; we have to somehow infer the kind
10021: of structure, and then look up in the documentation, which field of
10022: that structure corresponds to that offset.
1.53 anton 10023:
1.78 anton 10024: Finally, this kind of address arithmetic also causes maintenance
10025: troubles: If you add or delete a field somewhere in the middle of the
10026: structure, you have to find and change all computations for the fields
10027: afterwards.
1.52 anton 10028:
1.78 anton 10029: So, instead of using @code{cell+} and friends directly, how
10030: about storing the offsets in constants:
1.52 anton 10031:
1.78 anton 10032: @example
10033: 0 constant a-offset
10034: 0 float+ constant b-offset
10035: 0 float+ cell+ faligned c-offset
10036: @end example
1.64 pazsan 10037:
1.78 anton 10038: Now we can get the address of field @code{x} with @code{x-offset
10039: +}. This is much better in all respects. Of course, you still
10040: have to change all later offset definitions if you add a field. You can
10041: fix this by declaring the offsets in the following way:
1.57 anton 10042:
1.78 anton 10043: @example
10044: 0 constant a-offset
10045: a-offset float+ constant b-offset
10046: b-offset cell+ faligned constant c-offset
10047: @end example
1.57 anton 10048:
1.78 anton 10049: Since we always use the offsets with @code{+}, we could use a defining
10050: word @code{cfield} that includes the @code{+} in the action of the
10051: defined word:
1.64 pazsan 10052:
1.78 anton 10053: @example
10054: : cfield ( n "name" -- )
10055: create ,
10056: does> ( name execution: addr1 -- addr2 )
10057: @@ + ;
1.64 pazsan 10058:
1.78 anton 10059: 0 cfield a
10060: 0 a float+ cfield b
10061: 0 b cell+ faligned cfield c
10062: @end example
1.64 pazsan 10063:
1.78 anton 10064: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10065:
1.78 anton 10066: The structure field words now can be used quite nicely. However,
10067: their definition is still a bit cumbersome: We have to repeat the
10068: name, the information about size and alignment is distributed before
10069: and after the field definitions etc. The structure package presented
10070: here addresses these problems.
1.64 pazsan 10071:
1.78 anton 10072: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10073: @subsection Structure Usage
10074: @cindex structure usage
1.57 anton 10075:
1.78 anton 10076: @cindex @code{field} usage
10077: @cindex @code{struct} usage
10078: @cindex @code{end-struct} usage
10079: You can define a structure for a (data-less) linked list with:
1.57 anton 10080: @example
1.78 anton 10081: struct
10082: cell% field list-next
10083: end-struct list%
1.57 anton 10084: @end example
10085:
1.78 anton 10086: With the address of the list node on the stack, you can compute the
10087: address of the field that contains the address of the next node with
10088: @code{list-next}. E.g., you can determine the length of a list
10089: with:
1.57 anton 10090:
10091: @example
1.78 anton 10092: : list-length ( list -- n )
10093: \ "list" is a pointer to the first element of a linked list
10094: \ "n" is the length of the list
10095: 0 BEGIN ( list1 n1 )
10096: over
10097: WHILE ( list1 n1 )
10098: 1+ swap list-next @@ swap
10099: REPEAT
10100: nip ;
1.57 anton 10101: @end example
10102:
1.78 anton 10103: You can reserve memory for a list node in the dictionary with
10104: @code{list% %allot}, which leaves the address of the list node on the
10105: stack. For the equivalent allocation on the heap you can use @code{list%
10106: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10107: use @code{list% %allocate}). You can get the the size of a list
10108: node with @code{list% %size} and its alignment with @code{list%
10109: %alignment}.
10110:
10111: Note that in ANS Forth the body of a @code{create}d word is
10112: @code{aligned} but not necessarily @code{faligned};
10113: therefore, if you do a:
1.57 anton 10114:
10115: @example
1.78 anton 10116: create @emph{name} foo% %allot drop
1.57 anton 10117: @end example
10118:
1.78 anton 10119: @noindent
10120: then the memory alloted for @code{foo%} is guaranteed to start at the
10121: body of @code{@emph{name}} only if @code{foo%} contains only character,
10122: cell and double fields. Therefore, if your structure contains floats,
10123: better use
1.57 anton 10124:
10125: @example
1.78 anton 10126: foo% %allot constant @emph{name}
1.57 anton 10127: @end example
10128:
1.78 anton 10129: @cindex structures containing structures
10130: You can include a structure @code{foo%} as a field of
10131: another structure, like this:
1.65 anton 10132: @example
1.78 anton 10133: struct
10134: ...
10135: foo% field ...
10136: ...
10137: end-struct ...
1.65 anton 10138: @end example
1.52 anton 10139:
1.78 anton 10140: @cindex structure extension
10141: @cindex extended records
10142: Instead of starting with an empty structure, you can extend an
10143: existing structure. E.g., a plain linked list without data, as defined
10144: above, is hardly useful; You can extend it to a linked list of integers,
10145: like this:@footnote{This feature is also known as @emph{extended
10146: records}. It is the main innovation in the Oberon language; in other
10147: words, adding this feature to Modula-2 led Wirth to create a new
10148: language, write a new compiler etc. Adding this feature to Forth just
10149: required a few lines of code.}
1.52 anton 10150:
1.78 anton 10151: @example
10152: list%
10153: cell% field intlist-int
10154: end-struct intlist%
10155: @end example
1.55 anton 10156:
1.78 anton 10157: @code{intlist%} is a structure with two fields:
10158: @code{list-next} and @code{intlist-int}.
1.55 anton 10159:
1.78 anton 10160: @cindex structures containing arrays
10161: You can specify an array type containing @emph{n} elements of
10162: type @code{foo%} like this:
1.55 anton 10163:
10164: @example
1.78 anton 10165: foo% @emph{n} *
1.56 anton 10166: @end example
1.55 anton 10167:
1.78 anton 10168: You can use this array type in any place where you can use a normal
10169: type, e.g., when defining a @code{field}, or with
10170: @code{%allot}.
10171:
10172: @cindex first field optimization
10173: The first field is at the base address of a structure and the word for
10174: this field (e.g., @code{list-next}) actually does not change the address
10175: on the stack. You may be tempted to leave it away in the interest of
10176: run-time and space efficiency. This is not necessary, because the
10177: structure package optimizes this case: If you compile a first-field
10178: words, no code is generated. So, in the interest of readability and
10179: maintainability you should include the word for the field when accessing
10180: the field.
1.52 anton 10181:
10182:
1.78 anton 10183: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10184: @subsection Structure Naming Convention
10185: @cindex structure naming convention
1.52 anton 10186:
1.78 anton 10187: The field names that come to (my) mind are often quite generic, and,
10188: if used, would cause frequent name clashes. E.g., many structures
10189: probably contain a @code{counter} field. The structure names
10190: that come to (my) mind are often also the logical choice for the names
10191: of words that create such a structure.
1.52 anton 10192:
1.78 anton 10193: Therefore, I have adopted the following naming conventions:
1.52 anton 10194:
1.78 anton 10195: @itemize @bullet
10196: @cindex field naming convention
10197: @item
10198: The names of fields are of the form
10199: @code{@emph{struct}-@emph{field}}, where
10200: @code{@emph{struct}} is the basic name of the structure, and
10201: @code{@emph{field}} is the basic name of the field. You can
10202: think of field words as converting the (address of the)
10203: structure into the (address of the) field.
1.52 anton 10204:
1.78 anton 10205: @cindex structure naming convention
10206: @item
10207: The names of structures are of the form
10208: @code{@emph{struct}%}, where
10209: @code{@emph{struct}} is the basic name of the structure.
10210: @end itemize
1.52 anton 10211:
1.78 anton 10212: This naming convention does not work that well for fields of extended
10213: structures; e.g., the integer list structure has a field
10214: @code{intlist-int}, but has @code{list-next}, not
10215: @code{intlist-next}.
1.53 anton 10216:
1.78 anton 10217: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10218: @subsection Structure Implementation
10219: @cindex structure implementation
10220: @cindex implementation of structures
1.52 anton 10221:
1.78 anton 10222: The central idea in the implementation is to pass the data about the
10223: structure being built on the stack, not in some global
10224: variable. Everything else falls into place naturally once this design
10225: decision is made.
1.53 anton 10226:
1.78 anton 10227: The type description on the stack is of the form @emph{align
10228: size}. Keeping the size on the top-of-stack makes dealing with arrays
10229: very simple.
1.53 anton 10230:
1.78 anton 10231: @code{field} is a defining word that uses @code{Create}
10232: and @code{DOES>}. The body of the field contains the offset
10233: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10234:
10235: @example
1.78 anton 10236: @@ +
1.53 anton 10237: @end example
10238:
1.78 anton 10239: @noindent
10240: i.e., add the offset to the address, giving the stack effect
10241: @i{addr1 -- addr2} for a field.
10242:
10243: @cindex first field optimization, implementation
10244: This simple structure is slightly complicated by the optimization
10245: for fields with offset 0, which requires a different
10246: @code{DOES>}-part (because we cannot rely on there being
10247: something on the stack if such a field is invoked during
10248: compilation). Therefore, we put the different @code{DOES>}-parts
10249: in separate words, and decide which one to invoke based on the
10250: offset. For a zero offset, the field is basically a noop; it is
10251: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10252:
1.183 anton 10253: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10254: @subsection Structure Glossary
10255: @cindex structure glossary
1.53 anton 10256:
1.5 anton 10257:
1.78 anton 10258: doc-%align
10259: doc-%alignment
10260: doc-%alloc
10261: doc-%allocate
10262: doc-%allot
10263: doc-cell%
10264: doc-char%
10265: doc-dfloat%
10266: doc-double%
10267: doc-end-struct
10268: doc-field
10269: doc-float%
10270: doc-naligned
10271: doc-sfloat%
10272: doc-%size
10273: doc-struct
1.54 anton 10274:
10275:
1.183 anton 10276: @node Forth200x Structures, , Structure Glossary, Structures
10277: @subsection Forth200x Structures
10278: @cindex Structures in Forth200x
10279:
10280: The Forth 200x standard defines a slightly less convenient form of
10281: structures. In general (when using @code{field+}, you have to perform
10282: the alignment yourself, but there are a number of convenience words
10283: (e.g., @code{field:} that perform the alignment for you.
10284:
10285: A typical usage example is:
10286:
10287: @example
10288: 0
10289: field: s-a
10290: faligned 2 floats +field s-b
10291: constant s-struct
10292: @end example
10293:
10294: An alternative way of writing this structure is:
10295:
10296: @example
10297: begin-structure s-struct
10298: field: s-a
10299: faligned 2 floats +field s-b
10300: end-structure
10301: @end example
10302:
10303: doc-begin-structure
10304: doc-end-structure
10305: doc-+field
10306: doc-cfield:
10307: doc-field:
10308: doc-2field:
10309: doc-ffield:
10310: doc-sffield:
10311: doc-dffield:
10312:
1.26 crook 10313: @c -------------------------------------------------------------
1.78 anton 10314: @node Object-oriented Forth, Programming Tools, Structures, Words
10315: @section Object-oriented Forth
10316:
10317: Gforth comes with three packages for object-oriented programming:
10318: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10319: is preloaded, so you have to @code{include} them before use. The most
10320: important differences between these packages (and others) are discussed
10321: in @ref{Comparison with other object models}. All packages are written
10322: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10323:
1.78 anton 10324: @menu
10325: * Why object-oriented programming?::
10326: * Object-Oriented Terminology::
10327: * Objects::
10328: * OOF::
10329: * Mini-OOF::
10330: * Comparison with other object models::
10331: @end menu
1.5 anton 10332:
1.78 anton 10333: @c ----------------------------------------------------------------
10334: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10335: @subsection Why object-oriented programming?
10336: @cindex object-oriented programming motivation
10337: @cindex motivation for object-oriented programming
1.44 crook 10338:
1.78 anton 10339: Often we have to deal with several data structures (@emph{objects}),
10340: that have to be treated similarly in some respects, but differently in
10341: others. Graphical objects are the textbook example: circles, triangles,
10342: dinosaurs, icons, and others, and we may want to add more during program
10343: development. We want to apply some operations to any graphical object,
10344: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10345: has to do something different for every kind of object.
10346: @comment TODO add some other operations eg perimeter, area
10347: @comment and tie in to concrete examples later..
1.5 anton 10348:
1.78 anton 10349: We could implement @code{draw} as a big @code{CASE}
10350: control structure that executes the appropriate code depending on the
10351: kind of object to be drawn. This would be not be very elegant, and,
10352: moreover, we would have to change @code{draw} every time we add
10353: a new kind of graphical object (say, a spaceship).
1.44 crook 10354:
1.78 anton 10355: What we would rather do is: When defining spaceships, we would tell
10356: the system: ``Here's how you @code{draw} a spaceship; you figure
10357: out the rest''.
1.5 anton 10358:
1.78 anton 10359: This is the problem that all systems solve that (rightfully) call
10360: themselves object-oriented; the object-oriented packages presented here
10361: solve this problem (and not much else).
10362: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10363:
1.78 anton 10364: @c ------------------------------------------------------------------------
10365: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10366: @subsection Object-Oriented Terminology
10367: @cindex object-oriented terminology
10368: @cindex terminology for object-oriented programming
1.5 anton 10369:
1.78 anton 10370: This section is mainly for reference, so you don't have to understand
10371: all of it right away. The terminology is mainly Smalltalk-inspired. In
10372: short:
1.44 crook 10373:
1.78 anton 10374: @table @emph
10375: @cindex class
10376: @item class
10377: a data structure definition with some extras.
1.5 anton 10378:
1.78 anton 10379: @cindex object
10380: @item object
10381: an instance of the data structure described by the class definition.
1.5 anton 10382:
1.78 anton 10383: @cindex instance variables
10384: @item instance variables
10385: fields of the data structure.
1.5 anton 10386:
1.78 anton 10387: @cindex selector
10388: @cindex method selector
10389: @cindex virtual function
10390: @item selector
10391: (or @emph{method selector}) a word (e.g.,
10392: @code{draw}) that performs an operation on a variety of data
10393: structures (classes). A selector describes @emph{what} operation to
10394: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10395:
1.78 anton 10396: @cindex method
10397: @item method
10398: the concrete definition that performs the operation
10399: described by the selector for a specific class. A method specifies
10400: @emph{how} the operation is performed for a specific class.
1.5 anton 10401:
1.78 anton 10402: @cindex selector invocation
10403: @cindex message send
10404: @cindex invoking a selector
10405: @item selector invocation
10406: a call of a selector. One argument of the call (the TOS (top-of-stack))
10407: is used for determining which method is used. In Smalltalk terminology:
10408: a message (consisting of the selector and the other arguments) is sent
10409: to the object.
1.5 anton 10410:
1.78 anton 10411: @cindex receiving object
10412: @item receiving object
10413: the object used for determining the method executed by a selector
10414: invocation. In the @file{objects.fs} model, it is the object that is on
10415: the TOS when the selector is invoked. (@emph{Receiving} comes from
10416: the Smalltalk @emph{message} terminology.)
1.5 anton 10417:
1.78 anton 10418: @cindex child class
10419: @cindex parent class
10420: @cindex inheritance
10421: @item child class
10422: a class that has (@emph{inherits}) all properties (instance variables,
10423: selectors, methods) from a @emph{parent class}. In Smalltalk
10424: terminology: The subclass inherits from the superclass. In C++
10425: terminology: The derived class inherits from the base class.
1.5 anton 10426:
1.78 anton 10427: @end table
1.5 anton 10428:
1.78 anton 10429: @c If you wonder about the message sending terminology, it comes from
10430: @c a time when each object had it's own task and objects communicated via
10431: @c message passing; eventually the Smalltalk developers realized that
10432: @c they can do most things through simple (indirect) calls. They kept the
10433: @c terminology.
1.5 anton 10434:
1.78 anton 10435: @c --------------------------------------------------------------
10436: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10437: @subsection The @file{objects.fs} model
10438: @cindex objects
10439: @cindex object-oriented programming
1.26 crook 10440:
1.78 anton 10441: @cindex @file{objects.fs}
10442: @cindex @file{oof.fs}
1.26 crook 10443:
1.78 anton 10444: This section describes the @file{objects.fs} package. This material also
10445: has been published in M. Anton Ertl,
10446: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10447: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10448: 37--43.
10449: @c McKewan's and Zsoter's packages
1.26 crook 10450:
1.78 anton 10451: This section assumes that you have read @ref{Structures}.
1.5 anton 10452:
1.78 anton 10453: The techniques on which this model is based have been used to implement
10454: the parser generator, Gray, and have also been used in Gforth for
10455: implementing the various flavours of word lists (hashed or not,
10456: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10457:
10458:
1.26 crook 10459: @menu
1.78 anton 10460: * Properties of the Objects model::
10461: * Basic Objects Usage::
10462: * The Objects base class::
10463: * Creating objects::
10464: * Object-Oriented Programming Style::
10465: * Class Binding::
10466: * Method conveniences::
10467: * Classes and Scoping::
10468: * Dividing classes::
10469: * Object Interfaces::
10470: * Objects Implementation::
10471: * Objects Glossary::
1.26 crook 10472: @end menu
1.5 anton 10473:
1.78 anton 10474: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10475:
1.78 anton 10476: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10477: @subsubsection Properties of the @file{objects.fs} model
10478: @cindex @file{objects.fs} properties
1.5 anton 10479:
1.78 anton 10480: @itemize @bullet
10481: @item
10482: It is straightforward to pass objects on the stack. Passing
10483: selectors on the stack is a little less convenient, but possible.
1.44 crook 10484:
1.78 anton 10485: @item
10486: Objects are just data structures in memory, and are referenced by their
10487: address. You can create words for objects with normal defining words
10488: like @code{constant}. Likewise, there is no difference between instance
10489: variables that contain objects and those that contain other data.
1.5 anton 10490:
1.78 anton 10491: @item
10492: Late binding is efficient and easy to use.
1.44 crook 10493:
1.78 anton 10494: @item
10495: It avoids parsing, and thus avoids problems with state-smartness
10496: and reduced extensibility; for convenience there are a few parsing
10497: words, but they have non-parsing counterparts. There are also a few
10498: defining words that parse. This is hard to avoid, because all standard
10499: defining words parse (except @code{:noname}); however, such
10500: words are not as bad as many other parsing words, because they are not
10501: state-smart.
1.5 anton 10502:
1.78 anton 10503: @item
10504: It does not try to incorporate everything. It does a few things and does
10505: them well (IMO). In particular, this model was not designed to support
10506: information hiding (although it has features that may help); you can use
10507: a separate package for achieving this.
1.5 anton 10508:
1.78 anton 10509: @item
10510: It is layered; you don't have to learn and use all features to use this
10511: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10512: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10513: are optional and independent of each other.
1.5 anton 10514:
1.78 anton 10515: @item
10516: An implementation in ANS Forth is available.
1.5 anton 10517:
1.78 anton 10518: @end itemize
1.5 anton 10519:
1.44 crook 10520:
1.78 anton 10521: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10522: @subsubsection Basic @file{objects.fs} Usage
10523: @cindex basic objects usage
10524: @cindex objects, basic usage
1.5 anton 10525:
1.78 anton 10526: You can define a class for graphical objects like this:
1.44 crook 10527:
1.78 anton 10528: @cindex @code{class} usage
10529: @cindex @code{end-class} usage
10530: @cindex @code{selector} usage
1.5 anton 10531: @example
1.78 anton 10532: object class \ "object" is the parent class
10533: selector draw ( x y graphical -- )
10534: end-class graphical
10535: @end example
10536:
10537: This code defines a class @code{graphical} with an
10538: operation @code{draw}. We can perform the operation
10539: @code{draw} on any @code{graphical} object, e.g.:
10540:
10541: @example
10542: 100 100 t-rex draw
1.26 crook 10543: @end example
1.5 anton 10544:
1.78 anton 10545: @noindent
10546: where @code{t-rex} is a word (say, a constant) that produces a
10547: graphical object.
10548:
10549: @comment TODO add a 2nd operation eg perimeter.. and use for
10550: @comment a concrete example
1.5 anton 10551:
1.78 anton 10552: @cindex abstract class
10553: How do we create a graphical object? With the present definitions,
10554: we cannot create a useful graphical object. The class
10555: @code{graphical} describes graphical objects in general, but not
10556: any concrete graphical object type (C++ users would call it an
10557: @emph{abstract class}); e.g., there is no method for the selector
10558: @code{draw} in the class @code{graphical}.
1.5 anton 10559:
1.78 anton 10560: For concrete graphical objects, we define child classes of the
10561: class @code{graphical}, e.g.:
1.5 anton 10562:
1.78 anton 10563: @cindex @code{overrides} usage
10564: @cindex @code{field} usage in class definition
1.26 crook 10565: @example
1.78 anton 10566: graphical class \ "graphical" is the parent class
10567: cell% field circle-radius
1.5 anton 10568:
1.78 anton 10569: :noname ( x y circle -- )
10570: circle-radius @@ draw-circle ;
10571: overrides draw
1.5 anton 10572:
1.78 anton 10573: :noname ( n-radius circle -- )
10574: circle-radius ! ;
10575: overrides construct
1.5 anton 10576:
1.78 anton 10577: end-class circle
10578: @end example
1.44 crook 10579:
1.78 anton 10580: Here we define a class @code{circle} as a child of @code{graphical},
10581: with field @code{circle-radius} (which behaves just like a field
10582: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10583: for the selectors @code{draw} and @code{construct} (@code{construct} is
10584: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10585:
1.78 anton 10586: Now we can create a circle on the heap (i.e.,
10587: @code{allocate}d memory) with:
1.44 crook 10588:
1.78 anton 10589: @cindex @code{heap-new} usage
1.5 anton 10590: @example
1.78 anton 10591: 50 circle heap-new constant my-circle
1.5 anton 10592: @end example
10593:
1.78 anton 10594: @noindent
10595: @code{heap-new} invokes @code{construct}, thus
10596: initializing the field @code{circle-radius} with 50. We can draw
10597: this new circle at (100,100) with:
1.5 anton 10598:
10599: @example
1.78 anton 10600: 100 100 my-circle draw
1.5 anton 10601: @end example
10602:
1.78 anton 10603: @cindex selector invocation, restrictions
10604: @cindex class definition, restrictions
10605: Note: You can only invoke a selector if the object on the TOS
10606: (the receiving object) belongs to the class where the selector was
10607: defined or one of its descendents; e.g., you can invoke
10608: @code{draw} only for objects belonging to @code{graphical}
10609: or its descendents (e.g., @code{circle}). Immediately before
10610: @code{end-class}, the search order has to be the same as
10611: immediately after @code{class}.
10612:
10613: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10614: @subsubsection The @file{object.fs} base class
10615: @cindex @code{object} class
10616:
10617: When you define a class, you have to specify a parent class. So how do
10618: you start defining classes? There is one class available from the start:
10619: @code{object}. It is ancestor for all classes and so is the
10620: only class that has no parent. It has two selectors: @code{construct}
10621: and @code{print}.
10622:
10623: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10624: @subsubsection Creating objects
10625: @cindex creating objects
10626: @cindex object creation
10627: @cindex object allocation options
10628:
10629: @cindex @code{heap-new} discussion
10630: @cindex @code{dict-new} discussion
10631: @cindex @code{construct} discussion
10632: You can create and initialize an object of a class on the heap with
10633: @code{heap-new} ( ... class -- object ) and in the dictionary
10634: (allocation with @code{allot}) with @code{dict-new} (
10635: ... class -- object ). Both words invoke @code{construct}, which
10636: consumes the stack items indicated by "..." above.
10637:
10638: @cindex @code{init-object} discussion
10639: @cindex @code{class-inst-size} discussion
10640: If you want to allocate memory for an object yourself, you can get its
10641: alignment and size with @code{class-inst-size 2@@} ( class --
10642: align size ). Once you have memory for an object, you can initialize
10643: it with @code{init-object} ( ... class object -- );
10644: @code{construct} does only a part of the necessary work.
10645:
10646: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10647: @subsubsection Object-Oriented Programming Style
10648: @cindex object-oriented programming style
10649: @cindex programming style, object-oriented
1.5 anton 10650:
1.78 anton 10651: This section is not exhaustive.
1.5 anton 10652:
1.78 anton 10653: @cindex stack effects of selectors
10654: @cindex selectors and stack effects
10655: In general, it is a good idea to ensure that all methods for the
10656: same selector have the same stack effect: when you invoke a selector,
10657: you often have no idea which method will be invoked, so, unless all
10658: methods have the same stack effect, you will not know the stack effect
10659: of the selector invocation.
1.5 anton 10660:
1.78 anton 10661: One exception to this rule is methods for the selector
10662: @code{construct}. We know which method is invoked, because we
10663: specify the class to be constructed at the same place. Actually, I
10664: defined @code{construct} as a selector only to give the users a
10665: convenient way to specify initialization. The way it is used, a
10666: mechanism different from selector invocation would be more natural
10667: (but probably would take more code and more space to explain).
1.5 anton 10668:
1.78 anton 10669: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10670: @subsubsection Class Binding
10671: @cindex class binding
10672: @cindex early binding
1.5 anton 10673:
1.78 anton 10674: @cindex late binding
10675: Normal selector invocations determine the method at run-time depending
10676: on the class of the receiving object. This run-time selection is called
10677: @i{late binding}.
1.5 anton 10678:
1.78 anton 10679: Sometimes it's preferable to invoke a different method. For example,
10680: you might want to use the simple method for @code{print}ing
10681: @code{object}s instead of the possibly long-winded @code{print} method
10682: of the receiver class. You can achieve this by replacing the invocation
10683: of @code{print} with:
1.5 anton 10684:
1.78 anton 10685: @cindex @code{[bind]} usage
1.5 anton 10686: @example
1.78 anton 10687: [bind] object print
1.5 anton 10688: @end example
10689:
1.78 anton 10690: @noindent
10691: in compiled code or:
10692:
10693: @cindex @code{bind} usage
1.5 anton 10694: @example
1.78 anton 10695: bind object print
1.5 anton 10696: @end example
10697:
1.78 anton 10698: @cindex class binding, alternative to
10699: @noindent
10700: in interpreted code. Alternatively, you can define the method with a
10701: name (e.g., @code{print-object}), and then invoke it through the
10702: name. Class binding is just a (often more convenient) way to achieve
10703: the same effect; it avoids name clutter and allows you to invoke
10704: methods directly without naming them first.
1.5 anton 10705:
1.78 anton 10706: @cindex superclass binding
10707: @cindex parent class binding
10708: A frequent use of class binding is this: When we define a method
10709: for a selector, we often want the method to do what the selector does
10710: in the parent class, and a little more. There is a special word for
10711: this purpose: @code{[parent]}; @code{[parent]
10712: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10713: selector}}, where @code{@emph{parent}} is the parent
10714: class of the current class. E.g., a method definition might look like:
1.44 crook 10715:
1.78 anton 10716: @cindex @code{[parent]} usage
10717: @example
10718: :noname
10719: dup [parent] foo \ do parent's foo on the receiving object
10720: ... \ do some more
10721: ; overrides foo
10722: @end example
1.6 pazsan 10723:
1.78 anton 10724: @cindex class binding as optimization
10725: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10726: March 1997), Andrew McKewan presents class binding as an optimization
10727: technique. I recommend not using it for this purpose unless you are in
10728: an emergency. Late binding is pretty fast with this model anyway, so the
10729: benefit of using class binding is small; the cost of using class binding
10730: where it is not appropriate is reduced maintainability.
1.44 crook 10731:
1.78 anton 10732: While we are at programming style questions: You should bind
10733: selectors only to ancestor classes of the receiving object. E.g., say,
10734: you know that the receiving object is of class @code{foo} or its
10735: descendents; then you should bind only to @code{foo} and its
10736: ancestors.
1.12 anton 10737:
1.78 anton 10738: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10739: @subsubsection Method conveniences
10740: @cindex method conveniences
1.44 crook 10741:
1.78 anton 10742: In a method you usually access the receiving object pretty often. If
10743: you define the method as a plain colon definition (e.g., with
10744: @code{:noname}), you may have to do a lot of stack
10745: gymnastics. To avoid this, you can define the method with @code{m:
10746: ... ;m}. E.g., you could define the method for
10747: @code{draw}ing a @code{circle} with
1.6 pazsan 10748:
1.78 anton 10749: @cindex @code{this} usage
10750: @cindex @code{m:} usage
10751: @cindex @code{;m} usage
10752: @example
10753: m: ( x y circle -- )
10754: ( x y ) this circle-radius @@ draw-circle ;m
10755: @end example
1.6 pazsan 10756:
1.78 anton 10757: @cindex @code{exit} in @code{m: ... ;m}
10758: @cindex @code{exitm} discussion
10759: @cindex @code{catch} in @code{m: ... ;m}
10760: When this method is executed, the receiver object is removed from the
10761: stack; you can access it with @code{this} (admittedly, in this
10762: example the use of @code{m: ... ;m} offers no advantage). Note
10763: that I specify the stack effect for the whole method (i.e. including
10764: the receiver object), not just for the code between @code{m:}
10765: and @code{;m}. You cannot use @code{exit} in
10766: @code{m:...;m}; instead, use
10767: @code{exitm}.@footnote{Moreover, for any word that calls
10768: @code{catch} and was defined before loading
10769: @code{objects.fs}, you have to redefine it like I redefined
10770: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10771:
1.78 anton 10772: @cindex @code{inst-var} usage
10773: You will frequently use sequences of the form @code{this
10774: @emph{field}} (in the example above: @code{this
10775: circle-radius}). If you use the field only in this way, you can
10776: define it with @code{inst-var} and eliminate the
10777: @code{this} before the field name. E.g., the @code{circle}
10778: class above could also be defined with:
1.6 pazsan 10779:
1.78 anton 10780: @example
10781: graphical class
10782: cell% inst-var radius
1.6 pazsan 10783:
1.78 anton 10784: m: ( x y circle -- )
10785: radius @@ draw-circle ;m
10786: overrides draw
1.6 pazsan 10787:
1.78 anton 10788: m: ( n-radius circle -- )
10789: radius ! ;m
10790: overrides construct
1.6 pazsan 10791:
1.78 anton 10792: end-class circle
10793: @end example
1.6 pazsan 10794:
1.78 anton 10795: @code{radius} can only be used in @code{circle} and its
10796: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10797:
1.78 anton 10798: @cindex @code{inst-value} usage
10799: You can also define fields with @code{inst-value}, which is
10800: to @code{inst-var} what @code{value} is to
10801: @code{variable}. You can change the value of such a field with
10802: @code{[to-inst]}. E.g., we could also define the class
10803: @code{circle} like this:
1.44 crook 10804:
1.78 anton 10805: @example
10806: graphical class
10807: inst-value radius
1.6 pazsan 10808:
1.78 anton 10809: m: ( x y circle -- )
10810: radius draw-circle ;m
10811: overrides draw
1.44 crook 10812:
1.78 anton 10813: m: ( n-radius circle -- )
10814: [to-inst] radius ;m
10815: overrides construct
1.6 pazsan 10816:
1.78 anton 10817: end-class circle
10818: @end example
1.6 pazsan 10819:
1.78 anton 10820: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10821:
1.78 anton 10822: @c Finally, you can define named methods with @code{:m}. One use of this
10823: @c feature is the definition of words that occur only in one class and are
10824: @c not intended to be overridden, but which still need method context
10825: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10826: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10827:
10828:
1.78 anton 10829: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10830: @subsubsection Classes and Scoping
10831: @cindex classes and scoping
10832: @cindex scoping and classes
1.6 pazsan 10833:
1.78 anton 10834: Inheritance is frequent, unlike structure extension. This exacerbates
10835: the problem with the field name convention (@pxref{Structure Naming
10836: Convention}): One always has to remember in which class the field was
10837: originally defined; changing a part of the class structure would require
10838: changes for renaming in otherwise unaffected code.
1.6 pazsan 10839:
1.78 anton 10840: @cindex @code{inst-var} visibility
10841: @cindex @code{inst-value} visibility
10842: To solve this problem, I added a scoping mechanism (which was not in my
10843: original charter): A field defined with @code{inst-var} (or
10844: @code{inst-value}) is visible only in the class where it is defined and in
10845: the descendent classes of this class. Using such fields only makes
10846: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10847:
1.78 anton 10848: This scoping mechanism allows us to use the unadorned field name,
10849: because name clashes with unrelated words become much less likely.
1.6 pazsan 10850:
1.78 anton 10851: @cindex @code{protected} discussion
10852: @cindex @code{private} discussion
10853: Once we have this mechanism, we can also use it for controlling the
10854: visibility of other words: All words defined after
10855: @code{protected} are visible only in the current class and its
10856: descendents. @code{public} restores the compilation
10857: (i.e. @code{current}) word list that was in effect before. If you
10858: have several @code{protected}s without an intervening
10859: @code{public} or @code{set-current}, @code{public}
10860: will restore the compilation word list in effect before the first of
10861: these @code{protected}s.
1.6 pazsan 10862:
1.78 anton 10863: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10864: @subsubsection Dividing classes
10865: @cindex Dividing classes
10866: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10867:
1.78 anton 10868: You may want to do the definition of methods separate from the
10869: definition of the class, its selectors, fields, and instance variables,
10870: i.e., separate the implementation from the definition. You can do this
10871: in the following way:
1.6 pazsan 10872:
1.78 anton 10873: @example
10874: graphical class
10875: inst-value radius
10876: end-class circle
1.6 pazsan 10877:
1.78 anton 10878: ... \ do some other stuff
1.6 pazsan 10879:
1.78 anton 10880: circle methods \ now we are ready
1.44 crook 10881:
1.78 anton 10882: m: ( x y circle -- )
10883: radius draw-circle ;m
10884: overrides draw
1.6 pazsan 10885:
1.78 anton 10886: m: ( n-radius circle -- )
10887: [to-inst] radius ;m
10888: overrides construct
1.44 crook 10889:
1.78 anton 10890: end-methods
10891: @end example
1.7 pazsan 10892:
1.78 anton 10893: You can use several @code{methods}...@code{end-methods} sections. The
10894: only things you can do to the class in these sections are: defining
10895: methods, and overriding the class's selectors. You must not define new
10896: selectors or fields.
1.7 pazsan 10897:
1.78 anton 10898: Note that you often have to override a selector before using it. In
10899: particular, you usually have to override @code{construct} with a new
10900: method before you can invoke @code{heap-new} and friends. E.g., you
10901: must not create a circle before the @code{overrides construct} sequence
10902: in the example above.
1.7 pazsan 10903:
1.78 anton 10904: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10905: @subsubsection Object Interfaces
10906: @cindex object interfaces
10907: @cindex interfaces for objects
1.7 pazsan 10908:
1.78 anton 10909: In this model you can only call selectors defined in the class of the
10910: receiving objects or in one of its ancestors. If you call a selector
10911: with a receiving object that is not in one of these classes, the
10912: result is undefined; if you are lucky, the program crashes
10913: immediately.
1.7 pazsan 10914:
1.78 anton 10915: @cindex selectors common to hardly-related classes
10916: Now consider the case when you want to have a selector (or several)
10917: available in two classes: You would have to add the selector to a
10918: common ancestor class, in the worst case to @code{object}. You
10919: may not want to do this, e.g., because someone else is responsible for
10920: this ancestor class.
1.7 pazsan 10921:
1.78 anton 10922: The solution for this problem is interfaces. An interface is a
10923: collection of selectors. If a class implements an interface, the
10924: selectors become available to the class and its descendents. A class
10925: can implement an unlimited number of interfaces. For the problem
10926: discussed above, we would define an interface for the selector(s), and
10927: both classes would implement the interface.
1.7 pazsan 10928:
1.78 anton 10929: As an example, consider an interface @code{storage} for
10930: writing objects to disk and getting them back, and a class
10931: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10932:
1.78 anton 10933: @cindex @code{interface} usage
10934: @cindex @code{end-interface} usage
10935: @cindex @code{implementation} usage
10936: @example
10937: interface
10938: selector write ( file object -- )
10939: selector read1 ( file object -- )
10940: end-interface storage
1.13 pazsan 10941:
1.78 anton 10942: bar class
10943: storage implementation
1.13 pazsan 10944:
1.78 anton 10945: ... overrides write
10946: ... overrides read1
10947: ...
10948: end-class foo
10949: @end example
1.13 pazsan 10950:
1.78 anton 10951: @noindent
10952: (I would add a word @code{read} @i{( file -- object )} that uses
10953: @code{read1} internally, but that's beyond the point illustrated
10954: here.)
1.13 pazsan 10955:
1.78 anton 10956: Note that you cannot use @code{protected} in an interface; and
10957: of course you cannot define fields.
1.13 pazsan 10958:
1.78 anton 10959: In the Neon model, all selectors are available for all classes;
10960: therefore it does not need interfaces. The price you pay in this model
10961: is slower late binding, and therefore, added complexity to avoid late
10962: binding.
1.13 pazsan 10963:
1.78 anton 10964: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10965: @subsubsection @file{objects.fs} Implementation
10966: @cindex @file{objects.fs} implementation
1.13 pazsan 10967:
1.78 anton 10968: @cindex @code{object-map} discussion
10969: An object is a piece of memory, like one of the data structures
10970: described with @code{struct...end-struct}. It has a field
10971: @code{object-map} that points to the method map for the object's
10972: class.
1.13 pazsan 10973:
1.78 anton 10974: @cindex method map
10975: @cindex virtual function table
10976: The @emph{method map}@footnote{This is Self terminology; in C++
10977: terminology: virtual function table.} is an array that contains the
10978: execution tokens (@i{xt}s) of the methods for the object's class. Each
10979: selector contains an offset into a method map.
1.13 pazsan 10980:
1.78 anton 10981: @cindex @code{selector} implementation, class
10982: @code{selector} is a defining word that uses
10983: @code{CREATE} and @code{DOES>}. The body of the
10984: selector contains the offset; the @code{DOES>} action for a
10985: class selector is, basically:
1.8 pazsan 10986:
10987: @example
1.78 anton 10988: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10989: @end example
10990:
1.78 anton 10991: Since @code{object-map} is the first field of the object, it
10992: does not generate any code. As you can see, calling a selector has a
10993: small, constant cost.
1.26 crook 10994:
1.78 anton 10995: @cindex @code{current-interface} discussion
10996: @cindex class implementation and representation
10997: A class is basically a @code{struct} combined with a method
10998: map. During the class definition the alignment and size of the class
10999: are passed on the stack, just as with @code{struct}s, so
11000: @code{field} can also be used for defining class
11001: fields. However, passing more items on the stack would be
11002: inconvenient, so @code{class} builds a data structure in memory,
11003: which is accessed through the variable
11004: @code{current-interface}. After its definition is complete, the
11005: class is represented on the stack by a pointer (e.g., as parameter for
11006: a child class definition).
1.26 crook 11007:
1.78 anton 11008: A new class starts off with the alignment and size of its parent,
11009: and a copy of the parent's method map. Defining new fields extends the
11010: size and alignment; likewise, defining new selectors extends the
11011: method map. @code{overrides} just stores a new @i{xt} in the method
11012: map at the offset given by the selector.
1.13 pazsan 11013:
1.78 anton 11014: @cindex class binding, implementation
11015: Class binding just gets the @i{xt} at the offset given by the selector
11016: from the class's method map and @code{compile,}s (in the case of
11017: @code{[bind]}) it.
1.13 pazsan 11018:
1.78 anton 11019: @cindex @code{this} implementation
11020: @cindex @code{catch} and @code{this}
11021: @cindex @code{this} and @code{catch}
11022: I implemented @code{this} as a @code{value}. At the
11023: start of an @code{m:...;m} method the old @code{this} is
11024: stored to the return stack and restored at the end; and the object on
11025: the TOS is stored @code{TO this}. This technique has one
11026: disadvantage: If the user does not leave the method via
11027: @code{;m}, but via @code{throw} or @code{exit},
11028: @code{this} is not restored (and @code{exit} may
11029: crash). To deal with the @code{throw} problem, I have redefined
11030: @code{catch} to save and restore @code{this}; the same
11031: should be done with any word that can catch an exception. As for
11032: @code{exit}, I simply forbid it (as a replacement, there is
11033: @code{exitm}).
1.13 pazsan 11034:
1.78 anton 11035: @cindex @code{inst-var} implementation
11036: @code{inst-var} is just the same as @code{field}, with
11037: a different @code{DOES>} action:
1.13 pazsan 11038: @example
1.78 anton 11039: @@ this +
1.8 pazsan 11040: @end example
1.78 anton 11041: Similar for @code{inst-value}.
1.8 pazsan 11042:
1.78 anton 11043: @cindex class scoping implementation
11044: Each class also has a word list that contains the words defined with
11045: @code{inst-var} and @code{inst-value}, and its protected
11046: words. It also has a pointer to its parent. @code{class} pushes
11047: the word lists of the class and all its ancestors onto the search order stack,
11048: and @code{end-class} drops them.
1.20 pazsan 11049:
1.78 anton 11050: @cindex interface implementation
11051: An interface is like a class without fields, parent and protected
11052: words; i.e., it just has a method map. If a class implements an
11053: interface, its method map contains a pointer to the method map of the
11054: interface. The positive offsets in the map are reserved for class
11055: methods, therefore interface map pointers have negative
11056: offsets. Interfaces have offsets that are unique throughout the
11057: system, unlike class selectors, whose offsets are only unique for the
11058: classes where the selector is available (invokable).
1.20 pazsan 11059:
1.78 anton 11060: This structure means that interface selectors have to perform one
11061: indirection more than class selectors to find their method. Their body
11062: contains the interface map pointer offset in the class method map, and
11063: the method offset in the interface method map. The
11064: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11065:
11066: @example
1.78 anton 11067: ( object selector-body )
11068: 2dup selector-interface @@ ( object selector-body object interface-offset )
11069: swap object-map @@ + @@ ( object selector-body map )
11070: swap selector-offset @@ + @@ execute
1.20 pazsan 11071: @end example
11072:
1.78 anton 11073: where @code{object-map} and @code{selector-offset} are
11074: first fields and generate no code.
1.20 pazsan 11075:
1.78 anton 11076: As a concrete example, consider the following code:
1.20 pazsan 11077:
11078: @example
1.78 anton 11079: interface
11080: selector if1sel1
11081: selector if1sel2
11082: end-interface if1
1.20 pazsan 11083:
1.78 anton 11084: object class
11085: if1 implementation
11086: selector cl1sel1
11087: cell% inst-var cl1iv1
1.20 pazsan 11088:
1.78 anton 11089: ' m1 overrides construct
11090: ' m2 overrides if1sel1
11091: ' m3 overrides if1sel2
11092: ' m4 overrides cl1sel2
11093: end-class cl1
1.20 pazsan 11094:
1.78 anton 11095: create obj1 object dict-new drop
11096: create obj2 cl1 dict-new drop
11097: @end example
1.20 pazsan 11098:
1.78 anton 11099: The data structure created by this code (including the data structure
11100: for @code{object}) is shown in the
11101: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11102: @comment TODO add this diagram..
1.20 pazsan 11103:
1.78 anton 11104: @node Objects Glossary, , Objects Implementation, Objects
11105: @subsubsection @file{objects.fs} Glossary
11106: @cindex @file{objects.fs} Glossary
1.20 pazsan 11107:
11108:
1.78 anton 11109: doc---objects-bind
11110: doc---objects-<bind>
11111: doc---objects-bind'
11112: doc---objects-[bind]
11113: doc---objects-class
11114: doc---objects-class->map
11115: doc---objects-class-inst-size
11116: doc---objects-class-override!
1.79 anton 11117: doc---objects-class-previous
11118: doc---objects-class>order
1.78 anton 11119: doc---objects-construct
11120: doc---objects-current'
11121: doc---objects-[current]
11122: doc---objects-current-interface
11123: doc---objects-dict-new
11124: doc---objects-end-class
11125: doc---objects-end-class-noname
11126: doc---objects-end-interface
11127: doc---objects-end-interface-noname
11128: doc---objects-end-methods
11129: doc---objects-exitm
11130: doc---objects-heap-new
11131: doc---objects-implementation
11132: doc---objects-init-object
11133: doc---objects-inst-value
11134: doc---objects-inst-var
11135: doc---objects-interface
11136: doc---objects-m:
11137: doc---objects-:m
11138: doc---objects-;m
11139: doc---objects-method
11140: doc---objects-methods
11141: doc---objects-object
11142: doc---objects-overrides
11143: doc---objects-[parent]
11144: doc---objects-print
11145: doc---objects-protected
11146: doc---objects-public
11147: doc---objects-selector
11148: doc---objects-this
11149: doc---objects-<to-inst>
11150: doc---objects-[to-inst]
11151: doc---objects-to-this
11152: doc---objects-xt-new
1.20 pazsan 11153:
11154:
1.78 anton 11155: @c -------------------------------------------------------------
11156: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11157: @subsection The @file{oof.fs} model
11158: @cindex oof
11159: @cindex object-oriented programming
1.20 pazsan 11160:
1.78 anton 11161: @cindex @file{objects.fs}
11162: @cindex @file{oof.fs}
1.20 pazsan 11163:
1.78 anton 11164: This section describes the @file{oof.fs} package.
1.20 pazsan 11165:
1.78 anton 11166: The package described in this section has been used in bigFORTH since 1991, and
11167: used for two large applications: a chromatographic system used to
11168: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11169:
1.78 anton 11170: You can find a description (in German) of @file{oof.fs} in @cite{Object
11171: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11172: 10(2), 1994.
1.20 pazsan 11173:
1.78 anton 11174: @menu
11175: * Properties of the OOF model::
11176: * Basic OOF Usage::
11177: * The OOF base class::
11178: * Class Declaration::
11179: * Class Implementation::
11180: @end menu
1.20 pazsan 11181:
1.78 anton 11182: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11183: @subsubsection Properties of the @file{oof.fs} model
11184: @cindex @file{oof.fs} properties
1.20 pazsan 11185:
1.78 anton 11186: @itemize @bullet
11187: @item
11188: This model combines object oriented programming with information
11189: hiding. It helps you writing large application, where scoping is
11190: necessary, because it provides class-oriented scoping.
1.20 pazsan 11191:
1.78 anton 11192: @item
11193: Named objects, object pointers, and object arrays can be created,
11194: selector invocation uses the ``object selector'' syntax. Selector invocation
11195: to objects and/or selectors on the stack is a bit less convenient, but
11196: possible.
1.44 crook 11197:
1.78 anton 11198: @item
11199: Selector invocation and instance variable usage of the active object is
11200: straightforward, since both make use of the active object.
1.44 crook 11201:
1.78 anton 11202: @item
11203: Late binding is efficient and easy to use.
1.20 pazsan 11204:
1.78 anton 11205: @item
11206: State-smart objects parse selectors. However, extensibility is provided
11207: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11208:
1.78 anton 11209: @item
11210: An implementation in ANS Forth is available.
1.20 pazsan 11211:
1.78 anton 11212: @end itemize
1.23 crook 11213:
11214:
1.78 anton 11215: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11216: @subsubsection Basic @file{oof.fs} Usage
11217: @cindex @file{oof.fs} usage
1.23 crook 11218:
1.78 anton 11219: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11220:
1.78 anton 11221: You can define a class for graphical objects like this:
1.23 crook 11222:
1.78 anton 11223: @cindex @code{class} usage
11224: @cindex @code{class;} usage
11225: @cindex @code{method} usage
11226: @example
11227: object class graphical \ "object" is the parent class
1.139 pazsan 11228: method draw ( x y -- )
1.78 anton 11229: class;
11230: @end example
1.23 crook 11231:
1.78 anton 11232: This code defines a class @code{graphical} with an
11233: operation @code{draw}. We can perform the operation
11234: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11235:
1.78 anton 11236: @example
11237: 100 100 t-rex draw
11238: @end example
1.23 crook 11239:
1.78 anton 11240: @noindent
11241: where @code{t-rex} is an object or object pointer, created with e.g.
11242: @code{graphical : t-rex}.
1.23 crook 11243:
1.78 anton 11244: @cindex abstract class
11245: How do we create a graphical object? With the present definitions,
11246: we cannot create a useful graphical object. The class
11247: @code{graphical} describes graphical objects in general, but not
11248: any concrete graphical object type (C++ users would call it an
11249: @emph{abstract class}); e.g., there is no method for the selector
11250: @code{draw} in the class @code{graphical}.
1.23 crook 11251:
1.78 anton 11252: For concrete graphical objects, we define child classes of the
11253: class @code{graphical}, e.g.:
1.23 crook 11254:
1.78 anton 11255: @example
11256: graphical class circle \ "graphical" is the parent class
11257: cell var circle-radius
11258: how:
11259: : draw ( x y -- )
11260: circle-radius @@ draw-circle ;
1.23 crook 11261:
1.139 pazsan 11262: : init ( n-radius -- )
1.78 anton 11263: circle-radius ! ;
11264: class;
11265: @end example
1.1 anton 11266:
1.78 anton 11267: Here we define a class @code{circle} as a child of @code{graphical},
11268: with a field @code{circle-radius}; it defines new methods for the
11269: selectors @code{draw} and @code{init} (@code{init} is defined in
11270: @code{object}, the parent class of @code{graphical}).
1.1 anton 11271:
1.78 anton 11272: Now we can create a circle in the dictionary with:
1.1 anton 11273:
1.78 anton 11274: @example
11275: 50 circle : my-circle
11276: @end example
1.21 crook 11277:
1.78 anton 11278: @noindent
11279: @code{:} invokes @code{init}, thus initializing the field
11280: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11281: with:
1.1 anton 11282:
1.78 anton 11283: @example
11284: 100 100 my-circle draw
11285: @end example
1.1 anton 11286:
1.78 anton 11287: @cindex selector invocation, restrictions
11288: @cindex class definition, restrictions
11289: Note: You can only invoke a selector if the receiving object belongs to
11290: the class where the selector was defined or one of its descendents;
11291: e.g., you can invoke @code{draw} only for objects belonging to
11292: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11293: mechanism will check if you try to invoke a selector that is not
11294: defined in this class hierarchy, so you'll get an error at compilation
11295: time.
1.1 anton 11296:
11297:
1.78 anton 11298: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11299: @subsubsection The @file{oof.fs} base class
11300: @cindex @file{oof.fs} base class
1.1 anton 11301:
1.78 anton 11302: When you define a class, you have to specify a parent class. So how do
11303: you start defining classes? There is one class available from the start:
11304: @code{object}. You have to use it as ancestor for all classes. It is the
11305: only class that has no parent. Classes are also objects, except that
11306: they don't have instance variables; class manipulation such as
11307: inheritance or changing definitions of a class is handled through
11308: selectors of the class @code{object}.
1.1 anton 11309:
1.78 anton 11310: @code{object} provides a number of selectors:
1.1 anton 11311:
1.78 anton 11312: @itemize @bullet
11313: @item
11314: @code{class} for subclassing, @code{definitions} to add definitions
11315: later on, and @code{class?} to get type informations (is the class a
11316: subclass of the class passed on the stack?).
1.1 anton 11317:
1.78 anton 11318: doc---object-class
11319: doc---object-definitions
11320: doc---object-class?
1.1 anton 11321:
11322:
1.26 crook 11323: @item
1.78 anton 11324: @code{init} and @code{dispose} as constructor and destructor of the
11325: object. @code{init} is invocated after the object's memory is allocated,
11326: while @code{dispose} also handles deallocation. Thus if you redefine
11327: @code{dispose}, you have to call the parent's dispose with @code{super
11328: dispose}, too.
11329:
11330: doc---object-init
11331: doc---object-dispose
11332:
1.1 anton 11333:
1.26 crook 11334: @item
1.78 anton 11335: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11336: @code{[]} to create named and unnamed objects and object arrays or
11337: object pointers.
11338:
11339: doc---object-new
11340: doc---object-new[]
11341: doc---object-:
11342: doc---object-ptr
11343: doc---object-asptr
11344: doc---object-[]
11345:
1.1 anton 11346:
1.26 crook 11347: @item
1.78 anton 11348: @code{::} and @code{super} for explicit scoping. You should use explicit
11349: scoping only for super classes or classes with the same set of instance
11350: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11351:
1.78 anton 11352: doc---object-::
11353: doc---object-super
1.21 crook 11354:
11355:
1.26 crook 11356: @item
1.78 anton 11357: @code{self} to get the address of the object
1.21 crook 11358:
1.78 anton 11359: doc---object-self
1.21 crook 11360:
11361:
1.78 anton 11362: @item
11363: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11364: pointers and instance defers.
1.21 crook 11365:
1.78 anton 11366: doc---object-bind
11367: doc---object-bound
11368: doc---object-link
11369: doc---object-is
1.21 crook 11370:
11371:
1.78 anton 11372: @item
11373: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11374: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11375:
1.78 anton 11376: doc---object-'
11377: doc---object-postpone
1.21 crook 11378:
11379:
1.78 anton 11380: @item
11381: @code{with} and @code{endwith} to select the active object from the
11382: stack, and enable its scope. Using @code{with} and @code{endwith}
11383: also allows you to create code using selector @code{postpone} without being
11384: trapped by the state-smart objects.
1.21 crook 11385:
1.78 anton 11386: doc---object-with
11387: doc---object-endwith
1.21 crook 11388:
11389:
1.78 anton 11390: @end itemize
1.21 crook 11391:
1.78 anton 11392: @node Class Declaration, Class Implementation, The OOF base class, OOF
11393: @subsubsection Class Declaration
11394: @cindex class declaration
1.21 crook 11395:
1.78 anton 11396: @itemize @bullet
11397: @item
11398: Instance variables
1.21 crook 11399:
1.78 anton 11400: doc---oof-var
1.21 crook 11401:
11402:
1.78 anton 11403: @item
11404: Object pointers
1.21 crook 11405:
1.78 anton 11406: doc---oof-ptr
11407: doc---oof-asptr
1.21 crook 11408:
11409:
1.78 anton 11410: @item
11411: Instance defers
1.21 crook 11412:
1.78 anton 11413: doc---oof-defer
1.21 crook 11414:
11415:
1.78 anton 11416: @item
11417: Method selectors
1.21 crook 11418:
1.78 anton 11419: doc---oof-early
11420: doc---oof-method
1.21 crook 11421:
11422:
1.78 anton 11423: @item
11424: Class-wide variables
1.21 crook 11425:
1.78 anton 11426: doc---oof-static
1.21 crook 11427:
11428:
1.78 anton 11429: @item
11430: End declaration
1.1 anton 11431:
1.78 anton 11432: doc---oof-how:
11433: doc---oof-class;
1.21 crook 11434:
11435:
1.78 anton 11436: @end itemize
1.21 crook 11437:
1.78 anton 11438: @c -------------------------------------------------------------
11439: @node Class Implementation, , Class Declaration, OOF
11440: @subsubsection Class Implementation
11441: @cindex class implementation
1.21 crook 11442:
1.78 anton 11443: @c -------------------------------------------------------------
11444: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11445: @subsection The @file{mini-oof.fs} model
11446: @cindex mini-oof
1.21 crook 11447:
1.78 anton 11448: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11449: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11450: and reduces to the bare minimum of features. This is based on a posting
11451: of Bernd Paysan in comp.lang.forth.
1.21 crook 11452:
1.78 anton 11453: @menu
11454: * Basic Mini-OOF Usage::
11455: * Mini-OOF Example::
11456: * Mini-OOF Implementation::
11457: @end menu
1.21 crook 11458:
1.78 anton 11459: @c -------------------------------------------------------------
11460: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11461: @subsubsection Basic @file{mini-oof.fs} Usage
11462: @cindex mini-oof usage
1.21 crook 11463:
1.78 anton 11464: There is a base class (@code{class}, which allocates one cell for the
11465: object pointer) plus seven other words: to define a method, a variable,
11466: a class; to end a class, to resolve binding, to allocate an object and
11467: to compile a class method.
11468: @comment TODO better description of the last one
1.26 crook 11469:
1.21 crook 11470:
1.78 anton 11471: doc-object
11472: doc-method
11473: doc-var
11474: doc-class
11475: doc-end-class
11476: doc-defines
11477: doc-new
11478: doc-::
1.21 crook 11479:
11480:
11481:
1.78 anton 11482: @c -------------------------------------------------------------
11483: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11484: @subsubsection Mini-OOF Example
11485: @cindex mini-oof example
1.1 anton 11486:
1.78 anton 11487: A short example shows how to use this package. This example, in slightly
11488: extended form, is supplied as @file{moof-exm.fs}
11489: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11490:
1.26 crook 11491: @example
1.78 anton 11492: object class
11493: method init
11494: method draw
11495: end-class graphical
1.26 crook 11496: @end example
1.20 pazsan 11497:
1.78 anton 11498: This code defines a class @code{graphical} with an
11499: operation @code{draw}. We can perform the operation
11500: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11501:
1.26 crook 11502: @example
1.78 anton 11503: 100 100 t-rex draw
1.26 crook 11504: @end example
1.12 anton 11505:
1.78 anton 11506: where @code{t-rex} is an object or object pointer, created with e.g.
11507: @code{graphical new Constant t-rex}.
1.12 anton 11508:
1.78 anton 11509: For concrete graphical objects, we define child classes of the
11510: class @code{graphical}, e.g.:
1.12 anton 11511:
1.26 crook 11512: @example
11513: graphical class
1.78 anton 11514: cell var circle-radius
11515: end-class circle \ "graphical" is the parent class
1.12 anton 11516:
1.78 anton 11517: :noname ( x y -- )
11518: circle-radius @@ draw-circle ; circle defines draw
11519: :noname ( r -- )
11520: circle-radius ! ; circle defines init
11521: @end example
1.12 anton 11522:
1.78 anton 11523: There is no implicit init method, so we have to define one. The creation
11524: code of the object now has to call init explicitely.
1.21 crook 11525:
1.78 anton 11526: @example
11527: circle new Constant my-circle
11528: 50 my-circle init
1.12 anton 11529: @end example
11530:
1.78 anton 11531: It is also possible to add a function to create named objects with
11532: automatic call of @code{init}, given that all objects have @code{init}
11533: on the same place:
1.38 anton 11534:
1.78 anton 11535: @example
11536: : new: ( .. o "name" -- )
11537: new dup Constant init ;
11538: 80 circle new: large-circle
11539: @end example
1.12 anton 11540:
1.78 anton 11541: We can draw this new circle at (100,100) with:
1.12 anton 11542:
1.78 anton 11543: @example
11544: 100 100 my-circle draw
11545: @end example
1.12 anton 11546:
1.78 anton 11547: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11548: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11549:
1.78 anton 11550: Object-oriented systems with late binding typically use a
11551: ``vtable''-approach: the first variable in each object is a pointer to a
11552: table, which contains the methods as function pointers. The vtable
11553: may also contain other information.
1.12 anton 11554:
1.79 anton 11555: So first, let's declare selectors:
1.37 anton 11556:
11557: @example
1.79 anton 11558: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11559: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11560: @end example
1.37 anton 11561:
1.79 anton 11562: During selector declaration, the number of selectors and instance
11563: variables is on the stack (in address units). @code{method} creates one
11564: selector and increments the selector number. To execute a selector, it
1.78 anton 11565: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11566: executes the method @i{xt} stored there. Each selector takes the object
11567: it is invoked with as top of stack parameter; it passes the parameters
11568: (including the object) unchanged to the appropriate method which should
1.78 anton 11569: consume that object.
1.37 anton 11570:
1.78 anton 11571: Now, we also have to declare instance variables
1.37 anton 11572:
1.78 anton 11573: @example
1.79 anton 11574: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11575: DOES> ( o -- addr ) @@ + ;
1.37 anton 11576: @end example
11577:
1.78 anton 11578: As before, a word is created with the current offset. Instance
11579: variables can have different sizes (cells, floats, doubles, chars), so
11580: all we do is take the size and add it to the offset. If your machine
11581: has alignment restrictions, put the proper @code{aligned} or
11582: @code{faligned} before the variable, to adjust the variable
11583: offset. That's why it is on the top of stack.
1.37 anton 11584:
1.78 anton 11585: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11586:
1.78 anton 11587: @example
11588: Create object 1 cells , 2 cells ,
1.79 anton 11589: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11590: @end example
1.12 anton 11591:
1.78 anton 11592: For inheritance, the vtable of the parent object has to be
11593: copied when a new, derived class is declared. This gives all the
11594: methods of the parent class, which can be overridden, though.
1.12 anton 11595:
1.78 anton 11596: @example
1.79 anton 11597: : end-class ( class selectors vars "name" -- )
1.78 anton 11598: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11599: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11600: @end example
1.12 anton 11601:
1.78 anton 11602: The first line creates the vtable, initialized with
11603: @code{noop}s. The second line is the inheritance mechanism, it
11604: copies the xts from the parent vtable.
1.12 anton 11605:
1.78 anton 11606: We still have no way to define new methods, let's do that now:
1.12 anton 11607:
1.26 crook 11608: @example
1.79 anton 11609: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11610: @end example
1.12 anton 11611:
1.78 anton 11612: To allocate a new object, we need a word, too:
1.12 anton 11613:
1.78 anton 11614: @example
11615: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11616: @end example
11617:
1.78 anton 11618: Sometimes derived classes want to access the method of the
11619: parent object. There are two ways to achieve this with Mini-OOF:
11620: first, you could use named words, and second, you could look up the
11621: vtable of the parent object.
1.12 anton 11622:
1.78 anton 11623: @example
11624: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11625: @end example
1.12 anton 11626:
11627:
1.78 anton 11628: Nothing can be more confusing than a good example, so here is
11629: one. First let's declare a text object (called
11630: @code{button}), that stores text and position:
1.12 anton 11631:
1.78 anton 11632: @example
11633: object class
11634: cell var text
11635: cell var len
11636: cell var x
11637: cell var y
11638: method init
11639: method draw
11640: end-class button
11641: @end example
1.12 anton 11642:
1.78 anton 11643: @noindent
11644: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11645:
1.26 crook 11646: @example
1.78 anton 11647: :noname ( o -- )
11648: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11649: button defines draw
11650: :noname ( addr u o -- )
11651: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11652: button defines init
1.26 crook 11653: @end example
1.12 anton 11654:
1.78 anton 11655: @noindent
11656: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11657: new data and no new selectors:
1.78 anton 11658:
11659: @example
11660: button class
11661: end-class bold-button
1.12 anton 11662:
1.78 anton 11663: : bold 27 emit ." [1m" ;
11664: : normal 27 emit ." [0m" ;
11665: @end example
1.1 anton 11666:
1.78 anton 11667: @noindent
11668: The class @code{bold-button} has a different draw method to
11669: @code{button}, but the new method is defined in terms of the draw method
11670: for @code{button}:
1.20 pazsan 11671:
1.78 anton 11672: @example
11673: :noname bold [ button :: draw ] normal ; bold-button defines draw
11674: @end example
1.21 crook 11675:
1.78 anton 11676: @noindent
1.79 anton 11677: Finally, create two objects and apply selectors:
1.21 crook 11678:
1.26 crook 11679: @example
1.78 anton 11680: button new Constant foo
11681: s" thin foo" foo init
11682: page
11683: foo draw
11684: bold-button new Constant bar
11685: s" fat bar" bar init
11686: 1 bar y !
11687: bar draw
1.26 crook 11688: @end example
1.21 crook 11689:
11690:
1.78 anton 11691: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11692: @subsection Comparison with other object models
11693: @cindex comparison of object models
11694: @cindex object models, comparison
11695:
11696: Many object-oriented Forth extensions have been proposed (@cite{A survey
11697: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11698: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11699: relation of the object models described here to two well-known and two
11700: closely-related (by the use of method maps) models. Andras Zsoter
11701: helped us with this section.
11702:
11703: @cindex Neon model
11704: The most popular model currently seems to be the Neon model (see
11705: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11706: 1997) by Andrew McKewan) but this model has a number of limitations
11707: @footnote{A longer version of this critique can be
11708: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11709: Dimensions, May 1997) by Anton Ertl.}:
11710:
11711: @itemize @bullet
11712: @item
11713: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11714: to pass objects on the stack.
1.21 crook 11715:
1.78 anton 11716: @item
11717: It requires that the selector parses the input stream (at
1.79 anton 11718: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11719: hard to find.
1.21 crook 11720:
1.78 anton 11721: @item
1.79 anton 11722: It allows using every selector on every object; this eliminates the
11723: need for interfaces, but makes it harder to create efficient
11724: implementations.
1.78 anton 11725: @end itemize
1.21 crook 11726:
1.78 anton 11727: @cindex Pountain's object-oriented model
11728: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11729: Press, London, 1987) by Dick Pountain. However, it is not really about
11730: object-oriented programming, because it hardly deals with late
11731: binding. Instead, it focuses on features like information hiding and
11732: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11733:
1.78 anton 11734: @cindex Zsoter's object-oriented model
1.79 anton 11735: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11736: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11737: describes a model that makes heavy use of an active object (like
11738: @code{this} in @file{objects.fs}): The active object is not only used
11739: for accessing all fields, but also specifies the receiving object of
11740: every selector invocation; you have to change the active object
11741: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11742: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11743: the method entry point is unnecessary with Zsoter's model, because the
11744: receiving object is the active object already. On the other hand, the
11745: explicit change is absolutely necessary in that model, because otherwise
11746: no one could ever change the active object. An ANS Forth implementation
11747: of this model is available through
11748: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11749:
1.78 anton 11750: @cindex @file{oof.fs}, differences to other models
11751: The @file{oof.fs} model combines information hiding and overloading
11752: resolution (by keeping names in various word lists) with object-oriented
11753: programming. It sets the active object implicitly on method entry, but
11754: also allows explicit changing (with @code{>o...o>} or with
11755: @code{with...endwith}). It uses parsing and state-smart objects and
11756: classes for resolving overloading and for early binding: the object or
11757: class parses the selector and determines the method from this. If the
11758: selector is not parsed by an object or class, it performs a call to the
11759: selector for the active object (late binding), like Zsoter's model.
11760: Fields are always accessed through the active object. The big
11761: disadvantage of this model is the parsing and the state-smartness, which
11762: reduces extensibility and increases the opportunities for subtle bugs;
11763: essentially, you are only safe if you never tick or @code{postpone} an
11764: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11765:
1.78 anton 11766: @cindex @file{mini-oof.fs}, differences to other models
11767: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11768: version of the @file{objects.fs} model, but syntactically it is a
11769: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11770:
11771:
1.78 anton 11772: @c -------------------------------------------------------------
1.150 anton 11773: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11774: @section Programming Tools
11775: @cindex programming tools
1.21 crook 11776:
1.78 anton 11777: @c !! move this and assembler down below OO stuff.
1.21 crook 11778:
1.78 anton 11779: @menu
1.150 anton 11780: * Examining:: Data and Code.
11781: * Forgetting words:: Usually before reloading.
1.78 anton 11782: * Debugging:: Simple and quick.
11783: * Assertions:: Making your programs self-checking.
11784: * Singlestep Debugger:: Executing your program word by word.
11785: @end menu
1.21 crook 11786:
1.78 anton 11787: @node Examining, Forgetting words, Programming Tools, Programming Tools
11788: @subsection Examining data and code
11789: @cindex examining data and code
11790: @cindex data examination
11791: @cindex code examination
1.44 crook 11792:
1.78 anton 11793: The following words inspect the stack non-destructively:
1.21 crook 11794:
1.78 anton 11795: doc-.s
11796: doc-f.s
1.158 anton 11797: doc-maxdepth-.s
1.44 crook 11798:
1.78 anton 11799: There is a word @code{.r} but it does @i{not} display the return stack!
11800: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11801:
1.78 anton 11802: doc-depth
11803: doc-fdepth
11804: doc-clearstack
1.124 anton 11805: doc-clearstacks
1.21 crook 11806:
1.78 anton 11807: The following words inspect memory.
1.21 crook 11808:
1.78 anton 11809: doc-?
11810: doc-dump
1.21 crook 11811:
1.78 anton 11812: And finally, @code{see} allows to inspect code:
1.21 crook 11813:
1.78 anton 11814: doc-see
11815: doc-xt-see
1.111 anton 11816: doc-simple-see
11817: doc-simple-see-range
1.182 anton 11818: doc-see-code
11819: doc-see-code-range
1.21 crook 11820:
1.78 anton 11821: @node Forgetting words, Debugging, Examining, Programming Tools
11822: @subsection Forgetting words
11823: @cindex words, forgetting
11824: @cindex forgeting words
1.21 crook 11825:
1.78 anton 11826: @c anton: other, maybe better places for this subsection: Defining Words;
11827: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11828:
1.78 anton 11829: Forth allows you to forget words (and everything that was alloted in the
11830: dictonary after them) in a LIFO manner.
1.21 crook 11831:
1.78 anton 11832: doc-marker
1.21 crook 11833:
1.78 anton 11834: The most common use of this feature is during progam development: when
11835: you change a source file, forget all the words it defined and load it
11836: again (since you also forget everything defined after the source file
11837: was loaded, you have to reload that, too). Note that effects like
11838: storing to variables and destroyed system words are not undone when you
11839: forget words. With a system like Gforth, that is fast enough at
11840: starting up and compiling, I find it more convenient to exit and restart
11841: Gforth, as this gives me a clean slate.
1.21 crook 11842:
1.78 anton 11843: Here's an example of using @code{marker} at the start of a source file
11844: that you are debugging; it ensures that you only ever have one copy of
11845: the file's definitions compiled at any time:
1.21 crook 11846:
1.78 anton 11847: @example
11848: [IFDEF] my-code
11849: my-code
11850: [ENDIF]
1.26 crook 11851:
1.78 anton 11852: marker my-code
11853: init-included-files
1.21 crook 11854:
1.78 anton 11855: \ .. definitions start here
11856: \ .
11857: \ .
11858: \ end
11859: @end example
1.21 crook 11860:
1.26 crook 11861:
1.78 anton 11862: @node Debugging, Assertions, Forgetting words, Programming Tools
11863: @subsection Debugging
11864: @cindex debugging
1.21 crook 11865:
1.78 anton 11866: Languages with a slow edit/compile/link/test development loop tend to
11867: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11868:
1.78 anton 11869: A much better (faster) way in fast-compiling languages is to add
11870: printing code at well-selected places, let the program run, look at
11871: the output, see where things went wrong, add more printing code, etc.,
11872: until the bug is found.
1.21 crook 11873:
1.78 anton 11874: The simple debugging aids provided in @file{debugs.fs}
11875: are meant to support this style of debugging.
1.21 crook 11876:
1.78 anton 11877: The word @code{~~} prints debugging information (by default the source
11878: location and the stack contents). It is easy to insert. If you use Emacs
11879: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11880: query-replace them with nothing). The deferred words
1.101 anton 11881: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11882: @code{~~}. The default source location output format works well with
11883: Emacs' compilation mode, so you can step through the program at the
11884: source level using @kbd{C-x `} (the advantage over a stepping debugger
11885: is that you can step in any direction and you know where the crash has
11886: happened or where the strange data has occurred).
1.21 crook 11887:
1.78 anton 11888: doc-~~
11889: doc-printdebugdata
1.101 anton 11890: doc-.debugline
1.21 crook 11891:
1.106 anton 11892: @cindex filenames in @code{~~} output
11893: @code{~~} (and assertions) will usually print the wrong file name if a
11894: marker is executed in the same file after their occurance. They will
11895: print @samp{*somewhere*} as file name if a marker is executed in the
11896: same file before their occurance.
11897:
11898:
1.78 anton 11899: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11900: @subsection Assertions
11901: @cindex assertions
1.21 crook 11902:
1.78 anton 11903: It is a good idea to make your programs self-checking, especially if you
11904: make an assumption that may become invalid during maintenance (for
11905: example, that a certain field of a data structure is never zero). Gforth
11906: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11907:
11908: @example
1.78 anton 11909: assert( @i{flag} )
1.26 crook 11910: @end example
11911:
1.78 anton 11912: The code between @code{assert(} and @code{)} should compute a flag, that
11913: should be true if everything is alright and false otherwise. It should
11914: not change anything else on the stack. The overall stack effect of the
11915: assertion is @code{( -- )}. E.g.
1.21 crook 11916:
1.26 crook 11917: @example
1.78 anton 11918: assert( 1 1 + 2 = ) \ what we learn in school
11919: assert( dup 0<> ) \ assert that the top of stack is not zero
11920: assert( false ) \ this code should not be reached
1.21 crook 11921: @end example
11922:
1.78 anton 11923: The need for assertions is different at different times. During
11924: debugging, we want more checking, in production we sometimes care more
11925: for speed. Therefore, assertions can be turned off, i.e., the assertion
11926: becomes a comment. Depending on the importance of an assertion and the
11927: time it takes to check it, you may want to turn off some assertions and
11928: keep others turned on. Gforth provides several levels of assertions for
11929: this purpose:
11930:
11931:
11932: doc-assert0(
11933: doc-assert1(
11934: doc-assert2(
11935: doc-assert3(
11936: doc-assert(
11937: doc-)
1.21 crook 11938:
11939:
1.78 anton 11940: The variable @code{assert-level} specifies the highest assertions that
11941: are turned on. I.e., at the default @code{assert-level} of one,
11942: @code{assert0(} and @code{assert1(} assertions perform checking, while
11943: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11944:
1.78 anton 11945: The value of @code{assert-level} is evaluated at compile-time, not at
11946: run-time. Therefore you cannot turn assertions on or off at run-time;
11947: you have to set the @code{assert-level} appropriately before compiling a
11948: piece of code. You can compile different pieces of code at different
11949: @code{assert-level}s (e.g., a trusted library at level 1 and
11950: newly-written code at level 3).
1.26 crook 11951:
11952:
1.78 anton 11953: doc-assert-level
1.26 crook 11954:
11955:
1.78 anton 11956: If an assertion fails, a message compatible with Emacs' compilation mode
11957: is produced and the execution is aborted (currently with @code{ABORT"}.
11958: If there is interest, we will introduce a special throw code. But if you
11959: intend to @code{catch} a specific condition, using @code{throw} is
11960: probably more appropriate than an assertion).
1.106 anton 11961:
11962: @cindex filenames in assertion output
11963: Assertions (and @code{~~}) will usually print the wrong file name if a
11964: marker is executed in the same file after their occurance. They will
11965: print @samp{*somewhere*} as file name if a marker is executed in the
11966: same file before their occurance.
1.44 crook 11967:
1.78 anton 11968: Definitions in ANS Forth for these assertion words are provided
11969: in @file{compat/assert.fs}.
1.26 crook 11970:
1.44 crook 11971:
1.78 anton 11972: @node Singlestep Debugger, , Assertions, Programming Tools
11973: @subsection Singlestep Debugger
11974: @cindex singlestep Debugger
11975: @cindex debugging Singlestep
1.44 crook 11976:
1.189 anton 11977: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 11978:
1.78 anton 11979: When you create a new word there's often the need to check whether it
11980: behaves correctly or not. You can do this by typing @code{dbg
11981: badword}. A debug session might look like this:
1.26 crook 11982:
1.78 anton 11983: @example
11984: : badword 0 DO i . LOOP ; ok
11985: 2 dbg badword
11986: : badword
11987: Scanning code...
1.44 crook 11988:
1.78 anton 11989: Nesting debugger ready!
1.44 crook 11990:
1.78 anton 11991: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11992: 400D4740 8049F68 DO -> [ 0 ]
11993: 400D4744 804A0C8 i -> [ 1 ] 00000
11994: 400D4748 400C5E60 . -> 0 [ 0 ]
11995: 400D474C 8049D0C LOOP -> [ 0 ]
11996: 400D4744 804A0C8 i -> [ 1 ] 00001
11997: 400D4748 400C5E60 . -> 1 [ 0 ]
11998: 400D474C 8049D0C LOOP -> [ 0 ]
11999: 400D4758 804B384 ; -> ok
12000: @end example
1.21 crook 12001:
1.78 anton 12002: Each line displayed is one step. You always have to hit return to
12003: execute the next word that is displayed. If you don't want to execute
12004: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12005: an overview what keys are available:
1.44 crook 12006:
1.78 anton 12007: @table @i
1.44 crook 12008:
1.78 anton 12009: @item @key{RET}
12010: Next; Execute the next word.
1.21 crook 12011:
1.78 anton 12012: @item n
12013: Nest; Single step through next word.
1.44 crook 12014:
1.78 anton 12015: @item u
12016: Unnest; Stop debugging and execute rest of word. If we got to this word
12017: with nest, continue debugging with the calling word.
1.44 crook 12018:
1.78 anton 12019: @item d
12020: Done; Stop debugging and execute rest.
1.21 crook 12021:
1.78 anton 12022: @item s
12023: Stop; Abort immediately.
1.44 crook 12024:
1.78 anton 12025: @end table
1.44 crook 12026:
1.78 anton 12027: Debugging large application with this mechanism is very difficult, because
12028: you have to nest very deeply into the program before the interesting part
12029: begins. This takes a lot of time.
1.26 crook 12030:
1.78 anton 12031: To do it more directly put a @code{BREAK:} command into your source code.
12032: When program execution reaches @code{BREAK:} the single step debugger is
12033: invoked and you have all the features described above.
1.44 crook 12034:
1.78 anton 12035: If you have more than one part to debug it is useful to know where the
12036: program has stopped at the moment. You can do this by the
12037: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12038: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12039:
1.26 crook 12040:
1.78 anton 12041: doc-dbg
12042: doc-break:
12043: doc-break"
1.44 crook 12044:
1.150 anton 12045: @c ------------------------------------------------------------
12046: @node C Interface, Assembler and Code Words, Programming Tools, Words
12047: @section C Interface
12048: @cindex C interface
12049: @cindex foreign language interface
12050: @cindex interface to C functions
12051:
1.178 anton 12052: Note that the C interface is not yet complete; callbacks are missing,
12053: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12054:
12055: @menu
12056: * Calling C Functions::
12057: * Declaring C Functions::
1.180 anton 12058: * Calling C function pointers::
1.150 anton 12059: * Callbacks::
1.178 anton 12060: * C interface internals::
1.155 anton 12061: * Low-Level C Interface Words::
1.150 anton 12062: @end menu
12063:
1.151 pazsan 12064: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12065: @subsection Calling C functions
1.155 anton 12066: @cindex C functions, calls to
12067: @cindex calling C functions
1.150 anton 12068:
1.151 pazsan 12069: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12070: can call it as follows: You push the arguments on the stack(s), and
12071: then call the word for the C function. The arguments have to be
12072: pushed in the same order as the arguments appear in the C
12073: documentation (i.e., the first argument is deepest on the stack).
12074: Integer and pointer arguments have to be pushed on the data stack,
12075: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12076: by the called C function.
1.150 anton 12077:
1.155 anton 12078: On returning from the C function, the return value, if any, resides on
12079: the appropriate stack: an integer return value is pushed on the data
12080: stack, an FP return value on the FP stack, and a void return value
12081: results in not pushing anything. Note that most C functions have a
12082: return value, even if that is often not used in C; in Forth, you have
12083: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12084:
1.177 anton 12085: The C interface automatically converts between the C type and the
12086: Forth type as necessary, on a best-effort basis (in some cases, there
12087: may be some loss).
1.150 anton 12088:
12089: As an example, consider the POSIX function @code{lseek()}:
12090:
12091: @example
12092: off_t lseek(int fd, off_t offset, int whence);
12093: @end example
12094:
12095: This function takes three integer arguments, and returns an integer
12096: argument, so a Forth call for setting the current file offset to the
12097: start of the file could look like this:
12098:
12099: @example
12100: fd @@ 0 SEEK_SET lseek -1 = if
12101: ... \ error handling
12102: then
12103: @end example
12104:
12105: You might be worried that an @code{off_t} does not fit into a cell, so
12106: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12107: of the return values. In that case, in your declaration of the
12108: function (@pxref{Declaring C Functions}) you should declare it to use
12109: double-cells for the off_t argument and return value, and maybe give
12110: the resulting Forth word a different name, like @code{dlseek}; the
12111: result could be called like this:
1.150 anton 12112:
12113: @example
12114: fd @@ 0. SEEK_SET dlseek -1. d= if
12115: ... \ error handling
12116: then
12117: @end example
12118:
12119: Passing and returning structs or unions is currently not supported by
12120: our interface@footnote{If you know the calling convention of your C
12121: compiler, you usually can call such functions in some way, but that
12122: way is usually not portable between platforms, and sometimes not even
12123: between C compilers.}.
12124:
1.177 anton 12125: Calling functions with a variable number of arguments (@emph{variadic}
12126: functions, e.g., @code{printf()}) is only supported by having you
12127: declare one function-calling word for each argument pattern, and
12128: calling the appropriate word for the desired pattern.
12129:
1.150 anton 12130:
1.155 anton 12131:
1.180 anton 12132: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12133: @subsection Declaring C Functions
1.155 anton 12134: @cindex C functions, declarations
12135: @cindex declaring C functions
1.150 anton 12136:
12137: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12138: it. The declaration consists of two parts:
12139:
12140: @table @b
12141:
12142: @item The C part
1.179 anton 12143: is the C declaration of the function, or more typically and portably,
12144: a C-style @code{#include} of a file that contains the declaration of
12145: the C function.
1.177 anton 12146:
12147: @item The Forth part
12148: declares the Forth types of the parameters and the Forth word name
12149: corresponding to the C function.
12150:
12151: @end table
12152:
12153: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12154: declarations are:
12155:
12156: @example
12157: \c #define _FILE_OFFSET_BITS 64
12158: \c #include <sys/types.h>
12159: \c #include <unistd.h>
12160: c-function lseek lseek n n n -- n
12161: c-function dlseek lseek n d n -- d
12162: @end example
12163:
1.178 anton 12164: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12165: of the line is ordinary C code. You can use as many lines of C
12166: declarations as you like, and they are visible for all further
12167: function declarations.
12168:
12169: The Forth part declares each interface word with @code{c-function},
12170: followed by the Forth name of the word, the C name of the called
12171: function, and the stack effect of the word. The stack effect contains
1.178 anton 12172: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12173: exactly one type for the return value. The possible types are:
12174:
12175: @table @code
12176:
12177: @item n
12178: single-cell integer
12179:
12180: @item a
12181: address (single-cell)
12182:
12183: @item d
12184: double-cell integer
12185:
12186: @item r
12187: floating-point value
12188:
12189: @item func
12190: C function pointer
12191:
12192: @item void
12193: no value (used as return type for void functions)
12194:
12195: @end table
12196:
12197: @cindex variadic C functions
12198:
12199: To deal with variadic C functions, you can declare one Forth word for
12200: every pattern you want to use, e.g.:
12201:
12202: @example
12203: \c #include <stdio.h>
12204: c-function printf-nr printf a n r -- n
12205: c-function printf-rn printf a r n -- n
12206: @end example
12207:
12208: Note that with C functions declared as variadic (or if you don't
12209: provide a prototype), the C interface has no C type to convert to, so
12210: no automatic conversion happens, which may lead to portability
12211: problems in some cases. In such cases you can perform the conversion
12212: explicitly on the C level, e.g., as follows:
12213:
12214: @example
1.178 anton 12215: \c #define printfll(s,ll) printf(s,(long long)ll)
12216: c-function printfll printfll a n -- n
1.177 anton 12217: @end example
12218:
12219: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12220: that casts (converts) the Forth single-cell integer into a
12221: C @code{long long} before calling @code{printf()}.
1.177 anton 12222:
12223: doc-\c
12224: doc-c-function
12225:
12226: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12227: dynamic linking. If these features are not available, there are
12228: other, less convenient and less portable C interfaces in @file{lib.fs}
12229: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12230: mostly incompatible with each other and with the documented C
12231: interface; you can find some examples for the @file{lib.fs} interface
12232: in @file{lib.fs}.
1.177 anton 12233:
12234:
1.180 anton 12235: @node Calling C function pointers, Callbacks, Declaring C Functions, C Interface
12236: @subsection Calling C function pointers from Forth
12237: @cindex C function pointers, calling from Forth
1.177 anton 12238:
1.180 anton 12239: If you come across a C function pointer (e.g., in some C-constructed
12240: structure) and want to call it from your Forth program, you can also
12241: use the features explained until now to achieve that, as follows:
1.150 anton 12242:
1.180 anton 12243: Let us assume that there is a C function pointer type @code{func1}
12244: defined in some header file @file{func1.h}, and you know that these
12245: functions take one integer argument and return an integer result; and
12246: you want to call functions through such pointers. Just define
1.155 anton 12247:
1.180 anton 12248: @example
12249: \c #include <func1.h>
12250: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12251: c-function call-func1 call_func1 n func -- n
12252: @end example
12253:
12254: and then you can call a function pointed to by, say @code{func1a} as
12255: follows:
12256:
12257: @example
12258: -5 func1a call-func1 .
12259: @end example
12260:
12261: In the C part, @code{call_func} is defined as a macro to avoid having
12262: to declare the exact parameter and return types, so the C compiler
12263: knows them from the declaration of @code{func1}.
12264:
12265: The Forth word @code{call-func1} is similar to @code{execute}, except
12266: that it takes a C @code{func1} pointer instead of a Forth execution
12267: token, and it is specific to @code{func1} pointers. For each type of
12268: function pointer you want to call from Forth, you have to define
12269: a separate calling word.
12270:
12271:
12272: @node Callbacks, C interface internals, Calling C function pointers, C Interface
1.150 anton 12273: @subsection Callbacks
1.155 anton 12274: @cindex Callback functions written in Forth
12275: @cindex C function pointers to Forth words
12276:
1.177 anton 12277: Callbacks are not yet supported by the documented C interface. You
12278: can use the undocumented @file{lib.fs} interface for callbacks.
12279:
1.155 anton 12280: In some cases you have to pass a function pointer to a C function,
12281: i.e., the library wants to call back to your application (and the
12282: pointed-to function is called a callback function). You can pass the
12283: address of an existing C function (that you get with @code{lib-sym},
12284: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12285: function, you probably want to define the function as a Forth word.
12286:
12287: @c I don't understand the existing callback interface from the example - anton
12288:
1.165 anton 12289:
12290: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12291: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12292: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12293: @c > > C-Funktionsadresse auf dem TOS).
12294: @c >
12295: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12296: @c > gesehen habe, wozu das gut ist.
12297: @c
12298: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12299: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12300: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12301: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12302: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12303: @c demselben Prototyp.
12304:
12305:
1.178 anton 12306: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12307: @subsection How the C interface works
12308:
12309: The documented C interface works by generating a C code out of the
12310: declarations.
12311:
12312: In particular, for every Forth word declared with @code{c-function},
12313: it generates a wrapper function in C that takes the Forth data from
12314: the Forth stacks, and calls the target C function with these data as
12315: arguments. The C compiler then performs an implicit conversion
12316: between the Forth type from the stack, and the C type for the
12317: parameter, which is given by the C function prototype. After the C
12318: function returns, the return value is likewise implicitly converted to
12319: a Forth type and written back on the stack.
12320:
12321: The @code{\c} lines are literally included in the C code (but without
12322: the @code{\c}), and provide the necessary declarations so that the C
12323: compiler knows the C types and has enough information to perform the
12324: conversion.
12325:
12326: These wrapper functions are eventually compiled and dynamically linked
12327: into Gforth, and then they can be called.
12328:
12329:
1.178 anton 12330: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12331: @subsection Low-Level C Interface Words
1.44 crook 12332:
1.155 anton 12333: doc-open-lib
12334: doc-lib-sym
1.177 anton 12335: doc-call-c
1.26 crook 12336:
1.78 anton 12337: @c -------------------------------------------------------------
1.150 anton 12338: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12339: @section Assembler and Code Words
12340: @cindex assembler
12341: @cindex code words
1.44 crook 12342:
1.78 anton 12343: @menu
12344: * Code and ;code::
12345: * Common Assembler:: Assembler Syntax
12346: * Common Disassembler::
12347: * 386 Assembler:: Deviations and special cases
12348: * Alpha Assembler:: Deviations and special cases
12349: * MIPS assembler:: Deviations and special cases
1.161 anton 12350: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12351: * ARM Assembler:: Deviations and special cases
1.78 anton 12352: * Other assemblers:: How to write them
12353: @end menu
1.21 crook 12354:
1.78 anton 12355: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12356: @subsection @code{Code} and @code{;code}
1.26 crook 12357:
1.78 anton 12358: Gforth provides some words for defining primitives (words written in
12359: machine code), and for defining the machine-code equivalent of
12360: @code{DOES>}-based defining words. However, the machine-independent
12361: nature of Gforth poses a few problems: First of all, Gforth runs on
12362: several architectures, so it can provide no standard assembler. What's
12363: worse is that the register allocation not only depends on the processor,
12364: but also on the @code{gcc} version and options used.
1.44 crook 12365:
1.78 anton 12366: The words that Gforth offers encapsulate some system dependences (e.g.,
12367: the header structure), so a system-independent assembler may be used in
12368: Gforth. If you do not have an assembler, you can compile machine code
12369: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12370: because these words emit stuff in @i{data} space; it works because
12371: Gforth has unified code/data spaces. Assembler isn't likely to be
12372: portable anyway.}.
1.21 crook 12373:
1.44 crook 12374:
1.78 anton 12375: doc-assembler
12376: doc-init-asm
12377: doc-code
12378: doc-end-code
12379: doc-;code
12380: doc-flush-icache
1.44 crook 12381:
1.21 crook 12382:
1.78 anton 12383: If @code{flush-icache} does not work correctly, @code{code} words
12384: etc. will not work (reliably), either.
1.44 crook 12385:
1.78 anton 12386: The typical usage of these @code{code} words can be shown most easily by
12387: analogy to the equivalent high-level defining words:
1.44 crook 12388:
1.78 anton 12389: @example
12390: : foo code foo
12391: <high-level Forth words> <assembler>
12392: ; end-code
12393:
12394: : bar : bar
12395: <high-level Forth words> <high-level Forth words>
12396: CREATE CREATE
12397: <high-level Forth words> <high-level Forth words>
12398: DOES> ;code
12399: <high-level Forth words> <assembler>
12400: ; end-code
12401: @end example
1.21 crook 12402:
1.78 anton 12403: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12404:
1.78 anton 12405: @cindex registers of the inner interpreter
12406: In the assembly code you will want to refer to the inner interpreter's
12407: registers (e.g., the data stack pointer) and you may want to use other
12408: registers for temporary storage. Unfortunately, the register allocation
12409: is installation-dependent.
1.44 crook 12410:
1.78 anton 12411: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12412: (return stack pointer) may be in different places in @code{gforth} and
12413: @code{gforth-fast}, or different installations. This means that you
12414: cannot write a @code{NEXT} routine that works reliably on both versions
12415: or different installations; so for doing @code{NEXT}, I recommend
12416: jumping to @code{' noop >code-address}, which contains nothing but a
12417: @code{NEXT}.
1.21 crook 12418:
1.78 anton 12419: For general accesses to the inner interpreter's registers, the easiest
12420: solution is to use explicit register declarations (@pxref{Explicit Reg
12421: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12422: all of the inner interpreter's registers: You have to compile Gforth
12423: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12424: the appropriate declarations must be present in the @code{machine.h}
12425: file (see @code{mips.h} for an example; you can find a full list of all
12426: declarable register symbols with @code{grep register engine.c}). If you
12427: give explicit registers to all variables that are declared at the
12428: beginning of @code{engine()}, you should be able to use the other
12429: caller-saved registers for temporary storage. Alternatively, you can use
12430: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12431: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12432: reserve a register (however, this restriction on register allocation may
12433: slow Gforth significantly).
1.44 crook 12434:
1.78 anton 12435: If this solution is not viable (e.g., because @code{gcc} does not allow
12436: you to explicitly declare all the registers you need), you have to find
12437: out by looking at the code where the inner interpreter's registers
12438: reside and which registers can be used for temporary storage. You can
12439: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12440:
1.78 anton 12441: In any case, it is good practice to abstract your assembly code from the
12442: actual register allocation. E.g., if the data stack pointer resides in
12443: register @code{$17}, create an alias for this register called @code{sp},
12444: and use that in your assembly code.
1.21 crook 12445:
1.78 anton 12446: @cindex code words, portable
12447: Another option for implementing normal and defining words efficiently
12448: is to add the desired functionality to the source of Gforth. For normal
12449: words you just have to edit @file{primitives} (@pxref{Automatic
12450: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12451: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12452: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12453:
1.78 anton 12454: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12455: @subsection Common Assembler
1.44 crook 12456:
1.78 anton 12457: The assemblers in Gforth generally use a postfix syntax, i.e., the
12458: instruction name follows the operands.
1.21 crook 12459:
1.78 anton 12460: The operands are passed in the usual order (the same that is used in the
12461: manual of the architecture). Since they all are Forth words, they have
12462: to be separated by spaces; you can also use Forth words to compute the
12463: operands.
1.44 crook 12464:
1.78 anton 12465: The instruction names usually end with a @code{,}. This makes it easier
12466: to visually separate instructions if you put several of them on one
12467: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12468:
1.78 anton 12469: Registers are usually specified by number; e.g., (decimal) @code{11}
12470: specifies registers R11 and F11 on the Alpha architecture (which one,
12471: depends on the instruction). The usual names are also available, e.g.,
12472: @code{s2} for R11 on Alpha.
1.21 crook 12473:
1.78 anton 12474: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12475: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12476: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12477: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12478: conditions are specified in a way specific to each assembler.
1.1 anton 12479:
1.78 anton 12480: Note that the register assignments of the Gforth engine can change
12481: between Gforth versions, or even between different compilations of the
12482: same Gforth version (e.g., if you use a different GCC version). So if
12483: you want to refer to Gforth's registers (e.g., the stack pointer or
12484: TOS), I recommend defining your own words for refering to these
12485: registers, and using them later on; then you can easily adapt to a
12486: changed register assignment. The stability of the register assignment
12487: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12488:
1.100 anton 12489: The most common use of these registers is to dispatch to the next word
12490: (the @code{next} routine). A portable way to do this is to jump to
12491: @code{' noop >code-address} (of course, this is less efficient than
12492: integrating the @code{next} code and scheduling it well).
1.1 anton 12493:
1.96 anton 12494: Another difference between Gforth version is that the top of stack is
12495: kept in memory in @code{gforth} and, on most platforms, in a register in
12496: @code{gforth-fast}.
12497:
1.78 anton 12498: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12499: @subsection Common Disassembler
1.127 anton 12500: @cindex disassembler, general
12501: @cindex gdb disassembler
1.1 anton 12502:
1.78 anton 12503: You can disassemble a @code{code} word with @code{see}
12504: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12505:
1.127 anton 12506: doc-discode
1.44 crook 12507:
1.127 anton 12508: There are two kinds of disassembler for Gforth: The Forth disassembler
12509: (available on some CPUs) and the gdb disassembler (available on
12510: platforms with @command{gdb} and @command{mktemp}). If both are
12511: available, the Forth disassembler is used by default. If you prefer
12512: the gdb disassembler, say
12513:
12514: @example
12515: ' disasm-gdb is discode
12516: @end example
12517:
12518: If neither is available, @code{discode} performs @code{dump}.
12519:
12520: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12521: assembler (i.e., same syntax, etc.). It also includes additional
12522: information in comments. In particular, the address of the instruction
12523: is given in a comment before the instruction.
1.1 anton 12524:
1.127 anton 12525: The gdb disassembler produces output in the same format as the gdb
12526: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12527: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12528: the 386 and AMD64 architectures).
12529:
1.78 anton 12530: @code{See} may display more or less than the actual code of the word,
12531: because the recognition of the end of the code is unreliable. You can
1.127 anton 12532: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12533: the code word is not immediately followed by a named word. If you have
1.116 anton 12534: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12535: to ensure that the end is recognized.
1.21 crook 12536:
1.78 anton 12537: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12538: @subsection 386 Assembler
1.44 crook 12539:
1.78 anton 12540: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12541: available under GPL, and originally part of bigFORTH.
1.21 crook 12542:
1.78 anton 12543: The 386 disassembler included in Gforth was written by Andrew McKewan
12544: and is in the public domain.
1.21 crook 12545:
1.91 anton 12546: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12547:
1.78 anton 12548: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12549:
1.78 anton 12550: The assembler includes all instruction of the Athlon, i.e. 486 core
12551: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12552: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12553: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12554:
1.78 anton 12555: There are several prefixes to switch between different operation sizes,
12556: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12557: double-word accesses. Addressing modes can be switched with @code{.wa}
12558: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12559: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12560:
1.78 anton 12561: For floating point operations, the prefixes are @code{.fs} (IEEE
12562: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12563: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12564:
1.78 anton 12565: The MMX opcodes don't have size prefixes, they are spelled out like in
12566: the Intel assembler. Instead of move from and to memory, there are
12567: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12568:
1.78 anton 12569: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12570: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12571: e.g., @code{3 #}. Here are some examples of addressing modes in various
12572: syntaxes:
1.21 crook 12573:
1.26 crook 12574: @example
1.91 anton 12575: Gforth Intel (NASM) AT&T (gas) Name
12576: .w ax ax %ax register (16 bit)
12577: ax eax %eax register (32 bit)
12578: 3 # offset 3 $3 immediate
12579: 1000 #) byte ptr 1000 1000 displacement
12580: bx ) [ebx] (%ebx) base
12581: 100 di d) 100[edi] 100(%edi) base+displacement
12582: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12583: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12584: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12585: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12586: @end example
12587:
12588: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12589: @code{DI)} to enforce 32-bit displacement fields (useful for
12590: later patching).
1.21 crook 12591:
1.78 anton 12592: Some example of instructions are:
1.1 anton 12593:
12594: @example
1.78 anton 12595: ax bx mov \ move ebx,eax
12596: 3 # ax mov \ mov eax,3
1.137 pazsan 12597: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12598: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12599: .w ax bx mov \ mov bx,ax
1.1 anton 12600: @end example
12601:
1.78 anton 12602: The following forms are supported for binary instructions:
1.1 anton 12603:
12604: @example
1.78 anton 12605: <reg> <reg> <inst>
12606: <n> # <reg> <inst>
12607: <mem> <reg> <inst>
12608: <reg> <mem> <inst>
1.136 pazsan 12609: <n> # <mem> <inst>
1.1 anton 12610: @end example
12611:
1.136 pazsan 12612: The shift/rotate syntax is:
1.1 anton 12613:
1.26 crook 12614: @example
1.78 anton 12615: <reg/mem> 1 # shl \ shortens to shift without immediate
12616: <reg/mem> 4 # shl
12617: <reg/mem> cl shl
1.26 crook 12618: @end example
1.1 anton 12619:
1.78 anton 12620: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12621: the byte version.
1.1 anton 12622:
1.78 anton 12623: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12624: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12625: pc < >= <= >}. (Note that most of these words shadow some Forth words
12626: when @code{assembler} is in front of @code{forth} in the search path,
12627: e.g., in @code{code} words). Currently the control structure words use
12628: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12629: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12630:
1.78 anton 12631: Here is an example of a @code{code} word (assumes that the stack pointer
12632: is in esi and the TOS is in ebx):
1.21 crook 12633:
1.26 crook 12634: @example
1.78 anton 12635: code my+ ( n1 n2 -- n )
12636: 4 si D) bx add
12637: 4 # si add
12638: Next
12639: end-code
1.26 crook 12640: @end example
1.21 crook 12641:
1.161 anton 12642:
1.78 anton 12643: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12644: @subsection Alpha Assembler
1.21 crook 12645:
1.78 anton 12646: The Alpha assembler and disassembler were originally written by Bernd
12647: Thallner.
1.26 crook 12648:
1.78 anton 12649: The register names @code{a0}--@code{a5} are not available to avoid
12650: shadowing hex numbers.
1.2 jwilke 12651:
1.78 anton 12652: Immediate forms of arithmetic instructions are distinguished by a
12653: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12654: does not count as arithmetic instruction).
1.2 jwilke 12655:
1.78 anton 12656: You have to specify all operands to an instruction, even those that
12657: other assemblers consider optional, e.g., the destination register for
12658: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12659:
1.78 anton 12660: You can specify conditions for @code{if,} by removing the first @code{b}
12661: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12662:
1.26 crook 12663: @example
1.78 anton 12664: 11 fgt if, \ if F11>0e
12665: ...
12666: endif,
1.26 crook 12667: @end example
1.2 jwilke 12668:
1.78 anton 12669: @code{fbgt,} gives @code{fgt}.
12670:
1.161 anton 12671: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12672: @subsection MIPS assembler
1.2 jwilke 12673:
1.78 anton 12674: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12675:
1.78 anton 12676: Currently the assembler and disassembler only cover the MIPS-I
12677: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12678:
1.78 anton 12679: The register names @code{$a0}--@code{$a3} are not available to avoid
12680: shadowing hex numbers.
1.2 jwilke 12681:
1.78 anton 12682: Because there is no way to distinguish registers from immediate values,
12683: you have to explicitly use the immediate forms of instructions, i.e.,
12684: @code{addiu,}, not just @code{addu,} (@command{as} does this
12685: implicitly).
1.2 jwilke 12686:
1.78 anton 12687: If the architecture manual specifies several formats for the instruction
12688: (e.g., for @code{jalr,}), you usually have to use the one with more
12689: arguments (i.e., two for @code{jalr,}). When in doubt, see
12690: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12691:
1.78 anton 12692: Branches and jumps in the MIPS architecture have a delay slot. You have
12693: to fill it yourself (the simplest way is to use @code{nop,}), the
12694: assembler does not do it for you (unlike @command{as}). Even
12695: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12696: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12697: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12698:
1.78 anton 12699: Note that you must not put branches, jumps, or @code{li,} into the delay
12700: slot: @code{li,} may expand to several instructions, and control flow
12701: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12702:
1.78 anton 12703: For branches the argument specifying the target is a relative address;
12704: You have to add the address of the delay slot to get the absolute
12705: address.
1.1 anton 12706:
1.78 anton 12707: The MIPS architecture also has load delay slots and restrictions on
12708: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12709: yourself to satisfy these restrictions, the assembler does not do it for
12710: you.
1.1 anton 12711:
1.78 anton 12712: You can specify the conditions for @code{if,} etc. by taking a
12713: conditional branch and leaving away the @code{b} at the start and the
12714: @code{,} at the end. E.g.,
1.1 anton 12715:
1.26 crook 12716: @example
1.78 anton 12717: 4 5 eq if,
12718: ... \ do something if $4 equals $5
12719: then,
1.26 crook 12720: @end example
1.1 anton 12721:
1.161 anton 12722:
1.193 dvdkhlng 12723: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12724: @subsection PowerPC assembler
12725:
1.162 anton 12726: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12727: Revucky.
12728:
1.162 anton 12729: This assembler does not follow the convention of ending mnemonic names
12730: with a ``,'', so some mnemonic names shadow regular Forth words (in
12731: particular: @code{and or xor fabs}); so if you want to use the Forth
12732: words, you have to make them visible first, e.g., with @code{also
12733: forth}.
12734:
1.161 anton 12735: Registers are referred to by their number, e.g., @code{9} means the
12736: integer register 9 or the FP register 9 (depending on the
12737: instruction).
12738:
12739: Because there is no way to distinguish registers from immediate values,
12740: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12741: @code{addi,}, not just @code{add,}.
1.161 anton 12742:
1.162 anton 12743: The assembler and disassembler usually support the most general form
1.161 anton 12744: of an instruction, but usually not the shorter forms (especially for
12745: branches).
12746:
12747:
1.193 dvdkhlng 12748: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12749: @subsection ARM Assembler
1.161 anton 12750:
1.193 dvdkhlng 12751: The ARM assembler included in Gforth was written from scratch by David
12752: Kuehling.
12753:
12754: The assembler includes all instruction of ARM architecture version 4,
12755: but does not (yet) have support for Thumb instructions. It also lacks
12756: support for any co-processors.
12757:
12758: The assembler uses a postfix syntax with the target operand specified
12759: last. For load/store instructions the last operand will be the
12760: register(s) to be loaded from/stored to.
12761:
12762: Registers are specified by their names @code{r0} through @code{r15},
12763: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12764: @code{fp} provided for convenience. Note that @code{ip} means intra
12765: procedure call scratch register (@code{r12}) and does not refer to the
12766: instruction pointer.
12767:
12768: Condition codes can be specified anywhere in the instruction, but will
12769: be most readable if specified just in front of the mnemonic. The 'S'
12770: flag is not a separate word, but encoded into instruction mnemonics,
12771: ie. just use @code{adds,} instead of @code{add,} if you want the
12772: status register to be updated.
12773:
12774: The following table lists the syntax of operands for general
12775: instructions:
12776:
12777: @example
12778: Gforth normal assembler description
12779: 123 # #123 immediate
12780: r12 r12 register
12781: r12 4 #LSL r12, LSL #4 shift left by immediate
12782: r12 r1 #LSL r12, LSL r1 shift left by register
12783: r12 4 #LSR r12, LSR #4 shift right by immediate
12784: r12 r1 #LSR r12, LSR r1 shift right by register
12785: r12 4 #ASR r12, ASR #4 arithmetic shift right
12786: r12 r1 #ASR r12, ASR r1 ... by register
12787: r12 4 #ROR r12, ROR #4 rotate right by immediate
12788: r12 r1 #ROR r12, ROR r1 ... by register
12789: r12 RRX r12, RRX rotate right with extend by 1
12790: @end example
12791:
12792: Memory operand syntax is listed in this table:
12793:
12794: @example
12795: Gforth normal assembler description
12796: r4 ] [r4] register
12797: r4 4 #] [r4, #+4] register with immediate offset
12798: r4 -4 #] [r4, #-4] with negative offset
12799: r4 r1 +] [r4, +r1] register with register offset
12800: r4 r1 -] [r4, -r1] with negated register offset
12801: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
12802: r4 4 #]! [r4, #+4]! immediate preincrement
12803: r4 r1 +]! [r4, +r1]! register preincrement
12804: r4 r1 -]! [r4, +r1]! register predecrement
12805: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
12806: r4 -4 ]# [r4], #-4 immediate postdecrement
12807: r4 r1 ]+ [r4], r1 register postincrement
12808: r4 r1 ]- [r4], -r1 register postdecrement
12809: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
12810: ' xyz >body [#] xyz PC-relative addressing
12811: @end example
12812:
12813: Register lists for load/store multiple instructions are started and
12814: terminated by using the words @code{@{} and @code{@}}
12815: respectivly. Between braces, register names can be listed one by one,
12816: or register ranges can be formed by using the postfix operator
12817: @code{r-r}. The @code{^} flag is not encoded in the register list
12818: operand, but instead directly encoded into the instruction mnemonic,
12819: ie. use @code{^ldm,} and @code{^stm,}.
12820:
12821: Addressing modes for load/store multiple are not encoded as
12822: instruction suffixes, but instead specified after the register that
12823: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
12824: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
12825:
12826: The following table gives some examples:
12827:
12828: @example
12829: Gforth normal assembler
12830: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
12831: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
12832: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
12833: @end example
12834:
12835: Conditions for control structure words are specified in front of a
12836: word:
12837:
12838: @example
12839: r1 r2 cmp, \ compare r1 and r2
12840: eq if, \ equal?
12841: ... \ code executed if r1 == r2
12842: then,
12843: @end example
12844:
12845: Here is an example of a @code{code} word (assumes that the stack
12846: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
12847: clobbered):
12848:
12849: @example
12850: code my+ ( n1 n2 -- n3 )
12851: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
12852: r2 r3 r3 add, \ r3 = n2+n1
12853: r9 -4 #]! r3 str, \ push r3
12854: next,
12855: end-code
12856: @end example
12857:
12858: Look at @file{arch/arm/asm-example.fs} for more examples.
12859:
12860: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 12861: @subsection Other assemblers
12862:
12863: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12864: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12865: an assembler already. If you are writing them from scratch, please use
12866: a similar syntax style as the one we use (i.e., postfix, commas at the
12867: end of the instruction names, @pxref{Common Assembler}); make the output
12868: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12869: similar to the style we used.
12870:
12871: Hints on implementation: The most important part is to have a good test
12872: suite that contains all instructions. Once you have that, the rest is
12873: easy. For actual coding you can take a look at
12874: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12875: the assembler and disassembler, avoiding redundancy and some potential
12876: bugs. You can also look at that file (and @pxref{Advanced does> usage
12877: example}) to get ideas how to factor a disassembler.
12878:
12879: Start with the disassembler, because it's easier to reuse data from the
12880: disassembler for the assembler than the other way round.
1.1 anton 12881:
1.78 anton 12882: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12883: how simple it can be.
1.1 anton 12884:
1.161 anton 12885:
12886:
12887:
1.78 anton 12888: @c -------------------------------------------------------------
12889: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12890: @section Threading Words
12891: @cindex threading words
1.1 anton 12892:
1.78 anton 12893: @cindex code address
12894: These words provide access to code addresses and other threading stuff
12895: in Gforth (and, possibly, other interpretive Forths). It more or less
12896: abstracts away the differences between direct and indirect threading
12897: (and, for direct threading, the machine dependences). However, at
12898: present this wordset is still incomplete. It is also pretty low-level;
12899: some day it will hopefully be made unnecessary by an internals wordset
12900: that abstracts implementation details away completely.
1.1 anton 12901:
1.78 anton 12902: The terminology used here stems from indirect threaded Forth systems; in
12903: such a system, the XT of a word is represented by the CFA (code field
12904: address) of a word; the CFA points to a cell that contains the code
12905: address. The code address is the address of some machine code that
12906: performs the run-time action of invoking the word (e.g., the
12907: @code{dovar:} routine pushes the address of the body of the word (a
12908: variable) on the stack
12909: ).
1.1 anton 12910:
1.78 anton 12911: @cindex code address
12912: @cindex code field address
12913: In an indirect threaded Forth, you can get the code address of @i{name}
12914: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12915: >code-address}, independent of the threading method.
1.1 anton 12916:
1.78 anton 12917: doc-threading-method
12918: doc->code-address
12919: doc-code-address!
1.1 anton 12920:
1.78 anton 12921: @cindex @code{does>}-handler
12922: @cindex @code{does>}-code
12923: For a word defined with @code{DOES>}, the code address usually points to
12924: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12925: routine (in Gforth on some platforms, it can also point to the dodoes
12926: routine itself). What you are typically interested in, though, is
12927: whether a word is a @code{DOES>}-defined word, and what Forth code it
12928: executes; @code{>does-code} tells you that.
1.1 anton 12929:
1.78 anton 12930: doc->does-code
1.1 anton 12931:
1.78 anton 12932: To create a @code{DOES>}-defined word with the following basic words,
12933: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12934: @code{/does-handler} aus behind you have to place your executable Forth
12935: code. Finally you have to create a word and modify its behaviour with
12936: @code{does-handler!}.
1.1 anton 12937:
1.78 anton 12938: doc-does-code!
12939: doc-does-handler!
12940: doc-/does-handler
1.1 anton 12941:
1.78 anton 12942: The code addresses produced by various defining words are produced by
12943: the following words:
1.1 anton 12944:
1.78 anton 12945: doc-docol:
12946: doc-docon:
12947: doc-dovar:
12948: doc-douser:
12949: doc-dodefer:
12950: doc-dofield:
1.1 anton 12951:
1.99 anton 12952: @cindex definer
12953: The following two words generalize @code{>code-address},
12954: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12955:
12956: doc->definer
12957: doc-definer!
12958:
1.26 crook 12959: @c -------------------------------------------------------------
1.78 anton 12960: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12961: @section Passing Commands to the Operating System
12962: @cindex operating system - passing commands
12963: @cindex shell commands
12964:
12965: Gforth allows you to pass an arbitrary string to the host operating
12966: system shell (if such a thing exists) for execution.
12967:
12968: doc-sh
12969: doc-system
12970: doc-$?
1.23 crook 12971: doc-getenv
1.44 crook 12972:
1.26 crook 12973: @c -------------------------------------------------------------
1.47 crook 12974: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12975: @section Keeping track of Time
12976: @cindex time-related words
12977:
12978: doc-ms
12979: doc-time&date
1.79 anton 12980: doc-utime
12981: doc-cputime
1.47 crook 12982:
12983:
12984: @c -------------------------------------------------------------
12985: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12986: @section Miscellaneous Words
12987: @cindex miscellaneous words
12988:
1.29 crook 12989: @comment TODO find homes for these
12990:
1.26 crook 12991: These section lists the ANS Forth words that are not documented
1.21 crook 12992: elsewhere in this manual. Ultimately, they all need proper homes.
12993:
1.68 anton 12994: doc-quit
1.44 crook 12995:
1.26 crook 12996: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12997: (@pxref{ANS conformance}):
1.21 crook 12998:
12999: @code{EDITOR}
13000: @code{EMIT?}
13001: @code{FORGET}
13002:
1.24 anton 13003: @c ******************************************************************
13004: @node Error messages, Tools, Words, Top
13005: @chapter Error messages
13006: @cindex error messages
13007: @cindex backtrace
13008:
13009: A typical Gforth error message looks like this:
13010:
13011: @example
1.86 anton 13012: in file included from \evaluated string/:-1
1.24 anton 13013: in file included from ./yyy.fs:1
13014: ./xxx.fs:4: Invalid memory address
1.134 anton 13015: >>>bar<<<
1.79 anton 13016: Backtrace:
1.25 anton 13017: $400E664C @@
13018: $400E6664 foo
1.24 anton 13019: @end example
13020:
13021: The message identifying the error is @code{Invalid memory address}. The
13022: error happened when text-interpreting line 4 of the file
13023: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13024: word on the line where the error happened, is pointed out (with
1.134 anton 13025: @code{>>>} and @code{<<<}).
1.24 anton 13026:
13027: The file containing the error was included in line 1 of @file{./yyy.fs},
13028: and @file{yyy.fs} was included from a non-file (in this case, by giving
13029: @file{yyy.fs} as command-line parameter to Gforth).
13030:
13031: At the end of the error message you find a return stack dump that can be
13032: interpreted as a backtrace (possibly empty). On top you find the top of
13033: the return stack when the @code{throw} happened, and at the bottom you
13034: find the return stack entry just above the return stack of the topmost
13035: text interpreter.
13036:
13037: To the right of most return stack entries you see a guess for the word
13038: that pushed that return stack entry as its return address. This gives a
13039: backtrace. In our case we see that @code{bar} called @code{foo}, and
13040: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13041: address} exception).
13042:
13043: Note that the backtrace is not perfect: We don't know which return stack
13044: entries are return addresses (so we may get false positives); and in
13045: some cases (e.g., for @code{abort"}) we cannot determine from the return
13046: address the word that pushed the return address, so for some return
13047: addresses you see no names in the return stack dump.
1.25 anton 13048:
13049: @cindex @code{catch} and backtraces
13050: The return stack dump represents the return stack at the time when a
13051: specific @code{throw} was executed. In programs that make use of
13052: @code{catch}, it is not necessarily clear which @code{throw} should be
13053: used for the return stack dump (e.g., consider one @code{throw} that
13054: indicates an error, which is caught, and during recovery another error
1.160 anton 13055: happens; which @code{throw} should be used for the stack dump?).
13056: Gforth presents the return stack dump for the first @code{throw} after
13057: the last executed (not returned-to) @code{catch} or @code{nothrow};
13058: this works well in the usual case. To get the right backtrace, you
13059: usually want to insert @code{nothrow} or @code{['] false catch drop}
13060: after a @code{catch} if the error is not rethrown.
1.25 anton 13061:
13062: @cindex @code{gforth-fast} and backtraces
13063: @cindex @code{gforth-fast}, difference from @code{gforth}
13064: @cindex backtraces with @code{gforth-fast}
13065: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13066: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13067: from primitives (e.g., invalid memory address, stack empty etc.);
13068: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13069: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13070: exception caused by a primitive in @code{gforth-fast}, you will
13071: typically see no return stack dump at all; however, if the exception is
13072: caught by @code{catch} (e.g., for restoring some state), and then
13073: @code{throw}n again, the return stack dump will be for the first such
13074: @code{throw}.
1.2 jwilke 13075:
1.5 anton 13076: @c ******************************************************************
1.24 anton 13077: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13078: @chapter Tools
13079:
13080: @menu
13081: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13082: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13083: @end menu
13084:
13085: See also @ref{Emacs and Gforth}.
13086:
1.126 pazsan 13087: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13088: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13089: @cindex @file{ans-report.fs}
13090: @cindex report the words used in your program
13091: @cindex words used in your program
13092:
13093: If you want to label a Forth program as ANS Forth Program, you must
13094: document which wordsets the program uses; for extension wordsets, it is
13095: helpful to list the words the program requires from these wordsets
13096: (because Forth systems are allowed to provide only some words of them).
13097:
13098: The @file{ans-report.fs} tool makes it easy for you to determine which
13099: words from which wordset and which non-ANS words your application
13100: uses. You simply have to include @file{ans-report.fs} before loading the
13101: program you want to check. After loading your program, you can get the
13102: report with @code{print-ans-report}. A typical use is to run this as
13103: batch job like this:
13104: @example
13105: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13106: @end example
13107:
13108: The output looks like this (for @file{compat/control.fs}):
13109: @example
13110: The program uses the following words
13111: from CORE :
13112: : POSTPONE THEN ; immediate ?dup IF 0=
13113: from BLOCK-EXT :
13114: \
13115: from FILE :
13116: (
13117: @end example
13118:
13119: @subsection Caveats
13120:
13121: Note that @file{ans-report.fs} just checks which words are used, not whether
13122: they are used in an ANS Forth conforming way!
13123:
13124: Some words are defined in several wordsets in the
13125: standard. @file{ans-report.fs} reports them for only one of the
13126: wordsets, and not necessarily the one you expect. It depends on usage
13127: which wordset is the right one to specify. E.g., if you only use the
13128: compilation semantics of @code{S"}, it is a Core word; if you also use
13129: its interpretation semantics, it is a File word.
1.124 anton 13130:
13131:
1.127 anton 13132: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13133: @section Stack depth changes during interpretation
13134: @cindex @file{depth-changes.fs}
13135: @cindex depth changes during interpretation
13136: @cindex stack depth changes during interpretation
13137: @cindex items on the stack after interpretation
13138:
13139: Sometimes you notice that, after loading a file, there are items left
13140: on the stack. The tool @file{depth-changes.fs} helps you find out
13141: quickly where in the file these stack items are coming from.
13142:
13143: The simplest way of using @file{depth-changes.fs} is to include it
13144: before the file(s) you want to check, e.g.:
13145:
13146: @example
13147: gforth depth-changes.fs my-file.fs
13148: @end example
13149:
13150: This will compare the stack depths of the data and FP stack at every
13151: empty line (in interpretation state) against these depths at the last
13152: empty line (in interpretation state). If the depths are not equal,
13153: the position in the file and the stack contents are printed with
13154: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13155: change has occured in the paragraph of non-empty lines before the
13156: indicated line. It is a good idea to leave an empty line at the end
13157: of the file, so the last paragraph is checked, too.
13158:
13159: Checking only at empty lines usually works well, but sometimes you
13160: have big blocks of non-empty lines (e.g., when building a big table),
13161: and you want to know where in this block the stack depth changed. You
13162: can check all interpreted lines with
13163:
13164: @example
13165: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13166: @end example
13167:
13168: This checks the stack depth at every end-of-line. So the depth change
13169: occured in the line reported by the @code{~~} (not in the line
13170: before).
13171:
13172: Note that, while this offers better accuracy in indicating where the
13173: stack depth changes, it will often report many intentional stack depth
13174: changes (e.g., when an interpreted computation stretches across
13175: several lines). You can suppress the checking of some lines by
13176: putting backslashes at the end of these lines (not followed by white
13177: space), and using
13178:
13179: @example
13180: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13181: @end example
1.1 anton 13182:
13183: @c ******************************************************************
1.65 anton 13184: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13185: @chapter ANS conformance
13186: @cindex ANS conformance of Gforth
13187:
13188: To the best of our knowledge, Gforth is an
13189:
13190: ANS Forth System
13191: @itemize @bullet
13192: @item providing the Core Extensions word set
13193: @item providing the Block word set
13194: @item providing the Block Extensions word set
13195: @item providing the Double-Number word set
13196: @item providing the Double-Number Extensions word set
13197: @item providing the Exception word set
13198: @item providing the Exception Extensions word set
13199: @item providing the Facility word set
1.40 anton 13200: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13201: @item providing the File Access word set
13202: @item providing the File Access Extensions word set
13203: @item providing the Floating-Point word set
13204: @item providing the Floating-Point Extensions word set
13205: @item providing the Locals word set
13206: @item providing the Locals Extensions word set
13207: @item providing the Memory-Allocation word set
13208: @item providing the Memory-Allocation Extensions word set (that one's easy)
13209: @item providing the Programming-Tools word set
13210: @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
13211: @item providing the Search-Order word set
13212: @item providing the Search-Order Extensions word set
13213: @item providing the String word set
13214: @item providing the String Extensions word set (another easy one)
13215: @end itemize
13216:
1.118 anton 13217: Gforth has the following environmental restrictions:
13218:
13219: @cindex environmental restrictions
13220: @itemize @bullet
13221: @item
13222: While processing the OS command line, if an exception is not caught,
13223: Gforth exits with a non-zero exit code instyead of performing QUIT.
13224:
13225: @item
13226: When an @code{throw} is performed after a @code{query}, Gforth does not
13227: allways restore the input source specification in effect at the
13228: corresponding catch.
13229:
13230: @end itemize
13231:
13232:
1.1 anton 13233: @cindex system documentation
13234: In addition, ANS Forth systems are required to document certain
13235: implementation choices. This chapter tries to meet these
13236: requirements. In many cases it gives a way to ask the system for the
13237: information instead of providing the information directly, in
13238: particular, if the information depends on the processor, the operating
13239: system or the installation options chosen, or if they are likely to
13240: change during the maintenance of Gforth.
13241:
13242: @comment The framework for the rest has been taken from pfe.
13243:
13244: @menu
13245: * The Core Words::
13246: * The optional Block word set::
13247: * The optional Double Number word set::
13248: * The optional Exception word set::
13249: * The optional Facility word set::
13250: * The optional File-Access word set::
13251: * The optional Floating-Point word set::
13252: * The optional Locals word set::
13253: * The optional Memory-Allocation word set::
13254: * The optional Programming-Tools word set::
13255: * The optional Search-Order word set::
13256: @end menu
13257:
13258:
13259: @c =====================================================================
13260: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13261: @comment node-name, next, previous, up
13262: @section The Core Words
13263: @c =====================================================================
13264: @cindex core words, system documentation
13265: @cindex system documentation, core words
13266:
13267: @menu
13268: * core-idef:: Implementation Defined Options
13269: * core-ambcond:: Ambiguous Conditions
13270: * core-other:: Other System Documentation
13271: @end menu
13272:
13273: @c ---------------------------------------------------------------------
13274: @node core-idef, core-ambcond, The Core Words, The Core Words
13275: @subsection Implementation Defined Options
13276: @c ---------------------------------------------------------------------
13277: @cindex core words, implementation-defined options
13278: @cindex implementation-defined options, core words
13279:
13280:
13281: @table @i
13282: @item (Cell) aligned addresses:
13283: @cindex cell-aligned addresses
13284: @cindex aligned addresses
13285: processor-dependent. Gforth's alignment words perform natural alignment
13286: (e.g., an address aligned for a datum of size 8 is divisible by
13287: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13288:
13289: @item @code{EMIT} and non-graphic characters:
13290: @cindex @code{EMIT} and non-graphic characters
13291: @cindex non-graphic characters and @code{EMIT}
13292: The character is output using the C library function (actually, macro)
13293: @code{putc}.
13294:
13295: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13296: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13297: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13298: @cindex @code{ACCEPT}, editing
13299: @cindex @code{EXPECT}, editing
13300: This is modeled on the GNU readline library (@pxref{Readline
13301: Interaction, , Command Line Editing, readline, The GNU Readline
13302: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13303: producing a full word completion every time you type it (instead of
1.28 crook 13304: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13305:
13306: @item character set:
13307: @cindex character set
13308: The character set of your computer and display device. Gforth is
13309: 8-bit-clean (but some other component in your system may make trouble).
13310:
13311: @item Character-aligned address requirements:
13312: @cindex character-aligned address requirements
13313: installation-dependent. Currently a character is represented by a C
13314: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13315: (Comments on that requested).
13316:
13317: @item character-set extensions and matching of names:
13318: @cindex character-set extensions and matching of names
1.26 crook 13319: @cindex case-sensitivity for name lookup
13320: @cindex name lookup, case-sensitivity
13321: @cindex locale and case-sensitivity
1.21 crook 13322: Any character except the ASCII NUL character can be used in a
1.1 anton 13323: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13324: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13325: function is probably influenced by the locale. E.g., the @code{C} locale
13326: does not know about accents and umlauts, so they are matched
13327: case-sensitively in that locale. For portability reasons it is best to
13328: write programs such that they work in the @code{C} locale. Then one can
13329: use libraries written by a Polish programmer (who might use words
13330: containing ISO Latin-2 encoded characters) and by a French programmer
13331: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13332: funny results for some of the words (which ones, depends on the font you
13333: are using)). Also, the locale you prefer may not be available in other
13334: operating systems. Hopefully, Unicode will solve these problems one day.
13335:
13336: @item conditions under which control characters match a space delimiter:
13337: @cindex space delimiters
13338: @cindex control characters as delimiters
1.117 anton 13339: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13340: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13341: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13342: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13343: interpreter (aka text interpreter) by default, treats all white-space
13344: characters as delimiters.
13345:
1.26 crook 13346: @item format of the control-flow stack:
13347: @cindex control-flow stack, format
13348: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13349: stack item in cells is given by the constant @code{cs-item-size}. At the
13350: time of this writing, an item consists of a (pointer to a) locals list
13351: (third), an address in the code (second), and a tag for identifying the
13352: item (TOS). The following tags are used: @code{defstart},
13353: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13354: @code{scopestart}.
13355:
13356: @item conversion of digits > 35
13357: @cindex digits > 35
13358: The characters @code{[\]^_'} are the digits with the decimal value
13359: 36@minus{}41. There is no way to input many of the larger digits.
13360:
13361: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13362: @cindex @code{EXPECT}, display after end of input
13363: @cindex @code{ACCEPT}, display after end of input
13364: The cursor is moved to the end of the entered string. If the input is
13365: terminated using the @kbd{Return} key, a space is typed.
13366:
13367: @item exception abort sequence of @code{ABORT"}:
13368: @cindex exception abort sequence of @code{ABORT"}
13369: @cindex @code{ABORT"}, exception abort sequence
13370: The error string is stored into the variable @code{"error} and a
13371: @code{-2 throw} is performed.
13372:
13373: @item input line terminator:
13374: @cindex input line terminator
13375: @cindex line terminator on input
1.26 crook 13376: @cindex newline character on input
1.1 anton 13377: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13378: lines. One of these characters is typically produced when you type the
13379: @kbd{Enter} or @kbd{Return} key.
13380:
13381: @item maximum size of a counted string:
13382: @cindex maximum size of a counted string
13383: @cindex counted string, maximum size
13384: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13385: on all platforms, but this may change.
1.1 anton 13386:
13387: @item maximum size of a parsed string:
13388: @cindex maximum size of a parsed string
13389: @cindex parsed string, maximum size
13390: Given by the constant @code{/line}. Currently 255 characters.
13391:
13392: @item maximum size of a definition name, in characters:
13393: @cindex maximum size of a definition name, in characters
13394: @cindex name, maximum length
1.113 anton 13395: MAXU/8
1.1 anton 13396:
13397: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13398: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13399: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13400: MAXU/8
1.1 anton 13401:
13402: @item method of selecting the user input device:
13403: @cindex user input device, method of selecting
13404: The user input device is the standard input. There is currently no way to
13405: change it from within Gforth. However, the input can typically be
13406: redirected in the command line that starts Gforth.
13407:
13408: @item method of selecting the user output device:
13409: @cindex user output device, method of selecting
13410: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13411: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13412: output when the user output device is a terminal, otherwise the output
13413: is buffered.
1.1 anton 13414:
13415: @item methods of dictionary compilation:
13416: What are we expected to document here?
13417:
13418: @item number of bits in one address unit:
13419: @cindex number of bits in one address unit
13420: @cindex address unit, size in bits
13421: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13422: platforms.
1.1 anton 13423:
13424: @item number representation and arithmetic:
13425: @cindex number representation and arithmetic
1.79 anton 13426: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13427:
13428: @item ranges for integer types:
13429: @cindex ranges for integer types
13430: @cindex integer types, ranges
13431: Installation-dependent. Make environmental queries for @code{MAX-N},
13432: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13433: unsigned (and positive) types is 0. The lower bound for signed types on
13434: two's complement and one's complement machines machines can be computed
13435: by adding 1 to the upper bound.
13436:
13437: @item read-only data space regions:
13438: @cindex read-only data space regions
13439: @cindex data-space, read-only regions
13440: The whole Forth data space is writable.
13441:
13442: @item size of buffer at @code{WORD}:
13443: @cindex size of buffer at @code{WORD}
13444: @cindex @code{WORD} buffer size
13445: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13446: shared with the pictured numeric output string. If overwriting
13447: @code{PAD} is acceptable, it is as large as the remaining dictionary
13448: space, although only as much can be sensibly used as fits in a counted
13449: string.
13450:
13451: @item size of one cell in address units:
13452: @cindex cell size
13453: @code{1 cells .}.
13454:
13455: @item size of one character in address units:
13456: @cindex char size
1.79 anton 13457: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13458:
13459: @item size of the keyboard terminal buffer:
13460: @cindex size of the keyboard terminal buffer
13461: @cindex terminal buffer, size
13462: Varies. You can determine the size at a specific time using @code{lp@@
13463: tib - .}. It is shared with the locals stack and TIBs of files that
13464: include the current file. You can change the amount of space for TIBs
13465: and locals stack at Gforth startup with the command line option
13466: @code{-l}.
13467:
13468: @item size of the pictured numeric output buffer:
13469: @cindex size of the pictured numeric output buffer
13470: @cindex pictured numeric output buffer, size
13471: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13472: shared with @code{WORD}.
13473:
13474: @item size of the scratch area returned by @code{PAD}:
13475: @cindex size of the scratch area returned by @code{PAD}
13476: @cindex @code{PAD} size
13477: The remainder of dictionary space. @code{unused pad here - - .}.
13478:
13479: @item system case-sensitivity characteristics:
13480: @cindex case-sensitivity characteristics
1.26 crook 13481: Dictionary searches are case-insensitive (except in
1.1 anton 13482: @code{TABLE}s). However, as explained above under @i{character-set
13483: extensions}, the matching for non-ASCII characters is determined by the
13484: locale you are using. In the default @code{C} locale all non-ASCII
13485: characters are matched case-sensitively.
13486:
13487: @item system prompt:
13488: @cindex system prompt
13489: @cindex prompt
13490: @code{ ok} in interpret state, @code{ compiled} in compile state.
13491:
13492: @item division rounding:
13493: @cindex division rounding
1.166 anton 13494: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13495: division (with the default installation of Gforth). You can check
13496: this with @code{s" floored" environment? drop .}. If you write
13497: programs that need a specific division rounding, best use
13498: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13499:
13500: @item values of @code{STATE} when true:
13501: @cindex @code{STATE} values
13502: -1.
13503:
13504: @item values returned after arithmetic overflow:
13505: On two's complement machines, arithmetic is performed modulo
13506: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13507: arithmetic (with appropriate mapping for signed types). Division by
13508: zero typically results in a @code{-55 throw} (Floating-point
13509: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13510: division overflow can result in these throws, or in @code{-11 throw};
13511: in @code{gforth-fast} division overflow and divide by zero may also
13512: result in returning bogus results without producing an exception.
1.1 anton 13513:
13514: @item whether the current definition can be found after @t{DOES>}:
13515: @cindex @t{DOES>}, visibility of current definition
13516: No.
13517:
13518: @end table
13519:
13520: @c ---------------------------------------------------------------------
13521: @node core-ambcond, core-other, core-idef, The Core Words
13522: @subsection Ambiguous conditions
13523: @c ---------------------------------------------------------------------
13524: @cindex core words, ambiguous conditions
13525: @cindex ambiguous conditions, core words
13526:
13527: @table @i
13528:
13529: @item a name is neither a word nor a number:
13530: @cindex name not found
1.26 crook 13531: @cindex undefined word
1.80 anton 13532: @code{-13 throw} (Undefined word).
1.1 anton 13533:
13534: @item a definition name exceeds the maximum length allowed:
1.26 crook 13535: @cindex word name too long
1.1 anton 13536: @code{-19 throw} (Word name too long)
13537:
13538: @item addressing a region not inside the various data spaces of the forth system:
13539: @cindex Invalid memory address
1.32 anton 13540: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13541: typically readable. Accessing other addresses gives results dependent on
13542: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13543: address).
13544:
13545: @item argument type incompatible with parameter:
1.26 crook 13546: @cindex argument type mismatch
1.1 anton 13547: This is usually not caught. Some words perform checks, e.g., the control
13548: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13549: mismatch).
13550:
13551: @item attempting to obtain the execution token of a word with undefined execution semantics:
13552: @cindex Interpreting a compile-only word, for @code{'} etc.
13553: @cindex execution token of words with undefined execution semantics
13554: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13555: get an execution token for @code{compile-only-error} (which performs a
13556: @code{-14 throw} when executed).
13557:
13558: @item dividing by zero:
13559: @cindex dividing by zero
13560: @cindex floating point unidentified fault, integer division
1.80 anton 13561: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13562: zero); on other systems, this typically results in a @code{-55 throw}
13563: (Floating-point unidentified fault).
1.1 anton 13564:
13565: @item insufficient data stack or return stack space:
13566: @cindex insufficient data stack or return stack space
13567: @cindex stack overflow
1.26 crook 13568: @cindex address alignment exception, stack overflow
1.1 anton 13569: @cindex Invalid memory address, stack overflow
13570: Depending on the operating system, the installation, and the invocation
13571: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13572: it is not checked. If it is checked, you typically get a @code{-3 throw}
13573: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13574: throw} (Invalid memory address) (depending on the platform and how you
13575: achieved the overflow) as soon as the overflow happens. If it is not
13576: checked, overflows typically result in mysterious illegal memory
13577: accesses, producing @code{-9 throw} (Invalid memory address) or
13578: @code{-23 throw} (Address alignment exception); they might also destroy
13579: the internal data structure of @code{ALLOCATE} and friends, resulting in
13580: various errors in these words.
1.1 anton 13581:
13582: @item insufficient space for loop control parameters:
13583: @cindex insufficient space for loop control parameters
1.80 anton 13584: Like other return stack overflows.
1.1 anton 13585:
13586: @item insufficient space in the dictionary:
13587: @cindex insufficient space in the dictionary
13588: @cindex dictionary overflow
1.12 anton 13589: If you try to allot (either directly with @code{allot}, or indirectly
13590: with @code{,}, @code{create} etc.) more memory than available in the
13591: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13592: to access memory beyond the end of the dictionary, the results are
13593: similar to stack overflows.
1.1 anton 13594:
13595: @item interpreting a word with undefined interpretation semantics:
13596: @cindex interpreting a word with undefined interpretation semantics
13597: @cindex Interpreting a compile-only word
13598: For some words, we have defined interpretation semantics. For the
13599: others: @code{-14 throw} (Interpreting a compile-only word).
13600:
13601: @item modifying the contents of the input buffer or a string literal:
13602: @cindex modifying the contents of the input buffer or a string literal
13603: These are located in writable memory and can be modified.
13604:
13605: @item overflow of the pictured numeric output string:
13606: @cindex overflow of the pictured numeric output string
13607: @cindex pictured numeric output string, overflow
1.24 anton 13608: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13609:
13610: @item parsed string overflow:
13611: @cindex parsed string overflow
13612: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13613:
13614: @item producing a result out of range:
13615: @cindex result out of range
13616: On two's complement machines, arithmetic is performed modulo
13617: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13618: arithmetic (with appropriate mapping for signed types). Division by
13619: zero typically results in a @code{-10 throw} (divide by zero) or
13620: @code{-55 throw} (floating point unidentified fault). Overflow on
13621: division may result in these errors or in @code{-11 throw} (result out
13622: of range). @code{Gforth-fast} may silently produce bogus results on
13623: division overflow or division by zero. @code{Convert} and
1.24 anton 13624: @code{>number} currently overflow silently.
1.1 anton 13625:
13626: @item reading from an empty data or return stack:
13627: @cindex stack empty
13628: @cindex stack underflow
1.24 anton 13629: @cindex return stack underflow
1.1 anton 13630: The data stack is checked by the outer (aka text) interpreter after
13631: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13632: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13633: depending on operating system, installation, and invocation. If they are
13634: caught by a check, they typically result in @code{-4 throw} (Stack
13635: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13636: (Invalid memory address), depending on the platform and which stack
13637: underflows and by how much. Note that even if the system uses checking
13638: (through the MMU), your program may have to underflow by a significant
13639: number of stack items to trigger the reaction (the reason for this is
13640: that the MMU, and therefore the checking, works with a page-size
13641: granularity). If there is no checking, the symptoms resulting from an
13642: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13643: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13644: (Invalid memory address) and Illegal Instruction (typically @code{-260
13645: throw}).
1.1 anton 13646:
13647: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13648: @cindex unexpected end of the input buffer
13649: @cindex zero-length string as a name
13650: @cindex Attempt to use zero-length string as a name
13651: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13652: use zero-length string as a name). Words like @code{'} probably will not
13653: find what they search. Note that it is possible to create zero-length
13654: names with @code{nextname} (should it not?).
13655:
13656: @item @code{>IN} greater than input buffer:
13657: @cindex @code{>IN} greater than input buffer
13658: The next invocation of a parsing word returns a string with length 0.
13659:
13660: @item @code{RECURSE} appears after @code{DOES>}:
13661: @cindex @code{RECURSE} appears after @code{DOES>}
13662: Compiles a recursive call to the defining word, not to the defined word.
13663:
13664: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13665: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13666: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13667: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13668: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13669: the end of the file was reached), its source-id may be
13670: reused. Therefore, restoring an input source specification referencing a
13671: closed file may lead to unpredictable results instead of a @code{-12
13672: THROW}.
13673:
13674: In the future, Gforth may be able to restore input source specifications
13675: from other than the current input source.
13676:
13677: @item data space containing definitions gets de-allocated:
13678: @cindex data space containing definitions gets de-allocated
13679: Deallocation with @code{allot} is not checked. This typically results in
13680: memory access faults or execution of illegal instructions.
13681:
13682: @item data space read/write with incorrect alignment:
13683: @cindex data space read/write with incorrect alignment
13684: @cindex alignment faults
1.26 crook 13685: @cindex address alignment exception
1.1 anton 13686: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13687: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13688: alignment turned on, incorrect alignment results in a @code{-9 throw}
13689: (Invalid memory address). There are reportedly some processors with
1.12 anton 13690: alignment restrictions that do not report violations.
1.1 anton 13691:
13692: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13693: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13694: Like other alignment errors.
13695:
13696: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13697: Like other stack underflows.
13698:
13699: @item loop control parameters not available:
13700: @cindex loop control parameters not available
13701: Not checked. The counted loop words simply assume that the top of return
13702: stack items are loop control parameters and behave accordingly.
13703:
13704: @item most recent definition does not have a name (@code{IMMEDIATE}):
13705: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13706: @cindex last word was headerless
13707: @code{abort" last word was headerless"}.
13708:
13709: @item name not defined by @code{VALUE} used by @code{TO}:
13710: @cindex name not defined by @code{VALUE} used by @code{TO}
13711: @cindex @code{TO} on non-@code{VALUE}s
13712: @cindex Invalid name argument, @code{TO}
13713: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13714: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13715:
13716: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13717: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13718: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13719: @code{-13 throw} (Undefined word)
13720:
13721: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13722: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13723: Gforth behaves as if they were of the same type. I.e., you can predict
13724: the behaviour by interpreting all parameters as, e.g., signed.
13725:
13726: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13727: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13728: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13729: compilation semantics of @code{TO}.
13730:
13731: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13732: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13733: @cindex @code{WORD}, string overflow
13734: Not checked. The string will be ok, but the count will, of course,
13735: contain only the least significant bits of the length.
13736:
13737: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13738: @cindex @code{LSHIFT}, large shift counts
13739: @cindex @code{RSHIFT}, large shift counts
13740: Processor-dependent. Typical behaviours are returning 0 and using only
13741: the low bits of the shift count.
13742:
13743: @item word not defined via @code{CREATE}:
13744: @cindex @code{>BODY} of non-@code{CREATE}d words
13745: @code{>BODY} produces the PFA of the word no matter how it was defined.
13746:
13747: @cindex @code{DOES>} of non-@code{CREATE}d words
13748: @code{DOES>} changes the execution semantics of the last defined word no
13749: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13750: @code{CREATE , DOES>}.
13751:
13752: @item words improperly used outside @code{<#} and @code{#>}:
13753: Not checked. As usual, you can expect memory faults.
13754:
13755: @end table
13756:
13757:
13758: @c ---------------------------------------------------------------------
13759: @node core-other, , core-ambcond, The Core Words
13760: @subsection Other system documentation
13761: @c ---------------------------------------------------------------------
13762: @cindex other system documentation, core words
13763: @cindex core words, other system documentation
13764:
13765: @table @i
13766: @item nonstandard words using @code{PAD}:
13767: @cindex @code{PAD} use by nonstandard words
13768: None.
13769:
13770: @item operator's terminal facilities available:
13771: @cindex operator's terminal facilities available
1.80 anton 13772: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13773: and you can give commands to Gforth interactively. The actual facilities
13774: available depend on how you invoke Gforth.
13775:
13776: @item program data space available:
13777: @cindex program data space available
13778: @cindex data space available
13779: @code{UNUSED .} gives the remaining dictionary space. The total
13780: dictionary space can be specified with the @code{-m} switch
13781: (@pxref{Invoking Gforth}) when Gforth starts up.
13782:
13783: @item return stack space available:
13784: @cindex return stack space available
13785: You can compute the total return stack space in cells with
13786: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13787: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13788:
13789: @item stack space available:
13790: @cindex stack space available
13791: You can compute the total data stack space in cells with
13792: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13793: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13794:
13795: @item system dictionary space required, in address units:
13796: @cindex system dictionary space required, in address units
13797: Type @code{here forthstart - .} after startup. At the time of this
13798: writing, this gives 80080 (bytes) on a 32-bit system.
13799: @end table
13800:
13801:
13802: @c =====================================================================
13803: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13804: @section The optional Block word set
13805: @c =====================================================================
13806: @cindex system documentation, block words
13807: @cindex block words, system documentation
13808:
13809: @menu
13810: * block-idef:: Implementation Defined Options
13811: * block-ambcond:: Ambiguous Conditions
13812: * block-other:: Other System Documentation
13813: @end menu
13814:
13815:
13816: @c ---------------------------------------------------------------------
13817: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13818: @subsection Implementation Defined Options
13819: @c ---------------------------------------------------------------------
13820: @cindex implementation-defined options, block words
13821: @cindex block words, implementation-defined options
13822:
13823: @table @i
13824: @item the format for display by @code{LIST}:
13825: @cindex @code{LIST} display format
13826: First the screen number is displayed, then 16 lines of 64 characters,
13827: each line preceded by the line number.
13828:
13829: @item the length of a line affected by @code{\}:
13830: @cindex length of a line affected by @code{\}
13831: @cindex @code{\}, line length in blocks
13832: 64 characters.
13833: @end table
13834:
13835:
13836: @c ---------------------------------------------------------------------
13837: @node block-ambcond, block-other, block-idef, The optional Block word set
13838: @subsection Ambiguous conditions
13839: @c ---------------------------------------------------------------------
13840: @cindex block words, ambiguous conditions
13841: @cindex ambiguous conditions, block words
13842:
13843: @table @i
13844: @item correct block read was not possible:
13845: @cindex block read not possible
13846: Typically results in a @code{throw} of some OS-derived value (between
13847: -512 and -2048). If the blocks file was just not long enough, blanks are
13848: supplied for the missing portion.
13849:
13850: @item I/O exception in block transfer:
13851: @cindex I/O exception in block transfer
13852: @cindex block transfer, I/O exception
13853: Typically results in a @code{throw} of some OS-derived value (between
13854: -512 and -2048).
13855:
13856: @item invalid block number:
13857: @cindex invalid block number
13858: @cindex block number invalid
13859: @code{-35 throw} (Invalid block number)
13860:
13861: @item a program directly alters the contents of @code{BLK}:
13862: @cindex @code{BLK}, altering @code{BLK}
13863: The input stream is switched to that other block, at the same
13864: position. If the storing to @code{BLK} happens when interpreting
13865: non-block input, the system will get quite confused when the block ends.
13866:
13867: @item no current block buffer for @code{UPDATE}:
13868: @cindex @code{UPDATE}, no current block buffer
13869: @code{UPDATE} has no effect.
13870:
13871: @end table
13872:
13873: @c ---------------------------------------------------------------------
13874: @node block-other, , block-ambcond, The optional Block word set
13875: @subsection Other system documentation
13876: @c ---------------------------------------------------------------------
13877: @cindex other system documentation, block words
13878: @cindex block words, other system documentation
13879:
13880: @table @i
13881: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13882: No restrictions (yet).
13883:
13884: @item the number of blocks available for source and data:
13885: depends on your disk space.
13886:
13887: @end table
13888:
13889:
13890: @c =====================================================================
13891: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13892: @section The optional Double Number word set
13893: @c =====================================================================
13894: @cindex system documentation, double words
13895: @cindex double words, system documentation
13896:
13897: @menu
13898: * double-ambcond:: Ambiguous Conditions
13899: @end menu
13900:
13901:
13902: @c ---------------------------------------------------------------------
13903: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13904: @subsection Ambiguous conditions
13905: @c ---------------------------------------------------------------------
13906: @cindex double words, ambiguous conditions
13907: @cindex ambiguous conditions, double words
13908:
13909: @table @i
1.29 crook 13910: @item @i{d} outside of range of @i{n} in @code{D>S}:
13911: @cindex @code{D>S}, @i{d} out of range of @i{n}
13912: The least significant cell of @i{d} is produced.
1.1 anton 13913:
13914: @end table
13915:
13916:
13917: @c =====================================================================
13918: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13919: @section The optional Exception word set
13920: @c =====================================================================
13921: @cindex system documentation, exception words
13922: @cindex exception words, system documentation
13923:
13924: @menu
13925: * exception-idef:: Implementation Defined Options
13926: @end menu
13927:
13928:
13929: @c ---------------------------------------------------------------------
13930: @node exception-idef, , The optional Exception word set, The optional Exception word set
13931: @subsection Implementation Defined Options
13932: @c ---------------------------------------------------------------------
13933: @cindex implementation-defined options, exception words
13934: @cindex exception words, implementation-defined options
13935:
13936: @table @i
13937: @item @code{THROW}-codes used in the system:
13938: @cindex @code{THROW}-codes used in the system
13939: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13940: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13941: codes -512@minus{}-2047 are used for OS errors (for file and memory
13942: allocation operations). The mapping from OS error numbers to throw codes
13943: is -512@minus{}@code{errno}. One side effect of this mapping is that
13944: undefined OS errors produce a message with a strange number; e.g.,
13945: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13946: @end table
13947:
13948: @c =====================================================================
13949: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13950: @section The optional Facility word set
13951: @c =====================================================================
13952: @cindex system documentation, facility words
13953: @cindex facility words, system documentation
13954:
13955: @menu
13956: * facility-idef:: Implementation Defined Options
13957: * facility-ambcond:: Ambiguous Conditions
13958: @end menu
13959:
13960:
13961: @c ---------------------------------------------------------------------
13962: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13963: @subsection Implementation Defined Options
13964: @c ---------------------------------------------------------------------
13965: @cindex implementation-defined options, facility words
13966: @cindex facility words, implementation-defined options
13967:
13968: @table @i
13969: @item encoding of keyboard events (@code{EKEY}):
13970: @cindex keyboard events, encoding in @code{EKEY}
13971: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13972: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13973: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13974: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13975: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13976: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13977:
1.1 anton 13978:
13979: @item duration of a system clock tick:
13980: @cindex duration of a system clock tick
13981: @cindex clock tick duration
13982: System dependent. With respect to @code{MS}, the time is specified in
13983: microseconds. How well the OS and the hardware implement this, is
13984: another question.
13985:
13986: @item repeatability to be expected from the execution of @code{MS}:
13987: @cindex repeatability to be expected from the execution of @code{MS}
13988: @cindex @code{MS}, repeatability to be expected
13989: System dependent. On Unix, a lot depends on load. If the system is
13990: lightly loaded, and the delay is short enough that Gforth does not get
13991: swapped out, the performance should be acceptable. Under MS-DOS and
13992: other single-tasking systems, it should be good.
13993:
13994: @end table
13995:
13996:
13997: @c ---------------------------------------------------------------------
13998: @node facility-ambcond, , facility-idef, The optional Facility word set
13999: @subsection Ambiguous conditions
14000: @c ---------------------------------------------------------------------
14001: @cindex facility words, ambiguous conditions
14002: @cindex ambiguous conditions, facility words
14003:
14004: @table @i
14005: @item @code{AT-XY} can't be performed on user output device:
14006: @cindex @code{AT-XY} can't be performed on user output device
14007: Largely terminal dependent. No range checks are done on the arguments.
14008: No errors are reported. You may see some garbage appearing, you may see
14009: simply nothing happen.
14010:
14011: @end table
14012:
14013:
14014: @c =====================================================================
14015: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14016: @section The optional File-Access word set
14017: @c =====================================================================
14018: @cindex system documentation, file words
14019: @cindex file words, system documentation
14020:
14021: @menu
14022: * file-idef:: Implementation Defined Options
14023: * file-ambcond:: Ambiguous Conditions
14024: @end menu
14025:
14026: @c ---------------------------------------------------------------------
14027: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14028: @subsection Implementation Defined Options
14029: @c ---------------------------------------------------------------------
14030: @cindex implementation-defined options, file words
14031: @cindex file words, implementation-defined options
14032:
14033: @table @i
14034: @item file access methods used:
14035: @cindex file access methods used
14036: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14037: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14038: @code{wb}): The file is cleared, if it exists, and created, if it does
14039: not (with both @code{open-file} and @code{create-file}). Under Unix
14040: @code{create-file} creates a file with 666 permissions modified by your
14041: umask.
14042:
14043: @item file exceptions:
14044: @cindex file exceptions
14045: The file words do not raise exceptions (except, perhaps, memory access
14046: faults when you pass illegal addresses or file-ids).
14047:
14048: @item file line terminator:
14049: @cindex file line terminator
14050: System-dependent. Gforth uses C's newline character as line
14051: terminator. What the actual character code(s) of this are is
14052: system-dependent.
14053:
14054: @item file name format:
14055: @cindex file name format
14056: System dependent. Gforth just uses the file name format of your OS.
14057:
14058: @item information returned by @code{FILE-STATUS}:
14059: @cindex @code{FILE-STATUS}, returned information
14060: @code{FILE-STATUS} returns the most powerful file access mode allowed
14061: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14062: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14063: along with the returned mode.
14064:
14065: @item input file state after an exception when including source:
14066: @cindex exception when including source
14067: All files that are left via the exception are closed.
14068:
1.29 crook 14069: @item @i{ior} values and meaning:
14070: @cindex @i{ior} values and meaning
1.68 anton 14071: @cindex @i{wior} values and meaning
1.29 crook 14072: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14073: intended as throw codes. They typically are in the range
14074: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14075: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14076:
14077: @item maximum depth of file input nesting:
14078: @cindex maximum depth of file input nesting
14079: @cindex file input nesting, maximum depth
14080: limited by the amount of return stack, locals/TIB stack, and the number
14081: of open files available. This should not give you troubles.
14082:
14083: @item maximum size of input line:
14084: @cindex maximum size of input line
14085: @cindex input line size, maximum
14086: @code{/line}. Currently 255.
14087:
14088: @item methods of mapping block ranges to files:
14089: @cindex mapping block ranges to files
14090: @cindex files containing blocks
14091: @cindex blocks in files
14092: By default, blocks are accessed in the file @file{blocks.fb} in the
14093: current working directory. The file can be switched with @code{USE}.
14094:
14095: @item number of string buffers provided by @code{S"}:
14096: @cindex @code{S"}, number of string buffers
14097: 1
14098:
14099: @item size of string buffer used by @code{S"}:
14100: @cindex @code{S"}, size of string buffer
14101: @code{/line}. currently 255.
14102:
14103: @end table
14104:
14105: @c ---------------------------------------------------------------------
14106: @node file-ambcond, , file-idef, The optional File-Access word set
14107: @subsection Ambiguous conditions
14108: @c ---------------------------------------------------------------------
14109: @cindex file words, ambiguous conditions
14110: @cindex ambiguous conditions, file words
14111:
14112: @table @i
14113: @item attempting to position a file outside its boundaries:
14114: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14115: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14116: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14117:
14118: @item attempting to read from file positions not yet written:
14119: @cindex reading from file positions not yet written
14120: End-of-file, i.e., zero characters are read and no error is reported.
14121:
1.29 crook 14122: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14123: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14124: An appropriate exception may be thrown, but a memory fault or other
14125: problem is more probable.
14126:
1.29 crook 14127: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14128: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14129: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14130: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14131: thrown.
14132:
14133: @item named file cannot be opened (@code{INCLUDED}):
14134: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14135: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14136:
14137: @item requesting an unmapped block number:
14138: @cindex unmapped block numbers
14139: There are no unmapped legal block numbers. On some operating systems,
14140: writing a block with a large number may overflow the file system and
14141: have an error message as consequence.
14142:
14143: @item using @code{source-id} when @code{blk} is non-zero:
14144: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14145: @code{source-id} performs its function. Typically it will give the id of
14146: the source which loaded the block. (Better ideas?)
14147:
14148: @end table
14149:
14150:
14151: @c =====================================================================
14152: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14153: @section The optional Floating-Point word set
14154: @c =====================================================================
14155: @cindex system documentation, floating-point words
14156: @cindex floating-point words, system documentation
14157:
14158: @menu
14159: * floating-idef:: Implementation Defined Options
14160: * floating-ambcond:: Ambiguous Conditions
14161: @end menu
14162:
14163:
14164: @c ---------------------------------------------------------------------
14165: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14166: @subsection Implementation Defined Options
14167: @c ---------------------------------------------------------------------
14168: @cindex implementation-defined options, floating-point words
14169: @cindex floating-point words, implementation-defined options
14170:
14171: @table @i
14172: @item format and range of floating point numbers:
14173: @cindex format and range of floating point numbers
14174: @cindex floating point numbers, format and range
14175: System-dependent; the @code{double} type of C.
14176:
1.29 crook 14177: @item results of @code{REPRESENT} when @i{float} is out of range:
14178: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14179: System dependent; @code{REPRESENT} is implemented using the C library
14180: function @code{ecvt()} and inherits its behaviour in this respect.
14181:
14182: @item rounding or truncation of floating-point numbers:
14183: @cindex rounding of floating-point numbers
14184: @cindex truncation of floating-point numbers
14185: @cindex floating-point numbers, rounding or truncation
14186: System dependent; the rounding behaviour is inherited from the hosting C
14187: compiler. IEEE-FP-based (i.e., most) systems by default round to
14188: nearest, and break ties by rounding to even (i.e., such that the last
14189: bit of the mantissa is 0).
14190:
14191: @item size of floating-point stack:
14192: @cindex floating-point stack size
14193: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14194: the floating-point stack (in floats). You can specify this on startup
14195: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14196:
14197: @item width of floating-point stack:
14198: @cindex floating-point stack width
14199: @code{1 floats}.
14200:
14201: @end table
14202:
14203:
14204: @c ---------------------------------------------------------------------
14205: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14206: @subsection Ambiguous conditions
14207: @c ---------------------------------------------------------------------
14208: @cindex floating-point words, ambiguous conditions
14209: @cindex ambiguous conditions, floating-point words
14210:
14211: @table @i
14212: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14213: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14214: System-dependent. Typically results in a @code{-23 THROW} like other
14215: alignment violations.
14216:
14217: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14218: @cindex @code{f@@} used with an address that is not float aligned
14219: @cindex @code{f!} used with an address that is not float aligned
14220: System-dependent. Typically results in a @code{-23 THROW} like other
14221: alignment violations.
14222:
14223: @item floating-point result out of range:
14224: @cindex floating-point result out of range
1.80 anton 14225: System-dependent. Can result in a @code{-43 throw} (floating point
14226: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14227: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14228: unidentified fault), or can produce a special value representing, e.g.,
14229: Infinity.
14230:
14231: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14232: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14233: System-dependent. Typically results in an alignment fault like other
14234: alignment violations.
14235:
1.35 anton 14236: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14237: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14238: The floating-point number is converted into decimal nonetheless.
14239:
14240: @item Both arguments are equal to zero (@code{FATAN2}):
14241: @cindex @code{FATAN2}, both arguments are equal to zero
14242: System-dependent. @code{FATAN2} is implemented using the C library
14243: function @code{atan2()}.
14244:
1.29 crook 14245: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14246: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14247: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14248: because of small errors and the tan will be a very large (or very small)
14249: but finite number.
14250:
1.29 crook 14251: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14252: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14253: The result is rounded to the nearest float.
14254:
14255: @item dividing by zero:
14256: @cindex dividing by zero, floating-point
14257: @cindex floating-point dividing by zero
14258: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14259: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14260: (floating point divide by zero) or @code{-55 throw} (Floating-point
14261: unidentified fault).
1.1 anton 14262:
14263: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14264: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14265: System dependent. On IEEE-FP based systems the number is converted into
14266: an infinity.
14267:
1.29 crook 14268: @item @i{float}<1 (@code{FACOSH}):
14269: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14270: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14271: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14272:
1.29 crook 14273: @item @i{float}=<-1 (@code{FLNP1}):
14274: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14275: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14276: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14277: negative infinity for @i{float}=-1).
1.1 anton 14278:
1.29 crook 14279: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14280: @cindex @code{FLN}, @i{float}=<0
14281: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14282: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14283: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14284: negative infinity for @i{float}=0).
1.1 anton 14285:
1.29 crook 14286: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14287: @cindex @code{FASINH}, @i{float}<0
14288: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14289: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14290: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14291: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14292: C library?).
1.1 anton 14293:
1.29 crook 14294: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14295: @cindex @code{FACOS}, |@i{float}|>1
14296: @cindex @code{FASIN}, |@i{float}|>1
14297: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14298: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14299: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14300:
1.29 crook 14301: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14302: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14303: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14304: Platform-dependent; typically, some double number is produced and no
14305: error is reported.
1.1 anton 14306:
14307: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14308: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14309: @code{Precision} characters of the numeric output area are used. If
14310: @code{precision} is too high, these words will smash the data or code
14311: close to @code{here}.
1.1 anton 14312: @end table
14313:
14314: @c =====================================================================
14315: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14316: @section The optional Locals word set
14317: @c =====================================================================
14318: @cindex system documentation, locals words
14319: @cindex locals words, system documentation
14320:
14321: @menu
14322: * locals-idef:: Implementation Defined Options
14323: * locals-ambcond:: Ambiguous Conditions
14324: @end menu
14325:
14326:
14327: @c ---------------------------------------------------------------------
14328: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14329: @subsection Implementation Defined Options
14330: @c ---------------------------------------------------------------------
14331: @cindex implementation-defined options, locals words
14332: @cindex locals words, implementation-defined options
14333:
14334: @table @i
14335: @item maximum number of locals in a definition:
14336: @cindex maximum number of locals in a definition
14337: @cindex locals, maximum number in a definition
14338: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14339: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14340: characters. The number of locals in a definition is bounded by the size
14341: of locals-buffer, which contains the names of the locals.
14342:
14343: @end table
14344:
14345:
14346: @c ---------------------------------------------------------------------
14347: @node locals-ambcond, , locals-idef, The optional Locals word set
14348: @subsection Ambiguous conditions
14349: @c ---------------------------------------------------------------------
14350: @cindex locals words, ambiguous conditions
14351: @cindex ambiguous conditions, locals words
14352:
14353: @table @i
14354: @item executing a named local in interpretation state:
14355: @cindex local in interpretation state
14356: @cindex Interpreting a compile-only word, for a local
14357: Locals have no interpretation semantics. If you try to perform the
14358: interpretation semantics, you will get a @code{-14 throw} somewhere
14359: (Interpreting a compile-only word). If you perform the compilation
14360: semantics, the locals access will be compiled (irrespective of state).
14361:
1.29 crook 14362: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14363: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14364: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14365: @cindex Invalid name argument, @code{TO}
14366: @code{-32 throw} (Invalid name argument)
14367:
14368: @end table
14369:
14370:
14371: @c =====================================================================
14372: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14373: @section The optional Memory-Allocation word set
14374: @c =====================================================================
14375: @cindex system documentation, memory-allocation words
14376: @cindex memory-allocation words, system documentation
14377:
14378: @menu
14379: * memory-idef:: Implementation Defined Options
14380: @end menu
14381:
14382:
14383: @c ---------------------------------------------------------------------
14384: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14385: @subsection Implementation Defined Options
14386: @c ---------------------------------------------------------------------
14387: @cindex implementation-defined options, memory-allocation words
14388: @cindex memory-allocation words, implementation-defined options
14389:
14390: @table @i
1.29 crook 14391: @item values and meaning of @i{ior}:
14392: @cindex @i{ior} values and meaning
14393: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14394: intended as throw codes. They typically are in the range
14395: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14396: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14397:
14398: @end table
14399:
14400: @c =====================================================================
14401: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14402: @section The optional Programming-Tools word set
14403: @c =====================================================================
14404: @cindex system documentation, programming-tools words
14405: @cindex programming-tools words, system documentation
14406:
14407: @menu
14408: * programming-idef:: Implementation Defined Options
14409: * programming-ambcond:: Ambiguous Conditions
14410: @end menu
14411:
14412:
14413: @c ---------------------------------------------------------------------
14414: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14415: @subsection Implementation Defined Options
14416: @c ---------------------------------------------------------------------
14417: @cindex implementation-defined options, programming-tools words
14418: @cindex programming-tools words, implementation-defined options
14419:
14420: @table @i
14421: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14422: @cindex @code{;CODE} ending sequence
14423: @cindex @code{CODE} ending sequence
14424: @code{END-CODE}
14425:
14426: @item manner of processing input following @code{;CODE} and @code{CODE}:
14427: @cindex @code{;CODE}, processing input
14428: @cindex @code{CODE}, processing input
14429: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14430: the input is processed by the text interpreter, (starting) in interpret
14431: state.
14432:
14433: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14434: @cindex @code{ASSEMBLER}, search order capability
14435: The ANS Forth search order word set.
14436:
14437: @item source and format of display by @code{SEE}:
14438: @cindex @code{SEE}, source and format of output
1.80 anton 14439: The source for @code{see} is the executable code used by the inner
1.1 anton 14440: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14441: (and on some platforms, assembly code for primitives) as well as
14442: possible.
1.1 anton 14443:
14444: @end table
14445:
14446: @c ---------------------------------------------------------------------
14447: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14448: @subsection Ambiguous conditions
14449: @c ---------------------------------------------------------------------
14450: @cindex programming-tools words, ambiguous conditions
14451: @cindex ambiguous conditions, programming-tools words
14452:
14453: @table @i
14454:
1.21 crook 14455: @item deleting the compilation word list (@code{FORGET}):
14456: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14457: Not implemented (yet).
14458:
1.29 crook 14459: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14460: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14461: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14462: @cindex control-flow stack underflow
14463: This typically results in an @code{abort"} with a descriptive error
14464: message (may change into a @code{-22 throw} (Control structure mismatch)
14465: in the future). You may also get a memory access error. If you are
14466: unlucky, this ambiguous condition is not caught.
14467:
1.29 crook 14468: @item @i{name} can't be found (@code{FORGET}):
14469: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14470: Not implemented (yet).
14471:
1.29 crook 14472: @item @i{name} not defined via @code{CREATE}:
14473: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14474: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14475: the execution semantics of the last defined word no matter how it was
14476: defined.
14477:
14478: @item @code{POSTPONE} applied to @code{[IF]}:
14479: @cindex @code{POSTPONE} applied to @code{[IF]}
14480: @cindex @code{[IF]} and @code{POSTPONE}
14481: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14482: equivalent to @code{[IF]}.
14483:
14484: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14485: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14486: Continue in the same state of conditional compilation in the next outer
14487: input source. Currently there is no warning to the user about this.
14488:
14489: @item removing a needed definition (@code{FORGET}):
14490: @cindex @code{FORGET}, removing a needed definition
14491: Not implemented (yet).
14492:
14493: @end table
14494:
14495:
14496: @c =====================================================================
14497: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14498: @section The optional Search-Order word set
14499: @c =====================================================================
14500: @cindex system documentation, search-order words
14501: @cindex search-order words, system documentation
14502:
14503: @menu
14504: * search-idef:: Implementation Defined Options
14505: * search-ambcond:: Ambiguous Conditions
14506: @end menu
14507:
14508:
14509: @c ---------------------------------------------------------------------
14510: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14511: @subsection Implementation Defined Options
14512: @c ---------------------------------------------------------------------
14513: @cindex implementation-defined options, search-order words
14514: @cindex search-order words, implementation-defined options
14515:
14516: @table @i
14517: @item maximum number of word lists in search order:
14518: @cindex maximum number of word lists in search order
14519: @cindex search order, maximum depth
14520: @code{s" wordlists" environment? drop .}. Currently 16.
14521:
14522: @item minimum search order:
14523: @cindex minimum search order
14524: @cindex search order, minimum
14525: @code{root root}.
14526:
14527: @end table
14528:
14529: @c ---------------------------------------------------------------------
14530: @node search-ambcond, , search-idef, The optional Search-Order word set
14531: @subsection Ambiguous conditions
14532: @c ---------------------------------------------------------------------
14533: @cindex search-order words, ambiguous conditions
14534: @cindex ambiguous conditions, search-order words
14535:
14536: @table @i
1.21 crook 14537: @item changing the compilation word list (during compilation):
14538: @cindex changing the compilation word list (during compilation)
14539: @cindex compilation word list, change before definition ends
14540: The word is entered into the word list that was the compilation word list
1.1 anton 14541: at the start of the definition. Any changes to the name field (e.g.,
14542: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14543: are applied to the latest defined word (as reported by @code{latest} or
14544: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14545:
14546: @item search order empty (@code{previous}):
14547: @cindex @code{previous}, search order empty
1.26 crook 14548: @cindex vocstack empty, @code{previous}
1.1 anton 14549: @code{abort" Vocstack empty"}.
14550:
14551: @item too many word lists in search order (@code{also}):
14552: @cindex @code{also}, too many word lists in search order
1.26 crook 14553: @cindex vocstack full, @code{also}
1.1 anton 14554: @code{abort" Vocstack full"}.
14555:
14556: @end table
14557:
14558: @c ***************************************************************
1.65 anton 14559: @node Standard vs Extensions, Model, ANS conformance, Top
14560: @chapter Should I use Gforth extensions?
14561: @cindex Gforth extensions
14562:
14563: As you read through the rest of this manual, you will see documentation
14564: for @i{Standard} words, and documentation for some appealing Gforth
14565: @i{extensions}. You might ask yourself the question: @i{``Should I
14566: restrict myself to the standard, or should I use the extensions?''}
14567:
14568: The answer depends on the goals you have for the program you are working
14569: on:
14570:
14571: @itemize @bullet
14572:
14573: @item Is it just for yourself or do you want to share it with others?
14574:
14575: @item
14576: If you want to share it, do the others all use Gforth?
14577:
14578: @item
14579: If it is just for yourself, do you want to restrict yourself to Gforth?
14580:
14581: @end itemize
14582:
14583: If restricting the program to Gforth is ok, then there is no reason not
14584: to use extensions. It is still a good idea to keep to the standard
14585: where it is easy, in case you want to reuse these parts in another
14586: program that you want to be portable.
14587:
14588: If you want to be able to port the program to other Forth systems, there
14589: are the following points to consider:
14590:
14591: @itemize @bullet
14592:
14593: @item
14594: Most Forth systems that are being maintained support the ANS Forth
14595: standard. So if your program complies with the standard, it will be
14596: portable among many systems.
14597:
14598: @item
14599: A number of the Gforth extensions can be implemented in ANS Forth using
14600: public-domain files provided in the @file{compat/} directory. These are
14601: mentioned in the text in passing. There is no reason not to use these
14602: extensions, your program will still be ANS Forth compliant; just include
14603: the appropriate compat files with your program.
14604:
14605: @item
14606: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14607: analyse your program and determine what non-Standard words it relies
14608: upon. However, it does not check whether you use standard words in a
14609: non-standard way.
14610:
14611: @item
14612: Some techniques are not standardized by ANS Forth, and are hard or
14613: impossible to implement in a standard way, but can be implemented in
14614: most Forth systems easily, and usually in similar ways (e.g., accessing
14615: word headers). Forth has a rich historical precedent for programmers
14616: taking advantage of implementation-dependent features of their tools
14617: (for example, relying on a knowledge of the dictionary
14618: structure). Sometimes these techniques are necessary to extract every
14619: last bit of performance from the hardware, sometimes they are just a
14620: programming shorthand.
14621:
14622: @item
14623: Does using a Gforth extension save more work than the porting this part
14624: to other Forth systems (if any) will cost?
14625:
14626: @item
14627: Is the additional functionality worth the reduction in portability and
14628: the additional porting problems?
14629:
14630: @end itemize
14631:
14632: In order to perform these consideratios, you need to know what's
14633: standard and what's not. This manual generally states if something is
1.81 anton 14634: non-standard, but the authoritative source is the
14635: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14636: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14637: into the thought processes of the technical committee.
14638:
14639: Note also that portability between Forth systems is not the only
14640: portability issue; there is also the issue of portability between
14641: different platforms (processor/OS combinations).
14642:
14643: @c ***************************************************************
14644: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14645: @chapter Model
14646:
14647: This chapter has yet to be written. It will contain information, on
14648: which internal structures you can rely.
14649:
14650: @c ***************************************************************
14651: @node Integrating Gforth, Emacs and Gforth, Model, Top
14652: @chapter Integrating Gforth into C programs
14653:
14654: This is not yet implemented.
14655:
14656: Several people like to use Forth as scripting language for applications
14657: that are otherwise written in C, C++, or some other language.
14658:
14659: The Forth system ATLAST provides facilities for embedding it into
14660: applications; unfortunately it has several disadvantages: most
14661: importantly, it is not based on ANS Forth, and it is apparently dead
14662: (i.e., not developed further and not supported). The facilities
1.21 crook 14663: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14664: making the switch should not be hard.
14665:
14666: We also tried to design the interface such that it can easily be
14667: implemented by other Forth systems, so that we may one day arrive at a
14668: standardized interface. Such a standard interface would allow you to
14669: replace the Forth system without having to rewrite C code.
14670:
14671: You embed the Gforth interpreter by linking with the library
14672: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14673: global symbols in this library that belong to the interface, have the
14674: prefix @code{forth_}. (Global symbols that are used internally have the
14675: prefix @code{gforth_}).
14676:
14677: You can include the declarations of Forth types and the functions and
14678: variables of the interface with @code{#include <forth.h>}.
14679:
14680: Types.
14681:
14682: Variables.
14683:
14684: Data and FP Stack pointer. Area sizes.
14685:
14686: functions.
14687:
14688: forth_init(imagefile)
14689: forth_evaluate(string) exceptions?
14690: forth_goto(address) (or forth_execute(xt)?)
14691: forth_continue() (a corountining mechanism)
14692:
14693: Adding primitives.
14694:
14695: No checking.
14696:
14697: Signals?
14698:
14699: Accessing the Stacks
14700:
1.26 crook 14701: @c ******************************************************************
1.1 anton 14702: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14703: @chapter Emacs and Gforth
14704: @cindex Emacs and Gforth
14705:
14706: @cindex @file{gforth.el}
14707: @cindex @file{forth.el}
14708: @cindex Rydqvist, Goran
1.107 dvdkhlng 14709: @cindex Kuehling, David
1.1 anton 14710: @cindex comment editing commands
14711: @cindex @code{\}, editing with Emacs
14712: @cindex debug tracer editing commands
14713: @cindex @code{~~}, removal with Emacs
14714: @cindex Forth mode in Emacs
1.107 dvdkhlng 14715:
1.1 anton 14716: Gforth comes with @file{gforth.el}, an improved version of
14717: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14718: improvements are:
14719:
14720: @itemize @bullet
14721: @item
1.107 dvdkhlng 14722: A better handling of indentation.
14723: @item
14724: A custom hilighting engine for Forth-code.
1.26 crook 14725: @item
14726: Comment paragraph filling (@kbd{M-q})
14727: @item
14728: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14729: @item
14730: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14731: @item
14732: Support of the @code{info-lookup} feature for looking up the
14733: documentation of a word.
1.107 dvdkhlng 14734: @item
14735: Support for reading and writing blocks files.
1.26 crook 14736: @end itemize
14737:
1.107 dvdkhlng 14738: To get a basic description of these features, enter Forth mode and
14739: type @kbd{C-h m}.
1.1 anton 14740:
14741: @cindex source location of error or debugging output in Emacs
14742: @cindex error output, finding the source location in Emacs
14743: @cindex debugging output, finding the source location in Emacs
14744: In addition, Gforth supports Emacs quite well: The source code locations
14745: given in error messages, debugging output (from @code{~~}) and failed
14746: assertion messages are in the right format for Emacs' compilation mode
14747: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14748: Manual}) so the source location corresponding to an error or other
14749: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14750: @kbd{C-c C-c} for the error under the cursor).
14751:
1.107 dvdkhlng 14752: @cindex viewing the documentation of a word in Emacs
14753: @cindex context-sensitive help
14754: Moreover, for words documented in this manual, you can look up the
14755: glossary entry quickly by using @kbd{C-h TAB}
14756: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14757: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14758: later and does not work for words containing @code{:}.
14759:
14760: @menu
14761: * Installing gforth.el:: Making Emacs aware of Forth.
14762: * Emacs Tags:: Viewing the source of a word in Emacs.
14763: * Hilighting:: Making Forth code look prettier.
14764: * Auto-Indentation:: Customizing auto-indentation.
14765: * Blocks Files:: Reading and writing blocks files.
14766: @end menu
14767:
14768: @c ----------------------------------
1.109 anton 14769: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14770: @section Installing gforth.el
14771: @cindex @file{.emacs}
14772: @cindex @file{gforth.el}, installation
14773: To make the features from @file{gforth.el} available in Emacs, add
14774: the following lines to your @file{.emacs} file:
14775:
14776: @example
14777: (autoload 'forth-mode "gforth.el")
14778: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14779: auto-mode-alist))
14780: (autoload 'forth-block-mode "gforth.el")
14781: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14782: auto-mode-alist))
14783: (add-hook 'forth-mode-hook (function (lambda ()
14784: ;; customize variables here:
14785: (setq forth-indent-level 4)
14786: (setq forth-minor-indent-level 2)
14787: (setq forth-hilight-level 3)
14788: ;;; ...
14789: )))
14790: @end example
14791:
14792: @c ----------------------------------
14793: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14794: @section Emacs Tags
1.1 anton 14795: @cindex @file{TAGS} file
14796: @cindex @file{etags.fs}
14797: @cindex viewing the source of a word in Emacs
1.43 anton 14798: @cindex @code{require}, placement in files
14799: @cindex @code{include}, placement in files
1.107 dvdkhlng 14800: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14801: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14802: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14803: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14804: several tags files at the same time (e.g., one for the Gforth sources
14805: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14806: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14807: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14808: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14809: with @file{etags.fs}, you should avoid putting definitions both before
14810: and after @code{require} etc., otherwise you will see the same file
14811: visited several times by commands like @code{tags-search}.
1.1 anton 14812:
1.107 dvdkhlng 14813: @c ----------------------------------
14814: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14815: @section Hilighting
14816: @cindex hilighting Forth code in Emacs
14817: @cindex highlighting Forth code in Emacs
14818: @file{gforth.el} comes with a custom source hilighting engine. When
14819: you open a file in @code{forth-mode}, it will be completely parsed,
14820: assigning faces to keywords, comments, strings etc. While you edit
14821: the file, modified regions get parsed and updated on-the-fly.
14822:
14823: Use the variable `forth-hilight-level' to change the level of
14824: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14825: you set the hilighting level to 0, the parser will still work in the
14826: background, collecting information about whether regions of text are
14827: ``compiled'' or ``interpreted''. Those information are required for
14828: auto-indentation to work properly. Set `forth-disable-parser' to
14829: non-nil if your computer is too slow to handle parsing. This will
14830: have an impact on the smartness of the auto-indentation engine,
14831: though.
14832:
14833: Sometimes Forth sources define new features that should be hilighted,
14834: new control structures, defining-words etc. You can use the variable
14835: `forth-custom-words' to make @code{forth-mode} hilight additional
14836: words and constructs. See the docstring of `forth-words' for details
14837: (in Emacs, type @kbd{C-h v forth-words}).
14838:
14839: `forth-custom-words' is meant to be customized in your
14840: @file{.emacs} file. To customize hilighing in a file-specific manner,
14841: set `forth-local-words' in a local-variables section at the end of
14842: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14843:
14844: Example:
14845: @example
14846: 0 [IF]
14847: Local Variables:
14848: forth-local-words:
14849: ((("t:") definition-starter (font-lock-keyword-face . 1)
14850: "[ \t\n]" t name (font-lock-function-name-face . 3))
14851: ((";t") definition-ender (font-lock-keyword-face . 1)))
14852: End:
14853: [THEN]
14854: @end example
14855:
14856: @c ----------------------------------
14857: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14858: @section Auto-Indentation
14859: @cindex auto-indentation of Forth code in Emacs
14860: @cindex indentation of Forth code in Emacs
14861: @code{forth-mode} automatically tries to indent lines in a smart way,
14862: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14863:
14864: Simple customization can be achieved by setting
14865: `forth-indent-level' and `forth-minor-indent-level' in your
14866: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14867: per default by multiples of 4 columns. To use the more traditional
14868: 3-column indentation, add the following lines to your @file{.emacs}:
14869:
14870: @example
14871: (add-hook 'forth-mode-hook (function (lambda ()
14872: ;; customize variables here:
14873: (setq forth-indent-level 3)
14874: (setq forth-minor-indent-level 1)
14875: )))
14876: @end example
14877:
14878: If you want indentation to recognize non-default words, customize it
14879: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14880: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14881: v forth-indent-words}).
14882:
14883: To customize indentation in a file-specific manner, set
14884: `forth-local-indent-words' in a local-variables section at the end of
14885: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14886: Emacs Manual}).
14887:
14888: Example:
14889: @example
14890: 0 [IF]
14891: Local Variables:
14892: forth-local-indent-words:
14893: ((("t:") (0 . 2) (0 . 2))
14894: ((";t") (-2 . 0) (0 . -2)))
14895: End:
14896: [THEN]
14897: @end example
14898:
14899: @c ----------------------------------
1.109 anton 14900: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14901: @section Blocks Files
14902: @cindex blocks files, use with Emacs
14903: @code{forth-mode} Autodetects blocks files by checking whether the
14904: length of the first line exceeds 1023 characters. It then tries to
14905: convert the file into normal text format. When you save the file, it
14906: will be written to disk as normal stream-source file.
14907:
14908: If you want to write blocks files, use @code{forth-blocks-mode}. It
14909: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14910:
1.107 dvdkhlng 14911: @itemize @bullet
14912: @item
14913: Files are written to disk in blocks file format.
14914: @item
14915: Screen numbers are displayed in the mode line (enumerated beginning
14916: with the value of `forth-block-base')
14917: @item
14918: Warnings are displayed when lines exceed 64 characters.
14919: @item
14920: The beginning of the currently edited block is marked with an
14921: overlay-arrow.
14922: @end itemize
1.41 anton 14923:
1.107 dvdkhlng 14924: There are some restrictions you should be aware of. When you open a
14925: blocks file that contains tabulator or newline characters, these
14926: characters will be translated into spaces when the file is written
14927: back to disk. If tabs or newlines are encountered during blocks file
14928: reading, an error is output to the echo area. So have a look at the
14929: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14930:
1.107 dvdkhlng 14931: Please consult the docstring of @code{forth-blocks-mode} for more
14932: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14933:
1.26 crook 14934: @c ******************************************************************
1.1 anton 14935: @node Image Files, Engine, Emacs and Gforth, Top
14936: @chapter Image Files
1.26 crook 14937: @cindex image file
14938: @cindex @file{.fi} files
1.1 anton 14939: @cindex precompiled Forth code
14940: @cindex dictionary in persistent form
14941: @cindex persistent form of dictionary
14942:
14943: An image file is a file containing an image of the Forth dictionary,
14944: i.e., compiled Forth code and data residing in the dictionary. By
14945: convention, we use the extension @code{.fi} for image files.
14946:
14947: @menu
1.18 anton 14948: * Image Licensing Issues:: Distribution terms for images.
14949: * Image File Background:: Why have image files?
1.67 anton 14950: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14951: * Data-Relocatable Image Files:: are better.
1.67 anton 14952: * Fully Relocatable Image Files:: better yet.
1.18 anton 14953: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14954: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14955: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14956: @end menu
14957:
1.18 anton 14958: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14959: @section Image Licensing Issues
14960: @cindex license for images
14961: @cindex image license
14962:
14963: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14964: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14965: original image; i.e., according to copyright law it is a derived work of
14966: the original image.
14967:
14968: Since Gforth is distributed under the GNU GPL, the newly created image
14969: falls under the GNU GPL, too. In particular, this means that if you
14970: distribute the image, you have to make all of the sources for the image
1.113 anton 14971: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14972: GNU General Public License (Section 3)}.
14973:
14974: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14975: contains only code compiled from the sources you gave it; if none of
14976: these sources is under the GPL, the terms discussed above do not apply
14977: to the image. However, if your image needs an engine (a gforth binary)
14978: that is under the GPL, you should make sure that you distribute both in
14979: a way that is at most a @emph{mere aggregation}, if you don't want the
14980: terms of the GPL to apply to the image.
14981:
14982: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14983: @section Image File Background
14984: @cindex image file background
14985:
1.80 anton 14986: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14987: definitions written in Forth. Since the Forth compiler itself belongs to
14988: those definitions, it is not possible to start the system with the
1.80 anton 14989: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14990: code as an image file in nearly executable form. When Gforth starts up,
14991: a C routine loads the image file into memory, optionally relocates the
14992: addresses, then sets up the memory (stacks etc.) according to
14993: information in the image file, and (finally) starts executing Forth
14994: code.
1.1 anton 14995:
14996: The image file variants represent different compromises between the
14997: goals of making it easy to generate image files and making them
14998: portable.
14999:
15000: @cindex relocation at run-time
1.26 crook 15001: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15002: run-time. This avoids many of the complications discussed below (image
15003: files are data relocatable without further ado), but costs performance
15004: (one addition per memory access).
15005:
15006: @cindex relocation at load-time
1.26 crook 15007: By contrast, the Gforth loader performs relocation at image load time. The
15008: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15009: appropriate code-field addresses (or code addresses in the case of
15010: direct threading).
15011:
15012: There are three kinds of image files, with different degrees of
15013: relocatability: non-relocatable, data-relocatable, and fully relocatable
15014: image files.
15015:
15016: @cindex image file loader
15017: @cindex relocating loader
15018: @cindex loader for image files
15019: These image file variants have several restrictions in common; they are
15020: caused by the design of the image file loader:
15021:
15022: @itemize @bullet
15023: @item
15024: There is only one segment; in particular, this means, that an image file
15025: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15026: them). The contents of the stacks are not represented, either.
1.1 anton 15027:
15028: @item
15029: The only kinds of relocation supported are: adding the same offset to
15030: all cells that represent data addresses; and replacing special tokens
15031: with code addresses or with pieces of machine code.
15032:
15033: If any complex computations involving addresses are performed, the
15034: results cannot be represented in the image file. Several applications that
15035: use such computations come to mind:
15036: @itemize @minus
15037: @item
15038: Hashing addresses (or data structures which contain addresses) for table
15039: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15040: purpose, you will have no problem, because the hash tables are
15041: recomputed automatically when the system is started. If you use your own
15042: hash tables, you will have to do something similar.
15043:
15044: @item
15045: There's a cute implementation of doubly-linked lists that uses
15046: @code{XOR}ed addresses. You could represent such lists as singly-linked
15047: in the image file, and restore the doubly-linked representation on
15048: startup.@footnote{In my opinion, though, you should think thrice before
15049: using a doubly-linked list (whatever implementation).}
15050:
15051: @item
15052: The code addresses of run-time routines like @code{docol:} cannot be
15053: represented in the image file (because their tokens would be replaced by
15054: machine code in direct threaded implementations). As a workaround,
15055: compute these addresses at run-time with @code{>code-address} from the
15056: executions tokens of appropriate words (see the definitions of
1.80 anton 15057: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15058:
15059: @item
15060: On many architectures addresses are represented in machine code in some
15061: shifted or mangled form. You cannot put @code{CODE} words that contain
15062: absolute addresses in this form in a relocatable image file. Workarounds
15063: are representing the address in some relative form (e.g., relative to
15064: the CFA, which is present in some register), or loading the address from
15065: a place where it is stored in a non-mangled form.
15066: @end itemize
15067: @end itemize
15068:
15069: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15070: @section Non-Relocatable Image Files
15071: @cindex non-relocatable image files
1.26 crook 15072: @cindex image file, non-relocatable
1.1 anton 15073:
15074: These files are simple memory dumps of the dictionary. They are specific
15075: to the executable (i.e., @file{gforth} file) they were created
15076: with. What's worse, they are specific to the place on which the
15077: dictionary resided when the image was created. Now, there is no
15078: guarantee that the dictionary will reside at the same place the next
15079: time you start Gforth, so there's no guarantee that a non-relocatable
15080: image will work the next time (Gforth will complain instead of crashing,
15081: though).
15082:
15083: You can create a non-relocatable image file with
15084:
1.44 crook 15085:
1.1 anton 15086: doc-savesystem
15087:
1.44 crook 15088:
1.1 anton 15089: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15090: @section Data-Relocatable Image Files
15091: @cindex data-relocatable image files
1.26 crook 15092: @cindex image file, data-relocatable
1.1 anton 15093:
15094: These files contain relocatable data addresses, but fixed code addresses
15095: (instead of tokens). They are specific to the executable (i.e.,
15096: @file{gforth} file) they were created with. For direct threading on some
15097: architectures (e.g., the i386), data-relocatable images do not work. You
15098: get a data-relocatable image, if you use @file{gforthmi} with a
15099: Gforth binary that is not doubly indirect threaded (@pxref{Fully
15100: Relocatable Image Files}).
15101:
15102: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15103: @section Fully Relocatable Image Files
15104: @cindex fully relocatable image files
1.26 crook 15105: @cindex image file, fully relocatable
1.1 anton 15106:
15107: @cindex @file{kern*.fi}, relocatability
15108: @cindex @file{gforth.fi}, relocatability
15109: These image files have relocatable data addresses, and tokens for code
15110: addresses. They can be used with different binaries (e.g., with and
15111: without debugging) on the same machine, and even across machines with
15112: the same data formats (byte order, cell size, floating point
15113: format). However, they are usually specific to the version of Gforth
15114: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
15115: are fully relocatable.
15116:
15117: There are two ways to create a fully relocatable image file:
15118:
15119: @menu
1.29 crook 15120: * gforthmi:: The normal way
1.1 anton 15121: * cross.fs:: The hard way
15122: @end menu
15123:
15124: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15125: @subsection @file{gforthmi}
15126: @cindex @file{comp-i.fs}
15127: @cindex @file{gforthmi}
15128:
15129: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15130: image @i{file} that contains everything you would load by invoking
15131: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15132: @example
1.29 crook 15133: gforthmi @i{file} @i{options}
1.1 anton 15134: @end example
15135:
15136: E.g., if you want to create an image @file{asm.fi} that has the file
15137: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15138: like this:
15139:
15140: @example
15141: gforthmi asm.fi asm.fs
15142: @end example
15143:
1.27 crook 15144: @file{gforthmi} is implemented as a sh script and works like this: It
15145: produces two non-relocatable images for different addresses and then
15146: compares them. Its output reflects this: first you see the output (if
1.62 crook 15147: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15148: files, then you see the output of the comparing program: It displays the
15149: offset used for data addresses and the offset used for code addresses;
1.1 anton 15150: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15151: image files, it displays a line like this:
1.1 anton 15152:
15153: @example
15154: 78DC BFFFFA50 BFFFFA40
15155: @end example
15156:
15157: This means that at offset $78dc from @code{forthstart}, one input image
15158: contains $bffffa50, and the other contains $bffffa40. Since these cells
15159: cannot be represented correctly in the output image, you should examine
15160: these places in the dictionary and verify that these cells are dead
15161: (i.e., not read before they are written).
1.39 anton 15162:
15163: @cindex --application, @code{gforthmi} option
15164: If you insert the option @code{--application} in front of the image file
15165: name, you will get an image that uses the @code{--appl-image} option
15166: instead of the @code{--image-file} option (@pxref{Invoking
15167: Gforth}). When you execute such an image on Unix (by typing the image
15168: name as command), the Gforth engine will pass all options to the image
15169: instead of trying to interpret them as engine options.
1.1 anton 15170:
1.27 crook 15171: If you type @file{gforthmi} with no arguments, it prints some usage
15172: instructions.
15173:
1.1 anton 15174: @cindex @code{savesystem} during @file{gforthmi}
15175: @cindex @code{bye} during @file{gforthmi}
15176: @cindex doubly indirect threaded code
1.44 crook 15177: @cindex environment variables
15178: @cindex @code{GFORTHD} -- environment variable
15179: @cindex @code{GFORTH} -- environment variable
1.1 anton 15180: @cindex @code{gforth-ditc}
1.29 crook 15181: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 15182: words @code{savesystem} and @code{bye} must be visible. A special doubly
15183: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 15184: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 15185: this executable through the environment variable @code{GFORTHD}
15186: (default: @file{gforth-ditc}); if you pass a version that is not doubly
15187: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 15188: data-relocatable image (because there is no code address offset). The
15189: normal @file{gforth} executable is used for creating the relocatable
15190: image; you can pass the exact filename of this executable through the
15191: environment variable @code{GFORTH}.
1.1 anton 15192:
15193: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15194: @subsection @file{cross.fs}
15195: @cindex @file{cross.fs}
15196: @cindex cross-compiler
15197: @cindex metacompiler
1.47 crook 15198: @cindex target compiler
1.1 anton 15199:
15200: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15201: programming language (@pxref{Cross Compiler}).
1.1 anton 15202:
1.47 crook 15203: @code{cross} allows you to create image files for machines with
1.1 anton 15204: different data sizes and data formats than the one used for generating
15205: the image file. You can also use it to create an application image that
15206: does not contain a Forth compiler. These features are bought with
15207: restrictions and inconveniences in programming. E.g., addresses have to
15208: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15209: order to make the code relocatable.
15210:
15211:
15212: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15213: @section Stack and Dictionary Sizes
15214: @cindex image file, stack and dictionary sizes
15215: @cindex dictionary size default
15216: @cindex stack size default
15217:
15218: If you invoke Gforth with a command line flag for the size
15219: (@pxref{Invoking Gforth}), the size you specify is stored in the
15220: dictionary. If you save the dictionary with @code{savesystem} or create
15221: an image with @file{gforthmi}, this size will become the default
15222: for the resulting image file. E.g., the following will create a
1.21 crook 15223: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15224:
15225: @example
15226: gforthmi gforth.fi -m 1M
15227: @end example
15228:
15229: In other words, if you want to set the default size for the dictionary
15230: and the stacks of an image, just invoke @file{gforthmi} with the
15231: appropriate options when creating the image.
15232:
15233: @cindex stack size, cache-friendly
15234: Note: For cache-friendly behaviour (i.e., good performance), you should
15235: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15236: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15237: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15238:
15239: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15240: @section Running Image Files
15241: @cindex running image files
15242: @cindex invoking image files
15243: @cindex image file invocation
15244:
15245: @cindex -i, invoke image file
15246: @cindex --image file, invoke image file
1.29 crook 15247: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15248: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15249: @example
1.29 crook 15250: gforth -i @i{image}
1.1 anton 15251: @end example
15252:
15253: @cindex executable image file
1.26 crook 15254: @cindex image file, executable
1.1 anton 15255: If your operating system supports starting scripts with a line of the
15256: form @code{#! ...}, you just have to type the image file name to start
15257: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15258: just a convention). I.e., to run Gforth with the image file @i{image},
15259: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15260: This works because every @code{.fi} file starts with a line of this
15261: format:
15262:
15263: @example
15264: #! /usr/local/bin/gforth-0.4.0 -i
15265: @end example
15266:
15267: The file and pathname for the Gforth engine specified on this line is
15268: the specific Gforth executable that it was built against; i.e. the value
15269: of the environment variable @code{GFORTH} at the time that
15270: @file{gforthmi} was executed.
1.1 anton 15271:
1.27 crook 15272: You can make use of the same shell capability to make a Forth source
15273: file into an executable. For example, if you place this text in a file:
1.26 crook 15274:
15275: @example
15276: #! /usr/local/bin/gforth
15277:
15278: ." Hello, world" CR
15279: bye
15280: @end example
15281:
15282: @noindent
1.27 crook 15283: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15284: directly from the command line. The sequence @code{#!} is used in two
15285: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15286: system@footnote{The Unix kernel actually recognises two types of files:
15287: executable files and files of data, where the data is processed by an
15288: interpreter that is specified on the ``interpreter line'' -- the first
15289: line of the file, starting with the sequence #!. There may be a small
15290: limit (e.g., 32) on the number of characters that may be specified on
15291: the interpreter line.} secondly it is treated as a comment character by
15292: Gforth. Because of the second usage, a space is required between
1.80 anton 15293: @code{#!} and the path to the executable (moreover, some Unixes
15294: require the sequence @code{#! /}).
1.27 crook 15295:
15296: The disadvantage of this latter technique, compared with using
1.80 anton 15297: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15298: compiled on-the-fly, each time the program is invoked.
1.26 crook 15299:
1.1 anton 15300: doc-#!
15301:
1.44 crook 15302:
1.1 anton 15303: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15304: @section Modifying the Startup Sequence
15305: @cindex startup sequence for image file
15306: @cindex image file initialization sequence
15307: @cindex initialization sequence of image file
15308:
1.120 anton 15309: You can add your own initialization to the startup sequence of an image
15310: through the deferred word @code{'cold}. @code{'cold} is invoked just
15311: before the image-specific command line processing (i.e., loading files
15312: and evaluating (@code{-e}) strings) starts.
1.1 anton 15313:
15314: A sequence for adding your initialization usually looks like this:
15315:
15316: @example
15317: :noname
15318: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15319: ... \ your stuff
15320: ; IS 'cold
15321: @end example
15322:
1.157 anton 15323: After @code{'cold}, Gforth processes the image options
15324: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15325: another deferred word. This normally prints Gforth's startup message
15326: and does nothing else.
15327:
1.1 anton 15328: @cindex turnkey image files
1.26 crook 15329: @cindex image file, turnkey applications
1.157 anton 15330: So, if you want to make a turnkey image (i.e., an image for an
15331: application instead of an extended Forth system), you can do this in
15332: two ways:
15333:
15334: @itemize @bullet
15335:
15336: @item
15337: If you want to do your interpretation of the OS command-line
15338: arguments, hook into @code{'cold}. In that case you probably also
15339: want to build the image with @code{gforthmi --application}
15340: (@pxref{gforthmi}) to keep the engine from processing OS command line
15341: options. You can then do your own command-line processing with
15342: @code{next-arg}
15343:
15344: @item
15345: If you want to have the normal Gforth processing of OS command-line
15346: arguments, hook into @code{bootmessage}.
15347:
15348: @end itemize
15349:
15350: In either case, you probably do not want the word that you execute in
15351: these hooks to exit normally, but use @code{bye} or @code{throw}.
15352: Otherwise the Gforth startup process would continue and eventually
15353: present the Forth command line to the user.
1.26 crook 15354:
15355: doc-'cold
1.157 anton 15356: doc-bootmessage
1.44 crook 15357:
1.1 anton 15358: @c ******************************************************************
1.113 anton 15359: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15360: @chapter Engine
15361: @cindex engine
15362: @cindex virtual machine
15363:
1.26 crook 15364: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15365: may be helpful for finding your way in the Gforth sources.
15366:
1.109 anton 15367: The ideas in this section have also been published in the following
15368: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15369: Forth-Tagung '93; M. Anton Ertl,
15370: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15371: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15372: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15373: Threaded code variations and optimizations (extended version)}},
15374: Forth-Tagung '02.
1.1 anton 15375:
15376: @menu
15377: * Portability::
15378: * Threading::
15379: * Primitives::
15380: * Performance::
15381: @end menu
15382:
15383: @node Portability, Threading, Engine, Engine
15384: @section Portability
15385: @cindex engine portability
15386:
1.26 crook 15387: An important goal of the Gforth Project is availability across a wide
15388: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15389: achieved this goal by manually coding the engine in assembly language
15390: for several then-popular processors. This approach is very
15391: labor-intensive and the results are short-lived due to progress in
15392: computer architecture.
1.1 anton 15393:
15394: @cindex C, using C for the engine
15395: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15396: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15397: particularly popular for UNIX-based Forths due to the large variety of
15398: architectures of UNIX machines. Unfortunately an implementation in C
15399: does not mix well with the goals of efficiency and with using
15400: traditional techniques: Indirect or direct threading cannot be expressed
15401: in C, and switch threading, the fastest technique available in C, is
15402: significantly slower. Another problem with C is that it is very
15403: cumbersome to express double integer arithmetic.
15404:
15405: @cindex GNU C for the engine
15406: @cindex long long
15407: Fortunately, there is a portable language that does not have these
15408: limitations: GNU C, the version of C processed by the GNU C compiler
15409: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15410: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15411: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15412: threading possible, its @code{long long} type (@pxref{Long Long, ,
15413: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15414: double numbers on many systems. GNU C is freely available on all
1.1 anton 15415: important (and many unimportant) UNIX machines, VMS, 80386s running
15416: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15417: on all these machines.
15418:
15419: Writing in a portable language has the reputation of producing code that
15420: is slower than assembly. For our Forth engine we repeatedly looked at
15421: the code produced by the compiler and eliminated most compiler-induced
15422: inefficiencies by appropriate changes in the source code.
15423:
15424: @cindex explicit register declarations
15425: @cindex --enable-force-reg, configuration flag
15426: @cindex -DFORCE_REG
15427: However, register allocation cannot be portably influenced by the
15428: programmer, leading to some inefficiencies on register-starved
15429: machines. We use explicit register declarations (@pxref{Explicit Reg
15430: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15431: improve the speed on some machines. They are turned on by using the
15432: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15433: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15434: machine, but also on the compiler version: On some machines some
15435: compiler versions produce incorrect code when certain explicit register
15436: declarations are used. So by default @code{-DFORCE_REG} is not used.
15437:
15438: @node Threading, Primitives, Portability, Engine
15439: @section Threading
15440: @cindex inner interpreter implementation
15441: @cindex threaded code implementation
15442:
15443: @cindex labels as values
15444: GNU C's labels as values extension (available since @code{gcc-2.0},
15445: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15446: makes it possible to take the address of @i{label} by writing
15447: @code{&&@i{label}}. This address can then be used in a statement like
15448: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15449: @code{goto x}.
15450:
1.26 crook 15451: @cindex @code{NEXT}, indirect threaded
1.1 anton 15452: @cindex indirect threaded inner interpreter
15453: @cindex inner interpreter, indirect threaded
1.26 crook 15454: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15455: @example
15456: cfa = *ip++;
15457: ca = *cfa;
15458: goto *ca;
15459: @end example
15460: @cindex instruction pointer
15461: For those unfamiliar with the names: @code{ip} is the Forth instruction
15462: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15463: execution token and points to the code field of the next word to be
15464: executed; The @code{ca} (code address) fetched from there points to some
15465: executable code, e.g., a primitive or the colon definition handler
15466: @code{docol}.
15467:
1.26 crook 15468: @cindex @code{NEXT}, direct threaded
1.1 anton 15469: @cindex direct threaded inner interpreter
15470: @cindex inner interpreter, direct threaded
15471: Direct threading is even simpler:
15472: @example
15473: ca = *ip++;
15474: goto *ca;
15475: @end example
15476:
15477: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15478: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15479:
15480: @menu
15481: * Scheduling::
15482: * Direct or Indirect Threaded?::
1.109 anton 15483: * Dynamic Superinstructions::
1.1 anton 15484: * DOES>::
15485: @end menu
15486:
15487: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15488: @subsection Scheduling
15489: @cindex inner interpreter optimization
15490:
15491: There is a little complication: Pipelined and superscalar processors,
15492: i.e., RISC and some modern CISC machines can process independent
15493: instructions while waiting for the results of an instruction. The
15494: compiler usually reorders (schedules) the instructions in a way that
15495: achieves good usage of these delay slots. However, on our first tries
15496: the compiler did not do well on scheduling primitives. E.g., for
15497: @code{+} implemented as
15498: @example
15499: n=sp[0]+sp[1];
15500: sp++;
15501: sp[0]=n;
15502: NEXT;
15503: @end example
1.81 anton 15504: the @code{NEXT} comes strictly after the other code, i.e., there is
15505: nearly no scheduling. After a little thought the problem becomes clear:
15506: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15507: addresses (and the version of @code{gcc} we used would not know it even
15508: if it was possible), so it could not move the load of the cfa above the
15509: store to the TOS. Indeed the pointers could be the same, if code on or
15510: very near the top of stack were executed. In the interest of speed we
15511: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15512: in scheduling: @code{NEXT} is divided into several parts:
15513: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15514: like:
1.1 anton 15515: @example
1.81 anton 15516: NEXT_P0;
1.1 anton 15517: n=sp[0]+sp[1];
15518: sp++;
15519: NEXT_P1;
15520: sp[0]=n;
15521: NEXT_P2;
15522: @end example
15523:
1.81 anton 15524: There are various schemes that distribute the different operations of
15525: NEXT between these parts in several ways; in general, different schemes
15526: perform best on different processors. We use a scheme for most
15527: architectures that performs well for most processors of this
1.109 anton 15528: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15529: the scheme on installation time.
15530:
1.1 anton 15531:
1.109 anton 15532: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15533: @subsection Direct or Indirect Threaded?
15534: @cindex threading, direct or indirect?
15535:
1.109 anton 15536: Threaded forth code consists of references to primitives (simple machine
15537: code routines like @code{+}) and to non-primitives (e.g., colon
15538: definitions, variables, constants); for a specific class of
15539: non-primitives (e.g., variables) there is one code routine (e.g.,
15540: @code{dovar}), but each variable needs a separate reference to its data.
15541:
15542: Traditionally Forth has been implemented as indirect threaded code,
15543: because this allows to use only one cell to reference a non-primitive
15544: (basically you point to the data, and find the code address there).
15545:
15546: @cindex primitive-centric threaded code
15547: However, threaded code in Gforth (since 0.6.0) uses two cells for
15548: non-primitives, one for the code address, and one for the data address;
15549: the data pointer is an immediate argument for the virtual machine
15550: instruction represented by the code address. We call this
15551: @emph{primitive-centric} threaded code, because all code addresses point
15552: to simple primitives. E.g., for a variable, the code address is for
15553: @code{lit} (also used for integer literals like @code{99}).
15554:
15555: Primitive-centric threaded code allows us to use (faster) direct
15556: threading as dispatch method, completely portably (direct threaded code
15557: in Gforth before 0.6.0 required architecture-specific code). It also
15558: eliminates the performance problems related to I-cache consistency that
15559: 386 implementations have with direct threaded code, and allows
15560: additional optimizations.
15561:
15562: @cindex hybrid direct/indirect threaded code
15563: There is a catch, however: the @var{xt} parameter of @code{execute} can
15564: occupy only one cell, so how do we pass non-primitives with their code
15565: @emph{and} data addresses to them? Our answer is to use indirect
15566: threaded dispatch for @code{execute} and other words that use a
15567: single-cell xt. So, normal threaded code in colon definitions uses
15568: direct threading, and @code{execute} and similar words, which dispatch
15569: to xts on the data stack, use indirect threaded code. We call this
15570: @emph{hybrid direct/indirect} threaded code.
15571:
15572: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15573: @cindex gforth engine
15574: @cindex gforth-fast engine
15575: The engines @command{gforth} and @command{gforth-fast} use hybrid
15576: direct/indirect threaded code. This means that with these engines you
15577: cannot use @code{,} to compile an xt. Instead, you have to use
15578: @code{compile,}.
15579:
15580: @cindex gforth-itc engine
1.115 anton 15581: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15582: This engine uses plain old indirect threaded code. It still compiles in
15583: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15584: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15585: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15586: and execute @code{' , is compile,}. Your program can check if it is
15587: running on a hybrid direct/indirect threaded engine or a pure indirect
15588: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15589:
15590:
15591: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15592: @subsection Dynamic Superinstructions
15593: @cindex Dynamic superinstructions with replication
15594: @cindex Superinstructions
15595: @cindex Replication
15596:
15597: The engines @command{gforth} and @command{gforth-fast} use another
15598: optimization: Dynamic superinstructions with replication. As an
15599: example, consider the following colon definition:
15600:
15601: @example
15602: : squared ( n1 -- n2 )
15603: dup * ;
15604: @end example
15605:
15606: Gforth compiles this into the threaded code sequence
15607:
15608: @example
15609: dup
15610: *
15611: ;s
15612: @end example
15613:
15614: In normal direct threaded code there is a code address occupying one
15615: cell for each of these primitives. Each code address points to a
15616: machine code routine, and the interpreter jumps to this machine code in
15617: order to execute the primitive. The routines for these three
15618: primitives are (in @command{gforth-fast} on the 386):
15619:
15620: @example
15621: Code dup
15622: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15623: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15624: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15625: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15626: end-code
15627: Code *
15628: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15629: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15630: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15631: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15632: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15633: end-code
15634: Code ;s
15635: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15636: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15637: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15638: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15639: end-code
15640: @end example
15641:
15642: With dynamic superinstructions and replication the compiler does not
15643: just lay down the threaded code, but also copies the machine code
15644: fragments, usually without the jump at the end.
15645:
15646: @example
15647: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15648: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15649: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15650: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15651: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15652: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15653: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15654: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15655: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15656: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15657: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15658: @end example
15659:
15660: Only when a threaded-code control-flow change happens (e.g., in
15661: @code{;s}), the jump is appended. This optimization eliminates many of
15662: these jumps and makes the rest much more predictable. The speedup
15663: depends on the processor and the application; on the Athlon and Pentium
15664: III this optimization typically produces a speedup by a factor of 2.
15665:
15666: The code addresses in the direct-threaded code are set to point to the
15667: appropriate points in the copied machine code, in this example like
15668: this:
1.1 anton 15669:
1.109 anton 15670: @example
15671: primitive code address
15672: dup $4057D27D
15673: * $4057D286
15674: ;s $4057D292
15675: @end example
15676:
15677: Thus there can be threaded-code jumps to any place in this piece of
15678: code. This also simplifies decompilation quite a bit.
15679:
15680: @cindex --no-dynamic command-line option
15681: @cindex --no-super command-line option
15682: You can disable this optimization with @option{--no-dynamic}. You can
15683: use the copying without eliminating the jumps (i.e., dynamic
15684: replication, but without superinstructions) with @option{--no-super};
15685: this gives the branch prediction benefit alone; the effect on
1.110 anton 15686: performance depends on the CPU; on the Athlon and Pentium III the
15687: speedup is a little less than for dynamic superinstructions with
15688: replication.
15689:
15690: @cindex patching threaded code
15691: One use of these options is if you want to patch the threaded code.
15692: With superinstructions, many of the dispatch jumps are eliminated, so
15693: patching often has no effect. These options preserve all the dispatch
15694: jumps.
1.109 anton 15695:
15696: @cindex --dynamic command-line option
1.110 anton 15697: On some machines dynamic superinstructions are disabled by default,
15698: because it is unsafe on these machines. However, if you feel
15699: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15700:
15701: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15702: @subsection DOES>
15703: @cindex @code{DOES>} implementation
15704:
1.26 crook 15705: @cindex @code{dodoes} routine
15706: @cindex @code{DOES>}-code
1.1 anton 15707: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15708: the chunk of code executed by every word defined by a
1.109 anton 15709: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15710: this is only needed if the xt of the word is @code{execute}d. The main
15711: problem here is: How to find the Forth code to be executed, i.e. the
15712: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15713: solutions:
1.1 anton 15714:
1.21 crook 15715: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15716: @code{DOES>}-code address is stored in the cell after the code address
15717: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15718: illegal in the Forth-79 and all later standards, because in fig-Forth
15719: this address lies in the body (which is illegal in these
15720: standards). However, by making the code field larger for all words this
15721: solution becomes legal again. We use this approach. Leaving a cell
15722: unused in most words is a bit wasteful, but on the machines we are
15723: targeting this is hardly a problem.
15724:
1.1 anton 15725:
15726: @node Primitives, Performance, Threading, Engine
15727: @section Primitives
15728: @cindex primitives, implementation
15729: @cindex virtual machine instructions, implementation
15730:
15731: @menu
15732: * Automatic Generation::
15733: * TOS Optimization::
15734: * Produced code::
15735: @end menu
15736:
15737: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15738: @subsection Automatic Generation
15739: @cindex primitives, automatic generation
15740:
15741: @cindex @file{prims2x.fs}
1.109 anton 15742:
1.1 anton 15743: Since the primitives are implemented in a portable language, there is no
15744: longer any need to minimize the number of primitives. On the contrary,
15745: having many primitives has an advantage: speed. In order to reduce the
15746: number of errors in primitives and to make programming them easier, we
1.109 anton 15747: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15748: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15749: generates most (and sometimes all) of the C code for a primitive from
15750: the stack effect notation. The source for a primitive has the following
15751: form:
1.1 anton 15752:
15753: @cindex primitive source format
15754: @format
1.58 anton 15755: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15756: [@code{""}@i{glossary entry}@code{""}]
15757: @i{C code}
1.1 anton 15758: [@code{:}
1.29 crook 15759: @i{Forth code}]
1.1 anton 15760: @end format
15761:
15762: The items in brackets are optional. The category and glossary fields
15763: are there for generating the documentation, the Forth code is there
15764: for manual implementations on machines without GNU C. E.g., the source
15765: for the primitive @code{+} is:
15766: @example
1.58 anton 15767: + ( n1 n2 -- n ) core plus
1.1 anton 15768: n = n1+n2;
15769: @end example
15770:
15771: This looks like a specification, but in fact @code{n = n1+n2} is C
15772: code. Our primitive generation tool extracts a lot of information from
15773: the stack effect notations@footnote{We use a one-stack notation, even
15774: though we have separate data and floating-point stacks; The separate
15775: notation can be generated easily from the unified notation.}: The number
15776: of items popped from and pushed on the stack, their type, and by what
15777: name they are referred to in the C code. It then generates a C code
15778: prelude and postlude for each primitive. The final C code for @code{+}
15779: looks like this:
15780:
15781: @example
1.46 pazsan 15782: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15783: /* */ /* documentation */
1.81 anton 15784: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15785: @{
15786: DEF_CA /* definition of variable ca (indirect threading) */
15787: Cell n1; /* definitions of variables */
15788: Cell n2;
15789: Cell n;
1.81 anton 15790: NEXT_P0; /* NEXT part 0 */
1.1 anton 15791: n1 = (Cell) sp[1]; /* input */
15792: n2 = (Cell) TOS;
15793: sp += 1; /* stack adjustment */
15794: @{
15795: n = n1+n2; /* C code taken from the source */
15796: @}
15797: NEXT_P1; /* NEXT part 1 */
15798: TOS = (Cell)n; /* output */
15799: NEXT_P2; /* NEXT part 2 */
15800: @}
15801: @end example
15802:
15803: This looks long and inefficient, but the GNU C compiler optimizes quite
15804: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15805: HP RISC machines: Defining the @code{n}s does not produce any code, and
15806: using them as intermediate storage also adds no cost.
15807:
1.26 crook 15808: There are also other optimizations that are not illustrated by this
15809: example: assignments between simple variables are usually for free (copy
1.1 anton 15810: propagation). If one of the stack items is not used by the primitive
15811: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15812: (dead code elimination). On the other hand, there are some things that
15813: the compiler does not do, therefore they are performed by
15814: @file{prims2x.fs}: The compiler does not optimize code away that stores
15815: a stack item to the place where it just came from (e.g., @code{over}).
15816:
15817: While programming a primitive is usually easy, there are a few cases
15818: where the programmer has to take the actions of the generator into
15819: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15820: fall through to @code{NEXT}.
1.109 anton 15821:
15822: For more information
1.1 anton 15823:
15824: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15825: @subsection TOS Optimization
15826: @cindex TOS optimization for primitives
15827: @cindex primitives, keeping the TOS in a register
15828:
15829: An important optimization for stack machine emulators, e.g., Forth
15830: engines, is keeping one or more of the top stack items in
1.29 crook 15831: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15832: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15833: @itemize @bullet
15834: @item
1.29 crook 15835: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15836: due to fewer loads from and stores to the stack.
1.29 crook 15837: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15838: @i{y<n}, due to additional moves between registers.
1.1 anton 15839: @end itemize
15840:
15841: @cindex -DUSE_TOS
15842: @cindex -DUSE_NO_TOS
15843: In particular, keeping one item in a register is never a disadvantage,
15844: if there are enough registers. Keeping two items in registers is a
15845: disadvantage for frequent words like @code{?branch}, constants,
15846: variables, literals and @code{i}. Therefore our generator only produces
15847: code that keeps zero or one items in registers. The generated C code
15848: covers both cases; the selection between these alternatives is made at
15849: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15850: code for @code{+} is just a simple variable name in the one-item case,
15851: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15852: GNU C compiler tries to keep simple variables like @code{TOS} in
15853: registers, and it usually succeeds, if there are enough registers.
15854:
15855: @cindex -DUSE_FTOS
15856: @cindex -DUSE_NO_FTOS
15857: The primitive generator performs the TOS optimization for the
15858: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15859: operations the benefit of this optimization is even larger:
15860: floating-point operations take quite long on most processors, but can be
15861: performed in parallel with other operations as long as their results are
15862: not used. If the FP-TOS is kept in a register, this works. If
15863: it is kept on the stack, i.e., in memory, the store into memory has to
15864: wait for the result of the floating-point operation, lengthening the
15865: execution time of the primitive considerably.
15866:
15867: The TOS optimization makes the automatic generation of primitives a
15868: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15869: @code{TOS} is not sufficient. There are some special cases to
15870: consider:
15871: @itemize @bullet
15872: @item In the case of @code{dup ( w -- w w )} the generator must not
15873: eliminate the store to the original location of the item on the stack,
15874: if the TOS optimization is turned on.
15875: @item Primitives with stack effects of the form @code{--}
1.29 crook 15876: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15877: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15878: must load the TOS from the stack at the end. But for the null stack
15879: effect @code{--} no stores or loads should be generated.
15880: @end itemize
15881:
15882: @node Produced code, , TOS Optimization, Primitives
15883: @subsection Produced code
15884: @cindex primitives, assembly code listing
15885:
15886: @cindex @file{engine.s}
15887: To see what assembly code is produced for the primitives on your machine
15888: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15889: look at the resulting file @file{engine.s}. Alternatively, you can also
15890: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15891:
15892: @node Performance, , Primitives, Engine
15893: @section Performance
15894: @cindex performance of some Forth interpreters
15895: @cindex engine performance
15896: @cindex benchmarking Forth systems
15897: @cindex Gforth performance
15898:
15899: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15900: impossible to write a significantly faster threaded-code engine.
1.1 anton 15901:
15902: On register-starved machines like the 386 architecture processors
15903: improvements are possible, because @code{gcc} does not utilize the
15904: registers as well as a human, even with explicit register declarations;
15905: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15906: and hand-tuned it for the 486; this system is 1.19 times faster on the
15907: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15908: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15909: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15910: registers fit in real registers (and we can even afford to use the TOS
15911: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15912: earlier results. And dynamic superinstructions provide another speedup
15913: (but only around a factor 1.2 on the 486).
1.1 anton 15914:
15915: @cindex Win32Forth performance
15916: @cindex NT Forth performance
15917: @cindex eforth performance
15918: @cindex ThisForth performance
15919: @cindex PFE performance
15920: @cindex TILE performance
1.81 anton 15921: The potential advantage of assembly language implementations is not
1.112 anton 15922: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15923: (direct threaded, compiled with @code{gcc-2.95.1} and
15924: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15925: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15926: (with and without peephole (aka pinhole) optimization of the threaded
15927: code); all these systems were written in assembly language. We also
15928: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15929: with @code{gcc-2.6.3} with the default configuration for Linux:
15930: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15931: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15932: employs peephole optimization of the threaded code) and TILE (compiled
15933: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15934: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15935: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15936: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15937: then extended it to run the benchmarks, added the peephole optimizer,
15938: ran the benchmarks and reported the results.
1.40 anton 15939:
1.1 anton 15940: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15941: matrix multiplication come from the Stanford integer benchmarks and have
15942: been translated into Forth by Martin Fraeman; we used the versions
15943: included in the TILE Forth package, but with bigger data set sizes; and
15944: a recursive Fibonacci number computation for benchmarking calling
15945: performance. The following table shows the time taken for the benchmarks
15946: scaled by the time taken by Gforth (in other words, it shows the speedup
15947: factor that Gforth achieved over the other systems).
15948:
15949: @example
1.112 anton 15950: relative Win32- NT eforth This-
15951: time Gforth Forth Forth eforth +opt PFE Forth TILE
15952: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15953: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15954: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15955: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15956: @end example
15957:
1.26 crook 15958: You may be quite surprised by the good performance of Gforth when
15959: compared with systems written in assembly language. One important reason
15960: for the disappointing performance of these other systems is probably
15961: that they are not written optimally for the 486 (e.g., they use the
15962: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15963: but costly method for relocating the Forth image: like @code{cforth}, it
15964: computes the actual addresses at run time, resulting in two address
15965: computations per @code{NEXT} (@pxref{Image File Background}).
15966:
1.1 anton 15967: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15968: explained with the self-imposed restriction of the latter systems to
15969: standard C, which makes efficient threading impossible (however, the
1.4 anton 15970: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15971: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15972: Moreover, current C compilers have a hard time optimizing other aspects
15973: of the ThisForth and the TILE source.
15974:
1.26 crook 15975: The performance of Gforth on 386 architecture processors varies widely
15976: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15977: allocate any of the virtual machine registers into real machine
15978: registers by itself and would not work correctly with explicit register
1.112 anton 15979: declarations, giving a significantly slower engine (on a 486DX2/66
15980: running the Sieve) than the one measured above.
1.1 anton 15981:
1.26 crook 15982: Note that there have been several releases of Win32Forth since the
15983: release presented here, so the results presented above may have little
1.40 anton 15984: predictive value for the performance of Win32Forth today (results for
15985: the current release on an i486DX2/66 are welcome).
1.1 anton 15986:
15987: @cindex @file{Benchres}
1.66 anton 15988: In
15989: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15990: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15991: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15992: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15993: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15994: than the version used here. You can find a newer version of these
15995: measurements at
1.47 crook 15996: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15997: find numbers for Gforth on various machines in @file{Benchres}.
15998:
1.26 crook 15999: @c ******************************************************************
1.113 anton 16000: @c @node Binding to System Library, Cross Compiler, Engine, Top
16001: @c @chapter Binding to System Library
1.13 pazsan 16002:
1.113 anton 16003: @c ****************************************************************
16004: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16005: @chapter Cross Compiler
1.47 crook 16006: @cindex @file{cross.fs}
16007: @cindex cross-compiler
16008: @cindex metacompiler
16009: @cindex target compiler
1.13 pazsan 16010:
1.46 pazsan 16011: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16012: mostly written in Forth, including crucial parts like the outer
16013: interpreter and compiler, it needs compiled Forth code to get
16014: started. The cross compiler allows to create new images for other
16015: architectures, even running under another Forth system.
1.13 pazsan 16016:
16017: @menu
1.67 anton 16018: * Using the Cross Compiler::
16019: * How the Cross Compiler Works::
1.13 pazsan 16020: @end menu
16021:
1.21 crook 16022: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16023: @section Using the Cross Compiler
1.46 pazsan 16024:
16025: The cross compiler uses a language that resembles Forth, but isn't. The
16026: main difference is that you can execute Forth code after definition,
16027: while you usually can't execute the code compiled by cross, because the
16028: code you are compiling is typically for a different computer than the
16029: one you are compiling on.
16030:
1.81 anton 16031: @c anton: This chapter is somewhat different from waht I would expect: I
16032: @c would expect an explanation of the cross language and how to create an
16033: @c application image with it. The section explains some aspects of
16034: @c creating a Gforth kernel.
16035:
1.46 pazsan 16036: The Makefile is already set up to allow you to create kernels for new
16037: architectures with a simple make command. The generic kernels using the
16038: GCC compiled virtual machine are created in the normal build process
16039: with @code{make}. To create a embedded Gforth executable for e.g. the
16040: 8086 processor (running on a DOS machine), type
16041:
16042: @example
16043: make kernl-8086.fi
16044: @end example
16045:
16046: This will use the machine description from the @file{arch/8086}
16047: directory to create a new kernel. A machine file may look like that:
16048:
16049: @example
16050: \ Parameter for target systems 06oct92py
16051:
16052: 4 Constant cell \ cell size in bytes
16053: 2 Constant cell<< \ cell shift to bytes
16054: 5 Constant cell>bit \ cell shift to bits
16055: 8 Constant bits/char \ bits per character
16056: 8 Constant bits/byte \ bits per byte [default: 8]
16057: 8 Constant float \ bytes per float
16058: 8 Constant /maxalign \ maximum alignment in bytes
16059: false Constant bigendian \ byte order
16060: ( true=big, false=little )
16061:
16062: include machpc.fs \ feature list
16063: @end example
16064:
16065: This part is obligatory for the cross compiler itself, the feature list
16066: is used by the kernel to conditionally compile some features in and out,
16067: depending on whether the target supports these features.
16068:
16069: There are some optional features, if you define your own primitives,
16070: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16071: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16072: @code{prims-include} includes primitives, and @code{>boot} prepares for
16073: booting.
16074:
16075: @example
16076: : asm-include ." Include assembler" cr
16077: s" arch/8086/asm.fs" included ;
16078:
16079: : prims-include ." Include primitives" cr
16080: s" arch/8086/prim.fs" included ;
16081:
16082: : >boot ." Prepare booting" cr
16083: s" ' boot >body into-forth 1+ !" evaluate ;
16084: @end example
16085:
16086: These words are used as sort of macro during the cross compilation in
1.81 anton 16087: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16088: be possible --- but more complicated --- to write a new kernel project
16089: file, too.
16090:
16091: @file{kernel/main.fs} expects the machine description file name on the
16092: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16093: @code{mach-file} leaves a counted string on the stack, or
16094: @code{machine-file} leaves an address, count pair of the filename on the
16095: stack.
16096:
16097: The feature list is typically controlled using @code{SetValue}, generic
16098: files that are used by several projects can use @code{DefaultValue}
16099: instead. Both functions work like @code{Value}, when the value isn't
16100: defined, but @code{SetValue} works like @code{to} if the value is
16101: defined, and @code{DefaultValue} doesn't set anything, if the value is
16102: defined.
16103:
16104: @example
16105: \ generic mach file for pc gforth 03sep97jaw
16106:
16107: true DefaultValue NIL \ relocating
16108:
16109: >ENVIRON
16110:
16111: true DefaultValue file \ controls the presence of the
16112: \ file access wordset
16113: true DefaultValue OS \ flag to indicate a operating system
16114:
16115: true DefaultValue prims \ true: primitives are c-code
16116:
16117: true DefaultValue floating \ floating point wordset is present
16118:
16119: true DefaultValue glocals \ gforth locals are present
16120: \ will be loaded
16121: true DefaultValue dcomps \ double number comparisons
16122:
16123: true DefaultValue hash \ hashing primitives are loaded/present
16124:
16125: true DefaultValue xconds \ used together with glocals,
16126: \ special conditionals supporting gforths'
16127: \ local variables
16128: true DefaultValue header \ save a header information
16129:
16130: true DefaultValue backtrace \ enables backtrace code
16131:
16132: false DefaultValue ec
16133: false DefaultValue crlf
16134:
16135: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16136:
16137: &16 KB DefaultValue stack-size
16138: &15 KB &512 + DefaultValue fstack-size
16139: &15 KB DefaultValue rstack-size
16140: &14 KB &512 + DefaultValue lstack-size
16141: @end example
1.13 pazsan 16142:
1.48 anton 16143: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16144: @section How the Cross Compiler Works
1.13 pazsan 16145:
16146: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16147: @appendix Bugs
1.1 anton 16148: @cindex bug reporting
16149:
1.21 crook 16150: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16151:
1.103 anton 16152: If you find a bug, please submit a bug report through
16153: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16154:
16155: @itemize @bullet
16156: @item
1.81 anton 16157: A program (or a sequence of keyboard commands) that reproduces the bug.
16158: @item
16159: A description of what you think constitutes the buggy behaviour.
16160: @item
1.21 crook 16161: The Gforth version used (it is announced at the start of an
16162: interactive Gforth session).
16163: @item
16164: The machine and operating system (on Unix
16165: systems @code{uname -a} will report this information).
16166: @item
1.81 anton 16167: The installation options (you can find the configure options at the
16168: start of @file{config.status}) and configuration (@code{configure}
16169: output or @file{config.cache}).
1.21 crook 16170: @item
16171: A complete list of changes (if any) you (or your installer) have made to the
16172: Gforth sources.
16173: @end itemize
1.1 anton 16174:
16175: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16176: to Report Bugs, gcc.info, GNU C Manual}.
16177:
16178:
1.21 crook 16179: @node Origin, Forth-related information, Bugs, Top
16180: @appendix Authors and Ancestors of Gforth
1.1 anton 16181:
16182: @section Authors and Contributors
16183: @cindex authors of Gforth
16184: @cindex contributors to Gforth
16185:
16186: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16187: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16188: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16189: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16190: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16191: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16192: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16193: working on automatic support for calling C libraries. Helpful comments
16194: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16195: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16196: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16197: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16198: comments from many others; thank you all, sorry for not listing you
16199: here (but digging through my mailbox to extract your names is on my
16200: to-do list).
1.1 anton 16201:
16202: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16203: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16204: was developed across the Internet, and its authors did not meet
1.20 pazsan 16205: physically for the first 4 years of development.
1.1 anton 16206:
16207: @section Pedigree
1.26 crook 16208: @cindex pedigree of Gforth
1.1 anton 16209:
1.81 anton 16210: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16211: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16212:
1.20 pazsan 16213: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16214: 32 bit native code version of VolksForth for the Atari ST, written
16215: mostly by Dietrich Weineck.
16216:
1.81 anton 16217: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16218: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16219: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16220:
1.147 anton 16221: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16222: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16223:
16224: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16225: 1979. Robert Selzer and Bill Ragsdale developed the original
16226: implementation of fig-Forth for the 6502 based on microForth.
16227:
16228: The principal architect of microForth was Dean Sanderson. microForth was
16229: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16230: the 1802, and subsequently implemented on the 8080, the 6800 and the
16231: Z80.
16232:
16233: All earlier Forth systems were custom-made, usually by Charles Moore,
16234: who discovered (as he puts it) Forth during the late 60s. The first full
16235: Forth existed in 1971.
16236:
1.81 anton 16237: A part of the information in this section comes from
16238: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16239: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16240: Charles H. Moore, presented at the HOPL-II conference and preprinted
16241: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16242: genealogical information about Forth there. For a more general (and
16243: graphical) Forth family tree look see
16244: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16245: Forth Family Tree and Timeline}.
1.1 anton 16246:
1.81 anton 16247: @c ------------------------------------------------------------------
1.113 anton 16248: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16249: @appendix Other Forth-related information
16250: @cindex Forth-related information
16251:
1.81 anton 16252: @c anton: I threw most of this stuff out, because it can be found through
16253: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16254:
16255: @cindex comp.lang.forth
16256: @cindex frequently asked questions
1.81 anton 16257: There is an active news group (comp.lang.forth) discussing Forth
16258: (including Gforth) and Forth-related issues. Its
16259: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16260: (frequently asked questions and their answers) contains a lot of
16261: information on Forth. You should read it before posting to
16262: comp.lang.forth.
1.21 crook 16263:
1.81 anton 16264: The ANS Forth standard is most usable in its
16265: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16266:
1.113 anton 16267: @c ---------------------------------------------------
16268: @node Licenses, Word Index, Forth-related information, Top
16269: @appendix Licenses
16270:
16271: @menu
16272: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16273: * Copying:: GPL (for copying this software).
1.113 anton 16274: @end menu
16275:
1.192 anton 16276: @node GNU Free Documentation License, Copying, Licenses, Licenses
16277: @appendixsec GNU Free Documentation License
1.113 anton 16278: @include fdl.texi
16279:
1.192 anton 16280: @node Copying, , GNU Free Documentation License, Licenses
16281: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16282: @include gpl.texi
16283:
16284:
16285:
1.81 anton 16286: @c ------------------------------------------------------------------
1.113 anton 16287: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16288: @unnumbered Word Index
16289:
1.26 crook 16290: This index is a list of Forth words that have ``glossary'' entries
16291: within this manual. Each word is listed with its stack effect and
16292: wordset.
1.1 anton 16293:
16294: @printindex fn
16295:
1.81 anton 16296: @c anton: the name index seems superfluous given the word and concept indices.
16297:
16298: @c @node Name Index, Concept Index, Word Index, Top
16299: @c @unnumbered Name Index
1.41 anton 16300:
1.81 anton 16301: @c This index is a list of Forth words that have ``glossary'' entries
16302: @c within this manual.
1.41 anton 16303:
1.81 anton 16304: @c @printindex ky
1.41 anton 16305:
1.113 anton 16306: @c -------------------------------------------------------
1.81 anton 16307: @node Concept Index, , Word Index, Top
1.1 anton 16308: @unnumbered Concept and Word Index
16309:
1.26 crook 16310: Not all entries listed in this index are present verbatim in the
16311: text. This index also duplicates, in abbreviated form, all of the words
16312: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16313:
16314: @printindex cp
16315:
16316: @bye
1.81 anton 16317:
16318:
1.1 anton 16319:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>