Annotation of gforth/doc/gforth.ds, revision 1.193
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
2694: line-buffer swap fd-out write-file throw
2695: repeat ;
2696: @end example
2697:
2698: @subsection Close files
2699:
2700: @example
2701: fd-in close-file throw
2702: fd-out close-file throw
2703: @end example
2704:
2705: Likewise, you can put that into definitions, too:
2706:
2707: @example
2708: : close-input ( -- ) fd-in close-file throw ;
2709: : close-output ( -- ) fd-out close-file throw ;
2710: @end example
2711:
1.141 anton 2712: @quotation Assignment
1.84 pazsan 2713: How could you modify @code{copy-file} so that it copies until a second line is
2714: matched? Can you write a program that extracts a section of a text file,
2715: given the line that starts and the line that terminates that section?
1.141 anton 2716: @end quotation
1.84 pazsan 2717:
2718: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2719: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2720: @cindex semantics tutorial
2721: @cindex interpretation semantics tutorial
2722: @cindex compilation semantics tutorial
2723: @cindex immediate, tutorial
1.48 anton 2724:
2725: When a word is compiled, it behaves differently from being interpreted.
2726: E.g., consider @code{+}:
2727:
2728: @example
2729: 1 2 + .
2730: : foo + ;
2731: @end example
2732:
2733: These two behaviours are known as compilation and interpretation
2734: semantics. For normal words (e.g., @code{+}), the compilation semantics
2735: is to append the interpretation semantics to the currently defined word
2736: (@code{foo} in the example above). I.e., when @code{foo} is executed
2737: later, the interpretation semantics of @code{+} (i.e., adding two
2738: numbers) will be performed.
2739:
2740: However, there are words with non-default compilation semantics, e.g.,
2741: the control-flow words like @code{if}. You can use @code{immediate} to
2742: change the compilation semantics of the last defined word to be equal to
2743: the interpretation semantics:
2744:
2745: @example
2746: : [FOO] ( -- )
2747: 5 . ; immediate
2748:
2749: [FOO]
2750: : bar ( -- )
2751: [FOO] ;
2752: bar
2753: see bar
2754: @end example
2755:
2756: Two conventions to mark words with non-default compilation semnatics are
2757: names with brackets (more frequently used) and to write them all in
2758: upper case (less frequently used).
2759:
2760: In Gforth (and many other systems) you can also remove the
2761: interpretation semantics with @code{compile-only} (the compilation
2762: semantics is derived from the original interpretation semantics):
2763:
2764: @example
2765: : flip ( -- )
2766: 6 . ; compile-only \ but not immediate
2767: flip
2768:
2769: : flop ( -- )
2770: flip ;
2771: flop
2772: @end example
2773:
2774: In this example the interpretation semantics of @code{flop} is equal to
2775: the original interpretation semantics of @code{flip}.
2776:
2777: The text interpreter has two states: in interpret state, it performs the
2778: interpretation semantics of words it encounters; in compile state, it
2779: performs the compilation semantics of these words.
2780:
2781: Among other things, @code{:} switches into compile state, and @code{;}
2782: switches back to interpret state. They contain the factors @code{]}
2783: (switch to compile state) and @code{[} (switch to interpret state), that
2784: do nothing but switch the state.
2785:
2786: @example
2787: : xxx ( -- )
2788: [ 5 . ]
2789: ;
2790:
2791: xxx
2792: see xxx
2793: @end example
2794:
2795: These brackets are also the source of the naming convention mentioned
2796: above.
2797:
1.66 anton 2798: Reference: @ref{Interpretation and Compilation Semantics}.
2799:
1.48 anton 2800:
2801: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2802: @section Execution Tokens
1.66 anton 2803: @cindex execution tokens tutorial
2804: @cindex XT tutorial
1.48 anton 2805:
2806: @code{' word} gives you the execution token (XT) of a word. The XT is a
2807: cell representing the interpretation semantics of a word. You can
2808: execute this semantics with @code{execute}:
2809:
2810: @example
2811: ' + .s
2812: 1 2 rot execute .
2813: @end example
2814:
2815: The XT is similar to a function pointer in C. However, parameter
2816: passing through the stack makes it a little more flexible:
2817:
2818: @example
2819: : map-array ( ... addr u xt -- ... )
1.50 anton 2820: \ executes xt ( ... x -- ... ) for every element of the array starting
2821: \ at addr and containing u elements
1.48 anton 2822: @{ xt @}
2823: cells over + swap ?do
1.50 anton 2824: i @@ xt execute
1.48 anton 2825: 1 cells +loop ;
2826:
2827: create a 3 , 4 , 2 , -1 , 4 ,
2828: a 5 ' . map-array .s
2829: 0 a 5 ' + map-array .
2830: s" max-n" environment? drop .s
2831: a 5 ' min map-array .
2832: @end example
2833:
2834: You can use map-array with the XTs of words that consume one element
2835: more than they produce. In theory you can also use it with other XTs,
2836: but the stack effect then depends on the size of the array, which is
2837: hard to understand.
2838:
1.51 pazsan 2839: Since XTs are cell-sized, you can store them in memory and manipulate
2840: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2841: word with @code{compile,}:
2842:
2843: @example
2844: : foo1 ( n1 n2 -- n )
2845: [ ' + compile, ] ;
2846: see foo
2847: @end example
2848:
2849: This is non-standard, because @code{compile,} has no compilation
2850: semantics in the standard, but it works in good Forth systems. For the
2851: broken ones, use
2852:
2853: @example
2854: : [compile,] compile, ; immediate
2855:
2856: : foo1 ( n1 n2 -- n )
2857: [ ' + ] [compile,] ;
2858: see foo
2859: @end example
2860:
2861: @code{'} is a word with default compilation semantics; it parses the
2862: next word when its interpretation semantics are executed, not during
2863: compilation:
2864:
2865: @example
2866: : foo ( -- xt )
2867: ' ;
2868: see foo
2869: : bar ( ... "word" -- ... )
2870: ' execute ;
2871: see bar
1.60 anton 2872: 1 2 bar + .
1.48 anton 2873: @end example
2874:
2875: You often want to parse a word during compilation and compile its XT so
2876: it will be pushed on the stack at run-time. @code{[']} does this:
2877:
2878: @example
2879: : xt-+ ( -- xt )
2880: ['] + ;
2881: see xt-+
2882: 1 2 xt-+ execute .
2883: @end example
2884:
2885: Many programmers tend to see @code{'} and the word it parses as one
2886: unit, and expect it to behave like @code{[']} when compiled, and are
2887: confused by the actual behaviour. If you are, just remember that the
2888: Forth system just takes @code{'} as one unit and has no idea that it is
2889: a parsing word (attempts to convenience programmers in this issue have
2890: usually resulted in even worse pitfalls, see
1.66 anton 2891: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2892: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2893:
2894: Note that the state of the interpreter does not come into play when
1.51 pazsan 2895: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2896: compile state, it still gives you the interpretation semantics. And
2897: whatever that state is, @code{execute} performs the semantics
1.66 anton 2898: represented by the XT (i.e., for XTs produced with @code{'} the
2899: interpretation semantics).
2900:
2901: Reference: @ref{Tokens for Words}.
1.48 anton 2902:
2903:
2904: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2905: @section Exceptions
1.66 anton 2906: @cindex exceptions tutorial
1.48 anton 2907:
2908: @code{throw ( n -- )} causes an exception unless n is zero.
2909:
2910: @example
2911: 100 throw .s
2912: 0 throw .s
2913: @end example
2914:
2915: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2916: it catches exceptions and pushes the number of the exception on the
2917: stack (or 0, if the xt executed without exception). If there was an
2918: exception, the stacks have the same depth as when entering @code{catch}:
2919:
2920: @example
2921: .s
2922: 3 0 ' / catch .s
2923: 3 2 ' / catch .s
2924: @end example
2925:
1.141 anton 2926: @quotation Assignment
1.48 anton 2927: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2928: @end quotation
1.48 anton 2929:
2930: @code{Throw} always jumps to the dynamically next enclosing
2931: @code{catch}, even if it has to leave several call levels to achieve
2932: this:
2933:
2934: @example
2935: : foo 100 throw ;
2936: : foo1 foo ." after foo" ;
1.51 pazsan 2937: : bar ['] foo1 catch ;
1.60 anton 2938: bar .
1.48 anton 2939: @end example
2940:
2941: It is often important to restore a value upon leaving a definition, even
2942: if the definition is left through an exception. You can ensure this
2943: like this:
2944:
2945: @example
2946: : ...
2947: save-x
1.51 pazsan 2948: ['] word-changing-x catch ( ... n )
1.48 anton 2949: restore-x
2950: ( ... n ) throw ;
2951: @end example
2952:
1.172 anton 2953: However, this is still not safe against, e.g., the user pressing
2954: @kbd{Ctrl-C} when execution is between the @code{catch} and
2955: @code{restore-x}.
2956:
2957: Gforth provides an alternative exception handling syntax that is safe
2958: against such cases: @code{try ... restore ... endtry}. If the code
2959: between @code{try} and @code{endtry} has an exception, the stack
2960: depths are restored, the exception number is pushed on the stack, and
2961: the execution continues right after @code{restore}.
1.48 anton 2962:
1.172 anton 2963: The safer equivalent to the restoration code above is
1.48 anton 2964:
2965: @example
2966: : ...
2967: save-x
2968: try
1.92 anton 2969: word-changing-x 0
1.172 anton 2970: restore
2971: restore-x
2972: endtry
1.48 anton 2973: throw ;
2974: @end example
2975:
1.66 anton 2976: Reference: @ref{Exception Handling}.
2977:
1.48 anton 2978:
2979: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2980: @section Defining Words
1.66 anton 2981: @cindex defining words tutorial
2982: @cindex does> tutorial
2983: @cindex create...does> tutorial
2984:
2985: @c before semantics?
1.48 anton 2986:
2987: @code{:}, @code{create}, and @code{variable} are definition words: They
2988: define other words. @code{Constant} is another definition word:
2989:
2990: @example
2991: 5 constant foo
2992: foo .
2993: @end example
2994:
2995: You can also use the prefixes @code{2} (double-cell) and @code{f}
2996: (floating point) with @code{variable} and @code{constant}.
2997:
2998: You can also define your own defining words. E.g.:
2999:
3000: @example
3001: : variable ( "name" -- )
3002: create 0 , ;
3003: @end example
3004:
3005: You can also define defining words that create words that do something
3006: other than just producing their address:
3007:
3008: @example
3009: : constant ( n "name" -- )
3010: create ,
3011: does> ( -- n )
1.50 anton 3012: ( addr ) @@ ;
1.48 anton 3013:
3014: 5 constant foo
3015: foo .
3016: @end example
3017:
3018: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3019: @code{does>} replaces @code{;}, but it also does something else: It
3020: changes the last defined word such that it pushes the address of the
3021: body of the word and then performs the code after the @code{does>}
3022: whenever it is called.
3023:
3024: In the example above, @code{constant} uses @code{,} to store 5 into the
3025: body of @code{foo}. When @code{foo} executes, it pushes the address of
3026: the body onto the stack, then (in the code after the @code{does>})
3027: fetches the 5 from there.
3028:
3029: The stack comment near the @code{does>} reflects the stack effect of the
3030: defined word, not the stack effect of the code after the @code{does>}
3031: (the difference is that the code expects the address of the body that
3032: the stack comment does not show).
3033:
3034: You can use these definition words to do factoring in cases that involve
3035: (other) definition words. E.g., a field offset is always added to an
3036: address. Instead of defining
3037:
3038: @example
3039: 2 cells constant offset-field1
3040: @end example
3041:
3042: and using this like
3043:
3044: @example
3045: ( addr ) offset-field1 +
3046: @end example
3047:
3048: you can define a definition word
3049:
3050: @example
3051: : simple-field ( n "name" -- )
3052: create ,
3053: does> ( n1 -- n1+n )
1.50 anton 3054: ( addr ) @@ + ;
1.48 anton 3055: @end example
1.21 crook 3056:
1.48 anton 3057: Definition and use of field offsets now look like this:
1.21 crook 3058:
1.48 anton 3059: @example
3060: 2 cells simple-field field1
1.60 anton 3061: create mystruct 4 cells allot
3062: mystruct .s field1 .s drop
1.48 anton 3063: @end example
1.21 crook 3064:
1.48 anton 3065: If you want to do something with the word without performing the code
3066: after the @code{does>}, you can access the body of a @code{create}d word
3067: with @code{>body ( xt -- addr )}:
1.21 crook 3068:
1.48 anton 3069: @example
3070: : value ( n "name" -- )
3071: create ,
3072: does> ( -- n1 )
1.50 anton 3073: @@ ;
1.48 anton 3074: : to ( n "name" -- )
3075: ' >body ! ;
1.21 crook 3076:
1.48 anton 3077: 5 value foo
3078: foo .
3079: 7 to foo
3080: foo .
3081: @end example
1.21 crook 3082:
1.141 anton 3083: @quotation Assignment
1.48 anton 3084: Define @code{defer ( "name" -- )}, which creates a word that stores an
3085: XT (at the start the XT of @code{abort}), and upon execution
3086: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3087: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3088: recursion is one application of @code{defer}.
1.141 anton 3089: @end quotation
1.29 crook 3090:
1.66 anton 3091: Reference: @ref{User-defined Defining Words}.
3092:
3093:
1.48 anton 3094: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3095: @section Arrays and Records
1.66 anton 3096: @cindex arrays tutorial
3097: @cindex records tutorial
3098: @cindex structs tutorial
1.29 crook 3099:
1.48 anton 3100: Forth has no standard words for defining data structures such as arrays
3101: and records (structs in C terminology), but you can build them yourself
3102: based on address arithmetic. You can also define words for defining
3103: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3104:
1.48 anton 3105: One of the first projects a Forth newcomer sets out upon when learning
3106: about defining words is an array defining word (possibly for
3107: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3108: learn something from it. However, don't be disappointed when you later
3109: learn that you have little use for these words (inappropriate use would
3110: be even worse). I have not yet found a set of useful array words yet;
3111: the needs are just too diverse, and named, global arrays (the result of
3112: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3113: consider how to pass them as parameters). Another such project is a set
3114: of words to help dealing with strings.
1.29 crook 3115:
1.48 anton 3116: On the other hand, there is a useful set of record words, and it has
3117: been defined in @file{compat/struct.fs}; these words are predefined in
3118: Gforth. They are explained in depth elsewhere in this manual (see
3119: @pxref{Structures}). The @code{simple-field} example above is
3120: simplified variant of fields in this package.
1.21 crook 3121:
3122:
1.48 anton 3123: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3124: @section @code{POSTPONE}
1.66 anton 3125: @cindex postpone tutorial
1.21 crook 3126:
1.48 anton 3127: You can compile the compilation semantics (instead of compiling the
3128: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3129:
1.48 anton 3130: @example
3131: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3132: POSTPONE + ; immediate
1.48 anton 3133: : foo ( n1 n2 -- n )
3134: MY-+ ;
3135: 1 2 foo .
3136: see foo
3137: @end example
1.21 crook 3138:
1.48 anton 3139: During the definition of @code{foo} the text interpreter performs the
3140: compilation semantics of @code{MY-+}, which performs the compilation
3141: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3142:
3143: This example also displays separate stack comments for the compilation
3144: semantics and for the stack effect of the compiled code. For words with
3145: default compilation semantics these stack effects are usually not
3146: displayed; the stack effect of the compilation semantics is always
3147: @code{( -- )} for these words, the stack effect for the compiled code is
3148: the stack effect of the interpretation semantics.
3149:
3150: Note that the state of the interpreter does not come into play when
3151: performing the compilation semantics in this way. You can also perform
3152: it interpretively, e.g.:
3153:
3154: @example
3155: : foo2 ( n1 n2 -- n )
3156: [ MY-+ ] ;
3157: 1 2 foo .
3158: see foo
3159: @end example
1.21 crook 3160:
1.48 anton 3161: However, there are some broken Forth systems where this does not always
1.62 crook 3162: work, and therefore this practice was been declared non-standard in
1.48 anton 3163: 1999.
3164: @c !! repair.fs
3165:
3166: Here is another example for using @code{POSTPONE}:
1.44 crook 3167:
1.48 anton 3168: @example
3169: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3170: POSTPONE negate POSTPONE + ; immediate compile-only
3171: : bar ( n1 n2 -- n )
3172: MY-- ;
3173: 2 1 bar .
3174: see bar
3175: @end example
1.21 crook 3176:
1.48 anton 3177: You can define @code{ENDIF} in this way:
1.21 crook 3178:
1.48 anton 3179: @example
3180: : ENDIF ( Compilation: orig -- )
3181: POSTPONE then ; immediate
3182: @end example
1.21 crook 3183:
1.141 anton 3184: @quotation Assignment
1.48 anton 3185: Write @code{MY-2DUP} that has compilation semantics equivalent to
3186: @code{2dup}, but compiles @code{over over}.
1.141 anton 3187: @end quotation
1.29 crook 3188:
1.66 anton 3189: @c !! @xref{Macros} for reference
3190:
3191:
1.48 anton 3192: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3193: @section @code{Literal}
1.66 anton 3194: @cindex literal tutorial
1.29 crook 3195:
1.48 anton 3196: You cannot @code{POSTPONE} numbers:
1.21 crook 3197:
1.48 anton 3198: @example
3199: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3200: @end example
3201:
1.48 anton 3202: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3203:
1.48 anton 3204: @example
3205: : [FOO] ( compilation: --; run-time: -- n )
3206: 500 POSTPONE literal ; immediate
1.29 crook 3207:
1.60 anton 3208: : flip [FOO] ;
1.48 anton 3209: flip .
3210: see flip
3211: @end example
1.29 crook 3212:
1.48 anton 3213: @code{LITERAL} consumes a number at compile-time (when it's compilation
3214: semantics are executed) and pushes it at run-time (when the code it
3215: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3216: number computed at compile time into the current word:
1.29 crook 3217:
1.48 anton 3218: @example
3219: : bar ( -- n )
3220: [ 2 2 + ] literal ;
3221: see bar
3222: @end example
1.29 crook 3223:
1.141 anton 3224: @quotation Assignment
1.48 anton 3225: Write @code{]L} which allows writing the example above as @code{: bar (
3226: -- n ) [ 2 2 + ]L ;}
1.141 anton 3227: @end quotation
1.48 anton 3228:
1.66 anton 3229: @c !! @xref{Macros} for reference
3230:
1.48 anton 3231:
3232: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3233: @section Advanced macros
1.66 anton 3234: @cindex macros, advanced tutorial
3235: @cindex run-time code generation, tutorial
1.48 anton 3236:
1.66 anton 3237: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3238: Execution Tokens}. It frequently performs @code{execute}, a relatively
3239: expensive operation in some Forth implementations. You can use
1.48 anton 3240: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3241: and produce a word that contains the word to be performed directly:
3242:
3243: @c use ]] ... [[
3244: @example
3245: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3246: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3247: \ array beginning at addr and containing u elements
3248: @{ xt @}
3249: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3250: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3251: 1 cells POSTPONE literal POSTPONE +loop ;
3252:
3253: : sum-array ( addr u -- n )
3254: 0 rot rot [ ' + compile-map-array ] ;
3255: see sum-array
3256: a 5 sum-array .
3257: @end example
3258:
3259: You can use the full power of Forth for generating the code; here's an
3260: example where the code is generated in a loop:
3261:
3262: @example
3263: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3264: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3265: POSTPONE tuck POSTPONE @@
1.48 anton 3266: POSTPONE literal POSTPONE * POSTPONE +
3267: POSTPONE swap POSTPONE cell+ ;
3268:
3269: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3270: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3271: 0 postpone literal postpone swap
3272: [ ' compile-vmul-step compile-map-array ]
3273: postpone drop ;
3274: see compile-vmul
3275:
3276: : a-vmul ( addr -- n )
1.51 pazsan 3277: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3278: [ a 5 compile-vmul ] ;
3279: see a-vmul
3280: a a-vmul .
3281: @end example
3282:
3283: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3284: also use @code{map-array} instead (try it now!).
1.48 anton 3285:
3286: You can use this technique for efficient multiplication of large
3287: matrices. In matrix multiplication, you multiply every line of one
3288: matrix with every column of the other matrix. You can generate the code
3289: for one line once, and use it for every column. The only downside of
3290: this technique is that it is cumbersome to recover the memory consumed
3291: by the generated code when you are done (and in more complicated cases
3292: it is not possible portably).
3293:
1.66 anton 3294: @c !! @xref{Macros} for reference
3295:
3296:
1.48 anton 3297: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3298: @section Compilation Tokens
1.66 anton 3299: @cindex compilation tokens, tutorial
3300: @cindex CT, tutorial
1.48 anton 3301:
3302: This section is Gforth-specific. You can skip it.
3303:
3304: @code{' word compile,} compiles the interpretation semantics. For words
3305: with default compilation semantics this is the same as performing the
3306: compilation semantics. To represent the compilation semantics of other
3307: words (e.g., words like @code{if} that have no interpretation
3308: semantics), Gforth has the concept of a compilation token (CT,
3309: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3310: You can perform the compilation semantics represented by a CT with
3311: @code{execute}:
1.29 crook 3312:
1.48 anton 3313: @example
3314: : foo2 ( n1 n2 -- n )
3315: [ comp' + execute ] ;
3316: see foo
3317: @end example
1.29 crook 3318:
1.48 anton 3319: You can compile the compilation semantics represented by a CT with
3320: @code{postpone,}:
1.30 anton 3321:
1.48 anton 3322: @example
3323: : foo3 ( -- )
3324: [ comp' + postpone, ] ;
3325: see foo3
3326: @end example
1.30 anton 3327:
1.51 pazsan 3328: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3329: @code{comp'} is particularly useful for words that have no
3330: interpretation semantics:
1.29 crook 3331:
1.30 anton 3332: @example
1.48 anton 3333: ' if
1.60 anton 3334: comp' if .s 2drop
1.30 anton 3335: @end example
3336:
1.66 anton 3337: Reference: @ref{Tokens for Words}.
3338:
1.29 crook 3339:
1.48 anton 3340: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3341: @section Wordlists and Search Order
1.66 anton 3342: @cindex wordlists tutorial
3343: @cindex search order, tutorial
1.48 anton 3344:
3345: The dictionary is not just a memory area that allows you to allocate
3346: memory with @code{allot}, it also contains the Forth words, arranged in
3347: several wordlists. When searching for a word in a wordlist,
3348: conceptually you start searching at the youngest and proceed towards
3349: older words (in reality most systems nowadays use hash-tables); i.e., if
3350: you define a word with the same name as an older word, the new word
3351: shadows the older word.
3352:
3353: Which wordlists are searched in which order is determined by the search
3354: order. You can display the search order with @code{order}. It displays
3355: first the search order, starting with the wordlist searched first, then
3356: it displays the wordlist that will contain newly defined words.
1.21 crook 3357:
1.48 anton 3358: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3359:
1.48 anton 3360: @example
3361: wordlist constant mywords
3362: @end example
1.21 crook 3363:
1.48 anton 3364: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3365: defined words (the @emph{current} wordlist):
1.21 crook 3366:
1.48 anton 3367: @example
3368: mywords set-current
3369: order
3370: @end example
1.26 crook 3371:
1.48 anton 3372: Gforth does not display a name for the wordlist in @code{mywords}
3373: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3374:
1.48 anton 3375: You can get the current wordlist with @code{get-current ( -- wid)}. If
3376: you want to put something into a specific wordlist without overall
3377: effect on the current wordlist, this typically looks like this:
1.21 crook 3378:
1.48 anton 3379: @example
3380: get-current mywords set-current ( wid )
3381: create someword
3382: ( wid ) set-current
3383: @end example
1.21 crook 3384:
1.48 anton 3385: You can write the search order with @code{set-order ( wid1 .. widn n --
3386: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3387: searched wordlist is topmost.
1.21 crook 3388:
1.48 anton 3389: @example
3390: get-order mywords swap 1+ set-order
3391: order
3392: @end example
1.21 crook 3393:
1.48 anton 3394: Yes, the order of wordlists in the output of @code{order} is reversed
3395: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3396:
1.141 anton 3397: @quotation Assignment
1.48 anton 3398: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3399: wordlist to the search order. Define @code{previous ( -- )}, which
3400: removes the first searched wordlist from the search order. Experiment
3401: with boundary conditions (you will see some crashes or situations that
3402: are hard or impossible to leave).
1.141 anton 3403: @end quotation
1.21 crook 3404:
1.48 anton 3405: The search order is a powerful foundation for providing features similar
3406: to Modula-2 modules and C++ namespaces. However, trying to modularize
3407: programs in this way has disadvantages for debugging and reuse/factoring
3408: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3409: though). These disadvantages are not so clear in other
1.82 anton 3410: languages/programming environments, because these languages are not so
1.48 anton 3411: strong in debugging and reuse.
1.21 crook 3412:
1.66 anton 3413: @c !! example
3414:
3415: Reference: @ref{Word Lists}.
1.21 crook 3416:
1.29 crook 3417: @c ******************************************************************
1.48 anton 3418: @node Introduction, Words, Tutorial, Top
1.29 crook 3419: @comment node-name, next, previous, up
3420: @chapter An Introduction to ANS Forth
3421: @cindex Forth - an introduction
1.21 crook 3422:
1.83 anton 3423: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3424: that it is slower-paced in its examples, but uses them to dive deep into
3425: explaining Forth internals (not covered by the Tutorial). Apart from
3426: that, this chapter covers far less material. It is suitable for reading
3427: without using a computer.
3428:
1.29 crook 3429: The primary purpose of this manual is to document Gforth. However, since
3430: Forth is not a widely-known language and there is a lack of up-to-date
3431: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3432: material. For other sources of Forth-related
3433: information, see @ref{Forth-related information}.
1.21 crook 3434:
1.29 crook 3435: The examples in this section should work on any ANS Forth; the
3436: output shown was produced using Gforth. Each example attempts to
3437: reproduce the exact output that Gforth produces. If you try out the
3438: examples (and you should), what you should type is shown @kbd{like this}
3439: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3440: that, where the example shows @key{RET} it means that you should
1.29 crook 3441: press the ``carriage return'' key. Unfortunately, some output formats for
3442: this manual cannot show the difference between @kbd{this} and
3443: @code{this} which will make trying out the examples harder (but not
3444: impossible).
1.21 crook 3445:
1.29 crook 3446: Forth is an unusual language. It provides an interactive development
3447: environment which includes both an interpreter and compiler. Forth
3448: programming style encourages you to break a problem down into many
3449: @cindex factoring
3450: small fragments (@dfn{factoring}), and then to develop and test each
3451: fragment interactively. Forth advocates assert that breaking the
3452: edit-compile-test cycle used by conventional programming languages can
3453: lead to great productivity improvements.
1.21 crook 3454:
1.29 crook 3455: @menu
1.67 anton 3456: * Introducing the Text Interpreter::
3457: * Stacks and Postfix notation::
3458: * Your first definition::
3459: * How does that work?::
3460: * Forth is written in Forth::
3461: * Review - elements of a Forth system::
3462: * Where to go next::
3463: * Exercises::
1.29 crook 3464: @end menu
1.21 crook 3465:
1.29 crook 3466: @comment ----------------------------------------------
3467: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3468: @section Introducing the Text Interpreter
3469: @cindex text interpreter
3470: @cindex outer interpreter
1.21 crook 3471:
1.30 anton 3472: @c IMO this is too detailed and the pace is too slow for
3473: @c an introduction. If you know German, take a look at
3474: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3475: @c to see how I do it - anton
3476:
1.44 crook 3477: @c nac-> Where I have accepted your comments 100% and modified the text
3478: @c accordingly, I have deleted your comments. Elsewhere I have added a
3479: @c response like this to attempt to rationalise what I have done. Of
3480: @c course, this is a very clumsy mechanism for something that would be
3481: @c done far more efficiently over a beer. Please delete any dialogue
3482: @c you consider closed.
3483:
1.29 crook 3484: When you invoke the Forth image, you will see a startup banner printed
3485: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3486: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3487: its command line interpreter, which is called the @dfn{Text Interpreter}
3488: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3489: about the text interpreter as you read through this chapter, for more
3490: detail @pxref{The Text Interpreter}).
1.21 crook 3491:
1.29 crook 3492: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3493: input. Type a number and press the @key{RET} key:
1.21 crook 3494:
1.26 crook 3495: @example
1.30 anton 3496: @kbd{45@key{RET}} ok
1.26 crook 3497: @end example
1.21 crook 3498:
1.29 crook 3499: Rather than give you a prompt to invite you to input something, the text
3500: interpreter prints a status message @i{after} it has processed a line
3501: of input. The status message in this case (``@code{ ok}'' followed by
3502: carriage-return) indicates that the text interpreter was able to process
3503: all of your input successfully. Now type something illegal:
3504:
3505: @example
1.30 anton 3506: @kbd{qwer341@key{RET}}
1.134 anton 3507: *the terminal*:2: Undefined word
3508: >>>qwer341<<<
3509: Backtrace:
3510: $2A95B42A20 throw
3511: $2A95B57FB8 no.extensions
1.29 crook 3512: @end example
1.23 crook 3513:
1.134 anton 3514: The exact text, other than the ``Undefined word'' may differ slightly
3515: on your system, but the effect is the same; when the text interpreter
1.29 crook 3516: detects an error, it discards any remaining text on a line, resets
1.134 anton 3517: certain internal state and prints an error message. For a detailed
3518: description of error messages see @ref{Error messages}.
1.23 crook 3519:
1.29 crook 3520: The text interpreter waits for you to press carriage-return, and then
3521: processes your input line. Starting at the beginning of the line, it
3522: breaks the line into groups of characters separated by spaces. For each
3523: group of characters in turn, it makes two attempts to do something:
1.23 crook 3524:
1.29 crook 3525: @itemize @bullet
3526: @item
1.44 crook 3527: @cindex name dictionary
1.29 crook 3528: It tries to treat it as a command. It does this by searching a @dfn{name
3529: dictionary}. If the group of characters matches an entry in the name
3530: dictionary, the name dictionary provides the text interpreter with
3531: information that allows the text interpreter perform some actions. In
3532: Forth jargon, we say that the group
3533: @cindex word
3534: @cindex definition
3535: @cindex execution token
3536: @cindex xt
3537: of characters names a @dfn{word}, that the dictionary search returns an
3538: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3539: word, and that the text interpreter executes the xt. Often, the terms
3540: @dfn{word} and @dfn{definition} are used interchangeably.
3541: @item
3542: If the text interpreter fails to find a match in the name dictionary, it
3543: tries to treat the group of characters as a number in the current number
3544: base (when you start up Forth, the current number base is base 10). If
3545: the group of characters legitimately represents a number, the text
3546: interpreter pushes the number onto a stack (we'll learn more about that
3547: in the next section).
3548: @end itemize
1.23 crook 3549:
1.29 crook 3550: If the text interpreter is unable to do either of these things with any
3551: group of characters, it discards the group of characters and the rest of
3552: the line, then prints an error message. If the text interpreter reaches
3553: the end of the line without error, it prints the status message ``@code{ ok}''
3554: followed by carriage-return.
1.21 crook 3555:
1.29 crook 3556: This is the simplest command we can give to the text interpreter:
1.23 crook 3557:
3558: @example
1.30 anton 3559: @key{RET} ok
1.23 crook 3560: @end example
1.21 crook 3561:
1.29 crook 3562: The text interpreter did everything we asked it to do (nothing) without
3563: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3564: command:
1.21 crook 3565:
1.23 crook 3566: @example
1.30 anton 3567: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3568: *the terminal*:3: Undefined word
3569: 12 dup >>>fred<<< dup
3570: Backtrace:
3571: $2A95B42A20 throw
3572: $2A95B57FB8 no.extensions
1.23 crook 3573: @end example
1.21 crook 3574:
1.29 crook 3575: When you press the carriage-return key, the text interpreter starts to
3576: work its way along the line:
1.21 crook 3577:
1.29 crook 3578: @itemize @bullet
3579: @item
3580: When it gets to the space after the @code{2}, it takes the group of
3581: characters @code{12} and looks them up in the name
3582: dictionary@footnote{We can't tell if it found them or not, but assume
3583: for now that it did not}. There is no match for this group of characters
3584: in the name dictionary, so it tries to treat them as a number. It is
3585: able to do this successfully, so it puts the number, 12, ``on the stack''
3586: (whatever that means).
3587: @item
3588: The text interpreter resumes scanning the line and gets the next group
3589: of characters, @code{dup}. It looks it up in the name dictionary and
3590: (you'll have to take my word for this) finds it, and executes the word
3591: @code{dup} (whatever that means).
3592: @item
3593: Once again, the text interpreter resumes scanning the line and gets the
3594: group of characters @code{fred}. It looks them up in the name
3595: dictionary, but can't find them. It tries to treat them as a number, but
3596: they don't represent any legal number.
3597: @end itemize
1.21 crook 3598:
1.29 crook 3599: At this point, the text interpreter gives up and prints an error
3600: message. The error message shows exactly how far the text interpreter
3601: got in processing the line. In particular, it shows that the text
3602: interpreter made no attempt to do anything with the final character
3603: group, @code{dup}, even though we have good reason to believe that the
3604: text interpreter would have no problem looking that word up and
3605: executing it a second time.
1.21 crook 3606:
3607:
1.29 crook 3608: @comment ----------------------------------------------
3609: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3610: @section Stacks, postfix notation and parameter passing
3611: @cindex text interpreter
3612: @cindex outer interpreter
1.21 crook 3613:
1.29 crook 3614: In procedural programming languages (like C and Pascal), the
3615: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3616: functions or procedures are called with @dfn{explicit parameters}. For
3617: example, in C we might write:
1.21 crook 3618:
1.23 crook 3619: @example
1.29 crook 3620: total = total + new_volume(length,height,depth);
1.23 crook 3621: @end example
1.21 crook 3622:
1.23 crook 3623: @noindent
1.29 crook 3624: where new_volume is a function-call to another piece of code, and total,
3625: length, height and depth are all variables. length, height and depth are
3626: parameters to the function-call.
1.21 crook 3627:
1.29 crook 3628: In Forth, the equivalent of the function or procedure is the
3629: @dfn{definition} and parameters are implicitly passed between
3630: definitions using a shared stack that is visible to the
3631: programmer. Although Forth does support variables, the existence of the
3632: stack means that they are used far less often than in most other
3633: programming languages. When the text interpreter encounters a number, it
3634: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3635: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3636: used for any operation is implied unambiguously by the operation being
3637: performed. The stack used for all integer operations is called the @dfn{data
3638: stack} and, since this is the stack used most commonly, references to
3639: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3640:
1.29 crook 3641: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3642:
1.23 crook 3643: @example
1.30 anton 3644: @kbd{1 2 3@key{RET}} ok
1.23 crook 3645: @end example
1.21 crook 3646:
1.29 crook 3647: Then this instructs the text interpreter to placed three numbers on the
3648: (data) stack. An analogy for the behaviour of the stack is to take a
3649: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3650: the table. The 3 was the last card onto the pile (``last-in'') and if
3651: you take a card off the pile then, unless you're prepared to fiddle a
3652: bit, the card that you take off will be the 3 (``first-out''). The
3653: number that will be first-out of the stack is called the @dfn{top of
3654: stack}, which
3655: @cindex TOS definition
3656: is often abbreviated to @dfn{TOS}.
1.21 crook 3657:
1.29 crook 3658: To understand how parameters are passed in Forth, consider the
3659: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3660: be surprised to learn that this definition performs addition. More
3661: precisely, it adds two number together and produces a result. Where does
3662: it get the two numbers from? It takes the top two numbers off the
3663: stack. Where does it place the result? On the stack. You can act-out the
3664: behaviour of @code{+} with your playing cards like this:
1.21 crook 3665:
3666: @itemize @bullet
3667: @item
1.29 crook 3668: Pick up two cards from the stack on the table
1.21 crook 3669: @item
1.29 crook 3670: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3671: numbers''
1.21 crook 3672: @item
1.29 crook 3673: Decide that the answer is 5
1.21 crook 3674: @item
1.29 crook 3675: Shuffle the two cards back into the pack and find a 5
1.21 crook 3676: @item
1.29 crook 3677: Put a 5 on the remaining ace that's on the table.
1.21 crook 3678: @end itemize
3679:
1.29 crook 3680: If you don't have a pack of cards handy but you do have Forth running,
3681: you can use the definition @code{.s} to show the current state of the stack,
3682: without affecting the stack. Type:
1.21 crook 3683:
3684: @example
1.124 anton 3685: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3686: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3687: @end example
3688:
1.124 anton 3689: The text interpreter looks up the word @code{clearstacks} and executes
3690: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3691: left on it by earlier examples. The text interpreter pushes each of the
3692: three numbers in turn onto the stack. Finally, the text interpreter
3693: looks up the word @code{.s} and executes it. The effect of executing
3694: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3695: followed by a list of all the items on the stack; the item on the far
3696: right-hand side is the TOS.
1.21 crook 3697:
1.29 crook 3698: You can now type:
1.21 crook 3699:
1.29 crook 3700: @example
1.30 anton 3701: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3702: @end example
1.21 crook 3703:
1.29 crook 3704: @noindent
3705: which is correct; there are now 2 items on the stack and the result of
3706: the addition is 5.
1.23 crook 3707:
1.29 crook 3708: If you're playing with cards, try doing a second addition: pick up the
3709: two cards, work out that their sum is 6, shuffle them into the pack,
3710: look for a 6 and place that on the table. You now have just one item on
3711: the stack. What happens if you try to do a third addition? Pick up the
3712: first card, pick up the second card -- ah! There is no second card. This
3713: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3714: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3715: Underflow or an Invalid Memory Address error).
1.23 crook 3716:
1.29 crook 3717: The opposite situation to a stack underflow is a @dfn{stack overflow},
3718: which simply accepts that there is a finite amount of storage space
3719: reserved for the stack. To stretch the playing card analogy, if you had
3720: enough packs of cards and you piled the cards up on the table, you would
3721: eventually be unable to add another card; you'd hit the ceiling. Gforth
3722: allows you to set the maximum size of the stacks. In general, the only
3723: time that you will get a stack overflow is because a definition has a
3724: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3725:
1.29 crook 3726: There's one final use for the playing card analogy. If you model your
3727: stack using a pack of playing cards, the maximum number of items on
3728: your stack will be 52 (I assume you didn't use the Joker). The maximum
3729: @i{value} of any item on the stack is 13 (the King). In fact, the only
3730: possible numbers are positive integer numbers 1 through 13; you can't
3731: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3732: think about some of the cards, you can accommodate different
3733: numbers. For example, you could think of the Jack as representing 0,
3734: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3735: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3736: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3737:
1.29 crook 3738: In that analogy, the limit was the amount of information that a single
3739: stack entry could hold, and Forth has a similar limit. In Forth, the
3740: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3741: implementation dependent and affects the maximum value that a stack
3742: entry can hold. A Standard Forth provides a cell size of at least
3743: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3744:
1.29 crook 3745: Forth does not do any type checking for you, so you are free to
3746: manipulate and combine stack items in any way you wish. A convenient way
3747: of treating stack items is as 2's complement signed integers, and that
3748: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3749:
1.29 crook 3750: @example
1.30 anton 3751: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3752: @end example
1.21 crook 3753:
1.29 crook 3754: If you use numbers and definitions like @code{+} in order to turn Forth
3755: into a great big pocket calculator, you will realise that it's rather
3756: different from a normal calculator. Rather than typing 2 + 3 = you had
3757: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3758: result). The terminology used to describe this difference is to say that
3759: your calculator uses @dfn{Infix Notation} (parameters and operators are
3760: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3761: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3762:
1.29 crook 3763: Whilst postfix notation might look confusing to begin with, it has
3764: several important advantages:
1.21 crook 3765:
1.23 crook 3766: @itemize @bullet
3767: @item
1.29 crook 3768: it is unambiguous
1.23 crook 3769: @item
1.29 crook 3770: it is more concise
1.23 crook 3771: @item
1.29 crook 3772: it fits naturally with a stack-based system
1.23 crook 3773: @end itemize
1.21 crook 3774:
1.29 crook 3775: To examine these claims in more detail, consider these sums:
1.21 crook 3776:
1.29 crook 3777: @example
3778: 6 + 5 * 4 =
3779: 4 * 5 + 6 =
3780: @end example
1.21 crook 3781:
1.29 crook 3782: If you're just learning maths or your maths is very rusty, you will
3783: probably come up with the answer 44 for the first and 26 for the
3784: second. If you are a bit of a whizz at maths you will remember the
3785: @i{convention} that multiplication takes precendence over addition, and
3786: you'd come up with the answer 26 both times. To explain the answer 26
3787: to someone who got the answer 44, you'd probably rewrite the first sum
3788: like this:
1.21 crook 3789:
1.29 crook 3790: @example
3791: 6 + (5 * 4) =
3792: @end example
1.21 crook 3793:
1.29 crook 3794: If what you really wanted was to perform the addition before the
3795: multiplication, you would have to use parentheses to force it.
1.21 crook 3796:
1.29 crook 3797: If you did the first two sums on a pocket calculator you would probably
3798: get the right answers, unless you were very cautious and entered them using
3799: these keystroke sequences:
1.21 crook 3800:
1.29 crook 3801: 6 + 5 = * 4 =
3802: 4 * 5 = + 6 =
1.21 crook 3803:
1.29 crook 3804: Postfix notation is unambiguous because the order that the operators
3805: are applied is always explicit; that also means that parentheses are
3806: never required. The operators are @i{active} (the act of quoting the
3807: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3808:
1.29 crook 3809: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3810: equivalent ways:
1.26 crook 3811:
3812: @example
1.29 crook 3813: 6 5 4 * + or:
3814: 5 4 * 6 +
1.26 crook 3815: @end example
1.23 crook 3816:
1.29 crook 3817: An important thing that you should notice about this notation is that
3818: the @i{order} of the numbers does not change; if you want to subtract
3819: 2 from 10 you type @code{10 2 -}.
1.1 anton 3820:
1.29 crook 3821: The reason that Forth uses postfix notation is very simple to explain: it
3822: makes the implementation extremely simple, and it follows naturally from
3823: using the stack as a mechanism for passing parameters. Another way of
3824: thinking about this is to realise that all Forth definitions are
3825: @i{active}; they execute as they are encountered by the text
3826: interpreter. The result of this is that the syntax of Forth is trivially
3827: simple.
1.1 anton 3828:
3829:
3830:
1.29 crook 3831: @comment ----------------------------------------------
3832: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3833: @section Your first Forth definition
3834: @cindex first definition
1.1 anton 3835:
1.29 crook 3836: Until now, the examples we've seen have been trivial; we've just been
3837: using Forth as a bigger-than-pocket calculator. Also, each calculation
3838: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3839: again@footnote{That's not quite true. If you press the up-arrow key on
3840: your keyboard you should be able to scroll back to any earlier command,
3841: edit it and re-enter it.} In this section we'll see how to add new
3842: words to Forth's vocabulary.
1.1 anton 3843:
1.29 crook 3844: The easiest way to create a new word is to use a @dfn{colon
3845: definition}. We'll define a few and try them out before worrying too
3846: much about how they work. Try typing in these examples; be careful to
3847: copy the spaces accurately:
1.1 anton 3848:
1.29 crook 3849: @example
3850: : add-two 2 + . ;
3851: : greet ." Hello and welcome" ;
3852: : demo 5 add-two ;
3853: @end example
1.1 anton 3854:
1.29 crook 3855: @noindent
3856: Now try them out:
1.1 anton 3857:
1.29 crook 3858: @example
1.30 anton 3859: @kbd{greet@key{RET}} Hello and welcome ok
3860: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3861: @kbd{4 add-two@key{RET}} 6 ok
3862: @kbd{demo@key{RET}} 7 ok
3863: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3864: @end example
1.1 anton 3865:
1.29 crook 3866: The first new thing that we've introduced here is the pair of words
3867: @code{:} and @code{;}. These are used to start and terminate a new
3868: definition, respectively. The first word after the @code{:} is the name
3869: for the new definition.
1.1 anton 3870:
1.29 crook 3871: As you can see from the examples, a definition is built up of words that
3872: have already been defined; Forth makes no distinction between
3873: definitions that existed when you started the system up, and those that
3874: you define yourself.
1.1 anton 3875:
1.29 crook 3876: The examples also introduce the words @code{.} (dot), @code{."}
3877: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3878: the stack and displays it. It's like @code{.s} except that it only
3879: displays the top item of the stack and it is destructive; after it has
3880: executed, the number is no longer on the stack. There is always one
3881: space printed after the number, and no spaces before it. Dot-quote
3882: defines a string (a sequence of characters) that will be printed when
3883: the word is executed. The string can contain any printable characters
3884: except @code{"}. A @code{"} has a special function; it is not a Forth
3885: word but it acts as a delimiter (the way that delimiters work is
3886: described in the next section). Finally, @code{dup} duplicates the value
3887: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3888:
1.29 crook 3889: We already know that the text interpreter searches through the
3890: dictionary to locate names. If you've followed the examples earlier, you
3891: will already have a definition called @code{add-two}. Lets try modifying
3892: it by typing in a new definition:
1.1 anton 3893:
1.29 crook 3894: @example
1.30 anton 3895: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3896: @end example
1.5 anton 3897:
1.29 crook 3898: Forth recognised that we were defining a word that already exists, and
3899: printed a message to warn us of that fact. Let's try out the new
3900: definition:
1.5 anton 3901:
1.29 crook 3902: @example
1.30 anton 3903: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3904: @end example
1.1 anton 3905:
1.29 crook 3906: @noindent
3907: All that we've actually done here, though, is to create a new
3908: definition, with a particular name. The fact that there was already a
3909: definition with the same name did not make any difference to the way
3910: that the new definition was created (except that Forth printed a warning
3911: message). The old definition of add-two still exists (try @code{demo}
3912: again to see that this is true). Any new definition will use the new
3913: definition of @code{add-two}, but old definitions continue to use the
3914: version that already existed at the time that they were @code{compiled}.
1.1 anton 3915:
1.29 crook 3916: Before you go on to the next section, try defining and redefining some
3917: words of your own.
1.1 anton 3918:
1.29 crook 3919: @comment ----------------------------------------------
3920: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3921: @section How does that work?
3922: @cindex parsing words
1.1 anton 3923:
1.30 anton 3924: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3925:
3926: @c Is it a good idea to talk about the interpretation semantics of a
3927: @c number? We don't have an xt to go along with it. - anton
3928:
3929: @c Now that I have eliminated execution semantics, I wonder if it would not
3930: @c be better to keep them (or add run-time semantics), to make it easier to
3931: @c explain what compilation semantics usually does. - anton
3932:
1.44 crook 3933: @c nac-> I removed the term ``default compilation sematics'' from the
3934: @c introductory chapter. Removing ``execution semantics'' was making
3935: @c everything simpler to explain, then I think the use of this term made
3936: @c everything more complex again. I replaced it with ``default
3937: @c semantics'' (which is used elsewhere in the manual) by which I mean
3938: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3939: @c flag set''.
3940:
3941: @c anton: I have eliminated default semantics (except in one place where it
3942: @c means "default interpretation and compilation semantics"), because it
3943: @c makes no sense in the presence of combined words. I reverted to
3944: @c "execution semantics" where necessary.
3945:
3946: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3947: @c section (and, unusually for me, I think I even made it shorter!). See
3948: @c what you think -- I know I have not addressed your primary concern
3949: @c that it is too heavy-going for an introduction. From what I understood
3950: @c of your course notes it looks as though they might be a good framework.
3951: @c Things that I've tried to capture here are some things that came as a
3952: @c great revelation here when I first understood them. Also, I like the
3953: @c fact that a very simple code example shows up almost all of the issues
3954: @c that you need to understand to see how Forth works. That's unique and
3955: @c worthwhile to emphasise.
3956:
1.83 anton 3957: @c anton: I think it's a good idea to present the details, especially those
3958: @c that you found to be a revelation, and probably the tutorial tries to be
3959: @c too superficial and does not get some of the things across that make
3960: @c Forth special. I do believe that most of the time these things should
3961: @c be discussed at the end of a section or in separate sections instead of
3962: @c in the middle of a section (e.g., the stuff you added in "User-defined
3963: @c defining words" leads in a completely different direction from the rest
3964: @c of the section).
3965:
1.29 crook 3966: Now we're going to take another look at the definition of @code{add-two}
3967: from the previous section. From our knowledge of the way that the text
3968: interpreter works, we would have expected this result when we tried to
3969: define @code{add-two}:
1.21 crook 3970:
1.29 crook 3971: @example
1.44 crook 3972: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3973: *the terminal*:4: Undefined word
3974: : >>>add-two<<< 2 + . ;
1.29 crook 3975: @end example
1.28 crook 3976:
1.29 crook 3977: The reason that this didn't happen is bound up in the way that @code{:}
3978: works. The word @code{:} does two special things. The first special
3979: thing that it does prevents the text interpreter from ever seeing the
3980: characters @code{add-two}. The text interpreter uses a variable called
3981: @cindex modifying >IN
1.44 crook 3982: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3983: input line. When it encounters the word @code{:} it behaves in exactly
3984: the same way as it does for any other word; it looks it up in the name
3985: dictionary, finds its xt and executes it. When @code{:} executes, it
3986: looks at the input buffer, finds the word @code{add-two} and advances the
3987: value of @code{>IN} to point past it. It then does some other stuff
3988: associated with creating the new definition (including creating an entry
3989: for @code{add-two} in the name dictionary). When the execution of @code{:}
3990: completes, control returns to the text interpreter, which is oblivious
3991: to the fact that it has been tricked into ignoring part of the input
3992: line.
1.21 crook 3993:
1.29 crook 3994: @cindex parsing words
3995: Words like @code{:} -- words that advance the value of @code{>IN} and so
3996: prevent the text interpreter from acting on the whole of the input line
3997: -- are called @dfn{parsing words}.
1.21 crook 3998:
1.29 crook 3999: @cindex @code{state} - effect on the text interpreter
4000: @cindex text interpreter - effect of state
4001: The second special thing that @code{:} does is change the value of a
4002: variable called @code{state}, which affects the way that the text
4003: interpreter behaves. When Gforth starts up, @code{state} has the value
4004: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4005: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4006: the text interpreter is said to be @dfn{compiling}.
4007:
4008: In this example, the text interpreter is compiling when it processes the
4009: string ``@code{2 + . ;}''. It still breaks the string down into
4010: character sequences in the same way. However, instead of pushing the
4011: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4012: into the definition of @code{add-two} that will make the number @code{2} get
4013: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4014: the behaviours of @code{+} and @code{.} are also compiled into the
4015: definition.
4016:
4017: One category of words don't get compiled. These so-called @dfn{immediate
4018: words} get executed (performed @i{now}) regardless of whether the text
4019: interpreter is interpreting or compiling. The word @code{;} is an
4020: immediate word. Rather than being compiled into the definition, it
4021: executes. Its effect is to terminate the current definition, which
4022: includes changing the value of @code{state} back to 0.
4023:
4024: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4025: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4026: definition.
1.28 crook 4027:
1.30 anton 4028: In Forth, every word or number can be described in terms of two
1.29 crook 4029: properties:
1.28 crook 4030:
4031: @itemize @bullet
4032: @item
1.29 crook 4033: @cindex interpretation semantics
1.44 crook 4034: Its @dfn{interpretation semantics} describe how it will behave when the
4035: text interpreter encounters it in @dfn{interpret} state. The
4036: interpretation semantics of a word are represented by an @dfn{execution
4037: token}.
1.28 crook 4038: @item
1.29 crook 4039: @cindex compilation semantics
1.44 crook 4040: Its @dfn{compilation semantics} describe how it will behave when the
4041: text interpreter encounters it in @dfn{compile} state. The compilation
4042: semantics of a word are represented in an implementation-dependent way;
4043: Gforth uses a @dfn{compilation token}.
1.29 crook 4044: @end itemize
4045:
4046: @noindent
4047: Numbers are always treated in a fixed way:
4048:
4049: @itemize @bullet
1.28 crook 4050: @item
1.44 crook 4051: When the number is @dfn{interpreted}, its behaviour is to push the
4052: number onto the stack.
1.28 crook 4053: @item
1.30 anton 4054: When the number is @dfn{compiled}, a piece of code is appended to the
4055: current definition that pushes the number when it runs. (In other words,
4056: the compilation semantics of a number are to postpone its interpretation
4057: semantics until the run-time of the definition that it is being compiled
4058: into.)
1.29 crook 4059: @end itemize
4060:
1.44 crook 4061: Words don't behave in such a regular way, but most have @i{default
4062: semantics} which means that they behave like this:
1.29 crook 4063:
4064: @itemize @bullet
1.28 crook 4065: @item
1.30 anton 4066: The @dfn{interpretation semantics} of the word are to do something useful.
4067: @item
1.29 crook 4068: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4069: @dfn{interpretation semantics} to the current definition (so that its
4070: run-time behaviour is to do something useful).
1.28 crook 4071: @end itemize
4072:
1.30 anton 4073: @cindex immediate words
1.44 crook 4074: The actual behaviour of any particular word can be controlled by using
4075: the words @code{immediate} and @code{compile-only} when the word is
4076: defined. These words set flags in the name dictionary entry of the most
4077: recently defined word, and these flags are retrieved by the text
4078: interpreter when it finds the word in the name dictionary.
4079:
4080: A word that is marked as @dfn{immediate} has compilation semantics that
4081: are identical to its interpretation semantics. In other words, it
4082: behaves like this:
1.29 crook 4083:
4084: @itemize @bullet
4085: @item
1.30 anton 4086: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4087: @item
1.30 anton 4088: The @dfn{compilation semantics} of the word are to do something useful
4089: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4090: @end itemize
1.28 crook 4091:
1.44 crook 4092: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4093: performing the interpretation semantics of the word directly; an attempt
4094: to do so will generate an error. It is never necessary to use
4095: @code{compile-only} (and it is not even part of ANS Forth, though it is
4096: provided by many implementations) but it is good etiquette to apply it
4097: to a word that will not behave correctly (and might have unexpected
4098: side-effects) in interpret state. For example, it is only legal to use
4099: the conditional word @code{IF} within a definition. If you forget this
4100: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4101: @code{compile-only} allows the text interpreter to generate a helpful
4102: error message rather than subjecting you to the consequences of your
4103: folly.
4104:
1.29 crook 4105: This example shows the difference between an immediate and a
4106: non-immediate word:
1.28 crook 4107:
1.29 crook 4108: @example
4109: : show-state state @@ . ;
4110: : show-state-now show-state ; immediate
4111: : word1 show-state ;
4112: : word2 show-state-now ;
1.28 crook 4113: @end example
1.23 crook 4114:
1.29 crook 4115: The word @code{immediate} after the definition of @code{show-state-now}
4116: makes that word an immediate word. These definitions introduce a new
4117: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4118: variable, and leaves it on the stack. Therefore, the behaviour of
4119: @code{show-state} is to print a number that represents the current value
4120: of @code{state}.
1.28 crook 4121:
1.29 crook 4122: When you execute @code{word1}, it prints the number 0, indicating that
4123: the system is interpreting. When the text interpreter compiled the
4124: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4125: compilation semantics are to append its interpretation semantics to the
1.29 crook 4126: current definition. When you execute @code{word1}, it performs the
1.30 anton 4127: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4128: (and therefore @code{show-state}) are executed, the system is
4129: interpreting.
1.28 crook 4130:
1.30 anton 4131: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4132: you should have seen the number -1 printed, followed by ``@code{
4133: ok}''. When the text interpreter compiled the definition of
4134: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4135: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4136: semantics. It is executed straight away (even before the text
4137: interpreter has moved on to process another group of characters; the
4138: @code{;} in this example). The effect of executing it are to display the
4139: value of @code{state} @i{at the time that the definition of}
4140: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4141: system is compiling at this time. If you execute @code{word2} it does
4142: nothing at all.
1.28 crook 4143:
1.29 crook 4144: @cindex @code{."}, how it works
4145: Before leaving the subject of immediate words, consider the behaviour of
4146: @code{."} in the definition of @code{greet}, in the previous
4147: section. This word is both a parsing word and an immediate word. Notice
4148: that there is a space between @code{."} and the start of the text
4149: @code{Hello and welcome}, but that there is no space between the last
4150: letter of @code{welcome} and the @code{"} character. The reason for this
4151: is that @code{."} is a Forth word; it must have a space after it so that
4152: the text interpreter can identify it. The @code{"} is not a Forth word;
4153: it is a @dfn{delimiter}. The examples earlier show that, when the string
4154: is displayed, there is neither a space before the @code{H} nor after the
4155: @code{e}. Since @code{."} is an immediate word, it executes at the time
4156: that @code{greet} is defined. When it executes, its behaviour is to
4157: search forward in the input line looking for the delimiter. When it
4158: finds the delimiter, it updates @code{>IN} to point past the
4159: delimiter. It also compiles some magic code into the definition of
4160: @code{greet}; the xt of a run-time routine that prints a text string. It
4161: compiles the string @code{Hello and welcome} into memory so that it is
4162: available to be printed later. When the text interpreter gains control,
4163: the next word it finds in the input stream is @code{;} and so it
4164: terminates the definition of @code{greet}.
1.28 crook 4165:
4166:
4167: @comment ----------------------------------------------
1.29 crook 4168: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4169: @section Forth is written in Forth
4170: @cindex structure of Forth programs
4171:
4172: When you start up a Forth compiler, a large number of definitions
4173: already exist. In Forth, you develop a new application using bottom-up
4174: programming techniques to create new definitions that are defined in
4175: terms of existing definitions. As you create each definition you can
4176: test and debug it interactively.
4177:
4178: If you have tried out the examples in this section, you will probably
4179: have typed them in by hand; when you leave Gforth, your definitions will
4180: be lost. You can avoid this by using a text editor to enter Forth source
4181: code into a file, and then loading code from the file using
1.49 anton 4182: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4183: processed by the text interpreter, just as though you had typed it in by
4184: hand@footnote{Actually, there are some subtle differences -- see
4185: @ref{The Text Interpreter}.}.
4186:
4187: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4188: files for program entry (@pxref{Blocks}).
1.28 crook 4189:
1.29 crook 4190: In common with many, if not most, Forth compilers, most of Gforth is
4191: actually written in Forth. All of the @file{.fs} files in the
4192: installation directory@footnote{For example,
1.30 anton 4193: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4194: study to see examples of Forth programming.
1.28 crook 4195:
1.29 crook 4196: Gforth maintains a history file that records every line that you type to
4197: the text interpreter. This file is preserved between sessions, and is
4198: used to provide a command-line recall facility. If you enter long
4199: definitions by hand, you can use a text editor to paste them out of the
4200: history file into a Forth source file for reuse at a later time
1.49 anton 4201: (for more information @pxref{Command-line editing}).
1.28 crook 4202:
4203:
4204: @comment ----------------------------------------------
1.29 crook 4205: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4206: @section Review - elements of a Forth system
4207: @cindex elements of a Forth system
1.28 crook 4208:
1.29 crook 4209: To summarise this chapter:
1.28 crook 4210:
4211: @itemize @bullet
4212: @item
1.29 crook 4213: Forth programs use @dfn{factoring} to break a problem down into small
4214: fragments called @dfn{words} or @dfn{definitions}.
4215: @item
4216: Forth program development is an interactive process.
4217: @item
4218: The main command loop that accepts input, and controls both
4219: interpretation and compilation, is called the @dfn{text interpreter}
4220: (also known as the @dfn{outer interpreter}).
4221: @item
4222: Forth has a very simple syntax, consisting of words and numbers
4223: separated by spaces or carriage-return characters. Any additional syntax
4224: is imposed by @dfn{parsing words}.
4225: @item
4226: Forth uses a stack to pass parameters between words. As a result, it
4227: uses postfix notation.
4228: @item
4229: To use a word that has previously been defined, the text interpreter
4230: searches for the word in the @dfn{name dictionary}.
4231: @item
1.30 anton 4232: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4233: @item
1.29 crook 4234: The text interpreter uses the value of @code{state} to select between
4235: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4236: semantics} of a word that it encounters.
1.28 crook 4237: @item
1.30 anton 4238: The relationship between the @dfn{interpretation semantics} and
4239: @dfn{compilation semantics} for a word
1.29 crook 4240: depend upon the way in which the word was defined (for example, whether
4241: it is an @dfn{immediate} word).
1.28 crook 4242: @item
1.29 crook 4243: Forth definitions can be implemented in Forth (called @dfn{high-level
4244: definitions}) or in some other way (usually a lower-level language and
4245: as a result often called @dfn{low-level definitions}, @dfn{code
4246: definitions} or @dfn{primitives}).
1.28 crook 4247: @item
1.29 crook 4248: Many Forth systems are implemented mainly in Forth.
1.28 crook 4249: @end itemize
4250:
4251:
1.29 crook 4252: @comment ----------------------------------------------
1.48 anton 4253: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4254: @section Where To Go Next
4255: @cindex where to go next
1.28 crook 4256:
1.29 crook 4257: Amazing as it may seem, if you have read (and understood) this far, you
4258: know almost all the fundamentals about the inner workings of a Forth
4259: system. You certainly know enough to be able to read and understand the
4260: rest of this manual and the ANS Forth document, to learn more about the
4261: facilities that Forth in general and Gforth in particular provide. Even
4262: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4263: However, that's not a good idea just yet... better to try writing some
1.29 crook 4264: programs in Gforth.
1.28 crook 4265:
1.29 crook 4266: Forth has such a rich vocabulary that it can be hard to know where to
4267: start in learning it. This section suggests a few sets of words that are
4268: enough to write small but useful programs. Use the word index in this
4269: document to learn more about each word, then try it out and try to write
4270: small definitions using it. Start by experimenting with these words:
1.28 crook 4271:
4272: @itemize @bullet
4273: @item
1.29 crook 4274: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4275: @item
4276: Comparison: @code{MIN MAX =}
4277: @item
4278: Logic: @code{AND OR XOR NOT}
4279: @item
4280: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4281: @item
1.29 crook 4282: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4283: @item
1.29 crook 4284: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4285: @item
1.29 crook 4286: Defining words: @code{: ; CREATE}
1.28 crook 4287: @item
1.29 crook 4288: Memory allocation words: @code{ALLOT ,}
1.28 crook 4289: @item
1.29 crook 4290: Tools: @code{SEE WORDS .S MARKER}
4291: @end itemize
4292:
4293: When you have mastered those, go on to:
4294:
4295: @itemize @bullet
1.28 crook 4296: @item
1.29 crook 4297: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4298: @item
1.29 crook 4299: Memory access: @code{@@ !}
1.28 crook 4300: @end itemize
1.23 crook 4301:
1.29 crook 4302: When you have mastered these, there's nothing for it but to read through
4303: the whole of this manual and find out what you've missed.
4304:
4305: @comment ----------------------------------------------
1.48 anton 4306: @node Exercises, , Where to go next, Introduction
1.29 crook 4307: @section Exercises
4308: @cindex exercises
4309:
4310: TODO: provide a set of programming excercises linked into the stuff done
4311: already and into other sections of the manual. Provide solutions to all
4312: the exercises in a .fs file in the distribution.
4313:
4314: @c Get some inspiration from Starting Forth and Kelly&Spies.
4315:
4316: @c excercises:
4317: @c 1. take inches and convert to feet and inches.
4318: @c 2. take temperature and convert from fahrenheight to celcius;
4319: @c may need to care about symmetric vs floored??
4320: @c 3. take input line and do character substitution
4321: @c to encipher or decipher
4322: @c 4. as above but work on a file for in and out
4323: @c 5. take input line and convert to pig-latin
4324: @c
4325: @c thing of sets of things to exercise then come up with
4326: @c problems that need those things.
4327:
4328:
1.26 crook 4329: @c ******************************************************************
1.29 crook 4330: @node Words, Error messages, Introduction, Top
1.1 anton 4331: @chapter Forth Words
1.26 crook 4332: @cindex words
1.1 anton 4333:
4334: @menu
4335: * Notation::
1.65 anton 4336: * Case insensitivity::
4337: * Comments::
4338: * Boolean Flags::
1.1 anton 4339: * Arithmetic::
4340: * Stack Manipulation::
1.5 anton 4341: * Memory::
1.1 anton 4342: * Control Structures::
4343: * Defining Words::
1.65 anton 4344: * Interpretation and Compilation Semantics::
1.47 crook 4345: * Tokens for Words::
1.81 anton 4346: * Compiling words::
1.65 anton 4347: * The Text Interpreter::
1.111 anton 4348: * The Input Stream::
1.65 anton 4349: * Word Lists::
4350: * Environmental Queries::
1.12 anton 4351: * Files::
4352: * Blocks::
4353: * Other I/O::
1.121 anton 4354: * OS command line arguments::
1.78 anton 4355: * Locals::
4356: * Structures::
4357: * Object-oriented Forth::
1.12 anton 4358: * Programming Tools::
1.150 anton 4359: * C Interface::
1.12 anton 4360: * Assembler and Code Words::
4361: * Threading Words::
1.65 anton 4362: * Passing Commands to the OS::
4363: * Keeping track of Time::
4364: * Miscellaneous Words::
1.1 anton 4365: @end menu
4366:
1.65 anton 4367: @node Notation, Case insensitivity, Words, Words
1.1 anton 4368: @section Notation
4369: @cindex notation of glossary entries
4370: @cindex format of glossary entries
4371: @cindex glossary notation format
4372: @cindex word glossary entry format
4373:
4374: The Forth words are described in this section in the glossary notation
1.67 anton 4375: that has become a de-facto standard for Forth texts:
1.1 anton 4376:
4377: @format
1.29 crook 4378: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4379: @end format
1.29 crook 4380: @i{Description}
1.1 anton 4381:
4382: @table @var
4383: @item word
1.28 crook 4384: The name of the word.
1.1 anton 4385:
4386: @item Stack effect
4387: @cindex stack effect
1.29 crook 4388: The stack effect is written in the notation @code{@i{before} --
4389: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4390: stack entries before and after the execution of the word. The rest of
4391: the stack is not touched by the word. The top of stack is rightmost,
4392: i.e., a stack sequence is written as it is typed in. Note that Gforth
4393: uses a separate floating point stack, but a unified stack
1.29 crook 4394: notation. Also, return stack effects are not shown in @i{stack
4395: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4396: the type and/or the function of the item. See below for a discussion of
4397: the types.
4398:
4399: All words have two stack effects: A compile-time stack effect and a
4400: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4401: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4402: this standard behaviour, or the word does other unusual things at
4403: compile time, both stack effects are shown; otherwise only the run-time
4404: stack effect is shown.
4405:
4406: @cindex pronounciation of words
4407: @item pronunciation
4408: How the word is pronounced.
4409:
4410: @cindex wordset
1.67 anton 4411: @cindex environment wordset
1.1 anton 4412: @item wordset
1.21 crook 4413: The ANS Forth standard is divided into several word sets. A standard
4414: system need not support all of them. Therefore, in theory, the fewer
4415: word sets your program uses the more portable it will be. However, we
4416: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4417: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4418: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4419: describes words that will work in future releases of Gforth;
4420: @code{gforth-internal} words are more volatile. Environmental query
4421: strings are also displayed like words; you can recognize them by the
1.21 crook 4422: @code{environment} in the word set field.
1.1 anton 4423:
4424: @item Description
4425: A description of the behaviour of the word.
4426: @end table
4427:
4428: @cindex types of stack items
4429: @cindex stack item types
4430: The type of a stack item is specified by the character(s) the name
4431: starts with:
4432:
4433: @table @code
4434: @item f
4435: @cindex @code{f}, stack item type
4436: Boolean flags, i.e. @code{false} or @code{true}.
4437: @item c
4438: @cindex @code{c}, stack item type
4439: Char
4440: @item w
4441: @cindex @code{w}, stack item type
4442: Cell, can contain an integer or an address
4443: @item n
4444: @cindex @code{n}, stack item type
4445: signed integer
4446: @item u
4447: @cindex @code{u}, stack item type
4448: unsigned integer
4449: @item d
4450: @cindex @code{d}, stack item type
4451: double sized signed integer
4452: @item ud
4453: @cindex @code{ud}, stack item type
4454: double sized unsigned integer
4455: @item r
4456: @cindex @code{r}, stack item type
4457: Float (on the FP stack)
1.21 crook 4458: @item a-
1.1 anton 4459: @cindex @code{a_}, stack item type
4460: Cell-aligned address
1.21 crook 4461: @item c-
1.1 anton 4462: @cindex @code{c_}, stack item type
4463: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4464: @item f-
1.1 anton 4465: @cindex @code{f_}, stack item type
4466: Float-aligned address
1.21 crook 4467: @item df-
1.1 anton 4468: @cindex @code{df_}, stack item type
4469: Address aligned for IEEE double precision float
1.21 crook 4470: @item sf-
1.1 anton 4471: @cindex @code{sf_}, stack item type
4472: Address aligned for IEEE single precision float
4473: @item xt
4474: @cindex @code{xt}, stack item type
4475: Execution token, same size as Cell
4476: @item wid
4477: @cindex @code{wid}, stack item type
1.21 crook 4478: Word list ID, same size as Cell
1.68 anton 4479: @item ior, wior
4480: @cindex ior type description
4481: @cindex wior type description
4482: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4483: @item f83name
4484: @cindex @code{f83name}, stack item type
4485: Pointer to a name structure
4486: @item "
4487: @cindex @code{"}, stack item type
1.12 anton 4488: string in the input stream (not on the stack). The terminating character
4489: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4490: quotes.
4491: @end table
4492:
1.65 anton 4493: @comment ----------------------------------------------
4494: @node Case insensitivity, Comments, Notation, Words
4495: @section Case insensitivity
4496: @cindex case sensitivity
4497: @cindex upper and lower case
4498:
4499: Gforth is case-insensitive; you can enter definitions and invoke
4500: Standard words using upper, lower or mixed case (however,
4501: @pxref{core-idef, Implementation-defined options, Implementation-defined
4502: options}).
4503:
4504: ANS Forth only @i{requires} implementations to recognise Standard words
4505: when they are typed entirely in upper case. Therefore, a Standard
4506: program must use upper case for all Standard words. You can use whatever
4507: case you like for words that you define, but in a Standard program you
4508: have to use the words in the same case that you defined them.
4509:
4510: Gforth supports case sensitivity through @code{table}s (case-sensitive
4511: wordlists, @pxref{Word Lists}).
4512:
4513: Two people have asked how to convert Gforth to be case-sensitive; while
4514: we think this is a bad idea, you can change all wordlists into tables
4515: like this:
4516:
4517: @example
4518: ' table-find forth-wordlist wordlist-map @ !
4519: @end example
4520:
4521: Note that you now have to type the predefined words in the same case
4522: that we defined them, which are varying. You may want to convert them
4523: to your favourite case before doing this operation (I won't explain how,
4524: because if you are even contemplating doing this, you'd better have
4525: enough knowledge of Forth systems to know this already).
4526:
4527: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4528: @section Comments
1.26 crook 4529: @cindex comments
1.21 crook 4530:
1.29 crook 4531: Forth supports two styles of comment; the traditional @i{in-line} comment,
4532: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4533:
1.44 crook 4534:
1.23 crook 4535: doc-(
1.21 crook 4536: doc-\
1.23 crook 4537: doc-\G
1.21 crook 4538:
1.44 crook 4539:
1.21 crook 4540: @node Boolean Flags, Arithmetic, Comments, Words
4541: @section Boolean Flags
1.26 crook 4542: @cindex Boolean flags
1.21 crook 4543:
4544: A Boolean flag is cell-sized. A cell with all bits clear represents the
4545: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4546: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4547: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4548: @c on and off to Memory?
4549: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4550:
1.21 crook 4551: doc-true
4552: doc-false
1.29 crook 4553: doc-on
4554: doc-off
1.21 crook 4555:
1.44 crook 4556:
1.21 crook 4557: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4558: @section Arithmetic
4559: @cindex arithmetic words
4560:
4561: @cindex division with potentially negative operands
4562: Forth arithmetic is not checked, i.e., you will not hear about integer
4563: overflow on addition or multiplication, you may hear about division by
4564: zero if you are lucky. The operator is written after the operands, but
4565: the operands are still in the original order. I.e., the infix @code{2-1}
4566: corresponds to @code{2 1 -}. Forth offers a variety of division
4567: operators. If you perform division with potentially negative operands,
4568: you do not want to use @code{/} or @code{/mod} with its undefined
4569: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4570: former, @pxref{Mixed precision}).
1.26 crook 4571: @comment TODO discuss the different division forms and the std approach
1.1 anton 4572:
4573: @menu
4574: * Single precision::
1.67 anton 4575: * Double precision:: Double-cell integer arithmetic
1.1 anton 4576: * Bitwise operations::
1.67 anton 4577: * Numeric comparison::
1.29 crook 4578: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4579: * Floating Point::
4580: @end menu
4581:
1.67 anton 4582: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4583: @subsection Single precision
4584: @cindex single precision arithmetic words
4585:
1.67 anton 4586: @c !! cell undefined
4587:
4588: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4589: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4590: treat them. For the rules used by the text interpreter for recognising
4591: single-precision integers see @ref{Number Conversion}.
1.21 crook 4592:
1.67 anton 4593: These words are all defined for signed operands, but some of them also
4594: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4595: @code{*}.
1.44 crook 4596:
1.1 anton 4597: doc-+
1.21 crook 4598: doc-1+
1.128 anton 4599: doc-under+
1.1 anton 4600: doc--
1.21 crook 4601: doc-1-
1.1 anton 4602: doc-*
4603: doc-/
4604: doc-mod
4605: doc-/mod
4606: doc-negate
4607: doc-abs
4608: doc-min
4609: doc-max
1.27 crook 4610: doc-floored
1.1 anton 4611:
1.44 crook 4612:
1.67 anton 4613: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4614: @subsection Double precision
4615: @cindex double precision arithmetic words
4616:
1.49 anton 4617: For the rules used by the text interpreter for
4618: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4619:
4620: A double precision number is represented by a cell pair, with the most
1.67 anton 4621: significant cell at the TOS. It is trivial to convert an unsigned single
4622: to a double: simply push a @code{0} onto the TOS. Since numbers are
4623: represented by Gforth using 2's complement arithmetic, converting a
4624: signed single to a (signed) double requires sign-extension across the
4625: most significant cell. This can be achieved using @code{s>d}. The moral
4626: of the story is that you cannot convert a number without knowing whether
4627: it represents an unsigned or a signed number.
1.21 crook 4628:
1.67 anton 4629: These words are all defined for signed operands, but some of them also
4630: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4631:
1.21 crook 4632: doc-s>d
1.67 anton 4633: doc-d>s
1.21 crook 4634: doc-d+
4635: doc-d-
4636: doc-dnegate
4637: doc-dabs
4638: doc-dmin
4639: doc-dmax
4640:
1.44 crook 4641:
1.67 anton 4642: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4643: @subsection Bitwise operations
4644: @cindex bitwise operation words
4645:
4646:
4647: doc-and
4648: doc-or
4649: doc-xor
4650: doc-invert
4651: doc-lshift
4652: doc-rshift
4653: doc-2*
4654: doc-d2*
4655: doc-2/
4656: doc-d2/
4657:
4658:
4659: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4660: @subsection Numeric comparison
4661: @cindex numeric comparison words
4662:
1.67 anton 4663: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4664: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4665:
1.28 crook 4666: doc-<
4667: doc-<=
4668: doc-<>
4669: doc-=
4670: doc->
4671: doc->=
4672:
1.21 crook 4673: doc-0<
1.23 crook 4674: doc-0<=
1.21 crook 4675: doc-0<>
4676: doc-0=
1.23 crook 4677: doc-0>
4678: doc-0>=
1.28 crook 4679:
4680: doc-u<
4681: doc-u<=
1.44 crook 4682: @c u<> and u= exist but are the same as <> and =
1.31 anton 4683: @c doc-u<>
4684: @c doc-u=
1.28 crook 4685: doc-u>
4686: doc-u>=
4687:
4688: doc-within
4689:
4690: doc-d<
4691: doc-d<=
4692: doc-d<>
4693: doc-d=
4694: doc-d>
4695: doc-d>=
1.23 crook 4696:
1.21 crook 4697: doc-d0<
1.23 crook 4698: doc-d0<=
4699: doc-d0<>
1.21 crook 4700: doc-d0=
1.23 crook 4701: doc-d0>
4702: doc-d0>=
4703:
1.21 crook 4704: doc-du<
1.28 crook 4705: doc-du<=
1.44 crook 4706: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4707: @c doc-du<>
4708: @c doc-du=
1.28 crook 4709: doc-du>
4710: doc-du>=
1.1 anton 4711:
1.44 crook 4712:
1.21 crook 4713: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4714: @subsection Mixed precision
4715: @cindex mixed precision arithmetic words
4716:
1.44 crook 4717:
1.1 anton 4718: doc-m+
4719: doc-*/
4720: doc-*/mod
4721: doc-m*
4722: doc-um*
4723: doc-m*/
4724: doc-um/mod
4725: doc-fm/mod
4726: doc-sm/rem
4727:
1.44 crook 4728:
1.21 crook 4729: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4730: @subsection Floating Point
4731: @cindex floating point arithmetic words
4732:
1.49 anton 4733: For the rules used by the text interpreter for
4734: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4735:
1.67 anton 4736: Gforth has a separate floating point stack, but the documentation uses
4737: the unified notation.@footnote{It's easy to generate the separate
4738: notation from that by just separating the floating-point numbers out:
4739: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4740: r3 )}.}
1.1 anton 4741:
4742: @cindex floating-point arithmetic, pitfalls
4743: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4744: unwary (e.g., floating point addition is not associative) and even a
4745: few for the wary. You should not use them unless you know what you are
4746: doing or you don't care that the results you get are totally bogus. If
4747: you want to learn about the problems of floating point numbers (and
4748: how to avoid them), you might start with @cite{David Goldberg,
4749: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4750: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4751: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4752:
1.44 crook 4753:
1.21 crook 4754: doc-d>f
4755: doc-f>d
1.1 anton 4756: doc-f+
4757: doc-f-
4758: doc-f*
4759: doc-f/
4760: doc-fnegate
4761: doc-fabs
4762: doc-fmax
4763: doc-fmin
4764: doc-floor
4765: doc-fround
4766: doc-f**
4767: doc-fsqrt
4768: doc-fexp
4769: doc-fexpm1
4770: doc-fln
4771: doc-flnp1
4772: doc-flog
4773: doc-falog
1.32 anton 4774: doc-f2*
4775: doc-f2/
4776: doc-1/f
4777: doc-precision
4778: doc-set-precision
4779:
4780: @cindex angles in trigonometric operations
4781: @cindex trigonometric operations
4782: Angles in floating point operations are given in radians (a full circle
4783: has 2 pi radians).
4784:
1.1 anton 4785: doc-fsin
4786: doc-fcos
4787: doc-fsincos
4788: doc-ftan
4789: doc-fasin
4790: doc-facos
4791: doc-fatan
4792: doc-fatan2
4793: doc-fsinh
4794: doc-fcosh
4795: doc-ftanh
4796: doc-fasinh
4797: doc-facosh
4798: doc-fatanh
1.21 crook 4799: doc-pi
1.28 crook 4800:
1.32 anton 4801: @cindex equality of floats
4802: @cindex floating-point comparisons
1.31 anton 4803: One particular problem with floating-point arithmetic is that comparison
4804: for equality often fails when you would expect it to succeed. For this
4805: reason approximate equality is often preferred (but you still have to
1.67 anton 4806: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4807: differently from what you might expect. The comparison words are:
1.31 anton 4808:
4809: doc-f~rel
4810: doc-f~abs
1.68 anton 4811: doc-f~
1.31 anton 4812: doc-f=
4813: doc-f<>
4814:
4815: doc-f<
4816: doc-f<=
4817: doc-f>
4818: doc-f>=
4819:
1.21 crook 4820: doc-f0<
1.28 crook 4821: doc-f0<=
4822: doc-f0<>
1.21 crook 4823: doc-f0=
1.28 crook 4824: doc-f0>
4825: doc-f0>=
4826:
1.1 anton 4827:
4828: @node Stack Manipulation, Memory, Arithmetic, Words
4829: @section Stack Manipulation
4830: @cindex stack manipulation words
4831:
4832: @cindex floating-point stack in the standard
1.21 crook 4833: Gforth maintains a number of separate stacks:
4834:
1.29 crook 4835: @cindex data stack
4836: @cindex parameter stack
1.21 crook 4837: @itemize @bullet
4838: @item
1.29 crook 4839: A data stack (also known as the @dfn{parameter stack}) -- for
4840: characters, cells, addresses, and double cells.
1.21 crook 4841:
1.29 crook 4842: @cindex floating-point stack
1.21 crook 4843: @item
1.44 crook 4844: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4845:
1.29 crook 4846: @cindex return stack
1.21 crook 4847: @item
1.44 crook 4848: A return stack -- for holding the return addresses of colon
1.32 anton 4849: definitions and other (non-FP) data.
1.21 crook 4850:
1.29 crook 4851: @cindex locals stack
1.21 crook 4852: @item
1.44 crook 4853: A locals stack -- for holding local variables.
1.21 crook 4854: @end itemize
4855:
1.1 anton 4856: @menu
4857: * Data stack::
4858: * Floating point stack::
4859: * Return stack::
4860: * Locals stack::
4861: * Stack pointer manipulation::
4862: @end menu
4863:
4864: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4865: @subsection Data stack
4866: @cindex data stack manipulation words
4867: @cindex stack manipulations words, data stack
4868:
1.44 crook 4869:
1.1 anton 4870: doc-drop
4871: doc-nip
4872: doc-dup
4873: doc-over
4874: doc-tuck
4875: doc-swap
1.21 crook 4876: doc-pick
1.1 anton 4877: doc-rot
4878: doc--rot
4879: doc-?dup
4880: doc-roll
4881: doc-2drop
4882: doc-2nip
4883: doc-2dup
4884: doc-2over
4885: doc-2tuck
4886: doc-2swap
4887: doc-2rot
4888:
1.44 crook 4889:
1.1 anton 4890: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4891: @subsection Floating point stack
4892: @cindex floating-point stack manipulation words
4893: @cindex stack manipulation words, floating-point stack
4894:
1.32 anton 4895: Whilst every sane Forth has a separate floating-point stack, it is not
4896: strictly required; an ANS Forth system could theoretically keep
4897: floating-point numbers on the data stack. As an additional difficulty,
4898: you don't know how many cells a floating-point number takes. It is
4899: reportedly possible to write words in a way that they work also for a
4900: unified stack model, but we do not recommend trying it. Instead, just
4901: say that your program has an environmental dependency on a separate
4902: floating-point stack.
4903:
4904: doc-floating-stack
4905:
1.1 anton 4906: doc-fdrop
4907: doc-fnip
4908: doc-fdup
4909: doc-fover
4910: doc-ftuck
4911: doc-fswap
1.21 crook 4912: doc-fpick
1.1 anton 4913: doc-frot
4914:
1.44 crook 4915:
1.1 anton 4916: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4917: @subsection Return stack
4918: @cindex return stack manipulation words
4919: @cindex stack manipulation words, return stack
4920:
1.32 anton 4921: @cindex return stack and locals
4922: @cindex locals and return stack
4923: A Forth system is allowed to keep local variables on the
4924: return stack. This is reasonable, as local variables usually eliminate
4925: the need to use the return stack explicitly. So, if you want to produce
4926: a standard compliant program and you are using local variables in a
4927: word, forget about return stack manipulations in that word (refer to the
4928: standard document for the exact rules).
4929:
1.1 anton 4930: doc->r
4931: doc-r>
4932: doc-r@
4933: doc-rdrop
4934: doc-2>r
4935: doc-2r>
4936: doc-2r@
4937: doc-2rdrop
4938:
1.44 crook 4939:
1.1 anton 4940: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4941: @subsection Locals stack
4942:
1.78 anton 4943: Gforth uses an extra locals stack. It is described, along with the
4944: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4945:
1.1 anton 4946: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4947: @subsection Stack pointer manipulation
4948: @cindex stack pointer manipulation words
4949:
1.44 crook 4950: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4951: doc-sp0
1.1 anton 4952: doc-sp@
4953: doc-sp!
1.21 crook 4954: doc-fp0
1.1 anton 4955: doc-fp@
4956: doc-fp!
1.21 crook 4957: doc-rp0
1.1 anton 4958: doc-rp@
4959: doc-rp!
1.21 crook 4960: doc-lp0
1.1 anton 4961: doc-lp@
4962: doc-lp!
4963:
1.44 crook 4964:
1.1 anton 4965: @node Memory, Control Structures, Stack Manipulation, Words
4966: @section Memory
1.26 crook 4967: @cindex memory words
1.1 anton 4968:
1.32 anton 4969: @menu
4970: * Memory model::
4971: * Dictionary allocation::
4972: * Heap Allocation::
4973: * Memory Access::
4974: * Address arithmetic::
4975: * Memory Blocks::
4976: @end menu
4977:
1.67 anton 4978: In addition to the standard Forth memory allocation words, there is also
4979: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4980: garbage collector}.
4981:
1.32 anton 4982: @node Memory model, Dictionary allocation, Memory, Memory
4983: @subsection ANS Forth and Gforth memory models
4984:
4985: @c The ANS Forth description is a mess (e.g., is the heap part of
4986: @c the dictionary?), so let's not stick to closely with it.
4987:
1.67 anton 4988: ANS Forth considers a Forth system as consisting of several address
4989: spaces, of which only @dfn{data space} is managed and accessible with
4990: the memory words. Memory not necessarily in data space includes the
4991: stacks, the code (called code space) and the headers (called name
4992: space). In Gforth everything is in data space, but the code for the
4993: primitives is usually read-only.
1.32 anton 4994:
4995: Data space is divided into a number of areas: The (data space portion of
4996: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4997: refer to the search data structure embodied in word lists and headers,
4998: because it is used for looking up names, just as you would in a
4999: conventional dictionary.}, the heap, and a number of system-allocated
5000: buffers.
5001:
1.68 anton 5002: @cindex address arithmetic restrictions, ANS vs. Gforth
5003: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5004: In ANS Forth data space is also divided into contiguous regions. You
5005: can only use address arithmetic within a contiguous region, not between
5006: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5007: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5008: allocation}).
5009:
5010: Gforth provides one big address space, and address arithmetic can be
5011: performed between any addresses. However, in the dictionary headers or
5012: code are interleaved with data, so almost the only contiguous data space
5013: regions there are those described by ANS Forth as contiguous; but you
5014: can be sure that the dictionary is allocated towards increasing
5015: addresses even between contiguous regions. The memory order of
5016: allocations in the heap is platform-dependent (and possibly different
5017: from one run to the next).
5018:
1.27 crook 5019:
1.32 anton 5020: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5021: @subsection Dictionary allocation
1.27 crook 5022: @cindex reserving data space
5023: @cindex data space - reserving some
5024:
1.32 anton 5025: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5026: you want to deallocate X, you also deallocate everything
5027: allocated after X.
5028:
1.68 anton 5029: @cindex contiguous regions in dictionary allocation
1.32 anton 5030: The allocations using the words below are contiguous and grow the region
5031: towards increasing addresses. Other words that allocate dictionary
5032: memory of any kind (i.e., defining words including @code{:noname}) end
5033: the contiguous region and start a new one.
5034:
5035: In ANS Forth only @code{create}d words are guaranteed to produce an
5036: address that is the start of the following contiguous region. In
5037: particular, the cell allocated by @code{variable} is not guaranteed to
5038: be contiguous with following @code{allot}ed memory.
5039:
5040: You can deallocate memory by using @code{allot} with a negative argument
5041: (with some restrictions, see @code{allot}). For larger deallocations use
5042: @code{marker}.
1.27 crook 5043:
1.29 crook 5044:
1.27 crook 5045: doc-here
5046: doc-unused
5047: doc-allot
5048: doc-c,
1.29 crook 5049: doc-f,
1.27 crook 5050: doc-,
5051: doc-2,
5052:
1.32 anton 5053: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5054: course you should allocate memory in an aligned way, too. I.e., before
5055: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5056: The words below align @code{here} if it is not already. Basically it is
5057: only already aligned for a type, if the last allocation was a multiple
5058: of the size of this type and if @code{here} was aligned for this type
5059: before.
5060:
5061: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5062: ANS Forth (@code{maxalign}ed in Gforth).
5063:
5064: doc-align
5065: doc-falign
5066: doc-sfalign
5067: doc-dfalign
5068: doc-maxalign
5069: doc-cfalign
5070:
5071:
5072: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5073: @subsection Heap allocation
5074: @cindex heap allocation
5075: @cindex dynamic allocation of memory
5076: @cindex memory-allocation word set
5077:
1.68 anton 5078: @cindex contiguous regions and heap allocation
1.32 anton 5079: Heap allocation supports deallocation of allocated memory in any
5080: order. Dictionary allocation is not affected by it (i.e., it does not
5081: end a contiguous region). In Gforth, these words are implemented using
5082: the standard C library calls malloc(), free() and resize().
5083:
1.68 anton 5084: The memory region produced by one invocation of @code{allocate} or
5085: @code{resize} is internally contiguous. There is no contiguity between
5086: such a region and any other region (including others allocated from the
5087: heap).
5088:
1.32 anton 5089: doc-allocate
5090: doc-free
5091: doc-resize
5092:
1.27 crook 5093:
1.32 anton 5094: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5095: @subsection Memory Access
5096: @cindex memory access words
5097:
5098: doc-@
5099: doc-!
5100: doc-+!
5101: doc-c@
5102: doc-c!
5103: doc-2@
5104: doc-2!
5105: doc-f@
5106: doc-f!
5107: doc-sf@
5108: doc-sf!
5109: doc-df@
5110: doc-df!
1.144 anton 5111: doc-sw@
5112: doc-uw@
5113: doc-w!
5114: doc-sl@
5115: doc-ul@
5116: doc-l!
1.68 anton 5117:
1.32 anton 5118: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5119: @subsection Address arithmetic
1.1 anton 5120: @cindex address arithmetic words
5121:
1.67 anton 5122: Address arithmetic is the foundation on which you can build data
5123: structures like arrays, records (@pxref{Structures}) and objects
5124: (@pxref{Object-oriented Forth}).
1.32 anton 5125:
1.68 anton 5126: @cindex address unit
5127: @cindex au (address unit)
1.1 anton 5128: ANS Forth does not specify the sizes of the data types. Instead, it
5129: offers a number of words for computing sizes and doing address
1.29 crook 5130: arithmetic. Address arithmetic is performed in terms of address units
5131: (aus); on most systems the address unit is one byte. Note that a
5132: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5133: platforms where it is a noop, it compiles to nothing).
1.1 anton 5134:
1.67 anton 5135: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5136: you have the address of a cell, perform @code{1 cells +}, and you will
5137: have the address of the next cell.
5138:
1.68 anton 5139: @cindex contiguous regions and address arithmetic
1.67 anton 5140: In ANS Forth you can perform address arithmetic only within a contiguous
5141: region, i.e., if you have an address into one region, you can only add
5142: and subtract such that the result is still within the region; you can
5143: only subtract or compare addresses from within the same contiguous
5144: region. Reasons: several contiguous regions can be arranged in memory
5145: in any way; on segmented systems addresses may have unusual
5146: representations, such that address arithmetic only works within a
5147: region. Gforth provides a few more guarantees (linear address space,
5148: dictionary grows upwards), but in general I have found it easy to stay
5149: within contiguous regions (exception: computing and comparing to the
5150: address just beyond the end of an array).
5151:
1.1 anton 5152: @cindex alignment of addresses for types
5153: ANS Forth also defines words for aligning addresses for specific
5154: types. Many computers require that accesses to specific data types
5155: must only occur at specific addresses; e.g., that cells may only be
5156: accessed at addresses divisible by 4. Even if a machine allows unaligned
5157: accesses, it can usually perform aligned accesses faster.
5158:
5159: For the performance-conscious: alignment operations are usually only
5160: necessary during the definition of a data structure, not during the
5161: (more frequent) accesses to it.
5162:
5163: ANS Forth defines no words for character-aligning addresses. This is not
5164: an oversight, but reflects the fact that addresses that are not
5165: char-aligned have no use in the standard and therefore will not be
5166: created.
5167:
5168: @cindex @code{CREATE} and alignment
1.29 crook 5169: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5170: are cell-aligned; in addition, Gforth guarantees that these addresses
5171: are aligned for all purposes.
5172:
1.26 crook 5173: Note that the ANS Forth word @code{char} has nothing to do with address
5174: arithmetic.
1.1 anton 5175:
1.44 crook 5176:
1.1 anton 5177: doc-chars
5178: doc-char+
5179: doc-cells
5180: doc-cell+
5181: doc-cell
5182: doc-aligned
5183: doc-floats
5184: doc-float+
5185: doc-float
5186: doc-faligned
5187: doc-sfloats
5188: doc-sfloat+
5189: doc-sfaligned
5190: doc-dfloats
5191: doc-dfloat+
5192: doc-dfaligned
5193: doc-maxaligned
5194: doc-cfaligned
5195: doc-address-unit-bits
1.145 anton 5196: doc-/w
5197: doc-/l
1.44 crook 5198:
1.32 anton 5199: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5200: @subsection Memory Blocks
5201: @cindex memory block words
1.27 crook 5202: @cindex character strings - moving and copying
5203:
1.49 anton 5204: Memory blocks often represent character strings; For ways of storing
5205: character strings in memory see @ref{String Formats}. For other
5206: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5207:
1.67 anton 5208: A few of these words work on address unit blocks. In that case, you
5209: usually have to insert @code{CHARS} before the word when working on
5210: character strings. Most words work on character blocks, and expect a
5211: char-aligned address.
5212:
5213: When copying characters between overlapping memory regions, use
5214: @code{chars move} or choose carefully between @code{cmove} and
5215: @code{cmove>}.
1.44 crook 5216:
1.1 anton 5217: doc-move
5218: doc-erase
5219: doc-cmove
5220: doc-cmove>
5221: doc-fill
5222: doc-blank
1.21 crook 5223: doc-compare
1.111 anton 5224: doc-str=
5225: doc-str<
5226: doc-string-prefix?
1.21 crook 5227: doc-search
1.27 crook 5228: doc--trailing
5229: doc-/string
1.82 anton 5230: doc-bounds
1.141 anton 5231: doc-pad
1.111 anton 5232:
1.27 crook 5233: @comment TODO examples
5234:
1.1 anton 5235:
1.26 crook 5236: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5237: @section Control Structures
5238: @cindex control structures
5239:
1.33 anton 5240: Control structures in Forth cannot be used interpretively, only in a
5241: colon definition@footnote{To be precise, they have no interpretation
5242: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5243: not like this limitation, but have not seen a satisfying way around it
5244: yet, although many schemes have been proposed.
1.1 anton 5245:
5246: @menu
1.33 anton 5247: * Selection:: IF ... ELSE ... ENDIF
5248: * Simple Loops:: BEGIN ...
1.29 crook 5249: * Counted Loops:: DO
1.67 anton 5250: * Arbitrary control structures::
5251: * Calls and returns::
1.1 anton 5252: * Exception Handling::
5253: @end menu
5254:
5255: @node Selection, Simple Loops, Control Structures, Control Structures
5256: @subsection Selection
5257: @cindex selection control structures
5258: @cindex control structures for selection
5259:
5260: @cindex @code{IF} control structure
5261: @example
1.29 crook 5262: @i{flag}
1.1 anton 5263: IF
1.29 crook 5264: @i{code}
1.1 anton 5265: ENDIF
5266: @end example
1.21 crook 5267: @noindent
1.33 anton 5268:
1.44 crook 5269: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5270: with any bit set represents truth) @i{code} is executed.
1.33 anton 5271:
1.1 anton 5272: @example
1.29 crook 5273: @i{flag}
1.1 anton 5274: IF
1.29 crook 5275: @i{code1}
1.1 anton 5276: ELSE
1.29 crook 5277: @i{code2}
1.1 anton 5278: ENDIF
5279: @end example
5280:
1.44 crook 5281: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5282: executed.
1.33 anton 5283:
1.1 anton 5284: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5285: standard, and @code{ENDIF} is not, although it is quite popular. We
5286: recommend using @code{ENDIF}, because it is less confusing for people
5287: who also know other languages (and is not prone to reinforcing negative
5288: prejudices against Forth in these people). Adding @code{ENDIF} to a
5289: system that only supplies @code{THEN} is simple:
5290: @example
1.82 anton 5291: : ENDIF POSTPONE then ; immediate
1.1 anton 5292: @end example
5293:
5294: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5295: (adv.)} has the following meanings:
5296: @quotation
5297: ... 2b: following next after in order ... 3d: as a necessary consequence
5298: (if you were there, then you saw them).
5299: @end quotation
5300: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5301: and many other programming languages has the meaning 3d.]
5302:
1.21 crook 5303: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5304: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5305: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5306: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5307: @file{compat/control.fs}.
5308:
5309: @cindex @code{CASE} control structure
5310: @example
1.29 crook 5311: @i{n}
1.1 anton 5312: CASE
1.29 crook 5313: @i{n1} OF @i{code1} ENDOF
5314: @i{n2} OF @i{code2} ENDOF
1.1 anton 5315: @dots{}
1.68 anton 5316: ( n ) @i{default-code} ( n )
1.131 anton 5317: ENDCASE ( )
1.1 anton 5318: @end example
5319:
1.131 anton 5320: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5321: no @i{ni} matches, the optional @i{default-code} is executed. The
5322: optional default case can be added by simply writing the code after
5323: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5324: but must not consume it. The value @i{n} is consumed by this
5325: construction (either by a OF that matches, or by the ENDCASE, if no OF
5326: matches).
1.1 anton 5327:
1.69 anton 5328: @progstyle
1.131 anton 5329: To keep the code understandable, you should ensure that you change the
5330: stack in the same way (wrt. number and types of stack items consumed
5331: and pushed) on all paths through a selection construct.
1.69 anton 5332:
1.1 anton 5333: @node Simple Loops, Counted Loops, Selection, Control Structures
5334: @subsection Simple Loops
5335: @cindex simple loops
5336: @cindex loops without count
5337:
5338: @cindex @code{WHILE} loop
5339: @example
5340: BEGIN
1.29 crook 5341: @i{code1}
5342: @i{flag}
1.1 anton 5343: WHILE
1.29 crook 5344: @i{code2}
1.1 anton 5345: REPEAT
5346: @end example
5347:
1.29 crook 5348: @i{code1} is executed and @i{flag} is computed. If it is true,
5349: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5350: false, execution continues after the @code{REPEAT}.
5351:
5352: @cindex @code{UNTIL} loop
5353: @example
5354: BEGIN
1.29 crook 5355: @i{code}
5356: @i{flag}
1.1 anton 5357: UNTIL
5358: @end example
5359:
1.29 crook 5360: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5361:
1.69 anton 5362: @progstyle
5363: To keep the code understandable, a complete iteration of the loop should
5364: not change the number and types of the items on the stacks.
5365:
1.1 anton 5366: @cindex endless loop
5367: @cindex loops, endless
5368: @example
5369: BEGIN
1.29 crook 5370: @i{code}
1.1 anton 5371: AGAIN
5372: @end example
5373:
5374: This is an endless loop.
5375:
5376: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5377: @subsection Counted Loops
5378: @cindex counted loops
5379: @cindex loops, counted
5380: @cindex @code{DO} loops
5381:
5382: The basic counted loop is:
5383: @example
1.29 crook 5384: @i{limit} @i{start}
1.1 anton 5385: ?DO
1.29 crook 5386: @i{body}
1.1 anton 5387: LOOP
5388: @end example
5389:
1.29 crook 5390: This performs one iteration for every integer, starting from @i{start}
5391: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5392: accessed with @code{i}. For example, the loop:
1.1 anton 5393: @example
5394: 10 0 ?DO
5395: i .
5396: LOOP
5397: @end example
1.21 crook 5398: @noindent
5399: prints @code{0 1 2 3 4 5 6 7 8 9}
5400:
1.1 anton 5401: The index of the innermost loop can be accessed with @code{i}, the index
5402: of the next loop with @code{j}, and the index of the third loop with
5403: @code{k}.
5404:
1.44 crook 5405:
1.1 anton 5406: doc-i
5407: doc-j
5408: doc-k
5409:
1.44 crook 5410:
1.1 anton 5411: The loop control data are kept on the return stack, so there are some
1.21 crook 5412: restrictions on mixing return stack accesses and counted loop words. In
5413: particuler, if you put values on the return stack outside the loop, you
5414: cannot read them inside the loop@footnote{well, not in a way that is
5415: portable.}. If you put values on the return stack within a loop, you
5416: have to remove them before the end of the loop and before accessing the
5417: index of the loop.
1.1 anton 5418:
5419: There are several variations on the counted loop:
5420:
1.21 crook 5421: @itemize @bullet
5422: @item
5423: @code{LEAVE} leaves the innermost counted loop immediately; execution
5424: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5425:
5426: @example
5427: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5428: @end example
5429: prints @code{0 1 2 3}
5430:
1.1 anton 5431:
1.21 crook 5432: @item
5433: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5434: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5435: return stack so @code{EXIT} can get to its return address. For example:
5436:
5437: @example
5438: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5439: @end example
5440: prints @code{0 1 2 3}
5441:
5442:
5443: @item
1.29 crook 5444: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5445: (and @code{LOOP} iterates until they become equal by wrap-around
5446: arithmetic). This behaviour is usually not what you want. Therefore,
5447: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5448: @code{?DO}), which do not enter the loop if @i{start} is greater than
5449: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5450: unsigned loop parameters.
5451:
1.21 crook 5452: @item
5453: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5454: the loop, independent of the loop parameters. Do not use @code{DO}, even
5455: if you know that the loop is entered in any case. Such knowledge tends
5456: to become invalid during maintenance of a program, and then the
5457: @code{DO} will make trouble.
5458:
5459: @item
1.29 crook 5460: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5461: index by @i{n} instead of by 1. The loop is terminated when the border
5462: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5463:
1.21 crook 5464: @example
5465: 4 0 +DO i . 2 +LOOP
5466: @end example
5467: @noindent
5468: prints @code{0 2}
5469:
5470: @example
5471: 4 1 +DO i . 2 +LOOP
5472: @end example
5473: @noindent
5474: prints @code{1 3}
1.1 anton 5475:
1.68 anton 5476: @item
1.1 anton 5477: @cindex negative increment for counted loops
5478: @cindex counted loops with negative increment
1.29 crook 5479: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5480:
1.21 crook 5481: @example
5482: -1 0 ?DO i . -1 +LOOP
5483: @end example
5484: @noindent
5485: prints @code{0 -1}
1.1 anton 5486:
1.21 crook 5487: @example
5488: 0 0 ?DO i . -1 +LOOP
5489: @end example
5490: prints nothing.
1.1 anton 5491:
1.29 crook 5492: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5493: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5494: index by @i{u} each iteration. The loop is terminated when the border
5495: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5496: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5497:
1.21 crook 5498: @example
5499: -2 0 -DO i . 1 -LOOP
5500: @end example
5501: @noindent
5502: prints @code{0 -1}
1.1 anton 5503:
1.21 crook 5504: @example
5505: -1 0 -DO i . 1 -LOOP
5506: @end example
5507: @noindent
5508: prints @code{0}
5509:
5510: @example
5511: 0 0 -DO i . 1 -LOOP
5512: @end example
5513: @noindent
5514: prints nothing.
1.1 anton 5515:
1.21 crook 5516: @end itemize
1.1 anton 5517:
5518: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5519: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5520: for these words that uses only standard words is provided in
5521: @file{compat/loops.fs}.
1.1 anton 5522:
5523:
5524: @cindex @code{FOR} loops
1.26 crook 5525: Another counted loop is:
1.1 anton 5526: @example
1.29 crook 5527: @i{n}
1.1 anton 5528: FOR
1.29 crook 5529: @i{body}
1.1 anton 5530: NEXT
5531: @end example
5532: This is the preferred loop of native code compiler writers who are too
1.26 crook 5533: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5534: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5535: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5536: Forth systems may behave differently, even if they support @code{FOR}
5537: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5538:
5539: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5540: @subsection Arbitrary control structures
5541: @cindex control structures, user-defined
5542:
5543: @cindex control-flow stack
5544: ANS Forth permits and supports using control structures in a non-nested
5545: way. Information about incomplete control structures is stored on the
5546: control-flow stack. This stack may be implemented on the Forth data
5547: stack, and this is what we have done in Gforth.
5548:
5549: @cindex @code{orig}, control-flow stack item
5550: @cindex @code{dest}, control-flow stack item
5551: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5552: entry represents a backward branch target. A few words are the basis for
5553: building any control structure possible (except control structures that
5554: need storage, like calls, coroutines, and backtracking).
5555:
1.44 crook 5556:
1.1 anton 5557: doc-if
5558: doc-ahead
5559: doc-then
5560: doc-begin
5561: doc-until
5562: doc-again
5563: doc-cs-pick
5564: doc-cs-roll
5565:
1.44 crook 5566:
1.21 crook 5567: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5568: manipulate the control-flow stack in a portable way. Without them, you
5569: would need to know how many stack items are occupied by a control-flow
5570: entry (many systems use one cell. In Gforth they currently take three,
5571: but this may change in the future).
5572:
1.1 anton 5573: Some standard control structure words are built from these words:
5574:
1.44 crook 5575:
1.1 anton 5576: doc-else
5577: doc-while
5578: doc-repeat
5579:
1.44 crook 5580:
5581: @noindent
1.1 anton 5582: Gforth adds some more control-structure words:
5583:
1.44 crook 5584:
1.1 anton 5585: doc-endif
5586: doc-?dup-if
5587: doc-?dup-0=-if
5588:
1.44 crook 5589:
5590: @noindent
1.1 anton 5591: Counted loop words constitute a separate group of words:
5592:
1.44 crook 5593:
1.1 anton 5594: doc-?do
5595: doc-+do
5596: doc-u+do
5597: doc--do
5598: doc-u-do
5599: doc-do
5600: doc-for
5601: doc-loop
5602: doc-+loop
5603: doc--loop
5604: doc-next
5605: doc-leave
5606: doc-?leave
5607: doc-unloop
5608: doc-done
5609:
1.44 crook 5610:
1.21 crook 5611: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5612: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5613: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5614: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5615: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5616: resolved (by using one of the loop-ending words or @code{DONE}).
5617:
1.44 crook 5618: @noindent
1.26 crook 5619: Another group of control structure words are:
1.1 anton 5620:
1.44 crook 5621:
1.1 anton 5622: doc-case
5623: doc-endcase
5624: doc-of
5625: doc-endof
5626:
1.44 crook 5627:
1.21 crook 5628: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5629: @code{CS-ROLL}.
1.1 anton 5630:
5631: @subsubsection Programming Style
1.47 crook 5632: @cindex control structures programming style
5633: @cindex programming style, arbitrary control structures
1.1 anton 5634:
5635: In order to ensure readability we recommend that you do not create
5636: arbitrary control structures directly, but define new control structure
5637: words for the control structure you want and use these words in your
1.26 crook 5638: program. For example, instead of writing:
1.1 anton 5639:
5640: @example
1.26 crook 5641: BEGIN
1.1 anton 5642: ...
1.26 crook 5643: IF [ 1 CS-ROLL ]
1.1 anton 5644: ...
1.26 crook 5645: AGAIN THEN
1.1 anton 5646: @end example
5647:
1.21 crook 5648: @noindent
1.1 anton 5649: we recommend defining control structure words, e.g.,
5650:
5651: @example
1.26 crook 5652: : WHILE ( DEST -- ORIG DEST )
5653: POSTPONE IF
5654: 1 CS-ROLL ; immediate
5655:
5656: : REPEAT ( orig dest -- )
5657: POSTPONE AGAIN
5658: POSTPONE THEN ; immediate
1.1 anton 5659: @end example
5660:
1.21 crook 5661: @noindent
1.1 anton 5662: and then using these to create the control structure:
5663:
5664: @example
1.26 crook 5665: BEGIN
1.1 anton 5666: ...
1.26 crook 5667: WHILE
1.1 anton 5668: ...
1.26 crook 5669: REPEAT
1.1 anton 5670: @end example
5671:
5672: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5673: @code{WHILE} are predefined, so in this example it would not be
5674: necessary to define them.
5675:
5676: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5677: @subsection Calls and returns
5678: @cindex calling a definition
5679: @cindex returning from a definition
5680:
1.3 anton 5681: @cindex recursive definitions
5682: A definition can be called simply be writing the name of the definition
1.26 crook 5683: to be called. Normally a definition is invisible during its own
1.3 anton 5684: definition. If you want to write a directly recursive definition, you
1.26 crook 5685: can use @code{recursive} to make the current definition visible, or
5686: @code{recurse} to call the current definition directly.
1.3 anton 5687:
1.44 crook 5688:
1.3 anton 5689: doc-recursive
5690: doc-recurse
5691:
1.44 crook 5692:
1.21 crook 5693: @comment TODO add example of the two recursion methods
1.12 anton 5694: @quotation
5695: @progstyle
5696: I prefer using @code{recursive} to @code{recurse}, because calling the
5697: definition by name is more descriptive (if the name is well-chosen) than
5698: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5699: implementation, it is much better to read (and think) ``now sort the
5700: partitions'' than to read ``now do a recursive call''.
5701: @end quotation
1.3 anton 5702:
1.29 crook 5703: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5704:
5705: @example
1.28 crook 5706: Defer foo
1.3 anton 5707:
5708: : bar ( ... -- ... )
5709: ... foo ... ;
5710:
5711: :noname ( ... -- ... )
5712: ... bar ... ;
5713: IS foo
5714: @end example
5715:
1.170 pazsan 5716: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5717:
1.26 crook 5718: The current definition returns control to the calling definition when
1.33 anton 5719: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5720:
5721: doc-exit
5722: doc-;s
5723:
1.44 crook 5724:
1.1 anton 5725: @node Exception Handling, , Calls and returns, Control Structures
5726: @subsection Exception Handling
1.26 crook 5727: @cindex exceptions
1.1 anton 5728:
1.68 anton 5729: @c quit is a very bad idea for error handling,
5730: @c because it does not translate into a THROW
5731: @c it also does not belong into this chapter
5732:
5733: If a word detects an error condition that it cannot handle, it can
5734: @code{throw} an exception. In the simplest case, this will terminate
5735: your program, and report an appropriate error.
1.21 crook 5736:
1.68 anton 5737: doc-throw
1.1 anton 5738:
1.69 anton 5739: @code{Throw} consumes a cell-sized error number on the stack. There are
5740: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5741: Gforth (and most other systems) you can use the iors produced by various
5742: words as error numbers (e.g., a typical use of @code{allocate} is
5743: @code{allocate throw}). Gforth also provides the word @code{exception}
5744: to define your own error numbers (with decent error reporting); an ANS
5745: Forth version of this word (but without the error messages) is available
5746: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5747: numbers (anything outside the range -4095..0), but won't get nice error
5748: messages, only numbers. For example, try:
5749:
5750: @example
1.69 anton 5751: -10 throw \ ANS defined
5752: -267 throw \ system defined
5753: s" my error" exception throw \ user defined
5754: 7 throw \ arbitrary number
1.68 anton 5755: @end example
5756:
5757: doc---exception-exception
1.1 anton 5758:
1.69 anton 5759: A common idiom to @code{THROW} a specific error if a flag is true is
5760: this:
5761:
5762: @example
5763: @code{( flag ) 0<> @i{errno} and throw}
5764: @end example
5765:
5766: Your program can provide exception handlers to catch exceptions. An
5767: exception handler can be used to correct the problem, or to clean up
5768: some data structures and just throw the exception to the next exception
5769: handler. Note that @code{throw} jumps to the dynamically innermost
5770: exception handler. The system's exception handler is outermost, and just
5771: prints an error and restarts command-line interpretation (or, in batch
5772: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5773:
1.68 anton 5774: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5775:
1.68 anton 5776: doc-catch
1.160 anton 5777: doc-nothrow
1.68 anton 5778:
5779: The most common use of exception handlers is to clean up the state when
5780: an error happens. E.g.,
1.1 anton 5781:
1.26 crook 5782: @example
1.68 anton 5783: base @ >r hex \ actually the hex should be inside foo, or we h
5784: ['] foo catch ( nerror|0 )
5785: r> base !
1.69 anton 5786: ( nerror|0 ) throw \ pass it on
1.26 crook 5787: @end example
1.1 anton 5788:
1.69 anton 5789: A use of @code{catch} for handling the error @code{myerror} might look
5790: like this:
1.44 crook 5791:
1.68 anton 5792: @example
1.69 anton 5793: ['] foo catch
5794: CASE
1.160 anton 5795: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5796: dup throw \ default: pass other errors on, do nothing on non-errors
5797: ENDCASE
1.68 anton 5798: @end example
1.44 crook 5799:
1.68 anton 5800: Having to wrap the code into a separate word is often cumbersome,
5801: therefore Gforth provides an alternative syntax:
1.1 anton 5802:
5803: @example
1.69 anton 5804: TRY
1.68 anton 5805: @i{code1}
1.172 anton 5806: IFERROR
5807: @i{code2}
5808: THEN
5809: @i{code3}
1.69 anton 5810: ENDTRY
1.1 anton 5811: @end example
5812:
1.172 anton 5813: This performs @i{code1}. If @i{code1} completes normally, execution
5814: continues with @i{code3}. If @i{code1} or there is an exception
5815: before @code{endtry}, the stacks are reset to the state during
5816: @code{try}, the throw value is pushed on the data stack, and execution
5817: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5818:
1.68 anton 5819: doc-try
5820: doc-endtry
1.172 anton 5821: doc-iferror
5822:
5823: If you don't need @i{code2}, you can write @code{restore} instead of
5824: @code{iferror then}:
5825:
5826: @example
5827: TRY
5828: @i{code1}
5829: RESTORE
5830: @i{code3}
5831: ENDTRY
5832: @end example
1.26 crook 5833:
1.172 anton 5834: @cindex unwind-protect
1.69 anton 5835: The cleanup example from above in this syntax:
1.26 crook 5836:
1.68 anton 5837: @example
1.174 anton 5838: base @@ @{ oldbase @}
1.172 anton 5839: TRY
1.68 anton 5840: hex foo \ now the hex is placed correctly
1.69 anton 5841: 0 \ value for throw
1.172 anton 5842: RESTORE
5843: oldbase base !
5844: ENDTRY
5845: throw
1.1 anton 5846: @end example
5847:
1.172 anton 5848: An additional advantage of this variant is that an exception between
5849: @code{restore} and @code{endtry} (e.g., from the user pressing
5850: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5851: so the base will be restored under all circumstances.
5852:
5853: However, you have to ensure that this code does not cause an exception
5854: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5855: Moreover, you should also make sure that the stack contents needed by
5856: the @code{iferror}/@code{restore} code exist everywhere between
5857: @code{try} and @code{endtry}; in our example this is achived by
5858: putting the data in a local before the @code{try} (you cannot use the
5859: return stack because the exception frame (@i{sys1}) is in the way
5860: there).
5861:
5862: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5863:
5864: @cindex @code{recover} (old Gforth versions)
5865: If you do not want this exception-restarting behaviour, you achieve
5866: this as follows:
5867:
5868: @example
5869: TRY
5870: @i{code1}
5871: ENDTRY-IFERROR
5872: @i{code2}
5873: THEN
5874: @end example
5875:
5876: If there is an exception in @i{code1}, then @i{code2} is executed,
5877: otherwise execution continues behind the @code{then} (or in a possible
5878: @code{else} branch). This corresponds to the construct
5879:
5880: @example
5881: TRY
5882: @i{code1}
5883: RECOVER
5884: @i{code2}
5885: ENDTRY
5886: @end example
5887:
5888: in Gforth before version 0.7. So you can directly replace
5889: @code{recover}-using code; however, we recommend that you check if it
5890: would not be better to use one of the other @code{try} variants while
5891: you are at it.
5892:
1.173 anton 5893: To ease the transition, Gforth provides two compatibility files:
5894: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5895: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5896: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5897: ... endtry} syntax on new systems, so you can use that file as a
5898: stopgap to run old programs. Both files work on any system (they just
5899: do nothing if the system already has the syntax it implements), so you
5900: can unconditionally @code{require} one of these files, even if you use
5901: a mix old and new systems.
5902:
1.172 anton 5903: doc-restore
5904: doc-endtry-iferror
5905:
5906: Here's the error handling example:
1.1 anton 5907:
1.68 anton 5908: @example
1.69 anton 5909: TRY
1.68 anton 5910: foo
1.172 anton 5911: ENDTRY-IFERROR
1.69 anton 5912: CASE
1.160 anton 5913: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5914: throw \ pass other errors on
5915: ENDCASE
1.172 anton 5916: THEN
1.68 anton 5917: @end example
1.1 anton 5918:
1.69 anton 5919: @progstyle
5920: As usual, you should ensure that the stack depth is statically known at
5921: the end: either after the @code{throw} for passing on errors, or after
5922: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5923: selection construct for handling the error).
5924:
1.68 anton 5925: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5926: and you can provide an error message. @code{Abort} just produces an
5927: ``Aborted'' error.
1.1 anton 5928:
1.68 anton 5929: The problem with these words is that exception handlers cannot
5930: differentiate between different @code{abort"}s; they just look like
5931: @code{-2 throw} to them (the error message cannot be accessed by
5932: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5933: exception handlers.
1.44 crook 5934:
1.68 anton 5935: doc-abort"
1.26 crook 5936: doc-abort
1.29 crook 5937:
5938:
1.44 crook 5939:
1.29 crook 5940: @c -------------------------------------------------------------
1.47 crook 5941: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5942: @section Defining Words
5943: @cindex defining words
5944:
1.47 crook 5945: Defining words are used to extend Forth by creating new entries in the dictionary.
5946:
1.29 crook 5947: @menu
1.67 anton 5948: * CREATE::
1.44 crook 5949: * Variables:: Variables and user variables
1.67 anton 5950: * Constants::
1.44 crook 5951: * Values:: Initialised variables
1.67 anton 5952: * Colon Definitions::
1.44 crook 5953: * Anonymous Definitions:: Definitions without names
1.69 anton 5954: * Supplying names:: Passing definition names as strings
1.67 anton 5955: * User-defined Defining Words::
1.170 pazsan 5956: * Deferred Words:: Allow forward references
1.67 anton 5957: * Aliases::
1.29 crook 5958: @end menu
5959:
1.44 crook 5960: @node CREATE, Variables, Defining Words, Defining Words
5961: @subsection @code{CREATE}
1.29 crook 5962: @cindex simple defining words
5963: @cindex defining words, simple
5964:
5965: Defining words are used to create new entries in the dictionary. The
5966: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5967: this:
5968:
5969: @example
5970: CREATE new-word1
5971: @end example
5972:
1.69 anton 5973: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5974: input stream (@code{new-word1} in our example). It generates a
5975: dictionary entry for @code{new-word1}. When @code{new-word1} is
5976: executed, all that it does is leave an address on the stack. The address
5977: represents the value of the data space pointer (@code{HERE}) at the time
5978: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5979: associating a name with the address of a region of memory.
1.29 crook 5980:
1.34 anton 5981: doc-create
5982:
1.69 anton 5983: Note that in ANS Forth guarantees only for @code{create} that its body
5984: is in dictionary data space (i.e., where @code{here}, @code{allot}
5985: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5986: @code{create}d words can be modified with @code{does>}
5987: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5988: can only be applied to @code{create}d words.
5989:
1.29 crook 5990: By extending this example to reserve some memory in data space, we end
1.69 anton 5991: up with something like a @i{variable}. Here are two different ways to do
5992: it:
1.29 crook 5993:
5994: @example
5995: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5996: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5997: @end example
5998:
5999: The variable can be examined and modified using @code{@@} (``fetch'') and
6000: @code{!} (``store'') like this:
6001:
6002: @example
6003: new-word2 @@ . \ get address, fetch from it and display
6004: 1234 new-word2 ! \ new value, get address, store to it
6005: @end example
6006:
1.44 crook 6007: @cindex arrays
6008: A similar mechanism can be used to create arrays. For example, an
6009: 80-character text input buffer:
1.29 crook 6010:
6011: @example
1.44 crook 6012: CREATE text-buf 80 chars allot
6013:
1.168 anton 6014: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6015: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6016: @end example
1.29 crook 6017:
1.44 crook 6018: You can build arbitrarily complex data structures by allocating
1.49 anton 6019: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6020: learn about some Gforth tools that make it easier,
1.49 anton 6021: @xref{Structures}.
1.44 crook 6022:
6023:
6024: @node Variables, Constants, CREATE, Defining Words
6025: @subsection Variables
6026: @cindex variables
6027:
6028: The previous section showed how a sequence of commands could be used to
6029: generate a variable. As a final refinement, the whole code sequence can
6030: be wrapped up in a defining word (pre-empting the subject of the next
6031: section), making it easier to create new variables:
6032:
6033: @example
6034: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6035: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6036:
6037: myvariableX foo \ variable foo starts off with an unknown value
6038: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6039:
6040: 45 3 * foo ! \ set foo to 135
6041: 1234 joe ! \ set joe to 1234
6042: 3 joe +! \ increment joe by 3.. to 1237
6043: @end example
6044:
6045: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6046: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6047: guarantee that a @code{Variable} is initialised when it is created
6048: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6049: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6050: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6051: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6052: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6053: store a boolean, you can use @code{on} and @code{off} to toggle its
6054: state.
1.29 crook 6055:
1.34 anton 6056: doc-variable
6057: doc-2variable
6058: doc-fvariable
6059:
1.29 crook 6060: @cindex user variables
6061: @cindex user space
6062: The defining word @code{User} behaves in the same way as @code{Variable}.
6063: The difference is that it reserves space in @i{user (data) space} rather
6064: than normal data space. In a Forth system that has a multi-tasker, each
6065: task has its own set of user variables.
6066:
1.34 anton 6067: doc-user
1.67 anton 6068: @c doc-udp
6069: @c doc-uallot
1.34 anton 6070:
1.29 crook 6071: @comment TODO is that stuff about user variables strictly correct? Is it
6072: @comment just terminal tasks that have user variables?
6073: @comment should document tasker.fs (with some examples) elsewhere
6074: @comment in this manual, then expand on user space and user variables.
6075:
1.44 crook 6076: @node Constants, Values, Variables, Defining Words
6077: @subsection Constants
6078: @cindex constants
6079:
6080: @code{Constant} allows you to declare a fixed value and refer to it by
6081: name. For example:
1.29 crook 6082:
6083: @example
6084: 12 Constant INCHES-PER-FOOT
6085: 3E+08 fconstant SPEED-O-LIGHT
6086: @end example
6087:
6088: A @code{Variable} can be both read and written, so its run-time
6089: behaviour is to supply an address through which its current value can be
6090: manipulated. In contrast, the value of a @code{Constant} cannot be
6091: changed once it has been declared@footnote{Well, often it can be -- but
6092: not in a Standard, portable way. It's safer to use a @code{Value} (read
6093: on).} so it's not necessary to supply the address -- it is more
6094: efficient to return the value of the constant directly. That's exactly
6095: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6096: the top of the stack (You can find one
6097: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6098:
1.69 anton 6099: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6100: double and floating-point constants, respectively.
6101:
1.34 anton 6102: doc-constant
6103: doc-2constant
6104: doc-fconstant
6105:
6106: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6107: @c nac-> How could that not be true in an ANS Forth? You can't define a
6108: @c constant, use it and then delete the definition of the constant..
1.69 anton 6109:
6110: @c anton->An ANS Forth system can compile a constant to a literal; On
6111: @c decompilation you would see only the number, just as if it had been used
6112: @c in the first place. The word will stay, of course, but it will only be
6113: @c used by the text interpreter (no run-time duties, except when it is
6114: @c POSTPONEd or somesuch).
6115:
6116: @c nac:
1.44 crook 6117: @c I agree that it's rather deep, but IMO it is an important difference
6118: @c relative to other programming languages.. often it's annoying: it
6119: @c certainly changes my programming style relative to C.
6120:
1.69 anton 6121: @c anton: In what way?
6122:
1.29 crook 6123: Constants in Forth behave differently from their equivalents in other
6124: programming languages. In other languages, a constant (such as an EQU in
6125: assembler or a #define in C) only exists at compile-time; in the
6126: executable program the constant has been translated into an absolute
6127: number and, unless you are using a symbolic debugger, it's impossible to
6128: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6129: an entry in the header space and remains there after the code that uses
6130: it has been defined. In fact, it must remain in the dictionary since it
6131: has run-time duties to perform. For example:
1.29 crook 6132:
6133: @example
6134: 12 Constant INCHES-PER-FOOT
6135: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6136: @end example
6137:
6138: @cindex in-lining of constants
6139: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6140: associated with the constant @code{INCHES-PER-FOOT}. If you use
6141: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6142: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6143: attempt to optimise constants by in-lining them where they are used. You
6144: can force Gforth to in-line a constant like this:
6145:
6146: @example
6147: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6148: @end example
6149:
6150: If you use @code{see} to decompile @i{this} version of
6151: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6152: longer present. To understand how this works, read
6153: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6154:
6155: In-lining constants in this way might improve execution time
6156: fractionally, and can ensure that a constant is now only referenced at
6157: compile-time. However, the definition of the constant still remains in
6158: the dictionary. Some Forth compilers provide a mechanism for controlling
6159: a second dictionary for holding transient words such that this second
6160: dictionary can be deleted later in order to recover memory
6161: space. However, there is no standard way of doing this.
6162:
6163:
1.44 crook 6164: @node Values, Colon Definitions, Constants, Defining Words
6165: @subsection Values
6166: @cindex values
1.34 anton 6167:
1.69 anton 6168: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6169: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6170: (not in ANS Forth) you can access (and change) a @code{value} also with
6171: @code{>body}.
6172:
6173: Here are some
6174: examples:
1.29 crook 6175:
6176: @example
1.69 anton 6177: 12 Value APPLES \ Define APPLES with an initial value of 12
6178: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6179: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6180: APPLES \ puts 35 on the top of the stack.
1.29 crook 6181: @end example
6182:
1.44 crook 6183: doc-value
6184: doc-to
1.29 crook 6185:
1.35 anton 6186:
1.69 anton 6187:
1.44 crook 6188: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6189: @subsection Colon Definitions
6190: @cindex colon definitions
1.35 anton 6191:
6192: @example
1.44 crook 6193: : name ( ... -- ... )
6194: word1 word2 word3 ;
1.29 crook 6195: @end example
6196:
1.44 crook 6197: @noindent
6198: Creates a word called @code{name} that, upon execution, executes
6199: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6200:
1.49 anton 6201: The explanation above is somewhat superficial. For simple examples of
6202: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6203: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6204: Compilation Semantics}.
1.29 crook 6205:
1.44 crook 6206: doc-:
6207: doc-;
1.1 anton 6208:
1.34 anton 6209:
1.69 anton 6210: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6211: @subsection Anonymous Definitions
6212: @cindex colon definitions
6213: @cindex defining words without name
1.34 anton 6214:
1.44 crook 6215: Sometimes you want to define an @dfn{anonymous word}; a word without a
6216: name. You can do this with:
1.1 anton 6217:
1.44 crook 6218: doc-:noname
1.1 anton 6219:
1.44 crook 6220: This leaves the execution token for the word on the stack after the
6221: closing @code{;}. Here's an example in which a deferred word is
6222: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6223:
1.29 crook 6224: @example
1.44 crook 6225: Defer deferred
6226: :noname ( ... -- ... )
6227: ... ;
6228: IS deferred
1.29 crook 6229: @end example
1.26 crook 6230:
1.44 crook 6231: @noindent
6232: Gforth provides an alternative way of doing this, using two separate
6233: words:
1.27 crook 6234:
1.44 crook 6235: doc-noname
6236: @cindex execution token of last defined word
1.116 anton 6237: doc-latestxt
1.1 anton 6238:
1.44 crook 6239: @noindent
6240: The previous example can be rewritten using @code{noname} and
1.116 anton 6241: @code{latestxt}:
1.1 anton 6242:
1.26 crook 6243: @example
1.44 crook 6244: Defer deferred
6245: noname : ( ... -- ... )
6246: ... ;
1.116 anton 6247: latestxt IS deferred
1.26 crook 6248: @end example
1.1 anton 6249:
1.29 crook 6250: @noindent
1.44 crook 6251: @code{noname} works with any defining word, not just @code{:}.
6252:
1.116 anton 6253: @code{latestxt} also works when the last word was not defined as
1.71 anton 6254: @code{noname}. It does not work for combined words, though. It also has
6255: the useful property that is is valid as soon as the header for a
6256: definition has been built. Thus:
1.44 crook 6257:
6258: @example
1.116 anton 6259: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6260: @end example
1.1 anton 6261:
1.44 crook 6262: @noindent
6263: prints 3 numbers; the last two are the same.
1.26 crook 6264:
1.69 anton 6265: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6266: @subsection Supplying the name of a defined word
6267: @cindex names for defined words
6268: @cindex defining words, name given in a string
6269:
6270: By default, a defining word takes the name for the defined word from the
6271: input stream. Sometimes you want to supply the name from a string. You
6272: can do this with:
6273:
6274: doc-nextname
6275:
6276: For example:
6277:
6278: @example
6279: s" foo" nextname create
6280: @end example
6281:
6282: @noindent
6283: is equivalent to:
6284:
6285: @example
6286: create foo
6287: @end example
6288:
6289: @noindent
6290: @code{nextname} works with any defining word.
6291:
1.1 anton 6292:
1.170 pazsan 6293: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6294: @subsection User-defined Defining Words
6295: @cindex user-defined defining words
6296: @cindex defining words, user-defined
1.1 anton 6297:
1.29 crook 6298: You can create a new defining word by wrapping defining-time code around
6299: an existing defining word and putting the sequence in a colon
1.69 anton 6300: definition.
6301:
6302: @c anton: This example is very complex and leads in a quite different
6303: @c direction from the CREATE-DOES> stuff that follows. It should probably
6304: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6305: @c subsection of Defining Words)
6306:
6307: For example, suppose that you have a word @code{stats} that
1.29 crook 6308: gathers statistics about colon definitions given the @i{xt} of the
6309: definition, and you want every colon definition in your application to
6310: make a call to @code{stats}. You can define and use a new version of
6311: @code{:} like this:
6312:
6313: @example
6314: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6315: ... ; \ other code
6316:
1.116 anton 6317: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6318:
6319: my: foo + - ;
6320: @end example
6321:
6322: When @code{foo} is defined using @code{my:} these steps occur:
6323:
6324: @itemize @bullet
6325: @item
6326: @code{my:} is executed.
6327: @item
6328: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6329: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6330: the input stream for a name, builds a dictionary header for the name
6331: @code{foo} and switches @code{state} from interpret to compile.
6332: @item
1.116 anton 6333: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6334: being defined -- @code{foo} -- onto the stack.
6335: @item
6336: The code that was produced by @code{postpone literal} is executed; this
6337: causes the value on the stack to be compiled as a literal in the code
6338: area of @code{foo}.
6339: @item
6340: The code @code{['] stats} compiles a literal into the definition of
6341: @code{my:}. When @code{compile,} is executed, that literal -- the
6342: execution token for @code{stats} -- is layed down in the code area of
6343: @code{foo} , following the literal@footnote{Strictly speaking, the
6344: mechanism that @code{compile,} uses to convert an @i{xt} into something
6345: in the code area is implementation-dependent. A threaded implementation
6346: might spit out the execution token directly whilst another
6347: implementation might spit out a native code sequence.}.
6348: @item
6349: At this point, the execution of @code{my:} is complete, and control
6350: returns to the text interpreter. The text interpreter is in compile
6351: state, so subsequent text @code{+ -} is compiled into the definition of
6352: @code{foo} and the @code{;} terminates the definition as always.
6353: @end itemize
6354:
6355: You can use @code{see} to decompile a word that was defined using
6356: @code{my:} and see how it is different from a normal @code{:}
6357: definition. For example:
6358:
6359: @example
6360: : bar + - ; \ like foo but using : rather than my:
6361: see bar
6362: : bar
6363: + - ;
6364: see foo
6365: : foo
6366: 107645672 stats + - ;
6367:
1.140 anton 6368: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6369: @end example
6370:
6371: You can use techniques like this to make new defining words in terms of
6372: @i{any} existing defining word.
1.1 anton 6373:
6374:
1.29 crook 6375: @cindex defining defining words
1.26 crook 6376: @cindex @code{CREATE} ... @code{DOES>}
6377: If you want the words defined with your defining words to behave
6378: differently from words defined with standard defining words, you can
6379: write your defining word like this:
1.1 anton 6380:
6381: @example
1.26 crook 6382: : def-word ( "name" -- )
1.29 crook 6383: CREATE @i{code1}
1.26 crook 6384: DOES> ( ... -- ... )
1.29 crook 6385: @i{code2} ;
1.26 crook 6386:
6387: def-word name
1.1 anton 6388: @end example
6389:
1.29 crook 6390: @cindex child words
6391: This fragment defines a @dfn{defining word} @code{def-word} and then
6392: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6393: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6394: is not executed at this time. The word @code{name} is sometimes called a
6395: @dfn{child} of @code{def-word}.
6396:
6397: When you execute @code{name}, the address of the body of @code{name} is
6398: put on the data stack and @i{code2} is executed (the address of the body
6399: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6400: @code{CREATE}, i.e., the address a @code{create}d word returns by
6401: default).
6402:
6403: @c anton:
6404: @c www.dictionary.com says:
6405: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6406: @c several generations of absence, usually caused by the chance
6407: @c recombination of genes. 2.An individual or a part that exhibits
6408: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6409: @c of previous behavior after a period of absence.
6410: @c
6411: @c Doesn't seem to fit.
1.29 crook 6412:
1.69 anton 6413: @c @cindex atavism in child words
1.33 anton 6414: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6415: similarly; they all have a common run-time behaviour determined by
6416: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6417: body of the child word. The structure of the data is common to all
6418: children of @code{def-word}, but the data values are specific -- and
6419: private -- to each child word. When a child word is executed, the
6420: address of its private data area is passed as a parameter on TOS to be
6421: used and manipulated@footnote{It is legitimate both to read and write to
6422: this data area.} by @i{code2}.
1.29 crook 6423:
6424: The two fragments of code that make up the defining words act (are
6425: executed) at two completely separate times:
1.1 anton 6426:
1.29 crook 6427: @itemize @bullet
6428: @item
6429: At @i{define time}, the defining word executes @i{code1} to generate a
6430: child word
6431: @item
6432: At @i{child execution time}, when a child word is invoked, @i{code2}
6433: is executed, using parameters (data) that are private and specific to
6434: the child word.
6435: @end itemize
6436:
1.44 crook 6437: Another way of understanding the behaviour of @code{def-word} and
6438: @code{name} is to say that, if you make the following definitions:
1.33 anton 6439: @example
6440: : def-word1 ( "name" -- )
6441: CREATE @i{code1} ;
6442:
6443: : action1 ( ... -- ... )
6444: @i{code2} ;
6445:
6446: def-word1 name1
6447: @end example
6448:
1.44 crook 6449: @noindent
6450: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6451:
1.29 crook 6452: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6453:
1.1 anton 6454: @example
1.29 crook 6455: : CONSTANT ( w "name" -- )
6456: CREATE ,
1.26 crook 6457: DOES> ( -- w )
6458: @@ ;
1.1 anton 6459: @end example
6460:
1.29 crook 6461: @comment There is a beautiful description of how this works and what
6462: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6463: @comment commentary on the Counting Fruits problem.
6464:
6465: When you create a constant with @code{5 CONSTANT five}, a set of
6466: define-time actions take place; first a new word @code{five} is created,
6467: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6468: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6469: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6470: no code of its own; it simply contains a data field and a pointer to the
6471: code that follows @code{DOES>} in its defining word. That makes words
6472: created in this way very compact.
6473:
6474: The final example in this section is intended to remind you that space
6475: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6476: both read and written by a Standard program@footnote{Exercise: use this
6477: example as a starting point for your own implementation of @code{Value}
6478: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6479: @code{[']}.}:
6480:
6481: @example
6482: : foo ( "name" -- )
6483: CREATE -1 ,
6484: DOES> ( -- )
1.33 anton 6485: @@ . ;
1.29 crook 6486:
6487: foo first-word
6488: foo second-word
6489:
6490: 123 ' first-word >BODY !
6491: @end example
6492:
6493: If @code{first-word} had been a @code{CREATE}d word, we could simply
6494: have executed it to get the address of its data field. However, since it
6495: was defined to have @code{DOES>} actions, its execution semantics are to
6496: perform those @code{DOES>} actions. To get the address of its data field
6497: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6498: translate the xt into the address of the data field. When you execute
6499: @code{first-word}, it will display @code{123}. When you execute
6500: @code{second-word} it will display @code{-1}.
1.26 crook 6501:
6502: @cindex stack effect of @code{DOES>}-parts
6503: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6504: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6505: the stack effect of the defined words, not the stack effect of the
6506: following code (the following code expects the address of the body on
6507: the top of stack, which is not reflected in the stack comment). This is
6508: the convention that I use and recommend (it clashes a bit with using
6509: locals declarations for stack effect specification, though).
1.1 anton 6510:
1.53 anton 6511: @menu
6512: * CREATE..DOES> applications::
6513: * CREATE..DOES> details::
1.63 anton 6514: * Advanced does> usage example::
1.155 anton 6515: * Const-does>::
1.53 anton 6516: @end menu
6517:
6518: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6519: @subsubsection Applications of @code{CREATE..DOES>}
6520: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6521:
1.26 crook 6522: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6523:
1.26 crook 6524: @cindex factoring similar colon definitions
6525: When you see a sequence of code occurring several times, and you can
6526: identify a meaning, you will factor it out as a colon definition. When
6527: you see similar colon definitions, you can factor them using
6528: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6529: that look very similar:
1.1 anton 6530: @example
1.26 crook 6531: : ori, ( reg-target reg-source n -- )
6532: 0 asm-reg-reg-imm ;
6533: : andi, ( reg-target reg-source n -- )
6534: 1 asm-reg-reg-imm ;
1.1 anton 6535: @end example
6536:
1.26 crook 6537: @noindent
6538: This could be factored with:
6539: @example
6540: : reg-reg-imm ( op-code -- )
6541: CREATE ,
6542: DOES> ( reg-target reg-source n -- )
6543: @@ asm-reg-reg-imm ;
6544:
6545: 0 reg-reg-imm ori,
6546: 1 reg-reg-imm andi,
6547: @end example
1.1 anton 6548:
1.26 crook 6549: @cindex currying
6550: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6551: supply a part of the parameters for a word (known as @dfn{currying} in
6552: the functional language community). E.g., @code{+} needs two
6553: parameters. Creating versions of @code{+} with one parameter fixed can
6554: be done like this:
1.82 anton 6555:
1.1 anton 6556: @example
1.82 anton 6557: : curry+ ( n1 "name" -- )
1.26 crook 6558: CREATE ,
6559: DOES> ( n2 -- n1+n2 )
6560: @@ + ;
6561:
6562: 3 curry+ 3+
6563: -2 curry+ 2-
1.1 anton 6564: @end example
6565:
1.91 anton 6566:
1.63 anton 6567: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6568: @subsubsection The gory details of @code{CREATE..DOES>}
6569: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6570:
1.26 crook 6571: doc-does>
1.1 anton 6572:
1.26 crook 6573: @cindex @code{DOES>} in a separate definition
6574: This means that you need not use @code{CREATE} and @code{DOES>} in the
6575: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6576: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6577: @example
6578: : does1
6579: DOES> ( ... -- ... )
1.44 crook 6580: ... ;
6581:
6582: : does2
6583: DOES> ( ... -- ... )
6584: ... ;
6585:
6586: : def-word ( ... -- ... )
6587: create ...
6588: IF
6589: does1
6590: ELSE
6591: does2
6592: ENDIF ;
6593: @end example
6594:
6595: In this example, the selection of whether to use @code{does1} or
1.69 anton 6596: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6597: @code{CREATE}d.
6598:
6599: @cindex @code{DOES>} in interpretation state
6600: In a standard program you can apply a @code{DOES>}-part only if the last
6601: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6602: will override the behaviour of the last word defined in any case. In a
6603: standard program, you can use @code{DOES>} only in a colon
6604: definition. In Gforth, you can also use it in interpretation state, in a
6605: kind of one-shot mode; for example:
6606: @example
6607: CREATE name ( ... -- ... )
6608: @i{initialization}
6609: DOES>
6610: @i{code} ;
6611: @end example
6612:
6613: @noindent
6614: is equivalent to the standard:
6615: @example
6616: :noname
6617: DOES>
6618: @i{code} ;
6619: CREATE name EXECUTE ( ... -- ... )
6620: @i{initialization}
6621: @end example
6622:
1.53 anton 6623: doc->body
6624:
1.152 pazsan 6625: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6626: @subsubsection Advanced does> usage example
6627:
6628: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6629: for disassembling instructions, that follow a very repetetive scheme:
6630:
6631: @example
6632: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6633: @var{entry-num} cells @var{table} + !
6634: @end example
6635:
6636: Of course, this inspires the idea to factor out the commonalities to
6637: allow a definition like
6638:
6639: @example
6640: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6641: @end example
6642:
6643: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6644: correlated. Moreover, before I wrote the disassembler, there already
6645: existed code that defines instructions like this:
1.63 anton 6646:
6647: @example
6648: @var{entry-num} @var{inst-format} @var{inst-name}
6649: @end example
6650:
6651: This code comes from the assembler and resides in
6652: @file{arch/mips/insts.fs}.
6653:
6654: So I had to define the @var{inst-format} words that performed the scheme
6655: above when executed. At first I chose to use run-time code-generation:
6656:
6657: @example
6658: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6659: :noname Postpone @var{disasm-operands}
6660: name Postpone sliteral Postpone type Postpone ;
6661: swap cells @var{table} + ! ;
6662: @end example
6663:
6664: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6665:
1.63 anton 6666: An alternative would have been to write this using
6667: @code{create}/@code{does>}:
6668:
6669: @example
6670: : @var{inst-format} ( entry-num "name" -- )
6671: here name string, ( entry-num c-addr ) \ parse and save "name"
6672: noname create , ( entry-num )
1.116 anton 6673: latestxt swap cells @var{table} + !
1.63 anton 6674: does> ( addr w -- )
6675: \ disassemble instruction w at addr
6676: @@ >r
6677: @var{disasm-operands}
6678: r> count type ;
6679: @end example
6680:
6681: Somehow the first solution is simpler, mainly because it's simpler to
6682: shift a string from definition-time to use-time with @code{sliteral}
6683: than with @code{string,} and friends.
6684:
6685: I wrote a lot of words following this scheme and soon thought about
6686: factoring out the commonalities among them. Note that this uses a
6687: two-level defining word, i.e., a word that defines ordinary defining
6688: words.
6689:
6690: This time a solution involving @code{postpone} and friends seemed more
6691: difficult (try it as an exercise), so I decided to use a
6692: @code{create}/@code{does>} word; since I was already at it, I also used
6693: @code{create}/@code{does>} for the lower level (try using
6694: @code{postpone} etc. as an exercise), resulting in the following
6695: definition:
6696:
6697: @example
6698: : define-format ( disasm-xt table-xt -- )
6699: \ define an instruction format that uses disasm-xt for
6700: \ disassembling and enters the defined instructions into table
6701: \ table-xt
6702: create 2,
6703: does> ( u "inst" -- )
6704: \ defines an anonymous word for disassembling instruction inst,
6705: \ and enters it as u-th entry into table-xt
6706: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6707: noname create 2, \ define anonymous word
1.116 anton 6708: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6709: does> ( addr w -- )
6710: \ disassemble instruction w at addr
6711: 2@@ >r ( addr w disasm-xt R: c-addr )
6712: execute ( R: c-addr ) \ disassemble operands
6713: r> count type ; \ print name
6714: @end example
6715:
6716: Note that the tables here (in contrast to above) do the @code{cells +}
6717: by themselves (that's why you have to pass an xt). This word is used in
6718: the following way:
6719:
6720: @example
6721: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6722: @end example
6723:
1.71 anton 6724: As shown above, the defined instruction format is then used like this:
6725:
6726: @example
6727: @var{entry-num} @var{inst-format} @var{inst-name}
6728: @end example
6729:
1.63 anton 6730: In terms of currying, this kind of two-level defining word provides the
6731: parameters in three stages: first @var{disasm-operands} and @var{table},
6732: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6733: the instruction to be disassembled.
6734:
6735: Of course this did not quite fit all the instruction format names used
6736: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6737: the parameters into the right form.
6738:
6739: If you have trouble following this section, don't worry. First, this is
6740: involved and takes time (and probably some playing around) to
6741: understand; second, this is the first two-level
6742: @code{create}/@code{does>} word I have written in seventeen years of
6743: Forth; and if I did not have @file{insts.fs} to start with, I may well
6744: have elected to use just a one-level defining word (with some repeating
6745: of parameters when using the defining word). So it is not necessary to
6746: understand this, but it may improve your understanding of Forth.
1.44 crook 6747:
6748:
1.152 pazsan 6749: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6750: @subsubsection @code{Const-does>}
6751:
6752: A frequent use of @code{create}...@code{does>} is for transferring some
6753: values from definition-time to run-time. Gforth supports this use with
6754:
6755: doc-const-does>
6756:
6757: A typical use of this word is:
6758:
6759: @example
6760: : curry+ ( n1 "name" -- )
6761: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6762: + ;
6763:
6764: 3 curry+ 3+
6765: @end example
6766:
6767: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6768: definition to run-time.
6769:
6770: The advantages of using @code{const-does>} are:
6771:
6772: @itemize
6773:
6774: @item
6775: You don't have to deal with storing and retrieving the values, i.e.,
6776: your program becomes more writable and readable.
6777:
6778: @item
6779: When using @code{does>}, you have to introduce a @code{@@} that cannot
6780: be optimized away (because you could change the data using
6781: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6782:
6783: @end itemize
6784:
6785: An ANS Forth implementation of @code{const-does>} is available in
6786: @file{compat/const-does.fs}.
6787:
6788:
1.170 pazsan 6789: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6790: @subsection Deferred Words
1.44 crook 6791: @cindex deferred words
6792:
6793: The defining word @code{Defer} allows you to define a word by name
6794: without defining its behaviour; the definition of its behaviour is
6795: deferred. Here are two situation where this can be useful:
6796:
6797: @itemize @bullet
6798: @item
6799: Where you want to allow the behaviour of a word to be altered later, and
6800: for all precompiled references to the word to change when its behaviour
6801: is changed.
6802: @item
6803: For mutual recursion; @xref{Calls and returns}.
6804: @end itemize
6805:
6806: In the following example, @code{foo} always invokes the version of
6807: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6808: always invokes the version that prints ``@code{Hello}''. There is no way
6809: of getting @code{foo} to use the later version without re-ordering the
6810: source code and recompiling it.
6811:
6812: @example
6813: : greet ." Good morning" ;
6814: : foo ... greet ... ;
6815: : greet ." Hello" ;
6816: : bar ... greet ... ;
6817: @end example
6818:
6819: This problem can be solved by defining @code{greet} as a @code{Defer}red
6820: word. The behaviour of a @code{Defer}red word can be defined and
6821: redefined at any time by using @code{IS} to associate the xt of a
6822: previously-defined word with it. The previous example becomes:
6823:
6824: @example
1.69 anton 6825: Defer greet ( -- )
1.44 crook 6826: : foo ... greet ... ;
6827: : bar ... greet ... ;
1.69 anton 6828: : greet1 ( -- ) ." Good morning" ;
6829: : greet2 ( -- ) ." Hello" ;
1.132 anton 6830: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6831: @end example
6832:
1.69 anton 6833: @progstyle
6834: You should write a stack comment for every deferred word, and put only
6835: XTs into deferred words that conform to this stack effect. Otherwise
6836: it's too difficult to use the deferred word.
6837:
1.44 crook 6838: A deferred word can be used to improve the statistics-gathering example
6839: from @ref{User-defined Defining Words}; rather than edit the
6840: application's source code to change every @code{:} to a @code{my:}, do
6841: this:
6842:
6843: @example
6844: : real: : ; \ retain access to the original
6845: defer : \ redefine as a deferred word
1.132 anton 6846: ' my: IS : \ use special version of :
1.44 crook 6847: \
6848: \ load application here
6849: \
1.132 anton 6850: ' real: IS : \ go back to the original
1.44 crook 6851: @end example
6852:
6853:
1.132 anton 6854: One thing to note is that @code{IS} has special compilation semantics,
6855: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6856:
6857: @example
6858: : set-greet ( xt -- )
1.132 anton 6859: IS greet ;
1.44 crook 6860:
6861: ' greet1 set-greet
6862: @end example
6863:
1.132 anton 6864: In situations where @code{IS} does not fit, use @code{defer!} instead.
6865:
1.69 anton 6866: A deferred word can only inherit execution semantics from the xt
6867: (because that is all that an xt can represent -- for more discussion of
6868: this @pxref{Tokens for Words}); by default it will have default
6869: interpretation and compilation semantics deriving from this execution
6870: semantics. However, you can change the interpretation and compilation
6871: semantics of the deferred word in the usual ways:
1.44 crook 6872:
6873: @example
1.132 anton 6874: : bar .... ; immediate
1.44 crook 6875: Defer fred immediate
6876: Defer jim
6877:
1.132 anton 6878: ' bar IS jim \ jim has default semantics
6879: ' bar IS fred \ fred is immediate
1.44 crook 6880: @end example
6881:
6882: doc-defer
1.132 anton 6883: doc-defer!
1.44 crook 6884: doc-is
1.132 anton 6885: doc-defer@
6886: doc-action-of
1.44 crook 6887: @comment TODO document these: what's defers [is]
6888: doc-defers
6889:
6890: @c Use @code{words-deferred} to see a list of deferred words.
6891:
1.132 anton 6892: Definitions of these words (except @code{defers}) in ANS Forth are
6893: provided in @file{compat/defer.fs}.
1.44 crook 6894:
6895:
1.170 pazsan 6896: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6897: @subsection Aliases
6898: @cindex aliases
1.1 anton 6899:
1.44 crook 6900: The defining word @code{Alias} allows you to define a word by name that
6901: has the same behaviour as some other word. Here are two situation where
6902: this can be useful:
1.1 anton 6903:
1.44 crook 6904: @itemize @bullet
6905: @item
6906: When you want access to a word's definition from a different word list
6907: (for an example of this, see the definition of the @code{Root} word list
6908: in the Gforth source).
6909: @item
6910: When you want to create a synonym; a definition that can be known by
6911: either of two names (for example, @code{THEN} and @code{ENDIF} are
6912: aliases).
6913: @end itemize
1.1 anton 6914:
1.69 anton 6915: Like deferred words, an alias has default compilation and interpretation
6916: semantics at the beginning (not the modifications of the other word),
6917: but you can change them in the usual ways (@code{immediate},
6918: @code{compile-only}). For example:
1.1 anton 6919:
6920: @example
1.44 crook 6921: : foo ... ; immediate
6922:
6923: ' foo Alias bar \ bar is not an immediate word
6924: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6925: @end example
6926:
1.44 crook 6927: Words that are aliases have the same xt, different headers in the
6928: dictionary, and consequently different name tokens (@pxref{Tokens for
6929: Words}) and possibly different immediate flags. An alias can only have
6930: default or immediate compilation semantics; you can define aliases for
6931: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6932:
1.44 crook 6933: doc-alias
1.1 anton 6934:
6935:
1.47 crook 6936: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6937: @section Interpretation and Compilation Semantics
1.26 crook 6938: @cindex semantics, interpretation and compilation
1.1 anton 6939:
1.71 anton 6940: @c !! state and ' are used without explanation
6941: @c example for immediate/compile-only? or is the tutorial enough
6942:
1.26 crook 6943: @cindex interpretation semantics
1.71 anton 6944: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6945: interpreter does when it encounters the word in interpret state. It also
6946: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6947: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6948: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6949: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6950:
1.26 crook 6951: @cindex compilation semantics
1.71 anton 6952: The @dfn{compilation semantics} of a (named) word are what the text
6953: interpreter does when it encounters the word in compile state. It also
6954: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6955: compiles@footnote{In standard terminology, ``appends to the current
6956: definition''.} the compilation semantics of @i{word}.
1.1 anton 6957:
1.26 crook 6958: @cindex execution semantics
6959: The standard also talks about @dfn{execution semantics}. They are used
6960: only for defining the interpretation and compilation semantics of many
6961: words. By default, the interpretation semantics of a word are to
6962: @code{execute} its execution semantics, and the compilation semantics of
6963: a word are to @code{compile,} its execution semantics.@footnote{In
6964: standard terminology: The default interpretation semantics are its
6965: execution semantics; the default compilation semantics are to append its
6966: execution semantics to the execution semantics of the current
6967: definition.}
6968:
1.71 anton 6969: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6970: the text interpreter, ticked, or @code{postpone}d, so they have no
6971: interpretation or compilation semantics. Their behaviour is represented
6972: by their XT (@pxref{Tokens for Words}), and we call it execution
6973: semantics, too.
6974:
1.26 crook 6975: @comment TODO expand, make it co-operate with new sections on text interpreter.
6976:
6977: @cindex immediate words
6978: @cindex compile-only words
6979: You can change the semantics of the most-recently defined word:
6980:
1.44 crook 6981:
1.26 crook 6982: doc-immediate
6983: doc-compile-only
6984: doc-restrict
6985:
1.82 anton 6986: By convention, words with non-default compilation semantics (e.g.,
6987: immediate words) often have names surrounded with brackets (e.g.,
6988: @code{[']}, @pxref{Execution token}).
1.44 crook 6989:
1.26 crook 6990: Note that ticking (@code{'}) a compile-only word gives an error
6991: (``Interpreting a compile-only word'').
1.1 anton 6992:
1.47 crook 6993: @menu
1.67 anton 6994: * Combined words::
1.47 crook 6995: @end menu
1.44 crook 6996:
1.71 anton 6997:
1.48 anton 6998: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 6999: @subsection Combined Words
7000: @cindex combined words
7001:
7002: Gforth allows you to define @dfn{combined words} -- words that have an
7003: arbitrary combination of interpretation and compilation semantics.
7004:
1.26 crook 7005: doc-interpret/compile:
1.1 anton 7006:
1.26 crook 7007: This feature was introduced for implementing @code{TO} and @code{S"}. I
7008: recommend that you do not define such words, as cute as they may be:
7009: they make it hard to get at both parts of the word in some contexts.
7010: E.g., assume you want to get an execution token for the compilation
7011: part. Instead, define two words, one that embodies the interpretation
7012: part, and one that embodies the compilation part. Once you have done
7013: that, you can define a combined word with @code{interpret/compile:} for
7014: the convenience of your users.
1.1 anton 7015:
1.26 crook 7016: You might try to use this feature to provide an optimizing
7017: implementation of the default compilation semantics of a word. For
7018: example, by defining:
1.1 anton 7019: @example
1.26 crook 7020: :noname
7021: foo bar ;
7022: :noname
7023: POSTPONE foo POSTPONE bar ;
1.29 crook 7024: interpret/compile: opti-foobar
1.1 anton 7025: @end example
1.26 crook 7026:
1.23 crook 7027: @noindent
1.26 crook 7028: as an optimizing version of:
7029:
1.1 anton 7030: @example
1.26 crook 7031: : foobar
7032: foo bar ;
1.1 anton 7033: @end example
7034:
1.26 crook 7035: Unfortunately, this does not work correctly with @code{[compile]},
7036: because @code{[compile]} assumes that the compilation semantics of all
7037: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7038: opti-foobar} would compile compilation semantics, whereas
7039: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7040:
1.26 crook 7041: @cindex state-smart words (are a bad idea)
1.82 anton 7042: @anchor{state-smartness}
1.29 crook 7043: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7044: by @code{interpret/compile:} (words are state-smart if they check
7045: @code{STATE} during execution). E.g., they would try to code
7046: @code{foobar} like this:
1.1 anton 7047:
1.26 crook 7048: @example
7049: : foobar
7050: STATE @@
7051: IF ( compilation state )
7052: POSTPONE foo POSTPONE bar
7053: ELSE
7054: foo bar
7055: ENDIF ; immediate
7056: @end example
1.1 anton 7057:
1.26 crook 7058: Although this works if @code{foobar} is only processed by the text
7059: interpreter, it does not work in other contexts (like @code{'} or
7060: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7061: for a state-smart word, not for the interpretation semantics of the
7062: original @code{foobar}; when you execute this execution token (directly
7063: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7064: state, the result will not be what you expected (i.e., it will not
7065: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7066: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7067: M. Anton Ertl,
7068: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7069: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7070:
1.26 crook 7071: @cindex defining words with arbitrary semantics combinations
7072: It is also possible to write defining words that define words with
7073: arbitrary combinations of interpretation and compilation semantics. In
7074: general, they look like this:
1.1 anton 7075:
1.26 crook 7076: @example
7077: : def-word
7078: create-interpret/compile
1.29 crook 7079: @i{code1}
1.26 crook 7080: interpretation>
1.29 crook 7081: @i{code2}
1.26 crook 7082: <interpretation
7083: compilation>
1.29 crook 7084: @i{code3}
1.26 crook 7085: <compilation ;
7086: @end example
1.1 anton 7087:
1.29 crook 7088: For a @i{word} defined with @code{def-word}, the interpretation
7089: semantics are to push the address of the body of @i{word} and perform
7090: @i{code2}, and the compilation semantics are to push the address of
7091: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7092: can also be defined like this (except that the defined constants don't
7093: behave correctly when @code{[compile]}d):
1.1 anton 7094:
1.26 crook 7095: @example
7096: : constant ( n "name" -- )
7097: create-interpret/compile
7098: ,
7099: interpretation> ( -- n )
7100: @@
7101: <interpretation
7102: compilation> ( compilation. -- ; run-time. -- n )
7103: @@ postpone literal
7104: <compilation ;
7105: @end example
1.1 anton 7106:
1.44 crook 7107:
1.26 crook 7108: doc-create-interpret/compile
7109: doc-interpretation>
7110: doc-<interpretation
7111: doc-compilation>
7112: doc-<compilation
1.1 anton 7113:
1.44 crook 7114:
1.29 crook 7115: Words defined with @code{interpret/compile:} and
1.26 crook 7116: @code{create-interpret/compile} have an extended header structure that
7117: differs from other words; however, unless you try to access them with
7118: plain address arithmetic, you should not notice this. Words for
7119: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7120: @code{'} @i{word} @code{>body} also gives you the body of a word created
7121: with @code{create-interpret/compile}.
1.1 anton 7122:
1.44 crook 7123:
1.47 crook 7124: @c -------------------------------------------------------------
1.81 anton 7125: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7126: @section Tokens for Words
7127: @cindex tokens for words
7128:
7129: This section describes the creation and use of tokens that represent
7130: words.
7131:
1.71 anton 7132: @menu
7133: * Execution token:: represents execution/interpretation semantics
7134: * Compilation token:: represents compilation semantics
7135: * Name token:: represents named words
7136: @end menu
1.47 crook 7137:
1.71 anton 7138: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7139: @subsection Execution token
1.47 crook 7140:
7141: @cindex xt
7142: @cindex execution token
1.71 anton 7143: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7144: You can use @code{execute} to invoke this behaviour.
1.47 crook 7145:
1.71 anton 7146: @cindex tick (')
7147: You can use @code{'} to get an execution token that represents the
7148: interpretation semantics of a named word:
1.47 crook 7149:
7150: @example
1.97 anton 7151: 5 ' . ( n xt )
7152: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7153: @end example
1.47 crook 7154:
1.71 anton 7155: doc-'
7156:
7157: @code{'} parses at run-time; there is also a word @code{[']} that parses
7158: when it is compiled, and compiles the resulting XT:
7159:
7160: @example
7161: : foo ['] . execute ;
7162: 5 foo
7163: : bar ' execute ; \ by contrast,
7164: 5 bar . \ ' parses "." when bar executes
7165: @end example
7166:
7167: doc-[']
7168:
7169: If you want the execution token of @i{word}, write @code{['] @i{word}}
7170: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7171: @code{'} and @code{[']} behave somewhat unusually by complaining about
7172: compile-only words (because these words have no interpretation
7173: semantics). You might get what you want by using @code{COMP' @i{word}
7174: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7175: token}).
7176:
1.116 anton 7177: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7178: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7179: for the only behaviour the word has (the execution semantics). For
1.116 anton 7180: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7181: would produce if the word was defined anonymously.
7182:
7183: @example
7184: :noname ." hello" ;
7185: execute
1.47 crook 7186: @end example
7187:
1.71 anton 7188: An XT occupies one cell and can be manipulated like any other cell.
7189:
1.47 crook 7190: @cindex code field address
7191: @cindex CFA
1.71 anton 7192: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7193: operations that produce or consume it). For old hands: In Gforth, the
7194: XT is implemented as a code field address (CFA).
7195:
7196: doc-execute
7197: doc-perform
7198:
7199: @node Compilation token, Name token, Execution token, Tokens for Words
7200: @subsection Compilation token
1.47 crook 7201:
7202: @cindex compilation token
1.71 anton 7203: @cindex CT (compilation token)
7204: Gforth represents the compilation semantics of a named word by a
1.47 crook 7205: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7206: @i{xt} is an execution token. The compilation semantics represented by
7207: the compilation token can be performed with @code{execute}, which
7208: consumes the whole compilation token, with an additional stack effect
7209: determined by the represented compilation semantics.
7210:
7211: At present, the @i{w} part of a compilation token is an execution token,
7212: and the @i{xt} part represents either @code{execute} or
7213: @code{compile,}@footnote{Depending upon the compilation semantics of the
7214: word. If the word has default compilation semantics, the @i{xt} will
7215: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7216: @i{xt} will represent @code{execute}.}. However, don't rely on that
7217: knowledge, unless necessary; future versions of Gforth may introduce
7218: unusual compilation tokens (e.g., a compilation token that represents
7219: the compilation semantics of a literal).
7220:
1.71 anton 7221: You can perform the compilation semantics represented by the compilation
7222: token with @code{execute}. You can compile the compilation semantics
7223: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7224: equivalent to @code{postpone @i{word}}.
7225:
7226: doc-[comp']
7227: doc-comp'
7228: doc-postpone,
7229:
7230: @node Name token, , Compilation token, Tokens for Words
7231: @subsection Name token
1.47 crook 7232:
7233: @cindex name token
1.116 anton 7234: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7235: token is an abstract data type that occurs as argument or result of the
7236: words below.
7237:
7238: @c !! put this elswhere?
1.47 crook 7239: @cindex name field address
7240: @cindex NFA
1.116 anton 7241: The closest thing to the nt in older Forth systems is the name field
7242: address (NFA), but there are significant differences: in older Forth
7243: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7244: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7245: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7246: is a link field in the structure identified by the name token, but
7247: searching usually uses a hash table external to these structures; the
7248: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7249: implemented as the address of that count field.
1.47 crook 7250:
7251: doc-find-name
1.116 anton 7252: doc-latest
7253: doc->name
1.47 crook 7254: doc-name>int
7255: doc-name?int
7256: doc-name>comp
7257: doc-name>string
1.109 anton 7258: doc-id.
7259: doc-.name
7260: doc-.id
1.47 crook 7261:
1.81 anton 7262: @c ----------------------------------------------------------
7263: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7264: @section Compiling words
7265: @cindex compiling words
7266: @cindex macros
7267:
7268: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7269: between compilation and run-time. E.g., you can run arbitrary code
7270: between defining words (or for computing data used by defining words
7271: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7272: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7273: running arbitrary code while compiling a colon definition (exception:
7274: you must not allot dictionary space).
7275:
7276: @menu
7277: * Literals:: Compiling data values
7278: * Macros:: Compiling words
7279: @end menu
7280:
7281: @node Literals, Macros, Compiling words, Compiling words
7282: @subsection Literals
7283: @cindex Literals
7284:
7285: The simplest and most frequent example is to compute a literal during
7286: compilation. E.g., the following definition prints an array of strings,
7287: one string per line:
7288:
7289: @example
7290: : .strings ( addr u -- ) \ gforth
7291: 2* cells bounds U+DO
7292: cr i 2@@ type
7293: 2 cells +LOOP ;
7294: @end example
1.81 anton 7295:
1.82 anton 7296: With a simple-minded compiler like Gforth's, this computes @code{2
7297: cells} on every loop iteration. You can compute this value once and for
7298: all at compile time and compile it into the definition like this:
7299:
7300: @example
7301: : .strings ( addr u -- ) \ gforth
7302: 2* cells bounds U+DO
7303: cr i 2@@ type
7304: [ 2 cells ] literal +LOOP ;
7305: @end example
7306:
7307: @code{[} switches the text interpreter to interpret state (you will get
7308: an @code{ok} prompt if you type this example interactively and insert a
7309: newline between @code{[} and @code{]}), so it performs the
7310: interpretation semantics of @code{2 cells}; this computes a number.
7311: @code{]} switches the text interpreter back into compile state. It then
7312: performs @code{Literal}'s compilation semantics, which are to compile
7313: this number into the current word. You can decompile the word with
7314: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7315:
1.82 anton 7316: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7317: *} in this way.
1.81 anton 7318:
1.82 anton 7319: doc-[
7320: doc-]
1.81 anton 7321: doc-literal
7322: doc-]L
1.82 anton 7323:
7324: There are also words for compiling other data types than single cells as
7325: literals:
7326:
1.81 anton 7327: doc-2literal
7328: doc-fliteral
1.82 anton 7329: doc-sliteral
7330:
7331: @cindex colon-sys, passing data across @code{:}
7332: @cindex @code{:}, passing data across
7333: You might be tempted to pass data from outside a colon definition to the
7334: inside on the data stack. This does not work, because @code{:} puhes a
7335: colon-sys, making stuff below unaccessible. E.g., this does not work:
7336:
7337: @example
7338: 5 : foo literal ; \ error: "unstructured"
7339: @end example
7340:
7341: Instead, you have to pass the value in some other way, e.g., through a
7342: variable:
7343:
7344: @example
7345: variable temp
7346: 5 temp !
7347: : foo [ temp @@ ] literal ;
7348: @end example
7349:
7350:
7351: @node Macros, , Literals, Compiling words
7352: @subsection Macros
7353: @cindex Macros
7354: @cindex compiling compilation semantics
7355:
7356: @code{Literal} and friends compile data values into the current
7357: definition. You can also write words that compile other words into the
7358: current definition. E.g.,
7359:
7360: @example
7361: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7362: POSTPONE + ;
7363:
7364: : foo ( n1 n2 -- n )
7365: [ compile-+ ] ;
7366: 1 2 foo .
7367: @end example
7368:
7369: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7370: What happens in this example? @code{Postpone} compiles the compilation
7371: semantics of @code{+} into @code{compile-+}; later the text interpreter
7372: executes @code{compile-+} and thus the compilation semantics of +, which
7373: compile (the execution semantics of) @code{+} into
7374: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7375: should only be executed in compile state, so this example is not
7376: guaranteed to work on all standard systems, but on any decent system it
7377: will work.}
7378:
7379: doc-postpone
7380: doc-[compile]
7381:
7382: Compiling words like @code{compile-+} are usually immediate (or similar)
7383: so you do not have to switch to interpret state to execute them;
7384: mopifying the last example accordingly produces:
7385:
7386: @example
7387: : [compile-+] ( compilation: --; interpretation: -- )
7388: \ compiled code: ( n1 n2 -- n )
7389: POSTPONE + ; immediate
7390:
7391: : foo ( n1 n2 -- n )
7392: [compile-+] ;
7393: 1 2 foo .
7394: @end example
7395:
7396: Immediate compiling words are similar to macros in other languages (in
7397: particular, Lisp). The important differences to macros in, e.g., C are:
7398:
7399: @itemize @bullet
7400:
7401: @item
7402: You use the same language for defining and processing macros, not a
7403: separate preprocessing language and processor.
7404:
7405: @item
7406: Consequently, the full power of Forth is available in macro definitions.
7407: E.g., you can perform arbitrarily complex computations, or generate
7408: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7409: Tutorial}). This power is very useful when writing a parser generators
7410: or other code-generating software.
7411:
7412: @item
7413: Macros defined using @code{postpone} etc. deal with the language at a
7414: higher level than strings; name binding happens at macro definition
7415: time, so you can avoid the pitfalls of name collisions that can happen
7416: in C macros. Of course, Forth is a liberal language and also allows to
7417: shoot yourself in the foot with text-interpreted macros like
7418:
7419: @example
7420: : [compile-+] s" +" evaluate ; immediate
7421: @end example
7422:
7423: Apart from binding the name at macro use time, using @code{evaluate}
7424: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7425: @end itemize
7426:
7427: You may want the macro to compile a number into a word. The word to do
7428: it is @code{literal}, but you have to @code{postpone} it, so its
7429: compilation semantics take effect when the macro is executed, not when
7430: it is compiled:
7431:
7432: @example
7433: : [compile-5] ( -- ) \ compiled code: ( -- n )
7434: 5 POSTPONE literal ; immediate
7435:
7436: : foo [compile-5] ;
7437: foo .
7438: @end example
7439:
7440: You may want to pass parameters to a macro, that the macro should
7441: compile into the current definition. If the parameter is a number, then
7442: you can use @code{postpone literal} (similar for other values).
7443:
7444: If you want to pass a word that is to be compiled, the usual way is to
7445: pass an execution token and @code{compile,} it:
7446:
7447: @example
7448: : twice1 ( xt -- ) \ compiled code: ... -- ...
7449: dup compile, compile, ;
7450:
7451: : 2+ ( n1 -- n2 )
7452: [ ' 1+ twice1 ] ;
7453: @end example
7454:
7455: doc-compile,
7456:
7457: An alternative available in Gforth, that allows you to pass compile-only
7458: words as parameters is to use the compilation token (@pxref{Compilation
7459: token}). The same example in this technique:
7460:
7461: @example
7462: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7463: 2dup 2>r execute 2r> execute ;
7464:
7465: : 2+ ( n1 -- n2 )
7466: [ comp' 1+ twice ] ;
7467: @end example
7468:
7469: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7470: works even if the executed compilation semantics has an effect on the
7471: data stack.
7472:
7473: You can also define complete definitions with these words; this provides
7474: an alternative to using @code{does>} (@pxref{User-defined Defining
7475: Words}). E.g., instead of
7476:
7477: @example
7478: : curry+ ( n1 "name" -- )
7479: CREATE ,
7480: DOES> ( n2 -- n1+n2 )
7481: @@ + ;
7482: @end example
7483:
7484: you could define
7485:
7486: @example
7487: : curry+ ( n1 "name" -- )
7488: \ name execution: ( n2 -- n1+n2 )
7489: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7490:
1.82 anton 7491: -3 curry+ 3-
7492: see 3-
7493: @end example
1.81 anton 7494:
1.82 anton 7495: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7496: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7497:
1.82 anton 7498: This way of writing defining words is sometimes more, sometimes less
7499: convenient than using @code{does>} (@pxref{Advanced does> usage
7500: example}). One advantage of this method is that it can be optimized
7501: better, because the compiler knows that the value compiled with
7502: @code{literal} is fixed, whereas the data associated with a
7503: @code{create}d word can be changed.
1.47 crook 7504:
1.26 crook 7505: @c ----------------------------------------------------------
1.111 anton 7506: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7507: @section The Text Interpreter
7508: @cindex interpreter - outer
7509: @cindex text interpreter
7510: @cindex outer interpreter
1.1 anton 7511:
1.34 anton 7512: @c Should we really describe all these ugly details? IMO the text
7513: @c interpreter should be much cleaner, but that may not be possible within
7514: @c ANS Forth. - anton
1.44 crook 7515: @c nac-> I wanted to explain how it works to show how you can exploit
7516: @c it in your own programs. When I was writing a cross-compiler, figuring out
7517: @c some of these gory details was very helpful to me. None of the textbooks
7518: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7519: @c seems to positively avoid going into too much detail for some of
7520: @c the internals.
1.34 anton 7521:
1.71 anton 7522: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7523: @c it is; for the ugly details, I would prefer another place. I wonder
7524: @c whether we should have a chapter before "Words" that describes some
7525: @c basic concepts referred to in words, and a chapter after "Words" that
7526: @c describes implementation details.
7527:
1.29 crook 7528: The text interpreter@footnote{This is an expanded version of the
7529: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7530: that processes input from the current input device. It is also called
7531: the outer interpreter, in contrast to the inner interpreter
7532: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7533: implementations.
1.27 crook 7534:
1.29 crook 7535: @cindex interpret state
7536: @cindex compile state
7537: The text interpreter operates in one of two states: @dfn{interpret
7538: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7539: aptly-named variable @code{state}.
1.29 crook 7540:
7541: This section starts by describing how the text interpreter behaves when
7542: it is in interpret state, processing input from the user input device --
7543: the keyboard. This is the mode that a Forth system is in after it starts
7544: up.
7545:
7546: @cindex input buffer
7547: @cindex terminal input buffer
7548: The text interpreter works from an area of memory called the @dfn{input
7549: buffer}@footnote{When the text interpreter is processing input from the
7550: keyboard, this area of memory is called the @dfn{terminal input buffer}
7551: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7552: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7553: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7554: leading spaces (called @dfn{delimiters}) then parses a string (a
7555: sequence of non-space characters) until it reaches either a space
7556: character or the end of the buffer. Having parsed a string, it makes two
7557: attempts to process it:
1.27 crook 7558:
1.29 crook 7559: @cindex dictionary
1.27 crook 7560: @itemize @bullet
7561: @item
1.29 crook 7562: It looks for the string in a @dfn{dictionary} of definitions. If the
7563: string is found, the string names a @dfn{definition} (also known as a
7564: @dfn{word}) and the dictionary search returns information that allows
7565: the text interpreter to perform the word's @dfn{interpretation
7566: semantics}. In most cases, this simply means that the word will be
7567: executed.
1.27 crook 7568: @item
7569: If the string is not found in the dictionary, the text interpreter
1.29 crook 7570: attempts to treat it as a number, using the rules described in
7571: @ref{Number Conversion}. If the string represents a legal number in the
7572: current radix, the number is pushed onto a parameter stack (the data
7573: stack for integers, the floating-point stack for floating-point
7574: numbers).
7575: @end itemize
7576:
7577: If both attempts fail, or if the word is found in the dictionary but has
7578: no interpretation semantics@footnote{This happens if the word was
7579: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7580: remainder of the input buffer, issues an error message and waits for
7581: more input. If one of the attempts succeeds, the text interpreter
7582: repeats the parsing process until the whole of the input buffer has been
7583: processed, at which point it prints the status message ``@code{ ok}''
7584: and waits for more input.
7585:
1.71 anton 7586: @c anton: this should be in the input stream subsection (or below it)
7587:
1.29 crook 7588: @cindex parse area
7589: The text interpreter keeps track of its position in the input buffer by
7590: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7591: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7592: of the input buffer. The region from offset @code{>IN @@} to the end of
7593: the input buffer is called the @dfn{parse area}@footnote{In other words,
7594: the text interpreter processes the contents of the input buffer by
7595: parsing strings from the parse area until the parse area is empty.}.
7596: This example shows how @code{>IN} changes as the text interpreter parses
7597: the input buffer:
7598:
7599: @example
7600: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7601: CR ." ->" TYPE ." <-" ; IMMEDIATE
7602:
7603: 1 2 3 remaining + remaining .
7604:
7605: : foo 1 2 3 remaining SWAP remaining ;
7606: @end example
7607:
7608: @noindent
7609: The result is:
7610:
7611: @example
7612: ->+ remaining .<-
7613: ->.<-5 ok
7614:
7615: ->SWAP remaining ;-<
7616: ->;<- ok
7617: @end example
7618:
7619: @cindex parsing words
7620: The value of @code{>IN} can also be modified by a word in the input
7621: buffer that is executed by the text interpreter. This means that a word
7622: can ``trick'' the text interpreter into either skipping a section of the
7623: input buffer@footnote{This is how parsing words work.} or into parsing a
7624: section twice. For example:
1.27 crook 7625:
1.29 crook 7626: @example
1.71 anton 7627: : lat ." <<foo>>" ;
7628: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7629: @end example
7630:
7631: @noindent
7632: When @code{flat} is executed, this output is produced@footnote{Exercise
7633: for the reader: what would happen if the @code{3} were replaced with
7634: @code{4}?}:
7635:
7636: @example
1.71 anton 7637: <<bar>><<foo>>
1.29 crook 7638: @end example
7639:
1.71 anton 7640: This technique can be used to work around some of the interoperability
7641: problems of parsing words. Of course, it's better to avoid parsing
7642: words where possible.
7643:
1.29 crook 7644: @noindent
7645: Two important notes about the behaviour of the text interpreter:
1.27 crook 7646:
7647: @itemize @bullet
7648: @item
7649: It processes each input string to completion before parsing additional
1.29 crook 7650: characters from the input buffer.
7651: @item
7652: It treats the input buffer as a read-only region (and so must your code).
7653: @end itemize
7654:
7655: @noindent
7656: When the text interpreter is in compile state, its behaviour changes in
7657: these ways:
7658:
7659: @itemize @bullet
7660: @item
7661: If a parsed string is found in the dictionary, the text interpreter will
7662: perform the word's @dfn{compilation semantics}. In most cases, this
7663: simply means that the execution semantics of the word will be appended
7664: to the current definition.
1.27 crook 7665: @item
1.29 crook 7666: When a number is encountered, it is compiled into the current definition
7667: (as a literal) rather than being pushed onto a parameter stack.
7668: @item
7669: If an error occurs, @code{state} is modified to put the text interpreter
7670: back into interpret state.
7671: @item
7672: Each time a line is entered from the keyboard, Gforth prints
7673: ``@code{ compiled}'' rather than `` @code{ok}''.
7674: @end itemize
7675:
7676: @cindex text interpreter - input sources
7677: When the text interpreter is using an input device other than the
7678: keyboard, its behaviour changes in these ways:
7679:
7680: @itemize @bullet
7681: @item
7682: When the parse area is empty, the text interpreter attempts to refill
7683: the input buffer from the input source. When the input source is
1.71 anton 7684: exhausted, the input source is set back to the previous input source.
1.29 crook 7685: @item
7686: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7687: time the parse area is emptied.
7688: @item
7689: If an error occurs, the input source is set back to the user input
7690: device.
1.27 crook 7691: @end itemize
1.21 crook 7692:
1.49 anton 7693: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7694:
1.26 crook 7695: doc->in
1.27 crook 7696: doc-source
7697:
1.26 crook 7698: doc-tib
7699: doc-#tib
1.1 anton 7700:
1.44 crook 7701:
1.26 crook 7702: @menu
1.67 anton 7703: * Input Sources::
7704: * Number Conversion::
7705: * Interpret/Compile states::
7706: * Interpreter Directives::
1.26 crook 7707: @end menu
1.1 anton 7708:
1.29 crook 7709: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7710: @subsection Input Sources
7711: @cindex input sources
7712: @cindex text interpreter - input sources
7713:
1.44 crook 7714: By default, the text interpreter processes input from the user input
1.29 crook 7715: device (the keyboard) when Forth starts up. The text interpreter can
7716: process input from any of these sources:
7717:
7718: @itemize @bullet
7719: @item
7720: The user input device -- the keyboard.
7721: @item
7722: A file, using the words described in @ref{Forth source files}.
7723: @item
7724: A block, using the words described in @ref{Blocks}.
7725: @item
7726: A text string, using @code{evaluate}.
7727: @end itemize
7728:
7729: A program can identify the current input device from the values of
7730: @code{source-id} and @code{blk}.
7731:
1.44 crook 7732:
1.29 crook 7733: doc-source-id
7734: doc-blk
7735:
7736: doc-save-input
7737: doc-restore-input
7738:
7739: doc-evaluate
1.111 anton 7740: doc-query
1.1 anton 7741:
1.29 crook 7742:
1.44 crook 7743:
1.29 crook 7744: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7745: @subsection Number Conversion
7746: @cindex number conversion
7747: @cindex double-cell numbers, input format
7748: @cindex input format for double-cell numbers
7749: @cindex single-cell numbers, input format
7750: @cindex input format for single-cell numbers
7751: @cindex floating-point numbers, input format
7752: @cindex input format for floating-point numbers
1.1 anton 7753:
1.29 crook 7754: This section describes the rules that the text interpreter uses when it
7755: tries to convert a string into a number.
1.1 anton 7756:
1.26 crook 7757: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7758: number base@footnote{For example, 0-9 when the number base is decimal or
7759: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7760:
1.26 crook 7761: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7762:
1.29 crook 7763: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7764: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7765:
1.26 crook 7766: Let * represent any number of instances of the previous character
7767: (including none).
1.1 anton 7768:
1.26 crook 7769: Let any other character represent itself.
1.1 anton 7770:
1.29 crook 7771: @noindent
1.26 crook 7772: Now, the conversion rules are:
1.21 crook 7773:
1.26 crook 7774: @itemize @bullet
7775: @item
7776: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7777: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7778: @item
7779: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7780: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7781: arithmetic. Examples are -45 -5681 -0
7782: @item
7783: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7784: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7785: (all three of these represent the same number).
1.26 crook 7786: @item
7787: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7788: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7789: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7790: -34.65 (all three of these represent the same number).
1.26 crook 7791: @item
1.29 crook 7792: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7793: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7794: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7795: number) +12.E-4
1.26 crook 7796: @end itemize
1.1 anton 7797:
1.174 anton 7798: By default, the number base used for integer number conversion is
7799: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7800: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7801: change @code{base} anywhere, make sure to save the old value and
7802: restore it afterwards; better yet, use @code{base-execute}, which does
7803: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7804: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7805:
1.29 crook 7806: doc-dpl
1.174 anton 7807: doc-base-execute
1.26 crook 7808: doc-base
7809: doc-hex
7810: doc-decimal
1.1 anton 7811:
1.26 crook 7812: @cindex '-prefix for character strings
7813: @cindex &-prefix for decimal numbers
1.133 anton 7814: @cindex #-prefix for decimal numbers
1.26 crook 7815: @cindex %-prefix for binary numbers
7816: @cindex $-prefix for hexadecimal numbers
1.133 anton 7817: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7818: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7819: prefix@footnote{Some Forth implementations provide a similar scheme by
7820: implementing @code{$} etc. as parsing words that process the subsequent
7821: number in the input stream and push it onto the stack. For example, see
7822: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7823: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7824: is required between the prefix and the number.} before the first digit
1.133 anton 7825: of an (integer) number. The following prefixes are supported:
1.1 anton 7826:
1.26 crook 7827: @itemize @bullet
7828: @item
1.35 anton 7829: @code{&} -- decimal
1.26 crook 7830: @item
1.133 anton 7831: @code{#} -- decimal
7832: @item
1.35 anton 7833: @code{%} -- binary
1.26 crook 7834: @item
1.35 anton 7835: @code{$} -- hexadecimal
1.26 crook 7836: @item
1.133 anton 7837: @code{0x} -- hexadecimal, if base<33.
7838: @item
7839: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7840: optional @code{'} may be present after the character.
1.26 crook 7841: @end itemize
1.1 anton 7842:
1.26 crook 7843: Here are some examples, with the equivalent decimal number shown after
7844: in braces:
1.1 anton 7845:
1.26 crook 7846: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7847: 'A (65),
7848: -'a' (-97),
1.26 crook 7849: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7850:
1.26 crook 7851: @cindex number conversion - traps for the unwary
1.29 crook 7852: @noindent
1.26 crook 7853: Number conversion has a number of traps for the unwary:
1.1 anton 7854:
1.26 crook 7855: @itemize @bullet
7856: @item
7857: You cannot determine the current number base using the code sequence
1.35 anton 7858: @code{base @@ .} -- the number base is always 10 in the current number
7859: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7860: @item
7861: If the number base is set to a value greater than 14 (for example,
7862: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7863: it to be intepreted as either a single-precision integer or a
7864: floating-point number (Gforth treats it as an integer). The ambiguity
7865: can be resolved by explicitly stating the sign of the mantissa and/or
7866: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7867: ambiguity arises; either representation will be treated as a
7868: floating-point number.
7869: @item
1.29 crook 7870: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7871: It is used to specify file types.
7872: @item
1.72 anton 7873: ANS Forth requires the @code{.} of a double-precision number to be the
7874: final character in the string. Gforth allows the @code{.} to be
7875: anywhere after the first digit.
1.26 crook 7876: @item
7877: The number conversion process does not check for overflow.
7878: @item
1.72 anton 7879: In an ANS Forth program @code{base} is required to be decimal when
7880: converting floating-point numbers. In Gforth, number conversion to
7881: floating-point numbers always uses base &10, irrespective of the value
7882: of @code{base}.
1.26 crook 7883: @end itemize
1.1 anton 7884:
1.49 anton 7885: You can read numbers into your programs with the words described in
1.181 anton 7886: @ref{Line input and conversion}.
1.1 anton 7887:
1.82 anton 7888: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7889: @subsection Interpret/Compile states
7890: @cindex Interpret/Compile states
1.1 anton 7891:
1.29 crook 7892: A standard program is not permitted to change @code{state}
7893: explicitly. However, it can change @code{state} implicitly, using the
7894: words @code{[} and @code{]}. When @code{[} is executed it switches
7895: @code{state} to interpret state, and therefore the text interpreter
7896: starts interpreting. When @code{]} is executed it switches @code{state}
7897: to compile state and therefore the text interpreter starts
1.44 crook 7898: compiling. The most common usage for these words is for switching into
7899: interpret state and back from within a colon definition; this technique
1.49 anton 7900: can be used to compile a literal (for an example, @pxref{Literals}) or
7901: for conditional compilation (for an example, @pxref{Interpreter
7902: Directives}).
1.44 crook 7903:
1.35 anton 7904:
7905: @c This is a bad example: It's non-standard, and it's not necessary.
7906: @c However, I can't think of a good example for switching into compile
7907: @c state when there is no current word (@code{state}-smart words are not a
7908: @c good reason). So maybe we should use an example for switching into
7909: @c interpret @code{state} in a colon def. - anton
1.44 crook 7910: @c nac-> I agree. I started out by putting in the example, then realised
7911: @c that it was non-ANS, so wrote more words around it. I hope this
7912: @c re-written version is acceptable to you. I do want to keep the example
7913: @c as it is helpful for showing what is and what is not portable, particularly
7914: @c where it outlaws a style in common use.
7915:
1.72 anton 7916: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7917: @c that, we can also show what's not. In any case, I have written a
7918: @c section Compiling Words which also deals with [ ].
1.35 anton 7919:
1.95 anton 7920: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7921:
1.95 anton 7922: @c @code{[} and @code{]} also give you the ability to switch into compile
7923: @c state and back, but we cannot think of any useful Standard application
7924: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7925:
7926: @c @example
7927: @c : AA ." this is A" ;
7928: @c : BB ." this is B" ;
7929: @c : CC ." this is C" ;
7930:
7931: @c create table ] aa bb cc [
7932:
7933: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7934: @c cells table + @@ execute ;
7935: @c @end example
7936:
7937: @c This example builds a jump table; @code{0 go} will display ``@code{this
7938: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7939: @c defining @code{table} like this:
7940:
7941: @c @example
7942: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7943: @c @end example
7944:
7945: @c The problem with this code is that the definition of @code{table} is not
7946: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7947: @c @i{may} work on systems where code space and data space co-incide, the
7948: @c Standard only allows data space to be assigned for a @code{CREATE}d
7949: @c word. In addition, the Standard only allows @code{@@} to access data
7950: @c space, whilst this example is using it to access code space. The only
7951: @c portable, Standard way to build this table is to build it in data space,
7952: @c like this:
7953:
7954: @c @example
7955: @c create table ' aa , ' bb , ' cc ,
7956: @c @end example
1.29 crook 7957:
1.95 anton 7958: @c doc-state
1.44 crook 7959:
1.29 crook 7960:
1.82 anton 7961: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7962: @subsection Interpreter Directives
7963: @cindex interpreter directives
1.72 anton 7964: @cindex conditional compilation
1.1 anton 7965:
1.29 crook 7966: These words are usually used in interpret state; typically to control
7967: which parts of a source file are processed by the text
1.26 crook 7968: interpreter. There are only a few ANS Forth Standard words, but Gforth
7969: supplements these with a rich set of immediate control structure words
7970: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7971: used in compile state (@pxref{Control Structures}). Typical usages:
7972:
7973: @example
1.72 anton 7974: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7975: .
7976: .
1.72 anton 7977: HAVE-ASSEMBLER [IF]
1.29 crook 7978: : ASSEMBLER-FEATURE
7979: ...
7980: ;
7981: [ENDIF]
7982: .
7983: .
7984: : SEE
7985: ... \ general-purpose SEE code
1.72 anton 7986: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7987: ... \ assembler-specific SEE code
7988: [ [ENDIF] ]
7989: ;
7990: @end example
1.1 anton 7991:
1.44 crook 7992:
1.26 crook 7993: doc-[IF]
7994: doc-[ELSE]
7995: doc-[THEN]
7996: doc-[ENDIF]
1.1 anton 7997:
1.26 crook 7998: doc-[IFDEF]
7999: doc-[IFUNDEF]
1.1 anton 8000:
1.26 crook 8001: doc-[?DO]
8002: doc-[DO]
8003: doc-[FOR]
8004: doc-[LOOP]
8005: doc-[+LOOP]
8006: doc-[NEXT]
1.1 anton 8007:
1.26 crook 8008: doc-[BEGIN]
8009: doc-[UNTIL]
8010: doc-[AGAIN]
8011: doc-[WHILE]
8012: doc-[REPEAT]
1.1 anton 8013:
1.27 crook 8014:
1.26 crook 8015: @c -------------------------------------------------------------
1.111 anton 8016: @node The Input Stream, Word Lists, The Text Interpreter, Words
8017: @section The Input Stream
8018: @cindex input stream
8019:
8020: @c !! integrate this better with the "Text Interpreter" section
8021: The text interpreter reads from the input stream, which can come from
8022: several sources (@pxref{Input Sources}). Some words, in particular
8023: defining words, but also words like @code{'}, read parameters from the
8024: input stream instead of from the stack.
8025:
8026: Such words are called parsing words, because they parse the input
8027: stream. Parsing words are hard to use in other words, because it is
8028: hard to pass program-generated parameters through the input stream.
8029: They also usually have an unintuitive combination of interpretation and
8030: compilation semantics when implemented naively, leading to various
8031: approaches that try to produce a more intuitive behaviour
8032: (@pxref{Combined words}).
8033:
8034: It should be obvious by now that parsing words are a bad idea. If you
8035: want to implement a parsing word for convenience, also provide a factor
8036: of the word that does not parse, but takes the parameters on the stack.
8037: To implement the parsing word on top if it, you can use the following
8038: words:
8039:
8040: @c anton: these belong in the input stream section
8041: doc-parse
1.138 anton 8042: doc-parse-name
1.111 anton 8043: doc-parse-word
8044: doc-name
8045: doc-word
8046: doc-refill
8047:
8048: Conversely, if you have the bad luck (or lack of foresight) to have to
8049: deal with parsing words without having such factors, how do you pass a
8050: string that is not in the input stream to it?
8051:
8052: doc-execute-parsing
8053:
1.146 anton 8054: A definition of this word in ANS Forth is provided in
8055: @file{compat/execute-parsing.fs}.
8056:
1.111 anton 8057: If you want to run a parsing word on a file, the following word should
8058: help:
8059:
8060: doc-execute-parsing-file
8061:
8062: @c -------------------------------------------------------------
8063: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8064: @section Word Lists
8065: @cindex word lists
1.32 anton 8066: @cindex header space
1.1 anton 8067:
1.36 anton 8068: A wordlist is a list of named words; you can add new words and look up
8069: words by name (and you can remove words in a restricted way with
8070: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8071:
8072: @cindex search order stack
8073: The text interpreter searches the wordlists present in the search order
8074: (a stack of wordlists), from the top to the bottom. Within each
8075: wordlist, the search starts conceptually at the newest word; i.e., if
8076: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8077:
1.26 crook 8078: @cindex compilation word list
1.36 anton 8079: New words are added to the @dfn{compilation wordlist} (aka current
8080: wordlist).
1.1 anton 8081:
1.36 anton 8082: @cindex wid
8083: A word list is identified by a cell-sized word list identifier (@i{wid})
8084: in much the same way as a file is identified by a file handle. The
8085: numerical value of the wid has no (portable) meaning, and might change
8086: from session to session.
1.1 anton 8087:
1.29 crook 8088: The ANS Forth ``Search order'' word set is intended to provide a set of
8089: low-level tools that allow various different schemes to be
1.74 anton 8090: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8091: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8092: Forth.
1.1 anton 8093:
1.27 crook 8094: @comment TODO: locals section refers to here, saying that every word list (aka
8095: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8096: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8097:
1.45 crook 8098: @comment TODO: document markers, reveal, tables, mappedwordlist
8099:
8100: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8101: @comment word from the source files, rather than some alias.
1.44 crook 8102:
1.26 crook 8103: doc-forth-wordlist
8104: doc-definitions
8105: doc-get-current
8106: doc-set-current
8107: doc-get-order
1.185 anton 8108: doc-set-order
1.26 crook 8109: doc-wordlist
1.30 anton 8110: doc-table
1.79 anton 8111: doc->order
1.36 anton 8112: doc-previous
1.26 crook 8113: doc-also
1.185 anton 8114: doc-forth
1.26 crook 8115: doc-only
1.185 anton 8116: doc-order
1.15 anton 8117:
1.26 crook 8118: doc-find
8119: doc-search-wordlist
1.15 anton 8120:
1.26 crook 8121: doc-words
8122: doc-vlist
1.44 crook 8123: @c doc-words-deferred
1.1 anton 8124:
1.74 anton 8125: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8126: doc-root
8127: doc-vocabulary
8128: doc-seal
8129: doc-vocs
8130: doc-current
8131: doc-context
1.1 anton 8132:
1.44 crook 8133:
1.26 crook 8134: @menu
1.75 anton 8135: * Vocabularies::
1.67 anton 8136: * Why use word lists?::
1.75 anton 8137: * Word list example::
1.26 crook 8138: @end menu
8139:
1.75 anton 8140: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8141: @subsection Vocabularies
8142: @cindex Vocabularies, detailed explanation
8143:
8144: Here is an example of creating and using a new wordlist using ANS
8145: Forth words:
8146:
8147: @example
8148: wordlist constant my-new-words-wordlist
8149: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8150:
8151: \ add it to the search order
8152: also my-new-words
8153:
8154: \ alternatively, add it to the search order and make it
8155: \ the compilation word list
8156: also my-new-words definitions
8157: \ type "order" to see the problem
8158: @end example
8159:
8160: The problem with this example is that @code{order} has no way to
8161: associate the name @code{my-new-words} with the wid of the word list (in
8162: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8163: that has no associated name). There is no Standard way of associating a
8164: name with a wid.
8165:
8166: In Gforth, this example can be re-coded using @code{vocabulary}, which
8167: associates a name with a wid:
8168:
8169: @example
8170: vocabulary my-new-words
8171:
8172: \ add it to the search order
8173: also my-new-words
8174:
8175: \ alternatively, add it to the search order and make it
8176: \ the compilation word list
8177: my-new-words definitions
8178: \ type "order" to see that the problem is solved
8179: @end example
8180:
8181:
8182: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8183: @subsection Why use word lists?
8184: @cindex word lists - why use them?
8185:
1.74 anton 8186: Here are some reasons why people use wordlists:
1.26 crook 8187:
8188: @itemize @bullet
1.74 anton 8189:
8190: @c anton: Gforth's hashing implementation makes the search speed
8191: @c independent from the number of words. But it is linear with the number
8192: @c of wordlists that have to be searched, so in effect using more wordlists
8193: @c actually slows down compilation.
8194:
8195: @c @item
8196: @c To improve compilation speed by reducing the number of header space
8197: @c entries that must be searched. This is achieved by creating a new
8198: @c word list that contains all of the definitions that are used in the
8199: @c definition of a Forth system but which would not usually be used by
8200: @c programs running on that system. That word list would be on the search
8201: @c list when the Forth system was compiled but would be removed from the
8202: @c search list for normal operation. This can be a useful technique for
8203: @c low-performance systems (for example, 8-bit processors in embedded
8204: @c systems) but is unlikely to be necessary in high-performance desktop
8205: @c systems.
8206:
1.26 crook 8207: @item
8208: To prevent a set of words from being used outside the context in which
8209: they are valid. Two classic examples of this are an integrated editor
8210: (all of the edit commands are defined in a separate word list; the
8211: search order is set to the editor word list when the editor is invoked;
8212: the old search order is restored when the editor is terminated) and an
8213: integrated assembler (the op-codes for the machine are defined in a
8214: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8215:
8216: @item
8217: To organize the words of an application or library into a user-visible
8218: set (in @code{forth-wordlist} or some other common wordlist) and a set
8219: of helper words used just for the implementation (hidden in a separate
1.75 anton 8220: wordlist). This keeps @code{words}' output smaller, separates
8221: implementation and interface, and reduces the chance of name conflicts
8222: within the common wordlist.
1.74 anton 8223:
1.26 crook 8224: @item
8225: To prevent a name-space clash between multiple definitions with the same
8226: name. For example, when building a cross-compiler you might have a word
8227: @code{IF} that generates conditional code for your target system. By
8228: placing this definition in a different word list you can control whether
8229: the host system's @code{IF} or the target system's @code{IF} get used in
8230: any particular context by controlling the order of the word lists on the
8231: search order stack.
1.74 anton 8232:
1.26 crook 8233: @end itemize
1.1 anton 8234:
1.74 anton 8235: The downsides of using wordlists are:
8236:
8237: @itemize
8238:
8239: @item
8240: Debugging becomes more cumbersome.
8241:
8242: @item
8243: Name conflicts worked around with wordlists are still there, and you
8244: have to arrange the search order carefully to get the desired results;
8245: if you forget to do that, you get hard-to-find errors (as in any case
8246: where you read the code differently from the compiler; @code{see} can
1.75 anton 8247: help seeing which of several possible words the name resolves to in such
8248: cases). @code{See} displays just the name of the words, not what
8249: wordlist they belong to, so it might be misleading. Using unique names
8250: is a better approach to avoid name conflicts.
1.74 anton 8251:
8252: @item
8253: You have to explicitly undo any changes to the search order. In many
8254: cases it would be more convenient if this happened implicitly. Gforth
8255: currently does not provide such a feature, but it may do so in the
8256: future.
8257: @end itemize
8258:
8259:
1.75 anton 8260: @node Word list example, , Why use word lists?, Word Lists
8261: @subsection Word list example
8262: @cindex word lists - example
1.1 anton 8263:
1.74 anton 8264: The following example is from the
8265: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8266: garbage collector} and uses wordlists to separate public words from
8267: helper words:
8268:
8269: @example
8270: get-current ( wid )
8271: vocabulary garbage-collector also garbage-collector definitions
8272: ... \ define helper words
8273: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8274: ... \ define the public (i.e., API) words
8275: \ they can refer to the helper words
8276: previous \ restore original search order (helper words become invisible)
8277: @end example
8278:
1.26 crook 8279: @c -------------------------------------------------------------
8280: @node Environmental Queries, Files, Word Lists, Words
8281: @section Environmental Queries
8282: @cindex environmental queries
1.21 crook 8283:
1.26 crook 8284: ANS Forth introduced the idea of ``environmental queries'' as a way
8285: for a program running on a system to determine certain characteristics of the system.
8286: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8287:
1.32 anton 8288: The Standard requires that the header space used for environmental queries
8289: be distinct from the header space used for definitions.
1.21 crook 8290:
1.26 crook 8291: Typically, environmental queries are supported by creating a set of
1.29 crook 8292: definitions in a word list that is @i{only} used during environmental
1.26 crook 8293: queries; that is what Gforth does. There is no Standard way of adding
8294: definitions to the set of recognised environmental queries, but any
8295: implementation that supports the loading of optional word sets must have
8296: some mechanism for doing this (after loading the word set, the
8297: associated environmental query string must return @code{true}). In
8298: Gforth, the word list used to honour environmental queries can be
8299: manipulated just like any other word list.
1.21 crook 8300:
1.44 crook 8301:
1.26 crook 8302: doc-environment?
8303: doc-environment-wordlist
1.21 crook 8304:
1.26 crook 8305: doc-gforth
8306: doc-os-class
1.21 crook 8307:
1.44 crook 8308:
1.26 crook 8309: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8310: returning two items on the stack, querying it using @code{environment?}
8311: will return an additional item; the @code{true} flag that shows that the
8312: string was recognised.
1.21 crook 8313:
1.26 crook 8314: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8315:
1.26 crook 8316: Here are some examples of using environmental queries:
1.21 crook 8317:
1.26 crook 8318: @example
8319: s" address-unit-bits" environment? 0=
8320: [IF]
8321: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8322: [ELSE]
8323: drop \ ensure balanced stack effect
1.26 crook 8324: [THEN]
1.21 crook 8325:
1.75 anton 8326: \ this might occur in the prelude of a standard program that uses THROW
8327: s" exception" environment? [IF]
8328: 0= [IF]
8329: : throw abort" exception thrown" ;
8330: [THEN]
8331: [ELSE] \ we don't know, so make sure
8332: : throw abort" exception thrown" ;
8333: [THEN]
1.21 crook 8334:
1.26 crook 8335: s" gforth" environment? [IF] .( Gforth version ) TYPE
8336: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8337:
8338: \ a program using v*
8339: s" gforth" environment? [IF]
8340: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8341: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8342: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8343: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8344: LOOP
8345: 2drop 2drop ;
8346: [THEN]
8347: [ELSE] \
8348: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8349: ...
8350: [THEN]
1.26 crook 8351: @end example
1.21 crook 8352:
1.26 crook 8353: Here is an example of adding a definition to the environment word list:
1.21 crook 8354:
1.26 crook 8355: @example
8356: get-current environment-wordlist set-current
8357: true constant block
8358: true constant block-ext
8359: set-current
8360: @end example
1.21 crook 8361:
1.26 crook 8362: You can see what definitions are in the environment word list like this:
1.21 crook 8363:
1.26 crook 8364: @example
1.79 anton 8365: environment-wordlist >order words previous
1.26 crook 8366: @end example
1.21 crook 8367:
8368:
1.26 crook 8369: @c -------------------------------------------------------------
8370: @node Files, Blocks, Environmental Queries, Words
8371: @section Files
1.28 crook 8372: @cindex files
8373: @cindex I/O - file-handling
1.21 crook 8374:
1.26 crook 8375: Gforth provides facilities for accessing files that are stored in the
8376: host operating system's file-system. Files that are processed by Gforth
8377: can be divided into two categories:
1.21 crook 8378:
1.23 crook 8379: @itemize @bullet
8380: @item
1.29 crook 8381: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8382: @item
1.29 crook 8383: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8384: @end itemize
8385:
8386: @menu
1.48 anton 8387: * Forth source files::
8388: * General files::
1.167 anton 8389: * Redirection::
1.48 anton 8390: * Search Paths::
1.26 crook 8391: @end menu
8392:
8393: @c -------------------------------------------------------------
8394: @node Forth source files, General files, Files, Files
8395: @subsection Forth source files
8396: @cindex including files
8397: @cindex Forth source files
1.21 crook 8398:
1.26 crook 8399: The simplest way to interpret the contents of a file is to use one of
8400: these two formats:
1.21 crook 8401:
1.26 crook 8402: @example
8403: include mysource.fs
8404: s" mysource.fs" included
8405: @end example
1.21 crook 8406:
1.75 anton 8407: You usually want to include a file only if it is not included already
1.26 crook 8408: (by, say, another source file). In that case, you can use one of these
1.45 crook 8409: three formats:
1.21 crook 8410:
1.26 crook 8411: @example
8412: require mysource.fs
8413: needs mysource.fs
8414: s" mysource.fs" required
8415: @end example
1.21 crook 8416:
1.26 crook 8417: @cindex stack effect of included files
8418: @cindex including files, stack effect
1.45 crook 8419: It is good practice to write your source files such that interpreting them
8420: does not change the stack. Source files designed in this way can be used with
1.26 crook 8421: @code{required} and friends without complications. For example:
1.21 crook 8422:
1.26 crook 8423: @example
1.75 anton 8424: 1024 require foo.fs drop
1.26 crook 8425: @end example
1.21 crook 8426:
1.75 anton 8427: Here you want to pass the argument 1024 (e.g., a buffer size) to
8428: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8429: ), which allows its use with @code{require}. Of course with such
8430: parameters to required files, you have to ensure that the first
8431: @code{require} fits for all uses (i.e., @code{require} it early in the
8432: master load file).
1.44 crook 8433:
1.26 crook 8434: doc-include-file
8435: doc-included
1.28 crook 8436: doc-included?
1.26 crook 8437: doc-include
8438: doc-required
8439: doc-require
8440: doc-needs
1.75 anton 8441: @c doc-init-included-files @c internal
8442: doc-sourcefilename
8443: doc-sourceline#
1.44 crook 8444:
1.26 crook 8445: A definition in ANS Forth for @code{required} is provided in
8446: @file{compat/required.fs}.
1.21 crook 8447:
1.26 crook 8448: @c -------------------------------------------------------------
1.167 anton 8449: @node General files, Redirection, Forth source files, Files
1.26 crook 8450: @subsection General files
8451: @cindex general files
8452: @cindex file-handling
1.21 crook 8453:
1.75 anton 8454: Files are opened/created by name and type. The following file access
8455: methods (FAMs) are recognised:
1.44 crook 8456:
1.75 anton 8457: @cindex fam (file access method)
1.26 crook 8458: doc-r/o
8459: doc-r/w
8460: doc-w/o
8461: doc-bin
1.1 anton 8462:
1.44 crook 8463:
1.26 crook 8464: When a file is opened/created, it returns a file identifier,
1.29 crook 8465: @i{wfileid} that is used for all other file commands. All file
8466: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8467: successful operation and an implementation-defined non-zero value in the
8468: case of an error.
1.21 crook 8469:
1.44 crook 8470:
1.26 crook 8471: doc-open-file
8472: doc-create-file
1.21 crook 8473:
1.26 crook 8474: doc-close-file
8475: doc-delete-file
8476: doc-rename-file
8477: doc-read-file
8478: doc-read-line
1.154 anton 8479: doc-key-file
8480: doc-key?-file
1.26 crook 8481: doc-write-file
8482: doc-write-line
8483: doc-emit-file
8484: doc-flush-file
1.21 crook 8485:
1.26 crook 8486: doc-file-status
8487: doc-file-position
8488: doc-reposition-file
8489: doc-file-size
8490: doc-resize-file
1.21 crook 8491:
1.93 anton 8492: doc-slurp-file
8493: doc-slurp-fid
1.112 anton 8494: doc-stdin
8495: doc-stdout
8496: doc-stderr
1.44 crook 8497:
1.26 crook 8498: @c ---------------------------------------------------------
1.167 anton 8499: @node Redirection, Search Paths, General files, Files
8500: @subsection Redirection
8501: @cindex Redirection
8502: @cindex Input Redirection
8503: @cindex Output Redirection
8504:
8505: You can redirect the output of @code{type} and @code{emit} and all the
8506: words that use them (all output words that don't have an explicit
1.174 anton 8507: target file) to an arbitrary file with the @code{outfile-execute},
8508: used like this:
1.167 anton 8509:
8510: @example
1.174 anton 8511: : some-warning ( n -- )
8512: cr ." warning# " . ;
8513:
1.167 anton 8514: : print-some-warning ( n -- )
1.174 anton 8515: ['] some-warning stderr outfile-execute ;
1.167 anton 8516: @end example
8517:
1.174 anton 8518: After @code{some-warning} is executed, the original output direction
8519: is restored; this construct is safe against exceptions. Similarly,
8520: there is @code{infile-execute} for redirecting the input of @code{key}
8521: and its users (any input word that does not take a file explicitly).
8522:
8523: doc-outfile-execute
8524: doc-infile-execute
1.167 anton 8525:
8526: If you do not want to redirect the input or output to a file, you can
8527: also make use of the fact that @code{key}, @code{emit} and @code{type}
8528: are deferred words (@pxref{Deferred Words}). However, in that case
8529: you have to worry about the restoration and the protection against
8530: exceptions yourself; also, note that for redirecting the output in
8531: this way, you have to redirect both @code{emit} and @code{type}.
8532:
8533: @c ---------------------------------------------------------
8534: @node Search Paths, , Redirection, Files
1.26 crook 8535: @subsection Search Paths
8536: @cindex path for @code{included}
8537: @cindex file search path
8538: @cindex @code{include} search path
8539: @cindex search path for files
1.21 crook 8540:
1.26 crook 8541: If you specify an absolute filename (i.e., a filename starting with
8542: @file{/} or @file{~}, or with @file{:} in the second position (as in
8543: @samp{C:...})) for @code{included} and friends, that file is included
8544: just as you would expect.
1.21 crook 8545:
1.75 anton 8546: If the filename starts with @file{./}, this refers to the directory that
8547: the present file was @code{included} from. This allows files to include
8548: other files relative to their own position (irrespective of the current
8549: working directory or the absolute position). This feature is essential
8550: for libraries consisting of several files, where a file may include
8551: other files from the library. It corresponds to @code{#include "..."}
8552: in C. If the current input source is not a file, @file{.} refers to the
8553: directory of the innermost file being included, or, if there is no file
8554: being included, to the current working directory.
8555:
8556: For relative filenames (not starting with @file{./}), Gforth uses a
8557: search path similar to Forth's search order (@pxref{Word Lists}). It
8558: tries to find the given filename in the directories present in the path,
8559: and includes the first one it finds. There are separate search paths for
8560: Forth source files and general files. If the search path contains the
8561: directory @file{.}, this refers to the directory of the current file, or
8562: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8563:
1.26 crook 8564: Use @file{~+} to refer to the current working directory (as in the
8565: @code{bash}).
1.1 anton 8566:
1.75 anton 8567: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8568:
1.48 anton 8569: @menu
1.75 anton 8570: * Source Search Paths::
1.48 anton 8571: * General Search Paths::
8572: @end menu
8573:
1.26 crook 8574: @c ---------------------------------------------------------
1.75 anton 8575: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8576: @subsubsection Source Search Paths
8577: @cindex search path control, source files
1.5 anton 8578:
1.26 crook 8579: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8580: Gforth}). You can display it and change it using @code{fpath} in
8581: combination with the general path handling words.
1.5 anton 8582:
1.75 anton 8583: doc-fpath
8584: @c the functionality of the following words is easily available through
8585: @c fpath and the general path words. The may go away.
8586: @c doc-.fpath
8587: @c doc-fpath+
8588: @c doc-fpath=
8589: @c doc-open-fpath-file
1.44 crook 8590:
8591: @noindent
1.26 crook 8592: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8593:
1.26 crook 8594: @example
1.75 anton 8595: fpath path= /usr/lib/forth/|./
1.26 crook 8596: require timer.fs
8597: @end example
1.5 anton 8598:
1.75 anton 8599:
1.26 crook 8600: @c ---------------------------------------------------------
1.75 anton 8601: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8602: @subsubsection General Search Paths
1.75 anton 8603: @cindex search path control, source files
1.5 anton 8604:
1.26 crook 8605: Your application may need to search files in several directories, like
8606: @code{included} does. To facilitate this, Gforth allows you to define
8607: and use your own search paths, by providing generic equivalents of the
8608: Forth search path words:
1.5 anton 8609:
1.75 anton 8610: doc-open-path-file
8611: doc-path-allot
8612: doc-clear-path
8613: doc-also-path
1.26 crook 8614: doc-.path
8615: doc-path+
8616: doc-path=
1.5 anton 8617:
1.75 anton 8618: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8619:
1.75 anton 8620: Here's an example of creating an empty search path:
8621: @c
1.26 crook 8622: @example
1.75 anton 8623: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8624: @end example
1.5 anton 8625:
1.26 crook 8626: @c -------------------------------------------------------------
8627: @node Blocks, Other I/O, Files, Words
8628: @section Blocks
1.28 crook 8629: @cindex I/O - blocks
8630: @cindex blocks
8631:
8632: When you run Gforth on a modern desk-top computer, it runs under the
8633: control of an operating system which provides certain services. One of
8634: these services is @var{file services}, which allows Forth source code
8635: and data to be stored in files and read into Gforth (@pxref{Files}).
8636:
8637: Traditionally, Forth has been an important programming language on
8638: systems where it has interfaced directly to the underlying hardware with
8639: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8640: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8641:
8642: A block is a 1024-byte data area, which can be used to hold data or
8643: Forth source code. No structure is imposed on the contents of the
8644: block. A block is identified by its number; blocks are numbered
8645: contiguously from 1 to an implementation-defined maximum.
8646:
8647: A typical system that used blocks but no operating system might use a
8648: single floppy-disk drive for mass storage, with the disks formatted to
8649: provide 256-byte sectors. Blocks would be implemented by assigning the
8650: first four sectors of the disk to block 1, the second four sectors to
8651: block 2 and so on, up to the limit of the capacity of the disk. The disk
8652: would not contain any file system information, just the set of blocks.
8653:
1.29 crook 8654: @cindex blocks file
1.28 crook 8655: On systems that do provide file services, blocks are typically
1.29 crook 8656: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8657: file}. The size of the blocks file will be an exact multiple of 1024
8658: bytes, corresponding to the number of blocks it contains. This is the
8659: mechanism that Gforth uses.
8660:
1.29 crook 8661: @cindex @file{blocks.fb}
1.75 anton 8662: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8663: having specified a blocks file, Gforth defaults to the blocks file
8664: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8665: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8666:
1.29 crook 8667: @cindex block buffers
1.28 crook 8668: When you read and write blocks under program control, Gforth uses a
1.29 crook 8669: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8670: not used when you use @code{load} to interpret the contents of a block.
8671:
1.75 anton 8672: The behaviour of the block buffers is analagous to that of a cache.
8673: Each block buffer has three states:
1.28 crook 8674:
8675: @itemize @bullet
8676: @item
8677: Unassigned
8678: @item
8679: Assigned-clean
8680: @item
8681: Assigned-dirty
8682: @end itemize
8683:
1.29 crook 8684: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8685: block, the block (specified by its block number) must be assigned to a
8686: block buffer.
8687:
8688: The assignment of a block to a block buffer is performed by @code{block}
8689: or @code{buffer}. Use @code{block} when you wish to modify the existing
8690: contents of a block. Use @code{buffer} when you don't care about the
8691: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8692: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8693: with the particular block is already stored in a block buffer due to an
8694: earlier @code{block} command, @code{buffer} will return that block
8695: buffer and the existing contents of the block will be
8696: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8697: block buffer for the block.}.
1.28 crook 8698:
1.47 crook 8699: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8700: @code{buffer}, that block buffer becomes the @i{current block
8701: buffer}. Data may only be manipulated (read or written) within the
8702: current block buffer.
1.47 crook 8703:
8704: When the contents of the current block buffer has been modified it is
1.48 anton 8705: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8706: either abandon the changes (by doing nothing) or mark the block as
8707: changed (assigned-dirty), using @code{update}. Using @code{update} does
8708: not change the blocks file; it simply changes a block buffer's state to
8709: @i{assigned-dirty}. The block will be written implicitly when it's
8710: buffer is needed for another block, or explicitly by @code{flush} or
8711: @code{save-buffers}.
8712:
8713: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8714: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8715: @code{flush}.
1.28 crook 8716:
1.29 crook 8717: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8718: algorithm to assign a block buffer to a block. That means that any
8719: particular block can only be assigned to one specific block buffer,
1.29 crook 8720: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8721: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8722: the new block immediately. If it is @i{assigned-dirty} its current
8723: contents are written back to the blocks file on disk before it is
1.28 crook 8724: allocated to the new block.
8725:
8726: Although no structure is imposed on the contents of a block, it is
8727: traditional to display the contents as 16 lines each of 64 characters. A
8728: block provides a single, continuous stream of input (for example, it
8729: acts as a single parse area) -- there are no end-of-line characters
8730: within a block, and no end-of-file character at the end of a
8731: block. There are two consequences of this:
1.26 crook 8732:
1.28 crook 8733: @itemize @bullet
8734: @item
8735: The last character of one line wraps straight into the first character
8736: of the following line
8737: @item
8738: The word @code{\} -- comment to end of line -- requires special
8739: treatment; in the context of a block it causes all characters until the
8740: end of the current 64-character ``line'' to be ignored.
8741: @end itemize
8742:
8743: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8744: the current blocks file will be extended to the appropriate size and the
1.28 crook 8745: block buffer will be initialised with spaces.
8746:
1.47 crook 8747: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8748: for details) but doesn't encourage the use of blocks; the mechanism is
8749: only provided for backward compatibility -- ANS Forth requires blocks to
8750: be available when files are.
1.28 crook 8751:
8752: Common techniques that are used when working with blocks include:
8753:
8754: @itemize @bullet
8755: @item
8756: A screen editor that allows you to edit blocks without leaving the Forth
8757: environment.
8758: @item
8759: Shadow screens; where every code block has an associated block
8760: containing comments (for example: code in odd block numbers, comments in
8761: even block numbers). Typically, the block editor provides a convenient
8762: mechanism to toggle between code and comments.
8763: @item
8764: Load blocks; a single block (typically block 1) contains a number of
8765: @code{thru} commands which @code{load} the whole of the application.
8766: @end itemize
1.26 crook 8767:
1.29 crook 8768: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8769: integrated into a Forth programming environment.
1.26 crook 8770:
8771: @comment TODO what about errors on open-blocks?
1.44 crook 8772:
1.26 crook 8773: doc-open-blocks
8774: doc-use
1.75 anton 8775: doc-block-offset
1.26 crook 8776: doc-get-block-fid
8777: doc-block-position
1.28 crook 8778:
1.75 anton 8779: doc-list
1.28 crook 8780: doc-scr
8781:
1.184 anton 8782: doc-block
1.28 crook 8783: doc-buffer
8784:
1.75 anton 8785: doc-empty-buffers
8786: doc-empty-buffer
1.26 crook 8787: doc-update
1.28 crook 8788: doc-updated?
1.26 crook 8789: doc-save-buffers
1.75 anton 8790: doc-save-buffer
1.26 crook 8791: doc-flush
1.28 crook 8792:
1.26 crook 8793: doc-load
8794: doc-thru
8795: doc-+load
8796: doc-+thru
1.45 crook 8797: doc---gforthman--->
1.26 crook 8798: doc-block-included
8799:
1.44 crook 8800:
1.26 crook 8801: @c -------------------------------------------------------------
1.126 pazsan 8802: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8803: @section Other I/O
1.28 crook 8804: @cindex I/O - keyboard and display
1.26 crook 8805:
8806: @menu
8807: * Simple numeric output:: Predefined formats
8808: * Formatted numeric output:: Formatted (pictured) output
8809: * String Formats:: How Forth stores strings in memory
1.67 anton 8810: * Displaying characters and strings:: Other stuff
1.175 anton 8811: * Terminal output:: Cursor positioning etc.
1.181 anton 8812: * Single-key input::
8813: * Line input and conversion::
1.112 anton 8814: * Pipes:: How to create your own pipes
1.149 pazsan 8815: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8816: @end menu
8817:
8818: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8819: @subsection Simple numeric output
1.28 crook 8820: @cindex numeric output - simple/free-format
1.5 anton 8821:
1.26 crook 8822: The simplest output functions are those that display numbers from the
8823: data or floating-point stacks. Floating-point output is always displayed
8824: using base 10. Numbers displayed from the data stack use the value stored
8825: in @code{base}.
1.5 anton 8826:
1.44 crook 8827:
1.26 crook 8828: doc-.
8829: doc-dec.
8830: doc-hex.
8831: doc-u.
8832: doc-.r
8833: doc-u.r
8834: doc-d.
8835: doc-ud.
8836: doc-d.r
8837: doc-ud.r
8838: doc-f.
8839: doc-fe.
8840: doc-fs.
1.111 anton 8841: doc-f.rdp
1.44 crook 8842:
1.26 crook 8843: Examples of printing the number 1234.5678E23 in the different floating-point output
8844: formats are shown below:
1.5 anton 8845:
8846: @example
1.26 crook 8847: f. 123456779999999000000000000.
8848: fe. 123.456779999999E24
8849: fs. 1.23456779999999E26
1.5 anton 8850: @end example
8851:
8852:
1.26 crook 8853: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8854: @subsection Formatted numeric output
1.28 crook 8855: @cindex formatted numeric output
1.26 crook 8856: @cindex pictured numeric output
1.28 crook 8857: @cindex numeric output - formatted
1.26 crook 8858:
1.29 crook 8859: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8860: output} for formatted printing of integers. In this technique, digits
8861: are extracted from the number (using the current output radix defined by
8862: @code{base}), converted to ASCII codes and appended to a string that is
8863: built in a scratch-pad area of memory (@pxref{core-idef,
8864: Implementation-defined options, Implementation-defined
8865: options}). Arbitrary characters can be appended to the string during the
8866: extraction process. The completed string is specified by an address
8867: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8868: under program control.
1.5 anton 8869:
1.75 anton 8870: All of the integer output words described in the previous section
8871: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8872: numeric output.
1.5 anton 8873:
1.47 crook 8874: Three important things to remember about pictured numeric output:
1.5 anton 8875:
1.26 crook 8876: @itemize @bullet
8877: @item
1.28 crook 8878: It always operates on double-precision numbers; to display a
1.49 anton 8879: single-precision number, convert it first (for ways of doing this
8880: @pxref{Double precision}).
1.26 crook 8881: @item
1.28 crook 8882: It always treats the double-precision number as though it were
8883: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8884: @item
8885: The string is built up from right to left; least significant digit first.
8886: @end itemize
1.5 anton 8887:
1.44 crook 8888:
1.26 crook 8889: doc-<#
1.47 crook 8890: doc-<<#
1.26 crook 8891: doc-#
8892: doc-#s
8893: doc-hold
8894: doc-sign
8895: doc-#>
1.47 crook 8896: doc-#>>
1.5 anton 8897:
1.26 crook 8898: doc-represent
1.111 anton 8899: doc-f>str-rdp
8900: doc-f>buf-rdp
1.5 anton 8901:
1.44 crook 8902:
8903: @noindent
1.26 crook 8904: Here are some examples of using pictured numeric output:
1.5 anton 8905:
8906: @example
1.26 crook 8907: : my-u. ( u -- )
8908: \ Simplest use of pns.. behaves like Standard u.
8909: 0 \ convert to unsigned double
1.75 anton 8910: <<# \ start conversion
1.26 crook 8911: #s \ convert all digits
8912: #> \ complete conversion
1.75 anton 8913: TYPE SPACE \ display, with trailing space
8914: #>> ; \ release hold area
1.5 anton 8915:
1.26 crook 8916: : cents-only ( u -- )
8917: 0 \ convert to unsigned double
1.75 anton 8918: <<# \ start conversion
1.26 crook 8919: # # \ convert two least-significant digits
8920: #> \ complete conversion, discard other digits
1.75 anton 8921: TYPE SPACE \ display, with trailing space
8922: #>> ; \ release hold area
1.5 anton 8923:
1.26 crook 8924: : dollars-and-cents ( u -- )
8925: 0 \ convert to unsigned double
1.75 anton 8926: <<# \ start conversion
1.26 crook 8927: # # \ convert two least-significant digits
8928: [char] . hold \ insert decimal point
8929: #s \ convert remaining digits
8930: [char] $ hold \ append currency symbol
8931: #> \ complete conversion
1.75 anton 8932: TYPE SPACE \ display, with trailing space
8933: #>> ; \ release hold area
1.5 anton 8934:
1.26 crook 8935: : my-. ( n -- )
8936: \ handling negatives.. behaves like Standard .
8937: s>d \ convert to signed double
8938: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8939: <<# \ start conversion
1.26 crook 8940: #s \ convert all digits
8941: rot sign \ get at sign byte, append "-" if needed
8942: #> \ complete conversion
1.75 anton 8943: TYPE SPACE \ display, with trailing space
8944: #>> ; \ release hold area
1.5 anton 8945:
1.26 crook 8946: : account. ( n -- )
1.75 anton 8947: \ accountants don't like minus signs, they use parentheses
1.26 crook 8948: \ for negative numbers
8949: s>d \ convert to signed double
8950: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8951: <<# \ start conversion
1.26 crook 8952: 2 pick \ get copy of sign byte
8953: 0< IF [char] ) hold THEN \ right-most character of output
8954: #s \ convert all digits
8955: rot \ get at sign byte
8956: 0< IF [char] ( hold THEN
8957: #> \ complete conversion
1.75 anton 8958: TYPE SPACE \ display, with trailing space
8959: #>> ; \ release hold area
8960:
1.5 anton 8961: @end example
8962:
1.26 crook 8963: Here are some examples of using these words:
1.5 anton 8964:
8965: @example
1.26 crook 8966: 1 my-u. 1
8967: hex -1 my-u. decimal FFFFFFFF
8968: 1 cents-only 01
8969: 1234 cents-only 34
8970: 2 dollars-and-cents $0.02
8971: 1234 dollars-and-cents $12.34
8972: 123 my-. 123
8973: -123 my. -123
8974: 123 account. 123
8975: -456 account. (456)
1.5 anton 8976: @end example
8977:
8978:
1.26 crook 8979: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8980: @subsection String Formats
1.27 crook 8981: @cindex strings - see character strings
8982: @cindex character strings - formats
1.28 crook 8983: @cindex I/O - see character strings
1.75 anton 8984: @cindex counted strings
8985:
8986: @c anton: this does not really belong here; maybe the memory section,
8987: @c or the principles chapter
1.26 crook 8988:
1.27 crook 8989: Forth commonly uses two different methods for representing character
8990: strings:
1.26 crook 8991:
8992: @itemize @bullet
8993: @item
8994: @cindex address of counted string
1.45 crook 8995: @cindex counted string
1.29 crook 8996: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8997: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8998: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 8999: memory.
9000: @item
1.29 crook 9001: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9002: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9003: first byte of the string.
9004: @end itemize
9005:
9006: ANS Forth encourages the use of the second format when representing
1.75 anton 9007: strings.
1.26 crook 9008:
1.44 crook 9009:
1.26 crook 9010: doc-count
9011:
1.44 crook 9012:
1.49 anton 9013: For words that move, copy and search for strings see @ref{Memory
9014: Blocks}. For words that display characters and strings see
9015: @ref{Displaying characters and strings}.
1.26 crook 9016:
1.175 anton 9017: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9018: @subsection Displaying characters and strings
1.27 crook 9019: @cindex characters - compiling and displaying
9020: @cindex character strings - compiling and displaying
1.26 crook 9021:
9022: This section starts with a glossary of Forth words and ends with a set
9023: of examples.
9024:
9025: doc-bl
9026: doc-space
9027: doc-spaces
9028: doc-emit
9029: doc-toupper
9030: doc-."
9031: doc-.(
1.98 anton 9032: doc-.\"
1.26 crook 9033: doc-type
1.44 crook 9034: doc-typewhite
1.26 crook 9035: doc-cr
1.27 crook 9036: @cindex cursor control
1.26 crook 9037: doc-s"
1.98 anton 9038: doc-s\"
1.26 crook 9039: doc-c"
9040: doc-char
9041: doc-[char]
9042:
1.44 crook 9043:
9044: @noindent
1.26 crook 9045: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9046:
9047: @example
1.26 crook 9048: .( text-1)
9049: : my-word
9050: ." text-2" cr
9051: .( text-3)
9052: ;
9053:
9054: ." text-4"
9055:
9056: : my-char
9057: [char] ALPHABET emit
9058: char emit
9059: ;
1.5 anton 9060: @end example
9061:
1.26 crook 9062: When you load this code into Gforth, the following output is generated:
1.5 anton 9063:
1.26 crook 9064: @example
1.30 anton 9065: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9066: @end example
1.5 anton 9067:
1.26 crook 9068: @itemize @bullet
9069: @item
9070: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9071: is an immediate word; it behaves in the same way whether it is used inside
9072: or outside a colon definition.
9073: @item
9074: Message @code{text-4} is displayed because of Gforth's added interpretation
9075: semantics for @code{."}.
9076: @item
1.29 crook 9077: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9078: performs the compilation semantics for @code{."} within the definition of
9079: @code{my-word}.
9080: @end itemize
1.5 anton 9081:
1.26 crook 9082: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9083:
1.26 crook 9084: @example
1.30 anton 9085: @kbd{my-word @key{RET}} text-2
1.26 crook 9086: ok
1.30 anton 9087: @kbd{my-char fred @key{RET}} Af ok
9088: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9089: @end example
1.5 anton 9090:
9091: @itemize @bullet
9092: @item
1.26 crook 9093: Message @code{text-2} is displayed because of the run-time behaviour of
9094: @code{."}.
9095: @item
9096: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9097: on the stack at run-time. @code{emit} always displays the character
9098: when @code{my-char} is executed.
9099: @item
9100: @code{char} parses a string at run-time and the second @code{emit} displays
9101: the first character of the string.
1.5 anton 9102: @item
1.26 crook 9103: If you type @code{see my-char} you can see that @code{[char]} discarded
9104: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9105: definition of @code{my-char}.
1.5 anton 9106: @end itemize
9107:
9108:
1.181 anton 9109: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9110: @subsection Terminal output
9111: @cindex output to terminal
9112: @cindex terminal output
9113:
9114: If you are outputting to a terminal, you may want to control the
9115: positioning of the cursor:
9116: @cindex cursor positioning
9117:
9118: doc-at-xy
9119:
9120: In order to know where to position the cursor, it is often helpful to
9121: know the size of the screen:
9122: @cindex terminal size
9123:
9124: doc-form
9125:
9126: And sometimes you want to use:
9127: @cindex clear screen
9128:
9129: doc-page
9130:
9131: Note that on non-terminals you should use @code{12 emit}, not
9132: @code{page}, to get a form feed.
9133:
1.5 anton 9134:
1.181 anton 9135: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9136: @subsection Single-key input
9137: @cindex single-key input
9138: @cindex input, single-key
9139:
9140: If you want to get a single printable character, you can use
9141: @code{key}; to check whether a character is available for @code{key},
9142: you can use @code{key?}.
1.5 anton 9143:
1.181 anton 9144: doc-key
9145: doc-key?
1.27 crook 9146:
1.181 anton 9147: If you want to process a mix of printable and non-printable
9148: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9149: produces a keyboard event that you have to convert into a character
9150: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9151:
9152: Typical code for using EKEY looks like this:
9153:
9154: @example
9155: ekey ekey>char if ( c )
9156: ... \ do something with the character
9157: else ekey>fkey if ( key-id )
9158: case
9159: k-up of ... endof
9160: k-f1 of ... endof
9161: k-left k-shift-mask or k-ctrl-mask or of ... endof
9162: ...
9163: endcase
9164: else ( keyboard-event )
9165: drop \ just ignore an unknown keyboard event type
9166: then then
9167: @end example
1.44 crook 9168:
1.45 crook 9169: doc-ekey
1.141 anton 9170: doc-ekey>char
1.181 anton 9171: doc-ekey>fkey
1.45 crook 9172: doc-ekey?
1.141 anton 9173:
1.181 anton 9174: The key identifiers for cursor keys are:
1.141 anton 9175:
9176: doc-k-left
9177: doc-k-right
1.185 anton 9178: doc-k-up
9179: doc-k-down
9180: doc-k-home
9181: doc-k-end
1.141 anton 9182: doc-k-prior
9183: doc-k-next
9184: doc-k-insert
9185: doc-k-delete
9186:
1.181 anton 9187: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9188:
1.181 anton 9189: doc-k-f1
9190: doc-k-f2
9191: doc-k-f3
9192: doc-k-f4
9193: doc-k-f5
9194: doc-k-f6
9195: doc-k-f7
9196: doc-k-f8
9197: doc-k-f9
9198: doc-k-f10
9199: doc-k-f11
9200: doc-k-f12
9201:
9202: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9203:
9204: You can combine these key identifiers with masks for various shift keys:
9205:
9206: doc-k-shift-mask
9207: doc-k-ctrl-mask
9208: doc-k-alt-mask
9209:
9210: Note that, even if a Forth system has @code{ekey>fkey} and the key
9211: identifier words, the keys are not necessarily available or it may not
9212: necessarily be able to report all the keys and all the possible
9213: combinations with shift masks. Therefore, write your programs in such
9214: a way that they are still useful even if the keys and key combinations
9215: cannot be pressed or are not recognized.
9216:
9217: Examples: Older keyboards often do not have an F11 and F12 key. If
9218: you run Gforth in an xterm, the xterm catches a number of combinations
9219: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9220: Gforth currently does not recognize and report combinations with
9221: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9222: above would never be entered).
9223:
9224: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9225: you need the ANSI.SYS driver to get that behaviour); it works by
9226: recognizing the escape sequences that ANSI terminals send when such a
9227: key is pressed. If you have a terminal that sends other escape
9228: sequences, you will not get useful results on Gforth. Other Forth
9229: systems may work in a different way.
9230:
9231:
9232: @node Line input and conversion, Pipes, Single-key input, Other I/O
9233: @subsection Line input and conversion
9234: @cindex line input from terminal
9235: @cindex input, linewise from terminal
9236: @cindex convertin strings to numbers
9237: @cindex I/O - see input
9238:
9239: For ways of storing character strings in memory see @ref{String Formats}.
9240:
9241: @comment TODO examples for >number >float accept key key? pad parse word refill
9242: @comment then index them
1.141 anton 9243:
9244: Words for inputting one line from the keyboard:
9245:
9246: doc-accept
9247: doc-edit-line
9248:
9249: Conversion words:
9250:
1.143 anton 9251: doc-s>number?
9252: doc-s>unumber?
1.26 crook 9253: doc->number
9254: doc->float
1.143 anton 9255:
1.141 anton 9256:
1.27 crook 9257: @comment obsolescent words..
1.141 anton 9258: Obsolescent input and conversion words:
9259:
1.27 crook 9260: doc-convert
1.26 crook 9261: doc-expect
1.27 crook 9262: doc-span
1.5 anton 9263:
9264:
1.181 anton 9265: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9266: @subsection Pipes
9267: @cindex pipes, creating your own
9268:
9269: In addition to using Gforth in pipes created by other processes
9270: (@pxref{Gforth in pipes}), you can create your own pipe with
9271: @code{open-pipe}, and read from or write to it.
9272:
9273: doc-open-pipe
9274: doc-close-pipe
9275:
9276: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9277: you don't catch this exception, Gforth will catch it and exit, usually
9278: silently (@pxref{Gforth in pipes}). Since you probably do not want
9279: this, you should wrap a @code{catch} or @code{try} block around the code
9280: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9281: problem yourself, and then return to regular processing.
9282:
9283: doc-broken-pipe-error
9284:
1.155 anton 9285: @node Xchars and Unicode, , Pipes, Other I/O
9286: @subsection Xchars and Unicode
1.149 pazsan 9287:
1.188 pazsan 9288: ASCII is only appropriate for the English language. Most western
9289: languages however fit somewhat into the Forth frame, since a byte is
9290: sufficient to encode the few special characters in each (though not
9291: always the same encoding can be used; latin-1 is most widely used,
9292: though). For other languages, different char-sets have to be used,
9293: several of them variable-width. Most prominent representant is
9294: UTF-8. Let's call these extended characters xchars. The primitive
9295: fixed-size characters stored as bytes are called pchars in this
9296: section.
9297:
9298: The xchar words add a few data types:
9299:
9300: @itemize
9301:
9302: @item
9303: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9304: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9305: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9306: character set can be used.
9307:
9308: @item
9309: @var{xc-addr} is the address of an xchar in memory. Alignment
9310: requirements are the same as @var{c-addr}. The memory representation of an
9311: xchar differs from the stack representation, and depends on the
9312: encoding used. An xchar may use a variable number of pchars in memory.
9313:
9314: @item
9315: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9316: @var{xc-addr}, @var{u} pchars long.
9317:
9318: @end itemize
9319:
9320: doc-xc-size
9321: doc-x-size
9322: doc-xc@+
9323: doc-xc!+
9324: doc-xc!+?
9325: doc-xchar+
9326: doc-xchar-
9327: doc-+x/string
9328: doc-x\string-
9329: doc--trailing-garbage
9330: doc-x-width
9331: doc-xkey
9332: doc-xemit
9333:
9334: There's a new environment query
9335:
9336: doc-xchar-encoding
1.112 anton 9337:
1.121 anton 9338: @node OS command line arguments, Locals, Other I/O, Words
9339: @section OS command line arguments
9340: @cindex OS command line arguments
9341: @cindex command line arguments, OS
9342: @cindex arguments, OS command line
9343:
9344: The usual way to pass arguments to Gforth programs on the command line
9345: is via the @option{-e} option, e.g.
9346:
9347: @example
9348: gforth -e "123 456" foo.fs -e bye
9349: @end example
9350:
9351: However, you may want to interpret the command-line arguments directly.
9352: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9353: through @code{next-arg}:
1.121 anton 9354:
1.123 anton 9355: doc-next-arg
1.121 anton 9356:
1.123 anton 9357: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9358:
9359: @example
9360: : echo ( -- )
1.122 anton 9361: begin
1.123 anton 9362: next-arg 2dup 0 0 d<> while
9363: type space
9364: repeat
9365: 2drop ;
1.121 anton 9366:
9367: echo cr bye
9368: @end example
9369:
9370: This can be invoked with
9371:
9372: @example
9373: gforth echo.fs hello world
9374: @end example
1.123 anton 9375:
9376: and it will print
9377:
9378: @example
9379: hello world
9380: @end example
9381:
9382: The next lower level of dealing with the OS command line are the
9383: following words:
9384:
9385: doc-arg
9386: doc-shift-args
9387:
9388: Finally, at the lowest level Gforth provides the following words:
9389:
9390: doc-argc
9391: doc-argv
1.121 anton 9392:
1.78 anton 9393: @c -------------------------------------------------------------
1.126 pazsan 9394: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9395: @section Locals
9396: @cindex locals
9397:
9398: Local variables can make Forth programming more enjoyable and Forth
9399: programs easier to read. Unfortunately, the locals of ANS Forth are
9400: laden with restrictions. Therefore, we provide not only the ANS Forth
9401: locals wordset, but also our own, more powerful locals wordset (we
9402: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9403:
1.78 anton 9404: The ideas in this section have also been published in M. Anton Ertl,
9405: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9406: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9407:
9408: @menu
1.78 anton 9409: * Gforth locals::
9410: * ANS Forth locals::
1.5 anton 9411: @end menu
9412:
1.78 anton 9413: @node Gforth locals, ANS Forth locals, Locals, Locals
9414: @subsection Gforth locals
9415: @cindex Gforth locals
9416: @cindex locals, Gforth style
1.5 anton 9417:
1.78 anton 9418: Locals can be defined with
1.44 crook 9419:
1.78 anton 9420: @example
9421: @{ local1 local2 ... -- comment @}
9422: @end example
9423: or
9424: @example
9425: @{ local1 local2 ... @}
9426: @end example
1.5 anton 9427:
1.78 anton 9428: E.g.,
9429: @example
9430: : max @{ n1 n2 -- n3 @}
9431: n1 n2 > if
9432: n1
9433: else
9434: n2
9435: endif ;
9436: @end example
1.44 crook 9437:
1.78 anton 9438: The similarity of locals definitions with stack comments is intended. A
9439: locals definition often replaces the stack comment of a word. The order
9440: of the locals corresponds to the order in a stack comment and everything
9441: after the @code{--} is really a comment.
1.77 anton 9442:
1.78 anton 9443: This similarity has one disadvantage: It is too easy to confuse locals
9444: declarations with stack comments, causing bugs and making them hard to
9445: find. However, this problem can be avoided by appropriate coding
9446: conventions: Do not use both notations in the same program. If you do,
9447: they should be distinguished using additional means, e.g. by position.
1.77 anton 9448:
1.78 anton 9449: @cindex types of locals
9450: @cindex locals types
9451: The name of the local may be preceded by a type specifier, e.g.,
9452: @code{F:} for a floating point value:
1.5 anton 9453:
1.78 anton 9454: @example
9455: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9456: \ complex multiplication
9457: Ar Br f* Ai Bi f* f-
9458: Ar Bi f* Ai Br f* f+ ;
9459: @end example
1.44 crook 9460:
1.78 anton 9461: @cindex flavours of locals
9462: @cindex locals flavours
9463: @cindex value-flavoured locals
9464: @cindex variable-flavoured locals
9465: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9466: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9467: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9468: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9469: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9470: produces its address (which becomes invalid when the variable's scope is
9471: left). E.g., the standard word @code{emit} can be defined in terms of
9472: @code{type} like this:
1.5 anton 9473:
1.78 anton 9474: @example
9475: : emit @{ C^ char* -- @}
9476: char* 1 type ;
9477: @end example
1.5 anton 9478:
1.78 anton 9479: @cindex default type of locals
9480: @cindex locals, default type
9481: A local without type specifier is a @code{W:} local. Both flavours of
9482: locals are initialized with values from the data or FP stack.
1.44 crook 9483:
1.78 anton 9484: Currently there is no way to define locals with user-defined data
9485: structures, but we are working on it.
1.5 anton 9486:
1.78 anton 9487: Gforth allows defining locals everywhere in a colon definition. This
9488: poses the following questions:
1.5 anton 9489:
1.78 anton 9490: @menu
9491: * Where are locals visible by name?::
9492: * How long do locals live?::
9493: * Locals programming style::
9494: * Locals implementation::
9495: @end menu
1.44 crook 9496:
1.78 anton 9497: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9498: @subsubsection Where are locals visible by name?
9499: @cindex locals visibility
9500: @cindex visibility of locals
9501: @cindex scope of locals
1.5 anton 9502:
1.78 anton 9503: Basically, the answer is that locals are visible where you would expect
9504: it in block-structured languages, and sometimes a little longer. If you
9505: want to restrict the scope of a local, enclose its definition in
9506: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9507:
9508:
1.78 anton 9509: doc-scope
9510: doc-endscope
1.5 anton 9511:
9512:
1.78 anton 9513: These words behave like control structure words, so you can use them
9514: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9515: arbitrary ways.
1.77 anton 9516:
1.78 anton 9517: If you want a more exact answer to the visibility question, here's the
9518: basic principle: A local is visible in all places that can only be
9519: reached through the definition of the local@footnote{In compiler
9520: construction terminology, all places dominated by the definition of the
9521: local.}. In other words, it is not visible in places that can be reached
9522: without going through the definition of the local. E.g., locals defined
9523: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9524: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9525: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9526:
1.78 anton 9527: The reasoning behind this solution is: We want to have the locals
9528: visible as long as it is meaningful. The user can always make the
9529: visibility shorter by using explicit scoping. In a place that can
9530: only be reached through the definition of a local, the meaning of a
9531: local name is clear. In other places it is not: How is the local
9532: initialized at the control flow path that does not contain the
9533: definition? Which local is meant, if the same name is defined twice in
9534: two independent control flow paths?
1.77 anton 9535:
1.78 anton 9536: This should be enough detail for nearly all users, so you can skip the
9537: rest of this section. If you really must know all the gory details and
9538: options, read on.
1.77 anton 9539:
1.78 anton 9540: In order to implement this rule, the compiler has to know which places
9541: are unreachable. It knows this automatically after @code{AHEAD},
9542: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9543: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9544: compiler that the control flow never reaches that place. If
9545: @code{UNREACHABLE} is not used where it could, the only consequence is
9546: that the visibility of some locals is more limited than the rule above
9547: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9548: lie to the compiler), buggy code will be produced.
1.77 anton 9549:
1.5 anton 9550:
1.78 anton 9551: doc-unreachable
1.5 anton 9552:
1.23 crook 9553:
1.78 anton 9554: Another problem with this rule is that at @code{BEGIN}, the compiler
9555: does not know which locals will be visible on the incoming
9556: back-edge. All problems discussed in the following are due to this
9557: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9558: loops as examples; the discussion also applies to @code{?DO} and other
9559: loops). Perhaps the most insidious example is:
1.26 crook 9560: @example
1.78 anton 9561: AHEAD
9562: BEGIN
9563: x
9564: [ 1 CS-ROLL ] THEN
9565: @{ x @}
9566: ...
9567: UNTIL
1.26 crook 9568: @end example
1.23 crook 9569:
1.78 anton 9570: This should be legal according to the visibility rule. The use of
9571: @code{x} can only be reached through the definition; but that appears
9572: textually below the use.
9573:
9574: From this example it is clear that the visibility rules cannot be fully
9575: implemented without major headaches. Our implementation treats common
9576: cases as advertised and the exceptions are treated in a safe way: The
9577: compiler makes a reasonable guess about the locals visible after a
9578: @code{BEGIN}; if it is too pessimistic, the
9579: user will get a spurious error about the local not being defined; if the
9580: compiler is too optimistic, it will notice this later and issue a
9581: warning. In the case above the compiler would complain about @code{x}
9582: being undefined at its use. You can see from the obscure examples in
9583: this section that it takes quite unusual control structures to get the
9584: compiler into trouble, and even then it will often do fine.
1.23 crook 9585:
1.78 anton 9586: If the @code{BEGIN} is reachable from above, the most optimistic guess
9587: is that all locals visible before the @code{BEGIN} will also be
9588: visible after the @code{BEGIN}. This guess is valid for all loops that
9589: are entered only through the @code{BEGIN}, in particular, for normal
9590: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9591: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9592: compiler. When the branch to the @code{BEGIN} is finally generated by
9593: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9594: warns the user if it was too optimistic:
1.26 crook 9595: @example
1.78 anton 9596: IF
9597: @{ x @}
9598: BEGIN
9599: \ x ?
9600: [ 1 cs-roll ] THEN
9601: ...
9602: UNTIL
1.26 crook 9603: @end example
1.23 crook 9604:
1.78 anton 9605: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9606: optimistically assumes that it lives until the @code{THEN}. It notices
9607: this difference when it compiles the @code{UNTIL} and issues a
9608: warning. The user can avoid the warning, and make sure that @code{x}
9609: is not used in the wrong area by using explicit scoping:
9610: @example
9611: IF
9612: SCOPE
9613: @{ x @}
9614: ENDSCOPE
9615: BEGIN
9616: [ 1 cs-roll ] THEN
9617: ...
9618: UNTIL
9619: @end example
1.23 crook 9620:
1.78 anton 9621: Since the guess is optimistic, there will be no spurious error messages
9622: about undefined locals.
1.44 crook 9623:
1.78 anton 9624: If the @code{BEGIN} is not reachable from above (e.g., after
9625: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9626: optimistic guess, as the locals visible after the @code{BEGIN} may be
9627: defined later. Therefore, the compiler assumes that no locals are
9628: visible after the @code{BEGIN}. However, the user can use
9629: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9630: visible at the BEGIN as at the point where the top control-flow stack
9631: item was created.
1.23 crook 9632:
1.44 crook 9633:
1.78 anton 9634: doc-assume-live
1.26 crook 9635:
1.23 crook 9636:
1.78 anton 9637: @noindent
9638: E.g.,
9639: @example
9640: @{ x @}
9641: AHEAD
9642: ASSUME-LIVE
9643: BEGIN
9644: x
9645: [ 1 CS-ROLL ] THEN
9646: ...
9647: UNTIL
9648: @end example
1.44 crook 9649:
1.78 anton 9650: Other cases where the locals are defined before the @code{BEGIN} can be
9651: handled by inserting an appropriate @code{CS-ROLL} before the
9652: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9653: behind the @code{ASSUME-LIVE}).
1.23 crook 9654:
1.78 anton 9655: Cases where locals are defined after the @code{BEGIN} (but should be
9656: visible immediately after the @code{BEGIN}) can only be handled by
9657: rearranging the loop. E.g., the ``most insidious'' example above can be
9658: arranged into:
9659: @example
9660: BEGIN
9661: @{ x @}
9662: ... 0=
9663: WHILE
9664: x
9665: REPEAT
9666: @end example
1.44 crook 9667:
1.78 anton 9668: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9669: @subsubsection How long do locals live?
9670: @cindex locals lifetime
9671: @cindex lifetime of locals
1.23 crook 9672:
1.78 anton 9673: The right answer for the lifetime question would be: A local lives at
9674: least as long as it can be accessed. For a value-flavoured local this
9675: means: until the end of its visibility. However, a variable-flavoured
9676: local could be accessed through its address far beyond its visibility
9677: scope. Ultimately, this would mean that such locals would have to be
9678: garbage collected. Since this entails un-Forth-like implementation
9679: complexities, I adopted the same cowardly solution as some other
9680: languages (e.g., C): The local lives only as long as it is visible;
9681: afterwards its address is invalid (and programs that access it
9682: afterwards are erroneous).
1.23 crook 9683:
1.78 anton 9684: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9685: @subsubsection Locals programming style
9686: @cindex locals programming style
9687: @cindex programming style, locals
1.23 crook 9688:
1.78 anton 9689: The freedom to define locals anywhere has the potential to change
9690: programming styles dramatically. In particular, the need to use the
9691: return stack for intermediate storage vanishes. Moreover, all stack
9692: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9693: determined arguments) can be eliminated: If the stack items are in the
9694: wrong order, just write a locals definition for all of them; then
9695: write the items in the order you want.
1.23 crook 9696:
1.78 anton 9697: This seems a little far-fetched and eliminating stack manipulations is
9698: unlikely to become a conscious programming objective. Still, the number
9699: of stack manipulations will be reduced dramatically if local variables
9700: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9701: a traditional implementation of @code{max}).
1.23 crook 9702:
1.78 anton 9703: This shows one potential benefit of locals: making Forth programs more
9704: readable. Of course, this benefit will only be realized if the
9705: programmers continue to honour the principle of factoring instead of
9706: using the added latitude to make the words longer.
1.23 crook 9707:
1.78 anton 9708: @cindex single-assignment style for locals
9709: Using @code{TO} can and should be avoided. Without @code{TO},
9710: every value-flavoured local has only a single assignment and many
9711: advantages of functional languages apply to Forth. I.e., programs are
9712: easier to analyse, to optimize and to read: It is clear from the
9713: definition what the local stands for, it does not turn into something
9714: different later.
1.23 crook 9715:
1.78 anton 9716: E.g., a definition using @code{TO} might look like this:
9717: @example
9718: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9719: u1 u2 min 0
9720: ?do
9721: addr1 c@@ addr2 c@@ -
9722: ?dup-if
9723: unloop exit
9724: then
9725: addr1 char+ TO addr1
9726: addr2 char+ TO addr2
9727: loop
9728: u1 u2 - ;
1.26 crook 9729: @end example
1.78 anton 9730: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9731: every loop iteration. @code{strcmp} is a typical example of the
9732: readability problems of using @code{TO}. When you start reading
9733: @code{strcmp}, you think that @code{addr1} refers to the start of the
9734: string. Only near the end of the loop you realize that it is something
9735: else.
1.23 crook 9736:
1.78 anton 9737: This can be avoided by defining two locals at the start of the loop that
9738: are initialized with the right value for the current iteration.
9739: @example
9740: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9741: addr1 addr2
9742: u1 u2 min 0
9743: ?do @{ s1 s2 @}
9744: s1 c@@ s2 c@@ -
9745: ?dup-if
9746: unloop exit
9747: then
9748: s1 char+ s2 char+
9749: loop
9750: 2drop
9751: u1 u2 - ;
9752: @end example
9753: Here it is clear from the start that @code{s1} has a different value
9754: in every loop iteration.
1.23 crook 9755:
1.78 anton 9756: @node Locals implementation, , Locals programming style, Gforth locals
9757: @subsubsection Locals implementation
9758: @cindex locals implementation
9759: @cindex implementation of locals
1.23 crook 9760:
1.78 anton 9761: @cindex locals stack
9762: Gforth uses an extra locals stack. The most compelling reason for
9763: this is that the return stack is not float-aligned; using an extra stack
9764: also eliminates the problems and restrictions of using the return stack
9765: as locals stack. Like the other stacks, the locals stack grows toward
9766: lower addresses. A few primitives allow an efficient implementation:
9767:
9768:
9769: doc-@local#
9770: doc-f@local#
9771: doc-laddr#
9772: doc-lp+!#
9773: doc-lp!
9774: doc->l
9775: doc-f>l
9776:
9777:
9778: In addition to these primitives, some specializations of these
9779: primitives for commonly occurring inline arguments are provided for
9780: efficiency reasons, e.g., @code{@@local0} as specialization of
9781: @code{@@local#} for the inline argument 0. The following compiling words
9782: compile the right specialized version, or the general version, as
9783: appropriate:
1.23 crook 9784:
1.5 anton 9785:
1.107 dvdkhlng 9786: @c doc-compile-@local
9787: @c doc-compile-f@local
1.78 anton 9788: doc-compile-lp+!
1.5 anton 9789:
9790:
1.78 anton 9791: Combinations of conditional branches and @code{lp+!#} like
9792: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9793: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9794:
1.78 anton 9795: A special area in the dictionary space is reserved for keeping the
9796: local variable names. @code{@{} switches the dictionary pointer to this
9797: area and @code{@}} switches it back and generates the locals
9798: initializing code. @code{W:} etc.@ are normal defining words. This
9799: special area is cleared at the start of every colon definition.
1.5 anton 9800:
1.78 anton 9801: @cindex word list for defining locals
9802: A special feature of Gforth's dictionary is used to implement the
9803: definition of locals without type specifiers: every word list (aka
9804: vocabulary) has its own methods for searching
9805: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9806: with a special search method: When it is searched for a word, it
9807: actually creates that word using @code{W:}. @code{@{} changes the search
9808: order to first search the word list containing @code{@}}, @code{W:} etc.,
9809: and then the word list for defining locals without type specifiers.
1.5 anton 9810:
1.78 anton 9811: The lifetime rules support a stack discipline within a colon
9812: definition: The lifetime of a local is either nested with other locals
9813: lifetimes or it does not overlap them.
1.23 crook 9814:
1.78 anton 9815: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9816: pointer manipulation is generated. Between control structure words
9817: locals definitions can push locals onto the locals stack. @code{AGAIN}
9818: is the simplest of the other three control flow words. It has to
9819: restore the locals stack depth of the corresponding @code{BEGIN}
9820: before branching. The code looks like this:
9821: @format
9822: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9823: @code{branch} <begin>
9824: @end format
1.26 crook 9825:
1.78 anton 9826: @code{UNTIL} is a little more complicated: If it branches back, it
9827: must adjust the stack just like @code{AGAIN}. But if it falls through,
9828: the locals stack must not be changed. The compiler generates the
9829: following code:
9830: @format
9831: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9832: @end format
9833: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9834:
1.78 anton 9835: @code{THEN} can produce somewhat inefficient code:
9836: @format
9837: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9838: <orig target>:
9839: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9840: @end format
9841: The second @code{lp+!#} adjusts the locals stack pointer from the
9842: level at the @i{orig} point to the level after the @code{THEN}. The
9843: first @code{lp+!#} adjusts the locals stack pointer from the current
9844: level to the level at the orig point, so the complete effect is an
9845: adjustment from the current level to the right level after the
9846: @code{THEN}.
1.26 crook 9847:
1.78 anton 9848: @cindex locals information on the control-flow stack
9849: @cindex control-flow stack items, locals information
9850: In a conventional Forth implementation a dest control-flow stack entry
9851: is just the target address and an orig entry is just the address to be
9852: patched. Our locals implementation adds a word list to every orig or dest
9853: item. It is the list of locals visible (or assumed visible) at the point
9854: described by the entry. Our implementation also adds a tag to identify
9855: the kind of entry, in particular to differentiate between live and dead
9856: (reachable and unreachable) orig entries.
1.26 crook 9857:
1.78 anton 9858: A few unusual operations have to be performed on locals word lists:
1.44 crook 9859:
1.5 anton 9860:
1.78 anton 9861: doc-common-list
9862: doc-sub-list?
9863: doc-list-size
1.52 anton 9864:
9865:
1.78 anton 9866: Several features of our locals word list implementation make these
9867: operations easy to implement: The locals word lists are organised as
9868: linked lists; the tails of these lists are shared, if the lists
9869: contain some of the same locals; and the address of a name is greater
9870: than the address of the names behind it in the list.
1.5 anton 9871:
1.78 anton 9872: Another important implementation detail is the variable
9873: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9874: determine if they can be reached directly or only through the branch
9875: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9876: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9877: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9878:
1.78 anton 9879: Counted loops are similar to other loops in most respects, but
9880: @code{LEAVE} requires special attention: It performs basically the same
9881: service as @code{AHEAD}, but it does not create a control-flow stack
9882: entry. Therefore the information has to be stored elsewhere;
9883: traditionally, the information was stored in the target fields of the
9884: branches created by the @code{LEAVE}s, by organizing these fields into a
9885: linked list. Unfortunately, this clever trick does not provide enough
9886: space for storing our extended control flow information. Therefore, we
9887: introduce another stack, the leave stack. It contains the control-flow
9888: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9889:
1.78 anton 9890: Local names are kept until the end of the colon definition, even if
9891: they are no longer visible in any control-flow path. In a few cases
9892: this may lead to increased space needs for the locals name area, but
9893: usually less than reclaiming this space would cost in code size.
1.5 anton 9894:
1.44 crook 9895:
1.78 anton 9896: @node ANS Forth locals, , Gforth locals, Locals
9897: @subsection ANS Forth locals
9898: @cindex locals, ANS Forth style
1.5 anton 9899:
1.78 anton 9900: The ANS Forth locals wordset does not define a syntax for locals, but
9901: words that make it possible to define various syntaxes. One of the
9902: possible syntaxes is a subset of the syntax we used in the Gforth locals
9903: wordset, i.e.:
1.29 crook 9904:
9905: @example
1.78 anton 9906: @{ local1 local2 ... -- comment @}
9907: @end example
9908: @noindent
9909: or
9910: @example
9911: @{ local1 local2 ... @}
1.29 crook 9912: @end example
9913:
1.78 anton 9914: The order of the locals corresponds to the order in a stack comment. The
9915: restrictions are:
1.5 anton 9916:
1.78 anton 9917: @itemize @bullet
9918: @item
9919: Locals can only be cell-sized values (no type specifiers are allowed).
9920: @item
9921: Locals can be defined only outside control structures.
9922: @item
9923: Locals can interfere with explicit usage of the return stack. For the
9924: exact (and long) rules, see the standard. If you don't use return stack
9925: accessing words in a definition using locals, you will be all right. The
9926: purpose of this rule is to make locals implementation on the return
9927: stack easier.
9928: @item
9929: The whole definition must be in one line.
9930: @end itemize
1.5 anton 9931:
1.78 anton 9932: Locals defined in ANS Forth behave like @code{VALUE}s
9933: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9934: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9935:
1.78 anton 9936: Since the syntax above is supported by Gforth directly, you need not do
9937: anything to use it. If you want to port a program using this syntax to
9938: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9939: syntax on the other system.
1.5 anton 9940:
1.78 anton 9941: Note that a syntax shown in the standard, section A.13 looks
9942: similar, but is quite different in having the order of locals
9943: reversed. Beware!
1.5 anton 9944:
1.78 anton 9945: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9946:
1.78 anton 9947: doc-(local)
1.5 anton 9948:
1.78 anton 9949: The ANS Forth locals extension wordset defines a syntax using
9950: @code{locals|}, but it is so awful that we strongly recommend not to use
9951: it. We have implemented this syntax to make porting to Gforth easy, but
9952: do not document it here. The problem with this syntax is that the locals
9953: are defined in an order reversed with respect to the standard stack
9954: comment notation, making programs harder to read, and easier to misread
9955: and miswrite. The only merit of this syntax is that it is easy to
9956: implement using the ANS Forth locals wordset.
1.53 anton 9957:
9958:
1.78 anton 9959: @c ----------------------------------------------------------
9960: @node Structures, Object-oriented Forth, Locals, Words
9961: @section Structures
9962: @cindex structures
9963: @cindex records
1.53 anton 9964:
1.78 anton 9965: This section presents the structure package that comes with Gforth. A
9966: version of the package implemented in ANS Forth is available in
9967: @file{compat/struct.fs}. This package was inspired by a posting on
9968: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9969: possibly John Hayes). A version of this section has been published in
9970: M. Anton Ertl,
9971: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9972: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9973: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9974:
1.78 anton 9975: @menu
9976: * Why explicit structure support?::
9977: * Structure Usage::
9978: * Structure Naming Convention::
9979: * Structure Implementation::
9980: * Structure Glossary::
1.183 anton 9981: * Forth200x Structures::
1.78 anton 9982: @end menu
1.55 anton 9983:
1.78 anton 9984: @node Why explicit structure support?, Structure Usage, Structures, Structures
9985: @subsection Why explicit structure support?
1.53 anton 9986:
1.78 anton 9987: @cindex address arithmetic for structures
9988: @cindex structures using address arithmetic
9989: If we want to use a structure containing several fields, we could simply
9990: reserve memory for it, and access the fields using address arithmetic
9991: (@pxref{Address arithmetic}). As an example, consider a structure with
9992: the following fields
1.57 anton 9993:
1.78 anton 9994: @table @code
9995: @item a
9996: is a float
9997: @item b
9998: is a cell
9999: @item c
10000: is a float
10001: @end table
1.57 anton 10002:
1.78 anton 10003: Given the (float-aligned) base address of the structure we get the
10004: address of the field
1.52 anton 10005:
1.78 anton 10006: @table @code
10007: @item a
10008: without doing anything further.
10009: @item b
10010: with @code{float+}
10011: @item c
10012: with @code{float+ cell+ faligned}
10013: @end table
1.52 anton 10014:
1.78 anton 10015: It is easy to see that this can become quite tiring.
1.52 anton 10016:
1.78 anton 10017: Moreover, it is not very readable, because seeing a
10018: @code{cell+} tells us neither which kind of structure is
10019: accessed nor what field is accessed; we have to somehow infer the kind
10020: of structure, and then look up in the documentation, which field of
10021: that structure corresponds to that offset.
1.53 anton 10022:
1.78 anton 10023: Finally, this kind of address arithmetic also causes maintenance
10024: troubles: If you add or delete a field somewhere in the middle of the
10025: structure, you have to find and change all computations for the fields
10026: afterwards.
1.52 anton 10027:
1.78 anton 10028: So, instead of using @code{cell+} and friends directly, how
10029: about storing the offsets in constants:
1.52 anton 10030:
1.78 anton 10031: @example
10032: 0 constant a-offset
10033: 0 float+ constant b-offset
10034: 0 float+ cell+ faligned c-offset
10035: @end example
1.64 pazsan 10036:
1.78 anton 10037: Now we can get the address of field @code{x} with @code{x-offset
10038: +}. This is much better in all respects. Of course, you still
10039: have to change all later offset definitions if you add a field. You can
10040: fix this by declaring the offsets in the following way:
1.57 anton 10041:
1.78 anton 10042: @example
10043: 0 constant a-offset
10044: a-offset float+ constant b-offset
10045: b-offset cell+ faligned constant c-offset
10046: @end example
1.57 anton 10047:
1.78 anton 10048: Since we always use the offsets with @code{+}, we could use a defining
10049: word @code{cfield} that includes the @code{+} in the action of the
10050: defined word:
1.64 pazsan 10051:
1.78 anton 10052: @example
10053: : cfield ( n "name" -- )
10054: create ,
10055: does> ( name execution: addr1 -- addr2 )
10056: @@ + ;
1.64 pazsan 10057:
1.78 anton 10058: 0 cfield a
10059: 0 a float+ cfield b
10060: 0 b cell+ faligned cfield c
10061: @end example
1.64 pazsan 10062:
1.78 anton 10063: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10064:
1.78 anton 10065: The structure field words now can be used quite nicely. However,
10066: their definition is still a bit cumbersome: We have to repeat the
10067: name, the information about size and alignment is distributed before
10068: and after the field definitions etc. The structure package presented
10069: here addresses these problems.
1.64 pazsan 10070:
1.78 anton 10071: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10072: @subsection Structure Usage
10073: @cindex structure usage
1.57 anton 10074:
1.78 anton 10075: @cindex @code{field} usage
10076: @cindex @code{struct} usage
10077: @cindex @code{end-struct} usage
10078: You can define a structure for a (data-less) linked list with:
1.57 anton 10079: @example
1.78 anton 10080: struct
10081: cell% field list-next
10082: end-struct list%
1.57 anton 10083: @end example
10084:
1.78 anton 10085: With the address of the list node on the stack, you can compute the
10086: address of the field that contains the address of the next node with
10087: @code{list-next}. E.g., you can determine the length of a list
10088: with:
1.57 anton 10089:
10090: @example
1.78 anton 10091: : list-length ( list -- n )
10092: \ "list" is a pointer to the first element of a linked list
10093: \ "n" is the length of the list
10094: 0 BEGIN ( list1 n1 )
10095: over
10096: WHILE ( list1 n1 )
10097: 1+ swap list-next @@ swap
10098: REPEAT
10099: nip ;
1.57 anton 10100: @end example
10101:
1.78 anton 10102: You can reserve memory for a list node in the dictionary with
10103: @code{list% %allot}, which leaves the address of the list node on the
10104: stack. For the equivalent allocation on the heap you can use @code{list%
10105: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10106: use @code{list% %allocate}). You can get the the size of a list
10107: node with @code{list% %size} and its alignment with @code{list%
10108: %alignment}.
10109:
10110: Note that in ANS Forth the body of a @code{create}d word is
10111: @code{aligned} but not necessarily @code{faligned};
10112: therefore, if you do a:
1.57 anton 10113:
10114: @example
1.78 anton 10115: create @emph{name} foo% %allot drop
1.57 anton 10116: @end example
10117:
1.78 anton 10118: @noindent
10119: then the memory alloted for @code{foo%} is guaranteed to start at the
10120: body of @code{@emph{name}} only if @code{foo%} contains only character,
10121: cell and double fields. Therefore, if your structure contains floats,
10122: better use
1.57 anton 10123:
10124: @example
1.78 anton 10125: foo% %allot constant @emph{name}
1.57 anton 10126: @end example
10127:
1.78 anton 10128: @cindex structures containing structures
10129: You can include a structure @code{foo%} as a field of
10130: another structure, like this:
1.65 anton 10131: @example
1.78 anton 10132: struct
10133: ...
10134: foo% field ...
10135: ...
10136: end-struct ...
1.65 anton 10137: @end example
1.52 anton 10138:
1.78 anton 10139: @cindex structure extension
10140: @cindex extended records
10141: Instead of starting with an empty structure, you can extend an
10142: existing structure. E.g., a plain linked list without data, as defined
10143: above, is hardly useful; You can extend it to a linked list of integers,
10144: like this:@footnote{This feature is also known as @emph{extended
10145: records}. It is the main innovation in the Oberon language; in other
10146: words, adding this feature to Modula-2 led Wirth to create a new
10147: language, write a new compiler etc. Adding this feature to Forth just
10148: required a few lines of code.}
1.52 anton 10149:
1.78 anton 10150: @example
10151: list%
10152: cell% field intlist-int
10153: end-struct intlist%
10154: @end example
1.55 anton 10155:
1.78 anton 10156: @code{intlist%} is a structure with two fields:
10157: @code{list-next} and @code{intlist-int}.
1.55 anton 10158:
1.78 anton 10159: @cindex structures containing arrays
10160: You can specify an array type containing @emph{n} elements of
10161: type @code{foo%} like this:
1.55 anton 10162:
10163: @example
1.78 anton 10164: foo% @emph{n} *
1.56 anton 10165: @end example
1.55 anton 10166:
1.78 anton 10167: You can use this array type in any place where you can use a normal
10168: type, e.g., when defining a @code{field}, or with
10169: @code{%allot}.
10170:
10171: @cindex first field optimization
10172: The first field is at the base address of a structure and the word for
10173: this field (e.g., @code{list-next}) actually does not change the address
10174: on the stack. You may be tempted to leave it away in the interest of
10175: run-time and space efficiency. This is not necessary, because the
10176: structure package optimizes this case: If you compile a first-field
10177: words, no code is generated. So, in the interest of readability and
10178: maintainability you should include the word for the field when accessing
10179: the field.
1.52 anton 10180:
10181:
1.78 anton 10182: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10183: @subsection Structure Naming Convention
10184: @cindex structure naming convention
1.52 anton 10185:
1.78 anton 10186: The field names that come to (my) mind are often quite generic, and,
10187: if used, would cause frequent name clashes. E.g., many structures
10188: probably contain a @code{counter} field. The structure names
10189: that come to (my) mind are often also the logical choice for the names
10190: of words that create such a structure.
1.52 anton 10191:
1.78 anton 10192: Therefore, I have adopted the following naming conventions:
1.52 anton 10193:
1.78 anton 10194: @itemize @bullet
10195: @cindex field naming convention
10196: @item
10197: The names of fields are of the form
10198: @code{@emph{struct}-@emph{field}}, where
10199: @code{@emph{struct}} is the basic name of the structure, and
10200: @code{@emph{field}} is the basic name of the field. You can
10201: think of field words as converting the (address of the)
10202: structure into the (address of the) field.
1.52 anton 10203:
1.78 anton 10204: @cindex structure naming convention
10205: @item
10206: The names of structures are of the form
10207: @code{@emph{struct}%}, where
10208: @code{@emph{struct}} is the basic name of the structure.
10209: @end itemize
1.52 anton 10210:
1.78 anton 10211: This naming convention does not work that well for fields of extended
10212: structures; e.g., the integer list structure has a field
10213: @code{intlist-int}, but has @code{list-next}, not
10214: @code{intlist-next}.
1.53 anton 10215:
1.78 anton 10216: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10217: @subsection Structure Implementation
10218: @cindex structure implementation
10219: @cindex implementation of structures
1.52 anton 10220:
1.78 anton 10221: The central idea in the implementation is to pass the data about the
10222: structure being built on the stack, not in some global
10223: variable. Everything else falls into place naturally once this design
10224: decision is made.
1.53 anton 10225:
1.78 anton 10226: The type description on the stack is of the form @emph{align
10227: size}. Keeping the size on the top-of-stack makes dealing with arrays
10228: very simple.
1.53 anton 10229:
1.78 anton 10230: @code{field} is a defining word that uses @code{Create}
10231: and @code{DOES>}. The body of the field contains the offset
10232: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10233:
10234: @example
1.78 anton 10235: @@ +
1.53 anton 10236: @end example
10237:
1.78 anton 10238: @noindent
10239: i.e., add the offset to the address, giving the stack effect
10240: @i{addr1 -- addr2} for a field.
10241:
10242: @cindex first field optimization, implementation
10243: This simple structure is slightly complicated by the optimization
10244: for fields with offset 0, which requires a different
10245: @code{DOES>}-part (because we cannot rely on there being
10246: something on the stack if such a field is invoked during
10247: compilation). Therefore, we put the different @code{DOES>}-parts
10248: in separate words, and decide which one to invoke based on the
10249: offset. For a zero offset, the field is basically a noop; it is
10250: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10251:
1.183 anton 10252: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10253: @subsection Structure Glossary
10254: @cindex structure glossary
1.53 anton 10255:
1.5 anton 10256:
1.78 anton 10257: doc-%align
10258: doc-%alignment
10259: doc-%alloc
10260: doc-%allocate
10261: doc-%allot
10262: doc-cell%
10263: doc-char%
10264: doc-dfloat%
10265: doc-double%
10266: doc-end-struct
10267: doc-field
10268: doc-float%
10269: doc-naligned
10270: doc-sfloat%
10271: doc-%size
10272: doc-struct
1.54 anton 10273:
10274:
1.183 anton 10275: @node Forth200x Structures, , Structure Glossary, Structures
10276: @subsection Forth200x Structures
10277: @cindex Structures in Forth200x
10278:
10279: The Forth 200x standard defines a slightly less convenient form of
10280: structures. In general (when using @code{field+}, you have to perform
10281: the alignment yourself, but there are a number of convenience words
10282: (e.g., @code{field:} that perform the alignment for you.
10283:
10284: A typical usage example is:
10285:
10286: @example
10287: 0
10288: field: s-a
10289: faligned 2 floats +field s-b
10290: constant s-struct
10291: @end example
10292:
10293: An alternative way of writing this structure is:
10294:
10295: @example
10296: begin-structure s-struct
10297: field: s-a
10298: faligned 2 floats +field s-b
10299: end-structure
10300: @end example
10301:
10302: doc-begin-structure
10303: doc-end-structure
10304: doc-+field
10305: doc-cfield:
10306: doc-field:
10307: doc-2field:
10308: doc-ffield:
10309: doc-sffield:
10310: doc-dffield:
10311:
1.26 crook 10312: @c -------------------------------------------------------------
1.78 anton 10313: @node Object-oriented Forth, Programming Tools, Structures, Words
10314: @section Object-oriented Forth
10315:
10316: Gforth comes with three packages for object-oriented programming:
10317: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10318: is preloaded, so you have to @code{include} them before use. The most
10319: important differences between these packages (and others) are discussed
10320: in @ref{Comparison with other object models}. All packages are written
10321: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10322:
1.78 anton 10323: @menu
10324: * Why object-oriented programming?::
10325: * Object-Oriented Terminology::
10326: * Objects::
10327: * OOF::
10328: * Mini-OOF::
10329: * Comparison with other object models::
10330: @end menu
1.5 anton 10331:
1.78 anton 10332: @c ----------------------------------------------------------------
10333: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10334: @subsection Why object-oriented programming?
10335: @cindex object-oriented programming motivation
10336: @cindex motivation for object-oriented programming
1.44 crook 10337:
1.78 anton 10338: Often we have to deal with several data structures (@emph{objects}),
10339: that have to be treated similarly in some respects, but differently in
10340: others. Graphical objects are the textbook example: circles, triangles,
10341: dinosaurs, icons, and others, and we may want to add more during program
10342: development. We want to apply some operations to any graphical object,
10343: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10344: has to do something different for every kind of object.
10345: @comment TODO add some other operations eg perimeter, area
10346: @comment and tie in to concrete examples later..
1.5 anton 10347:
1.78 anton 10348: We could implement @code{draw} as a big @code{CASE}
10349: control structure that executes the appropriate code depending on the
10350: kind of object to be drawn. This would be not be very elegant, and,
10351: moreover, we would have to change @code{draw} every time we add
10352: a new kind of graphical object (say, a spaceship).
1.44 crook 10353:
1.78 anton 10354: What we would rather do is: When defining spaceships, we would tell
10355: the system: ``Here's how you @code{draw} a spaceship; you figure
10356: out the rest''.
1.5 anton 10357:
1.78 anton 10358: This is the problem that all systems solve that (rightfully) call
10359: themselves object-oriented; the object-oriented packages presented here
10360: solve this problem (and not much else).
10361: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10362:
1.78 anton 10363: @c ------------------------------------------------------------------------
10364: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10365: @subsection Object-Oriented Terminology
10366: @cindex object-oriented terminology
10367: @cindex terminology for object-oriented programming
1.5 anton 10368:
1.78 anton 10369: This section is mainly for reference, so you don't have to understand
10370: all of it right away. The terminology is mainly Smalltalk-inspired. In
10371: short:
1.44 crook 10372:
1.78 anton 10373: @table @emph
10374: @cindex class
10375: @item class
10376: a data structure definition with some extras.
1.5 anton 10377:
1.78 anton 10378: @cindex object
10379: @item object
10380: an instance of the data structure described by the class definition.
1.5 anton 10381:
1.78 anton 10382: @cindex instance variables
10383: @item instance variables
10384: fields of the data structure.
1.5 anton 10385:
1.78 anton 10386: @cindex selector
10387: @cindex method selector
10388: @cindex virtual function
10389: @item selector
10390: (or @emph{method selector}) a word (e.g.,
10391: @code{draw}) that performs an operation on a variety of data
10392: structures (classes). A selector describes @emph{what} operation to
10393: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10394:
1.78 anton 10395: @cindex method
10396: @item method
10397: the concrete definition that performs the operation
10398: described by the selector for a specific class. A method specifies
10399: @emph{how} the operation is performed for a specific class.
1.5 anton 10400:
1.78 anton 10401: @cindex selector invocation
10402: @cindex message send
10403: @cindex invoking a selector
10404: @item selector invocation
10405: a call of a selector. One argument of the call (the TOS (top-of-stack))
10406: is used for determining which method is used. In Smalltalk terminology:
10407: a message (consisting of the selector and the other arguments) is sent
10408: to the object.
1.5 anton 10409:
1.78 anton 10410: @cindex receiving object
10411: @item receiving object
10412: the object used for determining the method executed by a selector
10413: invocation. In the @file{objects.fs} model, it is the object that is on
10414: the TOS when the selector is invoked. (@emph{Receiving} comes from
10415: the Smalltalk @emph{message} terminology.)
1.5 anton 10416:
1.78 anton 10417: @cindex child class
10418: @cindex parent class
10419: @cindex inheritance
10420: @item child class
10421: a class that has (@emph{inherits}) all properties (instance variables,
10422: selectors, methods) from a @emph{parent class}. In Smalltalk
10423: terminology: The subclass inherits from the superclass. In C++
10424: terminology: The derived class inherits from the base class.
1.5 anton 10425:
1.78 anton 10426: @end table
1.5 anton 10427:
1.78 anton 10428: @c If you wonder about the message sending terminology, it comes from
10429: @c a time when each object had it's own task and objects communicated via
10430: @c message passing; eventually the Smalltalk developers realized that
10431: @c they can do most things through simple (indirect) calls. They kept the
10432: @c terminology.
1.5 anton 10433:
1.78 anton 10434: @c --------------------------------------------------------------
10435: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10436: @subsection The @file{objects.fs} model
10437: @cindex objects
10438: @cindex object-oriented programming
1.26 crook 10439:
1.78 anton 10440: @cindex @file{objects.fs}
10441: @cindex @file{oof.fs}
1.26 crook 10442:
1.78 anton 10443: This section describes the @file{objects.fs} package. This material also
10444: has been published in M. Anton Ertl,
10445: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10446: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10447: 37--43.
10448: @c McKewan's and Zsoter's packages
1.26 crook 10449:
1.78 anton 10450: This section assumes that you have read @ref{Structures}.
1.5 anton 10451:
1.78 anton 10452: The techniques on which this model is based have been used to implement
10453: the parser generator, Gray, and have also been used in Gforth for
10454: implementing the various flavours of word lists (hashed or not,
10455: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10456:
10457:
1.26 crook 10458: @menu
1.78 anton 10459: * Properties of the Objects model::
10460: * Basic Objects Usage::
10461: * The Objects base class::
10462: * Creating objects::
10463: * Object-Oriented Programming Style::
10464: * Class Binding::
10465: * Method conveniences::
10466: * Classes and Scoping::
10467: * Dividing classes::
10468: * Object Interfaces::
10469: * Objects Implementation::
10470: * Objects Glossary::
1.26 crook 10471: @end menu
1.5 anton 10472:
1.78 anton 10473: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10474:
1.78 anton 10475: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10476: @subsubsection Properties of the @file{objects.fs} model
10477: @cindex @file{objects.fs} properties
1.5 anton 10478:
1.78 anton 10479: @itemize @bullet
10480: @item
10481: It is straightforward to pass objects on the stack. Passing
10482: selectors on the stack is a little less convenient, but possible.
1.44 crook 10483:
1.78 anton 10484: @item
10485: Objects are just data structures in memory, and are referenced by their
10486: address. You can create words for objects with normal defining words
10487: like @code{constant}. Likewise, there is no difference between instance
10488: variables that contain objects and those that contain other data.
1.5 anton 10489:
1.78 anton 10490: @item
10491: Late binding is efficient and easy to use.
1.44 crook 10492:
1.78 anton 10493: @item
10494: It avoids parsing, and thus avoids problems with state-smartness
10495: and reduced extensibility; for convenience there are a few parsing
10496: words, but they have non-parsing counterparts. There are also a few
10497: defining words that parse. This is hard to avoid, because all standard
10498: defining words parse (except @code{:noname}); however, such
10499: words are not as bad as many other parsing words, because they are not
10500: state-smart.
1.5 anton 10501:
1.78 anton 10502: @item
10503: It does not try to incorporate everything. It does a few things and does
10504: them well (IMO). In particular, this model was not designed to support
10505: information hiding (although it has features that may help); you can use
10506: a separate package for achieving this.
1.5 anton 10507:
1.78 anton 10508: @item
10509: It is layered; you don't have to learn and use all features to use this
10510: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10511: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10512: are optional and independent of each other.
1.5 anton 10513:
1.78 anton 10514: @item
10515: An implementation in ANS Forth is available.
1.5 anton 10516:
1.78 anton 10517: @end itemize
1.5 anton 10518:
1.44 crook 10519:
1.78 anton 10520: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10521: @subsubsection Basic @file{objects.fs} Usage
10522: @cindex basic objects usage
10523: @cindex objects, basic usage
1.5 anton 10524:
1.78 anton 10525: You can define a class for graphical objects like this:
1.44 crook 10526:
1.78 anton 10527: @cindex @code{class} usage
10528: @cindex @code{end-class} usage
10529: @cindex @code{selector} usage
1.5 anton 10530: @example
1.78 anton 10531: object class \ "object" is the parent class
10532: selector draw ( x y graphical -- )
10533: end-class graphical
10534: @end example
10535:
10536: This code defines a class @code{graphical} with an
10537: operation @code{draw}. We can perform the operation
10538: @code{draw} on any @code{graphical} object, e.g.:
10539:
10540: @example
10541: 100 100 t-rex draw
1.26 crook 10542: @end example
1.5 anton 10543:
1.78 anton 10544: @noindent
10545: where @code{t-rex} is a word (say, a constant) that produces a
10546: graphical object.
10547:
10548: @comment TODO add a 2nd operation eg perimeter.. and use for
10549: @comment a concrete example
1.5 anton 10550:
1.78 anton 10551: @cindex abstract class
10552: How do we create a graphical object? With the present definitions,
10553: we cannot create a useful graphical object. The class
10554: @code{graphical} describes graphical objects in general, but not
10555: any concrete graphical object type (C++ users would call it an
10556: @emph{abstract class}); e.g., there is no method for the selector
10557: @code{draw} in the class @code{graphical}.
1.5 anton 10558:
1.78 anton 10559: For concrete graphical objects, we define child classes of the
10560: class @code{graphical}, e.g.:
1.5 anton 10561:
1.78 anton 10562: @cindex @code{overrides} usage
10563: @cindex @code{field} usage in class definition
1.26 crook 10564: @example
1.78 anton 10565: graphical class \ "graphical" is the parent class
10566: cell% field circle-radius
1.5 anton 10567:
1.78 anton 10568: :noname ( x y circle -- )
10569: circle-radius @@ draw-circle ;
10570: overrides draw
1.5 anton 10571:
1.78 anton 10572: :noname ( n-radius circle -- )
10573: circle-radius ! ;
10574: overrides construct
1.5 anton 10575:
1.78 anton 10576: end-class circle
10577: @end example
1.44 crook 10578:
1.78 anton 10579: Here we define a class @code{circle} as a child of @code{graphical},
10580: with field @code{circle-radius} (which behaves just like a field
10581: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10582: for the selectors @code{draw} and @code{construct} (@code{construct} is
10583: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10584:
1.78 anton 10585: Now we can create a circle on the heap (i.e.,
10586: @code{allocate}d memory) with:
1.44 crook 10587:
1.78 anton 10588: @cindex @code{heap-new} usage
1.5 anton 10589: @example
1.78 anton 10590: 50 circle heap-new constant my-circle
1.5 anton 10591: @end example
10592:
1.78 anton 10593: @noindent
10594: @code{heap-new} invokes @code{construct}, thus
10595: initializing the field @code{circle-radius} with 50. We can draw
10596: this new circle at (100,100) with:
1.5 anton 10597:
10598: @example
1.78 anton 10599: 100 100 my-circle draw
1.5 anton 10600: @end example
10601:
1.78 anton 10602: @cindex selector invocation, restrictions
10603: @cindex class definition, restrictions
10604: Note: You can only invoke a selector if the object on the TOS
10605: (the receiving object) belongs to the class where the selector was
10606: defined or one of its descendents; e.g., you can invoke
10607: @code{draw} only for objects belonging to @code{graphical}
10608: or its descendents (e.g., @code{circle}). Immediately before
10609: @code{end-class}, the search order has to be the same as
10610: immediately after @code{class}.
10611:
10612: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10613: @subsubsection The @file{object.fs} base class
10614: @cindex @code{object} class
10615:
10616: When you define a class, you have to specify a parent class. So how do
10617: you start defining classes? There is one class available from the start:
10618: @code{object}. It is ancestor for all classes and so is the
10619: only class that has no parent. It has two selectors: @code{construct}
10620: and @code{print}.
10621:
10622: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10623: @subsubsection Creating objects
10624: @cindex creating objects
10625: @cindex object creation
10626: @cindex object allocation options
10627:
10628: @cindex @code{heap-new} discussion
10629: @cindex @code{dict-new} discussion
10630: @cindex @code{construct} discussion
10631: You can create and initialize an object of a class on the heap with
10632: @code{heap-new} ( ... class -- object ) and in the dictionary
10633: (allocation with @code{allot}) with @code{dict-new} (
10634: ... class -- object ). Both words invoke @code{construct}, which
10635: consumes the stack items indicated by "..." above.
10636:
10637: @cindex @code{init-object} discussion
10638: @cindex @code{class-inst-size} discussion
10639: If you want to allocate memory for an object yourself, you can get its
10640: alignment and size with @code{class-inst-size 2@@} ( class --
10641: align size ). Once you have memory for an object, you can initialize
10642: it with @code{init-object} ( ... class object -- );
10643: @code{construct} does only a part of the necessary work.
10644:
10645: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10646: @subsubsection Object-Oriented Programming Style
10647: @cindex object-oriented programming style
10648: @cindex programming style, object-oriented
1.5 anton 10649:
1.78 anton 10650: This section is not exhaustive.
1.5 anton 10651:
1.78 anton 10652: @cindex stack effects of selectors
10653: @cindex selectors and stack effects
10654: In general, it is a good idea to ensure that all methods for the
10655: same selector have the same stack effect: when you invoke a selector,
10656: you often have no idea which method will be invoked, so, unless all
10657: methods have the same stack effect, you will not know the stack effect
10658: of the selector invocation.
1.5 anton 10659:
1.78 anton 10660: One exception to this rule is methods for the selector
10661: @code{construct}. We know which method is invoked, because we
10662: specify the class to be constructed at the same place. Actually, I
10663: defined @code{construct} as a selector only to give the users a
10664: convenient way to specify initialization. The way it is used, a
10665: mechanism different from selector invocation would be more natural
10666: (but probably would take more code and more space to explain).
1.5 anton 10667:
1.78 anton 10668: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10669: @subsubsection Class Binding
10670: @cindex class binding
10671: @cindex early binding
1.5 anton 10672:
1.78 anton 10673: @cindex late binding
10674: Normal selector invocations determine the method at run-time depending
10675: on the class of the receiving object. This run-time selection is called
10676: @i{late binding}.
1.5 anton 10677:
1.78 anton 10678: Sometimes it's preferable to invoke a different method. For example,
10679: you might want to use the simple method for @code{print}ing
10680: @code{object}s instead of the possibly long-winded @code{print} method
10681: of the receiver class. You can achieve this by replacing the invocation
10682: of @code{print} with:
1.5 anton 10683:
1.78 anton 10684: @cindex @code{[bind]} usage
1.5 anton 10685: @example
1.78 anton 10686: [bind] object print
1.5 anton 10687: @end example
10688:
1.78 anton 10689: @noindent
10690: in compiled code or:
10691:
10692: @cindex @code{bind} usage
1.5 anton 10693: @example
1.78 anton 10694: bind object print
1.5 anton 10695: @end example
10696:
1.78 anton 10697: @cindex class binding, alternative to
10698: @noindent
10699: in interpreted code. Alternatively, you can define the method with a
10700: name (e.g., @code{print-object}), and then invoke it through the
10701: name. Class binding is just a (often more convenient) way to achieve
10702: the same effect; it avoids name clutter and allows you to invoke
10703: methods directly without naming them first.
1.5 anton 10704:
1.78 anton 10705: @cindex superclass binding
10706: @cindex parent class binding
10707: A frequent use of class binding is this: When we define a method
10708: for a selector, we often want the method to do what the selector does
10709: in the parent class, and a little more. There is a special word for
10710: this purpose: @code{[parent]}; @code{[parent]
10711: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10712: selector}}, where @code{@emph{parent}} is the parent
10713: class of the current class. E.g., a method definition might look like:
1.44 crook 10714:
1.78 anton 10715: @cindex @code{[parent]} usage
10716: @example
10717: :noname
10718: dup [parent] foo \ do parent's foo on the receiving object
10719: ... \ do some more
10720: ; overrides foo
10721: @end example
1.6 pazsan 10722:
1.78 anton 10723: @cindex class binding as optimization
10724: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10725: March 1997), Andrew McKewan presents class binding as an optimization
10726: technique. I recommend not using it for this purpose unless you are in
10727: an emergency. Late binding is pretty fast with this model anyway, so the
10728: benefit of using class binding is small; the cost of using class binding
10729: where it is not appropriate is reduced maintainability.
1.44 crook 10730:
1.78 anton 10731: While we are at programming style questions: You should bind
10732: selectors only to ancestor classes of the receiving object. E.g., say,
10733: you know that the receiving object is of class @code{foo} or its
10734: descendents; then you should bind only to @code{foo} and its
10735: ancestors.
1.12 anton 10736:
1.78 anton 10737: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10738: @subsubsection Method conveniences
10739: @cindex method conveniences
1.44 crook 10740:
1.78 anton 10741: In a method you usually access the receiving object pretty often. If
10742: you define the method as a plain colon definition (e.g., with
10743: @code{:noname}), you may have to do a lot of stack
10744: gymnastics. To avoid this, you can define the method with @code{m:
10745: ... ;m}. E.g., you could define the method for
10746: @code{draw}ing a @code{circle} with
1.6 pazsan 10747:
1.78 anton 10748: @cindex @code{this} usage
10749: @cindex @code{m:} usage
10750: @cindex @code{;m} usage
10751: @example
10752: m: ( x y circle -- )
10753: ( x y ) this circle-radius @@ draw-circle ;m
10754: @end example
1.6 pazsan 10755:
1.78 anton 10756: @cindex @code{exit} in @code{m: ... ;m}
10757: @cindex @code{exitm} discussion
10758: @cindex @code{catch} in @code{m: ... ;m}
10759: When this method is executed, the receiver object is removed from the
10760: stack; you can access it with @code{this} (admittedly, in this
10761: example the use of @code{m: ... ;m} offers no advantage). Note
10762: that I specify the stack effect for the whole method (i.e. including
10763: the receiver object), not just for the code between @code{m:}
10764: and @code{;m}. You cannot use @code{exit} in
10765: @code{m:...;m}; instead, use
10766: @code{exitm}.@footnote{Moreover, for any word that calls
10767: @code{catch} and was defined before loading
10768: @code{objects.fs}, you have to redefine it like I redefined
10769: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10770:
1.78 anton 10771: @cindex @code{inst-var} usage
10772: You will frequently use sequences of the form @code{this
10773: @emph{field}} (in the example above: @code{this
10774: circle-radius}). If you use the field only in this way, you can
10775: define it with @code{inst-var} and eliminate the
10776: @code{this} before the field name. E.g., the @code{circle}
10777: class above could also be defined with:
1.6 pazsan 10778:
1.78 anton 10779: @example
10780: graphical class
10781: cell% inst-var radius
1.6 pazsan 10782:
1.78 anton 10783: m: ( x y circle -- )
10784: radius @@ draw-circle ;m
10785: overrides draw
1.6 pazsan 10786:
1.78 anton 10787: m: ( n-radius circle -- )
10788: radius ! ;m
10789: overrides construct
1.6 pazsan 10790:
1.78 anton 10791: end-class circle
10792: @end example
1.6 pazsan 10793:
1.78 anton 10794: @code{radius} can only be used in @code{circle} and its
10795: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10796:
1.78 anton 10797: @cindex @code{inst-value} usage
10798: You can also define fields with @code{inst-value}, which is
10799: to @code{inst-var} what @code{value} is to
10800: @code{variable}. You can change the value of such a field with
10801: @code{[to-inst]}. E.g., we could also define the class
10802: @code{circle} like this:
1.44 crook 10803:
1.78 anton 10804: @example
10805: graphical class
10806: inst-value radius
1.6 pazsan 10807:
1.78 anton 10808: m: ( x y circle -- )
10809: radius draw-circle ;m
10810: overrides draw
1.44 crook 10811:
1.78 anton 10812: m: ( n-radius circle -- )
10813: [to-inst] radius ;m
10814: overrides construct
1.6 pazsan 10815:
1.78 anton 10816: end-class circle
10817: @end example
1.6 pazsan 10818:
1.78 anton 10819: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10820:
1.78 anton 10821: @c Finally, you can define named methods with @code{:m}. One use of this
10822: @c feature is the definition of words that occur only in one class and are
10823: @c not intended to be overridden, but which still need method context
10824: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10825: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10826:
10827:
1.78 anton 10828: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10829: @subsubsection Classes and Scoping
10830: @cindex classes and scoping
10831: @cindex scoping and classes
1.6 pazsan 10832:
1.78 anton 10833: Inheritance is frequent, unlike structure extension. This exacerbates
10834: the problem with the field name convention (@pxref{Structure Naming
10835: Convention}): One always has to remember in which class the field was
10836: originally defined; changing a part of the class structure would require
10837: changes for renaming in otherwise unaffected code.
1.6 pazsan 10838:
1.78 anton 10839: @cindex @code{inst-var} visibility
10840: @cindex @code{inst-value} visibility
10841: To solve this problem, I added a scoping mechanism (which was not in my
10842: original charter): A field defined with @code{inst-var} (or
10843: @code{inst-value}) is visible only in the class where it is defined and in
10844: the descendent classes of this class. Using such fields only makes
10845: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10846:
1.78 anton 10847: This scoping mechanism allows us to use the unadorned field name,
10848: because name clashes with unrelated words become much less likely.
1.6 pazsan 10849:
1.78 anton 10850: @cindex @code{protected} discussion
10851: @cindex @code{private} discussion
10852: Once we have this mechanism, we can also use it for controlling the
10853: visibility of other words: All words defined after
10854: @code{protected} are visible only in the current class and its
10855: descendents. @code{public} restores the compilation
10856: (i.e. @code{current}) word list that was in effect before. If you
10857: have several @code{protected}s without an intervening
10858: @code{public} or @code{set-current}, @code{public}
10859: will restore the compilation word list in effect before the first of
10860: these @code{protected}s.
1.6 pazsan 10861:
1.78 anton 10862: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10863: @subsubsection Dividing classes
10864: @cindex Dividing classes
10865: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10866:
1.78 anton 10867: You may want to do the definition of methods separate from the
10868: definition of the class, its selectors, fields, and instance variables,
10869: i.e., separate the implementation from the definition. You can do this
10870: in the following way:
1.6 pazsan 10871:
1.78 anton 10872: @example
10873: graphical class
10874: inst-value radius
10875: end-class circle
1.6 pazsan 10876:
1.78 anton 10877: ... \ do some other stuff
1.6 pazsan 10878:
1.78 anton 10879: circle methods \ now we are ready
1.44 crook 10880:
1.78 anton 10881: m: ( x y circle -- )
10882: radius draw-circle ;m
10883: overrides draw
1.6 pazsan 10884:
1.78 anton 10885: m: ( n-radius circle -- )
10886: [to-inst] radius ;m
10887: overrides construct
1.44 crook 10888:
1.78 anton 10889: end-methods
10890: @end example
1.7 pazsan 10891:
1.78 anton 10892: You can use several @code{methods}...@code{end-methods} sections. The
10893: only things you can do to the class in these sections are: defining
10894: methods, and overriding the class's selectors. You must not define new
10895: selectors or fields.
1.7 pazsan 10896:
1.78 anton 10897: Note that you often have to override a selector before using it. In
10898: particular, you usually have to override @code{construct} with a new
10899: method before you can invoke @code{heap-new} and friends. E.g., you
10900: must not create a circle before the @code{overrides construct} sequence
10901: in the example above.
1.7 pazsan 10902:
1.78 anton 10903: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10904: @subsubsection Object Interfaces
10905: @cindex object interfaces
10906: @cindex interfaces for objects
1.7 pazsan 10907:
1.78 anton 10908: In this model you can only call selectors defined in the class of the
10909: receiving objects or in one of its ancestors. If you call a selector
10910: with a receiving object that is not in one of these classes, the
10911: result is undefined; if you are lucky, the program crashes
10912: immediately.
1.7 pazsan 10913:
1.78 anton 10914: @cindex selectors common to hardly-related classes
10915: Now consider the case when you want to have a selector (or several)
10916: available in two classes: You would have to add the selector to a
10917: common ancestor class, in the worst case to @code{object}. You
10918: may not want to do this, e.g., because someone else is responsible for
10919: this ancestor class.
1.7 pazsan 10920:
1.78 anton 10921: The solution for this problem is interfaces. An interface is a
10922: collection of selectors. If a class implements an interface, the
10923: selectors become available to the class and its descendents. A class
10924: can implement an unlimited number of interfaces. For the problem
10925: discussed above, we would define an interface for the selector(s), and
10926: both classes would implement the interface.
1.7 pazsan 10927:
1.78 anton 10928: As an example, consider an interface @code{storage} for
10929: writing objects to disk and getting them back, and a class
10930: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10931:
1.78 anton 10932: @cindex @code{interface} usage
10933: @cindex @code{end-interface} usage
10934: @cindex @code{implementation} usage
10935: @example
10936: interface
10937: selector write ( file object -- )
10938: selector read1 ( file object -- )
10939: end-interface storage
1.13 pazsan 10940:
1.78 anton 10941: bar class
10942: storage implementation
1.13 pazsan 10943:
1.78 anton 10944: ... overrides write
10945: ... overrides read1
10946: ...
10947: end-class foo
10948: @end example
1.13 pazsan 10949:
1.78 anton 10950: @noindent
10951: (I would add a word @code{read} @i{( file -- object )} that uses
10952: @code{read1} internally, but that's beyond the point illustrated
10953: here.)
1.13 pazsan 10954:
1.78 anton 10955: Note that you cannot use @code{protected} in an interface; and
10956: of course you cannot define fields.
1.13 pazsan 10957:
1.78 anton 10958: In the Neon model, all selectors are available for all classes;
10959: therefore it does not need interfaces. The price you pay in this model
10960: is slower late binding, and therefore, added complexity to avoid late
10961: binding.
1.13 pazsan 10962:
1.78 anton 10963: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10964: @subsubsection @file{objects.fs} Implementation
10965: @cindex @file{objects.fs} implementation
1.13 pazsan 10966:
1.78 anton 10967: @cindex @code{object-map} discussion
10968: An object is a piece of memory, like one of the data structures
10969: described with @code{struct...end-struct}. It has a field
10970: @code{object-map} that points to the method map for the object's
10971: class.
1.13 pazsan 10972:
1.78 anton 10973: @cindex method map
10974: @cindex virtual function table
10975: The @emph{method map}@footnote{This is Self terminology; in C++
10976: terminology: virtual function table.} is an array that contains the
10977: execution tokens (@i{xt}s) of the methods for the object's class. Each
10978: selector contains an offset into a method map.
1.13 pazsan 10979:
1.78 anton 10980: @cindex @code{selector} implementation, class
10981: @code{selector} is a defining word that uses
10982: @code{CREATE} and @code{DOES>}. The body of the
10983: selector contains the offset; the @code{DOES>} action for a
10984: class selector is, basically:
1.8 pazsan 10985:
10986: @example
1.78 anton 10987: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10988: @end example
10989:
1.78 anton 10990: Since @code{object-map} is the first field of the object, it
10991: does not generate any code. As you can see, calling a selector has a
10992: small, constant cost.
1.26 crook 10993:
1.78 anton 10994: @cindex @code{current-interface} discussion
10995: @cindex class implementation and representation
10996: A class is basically a @code{struct} combined with a method
10997: map. During the class definition the alignment and size of the class
10998: are passed on the stack, just as with @code{struct}s, so
10999: @code{field} can also be used for defining class
11000: fields. However, passing more items on the stack would be
11001: inconvenient, so @code{class} builds a data structure in memory,
11002: which is accessed through the variable
11003: @code{current-interface}. After its definition is complete, the
11004: class is represented on the stack by a pointer (e.g., as parameter for
11005: a child class definition).
1.26 crook 11006:
1.78 anton 11007: A new class starts off with the alignment and size of its parent,
11008: and a copy of the parent's method map. Defining new fields extends the
11009: size and alignment; likewise, defining new selectors extends the
11010: method map. @code{overrides} just stores a new @i{xt} in the method
11011: map at the offset given by the selector.
1.13 pazsan 11012:
1.78 anton 11013: @cindex class binding, implementation
11014: Class binding just gets the @i{xt} at the offset given by the selector
11015: from the class's method map and @code{compile,}s (in the case of
11016: @code{[bind]}) it.
1.13 pazsan 11017:
1.78 anton 11018: @cindex @code{this} implementation
11019: @cindex @code{catch} and @code{this}
11020: @cindex @code{this} and @code{catch}
11021: I implemented @code{this} as a @code{value}. At the
11022: start of an @code{m:...;m} method the old @code{this} is
11023: stored to the return stack and restored at the end; and the object on
11024: the TOS is stored @code{TO this}. This technique has one
11025: disadvantage: If the user does not leave the method via
11026: @code{;m}, but via @code{throw} or @code{exit},
11027: @code{this} is not restored (and @code{exit} may
11028: crash). To deal with the @code{throw} problem, I have redefined
11029: @code{catch} to save and restore @code{this}; the same
11030: should be done with any word that can catch an exception. As for
11031: @code{exit}, I simply forbid it (as a replacement, there is
11032: @code{exitm}).
1.13 pazsan 11033:
1.78 anton 11034: @cindex @code{inst-var} implementation
11035: @code{inst-var} is just the same as @code{field}, with
11036: a different @code{DOES>} action:
1.13 pazsan 11037: @example
1.78 anton 11038: @@ this +
1.8 pazsan 11039: @end example
1.78 anton 11040: Similar for @code{inst-value}.
1.8 pazsan 11041:
1.78 anton 11042: @cindex class scoping implementation
11043: Each class also has a word list that contains the words defined with
11044: @code{inst-var} and @code{inst-value}, and its protected
11045: words. It also has a pointer to its parent. @code{class} pushes
11046: the word lists of the class and all its ancestors onto the search order stack,
11047: and @code{end-class} drops them.
1.20 pazsan 11048:
1.78 anton 11049: @cindex interface implementation
11050: An interface is like a class without fields, parent and protected
11051: words; i.e., it just has a method map. If a class implements an
11052: interface, its method map contains a pointer to the method map of the
11053: interface. The positive offsets in the map are reserved for class
11054: methods, therefore interface map pointers have negative
11055: offsets. Interfaces have offsets that are unique throughout the
11056: system, unlike class selectors, whose offsets are only unique for the
11057: classes where the selector is available (invokable).
1.20 pazsan 11058:
1.78 anton 11059: This structure means that interface selectors have to perform one
11060: indirection more than class selectors to find their method. Their body
11061: contains the interface map pointer offset in the class method map, and
11062: the method offset in the interface method map. The
11063: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11064:
11065: @example
1.78 anton 11066: ( object selector-body )
11067: 2dup selector-interface @@ ( object selector-body object interface-offset )
11068: swap object-map @@ + @@ ( object selector-body map )
11069: swap selector-offset @@ + @@ execute
1.20 pazsan 11070: @end example
11071:
1.78 anton 11072: where @code{object-map} and @code{selector-offset} are
11073: first fields and generate no code.
1.20 pazsan 11074:
1.78 anton 11075: As a concrete example, consider the following code:
1.20 pazsan 11076:
11077: @example
1.78 anton 11078: interface
11079: selector if1sel1
11080: selector if1sel2
11081: end-interface if1
1.20 pazsan 11082:
1.78 anton 11083: object class
11084: if1 implementation
11085: selector cl1sel1
11086: cell% inst-var cl1iv1
1.20 pazsan 11087:
1.78 anton 11088: ' m1 overrides construct
11089: ' m2 overrides if1sel1
11090: ' m3 overrides if1sel2
11091: ' m4 overrides cl1sel2
11092: end-class cl1
1.20 pazsan 11093:
1.78 anton 11094: create obj1 object dict-new drop
11095: create obj2 cl1 dict-new drop
11096: @end example
1.20 pazsan 11097:
1.78 anton 11098: The data structure created by this code (including the data structure
11099: for @code{object}) is shown in the
11100: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11101: @comment TODO add this diagram..
1.20 pazsan 11102:
1.78 anton 11103: @node Objects Glossary, , Objects Implementation, Objects
11104: @subsubsection @file{objects.fs} Glossary
11105: @cindex @file{objects.fs} Glossary
1.20 pazsan 11106:
11107:
1.78 anton 11108: doc---objects-bind
11109: doc---objects-<bind>
11110: doc---objects-bind'
11111: doc---objects-[bind]
11112: doc---objects-class
11113: doc---objects-class->map
11114: doc---objects-class-inst-size
11115: doc---objects-class-override!
1.79 anton 11116: doc---objects-class-previous
11117: doc---objects-class>order
1.78 anton 11118: doc---objects-construct
11119: doc---objects-current'
11120: doc---objects-[current]
11121: doc---objects-current-interface
11122: doc---objects-dict-new
11123: doc---objects-end-class
11124: doc---objects-end-class-noname
11125: doc---objects-end-interface
11126: doc---objects-end-interface-noname
11127: doc---objects-end-methods
11128: doc---objects-exitm
11129: doc---objects-heap-new
11130: doc---objects-implementation
11131: doc---objects-init-object
11132: doc---objects-inst-value
11133: doc---objects-inst-var
11134: doc---objects-interface
11135: doc---objects-m:
11136: doc---objects-:m
11137: doc---objects-;m
11138: doc---objects-method
11139: doc---objects-methods
11140: doc---objects-object
11141: doc---objects-overrides
11142: doc---objects-[parent]
11143: doc---objects-print
11144: doc---objects-protected
11145: doc---objects-public
11146: doc---objects-selector
11147: doc---objects-this
11148: doc---objects-<to-inst>
11149: doc---objects-[to-inst]
11150: doc---objects-to-this
11151: doc---objects-xt-new
1.20 pazsan 11152:
11153:
1.78 anton 11154: @c -------------------------------------------------------------
11155: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11156: @subsection The @file{oof.fs} model
11157: @cindex oof
11158: @cindex object-oriented programming
1.20 pazsan 11159:
1.78 anton 11160: @cindex @file{objects.fs}
11161: @cindex @file{oof.fs}
1.20 pazsan 11162:
1.78 anton 11163: This section describes the @file{oof.fs} package.
1.20 pazsan 11164:
1.78 anton 11165: The package described in this section has been used in bigFORTH since 1991, and
11166: used for two large applications: a chromatographic system used to
11167: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11168:
1.78 anton 11169: You can find a description (in German) of @file{oof.fs} in @cite{Object
11170: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11171: 10(2), 1994.
1.20 pazsan 11172:
1.78 anton 11173: @menu
11174: * Properties of the OOF model::
11175: * Basic OOF Usage::
11176: * The OOF base class::
11177: * Class Declaration::
11178: * Class Implementation::
11179: @end menu
1.20 pazsan 11180:
1.78 anton 11181: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11182: @subsubsection Properties of the @file{oof.fs} model
11183: @cindex @file{oof.fs} properties
1.20 pazsan 11184:
1.78 anton 11185: @itemize @bullet
11186: @item
11187: This model combines object oriented programming with information
11188: hiding. It helps you writing large application, where scoping is
11189: necessary, because it provides class-oriented scoping.
1.20 pazsan 11190:
1.78 anton 11191: @item
11192: Named objects, object pointers, and object arrays can be created,
11193: selector invocation uses the ``object selector'' syntax. Selector invocation
11194: to objects and/or selectors on the stack is a bit less convenient, but
11195: possible.
1.44 crook 11196:
1.78 anton 11197: @item
11198: Selector invocation and instance variable usage of the active object is
11199: straightforward, since both make use of the active object.
1.44 crook 11200:
1.78 anton 11201: @item
11202: Late binding is efficient and easy to use.
1.20 pazsan 11203:
1.78 anton 11204: @item
11205: State-smart objects parse selectors. However, extensibility is provided
11206: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11207:
1.78 anton 11208: @item
11209: An implementation in ANS Forth is available.
1.20 pazsan 11210:
1.78 anton 11211: @end itemize
1.23 crook 11212:
11213:
1.78 anton 11214: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11215: @subsubsection Basic @file{oof.fs} Usage
11216: @cindex @file{oof.fs} usage
1.23 crook 11217:
1.78 anton 11218: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11219:
1.78 anton 11220: You can define a class for graphical objects like this:
1.23 crook 11221:
1.78 anton 11222: @cindex @code{class} usage
11223: @cindex @code{class;} usage
11224: @cindex @code{method} usage
11225: @example
11226: object class graphical \ "object" is the parent class
1.139 pazsan 11227: method draw ( x y -- )
1.78 anton 11228: class;
11229: @end example
1.23 crook 11230:
1.78 anton 11231: This code defines a class @code{graphical} with an
11232: operation @code{draw}. We can perform the operation
11233: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11234:
1.78 anton 11235: @example
11236: 100 100 t-rex draw
11237: @end example
1.23 crook 11238:
1.78 anton 11239: @noindent
11240: where @code{t-rex} is an object or object pointer, created with e.g.
11241: @code{graphical : t-rex}.
1.23 crook 11242:
1.78 anton 11243: @cindex abstract class
11244: How do we create a graphical object? With the present definitions,
11245: we cannot create a useful graphical object. The class
11246: @code{graphical} describes graphical objects in general, but not
11247: any concrete graphical object type (C++ users would call it an
11248: @emph{abstract class}); e.g., there is no method for the selector
11249: @code{draw} in the class @code{graphical}.
1.23 crook 11250:
1.78 anton 11251: For concrete graphical objects, we define child classes of the
11252: class @code{graphical}, e.g.:
1.23 crook 11253:
1.78 anton 11254: @example
11255: graphical class circle \ "graphical" is the parent class
11256: cell var circle-radius
11257: how:
11258: : draw ( x y -- )
11259: circle-radius @@ draw-circle ;
1.23 crook 11260:
1.139 pazsan 11261: : init ( n-radius -- )
1.78 anton 11262: circle-radius ! ;
11263: class;
11264: @end example
1.1 anton 11265:
1.78 anton 11266: Here we define a class @code{circle} as a child of @code{graphical},
11267: with a field @code{circle-radius}; it defines new methods for the
11268: selectors @code{draw} and @code{init} (@code{init} is defined in
11269: @code{object}, the parent class of @code{graphical}).
1.1 anton 11270:
1.78 anton 11271: Now we can create a circle in the dictionary with:
1.1 anton 11272:
1.78 anton 11273: @example
11274: 50 circle : my-circle
11275: @end example
1.21 crook 11276:
1.78 anton 11277: @noindent
11278: @code{:} invokes @code{init}, thus initializing the field
11279: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11280: with:
1.1 anton 11281:
1.78 anton 11282: @example
11283: 100 100 my-circle draw
11284: @end example
1.1 anton 11285:
1.78 anton 11286: @cindex selector invocation, restrictions
11287: @cindex class definition, restrictions
11288: Note: You can only invoke a selector if the receiving object belongs to
11289: the class where the selector was defined or one of its descendents;
11290: e.g., you can invoke @code{draw} only for objects belonging to
11291: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11292: mechanism will check if you try to invoke a selector that is not
11293: defined in this class hierarchy, so you'll get an error at compilation
11294: time.
1.1 anton 11295:
11296:
1.78 anton 11297: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11298: @subsubsection The @file{oof.fs} base class
11299: @cindex @file{oof.fs} base class
1.1 anton 11300:
1.78 anton 11301: When you define a class, you have to specify a parent class. So how do
11302: you start defining classes? There is one class available from the start:
11303: @code{object}. You have to use it as ancestor for all classes. It is the
11304: only class that has no parent. Classes are also objects, except that
11305: they don't have instance variables; class manipulation such as
11306: inheritance or changing definitions of a class is handled through
11307: selectors of the class @code{object}.
1.1 anton 11308:
1.78 anton 11309: @code{object} provides a number of selectors:
1.1 anton 11310:
1.78 anton 11311: @itemize @bullet
11312: @item
11313: @code{class} for subclassing, @code{definitions} to add definitions
11314: later on, and @code{class?} to get type informations (is the class a
11315: subclass of the class passed on the stack?).
1.1 anton 11316:
1.78 anton 11317: doc---object-class
11318: doc---object-definitions
11319: doc---object-class?
1.1 anton 11320:
11321:
1.26 crook 11322: @item
1.78 anton 11323: @code{init} and @code{dispose} as constructor and destructor of the
11324: object. @code{init} is invocated after the object's memory is allocated,
11325: while @code{dispose} also handles deallocation. Thus if you redefine
11326: @code{dispose}, you have to call the parent's dispose with @code{super
11327: dispose}, too.
11328:
11329: doc---object-init
11330: doc---object-dispose
11331:
1.1 anton 11332:
1.26 crook 11333: @item
1.78 anton 11334: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11335: @code{[]} to create named and unnamed objects and object arrays or
11336: object pointers.
11337:
11338: doc---object-new
11339: doc---object-new[]
11340: doc---object-:
11341: doc---object-ptr
11342: doc---object-asptr
11343: doc---object-[]
11344:
1.1 anton 11345:
1.26 crook 11346: @item
1.78 anton 11347: @code{::} and @code{super} for explicit scoping. You should use explicit
11348: scoping only for super classes or classes with the same set of instance
11349: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11350:
1.78 anton 11351: doc---object-::
11352: doc---object-super
1.21 crook 11353:
11354:
1.26 crook 11355: @item
1.78 anton 11356: @code{self} to get the address of the object
1.21 crook 11357:
1.78 anton 11358: doc---object-self
1.21 crook 11359:
11360:
1.78 anton 11361: @item
11362: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11363: pointers and instance defers.
1.21 crook 11364:
1.78 anton 11365: doc---object-bind
11366: doc---object-bound
11367: doc---object-link
11368: doc---object-is
1.21 crook 11369:
11370:
1.78 anton 11371: @item
11372: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11373: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11374:
1.78 anton 11375: doc---object-'
11376: doc---object-postpone
1.21 crook 11377:
11378:
1.78 anton 11379: @item
11380: @code{with} and @code{endwith} to select the active object from the
11381: stack, and enable its scope. Using @code{with} and @code{endwith}
11382: also allows you to create code using selector @code{postpone} without being
11383: trapped by the state-smart objects.
1.21 crook 11384:
1.78 anton 11385: doc---object-with
11386: doc---object-endwith
1.21 crook 11387:
11388:
1.78 anton 11389: @end itemize
1.21 crook 11390:
1.78 anton 11391: @node Class Declaration, Class Implementation, The OOF base class, OOF
11392: @subsubsection Class Declaration
11393: @cindex class declaration
1.21 crook 11394:
1.78 anton 11395: @itemize @bullet
11396: @item
11397: Instance variables
1.21 crook 11398:
1.78 anton 11399: doc---oof-var
1.21 crook 11400:
11401:
1.78 anton 11402: @item
11403: Object pointers
1.21 crook 11404:
1.78 anton 11405: doc---oof-ptr
11406: doc---oof-asptr
1.21 crook 11407:
11408:
1.78 anton 11409: @item
11410: Instance defers
1.21 crook 11411:
1.78 anton 11412: doc---oof-defer
1.21 crook 11413:
11414:
1.78 anton 11415: @item
11416: Method selectors
1.21 crook 11417:
1.78 anton 11418: doc---oof-early
11419: doc---oof-method
1.21 crook 11420:
11421:
1.78 anton 11422: @item
11423: Class-wide variables
1.21 crook 11424:
1.78 anton 11425: doc---oof-static
1.21 crook 11426:
11427:
1.78 anton 11428: @item
11429: End declaration
1.1 anton 11430:
1.78 anton 11431: doc---oof-how:
11432: doc---oof-class;
1.21 crook 11433:
11434:
1.78 anton 11435: @end itemize
1.21 crook 11436:
1.78 anton 11437: @c -------------------------------------------------------------
11438: @node Class Implementation, , Class Declaration, OOF
11439: @subsubsection Class Implementation
11440: @cindex class implementation
1.21 crook 11441:
1.78 anton 11442: @c -------------------------------------------------------------
11443: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11444: @subsection The @file{mini-oof.fs} model
11445: @cindex mini-oof
1.21 crook 11446:
1.78 anton 11447: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11448: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11449: and reduces to the bare minimum of features. This is based on a posting
11450: of Bernd Paysan in comp.lang.forth.
1.21 crook 11451:
1.78 anton 11452: @menu
11453: * Basic Mini-OOF Usage::
11454: * Mini-OOF Example::
11455: * Mini-OOF Implementation::
11456: @end menu
1.21 crook 11457:
1.78 anton 11458: @c -------------------------------------------------------------
11459: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11460: @subsubsection Basic @file{mini-oof.fs} Usage
11461: @cindex mini-oof usage
1.21 crook 11462:
1.78 anton 11463: There is a base class (@code{class}, which allocates one cell for the
11464: object pointer) plus seven other words: to define a method, a variable,
11465: a class; to end a class, to resolve binding, to allocate an object and
11466: to compile a class method.
11467: @comment TODO better description of the last one
1.26 crook 11468:
1.21 crook 11469:
1.78 anton 11470: doc-object
11471: doc-method
11472: doc-var
11473: doc-class
11474: doc-end-class
11475: doc-defines
11476: doc-new
11477: doc-::
1.21 crook 11478:
11479:
11480:
1.78 anton 11481: @c -------------------------------------------------------------
11482: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11483: @subsubsection Mini-OOF Example
11484: @cindex mini-oof example
1.1 anton 11485:
1.78 anton 11486: A short example shows how to use this package. This example, in slightly
11487: extended form, is supplied as @file{moof-exm.fs}
11488: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11489:
1.26 crook 11490: @example
1.78 anton 11491: object class
11492: method init
11493: method draw
11494: end-class graphical
1.26 crook 11495: @end example
1.20 pazsan 11496:
1.78 anton 11497: This code defines a class @code{graphical} with an
11498: operation @code{draw}. We can perform the operation
11499: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11500:
1.26 crook 11501: @example
1.78 anton 11502: 100 100 t-rex draw
1.26 crook 11503: @end example
1.12 anton 11504:
1.78 anton 11505: where @code{t-rex} is an object or object pointer, created with e.g.
11506: @code{graphical new Constant t-rex}.
1.12 anton 11507:
1.78 anton 11508: For concrete graphical objects, we define child classes of the
11509: class @code{graphical}, e.g.:
1.12 anton 11510:
1.26 crook 11511: @example
11512: graphical class
1.78 anton 11513: cell var circle-radius
11514: end-class circle \ "graphical" is the parent class
1.12 anton 11515:
1.78 anton 11516: :noname ( x y -- )
11517: circle-radius @@ draw-circle ; circle defines draw
11518: :noname ( r -- )
11519: circle-radius ! ; circle defines init
11520: @end example
1.12 anton 11521:
1.78 anton 11522: There is no implicit init method, so we have to define one. The creation
11523: code of the object now has to call init explicitely.
1.21 crook 11524:
1.78 anton 11525: @example
11526: circle new Constant my-circle
11527: 50 my-circle init
1.12 anton 11528: @end example
11529:
1.78 anton 11530: It is also possible to add a function to create named objects with
11531: automatic call of @code{init}, given that all objects have @code{init}
11532: on the same place:
1.38 anton 11533:
1.78 anton 11534: @example
11535: : new: ( .. o "name" -- )
11536: new dup Constant init ;
11537: 80 circle new: large-circle
11538: @end example
1.12 anton 11539:
1.78 anton 11540: We can draw this new circle at (100,100) with:
1.12 anton 11541:
1.78 anton 11542: @example
11543: 100 100 my-circle draw
11544: @end example
1.12 anton 11545:
1.78 anton 11546: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11547: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11548:
1.78 anton 11549: Object-oriented systems with late binding typically use a
11550: ``vtable''-approach: the first variable in each object is a pointer to a
11551: table, which contains the methods as function pointers. The vtable
11552: may also contain other information.
1.12 anton 11553:
1.79 anton 11554: So first, let's declare selectors:
1.37 anton 11555:
11556: @example
1.79 anton 11557: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11558: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11559: @end example
1.37 anton 11560:
1.79 anton 11561: During selector declaration, the number of selectors and instance
11562: variables is on the stack (in address units). @code{method} creates one
11563: selector and increments the selector number. To execute a selector, it
1.78 anton 11564: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11565: executes the method @i{xt} stored there. Each selector takes the object
11566: it is invoked with as top of stack parameter; it passes the parameters
11567: (including the object) unchanged to the appropriate method which should
1.78 anton 11568: consume that object.
1.37 anton 11569:
1.78 anton 11570: Now, we also have to declare instance variables
1.37 anton 11571:
1.78 anton 11572: @example
1.79 anton 11573: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11574: DOES> ( o -- addr ) @@ + ;
1.37 anton 11575: @end example
11576:
1.78 anton 11577: As before, a word is created with the current offset. Instance
11578: variables can have different sizes (cells, floats, doubles, chars), so
11579: all we do is take the size and add it to the offset. If your machine
11580: has alignment restrictions, put the proper @code{aligned} or
11581: @code{faligned} before the variable, to adjust the variable
11582: offset. That's why it is on the top of stack.
1.37 anton 11583:
1.78 anton 11584: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11585:
1.78 anton 11586: @example
11587: Create object 1 cells , 2 cells ,
1.79 anton 11588: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11589: @end example
1.12 anton 11590:
1.78 anton 11591: For inheritance, the vtable of the parent object has to be
11592: copied when a new, derived class is declared. This gives all the
11593: methods of the parent class, which can be overridden, though.
1.12 anton 11594:
1.78 anton 11595: @example
1.79 anton 11596: : end-class ( class selectors vars "name" -- )
1.78 anton 11597: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11598: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11599: @end example
1.12 anton 11600:
1.78 anton 11601: The first line creates the vtable, initialized with
11602: @code{noop}s. The second line is the inheritance mechanism, it
11603: copies the xts from the parent vtable.
1.12 anton 11604:
1.78 anton 11605: We still have no way to define new methods, let's do that now:
1.12 anton 11606:
1.26 crook 11607: @example
1.79 anton 11608: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11609: @end example
1.12 anton 11610:
1.78 anton 11611: To allocate a new object, we need a word, too:
1.12 anton 11612:
1.78 anton 11613: @example
11614: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11615: @end example
11616:
1.78 anton 11617: Sometimes derived classes want to access the method of the
11618: parent object. There are two ways to achieve this with Mini-OOF:
11619: first, you could use named words, and second, you could look up the
11620: vtable of the parent object.
1.12 anton 11621:
1.78 anton 11622: @example
11623: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11624: @end example
1.12 anton 11625:
11626:
1.78 anton 11627: Nothing can be more confusing than a good example, so here is
11628: one. First let's declare a text object (called
11629: @code{button}), that stores text and position:
1.12 anton 11630:
1.78 anton 11631: @example
11632: object class
11633: cell var text
11634: cell var len
11635: cell var x
11636: cell var y
11637: method init
11638: method draw
11639: end-class button
11640: @end example
1.12 anton 11641:
1.78 anton 11642: @noindent
11643: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11644:
1.26 crook 11645: @example
1.78 anton 11646: :noname ( o -- )
11647: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11648: button defines draw
11649: :noname ( addr u o -- )
11650: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11651: button defines init
1.26 crook 11652: @end example
1.12 anton 11653:
1.78 anton 11654: @noindent
11655: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11656: new data and no new selectors:
1.78 anton 11657:
11658: @example
11659: button class
11660: end-class bold-button
1.12 anton 11661:
1.78 anton 11662: : bold 27 emit ." [1m" ;
11663: : normal 27 emit ." [0m" ;
11664: @end example
1.1 anton 11665:
1.78 anton 11666: @noindent
11667: The class @code{bold-button} has a different draw method to
11668: @code{button}, but the new method is defined in terms of the draw method
11669: for @code{button}:
1.20 pazsan 11670:
1.78 anton 11671: @example
11672: :noname bold [ button :: draw ] normal ; bold-button defines draw
11673: @end example
1.21 crook 11674:
1.78 anton 11675: @noindent
1.79 anton 11676: Finally, create two objects and apply selectors:
1.21 crook 11677:
1.26 crook 11678: @example
1.78 anton 11679: button new Constant foo
11680: s" thin foo" foo init
11681: page
11682: foo draw
11683: bold-button new Constant bar
11684: s" fat bar" bar init
11685: 1 bar y !
11686: bar draw
1.26 crook 11687: @end example
1.21 crook 11688:
11689:
1.78 anton 11690: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11691: @subsection Comparison with other object models
11692: @cindex comparison of object models
11693: @cindex object models, comparison
11694:
11695: Many object-oriented Forth extensions have been proposed (@cite{A survey
11696: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11697: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11698: relation of the object models described here to two well-known and two
11699: closely-related (by the use of method maps) models. Andras Zsoter
11700: helped us with this section.
11701:
11702: @cindex Neon model
11703: The most popular model currently seems to be the Neon model (see
11704: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11705: 1997) by Andrew McKewan) but this model has a number of limitations
11706: @footnote{A longer version of this critique can be
11707: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11708: Dimensions, May 1997) by Anton Ertl.}:
11709:
11710: @itemize @bullet
11711: @item
11712: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11713: to pass objects on the stack.
1.21 crook 11714:
1.78 anton 11715: @item
11716: It requires that the selector parses the input stream (at
1.79 anton 11717: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11718: hard to find.
1.21 crook 11719:
1.78 anton 11720: @item
1.79 anton 11721: It allows using every selector on every object; this eliminates the
11722: need for interfaces, but makes it harder to create efficient
11723: implementations.
1.78 anton 11724: @end itemize
1.21 crook 11725:
1.78 anton 11726: @cindex Pountain's object-oriented model
11727: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11728: Press, London, 1987) by Dick Pountain. However, it is not really about
11729: object-oriented programming, because it hardly deals with late
11730: binding. Instead, it focuses on features like information hiding and
11731: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11732:
1.78 anton 11733: @cindex Zsoter's object-oriented model
1.79 anton 11734: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11735: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11736: describes a model that makes heavy use of an active object (like
11737: @code{this} in @file{objects.fs}): The active object is not only used
11738: for accessing all fields, but also specifies the receiving object of
11739: every selector invocation; you have to change the active object
11740: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11741: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11742: the method entry point is unnecessary with Zsoter's model, because the
11743: receiving object is the active object already. On the other hand, the
11744: explicit change is absolutely necessary in that model, because otherwise
11745: no one could ever change the active object. An ANS Forth implementation
11746: of this model is available through
11747: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11748:
1.78 anton 11749: @cindex @file{oof.fs}, differences to other models
11750: The @file{oof.fs} model combines information hiding and overloading
11751: resolution (by keeping names in various word lists) with object-oriented
11752: programming. It sets the active object implicitly on method entry, but
11753: also allows explicit changing (with @code{>o...o>} or with
11754: @code{with...endwith}). It uses parsing and state-smart objects and
11755: classes for resolving overloading and for early binding: the object or
11756: class parses the selector and determines the method from this. If the
11757: selector is not parsed by an object or class, it performs a call to the
11758: selector for the active object (late binding), like Zsoter's model.
11759: Fields are always accessed through the active object. The big
11760: disadvantage of this model is the parsing and the state-smartness, which
11761: reduces extensibility and increases the opportunities for subtle bugs;
11762: essentially, you are only safe if you never tick or @code{postpone} an
11763: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11764:
1.78 anton 11765: @cindex @file{mini-oof.fs}, differences to other models
11766: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11767: version of the @file{objects.fs} model, but syntactically it is a
11768: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11769:
11770:
1.78 anton 11771: @c -------------------------------------------------------------
1.150 anton 11772: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11773: @section Programming Tools
11774: @cindex programming tools
1.21 crook 11775:
1.78 anton 11776: @c !! move this and assembler down below OO stuff.
1.21 crook 11777:
1.78 anton 11778: @menu
1.150 anton 11779: * Examining:: Data and Code.
11780: * Forgetting words:: Usually before reloading.
1.78 anton 11781: * Debugging:: Simple and quick.
11782: * Assertions:: Making your programs self-checking.
11783: * Singlestep Debugger:: Executing your program word by word.
11784: @end menu
1.21 crook 11785:
1.78 anton 11786: @node Examining, Forgetting words, Programming Tools, Programming Tools
11787: @subsection Examining data and code
11788: @cindex examining data and code
11789: @cindex data examination
11790: @cindex code examination
1.44 crook 11791:
1.78 anton 11792: The following words inspect the stack non-destructively:
1.21 crook 11793:
1.78 anton 11794: doc-.s
11795: doc-f.s
1.158 anton 11796: doc-maxdepth-.s
1.44 crook 11797:
1.78 anton 11798: There is a word @code{.r} but it does @i{not} display the return stack!
11799: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11800:
1.78 anton 11801: doc-depth
11802: doc-fdepth
11803: doc-clearstack
1.124 anton 11804: doc-clearstacks
1.21 crook 11805:
1.78 anton 11806: The following words inspect memory.
1.21 crook 11807:
1.78 anton 11808: doc-?
11809: doc-dump
1.21 crook 11810:
1.78 anton 11811: And finally, @code{see} allows to inspect code:
1.21 crook 11812:
1.78 anton 11813: doc-see
11814: doc-xt-see
1.111 anton 11815: doc-simple-see
11816: doc-simple-see-range
1.182 anton 11817: doc-see-code
11818: doc-see-code-range
1.21 crook 11819:
1.78 anton 11820: @node Forgetting words, Debugging, Examining, Programming Tools
11821: @subsection Forgetting words
11822: @cindex words, forgetting
11823: @cindex forgeting words
1.21 crook 11824:
1.78 anton 11825: @c anton: other, maybe better places for this subsection: Defining Words;
11826: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11827:
1.78 anton 11828: Forth allows you to forget words (and everything that was alloted in the
11829: dictonary after them) in a LIFO manner.
1.21 crook 11830:
1.78 anton 11831: doc-marker
1.21 crook 11832:
1.78 anton 11833: The most common use of this feature is during progam development: when
11834: you change a source file, forget all the words it defined and load it
11835: again (since you also forget everything defined after the source file
11836: was loaded, you have to reload that, too). Note that effects like
11837: storing to variables and destroyed system words are not undone when you
11838: forget words. With a system like Gforth, that is fast enough at
11839: starting up and compiling, I find it more convenient to exit and restart
11840: Gforth, as this gives me a clean slate.
1.21 crook 11841:
1.78 anton 11842: Here's an example of using @code{marker} at the start of a source file
11843: that you are debugging; it ensures that you only ever have one copy of
11844: the file's definitions compiled at any time:
1.21 crook 11845:
1.78 anton 11846: @example
11847: [IFDEF] my-code
11848: my-code
11849: [ENDIF]
1.26 crook 11850:
1.78 anton 11851: marker my-code
11852: init-included-files
1.21 crook 11853:
1.78 anton 11854: \ .. definitions start here
11855: \ .
11856: \ .
11857: \ end
11858: @end example
1.21 crook 11859:
1.26 crook 11860:
1.78 anton 11861: @node Debugging, Assertions, Forgetting words, Programming Tools
11862: @subsection Debugging
11863: @cindex debugging
1.21 crook 11864:
1.78 anton 11865: Languages with a slow edit/compile/link/test development loop tend to
11866: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11867:
1.78 anton 11868: A much better (faster) way in fast-compiling languages is to add
11869: printing code at well-selected places, let the program run, look at
11870: the output, see where things went wrong, add more printing code, etc.,
11871: until the bug is found.
1.21 crook 11872:
1.78 anton 11873: The simple debugging aids provided in @file{debugs.fs}
11874: are meant to support this style of debugging.
1.21 crook 11875:
1.78 anton 11876: The word @code{~~} prints debugging information (by default the source
11877: location and the stack contents). It is easy to insert. If you use Emacs
11878: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11879: query-replace them with nothing). The deferred words
1.101 anton 11880: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11881: @code{~~}. The default source location output format works well with
11882: Emacs' compilation mode, so you can step through the program at the
11883: source level using @kbd{C-x `} (the advantage over a stepping debugger
11884: is that you can step in any direction and you know where the crash has
11885: happened or where the strange data has occurred).
1.21 crook 11886:
1.78 anton 11887: doc-~~
11888: doc-printdebugdata
1.101 anton 11889: doc-.debugline
1.21 crook 11890:
1.106 anton 11891: @cindex filenames in @code{~~} output
11892: @code{~~} (and assertions) will usually print the wrong file name if a
11893: marker is executed in the same file after their occurance. They will
11894: print @samp{*somewhere*} as file name if a marker is executed in the
11895: same file before their occurance.
11896:
11897:
1.78 anton 11898: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11899: @subsection Assertions
11900: @cindex assertions
1.21 crook 11901:
1.78 anton 11902: It is a good idea to make your programs self-checking, especially if you
11903: make an assumption that may become invalid during maintenance (for
11904: example, that a certain field of a data structure is never zero). Gforth
11905: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11906:
11907: @example
1.78 anton 11908: assert( @i{flag} )
1.26 crook 11909: @end example
11910:
1.78 anton 11911: The code between @code{assert(} and @code{)} should compute a flag, that
11912: should be true if everything is alright and false otherwise. It should
11913: not change anything else on the stack. The overall stack effect of the
11914: assertion is @code{( -- )}. E.g.
1.21 crook 11915:
1.26 crook 11916: @example
1.78 anton 11917: assert( 1 1 + 2 = ) \ what we learn in school
11918: assert( dup 0<> ) \ assert that the top of stack is not zero
11919: assert( false ) \ this code should not be reached
1.21 crook 11920: @end example
11921:
1.78 anton 11922: The need for assertions is different at different times. During
11923: debugging, we want more checking, in production we sometimes care more
11924: for speed. Therefore, assertions can be turned off, i.e., the assertion
11925: becomes a comment. Depending on the importance of an assertion and the
11926: time it takes to check it, you may want to turn off some assertions and
11927: keep others turned on. Gforth provides several levels of assertions for
11928: this purpose:
11929:
11930:
11931: doc-assert0(
11932: doc-assert1(
11933: doc-assert2(
11934: doc-assert3(
11935: doc-assert(
11936: doc-)
1.21 crook 11937:
11938:
1.78 anton 11939: The variable @code{assert-level} specifies the highest assertions that
11940: are turned on. I.e., at the default @code{assert-level} of one,
11941: @code{assert0(} and @code{assert1(} assertions perform checking, while
11942: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11943:
1.78 anton 11944: The value of @code{assert-level} is evaluated at compile-time, not at
11945: run-time. Therefore you cannot turn assertions on or off at run-time;
11946: you have to set the @code{assert-level} appropriately before compiling a
11947: piece of code. You can compile different pieces of code at different
11948: @code{assert-level}s (e.g., a trusted library at level 1 and
11949: newly-written code at level 3).
1.26 crook 11950:
11951:
1.78 anton 11952: doc-assert-level
1.26 crook 11953:
11954:
1.78 anton 11955: If an assertion fails, a message compatible with Emacs' compilation mode
11956: is produced and the execution is aborted (currently with @code{ABORT"}.
11957: If there is interest, we will introduce a special throw code. But if you
11958: intend to @code{catch} a specific condition, using @code{throw} is
11959: probably more appropriate than an assertion).
1.106 anton 11960:
11961: @cindex filenames in assertion output
11962: Assertions (and @code{~~}) will usually print the wrong file name if a
11963: marker is executed in the same file after their occurance. They will
11964: print @samp{*somewhere*} as file name if a marker is executed in the
11965: same file before their occurance.
1.44 crook 11966:
1.78 anton 11967: Definitions in ANS Forth for these assertion words are provided
11968: in @file{compat/assert.fs}.
1.26 crook 11969:
1.44 crook 11970:
1.78 anton 11971: @node Singlestep Debugger, , Assertions, Programming Tools
11972: @subsection Singlestep Debugger
11973: @cindex singlestep Debugger
11974: @cindex debugging Singlestep
1.44 crook 11975:
1.189 anton 11976: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 11977:
1.78 anton 11978: When you create a new word there's often the need to check whether it
11979: behaves correctly or not. You can do this by typing @code{dbg
11980: badword}. A debug session might look like this:
1.26 crook 11981:
1.78 anton 11982: @example
11983: : badword 0 DO i . LOOP ; ok
11984: 2 dbg badword
11985: : badword
11986: Scanning code...
1.44 crook 11987:
1.78 anton 11988: Nesting debugger ready!
1.44 crook 11989:
1.78 anton 11990: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11991: 400D4740 8049F68 DO -> [ 0 ]
11992: 400D4744 804A0C8 i -> [ 1 ] 00000
11993: 400D4748 400C5E60 . -> 0 [ 0 ]
11994: 400D474C 8049D0C LOOP -> [ 0 ]
11995: 400D4744 804A0C8 i -> [ 1 ] 00001
11996: 400D4748 400C5E60 . -> 1 [ 0 ]
11997: 400D474C 8049D0C LOOP -> [ 0 ]
11998: 400D4758 804B384 ; -> ok
11999: @end example
1.21 crook 12000:
1.78 anton 12001: Each line displayed is one step. You always have to hit return to
12002: execute the next word that is displayed. If you don't want to execute
12003: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12004: an overview what keys are available:
1.44 crook 12005:
1.78 anton 12006: @table @i
1.44 crook 12007:
1.78 anton 12008: @item @key{RET}
12009: Next; Execute the next word.
1.21 crook 12010:
1.78 anton 12011: @item n
12012: Nest; Single step through next word.
1.44 crook 12013:
1.78 anton 12014: @item u
12015: Unnest; Stop debugging and execute rest of word. If we got to this word
12016: with nest, continue debugging with the calling word.
1.44 crook 12017:
1.78 anton 12018: @item d
12019: Done; Stop debugging and execute rest.
1.21 crook 12020:
1.78 anton 12021: @item s
12022: Stop; Abort immediately.
1.44 crook 12023:
1.78 anton 12024: @end table
1.44 crook 12025:
1.78 anton 12026: Debugging large application with this mechanism is very difficult, because
12027: you have to nest very deeply into the program before the interesting part
12028: begins. This takes a lot of time.
1.26 crook 12029:
1.78 anton 12030: To do it more directly put a @code{BREAK:} command into your source code.
12031: When program execution reaches @code{BREAK:} the single step debugger is
12032: invoked and you have all the features described above.
1.44 crook 12033:
1.78 anton 12034: If you have more than one part to debug it is useful to know where the
12035: program has stopped at the moment. You can do this by the
12036: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12037: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12038:
1.26 crook 12039:
1.78 anton 12040: doc-dbg
12041: doc-break:
12042: doc-break"
1.44 crook 12043:
1.150 anton 12044: @c ------------------------------------------------------------
12045: @node C Interface, Assembler and Code Words, Programming Tools, Words
12046: @section C Interface
12047: @cindex C interface
12048: @cindex foreign language interface
12049: @cindex interface to C functions
12050:
1.178 anton 12051: Note that the C interface is not yet complete; callbacks are missing,
12052: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12053:
12054: @menu
12055: * Calling C Functions::
12056: * Declaring C Functions::
1.180 anton 12057: * Calling C function pointers::
1.150 anton 12058: * Callbacks::
1.178 anton 12059: * C interface internals::
1.155 anton 12060: * Low-Level C Interface Words::
1.150 anton 12061: @end menu
12062:
1.151 pazsan 12063: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12064: @subsection Calling C functions
1.155 anton 12065: @cindex C functions, calls to
12066: @cindex calling C functions
1.150 anton 12067:
1.151 pazsan 12068: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12069: can call it as follows: You push the arguments on the stack(s), and
12070: then call the word for the C function. The arguments have to be
12071: pushed in the same order as the arguments appear in the C
12072: documentation (i.e., the first argument is deepest on the stack).
12073: Integer and pointer arguments have to be pushed on the data stack,
12074: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12075: by the called C function.
1.150 anton 12076:
1.155 anton 12077: On returning from the C function, the return value, if any, resides on
12078: the appropriate stack: an integer return value is pushed on the data
12079: stack, an FP return value on the FP stack, and a void return value
12080: results in not pushing anything. Note that most C functions have a
12081: return value, even if that is often not used in C; in Forth, you have
12082: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12083:
1.177 anton 12084: The C interface automatically converts between the C type and the
12085: Forth type as necessary, on a best-effort basis (in some cases, there
12086: may be some loss).
1.150 anton 12087:
12088: As an example, consider the POSIX function @code{lseek()}:
12089:
12090: @example
12091: off_t lseek(int fd, off_t offset, int whence);
12092: @end example
12093:
12094: This function takes three integer arguments, and returns an integer
12095: argument, so a Forth call for setting the current file offset to the
12096: start of the file could look like this:
12097:
12098: @example
12099: fd @@ 0 SEEK_SET lseek -1 = if
12100: ... \ error handling
12101: then
12102: @end example
12103:
12104: You might be worried that an @code{off_t} does not fit into a cell, so
12105: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12106: of the return values. In that case, in your declaration of the
12107: function (@pxref{Declaring C Functions}) you should declare it to use
12108: double-cells for the off_t argument and return value, and maybe give
12109: the resulting Forth word a different name, like @code{dlseek}; the
12110: result could be called like this:
1.150 anton 12111:
12112: @example
12113: fd @@ 0. SEEK_SET dlseek -1. d= if
12114: ... \ error handling
12115: then
12116: @end example
12117:
12118: Passing and returning structs or unions is currently not supported by
12119: our interface@footnote{If you know the calling convention of your C
12120: compiler, you usually can call such functions in some way, but that
12121: way is usually not portable between platforms, and sometimes not even
12122: between C compilers.}.
12123:
1.177 anton 12124: Calling functions with a variable number of arguments (@emph{variadic}
12125: functions, e.g., @code{printf()}) is only supported by having you
12126: declare one function-calling word for each argument pattern, and
12127: calling the appropriate word for the desired pattern.
12128:
1.150 anton 12129:
1.155 anton 12130:
1.180 anton 12131: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12132: @subsection Declaring C Functions
1.155 anton 12133: @cindex C functions, declarations
12134: @cindex declaring C functions
1.150 anton 12135:
12136: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12137: it. The declaration consists of two parts:
12138:
12139: @table @b
12140:
12141: @item The C part
1.179 anton 12142: is the C declaration of the function, or more typically and portably,
12143: a C-style @code{#include} of a file that contains the declaration of
12144: the C function.
1.177 anton 12145:
12146: @item The Forth part
12147: declares the Forth types of the parameters and the Forth word name
12148: corresponding to the C function.
12149:
12150: @end table
12151:
12152: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12153: declarations are:
12154:
12155: @example
12156: \c #define _FILE_OFFSET_BITS 64
12157: \c #include <sys/types.h>
12158: \c #include <unistd.h>
12159: c-function lseek lseek n n n -- n
12160: c-function dlseek lseek n d n -- d
12161: @end example
12162:
1.178 anton 12163: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12164: of the line is ordinary C code. You can use as many lines of C
12165: declarations as you like, and they are visible for all further
12166: function declarations.
12167:
12168: The Forth part declares each interface word with @code{c-function},
12169: followed by the Forth name of the word, the C name of the called
12170: function, and the stack effect of the word. The stack effect contains
1.178 anton 12171: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12172: exactly one type for the return value. The possible types are:
12173:
12174: @table @code
12175:
12176: @item n
12177: single-cell integer
12178:
12179: @item a
12180: address (single-cell)
12181:
12182: @item d
12183: double-cell integer
12184:
12185: @item r
12186: floating-point value
12187:
12188: @item func
12189: C function pointer
12190:
12191: @item void
12192: no value (used as return type for void functions)
12193:
12194: @end table
12195:
12196: @cindex variadic C functions
12197:
12198: To deal with variadic C functions, you can declare one Forth word for
12199: every pattern you want to use, e.g.:
12200:
12201: @example
12202: \c #include <stdio.h>
12203: c-function printf-nr printf a n r -- n
12204: c-function printf-rn printf a r n -- n
12205: @end example
12206:
12207: Note that with C functions declared as variadic (or if you don't
12208: provide a prototype), the C interface has no C type to convert to, so
12209: no automatic conversion happens, which may lead to portability
12210: problems in some cases. In such cases you can perform the conversion
12211: explicitly on the C level, e.g., as follows:
12212:
12213: @example
1.178 anton 12214: \c #define printfll(s,ll) printf(s,(long long)ll)
12215: c-function printfll printfll a n -- n
1.177 anton 12216: @end example
12217:
12218: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12219: that casts (converts) the Forth single-cell integer into a
12220: C @code{long long} before calling @code{printf()}.
1.177 anton 12221:
12222: doc-\c
12223: doc-c-function
12224:
12225: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12226: dynamic linking. If these features are not available, there are
12227: other, less convenient and less portable C interfaces in @file{lib.fs}
12228: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12229: mostly incompatible with each other and with the documented C
12230: interface; you can find some examples for the @file{lib.fs} interface
12231: in @file{lib.fs}.
1.177 anton 12232:
12233:
1.180 anton 12234: @node Calling C function pointers, Callbacks, Declaring C Functions, C Interface
12235: @subsection Calling C function pointers from Forth
12236: @cindex C function pointers, calling from Forth
1.177 anton 12237:
1.180 anton 12238: If you come across a C function pointer (e.g., in some C-constructed
12239: structure) and want to call it from your Forth program, you can also
12240: use the features explained until now to achieve that, as follows:
1.150 anton 12241:
1.180 anton 12242: Let us assume that there is a C function pointer type @code{func1}
12243: defined in some header file @file{func1.h}, and you know that these
12244: functions take one integer argument and return an integer result; and
12245: you want to call functions through such pointers. Just define
1.155 anton 12246:
1.180 anton 12247: @example
12248: \c #include <func1.h>
12249: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12250: c-function call-func1 call_func1 n func -- n
12251: @end example
12252:
12253: and then you can call a function pointed to by, say @code{func1a} as
12254: follows:
12255:
12256: @example
12257: -5 func1a call-func1 .
12258: @end example
12259:
12260: In the C part, @code{call_func} is defined as a macro to avoid having
12261: to declare the exact parameter and return types, so the C compiler
12262: knows them from the declaration of @code{func1}.
12263:
12264: The Forth word @code{call-func1} is similar to @code{execute}, except
12265: that it takes a C @code{func1} pointer instead of a Forth execution
12266: token, and it is specific to @code{func1} pointers. For each type of
12267: function pointer you want to call from Forth, you have to define
12268: a separate calling word.
12269:
12270:
12271: @node Callbacks, C interface internals, Calling C function pointers, C Interface
1.150 anton 12272: @subsection Callbacks
1.155 anton 12273: @cindex Callback functions written in Forth
12274: @cindex C function pointers to Forth words
12275:
1.177 anton 12276: Callbacks are not yet supported by the documented C interface. You
12277: can use the undocumented @file{lib.fs} interface for callbacks.
12278:
1.155 anton 12279: In some cases you have to pass a function pointer to a C function,
12280: i.e., the library wants to call back to your application (and the
12281: pointed-to function is called a callback function). You can pass the
12282: address of an existing C function (that you get with @code{lib-sym},
12283: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12284: function, you probably want to define the function as a Forth word.
12285:
12286: @c I don't understand the existing callback interface from the example - anton
12287:
1.165 anton 12288:
12289: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12290: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12291: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12292: @c > > C-Funktionsadresse auf dem TOS).
12293: @c >
12294: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12295: @c > gesehen habe, wozu das gut ist.
12296: @c
12297: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12298: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12299: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12300: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12301: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12302: @c demselben Prototyp.
12303:
12304:
1.178 anton 12305: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12306: @subsection How the C interface works
12307:
12308: The documented C interface works by generating a C code out of the
12309: declarations.
12310:
12311: In particular, for every Forth word declared with @code{c-function},
12312: it generates a wrapper function in C that takes the Forth data from
12313: the Forth stacks, and calls the target C function with these data as
12314: arguments. The C compiler then performs an implicit conversion
12315: between the Forth type from the stack, and the C type for the
12316: parameter, which is given by the C function prototype. After the C
12317: function returns, the return value is likewise implicitly converted to
12318: a Forth type and written back on the stack.
12319:
12320: The @code{\c} lines are literally included in the C code (but without
12321: the @code{\c}), and provide the necessary declarations so that the C
12322: compiler knows the C types and has enough information to perform the
12323: conversion.
12324:
12325: These wrapper functions are eventually compiled and dynamically linked
12326: into Gforth, and then they can be called.
12327:
12328:
1.178 anton 12329: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12330: @subsection Low-Level C Interface Words
1.44 crook 12331:
1.155 anton 12332: doc-open-lib
12333: doc-lib-sym
1.177 anton 12334: doc-call-c
1.26 crook 12335:
1.78 anton 12336: @c -------------------------------------------------------------
1.150 anton 12337: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12338: @section Assembler and Code Words
12339: @cindex assembler
12340: @cindex code words
1.44 crook 12341:
1.78 anton 12342: @menu
12343: * Code and ;code::
12344: * Common Assembler:: Assembler Syntax
12345: * Common Disassembler::
12346: * 386 Assembler:: Deviations and special cases
12347: * Alpha Assembler:: Deviations and special cases
12348: * MIPS assembler:: Deviations and special cases
1.161 anton 12349: * PowerPC assembler:: Deviations and special cases
1.193 ! dvdkhlng 12350: * ARM Assembler:: Deviations and special cases
1.78 anton 12351: * Other assemblers:: How to write them
12352: @end menu
1.21 crook 12353:
1.78 anton 12354: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12355: @subsection @code{Code} and @code{;code}
1.26 crook 12356:
1.78 anton 12357: Gforth provides some words for defining primitives (words written in
12358: machine code), and for defining the machine-code equivalent of
12359: @code{DOES>}-based defining words. However, the machine-independent
12360: nature of Gforth poses a few problems: First of all, Gforth runs on
12361: several architectures, so it can provide no standard assembler. What's
12362: worse is that the register allocation not only depends on the processor,
12363: but also on the @code{gcc} version and options used.
1.44 crook 12364:
1.78 anton 12365: The words that Gforth offers encapsulate some system dependences (e.g.,
12366: the header structure), so a system-independent assembler may be used in
12367: Gforth. If you do not have an assembler, you can compile machine code
12368: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12369: because these words emit stuff in @i{data} space; it works because
12370: Gforth has unified code/data spaces. Assembler isn't likely to be
12371: portable anyway.}.
1.21 crook 12372:
1.44 crook 12373:
1.78 anton 12374: doc-assembler
12375: doc-init-asm
12376: doc-code
12377: doc-end-code
12378: doc-;code
12379: doc-flush-icache
1.44 crook 12380:
1.21 crook 12381:
1.78 anton 12382: If @code{flush-icache} does not work correctly, @code{code} words
12383: etc. will not work (reliably), either.
1.44 crook 12384:
1.78 anton 12385: The typical usage of these @code{code} words can be shown most easily by
12386: analogy to the equivalent high-level defining words:
1.44 crook 12387:
1.78 anton 12388: @example
12389: : foo code foo
12390: <high-level Forth words> <assembler>
12391: ; end-code
12392:
12393: : bar : bar
12394: <high-level Forth words> <high-level Forth words>
12395: CREATE CREATE
12396: <high-level Forth words> <high-level Forth words>
12397: DOES> ;code
12398: <high-level Forth words> <assembler>
12399: ; end-code
12400: @end example
1.21 crook 12401:
1.78 anton 12402: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12403:
1.78 anton 12404: @cindex registers of the inner interpreter
12405: In the assembly code you will want to refer to the inner interpreter's
12406: registers (e.g., the data stack pointer) and you may want to use other
12407: registers for temporary storage. Unfortunately, the register allocation
12408: is installation-dependent.
1.44 crook 12409:
1.78 anton 12410: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12411: (return stack pointer) may be in different places in @code{gforth} and
12412: @code{gforth-fast}, or different installations. This means that you
12413: cannot write a @code{NEXT} routine that works reliably on both versions
12414: or different installations; so for doing @code{NEXT}, I recommend
12415: jumping to @code{' noop >code-address}, which contains nothing but a
12416: @code{NEXT}.
1.21 crook 12417:
1.78 anton 12418: For general accesses to the inner interpreter's registers, the easiest
12419: solution is to use explicit register declarations (@pxref{Explicit Reg
12420: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12421: all of the inner interpreter's registers: You have to compile Gforth
12422: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12423: the appropriate declarations must be present in the @code{machine.h}
12424: file (see @code{mips.h} for an example; you can find a full list of all
12425: declarable register symbols with @code{grep register engine.c}). If you
12426: give explicit registers to all variables that are declared at the
12427: beginning of @code{engine()}, you should be able to use the other
12428: caller-saved registers for temporary storage. Alternatively, you can use
12429: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12430: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12431: reserve a register (however, this restriction on register allocation may
12432: slow Gforth significantly).
1.44 crook 12433:
1.78 anton 12434: If this solution is not viable (e.g., because @code{gcc} does not allow
12435: you to explicitly declare all the registers you need), you have to find
12436: out by looking at the code where the inner interpreter's registers
12437: reside and which registers can be used for temporary storage. You can
12438: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12439:
1.78 anton 12440: In any case, it is good practice to abstract your assembly code from the
12441: actual register allocation. E.g., if the data stack pointer resides in
12442: register @code{$17}, create an alias for this register called @code{sp},
12443: and use that in your assembly code.
1.21 crook 12444:
1.78 anton 12445: @cindex code words, portable
12446: Another option for implementing normal and defining words efficiently
12447: is to add the desired functionality to the source of Gforth. For normal
12448: words you just have to edit @file{primitives} (@pxref{Automatic
12449: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12450: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12451: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12452:
1.78 anton 12453: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12454: @subsection Common Assembler
1.44 crook 12455:
1.78 anton 12456: The assemblers in Gforth generally use a postfix syntax, i.e., the
12457: instruction name follows the operands.
1.21 crook 12458:
1.78 anton 12459: The operands are passed in the usual order (the same that is used in the
12460: manual of the architecture). Since they all are Forth words, they have
12461: to be separated by spaces; you can also use Forth words to compute the
12462: operands.
1.44 crook 12463:
1.78 anton 12464: The instruction names usually end with a @code{,}. This makes it easier
12465: to visually separate instructions if you put several of them on one
12466: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12467:
1.78 anton 12468: Registers are usually specified by number; e.g., (decimal) @code{11}
12469: specifies registers R11 and F11 on the Alpha architecture (which one,
12470: depends on the instruction). The usual names are also available, e.g.,
12471: @code{s2} for R11 on Alpha.
1.21 crook 12472:
1.78 anton 12473: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12474: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12475: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12476: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12477: conditions are specified in a way specific to each assembler.
1.1 anton 12478:
1.78 anton 12479: Note that the register assignments of the Gforth engine can change
12480: between Gforth versions, or even between different compilations of the
12481: same Gforth version (e.g., if you use a different GCC version). So if
12482: you want to refer to Gforth's registers (e.g., the stack pointer or
12483: TOS), I recommend defining your own words for refering to these
12484: registers, and using them later on; then you can easily adapt to a
12485: changed register assignment. The stability of the register assignment
12486: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12487:
1.100 anton 12488: The most common use of these registers is to dispatch to the next word
12489: (the @code{next} routine). A portable way to do this is to jump to
12490: @code{' noop >code-address} (of course, this is less efficient than
12491: integrating the @code{next} code and scheduling it well).
1.1 anton 12492:
1.96 anton 12493: Another difference between Gforth version is that the top of stack is
12494: kept in memory in @code{gforth} and, on most platforms, in a register in
12495: @code{gforth-fast}.
12496:
1.78 anton 12497: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12498: @subsection Common Disassembler
1.127 anton 12499: @cindex disassembler, general
12500: @cindex gdb disassembler
1.1 anton 12501:
1.78 anton 12502: You can disassemble a @code{code} word with @code{see}
12503: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12504:
1.127 anton 12505: doc-discode
1.44 crook 12506:
1.127 anton 12507: There are two kinds of disassembler for Gforth: The Forth disassembler
12508: (available on some CPUs) and the gdb disassembler (available on
12509: platforms with @command{gdb} and @command{mktemp}). If both are
12510: available, the Forth disassembler is used by default. If you prefer
12511: the gdb disassembler, say
12512:
12513: @example
12514: ' disasm-gdb is discode
12515: @end example
12516:
12517: If neither is available, @code{discode} performs @code{dump}.
12518:
12519: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12520: assembler (i.e., same syntax, etc.). It also includes additional
12521: information in comments. In particular, the address of the instruction
12522: is given in a comment before the instruction.
1.1 anton 12523:
1.127 anton 12524: The gdb disassembler produces output in the same format as the gdb
12525: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12526: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12527: the 386 and AMD64 architectures).
12528:
1.78 anton 12529: @code{See} may display more or less than the actual code of the word,
12530: because the recognition of the end of the code is unreliable. You can
1.127 anton 12531: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12532: the code word is not immediately followed by a named word. If you have
1.116 anton 12533: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12534: to ensure that the end is recognized.
1.21 crook 12535:
1.78 anton 12536: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12537: @subsection 386 Assembler
1.44 crook 12538:
1.78 anton 12539: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12540: available under GPL, and originally part of bigFORTH.
1.21 crook 12541:
1.78 anton 12542: The 386 disassembler included in Gforth was written by Andrew McKewan
12543: and is in the public domain.
1.21 crook 12544:
1.91 anton 12545: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12546:
1.78 anton 12547: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12548:
1.78 anton 12549: The assembler includes all instruction of the Athlon, i.e. 486 core
12550: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12551: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12552: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12553:
1.78 anton 12554: There are several prefixes to switch between different operation sizes,
12555: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12556: double-word accesses. Addressing modes can be switched with @code{.wa}
12557: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12558: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12559:
1.78 anton 12560: For floating point operations, the prefixes are @code{.fs} (IEEE
12561: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12562: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12563:
1.78 anton 12564: The MMX opcodes don't have size prefixes, they are spelled out like in
12565: the Intel assembler. Instead of move from and to memory, there are
12566: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12567:
1.78 anton 12568: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12569: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12570: e.g., @code{3 #}. Here are some examples of addressing modes in various
12571: syntaxes:
1.21 crook 12572:
1.26 crook 12573: @example
1.91 anton 12574: Gforth Intel (NASM) AT&T (gas) Name
12575: .w ax ax %ax register (16 bit)
12576: ax eax %eax register (32 bit)
12577: 3 # offset 3 $3 immediate
12578: 1000 #) byte ptr 1000 1000 displacement
12579: bx ) [ebx] (%ebx) base
12580: 100 di d) 100[edi] 100(%edi) base+displacement
12581: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12582: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12583: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12584: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12585: @end example
12586:
12587: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12588: @code{DI)} to enforce 32-bit displacement fields (useful for
12589: later patching).
1.21 crook 12590:
1.78 anton 12591: Some example of instructions are:
1.1 anton 12592:
12593: @example
1.78 anton 12594: ax bx mov \ move ebx,eax
12595: 3 # ax mov \ mov eax,3
1.137 pazsan 12596: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12597: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12598: .w ax bx mov \ mov bx,ax
1.1 anton 12599: @end example
12600:
1.78 anton 12601: The following forms are supported for binary instructions:
1.1 anton 12602:
12603: @example
1.78 anton 12604: <reg> <reg> <inst>
12605: <n> # <reg> <inst>
12606: <mem> <reg> <inst>
12607: <reg> <mem> <inst>
1.136 pazsan 12608: <n> # <mem> <inst>
1.1 anton 12609: @end example
12610:
1.136 pazsan 12611: The shift/rotate syntax is:
1.1 anton 12612:
1.26 crook 12613: @example
1.78 anton 12614: <reg/mem> 1 # shl \ shortens to shift without immediate
12615: <reg/mem> 4 # shl
12616: <reg/mem> cl shl
1.26 crook 12617: @end example
1.1 anton 12618:
1.78 anton 12619: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12620: the byte version.
1.1 anton 12621:
1.78 anton 12622: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12623: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12624: pc < >= <= >}. (Note that most of these words shadow some Forth words
12625: when @code{assembler} is in front of @code{forth} in the search path,
12626: e.g., in @code{code} words). Currently the control structure words use
12627: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12628: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12629:
1.78 anton 12630: Here is an example of a @code{code} word (assumes that the stack pointer
12631: is in esi and the TOS is in ebx):
1.21 crook 12632:
1.26 crook 12633: @example
1.78 anton 12634: code my+ ( n1 n2 -- n )
12635: 4 si D) bx add
12636: 4 # si add
12637: Next
12638: end-code
1.26 crook 12639: @end example
1.21 crook 12640:
1.161 anton 12641:
1.78 anton 12642: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12643: @subsection Alpha Assembler
1.21 crook 12644:
1.78 anton 12645: The Alpha assembler and disassembler were originally written by Bernd
12646: Thallner.
1.26 crook 12647:
1.78 anton 12648: The register names @code{a0}--@code{a5} are not available to avoid
12649: shadowing hex numbers.
1.2 jwilke 12650:
1.78 anton 12651: Immediate forms of arithmetic instructions are distinguished by a
12652: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12653: does not count as arithmetic instruction).
1.2 jwilke 12654:
1.78 anton 12655: You have to specify all operands to an instruction, even those that
12656: other assemblers consider optional, e.g., the destination register for
12657: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12658:
1.78 anton 12659: You can specify conditions for @code{if,} by removing the first @code{b}
12660: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12661:
1.26 crook 12662: @example
1.78 anton 12663: 11 fgt if, \ if F11>0e
12664: ...
12665: endif,
1.26 crook 12666: @end example
1.2 jwilke 12667:
1.78 anton 12668: @code{fbgt,} gives @code{fgt}.
12669:
1.161 anton 12670: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12671: @subsection MIPS assembler
1.2 jwilke 12672:
1.78 anton 12673: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12674:
1.78 anton 12675: Currently the assembler and disassembler only cover the MIPS-I
12676: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12677:
1.78 anton 12678: The register names @code{$a0}--@code{$a3} are not available to avoid
12679: shadowing hex numbers.
1.2 jwilke 12680:
1.78 anton 12681: Because there is no way to distinguish registers from immediate values,
12682: you have to explicitly use the immediate forms of instructions, i.e.,
12683: @code{addiu,}, not just @code{addu,} (@command{as} does this
12684: implicitly).
1.2 jwilke 12685:
1.78 anton 12686: If the architecture manual specifies several formats for the instruction
12687: (e.g., for @code{jalr,}), you usually have to use the one with more
12688: arguments (i.e., two for @code{jalr,}). When in doubt, see
12689: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12690:
1.78 anton 12691: Branches and jumps in the MIPS architecture have a delay slot. You have
12692: to fill it yourself (the simplest way is to use @code{nop,}), the
12693: assembler does not do it for you (unlike @command{as}). Even
12694: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12695: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12696: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12697:
1.78 anton 12698: Note that you must not put branches, jumps, or @code{li,} into the delay
12699: slot: @code{li,} may expand to several instructions, and control flow
12700: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12701:
1.78 anton 12702: For branches the argument specifying the target is a relative address;
12703: You have to add the address of the delay slot to get the absolute
12704: address.
1.1 anton 12705:
1.78 anton 12706: The MIPS architecture also has load delay slots and restrictions on
12707: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12708: yourself to satisfy these restrictions, the assembler does not do it for
12709: you.
1.1 anton 12710:
1.78 anton 12711: You can specify the conditions for @code{if,} etc. by taking a
12712: conditional branch and leaving away the @code{b} at the start and the
12713: @code{,} at the end. E.g.,
1.1 anton 12714:
1.26 crook 12715: @example
1.78 anton 12716: 4 5 eq if,
12717: ... \ do something if $4 equals $5
12718: then,
1.26 crook 12719: @end example
1.1 anton 12720:
1.161 anton 12721:
1.193 ! dvdkhlng 12722: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12723: @subsection PowerPC assembler
12724:
1.162 anton 12725: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12726: Revucky.
12727:
1.162 anton 12728: This assembler does not follow the convention of ending mnemonic names
12729: with a ``,'', so some mnemonic names shadow regular Forth words (in
12730: particular: @code{and or xor fabs}); so if you want to use the Forth
12731: words, you have to make them visible first, e.g., with @code{also
12732: forth}.
12733:
1.161 anton 12734: Registers are referred to by their number, e.g., @code{9} means the
12735: integer register 9 or the FP register 9 (depending on the
12736: instruction).
12737:
12738: Because there is no way to distinguish registers from immediate values,
12739: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12740: @code{addi,}, not just @code{add,}.
1.161 anton 12741:
1.162 anton 12742: The assembler and disassembler usually support the most general form
1.161 anton 12743: of an instruction, but usually not the shorter forms (especially for
12744: branches).
12745:
12746:
1.193 ! dvdkhlng 12747: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
! 12748: @subsection ARM Assembler
1.161 anton 12749:
1.193 ! dvdkhlng 12750: The ARM assembler included in Gforth was written from scratch by David
! 12751: Kuehling.
! 12752:
! 12753: The assembler includes all instruction of ARM architecture version 4,
! 12754: but does not (yet) have support for Thumb instructions. It also lacks
! 12755: support for any co-processors.
! 12756:
! 12757: The assembler uses a postfix syntax with the target operand specified
! 12758: last. For load/store instructions the last operand will be the
! 12759: register(s) to be loaded from/stored to.
! 12760:
! 12761: Registers are specified by their names @code{r0} through @code{r15},
! 12762: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
! 12763: @code{fp} provided for convenience. Note that @code{ip} means intra
! 12764: procedure call scratch register (@code{r12}) and does not refer to the
! 12765: instruction pointer.
! 12766:
! 12767: Condition codes can be specified anywhere in the instruction, but will
! 12768: be most readable if specified just in front of the mnemonic. The 'S'
! 12769: flag is not a separate word, but encoded into instruction mnemonics,
! 12770: ie. just use @code{adds,} instead of @code{add,} if you want the
! 12771: status register to be updated.
! 12772:
! 12773: The following table lists the syntax of operands for general
! 12774: instructions:
! 12775:
! 12776: @example
! 12777: Gforth normal assembler description
! 12778: 123 # #123 immediate
! 12779: r12 r12 register
! 12780: r12 4 #LSL r12, LSL #4 shift left by immediate
! 12781: r12 r1 #LSL r12, LSL r1 shift left by register
! 12782: r12 4 #LSR r12, LSR #4 shift right by immediate
! 12783: r12 r1 #LSR r12, LSR r1 shift right by register
! 12784: r12 4 #ASR r12, ASR #4 arithmetic shift right
! 12785: r12 r1 #ASR r12, ASR r1 ... by register
! 12786: r12 4 #ROR r12, ROR #4 rotate right by immediate
! 12787: r12 r1 #ROR r12, ROR r1 ... by register
! 12788: r12 RRX r12, RRX rotate right with extend by 1
! 12789: @end example
! 12790:
! 12791: Memory operand syntax is listed in this table:
! 12792:
! 12793: @example
! 12794: Gforth normal assembler description
! 12795: r4 ] [r4] register
! 12796: r4 4 #] [r4, #+4] register with immediate offset
! 12797: r4 -4 #] [r4, #-4] with negative offset
! 12798: r4 r1 +] [r4, +r1] register with register offset
! 12799: r4 r1 -] [r4, -r1] with negated register offset
! 12800: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
! 12801: r4 4 #]! [r4, #+4]! immediate preincrement
! 12802: r4 r1 +]! [r4, +r1]! register preincrement
! 12803: r4 r1 -]! [r4, +r1]! register predecrement
! 12804: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
! 12805: r4 -4 ]# [r4], #-4 immediate postdecrement
! 12806: r4 r1 ]+ [r4], r1 register postincrement
! 12807: r4 r1 ]- [r4], -r1 register postdecrement
! 12808: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
! 12809: ' xyz >body [#] xyz PC-relative addressing
! 12810: @end example
! 12811:
! 12812: Register lists for load/store multiple instructions are started and
! 12813: terminated by using the words @code{@{} and @code{@}}
! 12814: respectivly. Between braces, register names can be listed one by one,
! 12815: or register ranges can be formed by using the postfix operator
! 12816: @code{r-r}. The @code{^} flag is not encoded in the register list
! 12817: operand, but instead directly encoded into the instruction mnemonic,
! 12818: ie. use @code{^ldm,} and @code{^stm,}.
! 12819:
! 12820: Addressing modes for load/store multiple are not encoded as
! 12821: instruction suffixes, but instead specified after the register that
! 12822: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
! 12823: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
! 12824:
! 12825: The following table gives some examples:
! 12826:
! 12827: @example
! 12828: Gforth normal assembler
! 12829: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
! 12830: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
! 12831: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
! 12832: @end example
! 12833:
! 12834: Conditions for control structure words are specified in front of a
! 12835: word:
! 12836:
! 12837: @example
! 12838: r1 r2 cmp, \ compare r1 and r2
! 12839: eq if, \ equal?
! 12840: ... \ code executed if r1 == r2
! 12841: then,
! 12842: @end example
! 12843:
! 12844: Here is an example of a @code{code} word (assumes that the stack
! 12845: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
! 12846: clobbered):
! 12847:
! 12848: @example
! 12849: code my+ ( n1 n2 -- n3 )
! 12850: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
! 12851: r2 r3 r3 add, \ r3 = n2+n1
! 12852: r9 -4 #]! r3 str, \ push r3
! 12853: next,
! 12854: end-code
! 12855: @end example
! 12856:
! 12857: Look at @file{arch/arm/asm-example.fs} for more examples.
! 12858:
! 12859: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 12860: @subsection Other assemblers
12861:
12862: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12863: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12864: an assembler already. If you are writing them from scratch, please use
12865: a similar syntax style as the one we use (i.e., postfix, commas at the
12866: end of the instruction names, @pxref{Common Assembler}); make the output
12867: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12868: similar to the style we used.
12869:
12870: Hints on implementation: The most important part is to have a good test
12871: suite that contains all instructions. Once you have that, the rest is
12872: easy. For actual coding you can take a look at
12873: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12874: the assembler and disassembler, avoiding redundancy and some potential
12875: bugs. You can also look at that file (and @pxref{Advanced does> usage
12876: example}) to get ideas how to factor a disassembler.
12877:
12878: Start with the disassembler, because it's easier to reuse data from the
12879: disassembler for the assembler than the other way round.
1.1 anton 12880:
1.78 anton 12881: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12882: how simple it can be.
1.1 anton 12883:
1.161 anton 12884:
12885:
12886:
1.78 anton 12887: @c -------------------------------------------------------------
12888: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12889: @section Threading Words
12890: @cindex threading words
1.1 anton 12891:
1.78 anton 12892: @cindex code address
12893: These words provide access to code addresses and other threading stuff
12894: in Gforth (and, possibly, other interpretive Forths). It more or less
12895: abstracts away the differences between direct and indirect threading
12896: (and, for direct threading, the machine dependences). However, at
12897: present this wordset is still incomplete. It is also pretty low-level;
12898: some day it will hopefully be made unnecessary by an internals wordset
12899: that abstracts implementation details away completely.
1.1 anton 12900:
1.78 anton 12901: The terminology used here stems from indirect threaded Forth systems; in
12902: such a system, the XT of a word is represented by the CFA (code field
12903: address) of a word; the CFA points to a cell that contains the code
12904: address. The code address is the address of some machine code that
12905: performs the run-time action of invoking the word (e.g., the
12906: @code{dovar:} routine pushes the address of the body of the word (a
12907: variable) on the stack
12908: ).
1.1 anton 12909:
1.78 anton 12910: @cindex code address
12911: @cindex code field address
12912: In an indirect threaded Forth, you can get the code address of @i{name}
12913: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12914: >code-address}, independent of the threading method.
1.1 anton 12915:
1.78 anton 12916: doc-threading-method
12917: doc->code-address
12918: doc-code-address!
1.1 anton 12919:
1.78 anton 12920: @cindex @code{does>}-handler
12921: @cindex @code{does>}-code
12922: For a word defined with @code{DOES>}, the code address usually points to
12923: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12924: routine (in Gforth on some platforms, it can also point to the dodoes
12925: routine itself). What you are typically interested in, though, is
12926: whether a word is a @code{DOES>}-defined word, and what Forth code it
12927: executes; @code{>does-code} tells you that.
1.1 anton 12928:
1.78 anton 12929: doc->does-code
1.1 anton 12930:
1.78 anton 12931: To create a @code{DOES>}-defined word with the following basic words,
12932: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12933: @code{/does-handler} aus behind you have to place your executable Forth
12934: code. Finally you have to create a word and modify its behaviour with
12935: @code{does-handler!}.
1.1 anton 12936:
1.78 anton 12937: doc-does-code!
12938: doc-does-handler!
12939: doc-/does-handler
1.1 anton 12940:
1.78 anton 12941: The code addresses produced by various defining words are produced by
12942: the following words:
1.1 anton 12943:
1.78 anton 12944: doc-docol:
12945: doc-docon:
12946: doc-dovar:
12947: doc-douser:
12948: doc-dodefer:
12949: doc-dofield:
1.1 anton 12950:
1.99 anton 12951: @cindex definer
12952: The following two words generalize @code{>code-address},
12953: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12954:
12955: doc->definer
12956: doc-definer!
12957:
1.26 crook 12958: @c -------------------------------------------------------------
1.78 anton 12959: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12960: @section Passing Commands to the Operating System
12961: @cindex operating system - passing commands
12962: @cindex shell commands
12963:
12964: Gforth allows you to pass an arbitrary string to the host operating
12965: system shell (if such a thing exists) for execution.
12966:
12967: doc-sh
12968: doc-system
12969: doc-$?
1.23 crook 12970: doc-getenv
1.44 crook 12971:
1.26 crook 12972: @c -------------------------------------------------------------
1.47 crook 12973: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
12974: @section Keeping track of Time
12975: @cindex time-related words
12976:
12977: doc-ms
12978: doc-time&date
1.79 anton 12979: doc-utime
12980: doc-cputime
1.47 crook 12981:
12982:
12983: @c -------------------------------------------------------------
12984: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 12985: @section Miscellaneous Words
12986: @cindex miscellaneous words
12987:
1.29 crook 12988: @comment TODO find homes for these
12989:
1.26 crook 12990: These section lists the ANS Forth words that are not documented
1.21 crook 12991: elsewhere in this manual. Ultimately, they all need proper homes.
12992:
1.68 anton 12993: doc-quit
1.44 crook 12994:
1.26 crook 12995: The following ANS Forth words are not currently supported by Gforth
1.27 crook 12996: (@pxref{ANS conformance}):
1.21 crook 12997:
12998: @code{EDITOR}
12999: @code{EMIT?}
13000: @code{FORGET}
13001:
1.24 anton 13002: @c ******************************************************************
13003: @node Error messages, Tools, Words, Top
13004: @chapter Error messages
13005: @cindex error messages
13006: @cindex backtrace
13007:
13008: A typical Gforth error message looks like this:
13009:
13010: @example
1.86 anton 13011: in file included from \evaluated string/:-1
1.24 anton 13012: in file included from ./yyy.fs:1
13013: ./xxx.fs:4: Invalid memory address
1.134 anton 13014: >>>bar<<<
1.79 anton 13015: Backtrace:
1.25 anton 13016: $400E664C @@
13017: $400E6664 foo
1.24 anton 13018: @end example
13019:
13020: The message identifying the error is @code{Invalid memory address}. The
13021: error happened when text-interpreting line 4 of the file
13022: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13023: word on the line where the error happened, is pointed out (with
1.134 anton 13024: @code{>>>} and @code{<<<}).
1.24 anton 13025:
13026: The file containing the error was included in line 1 of @file{./yyy.fs},
13027: and @file{yyy.fs} was included from a non-file (in this case, by giving
13028: @file{yyy.fs} as command-line parameter to Gforth).
13029:
13030: At the end of the error message you find a return stack dump that can be
13031: interpreted as a backtrace (possibly empty). On top you find the top of
13032: the return stack when the @code{throw} happened, and at the bottom you
13033: find the return stack entry just above the return stack of the topmost
13034: text interpreter.
13035:
13036: To the right of most return stack entries you see a guess for the word
13037: that pushed that return stack entry as its return address. This gives a
13038: backtrace. In our case we see that @code{bar} called @code{foo}, and
13039: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13040: address} exception).
13041:
13042: Note that the backtrace is not perfect: We don't know which return stack
13043: entries are return addresses (so we may get false positives); and in
13044: some cases (e.g., for @code{abort"}) we cannot determine from the return
13045: address the word that pushed the return address, so for some return
13046: addresses you see no names in the return stack dump.
1.25 anton 13047:
13048: @cindex @code{catch} and backtraces
13049: The return stack dump represents the return stack at the time when a
13050: specific @code{throw} was executed. In programs that make use of
13051: @code{catch}, it is not necessarily clear which @code{throw} should be
13052: used for the return stack dump (e.g., consider one @code{throw} that
13053: indicates an error, which is caught, and during recovery another error
1.160 anton 13054: happens; which @code{throw} should be used for the stack dump?).
13055: Gforth presents the return stack dump for the first @code{throw} after
13056: the last executed (not returned-to) @code{catch} or @code{nothrow};
13057: this works well in the usual case. To get the right backtrace, you
13058: usually want to insert @code{nothrow} or @code{['] false catch drop}
13059: after a @code{catch} if the error is not rethrown.
1.25 anton 13060:
13061: @cindex @code{gforth-fast} and backtraces
13062: @cindex @code{gforth-fast}, difference from @code{gforth}
13063: @cindex backtraces with @code{gforth-fast}
13064: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13065: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13066: from primitives (e.g., invalid memory address, stack empty etc.);
13067: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13068: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13069: exception caused by a primitive in @code{gforth-fast}, you will
13070: typically see no return stack dump at all; however, if the exception is
13071: caught by @code{catch} (e.g., for restoring some state), and then
13072: @code{throw}n again, the return stack dump will be for the first such
13073: @code{throw}.
1.2 jwilke 13074:
1.5 anton 13075: @c ******************************************************************
1.24 anton 13076: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13077: @chapter Tools
13078:
13079: @menu
13080: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13081: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13082: @end menu
13083:
13084: See also @ref{Emacs and Gforth}.
13085:
1.126 pazsan 13086: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13087: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13088: @cindex @file{ans-report.fs}
13089: @cindex report the words used in your program
13090: @cindex words used in your program
13091:
13092: If you want to label a Forth program as ANS Forth Program, you must
13093: document which wordsets the program uses; for extension wordsets, it is
13094: helpful to list the words the program requires from these wordsets
13095: (because Forth systems are allowed to provide only some words of them).
13096:
13097: The @file{ans-report.fs} tool makes it easy for you to determine which
13098: words from which wordset and which non-ANS words your application
13099: uses. You simply have to include @file{ans-report.fs} before loading the
13100: program you want to check. After loading your program, you can get the
13101: report with @code{print-ans-report}. A typical use is to run this as
13102: batch job like this:
13103: @example
13104: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13105: @end example
13106:
13107: The output looks like this (for @file{compat/control.fs}):
13108: @example
13109: The program uses the following words
13110: from CORE :
13111: : POSTPONE THEN ; immediate ?dup IF 0=
13112: from BLOCK-EXT :
13113: \
13114: from FILE :
13115: (
13116: @end example
13117:
13118: @subsection Caveats
13119:
13120: Note that @file{ans-report.fs} just checks which words are used, not whether
13121: they are used in an ANS Forth conforming way!
13122:
13123: Some words are defined in several wordsets in the
13124: standard. @file{ans-report.fs} reports them for only one of the
13125: wordsets, and not necessarily the one you expect. It depends on usage
13126: which wordset is the right one to specify. E.g., if you only use the
13127: compilation semantics of @code{S"}, it is a Core word; if you also use
13128: its interpretation semantics, it is a File word.
1.124 anton 13129:
13130:
1.127 anton 13131: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13132: @section Stack depth changes during interpretation
13133: @cindex @file{depth-changes.fs}
13134: @cindex depth changes during interpretation
13135: @cindex stack depth changes during interpretation
13136: @cindex items on the stack after interpretation
13137:
13138: Sometimes you notice that, after loading a file, there are items left
13139: on the stack. The tool @file{depth-changes.fs} helps you find out
13140: quickly where in the file these stack items are coming from.
13141:
13142: The simplest way of using @file{depth-changes.fs} is to include it
13143: before the file(s) you want to check, e.g.:
13144:
13145: @example
13146: gforth depth-changes.fs my-file.fs
13147: @end example
13148:
13149: This will compare the stack depths of the data and FP stack at every
13150: empty line (in interpretation state) against these depths at the last
13151: empty line (in interpretation state). If the depths are not equal,
13152: the position in the file and the stack contents are printed with
13153: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13154: change has occured in the paragraph of non-empty lines before the
13155: indicated line. It is a good idea to leave an empty line at the end
13156: of the file, so the last paragraph is checked, too.
13157:
13158: Checking only at empty lines usually works well, but sometimes you
13159: have big blocks of non-empty lines (e.g., when building a big table),
13160: and you want to know where in this block the stack depth changed. You
13161: can check all interpreted lines with
13162:
13163: @example
13164: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13165: @end example
13166:
13167: This checks the stack depth at every end-of-line. So the depth change
13168: occured in the line reported by the @code{~~} (not in the line
13169: before).
13170:
13171: Note that, while this offers better accuracy in indicating where the
13172: stack depth changes, it will often report many intentional stack depth
13173: changes (e.g., when an interpreted computation stretches across
13174: several lines). You can suppress the checking of some lines by
13175: putting backslashes at the end of these lines (not followed by white
13176: space), and using
13177:
13178: @example
13179: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13180: @end example
1.1 anton 13181:
13182: @c ******************************************************************
1.65 anton 13183: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13184: @chapter ANS conformance
13185: @cindex ANS conformance of Gforth
13186:
13187: To the best of our knowledge, Gforth is an
13188:
13189: ANS Forth System
13190: @itemize @bullet
13191: @item providing the Core Extensions word set
13192: @item providing the Block word set
13193: @item providing the Block Extensions word set
13194: @item providing the Double-Number word set
13195: @item providing the Double-Number Extensions word set
13196: @item providing the Exception word set
13197: @item providing the Exception Extensions word set
13198: @item providing the Facility word set
1.40 anton 13199: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13200: @item providing the File Access word set
13201: @item providing the File Access Extensions word set
13202: @item providing the Floating-Point word set
13203: @item providing the Floating-Point Extensions word set
13204: @item providing the Locals word set
13205: @item providing the Locals Extensions word set
13206: @item providing the Memory-Allocation word set
13207: @item providing the Memory-Allocation Extensions word set (that one's easy)
13208: @item providing the Programming-Tools word set
13209: @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
13210: @item providing the Search-Order word set
13211: @item providing the Search-Order Extensions word set
13212: @item providing the String word set
13213: @item providing the String Extensions word set (another easy one)
13214: @end itemize
13215:
1.118 anton 13216: Gforth has the following environmental restrictions:
13217:
13218: @cindex environmental restrictions
13219: @itemize @bullet
13220: @item
13221: While processing the OS command line, if an exception is not caught,
13222: Gforth exits with a non-zero exit code instyead of performing QUIT.
13223:
13224: @item
13225: When an @code{throw} is performed after a @code{query}, Gforth does not
13226: allways restore the input source specification in effect at the
13227: corresponding catch.
13228:
13229: @end itemize
13230:
13231:
1.1 anton 13232: @cindex system documentation
13233: In addition, ANS Forth systems are required to document certain
13234: implementation choices. This chapter tries to meet these
13235: requirements. In many cases it gives a way to ask the system for the
13236: information instead of providing the information directly, in
13237: particular, if the information depends on the processor, the operating
13238: system or the installation options chosen, or if they are likely to
13239: change during the maintenance of Gforth.
13240:
13241: @comment The framework for the rest has been taken from pfe.
13242:
13243: @menu
13244: * The Core Words::
13245: * The optional Block word set::
13246: * The optional Double Number word set::
13247: * The optional Exception word set::
13248: * The optional Facility word set::
13249: * The optional File-Access word set::
13250: * The optional Floating-Point word set::
13251: * The optional Locals word set::
13252: * The optional Memory-Allocation word set::
13253: * The optional Programming-Tools word set::
13254: * The optional Search-Order word set::
13255: @end menu
13256:
13257:
13258: @c =====================================================================
13259: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13260: @comment node-name, next, previous, up
13261: @section The Core Words
13262: @c =====================================================================
13263: @cindex core words, system documentation
13264: @cindex system documentation, core words
13265:
13266: @menu
13267: * core-idef:: Implementation Defined Options
13268: * core-ambcond:: Ambiguous Conditions
13269: * core-other:: Other System Documentation
13270: @end menu
13271:
13272: @c ---------------------------------------------------------------------
13273: @node core-idef, core-ambcond, The Core Words, The Core Words
13274: @subsection Implementation Defined Options
13275: @c ---------------------------------------------------------------------
13276: @cindex core words, implementation-defined options
13277: @cindex implementation-defined options, core words
13278:
13279:
13280: @table @i
13281: @item (Cell) aligned addresses:
13282: @cindex cell-aligned addresses
13283: @cindex aligned addresses
13284: processor-dependent. Gforth's alignment words perform natural alignment
13285: (e.g., an address aligned for a datum of size 8 is divisible by
13286: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13287:
13288: @item @code{EMIT} and non-graphic characters:
13289: @cindex @code{EMIT} and non-graphic characters
13290: @cindex non-graphic characters and @code{EMIT}
13291: The character is output using the C library function (actually, macro)
13292: @code{putc}.
13293:
13294: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13295: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13296: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13297: @cindex @code{ACCEPT}, editing
13298: @cindex @code{EXPECT}, editing
13299: This is modeled on the GNU readline library (@pxref{Readline
13300: Interaction, , Command Line Editing, readline, The GNU Readline
13301: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13302: producing a full word completion every time you type it (instead of
1.28 crook 13303: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13304:
13305: @item character set:
13306: @cindex character set
13307: The character set of your computer and display device. Gforth is
13308: 8-bit-clean (but some other component in your system may make trouble).
13309:
13310: @item Character-aligned address requirements:
13311: @cindex character-aligned address requirements
13312: installation-dependent. Currently a character is represented by a C
13313: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13314: (Comments on that requested).
13315:
13316: @item character-set extensions and matching of names:
13317: @cindex character-set extensions and matching of names
1.26 crook 13318: @cindex case-sensitivity for name lookup
13319: @cindex name lookup, case-sensitivity
13320: @cindex locale and case-sensitivity
1.21 crook 13321: Any character except the ASCII NUL character can be used in a
1.1 anton 13322: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13323: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13324: function is probably influenced by the locale. E.g., the @code{C} locale
13325: does not know about accents and umlauts, so they are matched
13326: case-sensitively in that locale. For portability reasons it is best to
13327: write programs such that they work in the @code{C} locale. Then one can
13328: use libraries written by a Polish programmer (who might use words
13329: containing ISO Latin-2 encoded characters) and by a French programmer
13330: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13331: funny results for some of the words (which ones, depends on the font you
13332: are using)). Also, the locale you prefer may not be available in other
13333: operating systems. Hopefully, Unicode will solve these problems one day.
13334:
13335: @item conditions under which control characters match a space delimiter:
13336: @cindex space delimiters
13337: @cindex control characters as delimiters
1.117 anton 13338: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13339: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13340: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13341: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13342: interpreter (aka text interpreter) by default, treats all white-space
13343: characters as delimiters.
13344:
1.26 crook 13345: @item format of the control-flow stack:
13346: @cindex control-flow stack, format
13347: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13348: stack item in cells is given by the constant @code{cs-item-size}. At the
13349: time of this writing, an item consists of a (pointer to a) locals list
13350: (third), an address in the code (second), and a tag for identifying the
13351: item (TOS). The following tags are used: @code{defstart},
13352: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13353: @code{scopestart}.
13354:
13355: @item conversion of digits > 35
13356: @cindex digits > 35
13357: The characters @code{[\]^_'} are the digits with the decimal value
13358: 36@minus{}41. There is no way to input many of the larger digits.
13359:
13360: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13361: @cindex @code{EXPECT}, display after end of input
13362: @cindex @code{ACCEPT}, display after end of input
13363: The cursor is moved to the end of the entered string. If the input is
13364: terminated using the @kbd{Return} key, a space is typed.
13365:
13366: @item exception abort sequence of @code{ABORT"}:
13367: @cindex exception abort sequence of @code{ABORT"}
13368: @cindex @code{ABORT"}, exception abort sequence
13369: The error string is stored into the variable @code{"error} and a
13370: @code{-2 throw} is performed.
13371:
13372: @item input line terminator:
13373: @cindex input line terminator
13374: @cindex line terminator on input
1.26 crook 13375: @cindex newline character on input
1.1 anton 13376: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13377: lines. One of these characters is typically produced when you type the
13378: @kbd{Enter} or @kbd{Return} key.
13379:
13380: @item maximum size of a counted string:
13381: @cindex maximum size of a counted string
13382: @cindex counted string, maximum size
13383: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13384: on all platforms, but this may change.
1.1 anton 13385:
13386: @item maximum size of a parsed string:
13387: @cindex maximum size of a parsed string
13388: @cindex parsed string, maximum size
13389: Given by the constant @code{/line}. Currently 255 characters.
13390:
13391: @item maximum size of a definition name, in characters:
13392: @cindex maximum size of a definition name, in characters
13393: @cindex name, maximum length
1.113 anton 13394: MAXU/8
1.1 anton 13395:
13396: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13397: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13398: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13399: MAXU/8
1.1 anton 13400:
13401: @item method of selecting the user input device:
13402: @cindex user input device, method of selecting
13403: The user input device is the standard input. There is currently no way to
13404: change it from within Gforth. However, the input can typically be
13405: redirected in the command line that starts Gforth.
13406:
13407: @item method of selecting the user output device:
13408: @cindex user output device, method of selecting
13409: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13410: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13411: output when the user output device is a terminal, otherwise the output
13412: is buffered.
1.1 anton 13413:
13414: @item methods of dictionary compilation:
13415: What are we expected to document here?
13416:
13417: @item number of bits in one address unit:
13418: @cindex number of bits in one address unit
13419: @cindex address unit, size in bits
13420: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13421: platforms.
1.1 anton 13422:
13423: @item number representation and arithmetic:
13424: @cindex number representation and arithmetic
1.79 anton 13425: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13426:
13427: @item ranges for integer types:
13428: @cindex ranges for integer types
13429: @cindex integer types, ranges
13430: Installation-dependent. Make environmental queries for @code{MAX-N},
13431: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13432: unsigned (and positive) types is 0. The lower bound for signed types on
13433: two's complement and one's complement machines machines can be computed
13434: by adding 1 to the upper bound.
13435:
13436: @item read-only data space regions:
13437: @cindex read-only data space regions
13438: @cindex data-space, read-only regions
13439: The whole Forth data space is writable.
13440:
13441: @item size of buffer at @code{WORD}:
13442: @cindex size of buffer at @code{WORD}
13443: @cindex @code{WORD} buffer size
13444: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13445: shared with the pictured numeric output string. If overwriting
13446: @code{PAD} is acceptable, it is as large as the remaining dictionary
13447: space, although only as much can be sensibly used as fits in a counted
13448: string.
13449:
13450: @item size of one cell in address units:
13451: @cindex cell size
13452: @code{1 cells .}.
13453:
13454: @item size of one character in address units:
13455: @cindex char size
1.79 anton 13456: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13457:
13458: @item size of the keyboard terminal buffer:
13459: @cindex size of the keyboard terminal buffer
13460: @cindex terminal buffer, size
13461: Varies. You can determine the size at a specific time using @code{lp@@
13462: tib - .}. It is shared with the locals stack and TIBs of files that
13463: include the current file. You can change the amount of space for TIBs
13464: and locals stack at Gforth startup with the command line option
13465: @code{-l}.
13466:
13467: @item size of the pictured numeric output buffer:
13468: @cindex size of the pictured numeric output buffer
13469: @cindex pictured numeric output buffer, size
13470: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13471: shared with @code{WORD}.
13472:
13473: @item size of the scratch area returned by @code{PAD}:
13474: @cindex size of the scratch area returned by @code{PAD}
13475: @cindex @code{PAD} size
13476: The remainder of dictionary space. @code{unused pad here - - .}.
13477:
13478: @item system case-sensitivity characteristics:
13479: @cindex case-sensitivity characteristics
1.26 crook 13480: Dictionary searches are case-insensitive (except in
1.1 anton 13481: @code{TABLE}s). However, as explained above under @i{character-set
13482: extensions}, the matching for non-ASCII characters is determined by the
13483: locale you are using. In the default @code{C} locale all non-ASCII
13484: characters are matched case-sensitively.
13485:
13486: @item system prompt:
13487: @cindex system prompt
13488: @cindex prompt
13489: @code{ ok} in interpret state, @code{ compiled} in compile state.
13490:
13491: @item division rounding:
13492: @cindex division rounding
1.166 anton 13493: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13494: division (with the default installation of Gforth). You can check
13495: this with @code{s" floored" environment? drop .}. If you write
13496: programs that need a specific division rounding, best use
13497: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13498:
13499: @item values of @code{STATE} when true:
13500: @cindex @code{STATE} values
13501: -1.
13502:
13503: @item values returned after arithmetic overflow:
13504: On two's complement machines, arithmetic is performed modulo
13505: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13506: arithmetic (with appropriate mapping for signed types). Division by
13507: zero typically results in a @code{-55 throw} (Floating-point
13508: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13509: division overflow can result in these throws, or in @code{-11 throw};
13510: in @code{gforth-fast} division overflow and divide by zero may also
13511: result in returning bogus results without producing an exception.
1.1 anton 13512:
13513: @item whether the current definition can be found after @t{DOES>}:
13514: @cindex @t{DOES>}, visibility of current definition
13515: No.
13516:
13517: @end table
13518:
13519: @c ---------------------------------------------------------------------
13520: @node core-ambcond, core-other, core-idef, The Core Words
13521: @subsection Ambiguous conditions
13522: @c ---------------------------------------------------------------------
13523: @cindex core words, ambiguous conditions
13524: @cindex ambiguous conditions, core words
13525:
13526: @table @i
13527:
13528: @item a name is neither a word nor a number:
13529: @cindex name not found
1.26 crook 13530: @cindex undefined word
1.80 anton 13531: @code{-13 throw} (Undefined word).
1.1 anton 13532:
13533: @item a definition name exceeds the maximum length allowed:
1.26 crook 13534: @cindex word name too long
1.1 anton 13535: @code{-19 throw} (Word name too long)
13536:
13537: @item addressing a region not inside the various data spaces of the forth system:
13538: @cindex Invalid memory address
1.32 anton 13539: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13540: typically readable. Accessing other addresses gives results dependent on
13541: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13542: address).
13543:
13544: @item argument type incompatible with parameter:
1.26 crook 13545: @cindex argument type mismatch
1.1 anton 13546: This is usually not caught. Some words perform checks, e.g., the control
13547: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13548: mismatch).
13549:
13550: @item attempting to obtain the execution token of a word with undefined execution semantics:
13551: @cindex Interpreting a compile-only word, for @code{'} etc.
13552: @cindex execution token of words with undefined execution semantics
13553: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13554: get an execution token for @code{compile-only-error} (which performs a
13555: @code{-14 throw} when executed).
13556:
13557: @item dividing by zero:
13558: @cindex dividing by zero
13559: @cindex floating point unidentified fault, integer division
1.80 anton 13560: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13561: zero); on other systems, this typically results in a @code{-55 throw}
13562: (Floating-point unidentified fault).
1.1 anton 13563:
13564: @item insufficient data stack or return stack space:
13565: @cindex insufficient data stack or return stack space
13566: @cindex stack overflow
1.26 crook 13567: @cindex address alignment exception, stack overflow
1.1 anton 13568: @cindex Invalid memory address, stack overflow
13569: Depending on the operating system, the installation, and the invocation
13570: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13571: it is not checked. If it is checked, you typically get a @code{-3 throw}
13572: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13573: throw} (Invalid memory address) (depending on the platform and how you
13574: achieved the overflow) as soon as the overflow happens. If it is not
13575: checked, overflows typically result in mysterious illegal memory
13576: accesses, producing @code{-9 throw} (Invalid memory address) or
13577: @code{-23 throw} (Address alignment exception); they might also destroy
13578: the internal data structure of @code{ALLOCATE} and friends, resulting in
13579: various errors in these words.
1.1 anton 13580:
13581: @item insufficient space for loop control parameters:
13582: @cindex insufficient space for loop control parameters
1.80 anton 13583: Like other return stack overflows.
1.1 anton 13584:
13585: @item insufficient space in the dictionary:
13586: @cindex insufficient space in the dictionary
13587: @cindex dictionary overflow
1.12 anton 13588: If you try to allot (either directly with @code{allot}, or indirectly
13589: with @code{,}, @code{create} etc.) more memory than available in the
13590: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13591: to access memory beyond the end of the dictionary, the results are
13592: similar to stack overflows.
1.1 anton 13593:
13594: @item interpreting a word with undefined interpretation semantics:
13595: @cindex interpreting a word with undefined interpretation semantics
13596: @cindex Interpreting a compile-only word
13597: For some words, we have defined interpretation semantics. For the
13598: others: @code{-14 throw} (Interpreting a compile-only word).
13599:
13600: @item modifying the contents of the input buffer or a string literal:
13601: @cindex modifying the contents of the input buffer or a string literal
13602: These are located in writable memory and can be modified.
13603:
13604: @item overflow of the pictured numeric output string:
13605: @cindex overflow of the pictured numeric output string
13606: @cindex pictured numeric output string, overflow
1.24 anton 13607: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13608:
13609: @item parsed string overflow:
13610: @cindex parsed string overflow
13611: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13612:
13613: @item producing a result out of range:
13614: @cindex result out of range
13615: On two's complement machines, arithmetic is performed modulo
13616: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13617: arithmetic (with appropriate mapping for signed types). Division by
13618: zero typically results in a @code{-10 throw} (divide by zero) or
13619: @code{-55 throw} (floating point unidentified fault). Overflow on
13620: division may result in these errors or in @code{-11 throw} (result out
13621: of range). @code{Gforth-fast} may silently produce bogus results on
13622: division overflow or division by zero. @code{Convert} and
1.24 anton 13623: @code{>number} currently overflow silently.
1.1 anton 13624:
13625: @item reading from an empty data or return stack:
13626: @cindex stack empty
13627: @cindex stack underflow
1.24 anton 13628: @cindex return stack underflow
1.1 anton 13629: The data stack is checked by the outer (aka text) interpreter after
13630: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13631: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13632: depending on operating system, installation, and invocation. If they are
13633: caught by a check, they typically result in @code{-4 throw} (Stack
13634: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13635: (Invalid memory address), depending on the platform and which stack
13636: underflows and by how much. Note that even if the system uses checking
13637: (through the MMU), your program may have to underflow by a significant
13638: number of stack items to trigger the reaction (the reason for this is
13639: that the MMU, and therefore the checking, works with a page-size
13640: granularity). If there is no checking, the symptoms resulting from an
13641: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13642: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13643: (Invalid memory address) and Illegal Instruction (typically @code{-260
13644: throw}).
1.1 anton 13645:
13646: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13647: @cindex unexpected end of the input buffer
13648: @cindex zero-length string as a name
13649: @cindex Attempt to use zero-length string as a name
13650: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13651: use zero-length string as a name). Words like @code{'} probably will not
13652: find what they search. Note that it is possible to create zero-length
13653: names with @code{nextname} (should it not?).
13654:
13655: @item @code{>IN} greater than input buffer:
13656: @cindex @code{>IN} greater than input buffer
13657: The next invocation of a parsing word returns a string with length 0.
13658:
13659: @item @code{RECURSE} appears after @code{DOES>}:
13660: @cindex @code{RECURSE} appears after @code{DOES>}
13661: Compiles a recursive call to the defining word, not to the defined word.
13662:
13663: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13664: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13665: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13666: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13667: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13668: the end of the file was reached), its source-id may be
13669: reused. Therefore, restoring an input source specification referencing a
13670: closed file may lead to unpredictable results instead of a @code{-12
13671: THROW}.
13672:
13673: In the future, Gforth may be able to restore input source specifications
13674: from other than the current input source.
13675:
13676: @item data space containing definitions gets de-allocated:
13677: @cindex data space containing definitions gets de-allocated
13678: Deallocation with @code{allot} is not checked. This typically results in
13679: memory access faults or execution of illegal instructions.
13680:
13681: @item data space read/write with incorrect alignment:
13682: @cindex data space read/write with incorrect alignment
13683: @cindex alignment faults
1.26 crook 13684: @cindex address alignment exception
1.1 anton 13685: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13686: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13687: alignment turned on, incorrect alignment results in a @code{-9 throw}
13688: (Invalid memory address). There are reportedly some processors with
1.12 anton 13689: alignment restrictions that do not report violations.
1.1 anton 13690:
13691: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13692: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13693: Like other alignment errors.
13694:
13695: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13696: Like other stack underflows.
13697:
13698: @item loop control parameters not available:
13699: @cindex loop control parameters not available
13700: Not checked. The counted loop words simply assume that the top of return
13701: stack items are loop control parameters and behave accordingly.
13702:
13703: @item most recent definition does not have a name (@code{IMMEDIATE}):
13704: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13705: @cindex last word was headerless
13706: @code{abort" last word was headerless"}.
13707:
13708: @item name not defined by @code{VALUE} used by @code{TO}:
13709: @cindex name not defined by @code{VALUE} used by @code{TO}
13710: @cindex @code{TO} on non-@code{VALUE}s
13711: @cindex Invalid name argument, @code{TO}
13712: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13713: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13714:
13715: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13716: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13717: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13718: @code{-13 throw} (Undefined word)
13719:
13720: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13721: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13722: Gforth behaves as if they were of the same type. I.e., you can predict
13723: the behaviour by interpreting all parameters as, e.g., signed.
13724:
13725: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13726: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13727: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13728: compilation semantics of @code{TO}.
13729:
13730: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13731: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13732: @cindex @code{WORD}, string overflow
13733: Not checked. The string will be ok, but the count will, of course,
13734: contain only the least significant bits of the length.
13735:
13736: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13737: @cindex @code{LSHIFT}, large shift counts
13738: @cindex @code{RSHIFT}, large shift counts
13739: Processor-dependent. Typical behaviours are returning 0 and using only
13740: the low bits of the shift count.
13741:
13742: @item word not defined via @code{CREATE}:
13743: @cindex @code{>BODY} of non-@code{CREATE}d words
13744: @code{>BODY} produces the PFA of the word no matter how it was defined.
13745:
13746: @cindex @code{DOES>} of non-@code{CREATE}d words
13747: @code{DOES>} changes the execution semantics of the last defined word no
13748: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13749: @code{CREATE , DOES>}.
13750:
13751: @item words improperly used outside @code{<#} and @code{#>}:
13752: Not checked. As usual, you can expect memory faults.
13753:
13754: @end table
13755:
13756:
13757: @c ---------------------------------------------------------------------
13758: @node core-other, , core-ambcond, The Core Words
13759: @subsection Other system documentation
13760: @c ---------------------------------------------------------------------
13761: @cindex other system documentation, core words
13762: @cindex core words, other system documentation
13763:
13764: @table @i
13765: @item nonstandard words using @code{PAD}:
13766: @cindex @code{PAD} use by nonstandard words
13767: None.
13768:
13769: @item operator's terminal facilities available:
13770: @cindex operator's terminal facilities available
1.80 anton 13771: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13772: and you can give commands to Gforth interactively. The actual facilities
13773: available depend on how you invoke Gforth.
13774:
13775: @item program data space available:
13776: @cindex program data space available
13777: @cindex data space available
13778: @code{UNUSED .} gives the remaining dictionary space. The total
13779: dictionary space can be specified with the @code{-m} switch
13780: (@pxref{Invoking Gforth}) when Gforth starts up.
13781:
13782: @item return stack space available:
13783: @cindex return stack space available
13784: You can compute the total return stack space in cells with
13785: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13786: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13787:
13788: @item stack space available:
13789: @cindex stack space available
13790: You can compute the total data stack space in cells with
13791: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13792: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13793:
13794: @item system dictionary space required, in address units:
13795: @cindex system dictionary space required, in address units
13796: Type @code{here forthstart - .} after startup. At the time of this
13797: writing, this gives 80080 (bytes) on a 32-bit system.
13798: @end table
13799:
13800:
13801: @c =====================================================================
13802: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13803: @section The optional Block word set
13804: @c =====================================================================
13805: @cindex system documentation, block words
13806: @cindex block words, system documentation
13807:
13808: @menu
13809: * block-idef:: Implementation Defined Options
13810: * block-ambcond:: Ambiguous Conditions
13811: * block-other:: Other System Documentation
13812: @end menu
13813:
13814:
13815: @c ---------------------------------------------------------------------
13816: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13817: @subsection Implementation Defined Options
13818: @c ---------------------------------------------------------------------
13819: @cindex implementation-defined options, block words
13820: @cindex block words, implementation-defined options
13821:
13822: @table @i
13823: @item the format for display by @code{LIST}:
13824: @cindex @code{LIST} display format
13825: First the screen number is displayed, then 16 lines of 64 characters,
13826: each line preceded by the line number.
13827:
13828: @item the length of a line affected by @code{\}:
13829: @cindex length of a line affected by @code{\}
13830: @cindex @code{\}, line length in blocks
13831: 64 characters.
13832: @end table
13833:
13834:
13835: @c ---------------------------------------------------------------------
13836: @node block-ambcond, block-other, block-idef, The optional Block word set
13837: @subsection Ambiguous conditions
13838: @c ---------------------------------------------------------------------
13839: @cindex block words, ambiguous conditions
13840: @cindex ambiguous conditions, block words
13841:
13842: @table @i
13843: @item correct block read was not possible:
13844: @cindex block read not possible
13845: Typically results in a @code{throw} of some OS-derived value (between
13846: -512 and -2048). If the blocks file was just not long enough, blanks are
13847: supplied for the missing portion.
13848:
13849: @item I/O exception in block transfer:
13850: @cindex I/O exception in block transfer
13851: @cindex block transfer, I/O exception
13852: Typically results in a @code{throw} of some OS-derived value (between
13853: -512 and -2048).
13854:
13855: @item invalid block number:
13856: @cindex invalid block number
13857: @cindex block number invalid
13858: @code{-35 throw} (Invalid block number)
13859:
13860: @item a program directly alters the contents of @code{BLK}:
13861: @cindex @code{BLK}, altering @code{BLK}
13862: The input stream is switched to that other block, at the same
13863: position. If the storing to @code{BLK} happens when interpreting
13864: non-block input, the system will get quite confused when the block ends.
13865:
13866: @item no current block buffer for @code{UPDATE}:
13867: @cindex @code{UPDATE}, no current block buffer
13868: @code{UPDATE} has no effect.
13869:
13870: @end table
13871:
13872: @c ---------------------------------------------------------------------
13873: @node block-other, , block-ambcond, The optional Block word set
13874: @subsection Other system documentation
13875: @c ---------------------------------------------------------------------
13876: @cindex other system documentation, block words
13877: @cindex block words, other system documentation
13878:
13879: @table @i
13880: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13881: No restrictions (yet).
13882:
13883: @item the number of blocks available for source and data:
13884: depends on your disk space.
13885:
13886: @end table
13887:
13888:
13889: @c =====================================================================
13890: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13891: @section The optional Double Number word set
13892: @c =====================================================================
13893: @cindex system documentation, double words
13894: @cindex double words, system documentation
13895:
13896: @menu
13897: * double-ambcond:: Ambiguous Conditions
13898: @end menu
13899:
13900:
13901: @c ---------------------------------------------------------------------
13902: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13903: @subsection Ambiguous conditions
13904: @c ---------------------------------------------------------------------
13905: @cindex double words, ambiguous conditions
13906: @cindex ambiguous conditions, double words
13907:
13908: @table @i
1.29 crook 13909: @item @i{d} outside of range of @i{n} in @code{D>S}:
13910: @cindex @code{D>S}, @i{d} out of range of @i{n}
13911: The least significant cell of @i{d} is produced.
1.1 anton 13912:
13913: @end table
13914:
13915:
13916: @c =====================================================================
13917: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13918: @section The optional Exception word set
13919: @c =====================================================================
13920: @cindex system documentation, exception words
13921: @cindex exception words, system documentation
13922:
13923: @menu
13924: * exception-idef:: Implementation Defined Options
13925: @end menu
13926:
13927:
13928: @c ---------------------------------------------------------------------
13929: @node exception-idef, , The optional Exception word set, The optional Exception word set
13930: @subsection Implementation Defined Options
13931: @c ---------------------------------------------------------------------
13932: @cindex implementation-defined options, exception words
13933: @cindex exception words, implementation-defined options
13934:
13935: @table @i
13936: @item @code{THROW}-codes used in the system:
13937: @cindex @code{THROW}-codes used in the system
13938: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13939: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13940: codes -512@minus{}-2047 are used for OS errors (for file and memory
13941: allocation operations). The mapping from OS error numbers to throw codes
13942: is -512@minus{}@code{errno}. One side effect of this mapping is that
13943: undefined OS errors produce a message with a strange number; e.g.,
13944: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13945: @end table
13946:
13947: @c =====================================================================
13948: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13949: @section The optional Facility word set
13950: @c =====================================================================
13951: @cindex system documentation, facility words
13952: @cindex facility words, system documentation
13953:
13954: @menu
13955: * facility-idef:: Implementation Defined Options
13956: * facility-ambcond:: Ambiguous Conditions
13957: @end menu
13958:
13959:
13960: @c ---------------------------------------------------------------------
13961: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
13962: @subsection Implementation Defined Options
13963: @c ---------------------------------------------------------------------
13964: @cindex implementation-defined options, facility words
13965: @cindex facility words, implementation-defined options
13966:
13967: @table @i
13968: @item encoding of keyboard events (@code{EKEY}):
13969: @cindex keyboard events, encoding in @code{EKEY}
13970: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 13971: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 13972: Other keys are encoded with the constants @code{k-left}, @code{k-right},
13973: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
13974: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
13975: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 13976:
1.1 anton 13977:
13978: @item duration of a system clock tick:
13979: @cindex duration of a system clock tick
13980: @cindex clock tick duration
13981: System dependent. With respect to @code{MS}, the time is specified in
13982: microseconds. How well the OS and the hardware implement this, is
13983: another question.
13984:
13985: @item repeatability to be expected from the execution of @code{MS}:
13986: @cindex repeatability to be expected from the execution of @code{MS}
13987: @cindex @code{MS}, repeatability to be expected
13988: System dependent. On Unix, a lot depends on load. If the system is
13989: lightly loaded, and the delay is short enough that Gforth does not get
13990: swapped out, the performance should be acceptable. Under MS-DOS and
13991: other single-tasking systems, it should be good.
13992:
13993: @end table
13994:
13995:
13996: @c ---------------------------------------------------------------------
13997: @node facility-ambcond, , facility-idef, The optional Facility word set
13998: @subsection Ambiguous conditions
13999: @c ---------------------------------------------------------------------
14000: @cindex facility words, ambiguous conditions
14001: @cindex ambiguous conditions, facility words
14002:
14003: @table @i
14004: @item @code{AT-XY} can't be performed on user output device:
14005: @cindex @code{AT-XY} can't be performed on user output device
14006: Largely terminal dependent. No range checks are done on the arguments.
14007: No errors are reported. You may see some garbage appearing, you may see
14008: simply nothing happen.
14009:
14010: @end table
14011:
14012:
14013: @c =====================================================================
14014: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14015: @section The optional File-Access word set
14016: @c =====================================================================
14017: @cindex system documentation, file words
14018: @cindex file words, system documentation
14019:
14020: @menu
14021: * file-idef:: Implementation Defined Options
14022: * file-ambcond:: Ambiguous Conditions
14023: @end menu
14024:
14025: @c ---------------------------------------------------------------------
14026: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14027: @subsection Implementation Defined Options
14028: @c ---------------------------------------------------------------------
14029: @cindex implementation-defined options, file words
14030: @cindex file words, implementation-defined options
14031:
14032: @table @i
14033: @item file access methods used:
14034: @cindex file access methods used
14035: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14036: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14037: @code{wb}): The file is cleared, if it exists, and created, if it does
14038: not (with both @code{open-file} and @code{create-file}). Under Unix
14039: @code{create-file} creates a file with 666 permissions modified by your
14040: umask.
14041:
14042: @item file exceptions:
14043: @cindex file exceptions
14044: The file words do not raise exceptions (except, perhaps, memory access
14045: faults when you pass illegal addresses or file-ids).
14046:
14047: @item file line terminator:
14048: @cindex file line terminator
14049: System-dependent. Gforth uses C's newline character as line
14050: terminator. What the actual character code(s) of this are is
14051: system-dependent.
14052:
14053: @item file name format:
14054: @cindex file name format
14055: System dependent. Gforth just uses the file name format of your OS.
14056:
14057: @item information returned by @code{FILE-STATUS}:
14058: @cindex @code{FILE-STATUS}, returned information
14059: @code{FILE-STATUS} returns the most powerful file access mode allowed
14060: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14061: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14062: along with the returned mode.
14063:
14064: @item input file state after an exception when including source:
14065: @cindex exception when including source
14066: All files that are left via the exception are closed.
14067:
1.29 crook 14068: @item @i{ior} values and meaning:
14069: @cindex @i{ior} values and meaning
1.68 anton 14070: @cindex @i{wior} values and meaning
1.29 crook 14071: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14072: intended as throw codes. They typically are in the range
14073: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14074: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14075:
14076: @item maximum depth of file input nesting:
14077: @cindex maximum depth of file input nesting
14078: @cindex file input nesting, maximum depth
14079: limited by the amount of return stack, locals/TIB stack, and the number
14080: of open files available. This should not give you troubles.
14081:
14082: @item maximum size of input line:
14083: @cindex maximum size of input line
14084: @cindex input line size, maximum
14085: @code{/line}. Currently 255.
14086:
14087: @item methods of mapping block ranges to files:
14088: @cindex mapping block ranges to files
14089: @cindex files containing blocks
14090: @cindex blocks in files
14091: By default, blocks are accessed in the file @file{blocks.fb} in the
14092: current working directory. The file can be switched with @code{USE}.
14093:
14094: @item number of string buffers provided by @code{S"}:
14095: @cindex @code{S"}, number of string buffers
14096: 1
14097:
14098: @item size of string buffer used by @code{S"}:
14099: @cindex @code{S"}, size of string buffer
14100: @code{/line}. currently 255.
14101:
14102: @end table
14103:
14104: @c ---------------------------------------------------------------------
14105: @node file-ambcond, , file-idef, The optional File-Access word set
14106: @subsection Ambiguous conditions
14107: @c ---------------------------------------------------------------------
14108: @cindex file words, ambiguous conditions
14109: @cindex ambiguous conditions, file words
14110:
14111: @table @i
14112: @item attempting to position a file outside its boundaries:
14113: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14114: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14115: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14116:
14117: @item attempting to read from file positions not yet written:
14118: @cindex reading from file positions not yet written
14119: End-of-file, i.e., zero characters are read and no error is reported.
14120:
1.29 crook 14121: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14122: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14123: An appropriate exception may be thrown, but a memory fault or other
14124: problem is more probable.
14125:
1.29 crook 14126: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14127: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14128: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14129: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14130: thrown.
14131:
14132: @item named file cannot be opened (@code{INCLUDED}):
14133: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14134: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14135:
14136: @item requesting an unmapped block number:
14137: @cindex unmapped block numbers
14138: There are no unmapped legal block numbers. On some operating systems,
14139: writing a block with a large number may overflow the file system and
14140: have an error message as consequence.
14141:
14142: @item using @code{source-id} when @code{blk} is non-zero:
14143: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14144: @code{source-id} performs its function. Typically it will give the id of
14145: the source which loaded the block. (Better ideas?)
14146:
14147: @end table
14148:
14149:
14150: @c =====================================================================
14151: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14152: @section The optional Floating-Point word set
14153: @c =====================================================================
14154: @cindex system documentation, floating-point words
14155: @cindex floating-point words, system documentation
14156:
14157: @menu
14158: * floating-idef:: Implementation Defined Options
14159: * floating-ambcond:: Ambiguous Conditions
14160: @end menu
14161:
14162:
14163: @c ---------------------------------------------------------------------
14164: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14165: @subsection Implementation Defined Options
14166: @c ---------------------------------------------------------------------
14167: @cindex implementation-defined options, floating-point words
14168: @cindex floating-point words, implementation-defined options
14169:
14170: @table @i
14171: @item format and range of floating point numbers:
14172: @cindex format and range of floating point numbers
14173: @cindex floating point numbers, format and range
14174: System-dependent; the @code{double} type of C.
14175:
1.29 crook 14176: @item results of @code{REPRESENT} when @i{float} is out of range:
14177: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14178: System dependent; @code{REPRESENT} is implemented using the C library
14179: function @code{ecvt()} and inherits its behaviour in this respect.
14180:
14181: @item rounding or truncation of floating-point numbers:
14182: @cindex rounding of floating-point numbers
14183: @cindex truncation of floating-point numbers
14184: @cindex floating-point numbers, rounding or truncation
14185: System dependent; the rounding behaviour is inherited from the hosting C
14186: compiler. IEEE-FP-based (i.e., most) systems by default round to
14187: nearest, and break ties by rounding to even (i.e., such that the last
14188: bit of the mantissa is 0).
14189:
14190: @item size of floating-point stack:
14191: @cindex floating-point stack size
14192: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14193: the floating-point stack (in floats). You can specify this on startup
14194: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14195:
14196: @item width of floating-point stack:
14197: @cindex floating-point stack width
14198: @code{1 floats}.
14199:
14200: @end table
14201:
14202:
14203: @c ---------------------------------------------------------------------
14204: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14205: @subsection Ambiguous conditions
14206: @c ---------------------------------------------------------------------
14207: @cindex floating-point words, ambiguous conditions
14208: @cindex ambiguous conditions, floating-point words
14209:
14210: @table @i
14211: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14212: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14213: System-dependent. Typically results in a @code{-23 THROW} like other
14214: alignment violations.
14215:
14216: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14217: @cindex @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: System-dependent. Typically results in a @code{-23 THROW} like other
14220: alignment violations.
14221:
14222: @item floating-point result out of range:
14223: @cindex floating-point result out of range
1.80 anton 14224: System-dependent. Can result in a @code{-43 throw} (floating point
14225: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14226: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14227: unidentified fault), or can produce a special value representing, e.g.,
14228: Infinity.
14229:
14230: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14231: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14232: System-dependent. Typically results in an alignment fault like other
14233: alignment violations.
14234:
1.35 anton 14235: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14236: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14237: The floating-point number is converted into decimal nonetheless.
14238:
14239: @item Both arguments are equal to zero (@code{FATAN2}):
14240: @cindex @code{FATAN2}, both arguments are equal to zero
14241: System-dependent. @code{FATAN2} is implemented using the C library
14242: function @code{atan2()}.
14243:
1.29 crook 14244: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14245: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14246: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14247: because of small errors and the tan will be a very large (or very small)
14248: but finite number.
14249:
1.29 crook 14250: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14251: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14252: The result is rounded to the nearest float.
14253:
14254: @item dividing by zero:
14255: @cindex dividing by zero, floating-point
14256: @cindex floating-point dividing by zero
14257: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14258: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14259: (floating point divide by zero) or @code{-55 throw} (Floating-point
14260: unidentified fault).
1.1 anton 14261:
14262: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14263: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14264: System dependent. On IEEE-FP based systems the number is converted into
14265: an infinity.
14266:
1.29 crook 14267: @item @i{float}<1 (@code{FACOSH}):
14268: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14269: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14270: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14271:
1.29 crook 14272: @item @i{float}=<-1 (@code{FLNP1}):
14273: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14274: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14275: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14276: negative infinity for @i{float}=-1).
1.1 anton 14277:
1.29 crook 14278: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14279: @cindex @code{FLN}, @i{float}=<0
14280: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14281: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14282: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14283: negative infinity for @i{float}=0).
1.1 anton 14284:
1.29 crook 14285: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14286: @cindex @code{FASINH}, @i{float}<0
14287: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14288: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14289: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14290: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14291: C library?).
1.1 anton 14292:
1.29 crook 14293: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14294: @cindex @code{FACOS}, |@i{float}|>1
14295: @cindex @code{FASIN}, |@i{float}|>1
14296: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14297: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14298: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14299:
1.29 crook 14300: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14301: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14302: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14303: Platform-dependent; typically, some double number is produced and no
14304: error is reported.
1.1 anton 14305:
14306: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14307: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14308: @code{Precision} characters of the numeric output area are used. If
14309: @code{precision} is too high, these words will smash the data or code
14310: close to @code{here}.
1.1 anton 14311: @end table
14312:
14313: @c =====================================================================
14314: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14315: @section The optional Locals word set
14316: @c =====================================================================
14317: @cindex system documentation, locals words
14318: @cindex locals words, system documentation
14319:
14320: @menu
14321: * locals-idef:: Implementation Defined Options
14322: * locals-ambcond:: Ambiguous Conditions
14323: @end menu
14324:
14325:
14326: @c ---------------------------------------------------------------------
14327: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14328: @subsection Implementation Defined Options
14329: @c ---------------------------------------------------------------------
14330: @cindex implementation-defined options, locals words
14331: @cindex locals words, implementation-defined options
14332:
14333: @table @i
14334: @item maximum number of locals in a definition:
14335: @cindex maximum number of locals in a definition
14336: @cindex locals, maximum number in a definition
14337: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14338: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14339: characters. The number of locals in a definition is bounded by the size
14340: of locals-buffer, which contains the names of the locals.
14341:
14342: @end table
14343:
14344:
14345: @c ---------------------------------------------------------------------
14346: @node locals-ambcond, , locals-idef, The optional Locals word set
14347: @subsection Ambiguous conditions
14348: @c ---------------------------------------------------------------------
14349: @cindex locals words, ambiguous conditions
14350: @cindex ambiguous conditions, locals words
14351:
14352: @table @i
14353: @item executing a named local in interpretation state:
14354: @cindex local in interpretation state
14355: @cindex Interpreting a compile-only word, for a local
14356: Locals have no interpretation semantics. If you try to perform the
14357: interpretation semantics, you will get a @code{-14 throw} somewhere
14358: (Interpreting a compile-only word). If you perform the compilation
14359: semantics, the locals access will be compiled (irrespective of state).
14360:
1.29 crook 14361: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14362: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14363: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14364: @cindex Invalid name argument, @code{TO}
14365: @code{-32 throw} (Invalid name argument)
14366:
14367: @end table
14368:
14369:
14370: @c =====================================================================
14371: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14372: @section The optional Memory-Allocation word set
14373: @c =====================================================================
14374: @cindex system documentation, memory-allocation words
14375: @cindex memory-allocation words, system documentation
14376:
14377: @menu
14378: * memory-idef:: Implementation Defined Options
14379: @end menu
14380:
14381:
14382: @c ---------------------------------------------------------------------
14383: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14384: @subsection Implementation Defined Options
14385: @c ---------------------------------------------------------------------
14386: @cindex implementation-defined options, memory-allocation words
14387: @cindex memory-allocation words, implementation-defined options
14388:
14389: @table @i
1.29 crook 14390: @item values and meaning of @i{ior}:
14391: @cindex @i{ior} values and meaning
14392: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14393: intended as throw codes. They typically are in the range
14394: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14395: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14396:
14397: @end table
14398:
14399: @c =====================================================================
14400: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14401: @section The optional Programming-Tools word set
14402: @c =====================================================================
14403: @cindex system documentation, programming-tools words
14404: @cindex programming-tools words, system documentation
14405:
14406: @menu
14407: * programming-idef:: Implementation Defined Options
14408: * programming-ambcond:: Ambiguous Conditions
14409: @end menu
14410:
14411:
14412: @c ---------------------------------------------------------------------
14413: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14414: @subsection Implementation Defined Options
14415: @c ---------------------------------------------------------------------
14416: @cindex implementation-defined options, programming-tools words
14417: @cindex programming-tools words, implementation-defined options
14418:
14419: @table @i
14420: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14421: @cindex @code{;CODE} ending sequence
14422: @cindex @code{CODE} ending sequence
14423: @code{END-CODE}
14424:
14425: @item manner of processing input following @code{;CODE} and @code{CODE}:
14426: @cindex @code{;CODE}, processing input
14427: @cindex @code{CODE}, processing input
14428: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14429: the input is processed by the text interpreter, (starting) in interpret
14430: state.
14431:
14432: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14433: @cindex @code{ASSEMBLER}, search order capability
14434: The ANS Forth search order word set.
14435:
14436: @item source and format of display by @code{SEE}:
14437: @cindex @code{SEE}, source and format of output
1.80 anton 14438: The source for @code{see} is the executable code used by the inner
1.1 anton 14439: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14440: (and on some platforms, assembly code for primitives) as well as
14441: possible.
1.1 anton 14442:
14443: @end table
14444:
14445: @c ---------------------------------------------------------------------
14446: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14447: @subsection Ambiguous conditions
14448: @c ---------------------------------------------------------------------
14449: @cindex programming-tools words, ambiguous conditions
14450: @cindex ambiguous conditions, programming-tools words
14451:
14452: @table @i
14453:
1.21 crook 14454: @item deleting the compilation word list (@code{FORGET}):
14455: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14456: Not implemented (yet).
14457:
1.29 crook 14458: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14459: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14460: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14461: @cindex control-flow stack underflow
14462: This typically results in an @code{abort"} with a descriptive error
14463: message (may change into a @code{-22 throw} (Control structure mismatch)
14464: in the future). You may also get a memory access error. If you are
14465: unlucky, this ambiguous condition is not caught.
14466:
1.29 crook 14467: @item @i{name} can't be found (@code{FORGET}):
14468: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14469: Not implemented (yet).
14470:
1.29 crook 14471: @item @i{name} not defined via @code{CREATE}:
14472: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14473: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14474: the execution semantics of the last defined word no matter how it was
14475: defined.
14476:
14477: @item @code{POSTPONE} applied to @code{[IF]}:
14478: @cindex @code{POSTPONE} applied to @code{[IF]}
14479: @cindex @code{[IF]} and @code{POSTPONE}
14480: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14481: equivalent to @code{[IF]}.
14482:
14483: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14484: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14485: Continue in the same state of conditional compilation in the next outer
14486: input source. Currently there is no warning to the user about this.
14487:
14488: @item removing a needed definition (@code{FORGET}):
14489: @cindex @code{FORGET}, removing a needed definition
14490: Not implemented (yet).
14491:
14492: @end table
14493:
14494:
14495: @c =====================================================================
14496: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14497: @section The optional Search-Order word set
14498: @c =====================================================================
14499: @cindex system documentation, search-order words
14500: @cindex search-order words, system documentation
14501:
14502: @menu
14503: * search-idef:: Implementation Defined Options
14504: * search-ambcond:: Ambiguous Conditions
14505: @end menu
14506:
14507:
14508: @c ---------------------------------------------------------------------
14509: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14510: @subsection Implementation Defined Options
14511: @c ---------------------------------------------------------------------
14512: @cindex implementation-defined options, search-order words
14513: @cindex search-order words, implementation-defined options
14514:
14515: @table @i
14516: @item maximum number of word lists in search order:
14517: @cindex maximum number of word lists in search order
14518: @cindex search order, maximum depth
14519: @code{s" wordlists" environment? drop .}. Currently 16.
14520:
14521: @item minimum search order:
14522: @cindex minimum search order
14523: @cindex search order, minimum
14524: @code{root root}.
14525:
14526: @end table
14527:
14528: @c ---------------------------------------------------------------------
14529: @node search-ambcond, , search-idef, The optional Search-Order word set
14530: @subsection Ambiguous conditions
14531: @c ---------------------------------------------------------------------
14532: @cindex search-order words, ambiguous conditions
14533: @cindex ambiguous conditions, search-order words
14534:
14535: @table @i
1.21 crook 14536: @item changing the compilation word list (during compilation):
14537: @cindex changing the compilation word list (during compilation)
14538: @cindex compilation word list, change before definition ends
14539: The word is entered into the word list that was the compilation word list
1.1 anton 14540: at the start of the definition. Any changes to the name field (e.g.,
14541: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14542: are applied to the latest defined word (as reported by @code{latest} or
14543: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14544:
14545: @item search order empty (@code{previous}):
14546: @cindex @code{previous}, search order empty
1.26 crook 14547: @cindex vocstack empty, @code{previous}
1.1 anton 14548: @code{abort" Vocstack empty"}.
14549:
14550: @item too many word lists in search order (@code{also}):
14551: @cindex @code{also}, too many word lists in search order
1.26 crook 14552: @cindex vocstack full, @code{also}
1.1 anton 14553: @code{abort" Vocstack full"}.
14554:
14555: @end table
14556:
14557: @c ***************************************************************
1.65 anton 14558: @node Standard vs Extensions, Model, ANS conformance, Top
14559: @chapter Should I use Gforth extensions?
14560: @cindex Gforth extensions
14561:
14562: As you read through the rest of this manual, you will see documentation
14563: for @i{Standard} words, and documentation for some appealing Gforth
14564: @i{extensions}. You might ask yourself the question: @i{``Should I
14565: restrict myself to the standard, or should I use the extensions?''}
14566:
14567: The answer depends on the goals you have for the program you are working
14568: on:
14569:
14570: @itemize @bullet
14571:
14572: @item Is it just for yourself or do you want to share it with others?
14573:
14574: @item
14575: If you want to share it, do the others all use Gforth?
14576:
14577: @item
14578: If it is just for yourself, do you want to restrict yourself to Gforth?
14579:
14580: @end itemize
14581:
14582: If restricting the program to Gforth is ok, then there is no reason not
14583: to use extensions. It is still a good idea to keep to the standard
14584: where it is easy, in case you want to reuse these parts in another
14585: program that you want to be portable.
14586:
14587: If you want to be able to port the program to other Forth systems, there
14588: are the following points to consider:
14589:
14590: @itemize @bullet
14591:
14592: @item
14593: Most Forth systems that are being maintained support the ANS Forth
14594: standard. So if your program complies with the standard, it will be
14595: portable among many systems.
14596:
14597: @item
14598: A number of the Gforth extensions can be implemented in ANS Forth using
14599: public-domain files provided in the @file{compat/} directory. These are
14600: mentioned in the text in passing. There is no reason not to use these
14601: extensions, your program will still be ANS Forth compliant; just include
14602: the appropriate compat files with your program.
14603:
14604: @item
14605: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14606: analyse your program and determine what non-Standard words it relies
14607: upon. However, it does not check whether you use standard words in a
14608: non-standard way.
14609:
14610: @item
14611: Some techniques are not standardized by ANS Forth, and are hard or
14612: impossible to implement in a standard way, but can be implemented in
14613: most Forth systems easily, and usually in similar ways (e.g., accessing
14614: word headers). Forth has a rich historical precedent for programmers
14615: taking advantage of implementation-dependent features of their tools
14616: (for example, relying on a knowledge of the dictionary
14617: structure). Sometimes these techniques are necessary to extract every
14618: last bit of performance from the hardware, sometimes they are just a
14619: programming shorthand.
14620:
14621: @item
14622: Does using a Gforth extension save more work than the porting this part
14623: to other Forth systems (if any) will cost?
14624:
14625: @item
14626: Is the additional functionality worth the reduction in portability and
14627: the additional porting problems?
14628:
14629: @end itemize
14630:
14631: In order to perform these consideratios, you need to know what's
14632: standard and what's not. This manual generally states if something is
1.81 anton 14633: non-standard, but the authoritative source is the
14634: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14635: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14636: into the thought processes of the technical committee.
14637:
14638: Note also that portability between Forth systems is not the only
14639: portability issue; there is also the issue of portability between
14640: different platforms (processor/OS combinations).
14641:
14642: @c ***************************************************************
14643: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14644: @chapter Model
14645:
14646: This chapter has yet to be written. It will contain information, on
14647: which internal structures you can rely.
14648:
14649: @c ***************************************************************
14650: @node Integrating Gforth, Emacs and Gforth, Model, Top
14651: @chapter Integrating Gforth into C programs
14652:
14653: This is not yet implemented.
14654:
14655: Several people like to use Forth as scripting language for applications
14656: that are otherwise written in C, C++, or some other language.
14657:
14658: The Forth system ATLAST provides facilities for embedding it into
14659: applications; unfortunately it has several disadvantages: most
14660: importantly, it is not based on ANS Forth, and it is apparently dead
14661: (i.e., not developed further and not supported). The facilities
1.21 crook 14662: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14663: making the switch should not be hard.
14664:
14665: We also tried to design the interface such that it can easily be
14666: implemented by other Forth systems, so that we may one day arrive at a
14667: standardized interface. Such a standard interface would allow you to
14668: replace the Forth system without having to rewrite C code.
14669:
14670: You embed the Gforth interpreter by linking with the library
14671: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14672: global symbols in this library that belong to the interface, have the
14673: prefix @code{forth_}. (Global symbols that are used internally have the
14674: prefix @code{gforth_}).
14675:
14676: You can include the declarations of Forth types and the functions and
14677: variables of the interface with @code{#include <forth.h>}.
14678:
14679: Types.
14680:
14681: Variables.
14682:
14683: Data and FP Stack pointer. Area sizes.
14684:
14685: functions.
14686:
14687: forth_init(imagefile)
14688: forth_evaluate(string) exceptions?
14689: forth_goto(address) (or forth_execute(xt)?)
14690: forth_continue() (a corountining mechanism)
14691:
14692: Adding primitives.
14693:
14694: No checking.
14695:
14696: Signals?
14697:
14698: Accessing the Stacks
14699:
1.26 crook 14700: @c ******************************************************************
1.1 anton 14701: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14702: @chapter Emacs and Gforth
14703: @cindex Emacs and Gforth
14704:
14705: @cindex @file{gforth.el}
14706: @cindex @file{forth.el}
14707: @cindex Rydqvist, Goran
1.107 dvdkhlng 14708: @cindex Kuehling, David
1.1 anton 14709: @cindex comment editing commands
14710: @cindex @code{\}, editing with Emacs
14711: @cindex debug tracer editing commands
14712: @cindex @code{~~}, removal with Emacs
14713: @cindex Forth mode in Emacs
1.107 dvdkhlng 14714:
1.1 anton 14715: Gforth comes with @file{gforth.el}, an improved version of
14716: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14717: improvements are:
14718:
14719: @itemize @bullet
14720: @item
1.107 dvdkhlng 14721: A better handling of indentation.
14722: @item
14723: A custom hilighting engine for Forth-code.
1.26 crook 14724: @item
14725: Comment paragraph filling (@kbd{M-q})
14726: @item
14727: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14728: @item
14729: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14730: @item
14731: Support of the @code{info-lookup} feature for looking up the
14732: documentation of a word.
1.107 dvdkhlng 14733: @item
14734: Support for reading and writing blocks files.
1.26 crook 14735: @end itemize
14736:
1.107 dvdkhlng 14737: To get a basic description of these features, enter Forth mode and
14738: type @kbd{C-h m}.
1.1 anton 14739:
14740: @cindex source location of error or debugging output in Emacs
14741: @cindex error output, finding the source location in Emacs
14742: @cindex debugging output, finding the source location in Emacs
14743: In addition, Gforth supports Emacs quite well: The source code locations
14744: given in error messages, debugging output (from @code{~~}) and failed
14745: assertion messages are in the right format for Emacs' compilation mode
14746: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14747: Manual}) so the source location corresponding to an error or other
14748: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14749: @kbd{C-c C-c} for the error under the cursor).
14750:
1.107 dvdkhlng 14751: @cindex viewing the documentation of a word in Emacs
14752: @cindex context-sensitive help
14753: Moreover, for words documented in this manual, you can look up the
14754: glossary entry quickly by using @kbd{C-h TAB}
14755: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14756: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14757: later and does not work for words containing @code{:}.
14758:
14759: @menu
14760: * Installing gforth.el:: Making Emacs aware of Forth.
14761: * Emacs Tags:: Viewing the source of a word in Emacs.
14762: * Hilighting:: Making Forth code look prettier.
14763: * Auto-Indentation:: Customizing auto-indentation.
14764: * Blocks Files:: Reading and writing blocks files.
14765: @end menu
14766:
14767: @c ----------------------------------
1.109 anton 14768: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14769: @section Installing gforth.el
14770: @cindex @file{.emacs}
14771: @cindex @file{gforth.el}, installation
14772: To make the features from @file{gforth.el} available in Emacs, add
14773: the following lines to your @file{.emacs} file:
14774:
14775: @example
14776: (autoload 'forth-mode "gforth.el")
14777: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14778: auto-mode-alist))
14779: (autoload 'forth-block-mode "gforth.el")
14780: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14781: auto-mode-alist))
14782: (add-hook 'forth-mode-hook (function (lambda ()
14783: ;; customize variables here:
14784: (setq forth-indent-level 4)
14785: (setq forth-minor-indent-level 2)
14786: (setq forth-hilight-level 3)
14787: ;;; ...
14788: )))
14789: @end example
14790:
14791: @c ----------------------------------
14792: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14793: @section Emacs Tags
1.1 anton 14794: @cindex @file{TAGS} file
14795: @cindex @file{etags.fs}
14796: @cindex viewing the source of a word in Emacs
1.43 anton 14797: @cindex @code{require}, placement in files
14798: @cindex @code{include}, placement in files
1.107 dvdkhlng 14799: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14800: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14801: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14802: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14803: several tags files at the same time (e.g., one for the Gforth sources
14804: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14805: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14806: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14807: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14808: with @file{etags.fs}, you should avoid putting definitions both before
14809: and after @code{require} etc., otherwise you will see the same file
14810: visited several times by commands like @code{tags-search}.
1.1 anton 14811:
1.107 dvdkhlng 14812: @c ----------------------------------
14813: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14814: @section Hilighting
14815: @cindex hilighting Forth code in Emacs
14816: @cindex highlighting Forth code in Emacs
14817: @file{gforth.el} comes with a custom source hilighting engine. When
14818: you open a file in @code{forth-mode}, it will be completely parsed,
14819: assigning faces to keywords, comments, strings etc. While you edit
14820: the file, modified regions get parsed and updated on-the-fly.
14821:
14822: Use the variable `forth-hilight-level' to change the level of
14823: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14824: you set the hilighting level to 0, the parser will still work in the
14825: background, collecting information about whether regions of text are
14826: ``compiled'' or ``interpreted''. Those information are required for
14827: auto-indentation to work properly. Set `forth-disable-parser' to
14828: non-nil if your computer is too slow to handle parsing. This will
14829: have an impact on the smartness of the auto-indentation engine,
14830: though.
14831:
14832: Sometimes Forth sources define new features that should be hilighted,
14833: new control structures, defining-words etc. You can use the variable
14834: `forth-custom-words' to make @code{forth-mode} hilight additional
14835: words and constructs. See the docstring of `forth-words' for details
14836: (in Emacs, type @kbd{C-h v forth-words}).
14837:
14838: `forth-custom-words' is meant to be customized in your
14839: @file{.emacs} file. To customize hilighing in a file-specific manner,
14840: set `forth-local-words' in a local-variables section at the end of
14841: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14842:
14843: Example:
14844: @example
14845: 0 [IF]
14846: Local Variables:
14847: forth-local-words:
14848: ((("t:") definition-starter (font-lock-keyword-face . 1)
14849: "[ \t\n]" t name (font-lock-function-name-face . 3))
14850: ((";t") definition-ender (font-lock-keyword-face . 1)))
14851: End:
14852: [THEN]
14853: @end example
14854:
14855: @c ----------------------------------
14856: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14857: @section Auto-Indentation
14858: @cindex auto-indentation of Forth code in Emacs
14859: @cindex indentation of Forth code in Emacs
14860: @code{forth-mode} automatically tries to indent lines in a smart way,
14861: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14862:
14863: Simple customization can be achieved by setting
14864: `forth-indent-level' and `forth-minor-indent-level' in your
14865: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14866: per default by multiples of 4 columns. To use the more traditional
14867: 3-column indentation, add the following lines to your @file{.emacs}:
14868:
14869: @example
14870: (add-hook 'forth-mode-hook (function (lambda ()
14871: ;; customize variables here:
14872: (setq forth-indent-level 3)
14873: (setq forth-minor-indent-level 1)
14874: )))
14875: @end example
14876:
14877: If you want indentation to recognize non-default words, customize it
14878: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14879: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14880: v forth-indent-words}).
14881:
14882: To customize indentation in a file-specific manner, set
14883: `forth-local-indent-words' in a local-variables section at the end of
14884: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14885: Emacs Manual}).
14886:
14887: Example:
14888: @example
14889: 0 [IF]
14890: Local Variables:
14891: forth-local-indent-words:
14892: ((("t:") (0 . 2) (0 . 2))
14893: ((";t") (-2 . 0) (0 . -2)))
14894: End:
14895: [THEN]
14896: @end example
14897:
14898: @c ----------------------------------
1.109 anton 14899: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14900: @section Blocks Files
14901: @cindex blocks files, use with Emacs
14902: @code{forth-mode} Autodetects blocks files by checking whether the
14903: length of the first line exceeds 1023 characters. It then tries to
14904: convert the file into normal text format. When you save the file, it
14905: will be written to disk as normal stream-source file.
14906:
14907: If you want to write blocks files, use @code{forth-blocks-mode}. It
14908: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14909:
1.107 dvdkhlng 14910: @itemize @bullet
14911: @item
14912: Files are written to disk in blocks file format.
14913: @item
14914: Screen numbers are displayed in the mode line (enumerated beginning
14915: with the value of `forth-block-base')
14916: @item
14917: Warnings are displayed when lines exceed 64 characters.
14918: @item
14919: The beginning of the currently edited block is marked with an
14920: overlay-arrow.
14921: @end itemize
1.41 anton 14922:
1.107 dvdkhlng 14923: There are some restrictions you should be aware of. When you open a
14924: blocks file that contains tabulator or newline characters, these
14925: characters will be translated into spaces when the file is written
14926: back to disk. If tabs or newlines are encountered during blocks file
14927: reading, an error is output to the echo area. So have a look at the
14928: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14929:
1.107 dvdkhlng 14930: Please consult the docstring of @code{forth-blocks-mode} for more
14931: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14932:
1.26 crook 14933: @c ******************************************************************
1.1 anton 14934: @node Image Files, Engine, Emacs and Gforth, Top
14935: @chapter Image Files
1.26 crook 14936: @cindex image file
14937: @cindex @file{.fi} files
1.1 anton 14938: @cindex precompiled Forth code
14939: @cindex dictionary in persistent form
14940: @cindex persistent form of dictionary
14941:
14942: An image file is a file containing an image of the Forth dictionary,
14943: i.e., compiled Forth code and data residing in the dictionary. By
14944: convention, we use the extension @code{.fi} for image files.
14945:
14946: @menu
1.18 anton 14947: * Image Licensing Issues:: Distribution terms for images.
14948: * Image File Background:: Why have image files?
1.67 anton 14949: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14950: * Data-Relocatable Image Files:: are better.
1.67 anton 14951: * Fully Relocatable Image Files:: better yet.
1.18 anton 14952: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14953: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14954: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14955: @end menu
14956:
1.18 anton 14957: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14958: @section Image Licensing Issues
14959: @cindex license for images
14960: @cindex image license
14961:
14962: An image created with @code{gforthmi} (@pxref{gforthmi}) or
14963: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
14964: original image; i.e., according to copyright law it is a derived work of
14965: the original image.
14966:
14967: Since Gforth is distributed under the GNU GPL, the newly created image
14968: falls under the GNU GPL, too. In particular, this means that if you
14969: distribute the image, you have to make all of the sources for the image
1.113 anton 14970: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 14971: GNU General Public License (Section 3)}.
14972:
14973: If you create an image with @code{cross} (@pxref{cross.fs}), the image
14974: contains only code compiled from the sources you gave it; if none of
14975: these sources is under the GPL, the terms discussed above do not apply
14976: to the image. However, if your image needs an engine (a gforth binary)
14977: that is under the GPL, you should make sure that you distribute both in
14978: a way that is at most a @emph{mere aggregation}, if you don't want the
14979: terms of the GPL to apply to the image.
14980:
14981: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 14982: @section Image File Background
14983: @cindex image file background
14984:
1.80 anton 14985: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 14986: definitions written in Forth. Since the Forth compiler itself belongs to
14987: those definitions, it is not possible to start the system with the
1.80 anton 14988: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 14989: code as an image file in nearly executable form. When Gforth starts up,
14990: a C routine loads the image file into memory, optionally relocates the
14991: addresses, then sets up the memory (stacks etc.) according to
14992: information in the image file, and (finally) starts executing Forth
14993: code.
1.1 anton 14994:
14995: The image file variants represent different compromises between the
14996: goals of making it easy to generate image files and making them
14997: portable.
14998:
14999: @cindex relocation at run-time
1.26 crook 15000: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15001: run-time. This avoids many of the complications discussed below (image
15002: files are data relocatable without further ado), but costs performance
15003: (one addition per memory access).
15004:
15005: @cindex relocation at load-time
1.26 crook 15006: By contrast, the Gforth loader performs relocation at image load time. The
15007: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15008: appropriate code-field addresses (or code addresses in the case of
15009: direct threading).
15010:
15011: There are three kinds of image files, with different degrees of
15012: relocatability: non-relocatable, data-relocatable, and fully relocatable
15013: image files.
15014:
15015: @cindex image file loader
15016: @cindex relocating loader
15017: @cindex loader for image files
15018: These image file variants have several restrictions in common; they are
15019: caused by the design of the image file loader:
15020:
15021: @itemize @bullet
15022: @item
15023: There is only one segment; in particular, this means, that an image file
15024: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15025: them). The contents of the stacks are not represented, either.
1.1 anton 15026:
15027: @item
15028: The only kinds of relocation supported are: adding the same offset to
15029: all cells that represent data addresses; and replacing special tokens
15030: with code addresses or with pieces of machine code.
15031:
15032: If any complex computations involving addresses are performed, the
15033: results cannot be represented in the image file. Several applications that
15034: use such computations come to mind:
15035: @itemize @minus
15036: @item
15037: Hashing addresses (or data structures which contain addresses) for table
15038: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15039: purpose, you will have no problem, because the hash tables are
15040: recomputed automatically when the system is started. If you use your own
15041: hash tables, you will have to do something similar.
15042:
15043: @item
15044: There's a cute implementation of doubly-linked lists that uses
15045: @code{XOR}ed addresses. You could represent such lists as singly-linked
15046: in the image file, and restore the doubly-linked representation on
15047: startup.@footnote{In my opinion, though, you should think thrice before
15048: using a doubly-linked list (whatever implementation).}
15049:
15050: @item
15051: The code addresses of run-time routines like @code{docol:} cannot be
15052: represented in the image file (because their tokens would be replaced by
15053: machine code in direct threaded implementations). As a workaround,
15054: compute these addresses at run-time with @code{>code-address} from the
15055: executions tokens of appropriate words (see the definitions of
1.80 anton 15056: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15057:
15058: @item
15059: On many architectures addresses are represented in machine code in some
15060: shifted or mangled form. You cannot put @code{CODE} words that contain
15061: absolute addresses in this form in a relocatable image file. Workarounds
15062: are representing the address in some relative form (e.g., relative to
15063: the CFA, which is present in some register), or loading the address from
15064: a place where it is stored in a non-mangled form.
15065: @end itemize
15066: @end itemize
15067:
15068: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15069: @section Non-Relocatable Image Files
15070: @cindex non-relocatable image files
1.26 crook 15071: @cindex image file, non-relocatable
1.1 anton 15072:
15073: These files are simple memory dumps of the dictionary. They are specific
15074: to the executable (i.e., @file{gforth} file) they were created
15075: with. What's worse, they are specific to the place on which the
15076: dictionary resided when the image was created. Now, there is no
15077: guarantee that the dictionary will reside at the same place the next
15078: time you start Gforth, so there's no guarantee that a non-relocatable
15079: image will work the next time (Gforth will complain instead of crashing,
15080: though).
15081:
15082: You can create a non-relocatable image file with
15083:
1.44 crook 15084:
1.1 anton 15085: doc-savesystem
15086:
1.44 crook 15087:
1.1 anton 15088: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15089: @section Data-Relocatable Image Files
15090: @cindex data-relocatable image files
1.26 crook 15091: @cindex image file, data-relocatable
1.1 anton 15092:
15093: These files contain relocatable data addresses, but fixed code addresses
15094: (instead of tokens). They are specific to the executable (i.e.,
15095: @file{gforth} file) they were created with. For direct threading on some
15096: architectures (e.g., the i386), data-relocatable images do not work. You
15097: get a data-relocatable image, if you use @file{gforthmi} with a
15098: Gforth binary that is not doubly indirect threaded (@pxref{Fully
15099: Relocatable Image Files}).
15100:
15101: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15102: @section Fully Relocatable Image Files
15103: @cindex fully relocatable image files
1.26 crook 15104: @cindex image file, fully relocatable
1.1 anton 15105:
15106: @cindex @file{kern*.fi}, relocatability
15107: @cindex @file{gforth.fi}, relocatability
15108: These image files have relocatable data addresses, and tokens for code
15109: addresses. They can be used with different binaries (e.g., with and
15110: without debugging) on the same machine, and even across machines with
15111: the same data formats (byte order, cell size, floating point
15112: format). However, they are usually specific to the version of Gforth
15113: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
15114: are fully relocatable.
15115:
15116: There are two ways to create a fully relocatable image file:
15117:
15118: @menu
1.29 crook 15119: * gforthmi:: The normal way
1.1 anton 15120: * cross.fs:: The hard way
15121: @end menu
15122:
15123: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15124: @subsection @file{gforthmi}
15125: @cindex @file{comp-i.fs}
15126: @cindex @file{gforthmi}
15127:
15128: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15129: image @i{file} that contains everything you would load by invoking
15130: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15131: @example
1.29 crook 15132: gforthmi @i{file} @i{options}
1.1 anton 15133: @end example
15134:
15135: E.g., if you want to create an image @file{asm.fi} that has the file
15136: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15137: like this:
15138:
15139: @example
15140: gforthmi asm.fi asm.fs
15141: @end example
15142:
1.27 crook 15143: @file{gforthmi} is implemented as a sh script and works like this: It
15144: produces two non-relocatable images for different addresses and then
15145: compares them. Its output reflects this: first you see the output (if
1.62 crook 15146: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15147: files, then you see the output of the comparing program: It displays the
15148: offset used for data addresses and the offset used for code addresses;
1.1 anton 15149: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15150: image files, it displays a line like this:
1.1 anton 15151:
15152: @example
15153: 78DC BFFFFA50 BFFFFA40
15154: @end example
15155:
15156: This means that at offset $78dc from @code{forthstart}, one input image
15157: contains $bffffa50, and the other contains $bffffa40. Since these cells
15158: cannot be represented correctly in the output image, you should examine
15159: these places in the dictionary and verify that these cells are dead
15160: (i.e., not read before they are written).
1.39 anton 15161:
15162: @cindex --application, @code{gforthmi} option
15163: If you insert the option @code{--application} in front of the image file
15164: name, you will get an image that uses the @code{--appl-image} option
15165: instead of the @code{--image-file} option (@pxref{Invoking
15166: Gforth}). When you execute such an image on Unix (by typing the image
15167: name as command), the Gforth engine will pass all options to the image
15168: instead of trying to interpret them as engine options.
1.1 anton 15169:
1.27 crook 15170: If you type @file{gforthmi} with no arguments, it prints some usage
15171: instructions.
15172:
1.1 anton 15173: @cindex @code{savesystem} during @file{gforthmi}
15174: @cindex @code{bye} during @file{gforthmi}
15175: @cindex doubly indirect threaded code
1.44 crook 15176: @cindex environment variables
15177: @cindex @code{GFORTHD} -- environment variable
15178: @cindex @code{GFORTH} -- environment variable
1.1 anton 15179: @cindex @code{gforth-ditc}
1.29 crook 15180: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 15181: words @code{savesystem} and @code{bye} must be visible. A special doubly
15182: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 15183: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 15184: this executable through the environment variable @code{GFORTHD}
15185: (default: @file{gforth-ditc}); if you pass a version that is not doubly
15186: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 15187: data-relocatable image (because there is no code address offset). The
15188: normal @file{gforth} executable is used for creating the relocatable
15189: image; you can pass the exact filename of this executable through the
15190: environment variable @code{GFORTH}.
1.1 anton 15191:
15192: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15193: @subsection @file{cross.fs}
15194: @cindex @file{cross.fs}
15195: @cindex cross-compiler
15196: @cindex metacompiler
1.47 crook 15197: @cindex target compiler
1.1 anton 15198:
15199: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15200: programming language (@pxref{Cross Compiler}).
1.1 anton 15201:
1.47 crook 15202: @code{cross} allows you to create image files for machines with
1.1 anton 15203: different data sizes and data formats than the one used for generating
15204: the image file. You can also use it to create an application image that
15205: does not contain a Forth compiler. These features are bought with
15206: restrictions and inconveniences in programming. E.g., addresses have to
15207: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15208: order to make the code relocatable.
15209:
15210:
15211: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15212: @section Stack and Dictionary Sizes
15213: @cindex image file, stack and dictionary sizes
15214: @cindex dictionary size default
15215: @cindex stack size default
15216:
15217: If you invoke Gforth with a command line flag for the size
15218: (@pxref{Invoking Gforth}), the size you specify is stored in the
15219: dictionary. If you save the dictionary with @code{savesystem} or create
15220: an image with @file{gforthmi}, this size will become the default
15221: for the resulting image file. E.g., the following will create a
1.21 crook 15222: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15223:
15224: @example
15225: gforthmi gforth.fi -m 1M
15226: @end example
15227:
15228: In other words, if you want to set the default size for the dictionary
15229: and the stacks of an image, just invoke @file{gforthmi} with the
15230: appropriate options when creating the image.
15231:
15232: @cindex stack size, cache-friendly
15233: Note: For cache-friendly behaviour (i.e., good performance), you should
15234: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15235: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15236: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15237:
15238: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15239: @section Running Image Files
15240: @cindex running image files
15241: @cindex invoking image files
15242: @cindex image file invocation
15243:
15244: @cindex -i, invoke image file
15245: @cindex --image file, invoke image file
1.29 crook 15246: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15247: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15248: @example
1.29 crook 15249: gforth -i @i{image}
1.1 anton 15250: @end example
15251:
15252: @cindex executable image file
1.26 crook 15253: @cindex image file, executable
1.1 anton 15254: If your operating system supports starting scripts with a line of the
15255: form @code{#! ...}, you just have to type the image file name to start
15256: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15257: just a convention). I.e., to run Gforth with the image file @i{image},
15258: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15259: This works because every @code{.fi} file starts with a line of this
15260: format:
15261:
15262: @example
15263: #! /usr/local/bin/gforth-0.4.0 -i
15264: @end example
15265:
15266: The file and pathname for the Gforth engine specified on this line is
15267: the specific Gforth executable that it was built against; i.e. the value
15268: of the environment variable @code{GFORTH} at the time that
15269: @file{gforthmi} was executed.
1.1 anton 15270:
1.27 crook 15271: You can make use of the same shell capability to make a Forth source
15272: file into an executable. For example, if you place this text in a file:
1.26 crook 15273:
15274: @example
15275: #! /usr/local/bin/gforth
15276:
15277: ." Hello, world" CR
15278: bye
15279: @end example
15280:
15281: @noindent
1.27 crook 15282: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15283: directly from the command line. The sequence @code{#!} is used in two
15284: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15285: system@footnote{The Unix kernel actually recognises two types of files:
15286: executable files and files of data, where the data is processed by an
15287: interpreter that is specified on the ``interpreter line'' -- the first
15288: line of the file, starting with the sequence #!. There may be a small
15289: limit (e.g., 32) on the number of characters that may be specified on
15290: the interpreter line.} secondly it is treated as a comment character by
15291: Gforth. Because of the second usage, a space is required between
1.80 anton 15292: @code{#!} and the path to the executable (moreover, some Unixes
15293: require the sequence @code{#! /}).
1.27 crook 15294:
15295: The disadvantage of this latter technique, compared with using
1.80 anton 15296: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15297: compiled on-the-fly, each time the program is invoked.
1.26 crook 15298:
1.1 anton 15299: doc-#!
15300:
1.44 crook 15301:
1.1 anton 15302: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15303: @section Modifying the Startup Sequence
15304: @cindex startup sequence for image file
15305: @cindex image file initialization sequence
15306: @cindex initialization sequence of image file
15307:
1.120 anton 15308: You can add your own initialization to the startup sequence of an image
15309: through the deferred word @code{'cold}. @code{'cold} is invoked just
15310: before the image-specific command line processing (i.e., loading files
15311: and evaluating (@code{-e}) strings) starts.
1.1 anton 15312:
15313: A sequence for adding your initialization usually looks like this:
15314:
15315: @example
15316: :noname
15317: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15318: ... \ your stuff
15319: ; IS 'cold
15320: @end example
15321:
1.157 anton 15322: After @code{'cold}, Gforth processes the image options
15323: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15324: another deferred word. This normally prints Gforth's startup message
15325: and does nothing else.
15326:
1.1 anton 15327: @cindex turnkey image files
1.26 crook 15328: @cindex image file, turnkey applications
1.157 anton 15329: So, if you want to make a turnkey image (i.e., an image for an
15330: application instead of an extended Forth system), you can do this in
15331: two ways:
15332:
15333: @itemize @bullet
15334:
15335: @item
15336: If you want to do your interpretation of the OS command-line
15337: arguments, hook into @code{'cold}. In that case you probably also
15338: want to build the image with @code{gforthmi --application}
15339: (@pxref{gforthmi}) to keep the engine from processing OS command line
15340: options. You can then do your own command-line processing with
15341: @code{next-arg}
15342:
15343: @item
15344: If you want to have the normal Gforth processing of OS command-line
15345: arguments, hook into @code{bootmessage}.
15346:
15347: @end itemize
15348:
15349: In either case, you probably do not want the word that you execute in
15350: these hooks to exit normally, but use @code{bye} or @code{throw}.
15351: Otherwise the Gforth startup process would continue and eventually
15352: present the Forth command line to the user.
1.26 crook 15353:
15354: doc-'cold
1.157 anton 15355: doc-bootmessage
1.44 crook 15356:
1.1 anton 15357: @c ******************************************************************
1.113 anton 15358: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15359: @chapter Engine
15360: @cindex engine
15361: @cindex virtual machine
15362:
1.26 crook 15363: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15364: may be helpful for finding your way in the Gforth sources.
15365:
1.109 anton 15366: The ideas in this section have also been published in the following
15367: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15368: Forth-Tagung '93; M. Anton Ertl,
15369: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15370: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15371: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15372: Threaded code variations and optimizations (extended version)}},
15373: Forth-Tagung '02.
1.1 anton 15374:
15375: @menu
15376: * Portability::
15377: * Threading::
15378: * Primitives::
15379: * Performance::
15380: @end menu
15381:
15382: @node Portability, Threading, Engine, Engine
15383: @section Portability
15384: @cindex engine portability
15385:
1.26 crook 15386: An important goal of the Gforth Project is availability across a wide
15387: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15388: achieved this goal by manually coding the engine in assembly language
15389: for several then-popular processors. This approach is very
15390: labor-intensive and the results are short-lived due to progress in
15391: computer architecture.
1.1 anton 15392:
15393: @cindex C, using C for the engine
15394: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15395: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15396: particularly popular for UNIX-based Forths due to the large variety of
15397: architectures of UNIX machines. Unfortunately an implementation in C
15398: does not mix well with the goals of efficiency and with using
15399: traditional techniques: Indirect or direct threading cannot be expressed
15400: in C, and switch threading, the fastest technique available in C, is
15401: significantly slower. Another problem with C is that it is very
15402: cumbersome to express double integer arithmetic.
15403:
15404: @cindex GNU C for the engine
15405: @cindex long long
15406: Fortunately, there is a portable language that does not have these
15407: limitations: GNU C, the version of C processed by the GNU C compiler
15408: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15409: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15410: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15411: threading possible, its @code{long long} type (@pxref{Long Long, ,
15412: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15413: double numbers on many systems. GNU C is freely available on all
1.1 anton 15414: important (and many unimportant) UNIX machines, VMS, 80386s running
15415: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15416: on all these machines.
15417:
15418: Writing in a portable language has the reputation of producing code that
15419: is slower than assembly. For our Forth engine we repeatedly looked at
15420: the code produced by the compiler and eliminated most compiler-induced
15421: inefficiencies by appropriate changes in the source code.
15422:
15423: @cindex explicit register declarations
15424: @cindex --enable-force-reg, configuration flag
15425: @cindex -DFORCE_REG
15426: However, register allocation cannot be portably influenced by the
15427: programmer, leading to some inefficiencies on register-starved
15428: machines. We use explicit register declarations (@pxref{Explicit Reg
15429: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15430: improve the speed on some machines. They are turned on by using the
15431: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15432: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15433: machine, but also on the compiler version: On some machines some
15434: compiler versions produce incorrect code when certain explicit register
15435: declarations are used. So by default @code{-DFORCE_REG} is not used.
15436:
15437: @node Threading, Primitives, Portability, Engine
15438: @section Threading
15439: @cindex inner interpreter implementation
15440: @cindex threaded code implementation
15441:
15442: @cindex labels as values
15443: GNU C's labels as values extension (available since @code{gcc-2.0},
15444: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15445: makes it possible to take the address of @i{label} by writing
15446: @code{&&@i{label}}. This address can then be used in a statement like
15447: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15448: @code{goto x}.
15449:
1.26 crook 15450: @cindex @code{NEXT}, indirect threaded
1.1 anton 15451: @cindex indirect threaded inner interpreter
15452: @cindex inner interpreter, indirect threaded
1.26 crook 15453: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15454: @example
15455: cfa = *ip++;
15456: ca = *cfa;
15457: goto *ca;
15458: @end example
15459: @cindex instruction pointer
15460: For those unfamiliar with the names: @code{ip} is the Forth instruction
15461: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15462: execution token and points to the code field of the next word to be
15463: executed; The @code{ca} (code address) fetched from there points to some
15464: executable code, e.g., a primitive or the colon definition handler
15465: @code{docol}.
15466:
1.26 crook 15467: @cindex @code{NEXT}, direct threaded
1.1 anton 15468: @cindex direct threaded inner interpreter
15469: @cindex inner interpreter, direct threaded
15470: Direct threading is even simpler:
15471: @example
15472: ca = *ip++;
15473: goto *ca;
15474: @end example
15475:
15476: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15477: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15478:
15479: @menu
15480: * Scheduling::
15481: * Direct or Indirect Threaded?::
1.109 anton 15482: * Dynamic Superinstructions::
1.1 anton 15483: * DOES>::
15484: @end menu
15485:
15486: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15487: @subsection Scheduling
15488: @cindex inner interpreter optimization
15489:
15490: There is a little complication: Pipelined and superscalar processors,
15491: i.e., RISC and some modern CISC machines can process independent
15492: instructions while waiting for the results of an instruction. The
15493: compiler usually reorders (schedules) the instructions in a way that
15494: achieves good usage of these delay slots. However, on our first tries
15495: the compiler did not do well on scheduling primitives. E.g., for
15496: @code{+} implemented as
15497: @example
15498: n=sp[0]+sp[1];
15499: sp++;
15500: sp[0]=n;
15501: NEXT;
15502: @end example
1.81 anton 15503: the @code{NEXT} comes strictly after the other code, i.e., there is
15504: nearly no scheduling. After a little thought the problem becomes clear:
15505: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15506: addresses (and the version of @code{gcc} we used would not know it even
15507: if it was possible), so it could not move the load of the cfa above the
15508: store to the TOS. Indeed the pointers could be the same, if code on or
15509: very near the top of stack were executed. In the interest of speed we
15510: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15511: in scheduling: @code{NEXT} is divided into several parts:
15512: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15513: like:
1.1 anton 15514: @example
1.81 anton 15515: NEXT_P0;
1.1 anton 15516: n=sp[0]+sp[1];
15517: sp++;
15518: NEXT_P1;
15519: sp[0]=n;
15520: NEXT_P2;
15521: @end example
15522:
1.81 anton 15523: There are various schemes that distribute the different operations of
15524: NEXT between these parts in several ways; in general, different schemes
15525: perform best on different processors. We use a scheme for most
15526: architectures that performs well for most processors of this
1.109 anton 15527: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15528: the scheme on installation time.
15529:
1.1 anton 15530:
1.109 anton 15531: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15532: @subsection Direct or Indirect Threaded?
15533: @cindex threading, direct or indirect?
15534:
1.109 anton 15535: Threaded forth code consists of references to primitives (simple machine
15536: code routines like @code{+}) and to non-primitives (e.g., colon
15537: definitions, variables, constants); for a specific class of
15538: non-primitives (e.g., variables) there is one code routine (e.g.,
15539: @code{dovar}), but each variable needs a separate reference to its data.
15540:
15541: Traditionally Forth has been implemented as indirect threaded code,
15542: because this allows to use only one cell to reference a non-primitive
15543: (basically you point to the data, and find the code address there).
15544:
15545: @cindex primitive-centric threaded code
15546: However, threaded code in Gforth (since 0.6.0) uses two cells for
15547: non-primitives, one for the code address, and one for the data address;
15548: the data pointer is an immediate argument for the virtual machine
15549: instruction represented by the code address. We call this
15550: @emph{primitive-centric} threaded code, because all code addresses point
15551: to simple primitives. E.g., for a variable, the code address is for
15552: @code{lit} (also used for integer literals like @code{99}).
15553:
15554: Primitive-centric threaded code allows us to use (faster) direct
15555: threading as dispatch method, completely portably (direct threaded code
15556: in Gforth before 0.6.0 required architecture-specific code). It also
15557: eliminates the performance problems related to I-cache consistency that
15558: 386 implementations have with direct threaded code, and allows
15559: additional optimizations.
15560:
15561: @cindex hybrid direct/indirect threaded code
15562: There is a catch, however: the @var{xt} parameter of @code{execute} can
15563: occupy only one cell, so how do we pass non-primitives with their code
15564: @emph{and} data addresses to them? Our answer is to use indirect
15565: threaded dispatch for @code{execute} and other words that use a
15566: single-cell xt. So, normal threaded code in colon definitions uses
15567: direct threading, and @code{execute} and similar words, which dispatch
15568: to xts on the data stack, use indirect threaded code. We call this
15569: @emph{hybrid direct/indirect} threaded code.
15570:
15571: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15572: @cindex gforth engine
15573: @cindex gforth-fast engine
15574: The engines @command{gforth} and @command{gforth-fast} use hybrid
15575: direct/indirect threaded code. This means that with these engines you
15576: cannot use @code{,} to compile an xt. Instead, you have to use
15577: @code{compile,}.
15578:
15579: @cindex gforth-itc engine
1.115 anton 15580: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15581: This engine uses plain old indirect threaded code. It still compiles in
15582: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15583: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15584: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15585: and execute @code{' , is compile,}. Your program can check if it is
15586: running on a hybrid direct/indirect threaded engine or a pure indirect
15587: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15588:
15589:
15590: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15591: @subsection Dynamic Superinstructions
15592: @cindex Dynamic superinstructions with replication
15593: @cindex Superinstructions
15594: @cindex Replication
15595:
15596: The engines @command{gforth} and @command{gforth-fast} use another
15597: optimization: Dynamic superinstructions with replication. As an
15598: example, consider the following colon definition:
15599:
15600: @example
15601: : squared ( n1 -- n2 )
15602: dup * ;
15603: @end example
15604:
15605: Gforth compiles this into the threaded code sequence
15606:
15607: @example
15608: dup
15609: *
15610: ;s
15611: @end example
15612:
15613: In normal direct threaded code there is a code address occupying one
15614: cell for each of these primitives. Each code address points to a
15615: machine code routine, and the interpreter jumps to this machine code in
15616: order to execute the primitive. The routines for these three
15617: primitives are (in @command{gforth-fast} on the 386):
15618:
15619: @example
15620: Code dup
15621: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15622: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15623: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15624: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15625: end-code
15626: Code *
15627: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15628: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15629: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15630: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15631: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15632: end-code
15633: Code ;s
15634: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15635: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15636: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15637: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15638: end-code
15639: @end example
15640:
15641: With dynamic superinstructions and replication the compiler does not
15642: just lay down the threaded code, but also copies the machine code
15643: fragments, usually without the jump at the end.
15644:
15645: @example
15646: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15647: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15648: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15649: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15650: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15651: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15652: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15653: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15654: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15655: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15656: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15657: @end example
15658:
15659: Only when a threaded-code control-flow change happens (e.g., in
15660: @code{;s}), the jump is appended. This optimization eliminates many of
15661: these jumps and makes the rest much more predictable. The speedup
15662: depends on the processor and the application; on the Athlon and Pentium
15663: III this optimization typically produces a speedup by a factor of 2.
15664:
15665: The code addresses in the direct-threaded code are set to point to the
15666: appropriate points in the copied machine code, in this example like
15667: this:
1.1 anton 15668:
1.109 anton 15669: @example
15670: primitive code address
15671: dup $4057D27D
15672: * $4057D286
15673: ;s $4057D292
15674: @end example
15675:
15676: Thus there can be threaded-code jumps to any place in this piece of
15677: code. This also simplifies decompilation quite a bit.
15678:
15679: @cindex --no-dynamic command-line option
15680: @cindex --no-super command-line option
15681: You can disable this optimization with @option{--no-dynamic}. You can
15682: use the copying without eliminating the jumps (i.e., dynamic
15683: replication, but without superinstructions) with @option{--no-super};
15684: this gives the branch prediction benefit alone; the effect on
1.110 anton 15685: performance depends on the CPU; on the Athlon and Pentium III the
15686: speedup is a little less than for dynamic superinstructions with
15687: replication.
15688:
15689: @cindex patching threaded code
15690: One use of these options is if you want to patch the threaded code.
15691: With superinstructions, many of the dispatch jumps are eliminated, so
15692: patching often has no effect. These options preserve all the dispatch
15693: jumps.
1.109 anton 15694:
15695: @cindex --dynamic command-line option
1.110 anton 15696: On some machines dynamic superinstructions are disabled by default,
15697: because it is unsafe on these machines. However, if you feel
15698: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15699:
15700: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15701: @subsection DOES>
15702: @cindex @code{DOES>} implementation
15703:
1.26 crook 15704: @cindex @code{dodoes} routine
15705: @cindex @code{DOES>}-code
1.1 anton 15706: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15707: the chunk of code executed by every word defined by a
1.109 anton 15708: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15709: this is only needed if the xt of the word is @code{execute}d. The main
15710: problem here is: How to find the Forth code to be executed, i.e. the
15711: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15712: solutions:
1.1 anton 15713:
1.21 crook 15714: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15715: @code{DOES>}-code address is stored in the cell after the code address
15716: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15717: illegal in the Forth-79 and all later standards, because in fig-Forth
15718: this address lies in the body (which is illegal in these
15719: standards). However, by making the code field larger for all words this
15720: solution becomes legal again. We use this approach. Leaving a cell
15721: unused in most words is a bit wasteful, but on the machines we are
15722: targeting this is hardly a problem.
15723:
1.1 anton 15724:
15725: @node Primitives, Performance, Threading, Engine
15726: @section Primitives
15727: @cindex primitives, implementation
15728: @cindex virtual machine instructions, implementation
15729:
15730: @menu
15731: * Automatic Generation::
15732: * TOS Optimization::
15733: * Produced code::
15734: @end menu
15735:
15736: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15737: @subsection Automatic Generation
15738: @cindex primitives, automatic generation
15739:
15740: @cindex @file{prims2x.fs}
1.109 anton 15741:
1.1 anton 15742: Since the primitives are implemented in a portable language, there is no
15743: longer any need to minimize the number of primitives. On the contrary,
15744: having many primitives has an advantage: speed. In order to reduce the
15745: number of errors in primitives and to make programming them easier, we
1.109 anton 15746: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15747: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15748: generates most (and sometimes all) of the C code for a primitive from
15749: the stack effect notation. The source for a primitive has the following
15750: form:
1.1 anton 15751:
15752: @cindex primitive source format
15753: @format
1.58 anton 15754: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15755: [@code{""}@i{glossary entry}@code{""}]
15756: @i{C code}
1.1 anton 15757: [@code{:}
1.29 crook 15758: @i{Forth code}]
1.1 anton 15759: @end format
15760:
15761: The items in brackets are optional. The category and glossary fields
15762: are there for generating the documentation, the Forth code is there
15763: for manual implementations on machines without GNU C. E.g., the source
15764: for the primitive @code{+} is:
15765: @example
1.58 anton 15766: + ( n1 n2 -- n ) core plus
1.1 anton 15767: n = n1+n2;
15768: @end example
15769:
15770: This looks like a specification, but in fact @code{n = n1+n2} is C
15771: code. Our primitive generation tool extracts a lot of information from
15772: the stack effect notations@footnote{We use a one-stack notation, even
15773: though we have separate data and floating-point stacks; The separate
15774: notation can be generated easily from the unified notation.}: The number
15775: of items popped from and pushed on the stack, their type, and by what
15776: name they are referred to in the C code. It then generates a C code
15777: prelude and postlude for each primitive. The final C code for @code{+}
15778: looks like this:
15779:
15780: @example
1.46 pazsan 15781: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15782: /* */ /* documentation */
1.81 anton 15783: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15784: @{
15785: DEF_CA /* definition of variable ca (indirect threading) */
15786: Cell n1; /* definitions of variables */
15787: Cell n2;
15788: Cell n;
1.81 anton 15789: NEXT_P0; /* NEXT part 0 */
1.1 anton 15790: n1 = (Cell) sp[1]; /* input */
15791: n2 = (Cell) TOS;
15792: sp += 1; /* stack adjustment */
15793: @{
15794: n = n1+n2; /* C code taken from the source */
15795: @}
15796: NEXT_P1; /* NEXT part 1 */
15797: TOS = (Cell)n; /* output */
15798: NEXT_P2; /* NEXT part 2 */
15799: @}
15800: @end example
15801:
15802: This looks long and inefficient, but the GNU C compiler optimizes quite
15803: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15804: HP RISC machines: Defining the @code{n}s does not produce any code, and
15805: using them as intermediate storage also adds no cost.
15806:
1.26 crook 15807: There are also other optimizations that are not illustrated by this
15808: example: assignments between simple variables are usually for free (copy
1.1 anton 15809: propagation). If one of the stack items is not used by the primitive
15810: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15811: (dead code elimination). On the other hand, there are some things that
15812: the compiler does not do, therefore they are performed by
15813: @file{prims2x.fs}: The compiler does not optimize code away that stores
15814: a stack item to the place where it just came from (e.g., @code{over}).
15815:
15816: While programming a primitive is usually easy, there are a few cases
15817: where the programmer has to take the actions of the generator into
15818: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15819: fall through to @code{NEXT}.
1.109 anton 15820:
15821: For more information
1.1 anton 15822:
15823: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15824: @subsection TOS Optimization
15825: @cindex TOS optimization for primitives
15826: @cindex primitives, keeping the TOS in a register
15827:
15828: An important optimization for stack machine emulators, e.g., Forth
15829: engines, is keeping one or more of the top stack items in
1.29 crook 15830: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15831: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15832: @itemize @bullet
15833: @item
1.29 crook 15834: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15835: due to fewer loads from and stores to the stack.
1.29 crook 15836: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15837: @i{y<n}, due to additional moves between registers.
1.1 anton 15838: @end itemize
15839:
15840: @cindex -DUSE_TOS
15841: @cindex -DUSE_NO_TOS
15842: In particular, keeping one item in a register is never a disadvantage,
15843: if there are enough registers. Keeping two items in registers is a
15844: disadvantage for frequent words like @code{?branch}, constants,
15845: variables, literals and @code{i}. Therefore our generator only produces
15846: code that keeps zero or one items in registers. The generated C code
15847: covers both cases; the selection between these alternatives is made at
15848: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15849: code for @code{+} is just a simple variable name in the one-item case,
15850: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15851: GNU C compiler tries to keep simple variables like @code{TOS} in
15852: registers, and it usually succeeds, if there are enough registers.
15853:
15854: @cindex -DUSE_FTOS
15855: @cindex -DUSE_NO_FTOS
15856: The primitive generator performs the TOS optimization for the
15857: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15858: operations the benefit of this optimization is even larger:
15859: floating-point operations take quite long on most processors, but can be
15860: performed in parallel with other operations as long as their results are
15861: not used. If the FP-TOS is kept in a register, this works. If
15862: it is kept on the stack, i.e., in memory, the store into memory has to
15863: wait for the result of the floating-point operation, lengthening the
15864: execution time of the primitive considerably.
15865:
15866: The TOS optimization makes the automatic generation of primitives a
15867: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15868: @code{TOS} is not sufficient. There are some special cases to
15869: consider:
15870: @itemize @bullet
15871: @item In the case of @code{dup ( w -- w w )} the generator must not
15872: eliminate the store to the original location of the item on the stack,
15873: if the TOS optimization is turned on.
15874: @item Primitives with stack effects of the form @code{--}
1.29 crook 15875: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15876: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15877: must load the TOS from the stack at the end. But for the null stack
15878: effect @code{--} no stores or loads should be generated.
15879: @end itemize
15880:
15881: @node Produced code, , TOS Optimization, Primitives
15882: @subsection Produced code
15883: @cindex primitives, assembly code listing
15884:
15885: @cindex @file{engine.s}
15886: To see what assembly code is produced for the primitives on your machine
15887: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15888: look at the resulting file @file{engine.s}. Alternatively, you can also
15889: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15890:
15891: @node Performance, , Primitives, Engine
15892: @section Performance
15893: @cindex performance of some Forth interpreters
15894: @cindex engine performance
15895: @cindex benchmarking Forth systems
15896: @cindex Gforth performance
15897:
15898: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15899: impossible to write a significantly faster threaded-code engine.
1.1 anton 15900:
15901: On register-starved machines like the 386 architecture processors
15902: improvements are possible, because @code{gcc} does not utilize the
15903: registers as well as a human, even with explicit register declarations;
15904: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15905: and hand-tuned it for the 486; this system is 1.19 times faster on the
15906: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15907: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15908: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15909: registers fit in real registers (and we can even afford to use the TOS
15910: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15911: earlier results. And dynamic superinstructions provide another speedup
15912: (but only around a factor 1.2 on the 486).
1.1 anton 15913:
15914: @cindex Win32Forth performance
15915: @cindex NT Forth performance
15916: @cindex eforth performance
15917: @cindex ThisForth performance
15918: @cindex PFE performance
15919: @cindex TILE performance
1.81 anton 15920: The potential advantage of assembly language implementations is not
1.112 anton 15921: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15922: (direct threaded, compiled with @code{gcc-2.95.1} and
15923: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15924: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15925: (with and without peephole (aka pinhole) optimization of the threaded
15926: code); all these systems were written in assembly language. We also
15927: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15928: with @code{gcc-2.6.3} with the default configuration for Linux:
15929: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15930: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15931: employs peephole optimization of the threaded code) and TILE (compiled
15932: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15933: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15934: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15935: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15936: then extended it to run the benchmarks, added the peephole optimizer,
15937: ran the benchmarks and reported the results.
1.40 anton 15938:
1.1 anton 15939: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15940: matrix multiplication come from the Stanford integer benchmarks and have
15941: been translated into Forth by Martin Fraeman; we used the versions
15942: included in the TILE Forth package, but with bigger data set sizes; and
15943: a recursive Fibonacci number computation for benchmarking calling
15944: performance. The following table shows the time taken for the benchmarks
15945: scaled by the time taken by Gforth (in other words, it shows the speedup
15946: factor that Gforth achieved over the other systems).
15947:
15948: @example
1.112 anton 15949: relative Win32- NT eforth This-
15950: time Gforth Forth Forth eforth +opt PFE Forth TILE
15951: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15952: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15953: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15954: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15955: @end example
15956:
1.26 crook 15957: You may be quite surprised by the good performance of Gforth when
15958: compared with systems written in assembly language. One important reason
15959: for the disappointing performance of these other systems is probably
15960: that they are not written optimally for the 486 (e.g., they use the
15961: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
15962: but costly method for relocating the Forth image: like @code{cforth}, it
15963: computes the actual addresses at run time, resulting in two address
15964: computations per @code{NEXT} (@pxref{Image File Background}).
15965:
1.1 anton 15966: The speedup of Gforth over PFE, ThisForth and TILE can be easily
15967: explained with the self-imposed restriction of the latter systems to
15968: standard C, which makes efficient threading impossible (however, the
1.4 anton 15969: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 15970: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
15971: Moreover, current C compilers have a hard time optimizing other aspects
15972: of the ThisForth and the TILE source.
15973:
1.26 crook 15974: The performance of Gforth on 386 architecture processors varies widely
15975: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
15976: allocate any of the virtual machine registers into real machine
15977: registers by itself and would not work correctly with explicit register
1.112 anton 15978: declarations, giving a significantly slower engine (on a 486DX2/66
15979: running the Sieve) than the one measured above.
1.1 anton 15980:
1.26 crook 15981: Note that there have been several releases of Win32Forth since the
15982: release presented here, so the results presented above may have little
1.40 anton 15983: predictive value for the performance of Win32Forth today (results for
15984: the current release on an i486DX2/66 are welcome).
1.1 anton 15985:
15986: @cindex @file{Benchres}
1.66 anton 15987: In
15988: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
15989: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 15990: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 15991: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
15992: several native code systems; that version of Gforth is slower on a 486
1.112 anton 15993: than the version used here. You can find a newer version of these
15994: measurements at
1.47 crook 15995: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 15996: find numbers for Gforth on various machines in @file{Benchres}.
15997:
1.26 crook 15998: @c ******************************************************************
1.113 anton 15999: @c @node Binding to System Library, Cross Compiler, Engine, Top
16000: @c @chapter Binding to System Library
1.13 pazsan 16001:
1.113 anton 16002: @c ****************************************************************
16003: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16004: @chapter Cross Compiler
1.47 crook 16005: @cindex @file{cross.fs}
16006: @cindex cross-compiler
16007: @cindex metacompiler
16008: @cindex target compiler
1.13 pazsan 16009:
1.46 pazsan 16010: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16011: mostly written in Forth, including crucial parts like the outer
16012: interpreter and compiler, it needs compiled Forth code to get
16013: started. The cross compiler allows to create new images for other
16014: architectures, even running under another Forth system.
1.13 pazsan 16015:
16016: @menu
1.67 anton 16017: * Using the Cross Compiler::
16018: * How the Cross Compiler Works::
1.13 pazsan 16019: @end menu
16020:
1.21 crook 16021: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16022: @section Using the Cross Compiler
1.46 pazsan 16023:
16024: The cross compiler uses a language that resembles Forth, but isn't. The
16025: main difference is that you can execute Forth code after definition,
16026: while you usually can't execute the code compiled by cross, because the
16027: code you are compiling is typically for a different computer than the
16028: one you are compiling on.
16029:
1.81 anton 16030: @c anton: This chapter is somewhat different from waht I would expect: I
16031: @c would expect an explanation of the cross language and how to create an
16032: @c application image with it. The section explains some aspects of
16033: @c creating a Gforth kernel.
16034:
1.46 pazsan 16035: The Makefile is already set up to allow you to create kernels for new
16036: architectures with a simple make command. The generic kernels using the
16037: GCC compiled virtual machine are created in the normal build process
16038: with @code{make}. To create a embedded Gforth executable for e.g. the
16039: 8086 processor (running on a DOS machine), type
16040:
16041: @example
16042: make kernl-8086.fi
16043: @end example
16044:
16045: This will use the machine description from the @file{arch/8086}
16046: directory to create a new kernel. A machine file may look like that:
16047:
16048: @example
16049: \ Parameter for target systems 06oct92py
16050:
16051: 4 Constant cell \ cell size in bytes
16052: 2 Constant cell<< \ cell shift to bytes
16053: 5 Constant cell>bit \ cell shift to bits
16054: 8 Constant bits/char \ bits per character
16055: 8 Constant bits/byte \ bits per byte [default: 8]
16056: 8 Constant float \ bytes per float
16057: 8 Constant /maxalign \ maximum alignment in bytes
16058: false Constant bigendian \ byte order
16059: ( true=big, false=little )
16060:
16061: include machpc.fs \ feature list
16062: @end example
16063:
16064: This part is obligatory for the cross compiler itself, the feature list
16065: is used by the kernel to conditionally compile some features in and out,
16066: depending on whether the target supports these features.
16067:
16068: There are some optional features, if you define your own primitives,
16069: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16070: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16071: @code{prims-include} includes primitives, and @code{>boot} prepares for
16072: booting.
16073:
16074: @example
16075: : asm-include ." Include assembler" cr
16076: s" arch/8086/asm.fs" included ;
16077:
16078: : prims-include ." Include primitives" cr
16079: s" arch/8086/prim.fs" included ;
16080:
16081: : >boot ." Prepare booting" cr
16082: s" ' boot >body into-forth 1+ !" evaluate ;
16083: @end example
16084:
16085: These words are used as sort of macro during the cross compilation in
1.81 anton 16086: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16087: be possible --- but more complicated --- to write a new kernel project
16088: file, too.
16089:
16090: @file{kernel/main.fs} expects the machine description file name on the
16091: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16092: @code{mach-file} leaves a counted string on the stack, or
16093: @code{machine-file} leaves an address, count pair of the filename on the
16094: stack.
16095:
16096: The feature list is typically controlled using @code{SetValue}, generic
16097: files that are used by several projects can use @code{DefaultValue}
16098: instead. Both functions work like @code{Value}, when the value isn't
16099: defined, but @code{SetValue} works like @code{to} if the value is
16100: defined, and @code{DefaultValue} doesn't set anything, if the value is
16101: defined.
16102:
16103: @example
16104: \ generic mach file for pc gforth 03sep97jaw
16105:
16106: true DefaultValue NIL \ relocating
16107:
16108: >ENVIRON
16109:
16110: true DefaultValue file \ controls the presence of the
16111: \ file access wordset
16112: true DefaultValue OS \ flag to indicate a operating system
16113:
16114: true DefaultValue prims \ true: primitives are c-code
16115:
16116: true DefaultValue floating \ floating point wordset is present
16117:
16118: true DefaultValue glocals \ gforth locals are present
16119: \ will be loaded
16120: true DefaultValue dcomps \ double number comparisons
16121:
16122: true DefaultValue hash \ hashing primitives are loaded/present
16123:
16124: true DefaultValue xconds \ used together with glocals,
16125: \ special conditionals supporting gforths'
16126: \ local variables
16127: true DefaultValue header \ save a header information
16128:
16129: true DefaultValue backtrace \ enables backtrace code
16130:
16131: false DefaultValue ec
16132: false DefaultValue crlf
16133:
16134: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16135:
16136: &16 KB DefaultValue stack-size
16137: &15 KB &512 + DefaultValue fstack-size
16138: &15 KB DefaultValue rstack-size
16139: &14 KB &512 + DefaultValue lstack-size
16140: @end example
1.13 pazsan 16141:
1.48 anton 16142: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16143: @section How the Cross Compiler Works
1.13 pazsan 16144:
16145: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16146: @appendix Bugs
1.1 anton 16147: @cindex bug reporting
16148:
1.21 crook 16149: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16150:
1.103 anton 16151: If you find a bug, please submit a bug report through
16152: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16153:
16154: @itemize @bullet
16155: @item
1.81 anton 16156: A program (or a sequence of keyboard commands) that reproduces the bug.
16157: @item
16158: A description of what you think constitutes the buggy behaviour.
16159: @item
1.21 crook 16160: The Gforth version used (it is announced at the start of an
16161: interactive Gforth session).
16162: @item
16163: The machine and operating system (on Unix
16164: systems @code{uname -a} will report this information).
16165: @item
1.81 anton 16166: The installation options (you can find the configure options at the
16167: start of @file{config.status}) and configuration (@code{configure}
16168: output or @file{config.cache}).
1.21 crook 16169: @item
16170: A complete list of changes (if any) you (or your installer) have made to the
16171: Gforth sources.
16172: @end itemize
1.1 anton 16173:
16174: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16175: to Report Bugs, gcc.info, GNU C Manual}.
16176:
16177:
1.21 crook 16178: @node Origin, Forth-related information, Bugs, Top
16179: @appendix Authors and Ancestors of Gforth
1.1 anton 16180:
16181: @section Authors and Contributors
16182: @cindex authors of Gforth
16183: @cindex contributors to Gforth
16184:
16185: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16186: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16187: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16188: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16189: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16190: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16191: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16192: working on automatic support for calling C libraries. Helpful comments
16193: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16194: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16195: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16196: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16197: comments from many others; thank you all, sorry for not listing you
16198: here (but digging through my mailbox to extract your names is on my
16199: to-do list).
1.1 anton 16200:
16201: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16202: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16203: was developed across the Internet, and its authors did not meet
1.20 pazsan 16204: physically for the first 4 years of development.
1.1 anton 16205:
16206: @section Pedigree
1.26 crook 16207: @cindex pedigree of Gforth
1.1 anton 16208:
1.81 anton 16209: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16210: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16211:
1.20 pazsan 16212: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16213: 32 bit native code version of VolksForth for the Atari ST, written
16214: mostly by Dietrich Weineck.
16215:
1.81 anton 16216: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16217: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16218: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16219:
1.147 anton 16220: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16221: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16222:
16223: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16224: 1979. Robert Selzer and Bill Ragsdale developed the original
16225: implementation of fig-Forth for the 6502 based on microForth.
16226:
16227: The principal architect of microForth was Dean Sanderson. microForth was
16228: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16229: the 1802, and subsequently implemented on the 8080, the 6800 and the
16230: Z80.
16231:
16232: All earlier Forth systems were custom-made, usually by Charles Moore,
16233: who discovered (as he puts it) Forth during the late 60s. The first full
16234: Forth existed in 1971.
16235:
1.81 anton 16236: A part of the information in this section comes from
16237: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16238: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16239: Charles H. Moore, presented at the HOPL-II conference and preprinted
16240: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16241: genealogical information about Forth there. For a more general (and
16242: graphical) Forth family tree look see
16243: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16244: Forth Family Tree and Timeline}.
1.1 anton 16245:
1.81 anton 16246: @c ------------------------------------------------------------------
1.113 anton 16247: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16248: @appendix Other Forth-related information
16249: @cindex Forth-related information
16250:
1.81 anton 16251: @c anton: I threw most of this stuff out, because it can be found through
16252: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16253:
16254: @cindex comp.lang.forth
16255: @cindex frequently asked questions
1.81 anton 16256: There is an active news group (comp.lang.forth) discussing Forth
16257: (including Gforth) and Forth-related issues. Its
16258: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16259: (frequently asked questions and their answers) contains a lot of
16260: information on Forth. You should read it before posting to
16261: comp.lang.forth.
1.21 crook 16262:
1.81 anton 16263: The ANS Forth standard is most usable in its
16264: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16265:
1.113 anton 16266: @c ---------------------------------------------------
16267: @node Licenses, Word Index, Forth-related information, Top
16268: @appendix Licenses
16269:
16270: @menu
16271: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16272: * Copying:: GPL (for copying this software).
1.113 anton 16273: @end menu
16274:
1.192 anton 16275: @node GNU Free Documentation License, Copying, Licenses, Licenses
16276: @appendixsec GNU Free Documentation License
1.113 anton 16277: @include fdl.texi
16278:
1.192 anton 16279: @node Copying, , GNU Free Documentation License, Licenses
16280: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16281: @include gpl.texi
16282:
16283:
16284:
1.81 anton 16285: @c ------------------------------------------------------------------
1.113 anton 16286: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16287: @unnumbered Word Index
16288:
1.26 crook 16289: This index is a list of Forth words that have ``glossary'' entries
16290: within this manual. Each word is listed with its stack effect and
16291: wordset.
1.1 anton 16292:
16293: @printindex fn
16294:
1.81 anton 16295: @c anton: the name index seems superfluous given the word and concept indices.
16296:
16297: @c @node Name Index, Concept Index, Word Index, Top
16298: @c @unnumbered Name Index
1.41 anton 16299:
1.81 anton 16300: @c This index is a list of Forth words that have ``glossary'' entries
16301: @c within this manual.
1.41 anton 16302:
1.81 anton 16303: @c @printindex ky
1.41 anton 16304:
1.113 anton 16305: @c -------------------------------------------------------
1.81 anton 16306: @node Concept Index, , Word Index, Top
1.1 anton 16307: @unnumbered Concept and Word Index
16308:
1.26 crook 16309: Not all entries listed in this index are present verbatim in the
16310: text. This index also duplicates, in abbreviated form, all of the words
16311: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16312:
16313: @printindex cp
16314:
16315: @bye
1.81 anton 16316:
16317:
1.1 anton 16318:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>