Annotation of gforth/doc/gforth.ds, revision 1.195
1.1 anton 1: \input texinfo @c -*-texinfo-*-
2: @comment The source is gforth.ds, from which gforth.texi is generated
1.28 crook 3:
1.21 crook 4: @comment TODO: nac29jan99 - a list of things to add in the next edit:
1.28 crook 5: @comment 1. x-ref all ambiguous or implementation-defined features?
6: @comment 2. Describe the use of Auser Avariable AConstant A, etc.
7: @comment 3. words in miscellaneous section need a home.
8: @comment 4. search for TODO for other minor and major works required.
9: @comment 5. [rats] change all @var to @i in Forth source so that info
10: @comment file looks decent.
1.36 anton 11: @c Not an improvement IMO - anton
12: @c and anyway, this should be taken up
13: @c with Karl Berry (the texinfo guy) - anton
1.113 anton 14: @c
15: @c Karl Berry writes:
16: @c If they don't like the all-caps for @var Info output, all I can say is
17: @c that it's always been that way, and the usage of all-caps for
18: @c metavariables has a long tradition. I think it's best to just let it be
19: @c what it is, for the sake of consistency among manuals.
20: @c
1.29 crook 21: @comment .. would be useful to have a word that identified all deferred words
22: @comment should semantics stuff in intro be moved to another section
23:
1.66 anton 24: @c POSTPONE, COMPILE, [COMPILE], LITERAL should have their own section
1.28 crook 25:
1.1 anton 26: @comment %**start of header (This is for running Texinfo on a region.)
27: @setfilename gforth.info
1.113 anton 28: @include version.texi
1.1 anton 29: @settitle Gforth Manual
1.113 anton 30: @c @syncodeindex pg cp
1.49 anton 31:
1.12 anton 32: @macro progstyle {}
33: Programming style note:
1.3 anton 34: @end macro
1.48 anton 35:
36: @macro assignment {}
37: @table @i
38: @item Assignment:
39: @end macro
40: @macro endassignment {}
41: @end table
42: @end macro
43:
1.29 crook 44: @comment macros for beautifying glossary entries
45: @macro GLOSS-START {}
46: @iftex
47: @ninerm
48: @end iftex
49: @end macro
50:
51: @macro GLOSS-END {}
52: @iftex
53: @rm
54: @end iftex
55: @end macro
56:
1.113 anton 57: @comment %**end of header (This is for running Texinfo on a region.)
58: @copying
1.125 anton 59: This manual is for Gforth (version @value{VERSION}, @value{UPDATED}),
60: a fast and portable implementation of the ANS Forth language. It
61: serves as reference manual, but it also contains an introduction to
62: Forth and a Forth tutorial.
1.29 crook 63:
1.191 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007 Free Software Foundation, Inc.
1.29 crook 65:
1.113 anton 66: @quotation
67: Permission is granted to copy, distribute and/or modify this document
68: under the terms of the GNU Free Documentation License, Version 1.1 or
69: any later version published by the Free Software Foundation; with no
70: Invariant Sections, with the Front-Cover texts being ``A GNU Manual,''
71: and with the Back-Cover Texts as in (a) below. A copy of the
72: license is included in the section entitled ``GNU Free Documentation
73: License.''
74:
75: (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify
76: this GNU Manual, like GNU software. Copies published by the Free
77: Software Foundation raise funds for GNU development.''
78: @end quotation
79: @end copying
1.10 anton 80:
1.113 anton 81: @dircategory Software development
82: @direntry
83: * Gforth: (gforth). A fast interpreter for the Forth language.
84: @end direntry
85: @c The Texinfo manual also recommends doing this, but for Gforth it may
86: @c not make much sense
87: @c @dircategory Individual utilities
88: @c @direntry
89: @c * Gforth: (gforth)Invoking Gforth. gforth, gforth-fast, gforthmi
90: @c @end direntry
1.1 anton 91:
92: @titlepage
1.113 anton 93: @title Gforth
94: @subtitle for version @value{VERSION}, @value{UPDATED}
95: @author Neal Crook
96: @author Anton Ertl
1.114 anton 97: @author David Kuehling
1.113 anton 98: @author Bernd Paysan
99: @author Jens Wilke
1.1 anton 100: @page
101: @vskip 0pt plus 1filll
1.113 anton 102: @insertcopying
103: @end titlepage
1.1 anton 104:
1.113 anton 105: @contents
1.1 anton 106:
1.113 anton 107: @ifnottex
108: @node Top, Goals, (dir), (dir)
109: @top Gforth
1.1 anton 110:
1.113 anton 111: @insertcopying
1.49 anton 112: @end ifnottex
1.1 anton 113:
114: @menu
1.26 crook 115: * Goals:: About the Gforth Project
1.29 crook 116: * Gforth Environment:: Starting (and exiting) Gforth
1.48 anton 117: * Tutorial:: Hands-on Forth Tutorial
1.21 crook 118: * Introduction:: An introduction to ANS Forth
1.1 anton 119: * Words:: Forth words available in Gforth
1.24 anton 120: * Error messages:: How to interpret them
1.1 anton 121: * Tools:: Programming tools
122: * ANS conformance:: Implementation-defined options etc.
1.65 anton 123: * Standard vs Extensions:: Should I use extensions?
1.1 anton 124: * Model:: The abstract machine of Gforth
125: * Integrating Gforth:: Forth as scripting language for applications
126: * Emacs and Gforth:: The Gforth Mode
127: * Image Files:: @code{.fi} files contain compiled code
128: * Engine:: The inner interpreter and the primitives
1.13 pazsan 129: * Cross Compiler:: The Cross Compiler
1.1 anton 130: * Bugs:: How to report them
131: * Origin:: Authors and ancestors of Gforth
1.21 crook 132: * Forth-related information:: Books and places to look on the WWW
1.113 anton 133: * Licenses::
1.1 anton 134: * Word Index:: An item for each Forth word
135: * Concept Index:: A menu covering many topics
1.12 anton 136:
1.91 anton 137: @detailmenu
138: --- The Detailed Node Listing ---
1.12 anton 139:
1.29 crook 140: Gforth Environment
141:
1.32 anton 142: * Invoking Gforth:: Getting in
143: * Leaving Gforth:: Getting out
144: * Command-line editing::
1.48 anton 145: * Environment variables:: that affect how Gforth starts up
1.32 anton 146: * Gforth Files:: What gets installed and where
1.112 anton 147: * Gforth in pipes::
1.48 anton 148: * Startup speed:: When 35ms is not fast enough ...
149:
150: Forth Tutorial
151:
152: * Starting Gforth Tutorial::
153: * Syntax Tutorial::
154: * Crash Course Tutorial::
155: * Stack Tutorial::
156: * Arithmetics Tutorial::
157: * Stack Manipulation Tutorial::
158: * Using files for Forth code Tutorial::
159: * Comments Tutorial::
160: * Colon Definitions Tutorial::
161: * Decompilation Tutorial::
162: * Stack-Effect Comments Tutorial::
163: * Types Tutorial::
164: * Factoring Tutorial::
165: * Designing the stack effect Tutorial::
166: * Local Variables Tutorial::
167: * Conditional execution Tutorial::
168: * Flags and Comparisons Tutorial::
169: * General Loops Tutorial::
170: * Counted loops Tutorial::
171: * Recursion Tutorial::
172: * Leaving definitions or loops Tutorial::
173: * Return Stack Tutorial::
174: * Memory Tutorial::
175: * Characters and Strings Tutorial::
176: * Alignment Tutorial::
1.190 anton 177: * Floating Point Tutorial::
1.87 anton 178: * Files Tutorial::
1.48 anton 179: * Interpretation and Compilation Semantics and Immediacy Tutorial::
180: * Execution Tokens Tutorial::
181: * Exceptions Tutorial::
182: * Defining Words Tutorial::
183: * Arrays and Records Tutorial::
184: * POSTPONE Tutorial::
185: * Literal Tutorial::
186: * Advanced macros Tutorial::
187: * Compilation Tokens Tutorial::
188: * Wordlists and Search Order Tutorial::
1.29 crook 189:
1.24 anton 190: An Introduction to ANS Forth
191:
1.67 anton 192: * Introducing the Text Interpreter::
193: * Stacks and Postfix notation::
194: * Your first definition::
195: * How does that work?::
196: * Forth is written in Forth::
197: * Review - elements of a Forth system::
198: * Where to go next::
199: * Exercises::
1.24 anton 200:
1.12 anton 201: Forth Words
202:
203: * Notation::
1.65 anton 204: * Case insensitivity::
205: * Comments::
206: * Boolean Flags::
1.12 anton 207: * Arithmetic::
208: * Stack Manipulation::
209: * Memory::
210: * Control Structures::
211: * Defining Words::
1.65 anton 212: * Interpretation and Compilation Semantics::
1.47 crook 213: * Tokens for Words::
1.81 anton 214: * Compiling words::
1.65 anton 215: * The Text Interpreter::
1.111 anton 216: * The Input Stream::
1.65 anton 217: * Word Lists::
218: * Environmental Queries::
1.12 anton 219: * Files::
220: * Blocks::
221: * Other I/O::
1.121 anton 222: * OS command line arguments::
1.78 anton 223: * Locals::
224: * Structures::
225: * Object-oriented Forth::
1.12 anton 226: * Programming Tools::
1.150 anton 227: * C Interface::
1.12 anton 228: * Assembler and Code Words::
229: * Threading Words::
1.65 anton 230: * Passing Commands to the OS::
231: * Keeping track of Time::
232: * Miscellaneous Words::
1.12 anton 233:
234: Arithmetic
235:
236: * Single precision::
1.67 anton 237: * Double precision:: Double-cell integer arithmetic
1.12 anton 238: * Bitwise operations::
1.67 anton 239: * Numeric comparison::
1.32 anton 240: * Mixed precision:: Operations with single and double-cell integers
1.12 anton 241: * Floating Point::
242:
243: Stack Manipulation
244:
245: * Data stack::
246: * Floating point stack::
247: * Return stack::
248: * Locals stack::
249: * Stack pointer manipulation::
250:
251: Memory
252:
1.32 anton 253: * Memory model::
254: * Dictionary allocation::
255: * Heap Allocation::
256: * Memory Access::
257: * Address arithmetic::
258: * Memory Blocks::
1.12 anton 259:
260: Control Structures
261:
1.41 anton 262: * Selection:: IF ... ELSE ... ENDIF
263: * Simple Loops:: BEGIN ...
1.32 anton 264: * Counted Loops:: DO
1.67 anton 265: * Arbitrary control structures::
266: * Calls and returns::
1.12 anton 267: * Exception Handling::
268:
269: Defining Words
270:
1.67 anton 271: * CREATE::
1.44 crook 272: * Variables:: Variables and user variables
1.67 anton 273: * Constants::
1.44 crook 274: * Values:: Initialised variables
1.67 anton 275: * Colon Definitions::
1.44 crook 276: * Anonymous Definitions:: Definitions without names
1.71 anton 277: * Supplying names:: Passing definition names as strings
1.67 anton 278: * User-defined Defining Words::
1.170 pazsan 279: * Deferred Words:: Allow forward references
1.67 anton 280: * Aliases::
1.47 crook 281:
1.63 anton 282: User-defined Defining Words
283:
284: * CREATE..DOES> applications::
285: * CREATE..DOES> details::
286: * Advanced does> usage example::
1.155 anton 287: * Const-does>::
1.63 anton 288:
1.47 crook 289: Interpretation and Compilation Semantics
290:
1.67 anton 291: * Combined words::
1.12 anton 292:
1.71 anton 293: Tokens for Words
294:
295: * Execution token:: represents execution/interpretation semantics
296: * Compilation token:: represents compilation semantics
297: * Name token:: represents named words
298:
1.82 anton 299: Compiling words
300:
301: * Literals:: Compiling data values
302: * Macros:: Compiling words
303:
1.21 crook 304: The Text Interpreter
305:
1.67 anton 306: * Input Sources::
307: * Number Conversion::
308: * Interpret/Compile states::
309: * Interpreter Directives::
1.21 crook 310:
1.26 crook 311: Word Lists
312:
1.75 anton 313: * Vocabularies::
1.67 anton 314: * Why use word lists?::
1.75 anton 315: * Word list example::
1.26 crook 316:
317: Files
318:
1.48 anton 319: * Forth source files::
320: * General files::
1.167 anton 321: * Redirection::
1.48 anton 322: * Search Paths::
323:
324: Search Paths
325:
1.75 anton 326: * Source Search Paths::
1.26 crook 327: * General Search Paths::
328:
329: Other I/O
330:
1.32 anton 331: * Simple numeric output:: Predefined formats
332: * Formatted numeric output:: Formatted (pictured) output
333: * String Formats:: How Forth stores strings in memory
1.67 anton 334: * Displaying characters and strings:: Other stuff
1.178 anton 335: * Terminal output:: Cursor positioning etc.
1.181 anton 336: * Single-key input::
337: * Line input and conversion::
1.112 anton 338: * Pipes:: How to create your own pipes
1.149 pazsan 339: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 340:
341: Locals
342:
343: * Gforth locals::
344: * ANS Forth locals::
345:
346: Gforth locals
347:
348: * Where are locals visible by name?::
349: * How long do locals live?::
1.78 anton 350: * Locals programming style::
351: * Locals implementation::
1.26 crook 352:
1.12 anton 353: Structures
354:
355: * Why explicit structure support?::
356: * Structure Usage::
357: * Structure Naming Convention::
358: * Structure Implementation::
359: * Structure Glossary::
1.183 anton 360: * Forth200x Structures::
1.12 anton 361:
362: Object-oriented Forth
363:
1.48 anton 364: * Why object-oriented programming?::
365: * Object-Oriented Terminology::
366: * Objects::
367: * OOF::
368: * Mini-OOF::
1.23 crook 369: * Comparison with other object models::
1.12 anton 370:
1.24 anton 371: The @file{objects.fs} model
1.12 anton 372:
373: * Properties of the Objects model::
374: * Basic Objects Usage::
1.41 anton 375: * The Objects base class::
1.12 anton 376: * Creating objects::
377: * Object-Oriented Programming Style::
378: * Class Binding::
379: * Method conveniences::
380: * Classes and Scoping::
1.41 anton 381: * Dividing classes::
1.12 anton 382: * Object Interfaces::
383: * Objects Implementation::
384: * Objects Glossary::
385:
1.24 anton 386: The @file{oof.fs} model
1.12 anton 387:
1.67 anton 388: * Properties of the OOF model::
389: * Basic OOF Usage::
390: * The OOF base class::
391: * Class Declaration::
392: * Class Implementation::
1.12 anton 393:
1.24 anton 394: The @file{mini-oof.fs} model
1.23 crook 395:
1.48 anton 396: * Basic Mini-OOF Usage::
397: * Mini-OOF Example::
398: * Mini-OOF Implementation::
1.23 crook 399:
1.78 anton 400: Programming Tools
401:
1.150 anton 402: * Examining:: Data and Code.
403: * Forgetting words:: Usually before reloading.
1.78 anton 404: * Debugging:: Simple and quick.
405: * Assertions:: Making your programs self-checking.
406: * Singlestep Debugger:: Executing your program word by word.
407:
1.155 anton 408: C Interface
409:
410: * Calling C Functions::
411: * Declaring C Functions::
1.180 anton 412: * Calling C function pointers::
1.155 anton 413: * Callbacks::
1.178 anton 414: * C interface internals::
1.155 anton 415: * Low-Level C Interface Words::
416:
1.78 anton 417: Assembler and Code Words
418:
419: * Code and ;code::
420: * Common Assembler:: Assembler Syntax
421: * Common Disassembler::
422: * 386 Assembler:: Deviations and special cases
423: * Alpha Assembler:: Deviations and special cases
424: * MIPS assembler:: Deviations and special cases
1.167 anton 425: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 426: * ARM Assembler:: Deviations and special cases
1.78 anton 427: * Other assemblers:: How to write them
428:
1.12 anton 429: Tools
430:
431: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 432: * Stack depth changes:: Where does this stack item come from?
1.12 anton 433:
434: ANS conformance
435:
436: * The Core Words::
437: * The optional Block word set::
438: * The optional Double Number word set::
439: * The optional Exception word set::
440: * The optional Facility word set::
441: * The optional File-Access word set::
442: * The optional Floating-Point word set::
443: * The optional Locals word set::
444: * The optional Memory-Allocation word set::
445: * The optional Programming-Tools word set::
446: * The optional Search-Order word set::
447:
448: The Core Words
449:
450: * core-idef:: Implementation Defined Options
451: * core-ambcond:: Ambiguous Conditions
452: * core-other:: Other System Documentation
453:
454: The optional Block word set
455:
456: * block-idef:: Implementation Defined Options
457: * block-ambcond:: Ambiguous Conditions
458: * block-other:: Other System Documentation
459:
460: The optional Double Number word set
461:
462: * double-ambcond:: Ambiguous Conditions
463:
464: The optional Exception word set
465:
466: * exception-idef:: Implementation Defined Options
467:
468: The optional Facility word set
469:
470: * facility-idef:: Implementation Defined Options
471: * facility-ambcond:: Ambiguous Conditions
472:
473: The optional File-Access word set
474:
475: * file-idef:: Implementation Defined Options
476: * file-ambcond:: Ambiguous Conditions
477:
478: The optional Floating-Point word set
479:
480: * floating-idef:: Implementation Defined Options
481: * floating-ambcond:: Ambiguous Conditions
482:
483: The optional Locals word set
484:
485: * locals-idef:: Implementation Defined Options
486: * locals-ambcond:: Ambiguous Conditions
487:
488: The optional Memory-Allocation word set
489:
490: * memory-idef:: Implementation Defined Options
491:
492: The optional Programming-Tools word set
493:
494: * programming-idef:: Implementation Defined Options
495: * programming-ambcond:: Ambiguous Conditions
496:
497: The optional Search-Order word set
498:
499: * search-idef:: Implementation Defined Options
500: * search-ambcond:: Ambiguous Conditions
501:
1.109 anton 502: Emacs and Gforth
503:
504: * Installing gforth.el:: Making Emacs aware of Forth.
505: * Emacs Tags:: Viewing the source of a word in Emacs.
506: * Hilighting:: Making Forth code look prettier.
507: * Auto-Indentation:: Customizing auto-indentation.
508: * Blocks Files:: Reading and writing blocks files.
509:
1.12 anton 510: Image Files
511:
1.24 anton 512: * Image Licensing Issues:: Distribution terms for images.
513: * Image File Background:: Why have image files?
1.67 anton 514: * Non-Relocatable Image Files:: don't always work.
1.24 anton 515: * Data-Relocatable Image Files:: are better.
1.67 anton 516: * Fully Relocatable Image Files:: better yet.
1.24 anton 517: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 518: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 519: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 520:
521: Fully Relocatable Image Files
522:
1.27 crook 523: * gforthmi:: The normal way
1.12 anton 524: * cross.fs:: The hard way
525:
526: Engine
527:
528: * Portability::
529: * Threading::
530: * Primitives::
531: * Performance::
532:
533: Threading
534:
535: * Scheduling::
536: * Direct or Indirect Threaded?::
1.109 anton 537: * Dynamic Superinstructions::
1.12 anton 538: * DOES>::
539:
540: Primitives
541:
542: * Automatic Generation::
543: * TOS Optimization::
544: * Produced code::
1.13 pazsan 545:
546: Cross Compiler
547:
1.67 anton 548: * Using the Cross Compiler::
549: * How the Cross Compiler Works::
1.13 pazsan 550:
1.113 anton 551: Licenses
552:
553: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 554: * Copying:: GPL (for copying this software).
1.113 anton 555:
1.24 anton 556: @end detailmenu
1.1 anton 557: @end menu
558:
1.113 anton 559: @c ----------------------------------------------------------
1.1 anton 560: @iftex
561: @unnumbered Preface
562: @cindex Preface
1.21 crook 563: This manual documents Gforth. Some introductory material is provided for
564: readers who are unfamiliar with Forth or who are migrating to Gforth
565: from other Forth compilers. However, this manual is primarily a
566: reference manual.
1.1 anton 567: @end iftex
568:
1.28 crook 569: @comment TODO much more blurb here.
1.26 crook 570:
571: @c ******************************************************************
1.113 anton 572: @node Goals, Gforth Environment, Top, Top
1.26 crook 573: @comment node-name, next, previous, up
574: @chapter Goals of Gforth
575: @cindex goals of the Gforth project
576: The goal of the Gforth Project is to develop a standard model for
577: ANS Forth. This can be split into several subgoals:
578:
579: @itemize @bullet
580: @item
581: Gforth should conform to the ANS Forth Standard.
582: @item
583: It should be a model, i.e. it should define all the
584: implementation-dependent things.
585: @item
586: It should become standard, i.e. widely accepted and used. This goal
587: is the most difficult one.
588: @end itemize
589:
590: To achieve these goals Gforth should be
591: @itemize @bullet
592: @item
593: Similar to previous models (fig-Forth, F83)
594: @item
595: Powerful. It should provide for all the things that are considered
596: necessary today and even some that are not yet considered necessary.
597: @item
598: Efficient. It should not get the reputation of being exceptionally
599: slow.
600: @item
601: Free.
602: @item
603: Available on many machines/easy to port.
604: @end itemize
605:
606: Have we achieved these goals? Gforth conforms to the ANS Forth
607: standard. It may be considered a model, but we have not yet documented
608: which parts of the model are stable and which parts we are likely to
609: change. It certainly has not yet become a de facto standard, but it
610: appears to be quite popular. It has some similarities to and some
611: differences from previous models. It has some powerful features, but not
612: yet everything that we envisioned. We certainly have achieved our
1.65 anton 613: execution speed goals (@pxref{Performance})@footnote{However, in 1998
614: the bar was raised when the major commercial Forth vendors switched to
615: native code compilers.}. It is free and available on many machines.
1.29 crook 616:
1.26 crook 617: @c ******************************************************************
1.48 anton 618: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 619: @chapter Gforth Environment
620: @cindex Gforth environment
1.21 crook 621:
1.45 crook 622: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 623: material in this chapter.
1.21 crook 624:
625: @menu
1.29 crook 626: * Invoking Gforth:: Getting in
627: * Leaving Gforth:: Getting out
628: * Command-line editing::
1.48 anton 629: * Environment variables:: that affect how Gforth starts up
1.29 crook 630: * Gforth Files:: What gets installed and where
1.112 anton 631: * Gforth in pipes::
1.48 anton 632: * Startup speed:: When 35ms is not fast enough ...
1.21 crook 633: @end menu
634:
1.49 anton 635: For related information about the creation of images see @ref{Image Files}.
1.29 crook 636:
1.21 crook 637: @comment ----------------------------------------------
1.48 anton 638: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 639: @section Invoking Gforth
640: @cindex invoking Gforth
641: @cindex running Gforth
642: @cindex command-line options
643: @cindex options on the command line
644: @cindex flags on the command line
1.21 crook 645:
1.30 anton 646: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 647: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 648: will usually just say @code{gforth} -- this automatically loads the
649: default image file @file{gforth.fi}. In many other cases the default
650: Gforth image will be invoked like this:
1.21 crook 651: @example
1.30 anton 652: gforth [file | -e forth-code] ...
1.21 crook 653: @end example
1.29 crook 654: @noindent
655: This interprets the contents of the files and the Forth code in the order they
656: are given.
1.21 crook 657:
1.109 anton 658: In addition to the @command{gforth} engine, there is also an engine
659: called @command{gforth-fast}, which is faster, but gives less
660: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 661: errors (in particular, stack underflows and integer division errors)
662: later or not at all. You should use it for debugged,
1.109 anton 663: performance-critical programs.
664:
665: Moreover, there is an engine called @command{gforth-itc}, which is
666: useful in some backwards-compatibility situations (@pxref{Direct or
667: Indirect Threaded?}).
1.30 anton 668:
1.29 crook 669: In general, the command line looks like this:
1.21 crook 670:
671: @example
1.30 anton 672: gforth[-fast] [engine options] [image options]
1.21 crook 673: @end example
674:
1.30 anton 675: The engine options must come before the rest of the command
1.29 crook 676: line. They are:
1.26 crook 677:
1.29 crook 678: @table @code
679: @cindex -i, command-line option
680: @cindex --image-file, command-line option
681: @item --image-file @i{file}
682: @itemx -i @i{file}
683: Loads the Forth image @i{file} instead of the default
684: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 685:
1.39 anton 686: @cindex --appl-image, command-line option
687: @item --appl-image @i{file}
688: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 689: to the image (instead of processing them as engine options). This is
690: useful for building executable application images on Unix, built with
1.39 anton 691: @code{gforthmi --application ...}.
692:
1.29 crook 693: @cindex --path, command-line option
694: @cindex -p, command-line option
695: @item --path @i{path}
696: @itemx -p @i{path}
697: Uses @i{path} for searching the image file and Forth source code files
698: instead of the default in the environment variable @code{GFORTHPATH} or
699: the path specified at installation time (e.g.,
700: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
701: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 702:
1.29 crook 703: @cindex --dictionary-size, command-line option
704: @cindex -m, command-line option
705: @cindex @i{size} parameters for command-line options
706: @cindex size of the dictionary and the stacks
707: @item --dictionary-size @i{size}
708: @itemx -m @i{size}
709: Allocate @i{size} space for the Forth dictionary space instead of
710: using the default specified in the image (typically 256K). The
711: @i{size} specification for this and subsequent options consists of
712: an integer and a unit (e.g.,
713: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
714: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
715: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
716: @code{e} is used.
1.21 crook 717:
1.29 crook 718: @cindex --data-stack-size, command-line option
719: @cindex -d, command-line option
720: @item --data-stack-size @i{size}
721: @itemx -d @i{size}
722: Allocate @i{size} space for the data stack instead of using the
723: default specified in the image (typically 16K).
1.21 crook 724:
1.29 crook 725: @cindex --return-stack-size, command-line option
726: @cindex -r, command-line option
727: @item --return-stack-size @i{size}
728: @itemx -r @i{size}
729: Allocate @i{size} space for the return stack instead of using the
730: default specified in the image (typically 15K).
1.21 crook 731:
1.29 crook 732: @cindex --fp-stack-size, command-line option
733: @cindex -f, command-line option
734: @item --fp-stack-size @i{size}
735: @itemx -f @i{size}
736: Allocate @i{size} space for the floating point stack instead of
737: using the default specified in the image (typically 15.5K). In this case
738: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 739:
1.48 anton 740: @cindex --locals-stack-size, command-line option
741: @cindex -l, command-line option
742: @item --locals-stack-size @i{size}
743: @itemx -l @i{size}
744: Allocate @i{size} space for the locals stack instead of using the
745: default specified in the image (typically 14.5K).
746:
1.176 anton 747: @cindex --vm-commit, command-line option
748: @cindex overcommit memory for dictionary and stacks
749: @cindex memory overcommit for dictionary and stacks
750: @item --vm-commit
751: Normally, Gforth tries to start up even if there is not enough virtual
752: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
753: on OSs that support it); so you can ask for a really big dictionary
754: and/or stacks, and as long as you don't use more virtual memory than
755: is available, everything will be fine (but if you use more, processes
756: get killed). With this option you just use the default allocation
757: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
758: means that you cannot and should not ask for as big dictionary and
759: stacks, but once Gforth successfully starts up, out-of-memory won't
760: kill it.
761:
1.48 anton 762: @cindex -h, command-line option
763: @cindex --help, command-line option
764: @item --help
765: @itemx -h
766: Print a message about the command-line options
767:
768: @cindex -v, command-line option
769: @cindex --version, command-line option
770: @item --version
771: @itemx -v
772: Print version and exit
773:
774: @cindex --debug, command-line option
775: @item --debug
776: Print some information useful for debugging on startup.
777:
778: @cindex --offset-image, command-line option
779: @item --offset-image
780: Start the dictionary at a slightly different position than would be used
781: otherwise (useful for creating data-relocatable images,
782: @pxref{Data-Relocatable Image Files}).
783:
784: @cindex --no-offset-im, command-line option
785: @item --no-offset-im
786: Start the dictionary at the normal position.
787:
788: @cindex --clear-dictionary, command-line option
789: @item --clear-dictionary
790: Initialize all bytes in the dictionary to 0 before loading the image
791: (@pxref{Data-Relocatable Image Files}).
792:
793: @cindex --die-on-signal, command-line-option
794: @item --die-on-signal
795: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
796: or the segmentation violation SIGSEGV) by translating it into a Forth
797: @code{THROW}. With this option, Gforth exits if it receives such a
798: signal. This option is useful when the engine and/or the image might be
799: severely broken (such that it causes another signal before recovering
800: from the first); this option avoids endless loops in such cases.
1.109 anton 801:
1.119 anton 802: @cindex --no-dynamic, command-line option
803: @cindex --dynamic, command-line option
1.109 anton 804: @item --no-dynamic
805: @item --dynamic
806: Disable or enable dynamic superinstructions with replication
807: (@pxref{Dynamic Superinstructions}).
808:
1.119 anton 809: @cindex --no-super, command-line option
1.109 anton 810: @item --no-super
1.110 anton 811: Disable dynamic superinstructions, use just dynamic replication; this is
812: useful if you want to patch threaded code (@pxref{Dynamic
813: Superinstructions}).
1.119 anton 814:
815: @cindex --ss-number, command-line option
816: @item --ss-number=@var{N}
817: Use only the first @var{N} static superinstructions compiled into the
818: engine (default: use them all; note that only @code{gforth-fast} has
819: any). This option is useful for measuring the performance impact of
820: static superinstructions.
821:
822: @cindex --ss-min-..., command-line options
823: @item --ss-min-codesize
824: @item --ss-min-ls
825: @item --ss-min-lsu
826: @item --ss-min-nexts
827: Use specified metric for determining the cost of a primitive or static
828: superinstruction for static superinstruction selection. @code{Codesize}
829: is the native code size of the primive or static superinstruction,
830: @code{ls} is the number of loads and stores, @code{lsu} is the number of
831: loads, stores, and updates, and @code{nexts} is the number of dispatches
832: (not taking dynamic superinstructions into account), i.e. every
833: primitive or static superinstruction has cost 1. Default:
834: @code{codesize} if you use dynamic code generation, otherwise
835: @code{nexts}.
836:
837: @cindex --ss-greedy, command-line option
838: @item --ss-greedy
839: This option is useful for measuring the performance impact of static
840: superinstructions. By default, an optimal shortest-path algorithm is
841: used for selecting static superinstructions. With @option{--ss-greedy}
842: this algorithm is modified to assume that anything after the static
843: superinstruction currently under consideration is not combined into
844: static superinstructions. With @option{--ss-min-nexts} this produces
845: the same result as a greedy algorithm that always selects the longest
846: superinstruction available at the moment. E.g., if there are
847: superinstructions AB and BCD, then for the sequence A B C D the optimal
848: algorithm will select A BCD and the greedy algorithm will select AB C D.
849:
850: @cindex --print-metrics, command-line option
851: @item --print-metrics
852: Prints some metrics used during static superinstruction selection:
853: @code{code size} is the actual size of the dynamically generated code.
854: @code{Metric codesize} is the sum of the codesize metrics as seen by
855: static superinstruction selection; there is a difference from @code{code
856: size}, because not all primitives and static superinstructions are
857: compiled into dynamically generated code, and because of markers. The
858: other metrics correspond to the @option{ss-min-...} options. This
859: option is useful for evaluating the effects of the @option{--ss-...}
860: options.
1.109 anton 861:
1.48 anton 862: @end table
863:
864: @cindex loading files at startup
865: @cindex executing code on startup
866: @cindex batch processing with Gforth
867: As explained above, the image-specific command-line arguments for the
868: default image @file{gforth.fi} consist of a sequence of filenames and
869: @code{-e @var{forth-code}} options that are interpreted in the sequence
870: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 871: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
872: option takes only one argument; if you want to evaluate more Forth
873: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 874: after processing the command line (instead of entering interactive mode)
1.121 anton 875: append @code{-e bye} to the command line. You can also process the
876: command-line arguments with a Forth program (@pxref{OS command line
877: arguments}).
1.48 anton 878:
879: @cindex versions, invoking other versions of Gforth
880: If you have several versions of Gforth installed, @code{gforth} will
881: invoke the version that was installed last. @code{gforth-@i{version}}
882: invokes a specific version. If your environment contains the variable
883: @code{GFORTHPATH}, you may want to override it by using the
884: @code{--path} option.
885:
886: Not yet implemented:
887: On startup the system first executes the system initialization file
888: (unless the option @code{--no-init-file} is given; note that the system
889: resulting from using this option may not be ANS Forth conformant). Then
890: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 891: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 892: then in @file{~}, then in the normal path (see above).
893:
894:
895:
896: @comment ----------------------------------------------
897: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
898: @section Leaving Gforth
899: @cindex Gforth - leaving
900: @cindex leaving Gforth
901:
902: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
903: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
904: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 905: data are discarded. For ways of saving the state of the system before
906: leaving Gforth see @ref{Image Files}.
1.48 anton 907:
908: doc-bye
909:
910:
911: @comment ----------------------------------------------
1.65 anton 912: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 913: @section Command-line editing
914: @cindex command-line editing
915:
916: Gforth maintains a history file that records every line that you type to
917: the text interpreter. This file is preserved between sessions, and is
918: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
919: repeatedly you can recall successively older commands from this (or
920: previous) session(s). The full list of command-line editing facilities is:
921:
922: @itemize @bullet
923: @item
924: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
925: commands from the history buffer.
926: @item
927: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
928: from the history buffer.
929: @item
930: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
931: @item
932: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
933: @item
934: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
935: closing up the line.
936: @item
937: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
938: @item
939: @kbd{Ctrl-a} to move the cursor to the start of the line.
940: @item
941: @kbd{Ctrl-e} to move the cursor to the end of the line.
942: @item
943: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
944: line.
945: @item
946: @key{TAB} to step through all possible full-word completions of the word
947: currently being typed.
948: @item
1.65 anton 949: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
950: using @code{bye}).
951: @item
952: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
953: character under the cursor.
1.48 anton 954: @end itemize
955:
956: When editing, displayable characters are inserted to the left of the
957: cursor position; the line is always in ``insert'' (as opposed to
958: ``overstrike'') mode.
959:
960: @cindex history file
961: @cindex @file{.gforth-history}
962: On Unix systems, the history file is @file{~/.gforth-history} by
963: default@footnote{i.e. it is stored in the user's home directory.}. You
964: can find out the name and location of your history file using:
965:
966: @example
967: history-file type \ Unix-class systems
968:
969: history-file type \ Other systems
970: history-dir type
971: @end example
972:
973: If you enter long definitions by hand, you can use a text editor to
974: paste them out of the history file into a Forth source file for reuse at
975: a later time.
976:
977: Gforth never trims the size of the history file, so you should do this
978: periodically, if necessary.
979:
980: @comment this is all defined in history.fs
981: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
982: @comment chosen?
983:
984:
985: @comment ----------------------------------------------
1.65 anton 986: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 987: @section Environment variables
988: @cindex environment variables
989:
990: Gforth uses these environment variables:
991:
992: @itemize @bullet
993: @item
994: @cindex @code{GFORTHHIST} -- environment variable
995: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
996: open/create the history file, @file{.gforth-history}. Default:
997: @code{$HOME}.
998:
999: @item
1000: @cindex @code{GFORTHPATH} -- environment variable
1001: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1002: for Forth source-code files.
1003:
1004: @item
1.147 anton 1005: @cindex @code{LANG} -- environment variable
1006: @code{LANG} -- see @code{LC_CTYPE}
1007:
1008: @item
1009: @cindex @code{LC_ALL} -- environment variable
1010: @code{LC_ALL} -- see @code{LC_CTYPE}
1011:
1012: @item
1013: @cindex @code{LC_CTYPE} -- environment variable
1014: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1015: startup, Gforth uses the UTF-8 encoding for strings internally and
1016: expects its input and produces its output in UTF-8 encoding, otherwise
1017: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1018: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1019: that is unset, in @code{LANG}.
1020:
1021: @item
1.129 anton 1022: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1023:
1024: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1025: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1026: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1027: and the command are directly concatenated, so if a space between them is
1028: necessary, append it to the prefix.
1029:
1030: @item
1.48 anton 1031: @cindex @code{GFORTH} -- environment variable
1.49 anton 1032: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1033:
1034: @item
1035: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1036: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1037:
1038: @item
1039: @cindex @code{TMP}, @code{TEMP} - environment variable
1040: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1041: location for the history file.
1042: @end itemize
1043:
1044: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1045: @comment mentioning these.
1046:
1047: All the Gforth environment variables default to sensible values if they
1048: are not set.
1049:
1050:
1051: @comment ----------------------------------------------
1.112 anton 1052: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1053: @section Gforth files
1054: @cindex Gforth files
1055:
1056: When you install Gforth on a Unix system, it installs files in these
1057: locations by default:
1058:
1059: @itemize @bullet
1060: @item
1061: @file{/usr/local/bin/gforth}
1062: @item
1063: @file{/usr/local/bin/gforthmi}
1064: @item
1065: @file{/usr/local/man/man1/gforth.1} - man page.
1066: @item
1067: @file{/usr/local/info} - the Info version of this manual.
1068: @item
1069: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1070: @item
1071: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1072: @item
1073: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1074: @item
1075: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1076: @end itemize
1077:
1078: You can select different places for installation by using
1079: @code{configure} options (listed with @code{configure --help}).
1080:
1081: @comment ----------------------------------------------
1.112 anton 1082: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1083: @section Gforth in pipes
1084: @cindex pipes, Gforth as part of
1085:
1086: Gforth can be used in pipes created elsewhere (described here). It can
1087: also create pipes on its own (@pxref{Pipes}).
1088:
1089: @cindex input from pipes
1090: If you pipe into Gforth, your program should read with @code{read-file}
1091: or @code{read-line} from @code{stdin} (@pxref{General files}).
1092: @code{Key} does not recognize the end of input. Words like
1093: @code{accept} echo the input and are therefore usually not useful for
1094: reading from a pipe. You have to invoke the Forth program with an OS
1095: command-line option, as you have no chance to use the Forth command line
1096: (the text interpreter would try to interpret the pipe input).
1097:
1098: @cindex output in pipes
1099: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1100:
1101: @cindex silent exiting from Gforth
1102: When you write to a pipe that has been closed at the other end, Gforth
1103: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1104: into the exception @code{broken-pipe-error}. If your application does
1105: not catch that exception, the system catches it and exits, usually
1106: silently (unless you were working on the Forth command line; then it
1107: prints an error message and exits). This is usually the desired
1108: behaviour.
1109:
1110: If you do not like this behaviour, you have to catch the exception
1111: yourself, and react to it.
1112:
1113: Here's an example of an invocation of Gforth that is usable in a pipe:
1114:
1115: @example
1116: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1117: type repeat ; foo bye"
1118: @end example
1119:
1120: This example just copies the input verbatim to the output. A very
1121: simple pipe containing this example looks like this:
1122:
1123: @example
1124: cat startup.fs |
1125: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1126: type repeat ; foo bye"|
1127: head
1128: @end example
1129:
1130: @cindex stderr and pipes
1131: Pipes involving Gforth's @code{stderr} output do not work.
1132:
1133: @comment ----------------------------------------------
1134: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1135: @section Startup speed
1136: @cindex Startup speed
1137: @cindex speed, startup
1138:
1139: If Gforth is used for CGI scripts or in shell scripts, its startup
1140: speed may become a problem. On a 300MHz 21064a under Linux-2.2.13 with
1141: glibc-2.0.7, @code{gforth -e bye} takes about 24.6ms user and 11.3ms
1142: system time.
1143:
1144: If startup speed is a problem, you may consider the following ways to
1145: improve it; or you may consider ways to reduce the number of startups
1.62 crook 1146: (for example, by using Fast-CGI).
1.48 anton 1147:
1.112 anton 1148: An easy step that influences Gforth startup speed is the use of the
1149: @option{--no-dynamic} option; this decreases image loading speed, but
1150: increases compile-time and run-time.
1151:
1152: Another step to improve startup speed is to statically link Gforth, by
1.48 anton 1153: building it with @code{XLDFLAGS=-static}. This requires more memory for
1154: the code and will therefore slow down the first invocation, but
1155: subsequent invocations avoid the dynamic linking overhead. Another
1156: disadvantage is that Gforth won't profit from library upgrades. As a
1157: result, @code{gforth-static -e bye} takes about 17.1ms user and
1158: 8.2ms system time.
1159:
1160: The next step to improve startup speed is to use a non-relocatable image
1.65 anton 1161: (@pxref{Non-Relocatable Image Files}). You can create this image with
1.48 anton 1162: @code{gforth -e "savesystem gforthnr.fi bye"} and later use it with
1163: @code{gforth -i gforthnr.fi ...}. This avoids the relocation overhead
1164: and a part of the copy-on-write overhead. The disadvantage is that the
1.62 crook 1165: non-relocatable image does not work if the OS gives Gforth a different
1.48 anton 1166: address for the dictionary, for whatever reason; so you better provide a
1167: fallback on a relocatable image. @code{gforth-static -i gforthnr.fi -e
1168: bye} takes about 15.3ms user and 7.5ms system time.
1169:
1170: The final step is to disable dictionary hashing in Gforth. Gforth
1171: builds the hash table on startup, which takes much of the startup
1172: overhead. You can do this by commenting out the @code{include hash.fs}
1173: in @file{startup.fs} and everything that requires @file{hash.fs} (at the
1174: moment @file{table.fs} and @file{ekey.fs}) and then doing @code{make}.
1175: The disadvantages are that functionality like @code{table} and
1176: @code{ekey} is missing and that text interpretation (e.g., compiling)
1177: now takes much longer. So, you should only use this method if there is
1178: no significant text interpretation to perform (the script should be
1.62 crook 1179: compiled into the image, amongst other things). @code{gforth-static -i
1.48 anton 1180: gforthnrnh.fi -e bye} takes about 2.1ms user and 6.1ms system time.
1181:
1182: @c ******************************************************************
1183: @node Tutorial, Introduction, Gforth Environment, Top
1184: @chapter Forth Tutorial
1185: @cindex Tutorial
1186: @cindex Forth Tutorial
1187:
1.67 anton 1188: @c Topics from nac's Introduction that could be mentioned:
1189: @c press <ret> after each line
1190: @c Prompt
1191: @c numbers vs. words in dictionary on text interpretation
1192: @c what happens on redefinition
1193: @c parsing words (in particular, defining words)
1194:
1.83 anton 1195: The difference of this chapter from the Introduction
1196: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1197: be used while sitting in front of a computer, and covers much more
1198: material, but does not explain how the Forth system works.
1199:
1.62 crook 1200: This tutorial can be used with any ANS-compliant Forth; any
1201: Gforth-specific features are marked as such and you can skip them if you
1202: work with another Forth. This tutorial does not explain all features of
1203: Forth, just enough to get you started and give you some ideas about the
1204: facilities available in Forth. Read the rest of the manual and the
1205: standard when you are through this.
1.48 anton 1206:
1207: The intended way to use this tutorial is that you work through it while
1208: sitting in front of the console, take a look at the examples and predict
1209: what they will do, then try them out; if the outcome is not as expected,
1210: find out why (e.g., by trying out variations of the example), so you
1211: understand what's going on. There are also some assignments that you
1212: should solve.
1213:
1214: This tutorial assumes that you have programmed before and know what,
1215: e.g., a loop is.
1216:
1217: @c !! explain compat library
1218:
1219: @menu
1220: * Starting Gforth Tutorial::
1221: * Syntax Tutorial::
1222: * Crash Course Tutorial::
1223: * Stack Tutorial::
1224: * Arithmetics Tutorial::
1225: * Stack Manipulation Tutorial::
1226: * Using files for Forth code Tutorial::
1227: * Comments Tutorial::
1228: * Colon Definitions Tutorial::
1229: * Decompilation Tutorial::
1230: * Stack-Effect Comments Tutorial::
1231: * Types Tutorial::
1232: * Factoring Tutorial::
1233: * Designing the stack effect Tutorial::
1234: * Local Variables Tutorial::
1235: * Conditional execution Tutorial::
1236: * Flags and Comparisons Tutorial::
1237: * General Loops Tutorial::
1238: * Counted loops Tutorial::
1239: * Recursion Tutorial::
1240: * Leaving definitions or loops Tutorial::
1241: * Return Stack Tutorial::
1242: * Memory Tutorial::
1243: * Characters and Strings Tutorial::
1244: * Alignment Tutorial::
1.190 anton 1245: * Floating Point Tutorial::
1.87 anton 1246: * Files Tutorial::
1.48 anton 1247: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1248: * Execution Tokens Tutorial::
1249: * Exceptions Tutorial::
1250: * Defining Words Tutorial::
1251: * Arrays and Records Tutorial::
1252: * POSTPONE Tutorial::
1253: * Literal Tutorial::
1254: * Advanced macros Tutorial::
1255: * Compilation Tokens Tutorial::
1256: * Wordlists and Search Order Tutorial::
1257: @end menu
1258:
1259: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1260: @section Starting Gforth
1.66 anton 1261: @cindex starting Gforth tutorial
1.48 anton 1262: You can start Gforth by typing its name:
1263:
1264: @example
1265: gforth
1266: @end example
1267:
1268: That puts you into interactive mode; you can leave Gforth by typing
1269: @code{bye}. While in Gforth, you can edit the command line and access
1270: the command line history with cursor keys, similar to bash.
1271:
1272:
1273: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1274: @section Syntax
1.66 anton 1275: @cindex syntax tutorial
1.48 anton 1276:
1.171 anton 1277: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1278: space). Words are separated by white space. E.g., each of the
1279: following lines contains exactly one word:
1280:
1281: @example
1282: word
1283: !@@#$%^&*()
1284: 1234567890
1285: 5!a
1286: @end example
1287:
1288: A frequent beginner's error is to leave away necessary white space,
1289: resulting in an error like @samp{Undefined word}; so if you see such an
1290: error, check if you have put spaces wherever necessary.
1291:
1292: @example
1293: ." hello, world" \ correct
1294: ."hello, world" \ gives an "Undefined word" error
1295: @end example
1296:
1.65 anton 1297: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1298: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1299: your system is case-sensitive, you may have to type all the examples
1300: given here in upper case.
1301:
1302:
1303: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1304: @section Crash Course
1305:
1306: Type
1307:
1308: @example
1309: 0 0 !
1310: here execute
1311: ' catch >body 20 erase abort
1312: ' (quit) >body 20 erase
1313: @end example
1314:
1315: The last two examples are guaranteed to destroy parts of Gforth (and
1316: most other systems), so you better leave Gforth afterwards (if it has
1317: not finished by itself). On some systems you may have to kill gforth
1318: from outside (e.g., in Unix with @code{kill}).
1319:
1320: Now that you know how to produce crashes (and that there's not much to
1321: them), let's learn how to produce meaningful programs.
1322:
1323:
1324: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1325: @section Stack
1.66 anton 1326: @cindex stack tutorial
1.48 anton 1327:
1328: The most obvious feature of Forth is the stack. When you type in a
1329: number, it is pushed on the stack. You can display the content of the
1330: stack with @code{.s}.
1331:
1332: @example
1333: 1 2 .s
1334: 3 .s
1335: @end example
1336:
1337: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1338: appear in @code{.s} output as they appeared in the input.
1339:
1340: You can print the top of stack element with @code{.}.
1341:
1342: @example
1343: 1 2 3 . . .
1344: @end example
1345:
1346: In general, words consume their stack arguments (@code{.s} is an
1347: exception).
1348:
1.141 anton 1349: @quotation Assignment
1.48 anton 1350: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1351: @end quotation
1.48 anton 1352:
1353:
1354: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1355: @section Arithmetics
1.66 anton 1356: @cindex arithmetics tutorial
1.48 anton 1357:
1358: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1359: operate on the top two stack items:
1360:
1361: @example
1.67 anton 1362: 2 2 .s
1363: + .s
1364: .
1.48 anton 1365: 2 1 - .
1366: 7 3 mod .
1367: @end example
1368:
1369: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1370: as in the corresponding infix expression (this is generally the case in
1371: Forth).
1372:
1373: Parentheses are superfluous (and not available), because the order of
1374: the words unambiguously determines the order of evaluation and the
1375: operands:
1376:
1377: @example
1378: 3 4 + 5 * .
1379: 3 4 5 * + .
1380: @end example
1381:
1.141 anton 1382: @quotation Assignment
1.48 anton 1383: What are the infix expressions corresponding to the Forth code above?
1384: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1385: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1386: @end quotation
1.48 anton 1387:
1388: To change the sign, use @code{negate}:
1389:
1390: @example
1391: 2 negate .
1392: @end example
1393:
1.141 anton 1394: @quotation Assignment
1.48 anton 1395: Convert -(-3)*4-5 to Forth.
1.141 anton 1396: @end quotation
1.48 anton 1397:
1398: @code{/mod} performs both @code{/} and @code{mod}.
1399:
1400: @example
1401: 7 3 /mod . .
1402: @end example
1403:
1.66 anton 1404: Reference: @ref{Arithmetic}.
1405:
1406:
1.48 anton 1407: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1408: @section Stack Manipulation
1.66 anton 1409: @cindex stack manipulation tutorial
1.48 anton 1410:
1411: Stack manipulation words rearrange the data on the stack.
1412:
1413: @example
1414: 1 .s drop .s
1415: 1 .s dup .s drop drop .s
1416: 1 2 .s over .s drop drop drop
1417: 1 2 .s swap .s drop drop
1418: 1 2 3 .s rot .s drop drop drop
1419: @end example
1420:
1421: These are the most important stack manipulation words. There are also
1422: variants that manipulate twice as many stack items:
1423:
1424: @example
1425: 1 2 3 4 .s 2swap .s 2drop 2drop
1426: @end example
1427:
1428: Two more stack manipulation words are:
1429:
1430: @example
1431: 1 2 .s nip .s drop
1432: 1 2 .s tuck .s 2drop drop
1433: @end example
1434:
1.141 anton 1435: @quotation Assignment
1.48 anton 1436: Replace @code{nip} and @code{tuck} with combinations of other stack
1437: manipulation words.
1438:
1439: @example
1440: Given: How do you get:
1441: 1 2 3 3 2 1
1442: 1 2 3 1 2 3 2
1443: 1 2 3 1 2 3 3
1444: 1 2 3 1 3 3
1445: 1 2 3 2 1 3
1446: 1 2 3 4 4 3 2 1
1447: 1 2 3 1 2 3 1 2 3
1448: 1 2 3 4 1 2 3 4 1 2
1449: 1 2 3
1450: 1 2 3 1 2 3 4
1451: 1 2 3 1 3
1452: @end example
1.141 anton 1453: @end quotation
1.48 anton 1454:
1455: @example
1456: 5 dup * .
1457: @end example
1458:
1.141 anton 1459: @quotation Assignment
1.48 anton 1460: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1461: Write a piece of Forth code that expects two numbers on the stack
1462: (@var{a} and @var{b}, with @var{b} on top) and computes
1463: @code{(a-b)(a+1)}.
1.141 anton 1464: @end quotation
1.48 anton 1465:
1.66 anton 1466: Reference: @ref{Stack Manipulation}.
1467:
1468:
1.48 anton 1469: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1470: @section Using files for Forth code
1.66 anton 1471: @cindex loading Forth code, tutorial
1472: @cindex files containing Forth code, tutorial
1.48 anton 1473:
1474: While working at the Forth command line is convenient for one-line
1475: examples and short one-off code, you probably want to store your source
1476: code in files for convenient editing and persistence. You can use your
1477: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1478: Gforth}) to create @var{file.fs} and use
1.48 anton 1479:
1480: @example
1.102 anton 1481: s" @var{file.fs}" included
1.48 anton 1482: @end example
1483:
1484: to load it into your Forth system. The file name extension I use for
1485: Forth files is @samp{.fs}.
1486:
1487: You can easily start Gforth with some files loaded like this:
1488:
1489: @example
1.102 anton 1490: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1491: @end example
1492:
1493: If an error occurs during loading these files, Gforth terminates,
1494: whereas an error during @code{INCLUDED} within Gforth usually gives you
1495: a Gforth command line. Starting the Forth system every time gives you a
1496: clean start every time, without interference from the results of earlier
1497: tries.
1498:
1499: I often put all the tests in a file, then load the code and run the
1500: tests with
1501:
1502: @example
1.102 anton 1503: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1504: @end example
1505:
1506: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1507: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1508: restart this command without ado.
1509:
1510: The advantage of this approach is that the tests can be repeated easily
1511: every time the program ist changed, making it easy to catch bugs
1512: introduced by the change.
1513:
1.66 anton 1514: Reference: @ref{Forth source files}.
1515:
1.48 anton 1516:
1517: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1518: @section Comments
1.66 anton 1519: @cindex comments tutorial
1.48 anton 1520:
1521: @example
1522: \ That's a comment; it ends at the end of the line
1523: ( Another comment; it ends here: ) .s
1524: @end example
1525:
1526: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1527: separated with white space from the following text.
1528:
1529: @example
1530: \This gives an "Undefined word" error
1531: @end example
1532:
1533: The first @code{)} ends a comment started with @code{(}, so you cannot
1534: nest @code{(}-comments; and you cannot comment out text containing a
1535: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1536: avoid @code{)} in word names.}.
1537:
1538: I use @code{\}-comments for descriptive text and for commenting out code
1539: of one or more line; I use @code{(}-comments for describing the stack
1540: effect, the stack contents, or for commenting out sub-line pieces of
1541: code.
1542:
1543: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1544: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1545: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1546: with @kbd{M-q}.
1547:
1.66 anton 1548: Reference: @ref{Comments}.
1549:
1.48 anton 1550:
1551: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1552: @section Colon Definitions
1.66 anton 1553: @cindex colon definitions, tutorial
1554: @cindex definitions, tutorial
1555: @cindex procedures, tutorial
1556: @cindex functions, tutorial
1.48 anton 1557:
1558: are similar to procedures and functions in other programming languages.
1559:
1560: @example
1561: : squared ( n -- n^2 )
1562: dup * ;
1563: 5 squared .
1564: 7 squared .
1565: @end example
1566:
1567: @code{:} starts the colon definition; its name is @code{squared}. The
1568: following comment describes its stack effect. The words @code{dup *}
1569: are not executed, but compiled into the definition. @code{;} ends the
1570: colon definition.
1571:
1572: The newly-defined word can be used like any other word, including using
1573: it in other definitions:
1574:
1575: @example
1576: : cubed ( n -- n^3 )
1577: dup squared * ;
1578: -5 cubed .
1579: : fourth-power ( n -- n^4 )
1580: squared squared ;
1581: 3 fourth-power .
1582: @end example
1583:
1.141 anton 1584: @quotation Assignment
1.48 anton 1585: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1586: @code{/mod} in terms of other Forth words, and check if they work (hint:
1587: test your tests on the originals first). Don't let the
1588: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1589: @end quotation
1.48 anton 1590:
1.66 anton 1591: Reference: @ref{Colon Definitions}.
1592:
1.48 anton 1593:
1594: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1595: @section Decompilation
1.66 anton 1596: @cindex decompilation tutorial
1597: @cindex see tutorial
1.48 anton 1598:
1599: You can decompile colon definitions with @code{see}:
1600:
1601: @example
1602: see squared
1603: see cubed
1604: @end example
1605:
1606: In Gforth @code{see} shows you a reconstruction of the source code from
1607: the executable code. Informations that were present in the source, but
1608: not in the executable code, are lost (e.g., comments).
1609:
1.65 anton 1610: You can also decompile the predefined words:
1611:
1612: @example
1613: see .
1614: see +
1615: @end example
1616:
1617:
1.48 anton 1618: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1619: @section Stack-Effect Comments
1.66 anton 1620: @cindex stack-effect comments, tutorial
1621: @cindex --, tutorial
1.48 anton 1622: By convention the comment after the name of a definition describes the
1.171 anton 1623: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1624: the stack before the execution of the definition, i.e., the parameters
1625: that are passed into the colon definition; the part behind the @samp{--}
1626: is the state of the stack after the execution of the definition, i.e.,
1627: the results of the definition. The stack comment only shows the top
1628: stack items that the definition accesses and/or changes.
1629:
1630: You should put a correct stack effect on every definition, even if it is
1631: just @code{( -- )}. You should also add some descriptive comment to
1632: more complicated words (I usually do this in the lines following
1633: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1634: you have to work through every definition before you can understand
1.48 anton 1635: any).
1636:
1.141 anton 1637: @quotation Assignment
1.48 anton 1638: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1639: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1640: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1641: are done, you can compare your stack effects to those in this manual
1.48 anton 1642: (@pxref{Word Index}).
1.141 anton 1643: @end quotation
1.48 anton 1644:
1645: Sometimes programmers put comments at various places in colon
1646: definitions that describe the contents of the stack at that place (stack
1647: comments); i.e., they are like the first part of a stack-effect
1648: comment. E.g.,
1649:
1650: @example
1651: : cubed ( n -- n^3 )
1652: dup squared ( n n^2 ) * ;
1653: @end example
1654:
1655: In this case the stack comment is pretty superfluous, because the word
1656: is simple enough. If you think it would be a good idea to add such a
1657: comment to increase readability, you should also consider factoring the
1658: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1659: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1660: however, if you decide not to refactor it, then having such a comment is
1661: better than not having it.
1662:
1663: The names of the stack items in stack-effect and stack comments in the
1664: standard, in this manual, and in many programs specify the type through
1665: a type prefix, similar to Fortran and Hungarian notation. The most
1666: frequent prefixes are:
1667:
1668: @table @code
1669: @item n
1670: signed integer
1671: @item u
1672: unsigned integer
1673: @item c
1674: character
1675: @item f
1676: Boolean flags, i.e. @code{false} or @code{true}.
1677: @item a-addr,a-
1678: Cell-aligned address
1679: @item c-addr,c-
1680: Char-aligned address (note that a Char may have two bytes in Windows NT)
1681: @item xt
1682: Execution token, same size as Cell
1683: @item w,x
1684: Cell, can contain an integer or an address. It usually takes 32, 64 or
1685: 16 bits (depending on your platform and Forth system). A cell is more
1686: commonly known as machine word, but the term @emph{word} already means
1687: something different in Forth.
1688: @item d
1689: signed double-cell integer
1690: @item ud
1691: unsigned double-cell integer
1692: @item r
1693: Float (on the FP stack)
1694: @end table
1695:
1696: You can find a more complete list in @ref{Notation}.
1697:
1.141 anton 1698: @quotation Assignment
1.48 anton 1699: Write stack-effect comments for all definitions you have written up to
1700: now.
1.141 anton 1701: @end quotation
1.48 anton 1702:
1703:
1704: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1705: @section Types
1.66 anton 1706: @cindex types tutorial
1.48 anton 1707:
1708: In Forth the names of the operations are not overloaded; so similar
1709: operations on different types need different names; e.g., @code{+} adds
1710: integers, and you have to use @code{f+} to add floating-point numbers.
1711: The following prefixes are often used for related operations on
1712: different types:
1713:
1714: @table @code
1715: @item (none)
1716: signed integer
1717: @item u
1718: unsigned integer
1719: @item c
1720: character
1721: @item d
1722: signed double-cell integer
1723: @item ud, du
1724: unsigned double-cell integer
1725: @item 2
1726: two cells (not-necessarily double-cell numbers)
1727: @item m, um
1728: mixed single-cell and double-cell operations
1729: @item f
1730: floating-point (note that in stack comments @samp{f} represents flags,
1.66 anton 1731: and @samp{r} represents FP numbers).
1.48 anton 1732: @end table
1733:
1734: If there are no differences between the signed and the unsigned variant
1735: (e.g., for @code{+}), there is only the prefix-less variant.
1736:
1737: Forth does not perform type checking, neither at compile time, nor at
1738: run time. If you use the wrong oeration, the data are interpreted
1739: incorrectly:
1740:
1741: @example
1742: -1 u.
1743: @end example
1744:
1745: If you have only experience with type-checked languages until now, and
1746: have heard how important type-checking is, don't panic! In my
1747: experience (and that of other Forthers), type errors in Forth code are
1748: usually easy to find (once you get used to it), the increased vigilance
1749: of the programmer tends to catch some harder errors in addition to most
1750: type errors, and you never have to work around the type system, so in
1751: most situations the lack of type-checking seems to be a win (projects to
1752: add type checking to Forth have not caught on).
1753:
1754:
1755: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1756: @section Factoring
1.66 anton 1757: @cindex factoring tutorial
1.48 anton 1758:
1759: If you try to write longer definitions, you will soon find it hard to
1760: keep track of the stack contents. Therefore, good Forth programmers
1761: tend to write only short definitions (e.g., three lines). The art of
1762: finding meaningful short definitions is known as factoring (as in
1763: factoring polynomials).
1764:
1765: Well-factored programs offer additional advantages: smaller, more
1766: general words, are easier to test and debug and can be reused more and
1767: better than larger, specialized words.
1768:
1769: So, if you run into difficulties with stack management, when writing
1770: code, try to define meaningful factors for the word, and define the word
1771: in terms of those. Even if a factor contains only two words, it is
1772: often helpful.
1773:
1.65 anton 1774: Good factoring is not easy, and it takes some practice to get the knack
1775: for it; but even experienced Forth programmers often don't find the
1776: right solution right away, but only when rewriting the program. So, if
1777: you don't come up with a good solution immediately, keep trying, don't
1778: despair.
1.48 anton 1779:
1780: @c example !!
1781:
1782:
1783: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1784: @section Designing the stack effect
1.66 anton 1785: @cindex Stack effect design, tutorial
1786: @cindex design of stack effects, tutorial
1.48 anton 1787:
1788: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1789: function; and since there is only one result, you don't have to deal with
1.48 anton 1790: the order of results, either.
1791:
1.117 anton 1792: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1793: parameter and result order of a definition is important and should be
1794: designed well. The general guideline is to design the stack effect such
1795: that the word is simple to use in most cases, even if that complicates
1796: the implementation of the word. Some concrete rules are:
1797:
1798: @itemize @bullet
1799:
1800: @item
1801: Words consume all of their parameters (e.g., @code{.}).
1802:
1803: @item
1804: If there is a convention on the order of parameters (e.g., from
1805: mathematics or another programming language), stick with it (e.g.,
1806: @code{-}).
1807:
1808: @item
1809: If one parameter usually requires only a short computation (e.g., it is
1810: a constant), pass it on the top of the stack. Conversely, parameters
1811: that usually require a long sequence of code to compute should be passed
1812: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1813: read, because the reader does not need to keep track of the bottom item
1.48 anton 1814: through a long sequence of code (or, alternatively, through stack
1.49 anton 1815: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1816: address on top of the stack because it is usually simpler to compute
1817: than the stored value (often the address is just a variable).
1818:
1819: @item
1820: Similarly, results that are usually consumed quickly should be returned
1821: on the top of stack, whereas a result that is often used in long
1822: computations should be passed as bottom result. E.g., the file words
1823: like @code{open-file} return the error code on the top of stack, because
1824: it is usually consumed quickly by @code{throw}; moreover, the error code
1825: has to be checked before doing anything with the other results.
1826:
1827: @end itemize
1828:
1829: These rules are just general guidelines, don't lose sight of the overall
1830: goal to make the words easy to use. E.g., if the convention rule
1831: conflicts with the computation-length rule, you might decide in favour
1832: of the convention if the word will be used rarely, and in favour of the
1833: computation-length rule if the word will be used frequently (because
1834: with frequent use the cost of breaking the computation-length rule would
1835: be quite high, and frequent use makes it easier to remember an
1836: unconventional order).
1837:
1838: @c example !! structure package
1839:
1.65 anton 1840:
1.48 anton 1841: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1842: @section Local Variables
1.66 anton 1843: @cindex local variables, tutorial
1.48 anton 1844:
1845: You can define local variables (@emph{locals}) in a colon definition:
1846:
1847: @example
1848: : swap @{ a b -- b a @}
1849: b a ;
1850: 1 2 swap .s 2drop
1851: @end example
1852:
1853: (If your Forth system does not support this syntax, include
1.187 anton 1854: @file{compat/anslocal.fs} first).
1.48 anton 1855:
1856: In this example @code{@{ a b -- b a @}} is the locals definition; it
1857: takes two cells from the stack, puts the top of stack in @code{b} and
1858: the next stack element in @code{a}. @code{--} starts a comment ending
1859: with @code{@}}. After the locals definition, using the name of the
1860: local will push its value on the stack. You can leave the comment
1861: part (@code{-- b a}) away:
1862:
1863: @example
1864: : swap ( x1 x2 -- x2 x1 )
1865: @{ a b @} b a ;
1866: @end example
1867:
1868: In Gforth you can have several locals definitions, anywhere in a colon
1869: definition; in contrast, in a standard program you can have only one
1870: locals definition per colon definition, and that locals definition must
1.163 anton 1871: be outside any control structure.
1.48 anton 1872:
1873: With locals you can write slightly longer definitions without running
1874: into stack trouble. However, I recommend trying to write colon
1875: definitions without locals for exercise purposes to help you gain the
1876: essential factoring skills.
1877:
1.141 anton 1878: @quotation Assignment
1.48 anton 1879: Rewrite your definitions until now with locals
1.141 anton 1880: @end quotation
1.48 anton 1881:
1.66 anton 1882: Reference: @ref{Locals}.
1883:
1.48 anton 1884:
1885: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1886: @section Conditional execution
1.66 anton 1887: @cindex conditionals, tutorial
1888: @cindex if, tutorial
1.48 anton 1889:
1890: In Forth you can use control structures only inside colon definitions.
1891: An @code{if}-structure looks like this:
1892:
1893: @example
1894: : abs ( n1 -- +n2 )
1895: dup 0 < if
1896: negate
1897: endif ;
1898: 5 abs .
1899: -5 abs .
1900: @end example
1901:
1902: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1903: the following code is performed, otherwise execution continues after the
1.51 pazsan 1904: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1905: elements and produces a flag:
1.48 anton 1906:
1907: @example
1908: 1 2 < .
1909: 2 1 < .
1910: 1 1 < .
1911: @end example
1912:
1913: Actually the standard name for @code{endif} is @code{then}. This
1914: tutorial presents the examples using @code{endif}, because this is often
1915: less confusing for people familiar with other programming languages
1916: where @code{then} has a different meaning. If your system does not have
1917: @code{endif}, define it with
1918:
1919: @example
1920: : endif postpone then ; immediate
1921: @end example
1922:
1923: You can optionally use an @code{else}-part:
1924:
1925: @example
1926: : min ( n1 n2 -- n )
1927: 2dup < if
1928: drop
1929: else
1930: nip
1931: endif ;
1932: 2 3 min .
1933: 3 2 min .
1934: @end example
1935:
1.141 anton 1936: @quotation Assignment
1.48 anton 1937: Write @code{min} without @code{else}-part (hint: what's the definition
1938: of @code{nip}?).
1.141 anton 1939: @end quotation
1.48 anton 1940:
1.66 anton 1941: Reference: @ref{Selection}.
1942:
1.48 anton 1943:
1944: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1945: @section Flags and Comparisons
1.66 anton 1946: @cindex flags tutorial
1947: @cindex comparison tutorial
1.48 anton 1948:
1949: In a false-flag all bits are clear (0 when interpreted as integer). In
1950: a canonical true-flag all bits are set (-1 as a twos-complement signed
1951: integer); in many contexts (e.g., @code{if}) any non-zero value is
1952: treated as true flag.
1953:
1954: @example
1955: false .
1956: true .
1957: true hex u. decimal
1958: @end example
1959:
1960: Comparison words produce canonical flags:
1961:
1962: @example
1963: 1 1 = .
1964: 1 0= .
1965: 0 1 < .
1966: 0 0 < .
1967: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1968: -1 1 < .
1969: @end example
1970:
1.66 anton 1971: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1972: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1973: these combinations are standard (for details see the standard,
1974: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 1975:
1.171 anton 1976: You can use @code{and or xor invert} as operations on canonical flags.
1977: Actually they are bitwise operations:
1.48 anton 1978:
1979: @example
1980: 1 2 and .
1981: 1 2 or .
1982: 1 3 xor .
1983: 1 invert .
1984: @end example
1985:
1986: You can convert a zero/non-zero flag into a canonical flag with
1987: @code{0<>} (and complement it on the way with @code{0=}).
1988:
1989: @example
1990: 1 0= .
1991: 1 0<> .
1992: @end example
1993:
1.65 anton 1994: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 1995: operation of the Boolean operations to avoid @code{if}s:
1996:
1997: @example
1998: : foo ( n1 -- n2 )
1999: 0= if
2000: 14
2001: else
2002: 0
2003: endif ;
2004: 0 foo .
2005: 1 foo .
2006:
2007: : foo ( n1 -- n2 )
2008: 0= 14 and ;
2009: 0 foo .
2010: 1 foo .
2011: @end example
2012:
1.141 anton 2013: @quotation Assignment
1.48 anton 2014: Write @code{min} without @code{if}.
1.141 anton 2015: @end quotation
1.48 anton 2016:
1.66 anton 2017: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2018: @ref{Bitwise operations}.
2019:
1.48 anton 2020:
2021: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2022: @section General Loops
1.66 anton 2023: @cindex loops, indefinite, tutorial
1.48 anton 2024:
2025: The endless loop is the most simple one:
2026:
2027: @example
2028: : endless ( -- )
2029: 0 begin
2030: dup . 1+
2031: again ;
2032: endless
2033: @end example
2034:
2035: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2036: does nothing at run-time, @code{again} jumps back to @code{begin}.
2037:
2038: A loop with one exit at any place looks like this:
2039:
2040: @example
2041: : log2 ( +n1 -- n2 )
2042: \ logarithmus dualis of n1>0, rounded down to the next integer
2043: assert( dup 0> )
2044: 2/ 0 begin
2045: over 0> while
2046: 1+ swap 2/ swap
2047: repeat
2048: nip ;
2049: 7 log2 .
2050: 8 log2 .
2051: @end example
2052:
2053: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2054: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2055: continues behind the @code{while}. @code{Repeat} jumps back to
2056: @code{begin}, just like @code{again}.
2057:
2058: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2059: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2060: one bit (arithmetic shift right):
2061:
2062: @example
2063: -5 2 / .
2064: -5 2/ .
2065: @end example
2066:
2067: @code{assert(} is no standard word, but you can get it on systems other
2068: then Gforth by including @file{compat/assert.fs}. You can see what it
2069: does by trying
2070:
2071: @example
2072: 0 log2 .
2073: @end example
2074:
2075: Here's a loop with an exit at the end:
2076:
2077: @example
2078: : log2 ( +n1 -- n2 )
2079: \ logarithmus dualis of n1>0, rounded down to the next integer
2080: assert( dup 0 > )
2081: -1 begin
2082: 1+ swap 2/ swap
2083: over 0 <=
2084: until
2085: nip ;
2086: @end example
2087:
2088: @code{Until} consumes a flag; if it is non-zero, execution continues at
2089: the @code{begin}, otherwise after the @code{until}.
2090:
1.141 anton 2091: @quotation Assignment
1.48 anton 2092: Write a definition for computing the greatest common divisor.
1.141 anton 2093: @end quotation
1.48 anton 2094:
1.66 anton 2095: Reference: @ref{Simple Loops}.
2096:
1.48 anton 2097:
2098: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2099: @section Counted loops
1.66 anton 2100: @cindex loops, counted, tutorial
1.48 anton 2101:
2102: @example
2103: : ^ ( n1 u -- n )
1.171 anton 2104: \ n = the uth power of n1
1.48 anton 2105: 1 swap 0 u+do
2106: over *
2107: loop
2108: nip ;
2109: 3 2 ^ .
2110: 4 3 ^ .
2111: @end example
2112:
2113: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2114: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2115: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2116: times (or not at all, if @code{u3-u4<0}).
2117:
2118: You can see the stack effect design rules at work in the stack effect of
2119: the loop start words: Since the start value of the loop is more
2120: frequently constant than the end value, the start value is passed on
2121: the top-of-stack.
2122:
2123: You can access the counter of a counted loop with @code{i}:
2124:
2125: @example
2126: : fac ( u -- u! )
2127: 1 swap 1+ 1 u+do
2128: i *
2129: loop ;
2130: 5 fac .
2131: 7 fac .
2132: @end example
2133:
2134: There is also @code{+do}, which expects signed numbers (important for
2135: deciding whether to enter the loop).
2136:
1.141 anton 2137: @quotation Assignment
1.48 anton 2138: Write a definition for computing the nth Fibonacci number.
1.141 anton 2139: @end quotation
1.48 anton 2140:
1.65 anton 2141: You can also use increments other than 1:
2142:
2143: @example
2144: : up2 ( n1 n2 -- )
2145: +do
2146: i .
2147: 2 +loop ;
2148: 10 0 up2
2149:
2150: : down2 ( n1 n2 -- )
2151: -do
2152: i .
2153: 2 -loop ;
2154: 0 10 down2
2155: @end example
1.48 anton 2156:
1.66 anton 2157: Reference: @ref{Counted Loops}.
2158:
1.48 anton 2159:
2160: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2161: @section Recursion
1.66 anton 2162: @cindex recursion tutorial
1.48 anton 2163:
2164: Usually the name of a definition is not visible in the definition; but
2165: earlier definitions are usually visible:
2166:
2167: @example
1.166 anton 2168: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2169: : / ( n1 n2 -- n )
2170: dup 0= if
2171: -10 throw \ report division by zero
2172: endif
2173: / \ old version
2174: ;
2175: 1 0 /
2176: @end example
2177:
2178: For recursive definitions you can use @code{recursive} (non-standard) or
2179: @code{recurse}:
2180:
2181: @example
2182: : fac1 ( n -- n! ) recursive
2183: dup 0> if
2184: dup 1- fac1 *
2185: else
2186: drop 1
2187: endif ;
2188: 7 fac1 .
2189:
2190: : fac2 ( n -- n! )
2191: dup 0> if
2192: dup 1- recurse *
2193: else
2194: drop 1
2195: endif ;
2196: 8 fac2 .
2197: @end example
2198:
1.141 anton 2199: @quotation Assignment
1.48 anton 2200: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2201: @end quotation
1.48 anton 2202:
1.66 anton 2203: Reference (including indirect recursion): @xref{Calls and returns}.
2204:
1.48 anton 2205:
2206: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2207: @section Leaving definitions or loops
1.66 anton 2208: @cindex leaving definitions, tutorial
2209: @cindex leaving loops, tutorial
1.48 anton 2210:
2211: @code{EXIT} exits the current definition right away. For every counted
2212: loop that is left in this way, an @code{UNLOOP} has to be performed
2213: before the @code{EXIT}:
2214:
2215: @c !! real examples
2216: @example
2217: : ...
2218: ... u+do
2219: ... if
2220: ... unloop exit
2221: endif
2222: ...
2223: loop
2224: ... ;
2225: @end example
2226:
2227: @code{LEAVE} leaves the innermost counted loop right away:
2228:
2229: @example
2230: : ...
2231: ... u+do
2232: ... if
2233: ... leave
2234: endif
2235: ...
2236: loop
2237: ... ;
2238: @end example
2239:
1.65 anton 2240: @c !! example
1.48 anton 2241:
1.66 anton 2242: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2243:
2244:
1.48 anton 2245: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2246: @section Return Stack
1.66 anton 2247: @cindex return stack tutorial
1.48 anton 2248:
2249: In addition to the data stack Forth also has a second stack, the return
2250: stack; most Forth systems store the return addresses of procedure calls
2251: there (thus its name). Programmers can also use this stack:
2252:
2253: @example
2254: : foo ( n1 n2 -- )
2255: .s
2256: >r .s
1.50 anton 2257: r@@ .
1.48 anton 2258: >r .s
1.50 anton 2259: r@@ .
1.48 anton 2260: r> .
1.50 anton 2261: r@@ .
1.48 anton 2262: r> . ;
2263: 1 2 foo
2264: @end example
2265:
2266: @code{>r} takes an element from the data stack and pushes it onto the
2267: return stack; conversely, @code{r>} moves an elementm from the return to
2268: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2269: on the data stack.
1.48 anton 2270:
2271: Forth programmers usually use the return stack for storing data
2272: temporarily, if using the data stack alone would be too complex, and
2273: factoring and locals are not an option:
2274:
2275: @example
2276: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2277: rot >r rot r> ;
2278: @end example
2279:
2280: The return address of the definition and the loop control parameters of
2281: counted loops usually reside on the return stack, so you have to take
2282: all items, that you have pushed on the return stack in a colon
2283: definition or counted loop, from the return stack before the definition
2284: or loop ends. You cannot access items that you pushed on the return
2285: stack outside some definition or loop within the definition of loop.
2286:
2287: If you miscount the return stack items, this usually ends in a crash:
2288:
2289: @example
2290: : crash ( n -- )
2291: >r ;
2292: 5 crash
2293: @end example
2294:
2295: You cannot mix using locals and using the return stack (according to the
2296: standard; Gforth has no problem). However, they solve the same
2297: problems, so this shouldn't be an issue.
2298:
1.141 anton 2299: @quotation Assignment
1.48 anton 2300: Can you rewrite any of the definitions you wrote until now in a better
2301: way using the return stack?
1.141 anton 2302: @end quotation
1.48 anton 2303:
1.66 anton 2304: Reference: @ref{Return stack}.
2305:
1.48 anton 2306:
2307: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2308: @section Memory
1.66 anton 2309: @cindex memory access/allocation tutorial
1.48 anton 2310:
2311: You can create a global variable @code{v} with
2312:
2313: @example
2314: variable v ( -- addr )
2315: @end example
2316:
2317: @code{v} pushes the address of a cell in memory on the stack. This cell
2318: was reserved by @code{variable}. You can use @code{!} (store) to store
2319: values into this cell and @code{@@} (fetch) to load the value from the
2320: stack into memory:
2321:
2322: @example
2323: v .
2324: 5 v ! .s
1.50 anton 2325: v @@ .
1.48 anton 2326: @end example
2327:
1.65 anton 2328: You can see a raw dump of memory with @code{dump}:
2329:
2330: @example
2331: v 1 cells .s dump
2332: @end example
2333:
2334: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2335: generally, address units (aus)) that @code{n1 cells} occupy. You can
2336: also reserve more memory:
1.48 anton 2337:
2338: @example
2339: create v2 20 cells allot
1.65 anton 2340: v2 20 cells dump
1.48 anton 2341: @end example
2342:
1.65 anton 2343: creates a word @code{v2} and reserves 20 uninitialized cells; the
2344: address pushed by @code{v2} points to the start of these 20 cells. You
2345: can use address arithmetic to access these cells:
1.48 anton 2346:
2347: @example
2348: 3 v2 5 cells + !
1.65 anton 2349: v2 20 cells dump
1.48 anton 2350: @end example
2351:
2352: You can reserve and initialize memory with @code{,}:
2353:
2354: @example
2355: create v3
2356: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2357: v3 @@ .
2358: v3 cell+ @@ .
2359: v3 2 cells + @@ .
1.65 anton 2360: v3 5 cells dump
1.48 anton 2361: @end example
2362:
1.141 anton 2363: @quotation Assignment
1.48 anton 2364: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2365: @code{u} cells, with the first of these cells at @code{addr}, the next
2366: one at @code{addr cell+} etc.
1.141 anton 2367: @end quotation
1.48 anton 2368:
2369: You can also reserve memory without creating a new word:
2370:
2371: @example
1.60 anton 2372: here 10 cells allot .
2373: here .
1.48 anton 2374: @end example
2375:
2376: @code{Here} pushes the start address of the memory area. You should
2377: store it somewhere, or you will have a hard time finding the memory area
2378: again.
2379:
2380: @code{Allot} manages dictionary memory. The dictionary memory contains
2381: the system's data structures for words etc. on Gforth and most other
2382: Forth systems. It is managed like a stack: You can free the memory that
2383: you have just @code{allot}ed with
2384:
2385: @example
2386: -10 cells allot
1.60 anton 2387: here .
1.48 anton 2388: @end example
2389:
2390: Note that you cannot do this if you have created a new word in the
2391: meantime (because then your @code{allot}ed memory is no longer on the
2392: top of the dictionary ``stack'').
2393:
2394: Alternatively, you can use @code{allocate} and @code{free} which allow
2395: freeing memory in any order:
2396:
2397: @example
2398: 10 cells allocate throw .s
2399: 20 cells allocate throw .s
2400: swap
2401: free throw
2402: free throw
2403: @end example
2404:
2405: The @code{throw}s deal with errors (e.g., out of memory).
2406:
1.65 anton 2407: And there is also a
2408: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2409: garbage collector}, which eliminates the need to @code{free} memory
2410: explicitly.
1.48 anton 2411:
1.66 anton 2412: Reference: @ref{Memory}.
2413:
1.48 anton 2414:
2415: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2416: @section Characters and Strings
1.66 anton 2417: @cindex strings tutorial
2418: @cindex characters tutorial
1.48 anton 2419:
2420: On the stack characters take up a cell, like numbers. In memory they
2421: have their own size (one 8-bit byte on most systems), and therefore
2422: require their own words for memory access:
2423:
2424: @example
2425: create v4
2426: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2427: v4 4 chars + c@@ .
1.65 anton 2428: v4 5 chars dump
1.48 anton 2429: @end example
2430:
2431: The preferred representation of strings on the stack is @code{addr
2432: u-count}, where @code{addr} is the address of the first character and
2433: @code{u-count} is the number of characters in the string.
2434:
2435: @example
2436: v4 5 type
2437: @end example
2438:
2439: You get a string constant with
2440:
2441: @example
2442: s" hello, world" .s
2443: type
2444: @end example
2445:
2446: Make sure you have a space between @code{s"} and the string; @code{s"}
2447: is a normal Forth word and must be delimited with white space (try what
2448: happens when you remove the space).
2449:
2450: However, this interpretive use of @code{s"} is quite restricted: the
2451: string exists only until the next call of @code{s"} (some Forth systems
2452: keep more than one of these strings, but usually they still have a
1.62 crook 2453: limited lifetime).
1.48 anton 2454:
2455: @example
2456: s" hello," s" world" .s
2457: type
2458: type
2459: @end example
2460:
1.62 crook 2461: You can also use @code{s"} in a definition, and the resulting
2462: strings then live forever (well, for as long as the definition):
1.48 anton 2463:
2464: @example
2465: : foo s" hello," s" world" ;
2466: foo .s
2467: type
2468: type
2469: @end example
2470:
1.141 anton 2471: @quotation Assignment
1.48 anton 2472: @code{Emit ( c -- )} types @code{c} as character (not a number).
2473: Implement @code{type ( addr u -- )}.
1.141 anton 2474: @end quotation
1.48 anton 2475:
1.66 anton 2476: Reference: @ref{Memory Blocks}.
2477:
2478:
1.190 anton 2479: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2480: @section Alignment
1.66 anton 2481: @cindex alignment tutorial
2482: @cindex memory alignment tutorial
1.48 anton 2483:
2484: On many processors cells have to be aligned in memory, if you want to
2485: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2486: not require alignment, access to aligned cells is faster).
1.48 anton 2487:
2488: @code{Create} aligns @code{here} (i.e., the place where the next
2489: allocation will occur, and that the @code{create}d word points to).
2490: Likewise, the memory produced by @code{allocate} starts at an aligned
2491: address. Adding a number of @code{cells} to an aligned address produces
2492: another aligned address.
2493:
2494: However, address arithmetic involving @code{char+} and @code{chars} can
2495: create an address that is not cell-aligned. @code{Aligned ( addr --
2496: a-addr )} produces the next aligned address:
2497:
2498: @example
1.50 anton 2499: v3 char+ aligned .s @@ .
2500: v3 char+ .s @@ .
1.48 anton 2501: @end example
2502:
2503: Similarly, @code{align} advances @code{here} to the next aligned
2504: address:
2505:
2506: @example
2507: create v5 97 c,
2508: here .
2509: align here .
2510: 1000 ,
2511: @end example
2512:
2513: Note that you should use aligned addresses even if your processor does
2514: not require them, if you want your program to be portable.
2515:
1.66 anton 2516: Reference: @ref{Address arithmetic}.
2517:
1.190 anton 2518: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2519: @section Floating Point
2520: @cindex floating point tutorial
2521: @cindex FP tutorial
2522:
2523: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2524: might expect, but there are a few things worth noting:
2525:
2526: The first point is not specific to Forth, but so important and yet not
2527: universally known that I mention it here: FP numbers are not reals.
2528: Many properties (e.g., arithmetic laws) that reals have and that one
2529: expects of all kinds of numbers do not hold for FP numbers. If you
2530: want to use FP computations, you should learn about their problems and
2531: how to avoid them; a good starting point is @cite{David Goldberg,
2532: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2533: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2534: Computing Surveys 23(1):5@minus{}48, March 1991}.
2535:
2536: In Forth source code literal FP numbers need an exponent, e.g.,
2537: @code{1e0}; this can also be written shorter as @code{1e},
2538: @code{+1.0e+0}, and many variations in between. The reason for this
2539: is that, for historical reasons, Forth interprets a decimal point
2540: alone (e.g., @code{1.}) as indicating a double-cell integer. Another
2541: requirement for literal FP numbers is that the current base is
2542: decimal; with a hex base @code{1e} is interpreted as an integer.
2543:
2544: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2545: ANS Forth system may implement the FP stack on the data stack, but
2546: virtually all systems implement a separate FP stack; and programming
2547: in a way that accommodates all models is so cumbersome that nobody
2548: does it.} One advantage of this model is that cells are not in the
2549: way when accessing FP values, and vice versa. Forth has a set of
2550: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2551: frot} and (non-standard) @code{fnip ftuck fpick}.
2552:
2553: FP arithmetic words are prefixed with @code{F}. There is the usual
2554: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2555: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2556: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2557: computation results are usually inaccurate, so exact comparison is
2558: usually a mistake, and one should use approximate comparison.
2559: Unfortunately, @code{f~}, the standard word for that purpose, is not
2560: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2561: well.
2562:
2563: And of course there are words for accessing FP numbers in memory
2564: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2565: faligned}). There are also variants of these words with an @code{sf}
2566: and @code{df} prefix for accessing IEEE format single-precision and
2567: double-precision numbers in memory; their main purpose is for
2568: accessing external FP data (e.g., that has been read from or will be
2569: written to a file).
2570:
2571: Here is an example of a dot-product word and its use:
2572:
2573: @example
2574: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2575: >r swap 2swap swap 0e r> 0 ?DO
2576: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2577: LOOP
2578: 2drop 2drop ;
1.48 anton 2579:
1.190 anton 2580: create v 1.23e f, 4.56e f, 7.89e f,
2581:
2582: v 1 floats v 1 floats 3 v* f.
2583: @end example
2584:
2585: @quotation Assignment
2586: Write a program to solve a quadratic equation. Then read @cite{Henry
2587: G. Baker,
2588: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2589: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2590: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2591: program. Finally, find a test case where the original and the
2592: improved version produce different results.
2593: @end quotation
2594:
2595: Reference: @ref{Floating Point}; @ref{Floating point stack};
2596: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2597: arithmetic}.
2598:
2599: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2600: @section Files
2601: @cindex files tutorial
2602:
2603: This section gives a short introduction into how to use files inside
2604: Forth. It's broken up into five easy steps:
2605:
2606: @enumerate 1
2607: @item Opened an ASCII text file for input
2608: @item Opened a file for output
2609: @item Read input file until string matched (or some other condition matched)
2610: @item Wrote some lines from input ( modified or not) to output
2611: @item Closed the files.
2612: @end enumerate
2613:
1.153 anton 2614: Reference: @ref{General files}.
2615:
1.84 pazsan 2616: @subsection Open file for input
2617:
2618: @example
2619: s" foo.in" r/o open-file throw Value fd-in
2620: @end example
2621:
2622: @subsection Create file for output
2623:
2624: @example
2625: s" foo.out" w/o create-file throw Value fd-out
2626: @end example
2627:
2628: The available file modes are r/o for read-only access, r/w for
2629: read-write access, and w/o for write-only access. You could open both
2630: files with r/w, too, if you like. All file words return error codes; for
2631: most applications, it's best to pass there error codes with @code{throw}
2632: to the outer error handler.
2633:
2634: If you want words for opening and assigning, define them as follows:
2635:
2636: @example
2637: 0 Value fd-in
2638: 0 Value fd-out
2639: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2640: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2641: @end example
2642:
2643: Usage example:
2644:
2645: @example
2646: s" foo.in" open-input
2647: s" foo.out" open-output
2648: @end example
2649:
2650: @subsection Scan file for a particular line
2651:
2652: @example
2653: 256 Constant max-line
2654: Create line-buffer max-line 2 + allot
2655:
2656: : scan-file ( addr u -- )
2657: begin
2658: line-buffer max-line fd-in read-line throw
2659: while
2660: >r 2dup line-buffer r> compare 0=
2661: until
2662: else
2663: drop
2664: then
2665: 2drop ;
2666: @end example
2667:
2668: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2669: the buffer at addr, and returns the number of bytes read, a flag that is
2670: false when the end of file is reached, and an error code.
1.84 pazsan 2671:
2672: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2673: returns zero if both strings are equal. It returns a positive number if
2674: the first string is lexically greater, a negative if the second string
2675: is lexically greater.
2676:
2677: We haven't seen this loop here; it has two exits. Since the @code{while}
2678: exits with the number of bytes read on the stack, we have to clean up
2679: that separately; that's after the @code{else}.
2680:
2681: Usage example:
2682:
2683: @example
2684: s" The text I search is here" scan-file
2685: @end example
2686:
2687: @subsection Copy input to output
2688:
2689: @example
2690: : copy-file ( -- )
2691: begin
2692: line-buffer max-line fd-in read-line throw
2693: while
1.194 anton 2694: line-buffer swap fd-out write-line throw
1.84 pazsan 2695: repeat ;
2696: @end example
1.194 anton 2697: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2698:
2699: @subsection Close files
2700:
2701: @example
2702: fd-in close-file throw
2703: fd-out close-file throw
2704: @end example
2705:
2706: Likewise, you can put that into definitions, too:
2707:
2708: @example
2709: : close-input ( -- ) fd-in close-file throw ;
2710: : close-output ( -- ) fd-out close-file throw ;
2711: @end example
2712:
1.141 anton 2713: @quotation Assignment
1.84 pazsan 2714: How could you modify @code{copy-file} so that it copies until a second line is
2715: matched? Can you write a program that extracts a section of a text file,
2716: given the line that starts and the line that terminates that section?
1.141 anton 2717: @end quotation
1.84 pazsan 2718:
2719: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2720: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2721: @cindex semantics tutorial
2722: @cindex interpretation semantics tutorial
2723: @cindex compilation semantics tutorial
2724: @cindex immediate, tutorial
1.48 anton 2725:
2726: When a word is compiled, it behaves differently from being interpreted.
2727: E.g., consider @code{+}:
2728:
2729: @example
2730: 1 2 + .
2731: : foo + ;
2732: @end example
2733:
2734: These two behaviours are known as compilation and interpretation
2735: semantics. For normal words (e.g., @code{+}), the compilation semantics
2736: is to append the interpretation semantics to the currently defined word
2737: (@code{foo} in the example above). I.e., when @code{foo} is executed
2738: later, the interpretation semantics of @code{+} (i.e., adding two
2739: numbers) will be performed.
2740:
2741: However, there are words with non-default compilation semantics, e.g.,
2742: the control-flow words like @code{if}. You can use @code{immediate} to
2743: change the compilation semantics of the last defined word to be equal to
2744: the interpretation semantics:
2745:
2746: @example
2747: : [FOO] ( -- )
2748: 5 . ; immediate
2749:
2750: [FOO]
2751: : bar ( -- )
2752: [FOO] ;
2753: bar
2754: see bar
2755: @end example
2756:
2757: Two conventions to mark words with non-default compilation semnatics are
2758: names with brackets (more frequently used) and to write them all in
2759: upper case (less frequently used).
2760:
2761: In Gforth (and many other systems) you can also remove the
2762: interpretation semantics with @code{compile-only} (the compilation
2763: semantics is derived from the original interpretation semantics):
2764:
2765: @example
2766: : flip ( -- )
2767: 6 . ; compile-only \ but not immediate
2768: flip
2769:
2770: : flop ( -- )
2771: flip ;
2772: flop
2773: @end example
2774:
2775: In this example the interpretation semantics of @code{flop} is equal to
2776: the original interpretation semantics of @code{flip}.
2777:
2778: The text interpreter has two states: in interpret state, it performs the
2779: interpretation semantics of words it encounters; in compile state, it
2780: performs the compilation semantics of these words.
2781:
2782: Among other things, @code{:} switches into compile state, and @code{;}
2783: switches back to interpret state. They contain the factors @code{]}
2784: (switch to compile state) and @code{[} (switch to interpret state), that
2785: do nothing but switch the state.
2786:
2787: @example
2788: : xxx ( -- )
2789: [ 5 . ]
2790: ;
2791:
2792: xxx
2793: see xxx
2794: @end example
2795:
2796: These brackets are also the source of the naming convention mentioned
2797: above.
2798:
1.66 anton 2799: Reference: @ref{Interpretation and Compilation Semantics}.
2800:
1.48 anton 2801:
2802: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2803: @section Execution Tokens
1.66 anton 2804: @cindex execution tokens tutorial
2805: @cindex XT tutorial
1.48 anton 2806:
2807: @code{' word} gives you the execution token (XT) of a word. The XT is a
2808: cell representing the interpretation semantics of a word. You can
2809: execute this semantics with @code{execute}:
2810:
2811: @example
2812: ' + .s
2813: 1 2 rot execute .
2814: @end example
2815:
2816: The XT is similar to a function pointer in C. However, parameter
2817: passing through the stack makes it a little more flexible:
2818:
2819: @example
2820: : map-array ( ... addr u xt -- ... )
1.50 anton 2821: \ executes xt ( ... x -- ... ) for every element of the array starting
2822: \ at addr and containing u elements
1.48 anton 2823: @{ xt @}
2824: cells over + swap ?do
1.50 anton 2825: i @@ xt execute
1.48 anton 2826: 1 cells +loop ;
2827:
2828: create a 3 , 4 , 2 , -1 , 4 ,
2829: a 5 ' . map-array .s
2830: 0 a 5 ' + map-array .
2831: s" max-n" environment? drop .s
2832: a 5 ' min map-array .
2833: @end example
2834:
2835: You can use map-array with the XTs of words that consume one element
2836: more than they produce. In theory you can also use it with other XTs,
2837: but the stack effect then depends on the size of the array, which is
2838: hard to understand.
2839:
1.51 pazsan 2840: Since XTs are cell-sized, you can store them in memory and manipulate
2841: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2842: word with @code{compile,}:
2843:
2844: @example
2845: : foo1 ( n1 n2 -- n )
2846: [ ' + compile, ] ;
2847: see foo
2848: @end example
2849:
2850: This is non-standard, because @code{compile,} has no compilation
2851: semantics in the standard, but it works in good Forth systems. For the
2852: broken ones, use
2853:
2854: @example
2855: : [compile,] compile, ; immediate
2856:
2857: : foo1 ( n1 n2 -- n )
2858: [ ' + ] [compile,] ;
2859: see foo
2860: @end example
2861:
2862: @code{'} is a word with default compilation semantics; it parses the
2863: next word when its interpretation semantics are executed, not during
2864: compilation:
2865:
2866: @example
2867: : foo ( -- xt )
2868: ' ;
2869: see foo
2870: : bar ( ... "word" -- ... )
2871: ' execute ;
2872: see bar
1.60 anton 2873: 1 2 bar + .
1.48 anton 2874: @end example
2875:
2876: You often want to parse a word during compilation and compile its XT so
2877: it will be pushed on the stack at run-time. @code{[']} does this:
2878:
2879: @example
2880: : xt-+ ( -- xt )
2881: ['] + ;
2882: see xt-+
2883: 1 2 xt-+ execute .
2884: @end example
2885:
2886: Many programmers tend to see @code{'} and the word it parses as one
2887: unit, and expect it to behave like @code{[']} when compiled, and are
2888: confused by the actual behaviour. If you are, just remember that the
2889: Forth system just takes @code{'} as one unit and has no idea that it is
2890: a parsing word (attempts to convenience programmers in this issue have
2891: usually resulted in even worse pitfalls, see
1.66 anton 2892: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2893: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2894:
2895: Note that the state of the interpreter does not come into play when
1.51 pazsan 2896: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2897: compile state, it still gives you the interpretation semantics. And
2898: whatever that state is, @code{execute} performs the semantics
1.66 anton 2899: represented by the XT (i.e., for XTs produced with @code{'} the
2900: interpretation semantics).
2901:
2902: Reference: @ref{Tokens for Words}.
1.48 anton 2903:
2904:
2905: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2906: @section Exceptions
1.66 anton 2907: @cindex exceptions tutorial
1.48 anton 2908:
2909: @code{throw ( n -- )} causes an exception unless n is zero.
2910:
2911: @example
2912: 100 throw .s
2913: 0 throw .s
2914: @end example
2915:
2916: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2917: it catches exceptions and pushes the number of the exception on the
2918: stack (or 0, if the xt executed without exception). If there was an
2919: exception, the stacks have the same depth as when entering @code{catch}:
2920:
2921: @example
2922: .s
2923: 3 0 ' / catch .s
2924: 3 2 ' / catch .s
2925: @end example
2926:
1.141 anton 2927: @quotation Assignment
1.48 anton 2928: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2929: @end quotation
1.48 anton 2930:
2931: @code{Throw} always jumps to the dynamically next enclosing
2932: @code{catch}, even if it has to leave several call levels to achieve
2933: this:
2934:
2935: @example
2936: : foo 100 throw ;
2937: : foo1 foo ." after foo" ;
1.51 pazsan 2938: : bar ['] foo1 catch ;
1.60 anton 2939: bar .
1.48 anton 2940: @end example
2941:
2942: It is often important to restore a value upon leaving a definition, even
2943: if the definition is left through an exception. You can ensure this
2944: like this:
2945:
2946: @example
2947: : ...
2948: save-x
1.51 pazsan 2949: ['] word-changing-x catch ( ... n )
1.48 anton 2950: restore-x
2951: ( ... n ) throw ;
2952: @end example
2953:
1.172 anton 2954: However, this is still not safe against, e.g., the user pressing
2955: @kbd{Ctrl-C} when execution is between the @code{catch} and
2956: @code{restore-x}.
2957:
2958: Gforth provides an alternative exception handling syntax that is safe
2959: against such cases: @code{try ... restore ... endtry}. If the code
2960: between @code{try} and @code{endtry} has an exception, the stack
2961: depths are restored, the exception number is pushed on the stack, and
2962: the execution continues right after @code{restore}.
1.48 anton 2963:
1.172 anton 2964: The safer equivalent to the restoration code above is
1.48 anton 2965:
2966: @example
2967: : ...
2968: save-x
2969: try
1.92 anton 2970: word-changing-x 0
1.172 anton 2971: restore
2972: restore-x
2973: endtry
1.48 anton 2974: throw ;
2975: @end example
2976:
1.66 anton 2977: Reference: @ref{Exception Handling}.
2978:
1.48 anton 2979:
2980: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
2981: @section Defining Words
1.66 anton 2982: @cindex defining words tutorial
2983: @cindex does> tutorial
2984: @cindex create...does> tutorial
2985:
2986: @c before semantics?
1.48 anton 2987:
2988: @code{:}, @code{create}, and @code{variable} are definition words: They
2989: define other words. @code{Constant} is another definition word:
2990:
2991: @example
2992: 5 constant foo
2993: foo .
2994: @end example
2995:
2996: You can also use the prefixes @code{2} (double-cell) and @code{f}
2997: (floating point) with @code{variable} and @code{constant}.
2998:
2999: You can also define your own defining words. E.g.:
3000:
3001: @example
3002: : variable ( "name" -- )
3003: create 0 , ;
3004: @end example
3005:
3006: You can also define defining words that create words that do something
3007: other than just producing their address:
3008:
3009: @example
3010: : constant ( n "name" -- )
3011: create ,
3012: does> ( -- n )
1.50 anton 3013: ( addr ) @@ ;
1.48 anton 3014:
3015: 5 constant foo
3016: foo .
3017: @end example
3018:
3019: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3020: @code{does>} replaces @code{;}, but it also does something else: It
3021: changes the last defined word such that it pushes the address of the
3022: body of the word and then performs the code after the @code{does>}
3023: whenever it is called.
3024:
3025: In the example above, @code{constant} uses @code{,} to store 5 into the
3026: body of @code{foo}. When @code{foo} executes, it pushes the address of
3027: the body onto the stack, then (in the code after the @code{does>})
3028: fetches the 5 from there.
3029:
3030: The stack comment near the @code{does>} reflects the stack effect of the
3031: defined word, not the stack effect of the code after the @code{does>}
3032: (the difference is that the code expects the address of the body that
3033: the stack comment does not show).
3034:
3035: You can use these definition words to do factoring in cases that involve
3036: (other) definition words. E.g., a field offset is always added to an
3037: address. Instead of defining
3038:
3039: @example
3040: 2 cells constant offset-field1
3041: @end example
3042:
3043: and using this like
3044:
3045: @example
3046: ( addr ) offset-field1 +
3047: @end example
3048:
3049: you can define a definition word
3050:
3051: @example
3052: : simple-field ( n "name" -- )
3053: create ,
3054: does> ( n1 -- n1+n )
1.50 anton 3055: ( addr ) @@ + ;
1.48 anton 3056: @end example
1.21 crook 3057:
1.48 anton 3058: Definition and use of field offsets now look like this:
1.21 crook 3059:
1.48 anton 3060: @example
3061: 2 cells simple-field field1
1.60 anton 3062: create mystruct 4 cells allot
3063: mystruct .s field1 .s drop
1.48 anton 3064: @end example
1.21 crook 3065:
1.48 anton 3066: If you want to do something with the word without performing the code
3067: after the @code{does>}, you can access the body of a @code{create}d word
3068: with @code{>body ( xt -- addr )}:
1.21 crook 3069:
1.48 anton 3070: @example
3071: : value ( n "name" -- )
3072: create ,
3073: does> ( -- n1 )
1.50 anton 3074: @@ ;
1.48 anton 3075: : to ( n "name" -- )
3076: ' >body ! ;
1.21 crook 3077:
1.48 anton 3078: 5 value foo
3079: foo .
3080: 7 to foo
3081: foo .
3082: @end example
1.21 crook 3083:
1.141 anton 3084: @quotation Assignment
1.48 anton 3085: Define @code{defer ( "name" -- )}, which creates a word that stores an
3086: XT (at the start the XT of @code{abort}), and upon execution
3087: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3088: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3089: recursion is one application of @code{defer}.
1.141 anton 3090: @end quotation
1.29 crook 3091:
1.66 anton 3092: Reference: @ref{User-defined Defining Words}.
3093:
3094:
1.48 anton 3095: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3096: @section Arrays and Records
1.66 anton 3097: @cindex arrays tutorial
3098: @cindex records tutorial
3099: @cindex structs tutorial
1.29 crook 3100:
1.48 anton 3101: Forth has no standard words for defining data structures such as arrays
3102: and records (structs in C terminology), but you can build them yourself
3103: based on address arithmetic. You can also define words for defining
3104: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3105:
1.48 anton 3106: One of the first projects a Forth newcomer sets out upon when learning
3107: about defining words is an array defining word (possibly for
3108: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3109: learn something from it. However, don't be disappointed when you later
3110: learn that you have little use for these words (inappropriate use would
3111: be even worse). I have not yet found a set of useful array words yet;
3112: the needs are just too diverse, and named, global arrays (the result of
3113: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3114: consider how to pass them as parameters). Another such project is a set
3115: of words to help dealing with strings.
1.29 crook 3116:
1.48 anton 3117: On the other hand, there is a useful set of record words, and it has
3118: been defined in @file{compat/struct.fs}; these words are predefined in
3119: Gforth. They are explained in depth elsewhere in this manual (see
3120: @pxref{Structures}). The @code{simple-field} example above is
3121: simplified variant of fields in this package.
1.21 crook 3122:
3123:
1.48 anton 3124: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3125: @section @code{POSTPONE}
1.66 anton 3126: @cindex postpone tutorial
1.21 crook 3127:
1.48 anton 3128: You can compile the compilation semantics (instead of compiling the
3129: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3130:
1.48 anton 3131: @example
3132: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3133: POSTPONE + ; immediate
1.48 anton 3134: : foo ( n1 n2 -- n )
3135: MY-+ ;
3136: 1 2 foo .
3137: see foo
3138: @end example
1.21 crook 3139:
1.48 anton 3140: During the definition of @code{foo} the text interpreter performs the
3141: compilation semantics of @code{MY-+}, which performs the compilation
3142: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3143:
3144: This example also displays separate stack comments for the compilation
3145: semantics and for the stack effect of the compiled code. For words with
3146: default compilation semantics these stack effects are usually not
3147: displayed; the stack effect of the compilation semantics is always
3148: @code{( -- )} for these words, the stack effect for the compiled code is
3149: the stack effect of the interpretation semantics.
3150:
3151: Note that the state of the interpreter does not come into play when
3152: performing the compilation semantics in this way. You can also perform
3153: it interpretively, e.g.:
3154:
3155: @example
3156: : foo2 ( n1 n2 -- n )
3157: [ MY-+ ] ;
3158: 1 2 foo .
3159: see foo
3160: @end example
1.21 crook 3161:
1.48 anton 3162: However, there are some broken Forth systems where this does not always
1.62 crook 3163: work, and therefore this practice was been declared non-standard in
1.48 anton 3164: 1999.
3165: @c !! repair.fs
3166:
3167: Here is another example for using @code{POSTPONE}:
1.44 crook 3168:
1.48 anton 3169: @example
3170: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3171: POSTPONE negate POSTPONE + ; immediate compile-only
3172: : bar ( n1 n2 -- n )
3173: MY-- ;
3174: 2 1 bar .
3175: see bar
3176: @end example
1.21 crook 3177:
1.48 anton 3178: You can define @code{ENDIF} in this way:
1.21 crook 3179:
1.48 anton 3180: @example
3181: : ENDIF ( Compilation: orig -- )
3182: POSTPONE then ; immediate
3183: @end example
1.21 crook 3184:
1.141 anton 3185: @quotation Assignment
1.48 anton 3186: Write @code{MY-2DUP} that has compilation semantics equivalent to
3187: @code{2dup}, but compiles @code{over over}.
1.141 anton 3188: @end quotation
1.29 crook 3189:
1.66 anton 3190: @c !! @xref{Macros} for reference
3191:
3192:
1.48 anton 3193: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3194: @section @code{Literal}
1.66 anton 3195: @cindex literal tutorial
1.29 crook 3196:
1.48 anton 3197: You cannot @code{POSTPONE} numbers:
1.21 crook 3198:
1.48 anton 3199: @example
3200: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3201: @end example
3202:
1.48 anton 3203: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3204:
1.48 anton 3205: @example
3206: : [FOO] ( compilation: --; run-time: -- n )
3207: 500 POSTPONE literal ; immediate
1.29 crook 3208:
1.60 anton 3209: : flip [FOO] ;
1.48 anton 3210: flip .
3211: see flip
3212: @end example
1.29 crook 3213:
1.48 anton 3214: @code{LITERAL} consumes a number at compile-time (when it's compilation
3215: semantics are executed) and pushes it at run-time (when the code it
3216: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3217: number computed at compile time into the current word:
1.29 crook 3218:
1.48 anton 3219: @example
3220: : bar ( -- n )
3221: [ 2 2 + ] literal ;
3222: see bar
3223: @end example
1.29 crook 3224:
1.141 anton 3225: @quotation Assignment
1.48 anton 3226: Write @code{]L} which allows writing the example above as @code{: bar (
3227: -- n ) [ 2 2 + ]L ;}
1.141 anton 3228: @end quotation
1.48 anton 3229:
1.66 anton 3230: @c !! @xref{Macros} for reference
3231:
1.48 anton 3232:
3233: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3234: @section Advanced macros
1.66 anton 3235: @cindex macros, advanced tutorial
3236: @cindex run-time code generation, tutorial
1.48 anton 3237:
1.66 anton 3238: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3239: Execution Tokens}. It frequently performs @code{execute}, a relatively
3240: expensive operation in some Forth implementations. You can use
1.48 anton 3241: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3242: and produce a word that contains the word to be performed directly:
3243:
3244: @c use ]] ... [[
3245: @example
3246: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3247: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3248: \ array beginning at addr and containing u elements
3249: @{ xt @}
3250: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3251: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3252: 1 cells POSTPONE literal POSTPONE +loop ;
3253:
3254: : sum-array ( addr u -- n )
3255: 0 rot rot [ ' + compile-map-array ] ;
3256: see sum-array
3257: a 5 sum-array .
3258: @end example
3259:
3260: You can use the full power of Forth for generating the code; here's an
3261: example where the code is generated in a loop:
3262:
3263: @example
3264: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3265: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3266: POSTPONE tuck POSTPONE @@
1.48 anton 3267: POSTPONE literal POSTPONE * POSTPONE +
3268: POSTPONE swap POSTPONE cell+ ;
3269:
3270: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3271: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3272: 0 postpone literal postpone swap
3273: [ ' compile-vmul-step compile-map-array ]
3274: postpone drop ;
3275: see compile-vmul
3276:
3277: : a-vmul ( addr -- n )
1.51 pazsan 3278: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3279: [ a 5 compile-vmul ] ;
3280: see a-vmul
3281: a a-vmul .
3282: @end example
3283:
3284: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3285: also use @code{map-array} instead (try it now!).
1.48 anton 3286:
3287: You can use this technique for efficient multiplication of large
3288: matrices. In matrix multiplication, you multiply every line of one
3289: matrix with every column of the other matrix. You can generate the code
3290: for one line once, and use it for every column. The only downside of
3291: this technique is that it is cumbersome to recover the memory consumed
3292: by the generated code when you are done (and in more complicated cases
3293: it is not possible portably).
3294:
1.66 anton 3295: @c !! @xref{Macros} for reference
3296:
3297:
1.48 anton 3298: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3299: @section Compilation Tokens
1.66 anton 3300: @cindex compilation tokens, tutorial
3301: @cindex CT, tutorial
1.48 anton 3302:
3303: This section is Gforth-specific. You can skip it.
3304:
3305: @code{' word compile,} compiles the interpretation semantics. For words
3306: with default compilation semantics this is the same as performing the
3307: compilation semantics. To represent the compilation semantics of other
3308: words (e.g., words like @code{if} that have no interpretation
3309: semantics), Gforth has the concept of a compilation token (CT,
3310: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3311: You can perform the compilation semantics represented by a CT with
3312: @code{execute}:
1.29 crook 3313:
1.48 anton 3314: @example
3315: : foo2 ( n1 n2 -- n )
3316: [ comp' + execute ] ;
3317: see foo
3318: @end example
1.29 crook 3319:
1.48 anton 3320: You can compile the compilation semantics represented by a CT with
3321: @code{postpone,}:
1.30 anton 3322:
1.48 anton 3323: @example
3324: : foo3 ( -- )
3325: [ comp' + postpone, ] ;
3326: see foo3
3327: @end example
1.30 anton 3328:
1.51 pazsan 3329: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3330: @code{comp'} is particularly useful for words that have no
3331: interpretation semantics:
1.29 crook 3332:
1.30 anton 3333: @example
1.48 anton 3334: ' if
1.60 anton 3335: comp' if .s 2drop
1.30 anton 3336: @end example
3337:
1.66 anton 3338: Reference: @ref{Tokens for Words}.
3339:
1.29 crook 3340:
1.48 anton 3341: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3342: @section Wordlists and Search Order
1.66 anton 3343: @cindex wordlists tutorial
3344: @cindex search order, tutorial
1.48 anton 3345:
3346: The dictionary is not just a memory area that allows you to allocate
3347: memory with @code{allot}, it also contains the Forth words, arranged in
3348: several wordlists. When searching for a word in a wordlist,
3349: conceptually you start searching at the youngest and proceed towards
3350: older words (in reality most systems nowadays use hash-tables); i.e., if
3351: you define a word with the same name as an older word, the new word
3352: shadows the older word.
3353:
3354: Which wordlists are searched in which order is determined by the search
3355: order. You can display the search order with @code{order}. It displays
3356: first the search order, starting with the wordlist searched first, then
3357: it displays the wordlist that will contain newly defined words.
1.21 crook 3358:
1.48 anton 3359: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3360:
1.48 anton 3361: @example
3362: wordlist constant mywords
3363: @end example
1.21 crook 3364:
1.48 anton 3365: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3366: defined words (the @emph{current} wordlist):
1.21 crook 3367:
1.48 anton 3368: @example
3369: mywords set-current
3370: order
3371: @end example
1.26 crook 3372:
1.48 anton 3373: Gforth does not display a name for the wordlist in @code{mywords}
3374: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3375:
1.48 anton 3376: You can get the current wordlist with @code{get-current ( -- wid)}. If
3377: you want to put something into a specific wordlist without overall
3378: effect on the current wordlist, this typically looks like this:
1.21 crook 3379:
1.48 anton 3380: @example
3381: get-current mywords set-current ( wid )
3382: create someword
3383: ( wid ) set-current
3384: @end example
1.21 crook 3385:
1.48 anton 3386: You can write the search order with @code{set-order ( wid1 .. widn n --
3387: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3388: searched wordlist is topmost.
1.21 crook 3389:
1.48 anton 3390: @example
3391: get-order mywords swap 1+ set-order
3392: order
3393: @end example
1.21 crook 3394:
1.48 anton 3395: Yes, the order of wordlists in the output of @code{order} is reversed
3396: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3397:
1.141 anton 3398: @quotation Assignment
1.48 anton 3399: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3400: wordlist to the search order. Define @code{previous ( -- )}, which
3401: removes the first searched wordlist from the search order. Experiment
3402: with boundary conditions (you will see some crashes or situations that
3403: are hard or impossible to leave).
1.141 anton 3404: @end quotation
1.21 crook 3405:
1.48 anton 3406: The search order is a powerful foundation for providing features similar
3407: to Modula-2 modules and C++ namespaces. However, trying to modularize
3408: programs in this way has disadvantages for debugging and reuse/factoring
3409: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3410: though). These disadvantages are not so clear in other
1.82 anton 3411: languages/programming environments, because these languages are not so
1.48 anton 3412: strong in debugging and reuse.
1.21 crook 3413:
1.66 anton 3414: @c !! example
3415:
3416: Reference: @ref{Word Lists}.
1.21 crook 3417:
1.29 crook 3418: @c ******************************************************************
1.48 anton 3419: @node Introduction, Words, Tutorial, Top
1.29 crook 3420: @comment node-name, next, previous, up
3421: @chapter An Introduction to ANS Forth
3422: @cindex Forth - an introduction
1.21 crook 3423:
1.83 anton 3424: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3425: that it is slower-paced in its examples, but uses them to dive deep into
3426: explaining Forth internals (not covered by the Tutorial). Apart from
3427: that, this chapter covers far less material. It is suitable for reading
3428: without using a computer.
3429:
1.29 crook 3430: The primary purpose of this manual is to document Gforth. However, since
3431: Forth is not a widely-known language and there is a lack of up-to-date
3432: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3433: material. For other sources of Forth-related
3434: information, see @ref{Forth-related information}.
1.21 crook 3435:
1.29 crook 3436: The examples in this section should work on any ANS Forth; the
3437: output shown was produced using Gforth. Each example attempts to
3438: reproduce the exact output that Gforth produces. If you try out the
3439: examples (and you should), what you should type is shown @kbd{like this}
3440: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3441: that, where the example shows @key{RET} it means that you should
1.29 crook 3442: press the ``carriage return'' key. Unfortunately, some output formats for
3443: this manual cannot show the difference between @kbd{this} and
3444: @code{this} which will make trying out the examples harder (but not
3445: impossible).
1.21 crook 3446:
1.29 crook 3447: Forth is an unusual language. It provides an interactive development
3448: environment which includes both an interpreter and compiler. Forth
3449: programming style encourages you to break a problem down into many
3450: @cindex factoring
3451: small fragments (@dfn{factoring}), and then to develop and test each
3452: fragment interactively. Forth advocates assert that breaking the
3453: edit-compile-test cycle used by conventional programming languages can
3454: lead to great productivity improvements.
1.21 crook 3455:
1.29 crook 3456: @menu
1.67 anton 3457: * Introducing the Text Interpreter::
3458: * Stacks and Postfix notation::
3459: * Your first definition::
3460: * How does that work?::
3461: * Forth is written in Forth::
3462: * Review - elements of a Forth system::
3463: * Where to go next::
3464: * Exercises::
1.29 crook 3465: @end menu
1.21 crook 3466:
1.29 crook 3467: @comment ----------------------------------------------
3468: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3469: @section Introducing the Text Interpreter
3470: @cindex text interpreter
3471: @cindex outer interpreter
1.21 crook 3472:
1.30 anton 3473: @c IMO this is too detailed and the pace is too slow for
3474: @c an introduction. If you know German, take a look at
3475: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3476: @c to see how I do it - anton
3477:
1.44 crook 3478: @c nac-> Where I have accepted your comments 100% and modified the text
3479: @c accordingly, I have deleted your comments. Elsewhere I have added a
3480: @c response like this to attempt to rationalise what I have done. Of
3481: @c course, this is a very clumsy mechanism for something that would be
3482: @c done far more efficiently over a beer. Please delete any dialogue
3483: @c you consider closed.
3484:
1.29 crook 3485: When you invoke the Forth image, you will see a startup banner printed
3486: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3487: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3488: its command line interpreter, which is called the @dfn{Text Interpreter}
3489: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3490: about the text interpreter as you read through this chapter, for more
3491: detail @pxref{The Text Interpreter}).
1.21 crook 3492:
1.29 crook 3493: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3494: input. Type a number and press the @key{RET} key:
1.21 crook 3495:
1.26 crook 3496: @example
1.30 anton 3497: @kbd{45@key{RET}} ok
1.26 crook 3498: @end example
1.21 crook 3499:
1.29 crook 3500: Rather than give you a prompt to invite you to input something, the text
3501: interpreter prints a status message @i{after} it has processed a line
3502: of input. The status message in this case (``@code{ ok}'' followed by
3503: carriage-return) indicates that the text interpreter was able to process
3504: all of your input successfully. Now type something illegal:
3505:
3506: @example
1.30 anton 3507: @kbd{qwer341@key{RET}}
1.134 anton 3508: *the terminal*:2: Undefined word
3509: >>>qwer341<<<
3510: Backtrace:
3511: $2A95B42A20 throw
3512: $2A95B57FB8 no.extensions
1.29 crook 3513: @end example
1.23 crook 3514:
1.134 anton 3515: The exact text, other than the ``Undefined word'' may differ slightly
3516: on your system, but the effect is the same; when the text interpreter
1.29 crook 3517: detects an error, it discards any remaining text on a line, resets
1.134 anton 3518: certain internal state and prints an error message. For a detailed
3519: description of error messages see @ref{Error messages}.
1.23 crook 3520:
1.29 crook 3521: The text interpreter waits for you to press carriage-return, and then
3522: processes your input line. Starting at the beginning of the line, it
3523: breaks the line into groups of characters separated by spaces. For each
3524: group of characters in turn, it makes two attempts to do something:
1.23 crook 3525:
1.29 crook 3526: @itemize @bullet
3527: @item
1.44 crook 3528: @cindex name dictionary
1.29 crook 3529: It tries to treat it as a command. It does this by searching a @dfn{name
3530: dictionary}. If the group of characters matches an entry in the name
3531: dictionary, the name dictionary provides the text interpreter with
3532: information that allows the text interpreter perform some actions. In
3533: Forth jargon, we say that the group
3534: @cindex word
3535: @cindex definition
3536: @cindex execution token
3537: @cindex xt
3538: of characters names a @dfn{word}, that the dictionary search returns an
3539: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3540: word, and that the text interpreter executes the xt. Often, the terms
3541: @dfn{word} and @dfn{definition} are used interchangeably.
3542: @item
3543: If the text interpreter fails to find a match in the name dictionary, it
3544: tries to treat the group of characters as a number in the current number
3545: base (when you start up Forth, the current number base is base 10). If
3546: the group of characters legitimately represents a number, the text
3547: interpreter pushes the number onto a stack (we'll learn more about that
3548: in the next section).
3549: @end itemize
1.23 crook 3550:
1.29 crook 3551: If the text interpreter is unable to do either of these things with any
3552: group of characters, it discards the group of characters and the rest of
3553: the line, then prints an error message. If the text interpreter reaches
3554: the end of the line without error, it prints the status message ``@code{ ok}''
3555: followed by carriage-return.
1.21 crook 3556:
1.29 crook 3557: This is the simplest command we can give to the text interpreter:
1.23 crook 3558:
3559: @example
1.30 anton 3560: @key{RET} ok
1.23 crook 3561: @end example
1.21 crook 3562:
1.29 crook 3563: The text interpreter did everything we asked it to do (nothing) without
3564: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3565: command:
1.21 crook 3566:
1.23 crook 3567: @example
1.30 anton 3568: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3569: *the terminal*:3: Undefined word
3570: 12 dup >>>fred<<< dup
3571: Backtrace:
3572: $2A95B42A20 throw
3573: $2A95B57FB8 no.extensions
1.23 crook 3574: @end example
1.21 crook 3575:
1.29 crook 3576: When you press the carriage-return key, the text interpreter starts to
3577: work its way along the line:
1.21 crook 3578:
1.29 crook 3579: @itemize @bullet
3580: @item
3581: When it gets to the space after the @code{2}, it takes the group of
3582: characters @code{12} and looks them up in the name
3583: dictionary@footnote{We can't tell if it found them or not, but assume
3584: for now that it did not}. There is no match for this group of characters
3585: in the name dictionary, so it tries to treat them as a number. It is
3586: able to do this successfully, so it puts the number, 12, ``on the stack''
3587: (whatever that means).
3588: @item
3589: The text interpreter resumes scanning the line and gets the next group
3590: of characters, @code{dup}. It looks it up in the name dictionary and
3591: (you'll have to take my word for this) finds it, and executes the word
3592: @code{dup} (whatever that means).
3593: @item
3594: Once again, the text interpreter resumes scanning the line and gets the
3595: group of characters @code{fred}. It looks them up in the name
3596: dictionary, but can't find them. It tries to treat them as a number, but
3597: they don't represent any legal number.
3598: @end itemize
1.21 crook 3599:
1.29 crook 3600: At this point, the text interpreter gives up and prints an error
3601: message. The error message shows exactly how far the text interpreter
3602: got in processing the line. In particular, it shows that the text
3603: interpreter made no attempt to do anything with the final character
3604: group, @code{dup}, even though we have good reason to believe that the
3605: text interpreter would have no problem looking that word up and
3606: executing it a second time.
1.21 crook 3607:
3608:
1.29 crook 3609: @comment ----------------------------------------------
3610: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3611: @section Stacks, postfix notation and parameter passing
3612: @cindex text interpreter
3613: @cindex outer interpreter
1.21 crook 3614:
1.29 crook 3615: In procedural programming languages (like C and Pascal), the
3616: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3617: functions or procedures are called with @dfn{explicit parameters}. For
3618: example, in C we might write:
1.21 crook 3619:
1.23 crook 3620: @example
1.29 crook 3621: total = total + new_volume(length,height,depth);
1.23 crook 3622: @end example
1.21 crook 3623:
1.23 crook 3624: @noindent
1.29 crook 3625: where new_volume is a function-call to another piece of code, and total,
3626: length, height and depth are all variables. length, height and depth are
3627: parameters to the function-call.
1.21 crook 3628:
1.29 crook 3629: In Forth, the equivalent of the function or procedure is the
3630: @dfn{definition} and parameters are implicitly passed between
3631: definitions using a shared stack that is visible to the
3632: programmer. Although Forth does support variables, the existence of the
3633: stack means that they are used far less often than in most other
3634: programming languages. When the text interpreter encounters a number, it
3635: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3636: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3637: used for any operation is implied unambiguously by the operation being
3638: performed. The stack used for all integer operations is called the @dfn{data
3639: stack} and, since this is the stack used most commonly, references to
3640: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3641:
1.29 crook 3642: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3643:
1.23 crook 3644: @example
1.30 anton 3645: @kbd{1 2 3@key{RET}} ok
1.23 crook 3646: @end example
1.21 crook 3647:
1.29 crook 3648: Then this instructs the text interpreter to placed three numbers on the
3649: (data) stack. An analogy for the behaviour of the stack is to take a
3650: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3651: the table. The 3 was the last card onto the pile (``last-in'') and if
3652: you take a card off the pile then, unless you're prepared to fiddle a
3653: bit, the card that you take off will be the 3 (``first-out''). The
3654: number that will be first-out of the stack is called the @dfn{top of
3655: stack}, which
3656: @cindex TOS definition
3657: is often abbreviated to @dfn{TOS}.
1.21 crook 3658:
1.29 crook 3659: To understand how parameters are passed in Forth, consider the
3660: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3661: be surprised to learn that this definition performs addition. More
3662: precisely, it adds two number together and produces a result. Where does
3663: it get the two numbers from? It takes the top two numbers off the
3664: stack. Where does it place the result? On the stack. You can act-out the
3665: behaviour of @code{+} with your playing cards like this:
1.21 crook 3666:
3667: @itemize @bullet
3668: @item
1.29 crook 3669: Pick up two cards from the stack on the table
1.21 crook 3670: @item
1.29 crook 3671: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3672: numbers''
1.21 crook 3673: @item
1.29 crook 3674: Decide that the answer is 5
1.21 crook 3675: @item
1.29 crook 3676: Shuffle the two cards back into the pack and find a 5
1.21 crook 3677: @item
1.29 crook 3678: Put a 5 on the remaining ace that's on the table.
1.21 crook 3679: @end itemize
3680:
1.29 crook 3681: If you don't have a pack of cards handy but you do have Forth running,
3682: you can use the definition @code{.s} to show the current state of the stack,
3683: without affecting the stack. Type:
1.21 crook 3684:
3685: @example
1.124 anton 3686: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3687: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3688: @end example
3689:
1.124 anton 3690: The text interpreter looks up the word @code{clearstacks} and executes
3691: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3692: left on it by earlier examples. The text interpreter pushes each of the
3693: three numbers in turn onto the stack. Finally, the text interpreter
3694: looks up the word @code{.s} and executes it. The effect of executing
3695: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3696: followed by a list of all the items on the stack; the item on the far
3697: right-hand side is the TOS.
1.21 crook 3698:
1.29 crook 3699: You can now type:
1.21 crook 3700:
1.29 crook 3701: @example
1.30 anton 3702: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3703: @end example
1.21 crook 3704:
1.29 crook 3705: @noindent
3706: which is correct; there are now 2 items on the stack and the result of
3707: the addition is 5.
1.23 crook 3708:
1.29 crook 3709: If you're playing with cards, try doing a second addition: pick up the
3710: two cards, work out that their sum is 6, shuffle them into the pack,
3711: look for a 6 and place that on the table. You now have just one item on
3712: the stack. What happens if you try to do a third addition? Pick up the
3713: first card, pick up the second card -- ah! There is no second card. This
3714: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3715: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3716: Underflow or an Invalid Memory Address error).
1.23 crook 3717:
1.29 crook 3718: The opposite situation to a stack underflow is a @dfn{stack overflow},
3719: which simply accepts that there is a finite amount of storage space
3720: reserved for the stack. To stretch the playing card analogy, if you had
3721: enough packs of cards and you piled the cards up on the table, you would
3722: eventually be unable to add another card; you'd hit the ceiling. Gforth
3723: allows you to set the maximum size of the stacks. In general, the only
3724: time that you will get a stack overflow is because a definition has a
3725: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3726:
1.29 crook 3727: There's one final use for the playing card analogy. If you model your
3728: stack using a pack of playing cards, the maximum number of items on
3729: your stack will be 52 (I assume you didn't use the Joker). The maximum
3730: @i{value} of any item on the stack is 13 (the King). In fact, the only
3731: possible numbers are positive integer numbers 1 through 13; you can't
3732: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3733: think about some of the cards, you can accommodate different
3734: numbers. For example, you could think of the Jack as representing 0,
3735: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3736: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3737: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3738:
1.29 crook 3739: In that analogy, the limit was the amount of information that a single
3740: stack entry could hold, and Forth has a similar limit. In Forth, the
3741: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3742: implementation dependent and affects the maximum value that a stack
3743: entry can hold. A Standard Forth provides a cell size of at least
3744: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3745:
1.29 crook 3746: Forth does not do any type checking for you, so you are free to
3747: manipulate and combine stack items in any way you wish. A convenient way
3748: of treating stack items is as 2's complement signed integers, and that
3749: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3750:
1.29 crook 3751: @example
1.30 anton 3752: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3753: @end example
1.21 crook 3754:
1.29 crook 3755: If you use numbers and definitions like @code{+} in order to turn Forth
3756: into a great big pocket calculator, you will realise that it's rather
3757: different from a normal calculator. Rather than typing 2 + 3 = you had
3758: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3759: result). The terminology used to describe this difference is to say that
3760: your calculator uses @dfn{Infix Notation} (parameters and operators are
3761: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3762: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3763:
1.29 crook 3764: Whilst postfix notation might look confusing to begin with, it has
3765: several important advantages:
1.21 crook 3766:
1.23 crook 3767: @itemize @bullet
3768: @item
1.29 crook 3769: it is unambiguous
1.23 crook 3770: @item
1.29 crook 3771: it is more concise
1.23 crook 3772: @item
1.29 crook 3773: it fits naturally with a stack-based system
1.23 crook 3774: @end itemize
1.21 crook 3775:
1.29 crook 3776: To examine these claims in more detail, consider these sums:
1.21 crook 3777:
1.29 crook 3778: @example
3779: 6 + 5 * 4 =
3780: 4 * 5 + 6 =
3781: @end example
1.21 crook 3782:
1.29 crook 3783: If you're just learning maths or your maths is very rusty, you will
3784: probably come up with the answer 44 for the first and 26 for the
3785: second. If you are a bit of a whizz at maths you will remember the
3786: @i{convention} that multiplication takes precendence over addition, and
3787: you'd come up with the answer 26 both times. To explain the answer 26
3788: to someone who got the answer 44, you'd probably rewrite the first sum
3789: like this:
1.21 crook 3790:
1.29 crook 3791: @example
3792: 6 + (5 * 4) =
3793: @end example
1.21 crook 3794:
1.29 crook 3795: If what you really wanted was to perform the addition before the
3796: multiplication, you would have to use parentheses to force it.
1.21 crook 3797:
1.29 crook 3798: If you did the first two sums on a pocket calculator you would probably
3799: get the right answers, unless you were very cautious and entered them using
3800: these keystroke sequences:
1.21 crook 3801:
1.29 crook 3802: 6 + 5 = * 4 =
3803: 4 * 5 = + 6 =
1.21 crook 3804:
1.29 crook 3805: Postfix notation is unambiguous because the order that the operators
3806: are applied is always explicit; that also means that parentheses are
3807: never required. The operators are @i{active} (the act of quoting the
3808: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3809:
1.29 crook 3810: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3811: equivalent ways:
1.26 crook 3812:
3813: @example
1.29 crook 3814: 6 5 4 * + or:
3815: 5 4 * 6 +
1.26 crook 3816: @end example
1.23 crook 3817:
1.29 crook 3818: An important thing that you should notice about this notation is that
3819: the @i{order} of the numbers does not change; if you want to subtract
3820: 2 from 10 you type @code{10 2 -}.
1.1 anton 3821:
1.29 crook 3822: The reason that Forth uses postfix notation is very simple to explain: it
3823: makes the implementation extremely simple, and it follows naturally from
3824: using the stack as a mechanism for passing parameters. Another way of
3825: thinking about this is to realise that all Forth definitions are
3826: @i{active}; they execute as they are encountered by the text
3827: interpreter. The result of this is that the syntax of Forth is trivially
3828: simple.
1.1 anton 3829:
3830:
3831:
1.29 crook 3832: @comment ----------------------------------------------
3833: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3834: @section Your first Forth definition
3835: @cindex first definition
1.1 anton 3836:
1.29 crook 3837: Until now, the examples we've seen have been trivial; we've just been
3838: using Forth as a bigger-than-pocket calculator. Also, each calculation
3839: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3840: again@footnote{That's not quite true. If you press the up-arrow key on
3841: your keyboard you should be able to scroll back to any earlier command,
3842: edit it and re-enter it.} In this section we'll see how to add new
3843: words to Forth's vocabulary.
1.1 anton 3844:
1.29 crook 3845: The easiest way to create a new word is to use a @dfn{colon
3846: definition}. We'll define a few and try them out before worrying too
3847: much about how they work. Try typing in these examples; be careful to
3848: copy the spaces accurately:
1.1 anton 3849:
1.29 crook 3850: @example
3851: : add-two 2 + . ;
3852: : greet ." Hello and welcome" ;
3853: : demo 5 add-two ;
3854: @end example
1.1 anton 3855:
1.29 crook 3856: @noindent
3857: Now try them out:
1.1 anton 3858:
1.29 crook 3859: @example
1.30 anton 3860: @kbd{greet@key{RET}} Hello and welcome ok
3861: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3862: @kbd{4 add-two@key{RET}} 6 ok
3863: @kbd{demo@key{RET}} 7 ok
3864: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3865: @end example
1.1 anton 3866:
1.29 crook 3867: The first new thing that we've introduced here is the pair of words
3868: @code{:} and @code{;}. These are used to start and terminate a new
3869: definition, respectively. The first word after the @code{:} is the name
3870: for the new definition.
1.1 anton 3871:
1.29 crook 3872: As you can see from the examples, a definition is built up of words that
3873: have already been defined; Forth makes no distinction between
3874: definitions that existed when you started the system up, and those that
3875: you define yourself.
1.1 anton 3876:
1.29 crook 3877: The examples also introduce the words @code{.} (dot), @code{."}
3878: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3879: the stack and displays it. It's like @code{.s} except that it only
3880: displays the top item of the stack and it is destructive; after it has
3881: executed, the number is no longer on the stack. There is always one
3882: space printed after the number, and no spaces before it. Dot-quote
3883: defines a string (a sequence of characters) that will be printed when
3884: the word is executed. The string can contain any printable characters
3885: except @code{"}. A @code{"} has a special function; it is not a Forth
3886: word but it acts as a delimiter (the way that delimiters work is
3887: described in the next section). Finally, @code{dup} duplicates the value
3888: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3889:
1.29 crook 3890: We already know that the text interpreter searches through the
3891: dictionary to locate names. If you've followed the examples earlier, you
3892: will already have a definition called @code{add-two}. Lets try modifying
3893: it by typing in a new definition:
1.1 anton 3894:
1.29 crook 3895: @example
1.30 anton 3896: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3897: @end example
1.5 anton 3898:
1.29 crook 3899: Forth recognised that we were defining a word that already exists, and
3900: printed a message to warn us of that fact. Let's try out the new
3901: definition:
1.5 anton 3902:
1.29 crook 3903: @example
1.30 anton 3904: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3905: @end example
1.1 anton 3906:
1.29 crook 3907: @noindent
3908: All that we've actually done here, though, is to create a new
3909: definition, with a particular name. The fact that there was already a
3910: definition with the same name did not make any difference to the way
3911: that the new definition was created (except that Forth printed a warning
3912: message). The old definition of add-two still exists (try @code{demo}
3913: again to see that this is true). Any new definition will use the new
3914: definition of @code{add-two}, but old definitions continue to use the
3915: version that already existed at the time that they were @code{compiled}.
1.1 anton 3916:
1.29 crook 3917: Before you go on to the next section, try defining and redefining some
3918: words of your own.
1.1 anton 3919:
1.29 crook 3920: @comment ----------------------------------------------
3921: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3922: @section How does that work?
3923: @cindex parsing words
1.1 anton 3924:
1.30 anton 3925: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3926:
3927: @c Is it a good idea to talk about the interpretation semantics of a
3928: @c number? We don't have an xt to go along with it. - anton
3929:
3930: @c Now that I have eliminated execution semantics, I wonder if it would not
3931: @c be better to keep them (or add run-time semantics), to make it easier to
3932: @c explain what compilation semantics usually does. - anton
3933:
1.44 crook 3934: @c nac-> I removed the term ``default compilation sematics'' from the
3935: @c introductory chapter. Removing ``execution semantics'' was making
3936: @c everything simpler to explain, then I think the use of this term made
3937: @c everything more complex again. I replaced it with ``default
3938: @c semantics'' (which is used elsewhere in the manual) by which I mean
3939: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3940: @c flag set''.
3941:
3942: @c anton: I have eliminated default semantics (except in one place where it
3943: @c means "default interpretation and compilation semantics"), because it
3944: @c makes no sense in the presence of combined words. I reverted to
3945: @c "execution semantics" where necessary.
3946:
3947: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3948: @c section (and, unusually for me, I think I even made it shorter!). See
3949: @c what you think -- I know I have not addressed your primary concern
3950: @c that it is too heavy-going for an introduction. From what I understood
3951: @c of your course notes it looks as though they might be a good framework.
3952: @c Things that I've tried to capture here are some things that came as a
3953: @c great revelation here when I first understood them. Also, I like the
3954: @c fact that a very simple code example shows up almost all of the issues
3955: @c that you need to understand to see how Forth works. That's unique and
3956: @c worthwhile to emphasise.
3957:
1.83 anton 3958: @c anton: I think it's a good idea to present the details, especially those
3959: @c that you found to be a revelation, and probably the tutorial tries to be
3960: @c too superficial and does not get some of the things across that make
3961: @c Forth special. I do believe that most of the time these things should
3962: @c be discussed at the end of a section or in separate sections instead of
3963: @c in the middle of a section (e.g., the stuff you added in "User-defined
3964: @c defining words" leads in a completely different direction from the rest
3965: @c of the section).
3966:
1.29 crook 3967: Now we're going to take another look at the definition of @code{add-two}
3968: from the previous section. From our knowledge of the way that the text
3969: interpreter works, we would have expected this result when we tried to
3970: define @code{add-two}:
1.21 crook 3971:
1.29 crook 3972: @example
1.44 crook 3973: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 3974: *the terminal*:4: Undefined word
3975: : >>>add-two<<< 2 + . ;
1.29 crook 3976: @end example
1.28 crook 3977:
1.29 crook 3978: The reason that this didn't happen is bound up in the way that @code{:}
3979: works. The word @code{:} does two special things. The first special
3980: thing that it does prevents the text interpreter from ever seeing the
3981: characters @code{add-two}. The text interpreter uses a variable called
3982: @cindex modifying >IN
1.44 crook 3983: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 3984: input line. When it encounters the word @code{:} it behaves in exactly
3985: the same way as it does for any other word; it looks it up in the name
3986: dictionary, finds its xt and executes it. When @code{:} executes, it
3987: looks at the input buffer, finds the word @code{add-two} and advances the
3988: value of @code{>IN} to point past it. It then does some other stuff
3989: associated with creating the new definition (including creating an entry
3990: for @code{add-two} in the name dictionary). When the execution of @code{:}
3991: completes, control returns to the text interpreter, which is oblivious
3992: to the fact that it has been tricked into ignoring part of the input
3993: line.
1.21 crook 3994:
1.29 crook 3995: @cindex parsing words
3996: Words like @code{:} -- words that advance the value of @code{>IN} and so
3997: prevent the text interpreter from acting on the whole of the input line
3998: -- are called @dfn{parsing words}.
1.21 crook 3999:
1.29 crook 4000: @cindex @code{state} - effect on the text interpreter
4001: @cindex text interpreter - effect of state
4002: The second special thing that @code{:} does is change the value of a
4003: variable called @code{state}, which affects the way that the text
4004: interpreter behaves. When Gforth starts up, @code{state} has the value
4005: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4006: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4007: the text interpreter is said to be @dfn{compiling}.
4008:
4009: In this example, the text interpreter is compiling when it processes the
4010: string ``@code{2 + . ;}''. It still breaks the string down into
4011: character sequences in the same way. However, instead of pushing the
4012: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4013: into the definition of @code{add-two} that will make the number @code{2} get
4014: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4015: the behaviours of @code{+} and @code{.} are also compiled into the
4016: definition.
4017:
4018: One category of words don't get compiled. These so-called @dfn{immediate
4019: words} get executed (performed @i{now}) regardless of whether the text
4020: interpreter is interpreting or compiling. The word @code{;} is an
4021: immediate word. Rather than being compiled into the definition, it
4022: executes. Its effect is to terminate the current definition, which
4023: includes changing the value of @code{state} back to 0.
4024:
4025: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4026: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4027: definition.
1.28 crook 4028:
1.30 anton 4029: In Forth, every word or number can be described in terms of two
1.29 crook 4030: properties:
1.28 crook 4031:
4032: @itemize @bullet
4033: @item
1.29 crook 4034: @cindex interpretation semantics
1.44 crook 4035: Its @dfn{interpretation semantics} describe how it will behave when the
4036: text interpreter encounters it in @dfn{interpret} state. The
4037: interpretation semantics of a word are represented by an @dfn{execution
4038: token}.
1.28 crook 4039: @item
1.29 crook 4040: @cindex compilation semantics
1.44 crook 4041: Its @dfn{compilation semantics} describe how it will behave when the
4042: text interpreter encounters it in @dfn{compile} state. The compilation
4043: semantics of a word are represented in an implementation-dependent way;
4044: Gforth uses a @dfn{compilation token}.
1.29 crook 4045: @end itemize
4046:
4047: @noindent
4048: Numbers are always treated in a fixed way:
4049:
4050: @itemize @bullet
1.28 crook 4051: @item
1.44 crook 4052: When the number is @dfn{interpreted}, its behaviour is to push the
4053: number onto the stack.
1.28 crook 4054: @item
1.30 anton 4055: When the number is @dfn{compiled}, a piece of code is appended to the
4056: current definition that pushes the number when it runs. (In other words,
4057: the compilation semantics of a number are to postpone its interpretation
4058: semantics until the run-time of the definition that it is being compiled
4059: into.)
1.29 crook 4060: @end itemize
4061:
1.44 crook 4062: Words don't behave in such a regular way, but most have @i{default
4063: semantics} which means that they behave like this:
1.29 crook 4064:
4065: @itemize @bullet
1.28 crook 4066: @item
1.30 anton 4067: The @dfn{interpretation semantics} of the word are to do something useful.
4068: @item
1.29 crook 4069: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4070: @dfn{interpretation semantics} to the current definition (so that its
4071: run-time behaviour is to do something useful).
1.28 crook 4072: @end itemize
4073:
1.30 anton 4074: @cindex immediate words
1.44 crook 4075: The actual behaviour of any particular word can be controlled by using
4076: the words @code{immediate} and @code{compile-only} when the word is
4077: defined. These words set flags in the name dictionary entry of the most
4078: recently defined word, and these flags are retrieved by the text
4079: interpreter when it finds the word in the name dictionary.
4080:
4081: A word that is marked as @dfn{immediate} has compilation semantics that
4082: are identical to its interpretation semantics. In other words, it
4083: behaves like this:
1.29 crook 4084:
4085: @itemize @bullet
4086: @item
1.30 anton 4087: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4088: @item
1.30 anton 4089: The @dfn{compilation semantics} of the word are to do something useful
4090: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4091: @end itemize
1.28 crook 4092:
1.44 crook 4093: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4094: performing the interpretation semantics of the word directly; an attempt
4095: to do so will generate an error. It is never necessary to use
4096: @code{compile-only} (and it is not even part of ANS Forth, though it is
4097: provided by many implementations) but it is good etiquette to apply it
4098: to a word that will not behave correctly (and might have unexpected
4099: side-effects) in interpret state. For example, it is only legal to use
4100: the conditional word @code{IF} within a definition. If you forget this
4101: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4102: @code{compile-only} allows the text interpreter to generate a helpful
4103: error message rather than subjecting you to the consequences of your
4104: folly.
4105:
1.29 crook 4106: This example shows the difference between an immediate and a
4107: non-immediate word:
1.28 crook 4108:
1.29 crook 4109: @example
4110: : show-state state @@ . ;
4111: : show-state-now show-state ; immediate
4112: : word1 show-state ;
4113: : word2 show-state-now ;
1.28 crook 4114: @end example
1.23 crook 4115:
1.29 crook 4116: The word @code{immediate} after the definition of @code{show-state-now}
4117: makes that word an immediate word. These definitions introduce a new
4118: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4119: variable, and leaves it on the stack. Therefore, the behaviour of
4120: @code{show-state} is to print a number that represents the current value
4121: of @code{state}.
1.28 crook 4122:
1.29 crook 4123: When you execute @code{word1}, it prints the number 0, indicating that
4124: the system is interpreting. When the text interpreter compiled the
4125: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4126: compilation semantics are to append its interpretation semantics to the
1.29 crook 4127: current definition. When you execute @code{word1}, it performs the
1.30 anton 4128: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4129: (and therefore @code{show-state}) are executed, the system is
4130: interpreting.
1.28 crook 4131:
1.30 anton 4132: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4133: you should have seen the number -1 printed, followed by ``@code{
4134: ok}''. When the text interpreter compiled the definition of
4135: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4136: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4137: semantics. It is executed straight away (even before the text
4138: interpreter has moved on to process another group of characters; the
4139: @code{;} in this example). The effect of executing it are to display the
4140: value of @code{state} @i{at the time that the definition of}
4141: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4142: system is compiling at this time. If you execute @code{word2} it does
4143: nothing at all.
1.28 crook 4144:
1.29 crook 4145: @cindex @code{."}, how it works
4146: Before leaving the subject of immediate words, consider the behaviour of
4147: @code{."} in the definition of @code{greet}, in the previous
4148: section. This word is both a parsing word and an immediate word. Notice
4149: that there is a space between @code{."} and the start of the text
4150: @code{Hello and welcome}, but that there is no space between the last
4151: letter of @code{welcome} and the @code{"} character. The reason for this
4152: is that @code{."} is a Forth word; it must have a space after it so that
4153: the text interpreter can identify it. The @code{"} is not a Forth word;
4154: it is a @dfn{delimiter}. The examples earlier show that, when the string
4155: is displayed, there is neither a space before the @code{H} nor after the
4156: @code{e}. Since @code{."} is an immediate word, it executes at the time
4157: that @code{greet} is defined. When it executes, its behaviour is to
4158: search forward in the input line looking for the delimiter. When it
4159: finds the delimiter, it updates @code{>IN} to point past the
4160: delimiter. It also compiles some magic code into the definition of
4161: @code{greet}; the xt of a run-time routine that prints a text string. It
4162: compiles the string @code{Hello and welcome} into memory so that it is
4163: available to be printed later. When the text interpreter gains control,
4164: the next word it finds in the input stream is @code{;} and so it
4165: terminates the definition of @code{greet}.
1.28 crook 4166:
4167:
4168: @comment ----------------------------------------------
1.29 crook 4169: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4170: @section Forth is written in Forth
4171: @cindex structure of Forth programs
4172:
4173: When you start up a Forth compiler, a large number of definitions
4174: already exist. In Forth, you develop a new application using bottom-up
4175: programming techniques to create new definitions that are defined in
4176: terms of existing definitions. As you create each definition you can
4177: test and debug it interactively.
4178:
4179: If you have tried out the examples in this section, you will probably
4180: have typed them in by hand; when you leave Gforth, your definitions will
4181: be lost. You can avoid this by using a text editor to enter Forth source
4182: code into a file, and then loading code from the file using
1.49 anton 4183: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4184: processed by the text interpreter, just as though you had typed it in by
4185: hand@footnote{Actually, there are some subtle differences -- see
4186: @ref{The Text Interpreter}.}.
4187:
4188: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4189: files for program entry (@pxref{Blocks}).
1.28 crook 4190:
1.29 crook 4191: In common with many, if not most, Forth compilers, most of Gforth is
4192: actually written in Forth. All of the @file{.fs} files in the
4193: installation directory@footnote{For example,
1.30 anton 4194: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4195: study to see examples of Forth programming.
1.28 crook 4196:
1.29 crook 4197: Gforth maintains a history file that records every line that you type to
4198: the text interpreter. This file is preserved between sessions, and is
4199: used to provide a command-line recall facility. If you enter long
4200: definitions by hand, you can use a text editor to paste them out of the
4201: history file into a Forth source file for reuse at a later time
1.49 anton 4202: (for more information @pxref{Command-line editing}).
1.28 crook 4203:
4204:
4205: @comment ----------------------------------------------
1.29 crook 4206: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4207: @section Review - elements of a Forth system
4208: @cindex elements of a Forth system
1.28 crook 4209:
1.29 crook 4210: To summarise this chapter:
1.28 crook 4211:
4212: @itemize @bullet
4213: @item
1.29 crook 4214: Forth programs use @dfn{factoring} to break a problem down into small
4215: fragments called @dfn{words} or @dfn{definitions}.
4216: @item
4217: Forth program development is an interactive process.
4218: @item
4219: The main command loop that accepts input, and controls both
4220: interpretation and compilation, is called the @dfn{text interpreter}
4221: (also known as the @dfn{outer interpreter}).
4222: @item
4223: Forth has a very simple syntax, consisting of words and numbers
4224: separated by spaces or carriage-return characters. Any additional syntax
4225: is imposed by @dfn{parsing words}.
4226: @item
4227: Forth uses a stack to pass parameters between words. As a result, it
4228: uses postfix notation.
4229: @item
4230: To use a word that has previously been defined, the text interpreter
4231: searches for the word in the @dfn{name dictionary}.
4232: @item
1.30 anton 4233: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4234: @item
1.29 crook 4235: The text interpreter uses the value of @code{state} to select between
4236: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4237: semantics} of a word that it encounters.
1.28 crook 4238: @item
1.30 anton 4239: The relationship between the @dfn{interpretation semantics} and
4240: @dfn{compilation semantics} for a word
1.29 crook 4241: depend upon the way in which the word was defined (for example, whether
4242: it is an @dfn{immediate} word).
1.28 crook 4243: @item
1.29 crook 4244: Forth definitions can be implemented in Forth (called @dfn{high-level
4245: definitions}) or in some other way (usually a lower-level language and
4246: as a result often called @dfn{low-level definitions}, @dfn{code
4247: definitions} or @dfn{primitives}).
1.28 crook 4248: @item
1.29 crook 4249: Many Forth systems are implemented mainly in Forth.
1.28 crook 4250: @end itemize
4251:
4252:
1.29 crook 4253: @comment ----------------------------------------------
1.48 anton 4254: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4255: @section Where To Go Next
4256: @cindex where to go next
1.28 crook 4257:
1.29 crook 4258: Amazing as it may seem, if you have read (and understood) this far, you
4259: know almost all the fundamentals about the inner workings of a Forth
4260: system. You certainly know enough to be able to read and understand the
4261: rest of this manual and the ANS Forth document, to learn more about the
4262: facilities that Forth in general and Gforth in particular provide. Even
4263: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4264: However, that's not a good idea just yet... better to try writing some
1.29 crook 4265: programs in Gforth.
1.28 crook 4266:
1.29 crook 4267: Forth has such a rich vocabulary that it can be hard to know where to
4268: start in learning it. This section suggests a few sets of words that are
4269: enough to write small but useful programs. Use the word index in this
4270: document to learn more about each word, then try it out and try to write
4271: small definitions using it. Start by experimenting with these words:
1.28 crook 4272:
4273: @itemize @bullet
4274: @item
1.29 crook 4275: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4276: @item
4277: Comparison: @code{MIN MAX =}
4278: @item
4279: Logic: @code{AND OR XOR NOT}
4280: @item
4281: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4282: @item
1.29 crook 4283: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4284: @item
1.29 crook 4285: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4286: @item
1.29 crook 4287: Defining words: @code{: ; CREATE}
1.28 crook 4288: @item
1.29 crook 4289: Memory allocation words: @code{ALLOT ,}
1.28 crook 4290: @item
1.29 crook 4291: Tools: @code{SEE WORDS .S MARKER}
4292: @end itemize
4293:
4294: When you have mastered those, go on to:
4295:
4296: @itemize @bullet
1.28 crook 4297: @item
1.29 crook 4298: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4299: @item
1.29 crook 4300: Memory access: @code{@@ !}
1.28 crook 4301: @end itemize
1.23 crook 4302:
1.29 crook 4303: When you have mastered these, there's nothing for it but to read through
4304: the whole of this manual and find out what you've missed.
4305:
4306: @comment ----------------------------------------------
1.48 anton 4307: @node Exercises, , Where to go next, Introduction
1.29 crook 4308: @section Exercises
4309: @cindex exercises
4310:
4311: TODO: provide a set of programming excercises linked into the stuff done
4312: already and into other sections of the manual. Provide solutions to all
4313: the exercises in a .fs file in the distribution.
4314:
4315: @c Get some inspiration from Starting Forth and Kelly&Spies.
4316:
4317: @c excercises:
4318: @c 1. take inches and convert to feet and inches.
4319: @c 2. take temperature and convert from fahrenheight to celcius;
4320: @c may need to care about symmetric vs floored??
4321: @c 3. take input line and do character substitution
4322: @c to encipher or decipher
4323: @c 4. as above but work on a file for in and out
4324: @c 5. take input line and convert to pig-latin
4325: @c
4326: @c thing of sets of things to exercise then come up with
4327: @c problems that need those things.
4328:
4329:
1.26 crook 4330: @c ******************************************************************
1.29 crook 4331: @node Words, Error messages, Introduction, Top
1.1 anton 4332: @chapter Forth Words
1.26 crook 4333: @cindex words
1.1 anton 4334:
4335: @menu
4336: * Notation::
1.65 anton 4337: * Case insensitivity::
4338: * Comments::
4339: * Boolean Flags::
1.1 anton 4340: * Arithmetic::
4341: * Stack Manipulation::
1.5 anton 4342: * Memory::
1.1 anton 4343: * Control Structures::
4344: * Defining Words::
1.65 anton 4345: * Interpretation and Compilation Semantics::
1.47 crook 4346: * Tokens for Words::
1.81 anton 4347: * Compiling words::
1.65 anton 4348: * The Text Interpreter::
1.111 anton 4349: * The Input Stream::
1.65 anton 4350: * Word Lists::
4351: * Environmental Queries::
1.12 anton 4352: * Files::
4353: * Blocks::
4354: * Other I/O::
1.121 anton 4355: * OS command line arguments::
1.78 anton 4356: * Locals::
4357: * Structures::
4358: * Object-oriented Forth::
1.12 anton 4359: * Programming Tools::
1.150 anton 4360: * C Interface::
1.12 anton 4361: * Assembler and Code Words::
4362: * Threading Words::
1.65 anton 4363: * Passing Commands to the OS::
4364: * Keeping track of Time::
4365: * Miscellaneous Words::
1.1 anton 4366: @end menu
4367:
1.65 anton 4368: @node Notation, Case insensitivity, Words, Words
1.1 anton 4369: @section Notation
4370: @cindex notation of glossary entries
4371: @cindex format of glossary entries
4372: @cindex glossary notation format
4373: @cindex word glossary entry format
4374:
4375: The Forth words are described in this section in the glossary notation
1.67 anton 4376: that has become a de-facto standard for Forth texts:
1.1 anton 4377:
4378: @format
1.29 crook 4379: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4380: @end format
1.29 crook 4381: @i{Description}
1.1 anton 4382:
4383: @table @var
4384: @item word
1.28 crook 4385: The name of the word.
1.1 anton 4386:
4387: @item Stack effect
4388: @cindex stack effect
1.29 crook 4389: The stack effect is written in the notation @code{@i{before} --
4390: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4391: stack entries before and after the execution of the word. The rest of
4392: the stack is not touched by the word. The top of stack is rightmost,
4393: i.e., a stack sequence is written as it is typed in. Note that Gforth
4394: uses a separate floating point stack, but a unified stack
1.29 crook 4395: notation. Also, return stack effects are not shown in @i{stack
4396: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4397: the type and/or the function of the item. See below for a discussion of
4398: the types.
4399:
4400: All words have two stack effects: A compile-time stack effect and a
4401: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4402: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4403: this standard behaviour, or the word does other unusual things at
4404: compile time, both stack effects are shown; otherwise only the run-time
4405: stack effect is shown.
4406:
4407: @cindex pronounciation of words
4408: @item pronunciation
4409: How the word is pronounced.
4410:
4411: @cindex wordset
1.67 anton 4412: @cindex environment wordset
1.1 anton 4413: @item wordset
1.21 crook 4414: The ANS Forth standard is divided into several word sets. A standard
4415: system need not support all of them. Therefore, in theory, the fewer
4416: word sets your program uses the more portable it will be. However, we
4417: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4418: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4419: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4420: describes words that will work in future releases of Gforth;
4421: @code{gforth-internal} words are more volatile. Environmental query
4422: strings are also displayed like words; you can recognize them by the
1.21 crook 4423: @code{environment} in the word set field.
1.1 anton 4424:
4425: @item Description
4426: A description of the behaviour of the word.
4427: @end table
4428:
4429: @cindex types of stack items
4430: @cindex stack item types
4431: The type of a stack item is specified by the character(s) the name
4432: starts with:
4433:
4434: @table @code
4435: @item f
4436: @cindex @code{f}, stack item type
4437: Boolean flags, i.e. @code{false} or @code{true}.
4438: @item c
4439: @cindex @code{c}, stack item type
4440: Char
4441: @item w
4442: @cindex @code{w}, stack item type
4443: Cell, can contain an integer or an address
4444: @item n
4445: @cindex @code{n}, stack item type
4446: signed integer
4447: @item u
4448: @cindex @code{u}, stack item type
4449: unsigned integer
4450: @item d
4451: @cindex @code{d}, stack item type
4452: double sized signed integer
4453: @item ud
4454: @cindex @code{ud}, stack item type
4455: double sized unsigned integer
4456: @item r
4457: @cindex @code{r}, stack item type
4458: Float (on the FP stack)
1.21 crook 4459: @item a-
1.1 anton 4460: @cindex @code{a_}, stack item type
4461: Cell-aligned address
1.21 crook 4462: @item c-
1.1 anton 4463: @cindex @code{c_}, stack item type
4464: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4465: @item f-
1.1 anton 4466: @cindex @code{f_}, stack item type
4467: Float-aligned address
1.21 crook 4468: @item df-
1.1 anton 4469: @cindex @code{df_}, stack item type
4470: Address aligned for IEEE double precision float
1.21 crook 4471: @item sf-
1.1 anton 4472: @cindex @code{sf_}, stack item type
4473: Address aligned for IEEE single precision float
4474: @item xt
4475: @cindex @code{xt}, stack item type
4476: Execution token, same size as Cell
4477: @item wid
4478: @cindex @code{wid}, stack item type
1.21 crook 4479: Word list ID, same size as Cell
1.68 anton 4480: @item ior, wior
4481: @cindex ior type description
4482: @cindex wior type description
4483: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4484: @item f83name
4485: @cindex @code{f83name}, stack item type
4486: Pointer to a name structure
4487: @item "
4488: @cindex @code{"}, stack item type
1.12 anton 4489: string in the input stream (not on the stack). The terminating character
4490: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4491: quotes.
4492: @end table
4493:
1.65 anton 4494: @comment ----------------------------------------------
4495: @node Case insensitivity, Comments, Notation, Words
4496: @section Case insensitivity
4497: @cindex case sensitivity
4498: @cindex upper and lower case
4499:
4500: Gforth is case-insensitive; you can enter definitions and invoke
4501: Standard words using upper, lower or mixed case (however,
4502: @pxref{core-idef, Implementation-defined options, Implementation-defined
4503: options}).
4504:
4505: ANS Forth only @i{requires} implementations to recognise Standard words
4506: when they are typed entirely in upper case. Therefore, a Standard
4507: program must use upper case for all Standard words. You can use whatever
4508: case you like for words that you define, but in a Standard program you
4509: have to use the words in the same case that you defined them.
4510:
4511: Gforth supports case sensitivity through @code{table}s (case-sensitive
4512: wordlists, @pxref{Word Lists}).
4513:
4514: Two people have asked how to convert Gforth to be case-sensitive; while
4515: we think this is a bad idea, you can change all wordlists into tables
4516: like this:
4517:
4518: @example
4519: ' table-find forth-wordlist wordlist-map @ !
4520: @end example
4521:
4522: Note that you now have to type the predefined words in the same case
4523: that we defined them, which are varying. You may want to convert them
4524: to your favourite case before doing this operation (I won't explain how,
4525: because if you are even contemplating doing this, you'd better have
4526: enough knowledge of Forth systems to know this already).
4527:
4528: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4529: @section Comments
1.26 crook 4530: @cindex comments
1.21 crook 4531:
1.29 crook 4532: Forth supports two styles of comment; the traditional @i{in-line} comment,
4533: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4534:
1.44 crook 4535:
1.23 crook 4536: doc-(
1.21 crook 4537: doc-\
1.23 crook 4538: doc-\G
1.21 crook 4539:
1.44 crook 4540:
1.21 crook 4541: @node Boolean Flags, Arithmetic, Comments, Words
4542: @section Boolean Flags
1.26 crook 4543: @cindex Boolean flags
1.21 crook 4544:
4545: A Boolean flag is cell-sized. A cell with all bits clear represents the
4546: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4547: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4548: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4549: @c on and off to Memory?
4550: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4551:
1.21 crook 4552: doc-true
4553: doc-false
1.29 crook 4554: doc-on
4555: doc-off
1.21 crook 4556:
1.44 crook 4557:
1.21 crook 4558: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4559: @section Arithmetic
4560: @cindex arithmetic words
4561:
4562: @cindex division with potentially negative operands
4563: Forth arithmetic is not checked, i.e., you will not hear about integer
4564: overflow on addition or multiplication, you may hear about division by
4565: zero if you are lucky. The operator is written after the operands, but
4566: the operands are still in the original order. I.e., the infix @code{2-1}
4567: corresponds to @code{2 1 -}. Forth offers a variety of division
4568: operators. If you perform division with potentially negative operands,
4569: you do not want to use @code{/} or @code{/mod} with its undefined
4570: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4571: former, @pxref{Mixed precision}).
1.26 crook 4572: @comment TODO discuss the different division forms and the std approach
1.1 anton 4573:
4574: @menu
4575: * Single precision::
1.67 anton 4576: * Double precision:: Double-cell integer arithmetic
1.1 anton 4577: * Bitwise operations::
1.67 anton 4578: * Numeric comparison::
1.29 crook 4579: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4580: * Floating Point::
4581: @end menu
4582:
1.67 anton 4583: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4584: @subsection Single precision
4585: @cindex single precision arithmetic words
4586:
1.67 anton 4587: @c !! cell undefined
4588:
4589: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4590: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4591: treat them. For the rules used by the text interpreter for recognising
4592: single-precision integers see @ref{Number Conversion}.
1.21 crook 4593:
1.67 anton 4594: These words are all defined for signed operands, but some of them also
4595: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4596: @code{*}.
1.44 crook 4597:
1.1 anton 4598: doc-+
1.21 crook 4599: doc-1+
1.128 anton 4600: doc-under+
1.1 anton 4601: doc--
1.21 crook 4602: doc-1-
1.1 anton 4603: doc-*
4604: doc-/
4605: doc-mod
4606: doc-/mod
4607: doc-negate
4608: doc-abs
4609: doc-min
4610: doc-max
1.27 crook 4611: doc-floored
1.1 anton 4612:
1.44 crook 4613:
1.67 anton 4614: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4615: @subsection Double precision
4616: @cindex double precision arithmetic words
4617:
1.49 anton 4618: For the rules used by the text interpreter for
4619: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4620:
4621: A double precision number is represented by a cell pair, with the most
1.67 anton 4622: significant cell at the TOS. It is trivial to convert an unsigned single
4623: to a double: simply push a @code{0} onto the TOS. Since numbers are
4624: represented by Gforth using 2's complement arithmetic, converting a
4625: signed single to a (signed) double requires sign-extension across the
4626: most significant cell. This can be achieved using @code{s>d}. The moral
4627: of the story is that you cannot convert a number without knowing whether
4628: it represents an unsigned or a signed number.
1.21 crook 4629:
1.67 anton 4630: These words are all defined for signed operands, but some of them also
4631: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4632:
1.21 crook 4633: doc-s>d
1.67 anton 4634: doc-d>s
1.21 crook 4635: doc-d+
4636: doc-d-
4637: doc-dnegate
4638: doc-dabs
4639: doc-dmin
4640: doc-dmax
4641:
1.44 crook 4642:
1.67 anton 4643: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4644: @subsection Bitwise operations
4645: @cindex bitwise operation words
4646:
4647:
4648: doc-and
4649: doc-or
4650: doc-xor
4651: doc-invert
4652: doc-lshift
4653: doc-rshift
4654: doc-2*
4655: doc-d2*
4656: doc-2/
4657: doc-d2/
4658:
4659:
4660: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4661: @subsection Numeric comparison
4662: @cindex numeric comparison words
4663:
1.67 anton 4664: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4665: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4666:
1.28 crook 4667: doc-<
4668: doc-<=
4669: doc-<>
4670: doc-=
4671: doc->
4672: doc->=
4673:
1.21 crook 4674: doc-0<
1.23 crook 4675: doc-0<=
1.21 crook 4676: doc-0<>
4677: doc-0=
1.23 crook 4678: doc-0>
4679: doc-0>=
1.28 crook 4680:
4681: doc-u<
4682: doc-u<=
1.44 crook 4683: @c u<> and u= exist but are the same as <> and =
1.31 anton 4684: @c doc-u<>
4685: @c doc-u=
1.28 crook 4686: doc-u>
4687: doc-u>=
4688:
4689: doc-within
4690:
4691: doc-d<
4692: doc-d<=
4693: doc-d<>
4694: doc-d=
4695: doc-d>
4696: doc-d>=
1.23 crook 4697:
1.21 crook 4698: doc-d0<
1.23 crook 4699: doc-d0<=
4700: doc-d0<>
1.21 crook 4701: doc-d0=
1.23 crook 4702: doc-d0>
4703: doc-d0>=
4704:
1.21 crook 4705: doc-du<
1.28 crook 4706: doc-du<=
1.44 crook 4707: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4708: @c doc-du<>
4709: @c doc-du=
1.28 crook 4710: doc-du>
4711: doc-du>=
1.1 anton 4712:
1.44 crook 4713:
1.21 crook 4714: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4715: @subsection Mixed precision
4716: @cindex mixed precision arithmetic words
4717:
1.44 crook 4718:
1.1 anton 4719: doc-m+
4720: doc-*/
4721: doc-*/mod
4722: doc-m*
4723: doc-um*
4724: doc-m*/
4725: doc-um/mod
4726: doc-fm/mod
4727: doc-sm/rem
4728:
1.44 crook 4729:
1.21 crook 4730: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4731: @subsection Floating Point
4732: @cindex floating point arithmetic words
4733:
1.49 anton 4734: For the rules used by the text interpreter for
4735: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4736:
1.67 anton 4737: Gforth has a separate floating point stack, but the documentation uses
4738: the unified notation.@footnote{It's easy to generate the separate
4739: notation from that by just separating the floating-point numbers out:
4740: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4741: r3 )}.}
1.1 anton 4742:
4743: @cindex floating-point arithmetic, pitfalls
4744: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4745: unwary (e.g., floating point addition is not associative) and even a
4746: few for the wary. You should not use them unless you know what you are
4747: doing or you don't care that the results you get are totally bogus. If
4748: you want to learn about the problems of floating point numbers (and
4749: how to avoid them), you might start with @cite{David Goldberg,
4750: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4751: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4752: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4753:
1.44 crook 4754:
1.21 crook 4755: doc-d>f
4756: doc-f>d
1.1 anton 4757: doc-f+
4758: doc-f-
4759: doc-f*
4760: doc-f/
4761: doc-fnegate
4762: doc-fabs
4763: doc-fmax
4764: doc-fmin
4765: doc-floor
4766: doc-fround
4767: doc-f**
4768: doc-fsqrt
4769: doc-fexp
4770: doc-fexpm1
4771: doc-fln
4772: doc-flnp1
4773: doc-flog
4774: doc-falog
1.32 anton 4775: doc-f2*
4776: doc-f2/
4777: doc-1/f
4778: doc-precision
4779: doc-set-precision
4780:
4781: @cindex angles in trigonometric operations
4782: @cindex trigonometric operations
4783: Angles in floating point operations are given in radians (a full circle
4784: has 2 pi radians).
4785:
1.1 anton 4786: doc-fsin
4787: doc-fcos
4788: doc-fsincos
4789: doc-ftan
4790: doc-fasin
4791: doc-facos
4792: doc-fatan
4793: doc-fatan2
4794: doc-fsinh
4795: doc-fcosh
4796: doc-ftanh
4797: doc-fasinh
4798: doc-facosh
4799: doc-fatanh
1.21 crook 4800: doc-pi
1.28 crook 4801:
1.32 anton 4802: @cindex equality of floats
4803: @cindex floating-point comparisons
1.31 anton 4804: One particular problem with floating-point arithmetic is that comparison
4805: for equality often fails when you would expect it to succeed. For this
4806: reason approximate equality is often preferred (but you still have to
1.67 anton 4807: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4808: differently from what you might expect. The comparison words are:
1.31 anton 4809:
4810: doc-f~rel
4811: doc-f~abs
1.68 anton 4812: doc-f~
1.31 anton 4813: doc-f=
4814: doc-f<>
4815:
4816: doc-f<
4817: doc-f<=
4818: doc-f>
4819: doc-f>=
4820:
1.21 crook 4821: doc-f0<
1.28 crook 4822: doc-f0<=
4823: doc-f0<>
1.21 crook 4824: doc-f0=
1.28 crook 4825: doc-f0>
4826: doc-f0>=
4827:
1.1 anton 4828:
4829: @node Stack Manipulation, Memory, Arithmetic, Words
4830: @section Stack Manipulation
4831: @cindex stack manipulation words
4832:
4833: @cindex floating-point stack in the standard
1.21 crook 4834: Gforth maintains a number of separate stacks:
4835:
1.29 crook 4836: @cindex data stack
4837: @cindex parameter stack
1.21 crook 4838: @itemize @bullet
4839: @item
1.29 crook 4840: A data stack (also known as the @dfn{parameter stack}) -- for
4841: characters, cells, addresses, and double cells.
1.21 crook 4842:
1.29 crook 4843: @cindex floating-point stack
1.21 crook 4844: @item
1.44 crook 4845: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4846:
1.29 crook 4847: @cindex return stack
1.21 crook 4848: @item
1.44 crook 4849: A return stack -- for holding the return addresses of colon
1.32 anton 4850: definitions and other (non-FP) data.
1.21 crook 4851:
1.29 crook 4852: @cindex locals stack
1.21 crook 4853: @item
1.44 crook 4854: A locals stack -- for holding local variables.
1.21 crook 4855: @end itemize
4856:
1.1 anton 4857: @menu
4858: * Data stack::
4859: * Floating point stack::
4860: * Return stack::
4861: * Locals stack::
4862: * Stack pointer manipulation::
4863: @end menu
4864:
4865: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4866: @subsection Data stack
4867: @cindex data stack manipulation words
4868: @cindex stack manipulations words, data stack
4869:
1.44 crook 4870:
1.1 anton 4871: doc-drop
4872: doc-nip
4873: doc-dup
4874: doc-over
4875: doc-tuck
4876: doc-swap
1.21 crook 4877: doc-pick
1.1 anton 4878: doc-rot
4879: doc--rot
4880: doc-?dup
4881: doc-roll
4882: doc-2drop
4883: doc-2nip
4884: doc-2dup
4885: doc-2over
4886: doc-2tuck
4887: doc-2swap
4888: doc-2rot
4889:
1.44 crook 4890:
1.1 anton 4891: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4892: @subsection Floating point stack
4893: @cindex floating-point stack manipulation words
4894: @cindex stack manipulation words, floating-point stack
4895:
1.32 anton 4896: Whilst every sane Forth has a separate floating-point stack, it is not
4897: strictly required; an ANS Forth system could theoretically keep
4898: floating-point numbers on the data stack. As an additional difficulty,
4899: you don't know how many cells a floating-point number takes. It is
4900: reportedly possible to write words in a way that they work also for a
4901: unified stack model, but we do not recommend trying it. Instead, just
4902: say that your program has an environmental dependency on a separate
4903: floating-point stack.
4904:
4905: doc-floating-stack
4906:
1.1 anton 4907: doc-fdrop
4908: doc-fnip
4909: doc-fdup
4910: doc-fover
4911: doc-ftuck
4912: doc-fswap
1.21 crook 4913: doc-fpick
1.1 anton 4914: doc-frot
4915:
1.44 crook 4916:
1.1 anton 4917: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4918: @subsection Return stack
4919: @cindex return stack manipulation words
4920: @cindex stack manipulation words, return stack
4921:
1.32 anton 4922: @cindex return stack and locals
4923: @cindex locals and return stack
4924: A Forth system is allowed to keep local variables on the
4925: return stack. This is reasonable, as local variables usually eliminate
4926: the need to use the return stack explicitly. So, if you want to produce
4927: a standard compliant program and you are using local variables in a
4928: word, forget about return stack manipulations in that word (refer to the
4929: standard document for the exact rules).
4930:
1.1 anton 4931: doc->r
4932: doc-r>
4933: doc-r@
4934: doc-rdrop
4935: doc-2>r
4936: doc-2r>
4937: doc-2r@
4938: doc-2rdrop
4939:
1.44 crook 4940:
1.1 anton 4941: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4942: @subsection Locals stack
4943:
1.78 anton 4944: Gforth uses an extra locals stack. It is described, along with the
4945: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4946:
1.1 anton 4947: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4948: @subsection Stack pointer manipulation
4949: @cindex stack pointer manipulation words
4950:
1.44 crook 4951: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4952: doc-sp0
1.1 anton 4953: doc-sp@
4954: doc-sp!
1.21 crook 4955: doc-fp0
1.1 anton 4956: doc-fp@
4957: doc-fp!
1.21 crook 4958: doc-rp0
1.1 anton 4959: doc-rp@
4960: doc-rp!
1.21 crook 4961: doc-lp0
1.1 anton 4962: doc-lp@
4963: doc-lp!
4964:
1.44 crook 4965:
1.1 anton 4966: @node Memory, Control Structures, Stack Manipulation, Words
4967: @section Memory
1.26 crook 4968: @cindex memory words
1.1 anton 4969:
1.32 anton 4970: @menu
4971: * Memory model::
4972: * Dictionary allocation::
4973: * Heap Allocation::
4974: * Memory Access::
4975: * Address arithmetic::
4976: * Memory Blocks::
4977: @end menu
4978:
1.67 anton 4979: In addition to the standard Forth memory allocation words, there is also
4980: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
4981: garbage collector}.
4982:
1.32 anton 4983: @node Memory model, Dictionary allocation, Memory, Memory
4984: @subsection ANS Forth and Gforth memory models
4985:
4986: @c The ANS Forth description is a mess (e.g., is the heap part of
4987: @c the dictionary?), so let's not stick to closely with it.
4988:
1.67 anton 4989: ANS Forth considers a Forth system as consisting of several address
4990: spaces, of which only @dfn{data space} is managed and accessible with
4991: the memory words. Memory not necessarily in data space includes the
4992: stacks, the code (called code space) and the headers (called name
4993: space). In Gforth everything is in data space, but the code for the
4994: primitives is usually read-only.
1.32 anton 4995:
4996: Data space is divided into a number of areas: The (data space portion of
4997: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
4998: refer to the search data structure embodied in word lists and headers,
4999: because it is used for looking up names, just as you would in a
5000: conventional dictionary.}, the heap, and a number of system-allocated
5001: buffers.
5002:
1.68 anton 5003: @cindex address arithmetic restrictions, ANS vs. Gforth
5004: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5005: In ANS Forth data space is also divided into contiguous regions. You
5006: can only use address arithmetic within a contiguous region, not between
5007: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5008: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5009: allocation}).
5010:
5011: Gforth provides one big address space, and address arithmetic can be
5012: performed between any addresses. However, in the dictionary headers or
5013: code are interleaved with data, so almost the only contiguous data space
5014: regions there are those described by ANS Forth as contiguous; but you
5015: can be sure that the dictionary is allocated towards increasing
5016: addresses even between contiguous regions. The memory order of
5017: allocations in the heap is platform-dependent (and possibly different
5018: from one run to the next).
5019:
1.27 crook 5020:
1.32 anton 5021: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5022: @subsection Dictionary allocation
1.27 crook 5023: @cindex reserving data space
5024: @cindex data space - reserving some
5025:
1.32 anton 5026: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5027: you want to deallocate X, you also deallocate everything
5028: allocated after X.
5029:
1.68 anton 5030: @cindex contiguous regions in dictionary allocation
1.32 anton 5031: The allocations using the words below are contiguous and grow the region
5032: towards increasing addresses. Other words that allocate dictionary
5033: memory of any kind (i.e., defining words including @code{:noname}) end
5034: the contiguous region and start a new one.
5035:
5036: In ANS Forth only @code{create}d words are guaranteed to produce an
5037: address that is the start of the following contiguous region. In
5038: particular, the cell allocated by @code{variable} is not guaranteed to
5039: be contiguous with following @code{allot}ed memory.
5040:
5041: You can deallocate memory by using @code{allot} with a negative argument
5042: (with some restrictions, see @code{allot}). For larger deallocations use
5043: @code{marker}.
1.27 crook 5044:
1.29 crook 5045:
1.27 crook 5046: doc-here
5047: doc-unused
5048: doc-allot
5049: doc-c,
1.29 crook 5050: doc-f,
1.27 crook 5051: doc-,
5052: doc-2,
5053:
1.32 anton 5054: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5055: course you should allocate memory in an aligned way, too. I.e., before
5056: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5057: The words below align @code{here} if it is not already. Basically it is
5058: only already aligned for a type, if the last allocation was a multiple
5059: of the size of this type and if @code{here} was aligned for this type
5060: before.
5061:
5062: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5063: ANS Forth (@code{maxalign}ed in Gforth).
5064:
5065: doc-align
5066: doc-falign
5067: doc-sfalign
5068: doc-dfalign
5069: doc-maxalign
5070: doc-cfalign
5071:
5072:
5073: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5074: @subsection Heap allocation
5075: @cindex heap allocation
5076: @cindex dynamic allocation of memory
5077: @cindex memory-allocation word set
5078:
1.68 anton 5079: @cindex contiguous regions and heap allocation
1.32 anton 5080: Heap allocation supports deallocation of allocated memory in any
5081: order. Dictionary allocation is not affected by it (i.e., it does not
5082: end a contiguous region). In Gforth, these words are implemented using
5083: the standard C library calls malloc(), free() and resize().
5084:
1.68 anton 5085: The memory region produced by one invocation of @code{allocate} or
5086: @code{resize} is internally contiguous. There is no contiguity between
5087: such a region and any other region (including others allocated from the
5088: heap).
5089:
1.32 anton 5090: doc-allocate
5091: doc-free
5092: doc-resize
5093:
1.27 crook 5094:
1.32 anton 5095: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5096: @subsection Memory Access
5097: @cindex memory access words
5098:
5099: doc-@
5100: doc-!
5101: doc-+!
5102: doc-c@
5103: doc-c!
5104: doc-2@
5105: doc-2!
5106: doc-f@
5107: doc-f!
5108: doc-sf@
5109: doc-sf!
5110: doc-df@
5111: doc-df!
1.144 anton 5112: doc-sw@
5113: doc-uw@
5114: doc-w!
5115: doc-sl@
5116: doc-ul@
5117: doc-l!
1.68 anton 5118:
1.32 anton 5119: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5120: @subsection Address arithmetic
1.1 anton 5121: @cindex address arithmetic words
5122:
1.67 anton 5123: Address arithmetic is the foundation on which you can build data
5124: structures like arrays, records (@pxref{Structures}) and objects
5125: (@pxref{Object-oriented Forth}).
1.32 anton 5126:
1.68 anton 5127: @cindex address unit
5128: @cindex au (address unit)
1.1 anton 5129: ANS Forth does not specify the sizes of the data types. Instead, it
5130: offers a number of words for computing sizes and doing address
1.29 crook 5131: arithmetic. Address arithmetic is performed in terms of address units
5132: (aus); on most systems the address unit is one byte. Note that a
5133: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5134: platforms where it is a noop, it compiles to nothing).
1.1 anton 5135:
1.67 anton 5136: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5137: you have the address of a cell, perform @code{1 cells +}, and you will
5138: have the address of the next cell.
5139:
1.68 anton 5140: @cindex contiguous regions and address arithmetic
1.67 anton 5141: In ANS Forth you can perform address arithmetic only within a contiguous
5142: region, i.e., if you have an address into one region, you can only add
5143: and subtract such that the result is still within the region; you can
5144: only subtract or compare addresses from within the same contiguous
5145: region. Reasons: several contiguous regions can be arranged in memory
5146: in any way; on segmented systems addresses may have unusual
5147: representations, such that address arithmetic only works within a
5148: region. Gforth provides a few more guarantees (linear address space,
5149: dictionary grows upwards), but in general I have found it easy to stay
5150: within contiguous regions (exception: computing and comparing to the
5151: address just beyond the end of an array).
5152:
1.1 anton 5153: @cindex alignment of addresses for types
5154: ANS Forth also defines words for aligning addresses for specific
5155: types. Many computers require that accesses to specific data types
5156: must only occur at specific addresses; e.g., that cells may only be
5157: accessed at addresses divisible by 4. Even if a machine allows unaligned
5158: accesses, it can usually perform aligned accesses faster.
5159:
5160: For the performance-conscious: alignment operations are usually only
5161: necessary during the definition of a data structure, not during the
5162: (more frequent) accesses to it.
5163:
5164: ANS Forth defines no words for character-aligning addresses. This is not
5165: an oversight, but reflects the fact that addresses that are not
5166: char-aligned have no use in the standard and therefore will not be
5167: created.
5168:
5169: @cindex @code{CREATE} and alignment
1.29 crook 5170: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5171: are cell-aligned; in addition, Gforth guarantees that these addresses
5172: are aligned for all purposes.
5173:
1.26 crook 5174: Note that the ANS Forth word @code{char} has nothing to do with address
5175: arithmetic.
1.1 anton 5176:
1.44 crook 5177:
1.1 anton 5178: doc-chars
5179: doc-char+
5180: doc-cells
5181: doc-cell+
5182: doc-cell
5183: doc-aligned
5184: doc-floats
5185: doc-float+
5186: doc-float
5187: doc-faligned
5188: doc-sfloats
5189: doc-sfloat+
5190: doc-sfaligned
5191: doc-dfloats
5192: doc-dfloat+
5193: doc-dfaligned
5194: doc-maxaligned
5195: doc-cfaligned
5196: doc-address-unit-bits
1.145 anton 5197: doc-/w
5198: doc-/l
1.44 crook 5199:
1.32 anton 5200: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5201: @subsection Memory Blocks
5202: @cindex memory block words
1.27 crook 5203: @cindex character strings - moving and copying
5204:
1.49 anton 5205: Memory blocks often represent character strings; For ways of storing
5206: character strings in memory see @ref{String Formats}. For other
5207: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5208:
1.67 anton 5209: A few of these words work on address unit blocks. In that case, you
5210: usually have to insert @code{CHARS} before the word when working on
5211: character strings. Most words work on character blocks, and expect a
5212: char-aligned address.
5213:
5214: When copying characters between overlapping memory regions, use
5215: @code{chars move} or choose carefully between @code{cmove} and
5216: @code{cmove>}.
1.44 crook 5217:
1.1 anton 5218: doc-move
5219: doc-erase
5220: doc-cmove
5221: doc-cmove>
5222: doc-fill
5223: doc-blank
1.21 crook 5224: doc-compare
1.111 anton 5225: doc-str=
5226: doc-str<
5227: doc-string-prefix?
1.21 crook 5228: doc-search
1.27 crook 5229: doc--trailing
5230: doc-/string
1.82 anton 5231: doc-bounds
1.141 anton 5232: doc-pad
1.111 anton 5233:
1.27 crook 5234: @comment TODO examples
5235:
1.1 anton 5236:
1.26 crook 5237: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5238: @section Control Structures
5239: @cindex control structures
5240:
1.33 anton 5241: Control structures in Forth cannot be used interpretively, only in a
5242: colon definition@footnote{To be precise, they have no interpretation
5243: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5244: not like this limitation, but have not seen a satisfying way around it
5245: yet, although many schemes have been proposed.
1.1 anton 5246:
5247: @menu
1.33 anton 5248: * Selection:: IF ... ELSE ... ENDIF
5249: * Simple Loops:: BEGIN ...
1.29 crook 5250: * Counted Loops:: DO
1.67 anton 5251: * Arbitrary control structures::
5252: * Calls and returns::
1.1 anton 5253: * Exception Handling::
5254: @end menu
5255:
5256: @node Selection, Simple Loops, Control Structures, Control Structures
5257: @subsection Selection
5258: @cindex selection control structures
5259: @cindex control structures for selection
5260:
5261: @cindex @code{IF} control structure
5262: @example
1.29 crook 5263: @i{flag}
1.1 anton 5264: IF
1.29 crook 5265: @i{code}
1.1 anton 5266: ENDIF
5267: @end example
1.21 crook 5268: @noindent
1.33 anton 5269:
1.44 crook 5270: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5271: with any bit set represents truth) @i{code} is executed.
1.33 anton 5272:
1.1 anton 5273: @example
1.29 crook 5274: @i{flag}
1.1 anton 5275: IF
1.29 crook 5276: @i{code1}
1.1 anton 5277: ELSE
1.29 crook 5278: @i{code2}
1.1 anton 5279: ENDIF
5280: @end example
5281:
1.44 crook 5282: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5283: executed.
1.33 anton 5284:
1.1 anton 5285: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5286: standard, and @code{ENDIF} is not, although it is quite popular. We
5287: recommend using @code{ENDIF}, because it is less confusing for people
5288: who also know other languages (and is not prone to reinforcing negative
5289: prejudices against Forth in these people). Adding @code{ENDIF} to a
5290: system that only supplies @code{THEN} is simple:
5291: @example
1.82 anton 5292: : ENDIF POSTPONE then ; immediate
1.1 anton 5293: @end example
5294:
5295: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5296: (adv.)} has the following meanings:
5297: @quotation
5298: ... 2b: following next after in order ... 3d: as a necessary consequence
5299: (if you were there, then you saw them).
5300: @end quotation
5301: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5302: and many other programming languages has the meaning 3d.]
5303:
1.21 crook 5304: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5305: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5306: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5307: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5308: @file{compat/control.fs}.
5309:
5310: @cindex @code{CASE} control structure
5311: @example
1.29 crook 5312: @i{n}
1.1 anton 5313: CASE
1.29 crook 5314: @i{n1} OF @i{code1} ENDOF
5315: @i{n2} OF @i{code2} ENDOF
1.1 anton 5316: @dots{}
1.68 anton 5317: ( n ) @i{default-code} ( n )
1.131 anton 5318: ENDCASE ( )
1.1 anton 5319: @end example
5320:
1.131 anton 5321: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5322: no @i{ni} matches, the optional @i{default-code} is executed. The
5323: optional default case can be added by simply writing the code after
5324: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5325: but must not consume it. The value @i{n} is consumed by this
5326: construction (either by a OF that matches, or by the ENDCASE, if no OF
5327: matches).
1.1 anton 5328:
1.69 anton 5329: @progstyle
1.131 anton 5330: To keep the code understandable, you should ensure that you change the
5331: stack in the same way (wrt. number and types of stack items consumed
5332: and pushed) on all paths through a selection construct.
1.69 anton 5333:
1.1 anton 5334: @node Simple Loops, Counted Loops, Selection, Control Structures
5335: @subsection Simple Loops
5336: @cindex simple loops
5337: @cindex loops without count
5338:
5339: @cindex @code{WHILE} loop
5340: @example
5341: BEGIN
1.29 crook 5342: @i{code1}
5343: @i{flag}
1.1 anton 5344: WHILE
1.29 crook 5345: @i{code2}
1.1 anton 5346: REPEAT
5347: @end example
5348:
1.29 crook 5349: @i{code1} is executed and @i{flag} is computed. If it is true,
5350: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5351: false, execution continues after the @code{REPEAT}.
5352:
5353: @cindex @code{UNTIL} loop
5354: @example
5355: BEGIN
1.29 crook 5356: @i{code}
5357: @i{flag}
1.1 anton 5358: UNTIL
5359: @end example
5360:
1.29 crook 5361: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5362:
1.69 anton 5363: @progstyle
5364: To keep the code understandable, a complete iteration of the loop should
5365: not change the number and types of the items on the stacks.
5366:
1.1 anton 5367: @cindex endless loop
5368: @cindex loops, endless
5369: @example
5370: BEGIN
1.29 crook 5371: @i{code}
1.1 anton 5372: AGAIN
5373: @end example
5374:
5375: This is an endless loop.
5376:
5377: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5378: @subsection Counted Loops
5379: @cindex counted loops
5380: @cindex loops, counted
5381: @cindex @code{DO} loops
5382:
5383: The basic counted loop is:
5384: @example
1.29 crook 5385: @i{limit} @i{start}
1.1 anton 5386: ?DO
1.29 crook 5387: @i{body}
1.1 anton 5388: LOOP
5389: @end example
5390:
1.29 crook 5391: This performs one iteration for every integer, starting from @i{start}
5392: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5393: accessed with @code{i}. For example, the loop:
1.1 anton 5394: @example
5395: 10 0 ?DO
5396: i .
5397: LOOP
5398: @end example
1.21 crook 5399: @noindent
5400: prints @code{0 1 2 3 4 5 6 7 8 9}
5401:
1.1 anton 5402: The index of the innermost loop can be accessed with @code{i}, the index
5403: of the next loop with @code{j}, and the index of the third loop with
5404: @code{k}.
5405:
1.44 crook 5406:
1.1 anton 5407: doc-i
5408: doc-j
5409: doc-k
5410:
1.44 crook 5411:
1.1 anton 5412: The loop control data are kept on the return stack, so there are some
1.21 crook 5413: restrictions on mixing return stack accesses and counted loop words. In
5414: particuler, if you put values on the return stack outside the loop, you
5415: cannot read them inside the loop@footnote{well, not in a way that is
5416: portable.}. If you put values on the return stack within a loop, you
5417: have to remove them before the end of the loop and before accessing the
5418: index of the loop.
1.1 anton 5419:
5420: There are several variations on the counted loop:
5421:
1.21 crook 5422: @itemize @bullet
5423: @item
5424: @code{LEAVE} leaves the innermost counted loop immediately; execution
5425: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5426:
5427: @example
5428: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5429: @end example
5430: prints @code{0 1 2 3}
5431:
1.1 anton 5432:
1.21 crook 5433: @item
5434: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5435: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5436: return stack so @code{EXIT} can get to its return address. For example:
5437:
5438: @example
5439: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5440: @end example
5441: prints @code{0 1 2 3}
5442:
5443:
5444: @item
1.29 crook 5445: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5446: (and @code{LOOP} iterates until they become equal by wrap-around
5447: arithmetic). This behaviour is usually not what you want. Therefore,
5448: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5449: @code{?DO}), which do not enter the loop if @i{start} is greater than
5450: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5451: unsigned loop parameters.
5452:
1.21 crook 5453: @item
5454: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5455: the loop, independent of the loop parameters. Do not use @code{DO}, even
5456: if you know that the loop is entered in any case. Such knowledge tends
5457: to become invalid during maintenance of a program, and then the
5458: @code{DO} will make trouble.
5459:
5460: @item
1.29 crook 5461: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5462: index by @i{n} instead of by 1. The loop is terminated when the border
5463: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5464:
1.21 crook 5465: @example
5466: 4 0 +DO i . 2 +LOOP
5467: @end example
5468: @noindent
5469: prints @code{0 2}
5470:
5471: @example
5472: 4 1 +DO i . 2 +LOOP
5473: @end example
5474: @noindent
5475: prints @code{1 3}
1.1 anton 5476:
1.68 anton 5477: @item
1.1 anton 5478: @cindex negative increment for counted loops
5479: @cindex counted loops with negative increment
1.29 crook 5480: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5481:
1.21 crook 5482: @example
5483: -1 0 ?DO i . -1 +LOOP
5484: @end example
5485: @noindent
5486: prints @code{0 -1}
1.1 anton 5487:
1.21 crook 5488: @example
5489: 0 0 ?DO i . -1 +LOOP
5490: @end example
5491: prints nothing.
1.1 anton 5492:
1.29 crook 5493: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5494: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5495: index by @i{u} each iteration. The loop is terminated when the border
5496: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5497: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5498:
1.21 crook 5499: @example
5500: -2 0 -DO i . 1 -LOOP
5501: @end example
5502: @noindent
5503: prints @code{0 -1}
1.1 anton 5504:
1.21 crook 5505: @example
5506: -1 0 -DO i . 1 -LOOP
5507: @end example
5508: @noindent
5509: prints @code{0}
5510:
5511: @example
5512: 0 0 -DO i . 1 -LOOP
5513: @end example
5514: @noindent
5515: prints nothing.
1.1 anton 5516:
1.21 crook 5517: @end itemize
1.1 anton 5518:
5519: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5520: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5521: for these words that uses only standard words is provided in
5522: @file{compat/loops.fs}.
1.1 anton 5523:
5524:
5525: @cindex @code{FOR} loops
1.26 crook 5526: Another counted loop is:
1.1 anton 5527: @example
1.29 crook 5528: @i{n}
1.1 anton 5529: FOR
1.29 crook 5530: @i{body}
1.1 anton 5531: NEXT
5532: @end example
5533: This is the preferred loop of native code compiler writers who are too
1.26 crook 5534: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5535: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5536: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5537: Forth systems may behave differently, even if they support @code{FOR}
5538: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5539:
5540: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5541: @subsection Arbitrary control structures
5542: @cindex control structures, user-defined
5543:
5544: @cindex control-flow stack
5545: ANS Forth permits and supports using control structures in a non-nested
5546: way. Information about incomplete control structures is stored on the
5547: control-flow stack. This stack may be implemented on the Forth data
5548: stack, and this is what we have done in Gforth.
5549:
5550: @cindex @code{orig}, control-flow stack item
5551: @cindex @code{dest}, control-flow stack item
5552: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5553: entry represents a backward branch target. A few words are the basis for
5554: building any control structure possible (except control structures that
5555: need storage, like calls, coroutines, and backtracking).
5556:
1.44 crook 5557:
1.1 anton 5558: doc-if
5559: doc-ahead
5560: doc-then
5561: doc-begin
5562: doc-until
5563: doc-again
5564: doc-cs-pick
5565: doc-cs-roll
5566:
1.44 crook 5567:
1.21 crook 5568: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5569: manipulate the control-flow stack in a portable way. Without them, you
5570: would need to know how many stack items are occupied by a control-flow
5571: entry (many systems use one cell. In Gforth they currently take three,
5572: but this may change in the future).
5573:
1.1 anton 5574: Some standard control structure words are built from these words:
5575:
1.44 crook 5576:
1.1 anton 5577: doc-else
5578: doc-while
5579: doc-repeat
5580:
1.44 crook 5581:
5582: @noindent
1.1 anton 5583: Gforth adds some more control-structure words:
5584:
1.44 crook 5585:
1.1 anton 5586: doc-endif
5587: doc-?dup-if
5588: doc-?dup-0=-if
5589:
1.44 crook 5590:
5591: @noindent
1.1 anton 5592: Counted loop words constitute a separate group of words:
5593:
1.44 crook 5594:
1.1 anton 5595: doc-?do
5596: doc-+do
5597: doc-u+do
5598: doc--do
5599: doc-u-do
5600: doc-do
5601: doc-for
5602: doc-loop
5603: doc-+loop
5604: doc--loop
5605: doc-next
5606: doc-leave
5607: doc-?leave
5608: doc-unloop
5609: doc-done
5610:
1.44 crook 5611:
1.21 crook 5612: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5613: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5614: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5615: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5616: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5617: resolved (by using one of the loop-ending words or @code{DONE}).
5618:
1.44 crook 5619: @noindent
1.26 crook 5620: Another group of control structure words are:
1.1 anton 5621:
1.44 crook 5622:
1.1 anton 5623: doc-case
5624: doc-endcase
5625: doc-of
5626: doc-endof
5627:
1.44 crook 5628:
1.21 crook 5629: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5630: @code{CS-ROLL}.
1.1 anton 5631:
5632: @subsubsection Programming Style
1.47 crook 5633: @cindex control structures programming style
5634: @cindex programming style, arbitrary control structures
1.1 anton 5635:
5636: In order to ensure readability we recommend that you do not create
5637: arbitrary control structures directly, but define new control structure
5638: words for the control structure you want and use these words in your
1.26 crook 5639: program. For example, instead of writing:
1.1 anton 5640:
5641: @example
1.26 crook 5642: BEGIN
1.1 anton 5643: ...
1.26 crook 5644: IF [ 1 CS-ROLL ]
1.1 anton 5645: ...
1.26 crook 5646: AGAIN THEN
1.1 anton 5647: @end example
5648:
1.21 crook 5649: @noindent
1.1 anton 5650: we recommend defining control structure words, e.g.,
5651:
5652: @example
1.26 crook 5653: : WHILE ( DEST -- ORIG DEST )
5654: POSTPONE IF
5655: 1 CS-ROLL ; immediate
5656:
5657: : REPEAT ( orig dest -- )
5658: POSTPONE AGAIN
5659: POSTPONE THEN ; immediate
1.1 anton 5660: @end example
5661:
1.21 crook 5662: @noindent
1.1 anton 5663: and then using these to create the control structure:
5664:
5665: @example
1.26 crook 5666: BEGIN
1.1 anton 5667: ...
1.26 crook 5668: WHILE
1.1 anton 5669: ...
1.26 crook 5670: REPEAT
1.1 anton 5671: @end example
5672:
5673: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5674: @code{WHILE} are predefined, so in this example it would not be
5675: necessary to define them.
5676:
5677: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5678: @subsection Calls and returns
5679: @cindex calling a definition
5680: @cindex returning from a definition
5681:
1.3 anton 5682: @cindex recursive definitions
5683: A definition can be called simply be writing the name of the definition
1.26 crook 5684: to be called. Normally a definition is invisible during its own
1.3 anton 5685: definition. If you want to write a directly recursive definition, you
1.26 crook 5686: can use @code{recursive} to make the current definition visible, or
5687: @code{recurse} to call the current definition directly.
1.3 anton 5688:
1.44 crook 5689:
1.3 anton 5690: doc-recursive
5691: doc-recurse
5692:
1.44 crook 5693:
1.21 crook 5694: @comment TODO add example of the two recursion methods
1.12 anton 5695: @quotation
5696: @progstyle
5697: I prefer using @code{recursive} to @code{recurse}, because calling the
5698: definition by name is more descriptive (if the name is well-chosen) than
5699: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5700: implementation, it is much better to read (and think) ``now sort the
5701: partitions'' than to read ``now do a recursive call''.
5702: @end quotation
1.3 anton 5703:
1.29 crook 5704: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5705:
5706: @example
1.28 crook 5707: Defer foo
1.3 anton 5708:
5709: : bar ( ... -- ... )
5710: ... foo ... ;
5711:
5712: :noname ( ... -- ... )
5713: ... bar ... ;
5714: IS foo
5715: @end example
5716:
1.170 pazsan 5717: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5718:
1.26 crook 5719: The current definition returns control to the calling definition when
1.33 anton 5720: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5721:
5722: doc-exit
5723: doc-;s
5724:
1.44 crook 5725:
1.1 anton 5726: @node Exception Handling, , Calls and returns, Control Structures
5727: @subsection Exception Handling
1.26 crook 5728: @cindex exceptions
1.1 anton 5729:
1.68 anton 5730: @c quit is a very bad idea for error handling,
5731: @c because it does not translate into a THROW
5732: @c it also does not belong into this chapter
5733:
5734: If a word detects an error condition that it cannot handle, it can
5735: @code{throw} an exception. In the simplest case, this will terminate
5736: your program, and report an appropriate error.
1.21 crook 5737:
1.68 anton 5738: doc-throw
1.1 anton 5739:
1.69 anton 5740: @code{Throw} consumes a cell-sized error number on the stack. There are
5741: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5742: Gforth (and most other systems) you can use the iors produced by various
5743: words as error numbers (e.g., a typical use of @code{allocate} is
5744: @code{allocate throw}). Gforth also provides the word @code{exception}
5745: to define your own error numbers (with decent error reporting); an ANS
5746: Forth version of this word (but without the error messages) is available
5747: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5748: numbers (anything outside the range -4095..0), but won't get nice error
5749: messages, only numbers. For example, try:
5750:
5751: @example
1.69 anton 5752: -10 throw \ ANS defined
5753: -267 throw \ system defined
5754: s" my error" exception throw \ user defined
5755: 7 throw \ arbitrary number
1.68 anton 5756: @end example
5757:
5758: doc---exception-exception
1.1 anton 5759:
1.69 anton 5760: A common idiom to @code{THROW} a specific error if a flag is true is
5761: this:
5762:
5763: @example
5764: @code{( flag ) 0<> @i{errno} and throw}
5765: @end example
5766:
5767: Your program can provide exception handlers to catch exceptions. An
5768: exception handler can be used to correct the problem, or to clean up
5769: some data structures and just throw the exception to the next exception
5770: handler. Note that @code{throw} jumps to the dynamically innermost
5771: exception handler. The system's exception handler is outermost, and just
5772: prints an error and restarts command-line interpretation (or, in batch
5773: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5774:
1.68 anton 5775: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5776:
1.68 anton 5777: doc-catch
1.160 anton 5778: doc-nothrow
1.68 anton 5779:
5780: The most common use of exception handlers is to clean up the state when
5781: an error happens. E.g.,
1.1 anton 5782:
1.26 crook 5783: @example
1.68 anton 5784: base @ >r hex \ actually the hex should be inside foo, or we h
5785: ['] foo catch ( nerror|0 )
5786: r> base !
1.69 anton 5787: ( nerror|0 ) throw \ pass it on
1.26 crook 5788: @end example
1.1 anton 5789:
1.69 anton 5790: A use of @code{catch} for handling the error @code{myerror} might look
5791: like this:
1.44 crook 5792:
1.68 anton 5793: @example
1.69 anton 5794: ['] foo catch
5795: CASE
1.160 anton 5796: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5797: dup throw \ default: pass other errors on, do nothing on non-errors
5798: ENDCASE
1.68 anton 5799: @end example
1.44 crook 5800:
1.68 anton 5801: Having to wrap the code into a separate word is often cumbersome,
5802: therefore Gforth provides an alternative syntax:
1.1 anton 5803:
5804: @example
1.69 anton 5805: TRY
1.68 anton 5806: @i{code1}
1.172 anton 5807: IFERROR
5808: @i{code2}
5809: THEN
5810: @i{code3}
1.69 anton 5811: ENDTRY
1.1 anton 5812: @end example
5813:
1.172 anton 5814: This performs @i{code1}. If @i{code1} completes normally, execution
5815: continues with @i{code3}. If @i{code1} or there is an exception
5816: before @code{endtry}, the stacks are reset to the state during
5817: @code{try}, the throw value is pushed on the data stack, and execution
5818: constinues at @i{code2}, and finally falls through the @i{code3}.
1.26 crook 5819:
1.68 anton 5820: doc-try
5821: doc-endtry
1.172 anton 5822: doc-iferror
5823:
5824: If you don't need @i{code2}, you can write @code{restore} instead of
5825: @code{iferror then}:
5826:
5827: @example
5828: TRY
5829: @i{code1}
5830: RESTORE
5831: @i{code3}
5832: ENDTRY
5833: @end example
1.26 crook 5834:
1.172 anton 5835: @cindex unwind-protect
1.69 anton 5836: The cleanup example from above in this syntax:
1.26 crook 5837:
1.68 anton 5838: @example
1.174 anton 5839: base @@ @{ oldbase @}
1.172 anton 5840: TRY
1.68 anton 5841: hex foo \ now the hex is placed correctly
1.69 anton 5842: 0 \ value for throw
1.172 anton 5843: RESTORE
5844: oldbase base !
5845: ENDTRY
5846: throw
1.1 anton 5847: @end example
5848:
1.172 anton 5849: An additional advantage of this variant is that an exception between
5850: @code{restore} and @code{endtry} (e.g., from the user pressing
5851: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5852: so the base will be restored under all circumstances.
5853:
5854: However, you have to ensure that this code does not cause an exception
5855: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5856: Moreover, you should also make sure that the stack contents needed by
5857: the @code{iferror}/@code{restore} code exist everywhere between
5858: @code{try} and @code{endtry}; in our example this is achived by
5859: putting the data in a local before the @code{try} (you cannot use the
5860: return stack because the exception frame (@i{sys1}) is in the way
5861: there).
5862:
5863: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5864:
5865: @cindex @code{recover} (old Gforth versions)
5866: If you do not want this exception-restarting behaviour, you achieve
5867: this as follows:
5868:
5869: @example
5870: TRY
5871: @i{code1}
5872: ENDTRY-IFERROR
5873: @i{code2}
5874: THEN
5875: @end example
5876:
5877: If there is an exception in @i{code1}, then @i{code2} is executed,
5878: otherwise execution continues behind the @code{then} (or in a possible
5879: @code{else} branch). This corresponds to the construct
5880:
5881: @example
5882: TRY
5883: @i{code1}
5884: RECOVER
5885: @i{code2}
5886: ENDTRY
5887: @end example
5888:
5889: in Gforth before version 0.7. So you can directly replace
5890: @code{recover}-using code; however, we recommend that you check if it
5891: would not be better to use one of the other @code{try} variants while
5892: you are at it.
5893:
1.173 anton 5894: To ease the transition, Gforth provides two compatibility files:
5895: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5896: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5897: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5898: ... endtry} syntax on new systems, so you can use that file as a
5899: stopgap to run old programs. Both files work on any system (they just
5900: do nothing if the system already has the syntax it implements), so you
5901: can unconditionally @code{require} one of these files, even if you use
5902: a mix old and new systems.
5903:
1.172 anton 5904: doc-restore
5905: doc-endtry-iferror
5906:
5907: Here's the error handling example:
1.1 anton 5908:
1.68 anton 5909: @example
1.69 anton 5910: TRY
1.68 anton 5911: foo
1.172 anton 5912: ENDTRY-IFERROR
1.69 anton 5913: CASE
1.160 anton 5914: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5915: throw \ pass other errors on
5916: ENDCASE
1.172 anton 5917: THEN
1.68 anton 5918: @end example
1.1 anton 5919:
1.69 anton 5920: @progstyle
5921: As usual, you should ensure that the stack depth is statically known at
5922: the end: either after the @code{throw} for passing on errors, or after
5923: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5924: selection construct for handling the error).
5925:
1.68 anton 5926: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5927: and you can provide an error message. @code{Abort} just produces an
5928: ``Aborted'' error.
1.1 anton 5929:
1.68 anton 5930: The problem with these words is that exception handlers cannot
5931: differentiate between different @code{abort"}s; they just look like
5932: @code{-2 throw} to them (the error message cannot be accessed by
5933: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5934: exception handlers.
1.44 crook 5935:
1.68 anton 5936: doc-abort"
1.26 crook 5937: doc-abort
1.29 crook 5938:
5939:
1.44 crook 5940:
1.29 crook 5941: @c -------------------------------------------------------------
1.47 crook 5942: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5943: @section Defining Words
5944: @cindex defining words
5945:
1.47 crook 5946: Defining words are used to extend Forth by creating new entries in the dictionary.
5947:
1.29 crook 5948: @menu
1.67 anton 5949: * CREATE::
1.44 crook 5950: * Variables:: Variables and user variables
1.67 anton 5951: * Constants::
1.44 crook 5952: * Values:: Initialised variables
1.67 anton 5953: * Colon Definitions::
1.44 crook 5954: * Anonymous Definitions:: Definitions without names
1.69 anton 5955: * Supplying names:: Passing definition names as strings
1.67 anton 5956: * User-defined Defining Words::
1.170 pazsan 5957: * Deferred Words:: Allow forward references
1.67 anton 5958: * Aliases::
1.29 crook 5959: @end menu
5960:
1.44 crook 5961: @node CREATE, Variables, Defining Words, Defining Words
5962: @subsection @code{CREATE}
1.29 crook 5963: @cindex simple defining words
5964: @cindex defining words, simple
5965:
5966: Defining words are used to create new entries in the dictionary. The
5967: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5968: this:
5969:
5970: @example
5971: CREATE new-word1
5972: @end example
5973:
1.69 anton 5974: @code{CREATE} is a parsing word, i.e., it takes an argument from the
5975: input stream (@code{new-word1} in our example). It generates a
5976: dictionary entry for @code{new-word1}. When @code{new-word1} is
5977: executed, all that it does is leave an address on the stack. The address
5978: represents the value of the data space pointer (@code{HERE}) at the time
5979: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
5980: associating a name with the address of a region of memory.
1.29 crook 5981:
1.34 anton 5982: doc-create
5983:
1.69 anton 5984: Note that in ANS Forth guarantees only for @code{create} that its body
5985: is in dictionary data space (i.e., where @code{here}, @code{allot}
5986: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
5987: @code{create}d words can be modified with @code{does>}
5988: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
5989: can only be applied to @code{create}d words.
5990:
1.29 crook 5991: By extending this example to reserve some memory in data space, we end
1.69 anton 5992: up with something like a @i{variable}. Here are two different ways to do
5993: it:
1.29 crook 5994:
5995: @example
5996: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
5997: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
5998: @end example
5999:
6000: The variable can be examined and modified using @code{@@} (``fetch'') and
6001: @code{!} (``store'') like this:
6002:
6003: @example
6004: new-word2 @@ . \ get address, fetch from it and display
6005: 1234 new-word2 ! \ new value, get address, store to it
6006: @end example
6007:
1.44 crook 6008: @cindex arrays
6009: A similar mechanism can be used to create arrays. For example, an
6010: 80-character text input buffer:
1.29 crook 6011:
6012: @example
1.44 crook 6013: CREATE text-buf 80 chars allot
6014:
1.168 anton 6015: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6016: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6017: @end example
1.29 crook 6018:
1.44 crook 6019: You can build arbitrarily complex data structures by allocating
1.49 anton 6020: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6021: learn about some Gforth tools that make it easier,
1.49 anton 6022: @xref{Structures}.
1.44 crook 6023:
6024:
6025: @node Variables, Constants, CREATE, Defining Words
6026: @subsection Variables
6027: @cindex variables
6028:
6029: The previous section showed how a sequence of commands could be used to
6030: generate a variable. As a final refinement, the whole code sequence can
6031: be wrapped up in a defining word (pre-empting the subject of the next
6032: section), making it easier to create new variables:
6033:
6034: @example
6035: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6036: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6037:
6038: myvariableX foo \ variable foo starts off with an unknown value
6039: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6040:
6041: 45 3 * foo ! \ set foo to 135
6042: 1234 joe ! \ set joe to 1234
6043: 3 joe +! \ increment joe by 3.. to 1237
6044: @end example
6045:
6046: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6047: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6048: guarantee that a @code{Variable} is initialised when it is created
6049: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6050: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6051: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6052: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6053: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6054: store a boolean, you can use @code{on} and @code{off} to toggle its
6055: state.
1.29 crook 6056:
1.34 anton 6057: doc-variable
6058: doc-2variable
6059: doc-fvariable
6060:
1.29 crook 6061: @cindex user variables
6062: @cindex user space
6063: The defining word @code{User} behaves in the same way as @code{Variable}.
6064: The difference is that it reserves space in @i{user (data) space} rather
6065: than normal data space. In a Forth system that has a multi-tasker, each
6066: task has its own set of user variables.
6067:
1.34 anton 6068: doc-user
1.67 anton 6069: @c doc-udp
6070: @c doc-uallot
1.34 anton 6071:
1.29 crook 6072: @comment TODO is that stuff about user variables strictly correct? Is it
6073: @comment just terminal tasks that have user variables?
6074: @comment should document tasker.fs (with some examples) elsewhere
6075: @comment in this manual, then expand on user space and user variables.
6076:
1.44 crook 6077: @node Constants, Values, Variables, Defining Words
6078: @subsection Constants
6079: @cindex constants
6080:
6081: @code{Constant} allows you to declare a fixed value and refer to it by
6082: name. For example:
1.29 crook 6083:
6084: @example
6085: 12 Constant INCHES-PER-FOOT
6086: 3E+08 fconstant SPEED-O-LIGHT
6087: @end example
6088:
6089: A @code{Variable} can be both read and written, so its run-time
6090: behaviour is to supply an address through which its current value can be
6091: manipulated. In contrast, the value of a @code{Constant} cannot be
6092: changed once it has been declared@footnote{Well, often it can be -- but
6093: not in a Standard, portable way. It's safer to use a @code{Value} (read
6094: on).} so it's not necessary to supply the address -- it is more
6095: efficient to return the value of the constant directly. That's exactly
6096: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6097: the top of the stack (You can find one
6098: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6099:
1.69 anton 6100: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6101: double and floating-point constants, respectively.
6102:
1.34 anton 6103: doc-constant
6104: doc-2constant
6105: doc-fconstant
6106:
6107: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6108: @c nac-> How could that not be true in an ANS Forth? You can't define a
6109: @c constant, use it and then delete the definition of the constant..
1.69 anton 6110:
6111: @c anton->An ANS Forth system can compile a constant to a literal; On
6112: @c decompilation you would see only the number, just as if it had been used
6113: @c in the first place. The word will stay, of course, but it will only be
6114: @c used by the text interpreter (no run-time duties, except when it is
6115: @c POSTPONEd or somesuch).
6116:
6117: @c nac:
1.44 crook 6118: @c I agree that it's rather deep, but IMO it is an important difference
6119: @c relative to other programming languages.. often it's annoying: it
6120: @c certainly changes my programming style relative to C.
6121:
1.69 anton 6122: @c anton: In what way?
6123:
1.29 crook 6124: Constants in Forth behave differently from their equivalents in other
6125: programming languages. In other languages, a constant (such as an EQU in
6126: assembler or a #define in C) only exists at compile-time; in the
6127: executable program the constant has been translated into an absolute
6128: number and, unless you are using a symbolic debugger, it's impossible to
6129: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6130: an entry in the header space and remains there after the code that uses
6131: it has been defined. In fact, it must remain in the dictionary since it
6132: has run-time duties to perform. For example:
1.29 crook 6133:
6134: @example
6135: 12 Constant INCHES-PER-FOOT
6136: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6137: @end example
6138:
6139: @cindex in-lining of constants
6140: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6141: associated with the constant @code{INCHES-PER-FOOT}. If you use
6142: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6143: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6144: attempt to optimise constants by in-lining them where they are used. You
6145: can force Gforth to in-line a constant like this:
6146:
6147: @example
6148: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6149: @end example
6150:
6151: If you use @code{see} to decompile @i{this} version of
6152: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6153: longer present. To understand how this works, read
6154: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6155:
6156: In-lining constants in this way might improve execution time
6157: fractionally, and can ensure that a constant is now only referenced at
6158: compile-time. However, the definition of the constant still remains in
6159: the dictionary. Some Forth compilers provide a mechanism for controlling
6160: a second dictionary for holding transient words such that this second
6161: dictionary can be deleted later in order to recover memory
6162: space. However, there is no standard way of doing this.
6163:
6164:
1.44 crook 6165: @node Values, Colon Definitions, Constants, Defining Words
6166: @subsection Values
6167: @cindex values
1.34 anton 6168:
1.69 anton 6169: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6170: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6171: (not in ANS Forth) you can access (and change) a @code{value} also with
6172: @code{>body}.
6173:
6174: Here are some
6175: examples:
1.29 crook 6176:
6177: @example
1.69 anton 6178: 12 Value APPLES \ Define APPLES with an initial value of 12
6179: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6180: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6181: APPLES \ puts 35 on the top of the stack.
1.29 crook 6182: @end example
6183:
1.44 crook 6184: doc-value
6185: doc-to
1.29 crook 6186:
1.35 anton 6187:
1.69 anton 6188:
1.44 crook 6189: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6190: @subsection Colon Definitions
6191: @cindex colon definitions
1.35 anton 6192:
6193: @example
1.44 crook 6194: : name ( ... -- ... )
6195: word1 word2 word3 ;
1.29 crook 6196: @end example
6197:
1.44 crook 6198: @noindent
6199: Creates a word called @code{name} that, upon execution, executes
6200: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6201:
1.49 anton 6202: The explanation above is somewhat superficial. For simple examples of
6203: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6204: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6205: Compilation Semantics}.
1.29 crook 6206:
1.44 crook 6207: doc-:
6208: doc-;
1.1 anton 6209:
1.34 anton 6210:
1.69 anton 6211: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6212: @subsection Anonymous Definitions
6213: @cindex colon definitions
6214: @cindex defining words without name
1.34 anton 6215:
1.44 crook 6216: Sometimes you want to define an @dfn{anonymous word}; a word without a
6217: name. You can do this with:
1.1 anton 6218:
1.44 crook 6219: doc-:noname
1.1 anton 6220:
1.44 crook 6221: This leaves the execution token for the word on the stack after the
6222: closing @code{;}. Here's an example in which a deferred word is
6223: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6224:
1.29 crook 6225: @example
1.44 crook 6226: Defer deferred
6227: :noname ( ... -- ... )
6228: ... ;
6229: IS deferred
1.29 crook 6230: @end example
1.26 crook 6231:
1.44 crook 6232: @noindent
6233: Gforth provides an alternative way of doing this, using two separate
6234: words:
1.27 crook 6235:
1.44 crook 6236: doc-noname
6237: @cindex execution token of last defined word
1.116 anton 6238: doc-latestxt
1.1 anton 6239:
1.44 crook 6240: @noindent
6241: The previous example can be rewritten using @code{noname} and
1.116 anton 6242: @code{latestxt}:
1.1 anton 6243:
1.26 crook 6244: @example
1.44 crook 6245: Defer deferred
6246: noname : ( ... -- ... )
6247: ... ;
1.116 anton 6248: latestxt IS deferred
1.26 crook 6249: @end example
1.1 anton 6250:
1.29 crook 6251: @noindent
1.44 crook 6252: @code{noname} works with any defining word, not just @code{:}.
6253:
1.116 anton 6254: @code{latestxt} also works when the last word was not defined as
1.71 anton 6255: @code{noname}. It does not work for combined words, though. It also has
6256: the useful property that is is valid as soon as the header for a
6257: definition has been built. Thus:
1.44 crook 6258:
6259: @example
1.116 anton 6260: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6261: @end example
1.1 anton 6262:
1.44 crook 6263: @noindent
6264: prints 3 numbers; the last two are the same.
1.26 crook 6265:
1.69 anton 6266: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6267: @subsection Supplying the name of a defined word
6268: @cindex names for defined words
6269: @cindex defining words, name given in a string
6270:
6271: By default, a defining word takes the name for the defined word from the
6272: input stream. Sometimes you want to supply the name from a string. You
6273: can do this with:
6274:
6275: doc-nextname
6276:
6277: For example:
6278:
6279: @example
6280: s" foo" nextname create
6281: @end example
6282:
6283: @noindent
6284: is equivalent to:
6285:
6286: @example
6287: create foo
6288: @end example
6289:
6290: @noindent
6291: @code{nextname} works with any defining word.
6292:
1.1 anton 6293:
1.170 pazsan 6294: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6295: @subsection User-defined Defining Words
6296: @cindex user-defined defining words
6297: @cindex defining words, user-defined
1.1 anton 6298:
1.29 crook 6299: You can create a new defining word by wrapping defining-time code around
6300: an existing defining word and putting the sequence in a colon
1.69 anton 6301: definition.
6302:
6303: @c anton: This example is very complex and leads in a quite different
6304: @c direction from the CREATE-DOES> stuff that follows. It should probably
6305: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6306: @c subsection of Defining Words)
6307:
6308: For example, suppose that you have a word @code{stats} that
1.29 crook 6309: gathers statistics about colon definitions given the @i{xt} of the
6310: definition, and you want every colon definition in your application to
6311: make a call to @code{stats}. You can define and use a new version of
6312: @code{:} like this:
6313:
6314: @example
6315: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6316: ... ; \ other code
6317:
1.116 anton 6318: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6319:
6320: my: foo + - ;
6321: @end example
6322:
6323: When @code{foo} is defined using @code{my:} these steps occur:
6324:
6325: @itemize @bullet
6326: @item
6327: @code{my:} is executed.
6328: @item
6329: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6330: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6331: the input stream for a name, builds a dictionary header for the name
6332: @code{foo} and switches @code{state} from interpret to compile.
6333: @item
1.116 anton 6334: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6335: being defined -- @code{foo} -- onto the stack.
6336: @item
6337: The code that was produced by @code{postpone literal} is executed; this
6338: causes the value on the stack to be compiled as a literal in the code
6339: area of @code{foo}.
6340: @item
6341: The code @code{['] stats} compiles a literal into the definition of
6342: @code{my:}. When @code{compile,} is executed, that literal -- the
6343: execution token for @code{stats} -- is layed down in the code area of
6344: @code{foo} , following the literal@footnote{Strictly speaking, the
6345: mechanism that @code{compile,} uses to convert an @i{xt} into something
6346: in the code area is implementation-dependent. A threaded implementation
6347: might spit out the execution token directly whilst another
6348: implementation might spit out a native code sequence.}.
6349: @item
6350: At this point, the execution of @code{my:} is complete, and control
6351: returns to the text interpreter. The text interpreter is in compile
6352: state, so subsequent text @code{+ -} is compiled into the definition of
6353: @code{foo} and the @code{;} terminates the definition as always.
6354: @end itemize
6355:
6356: You can use @code{see} to decompile a word that was defined using
6357: @code{my:} and see how it is different from a normal @code{:}
6358: definition. For example:
6359:
6360: @example
6361: : bar + - ; \ like foo but using : rather than my:
6362: see bar
6363: : bar
6364: + - ;
6365: see foo
6366: : foo
6367: 107645672 stats + - ;
6368:
1.140 anton 6369: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6370: @end example
6371:
6372: You can use techniques like this to make new defining words in terms of
6373: @i{any} existing defining word.
1.1 anton 6374:
6375:
1.29 crook 6376: @cindex defining defining words
1.26 crook 6377: @cindex @code{CREATE} ... @code{DOES>}
6378: If you want the words defined with your defining words to behave
6379: differently from words defined with standard defining words, you can
6380: write your defining word like this:
1.1 anton 6381:
6382: @example
1.26 crook 6383: : def-word ( "name" -- )
1.29 crook 6384: CREATE @i{code1}
1.26 crook 6385: DOES> ( ... -- ... )
1.29 crook 6386: @i{code2} ;
1.26 crook 6387:
6388: def-word name
1.1 anton 6389: @end example
6390:
1.29 crook 6391: @cindex child words
6392: This fragment defines a @dfn{defining word} @code{def-word} and then
6393: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6394: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6395: is not executed at this time. The word @code{name} is sometimes called a
6396: @dfn{child} of @code{def-word}.
6397:
6398: When you execute @code{name}, the address of the body of @code{name} is
6399: put on the data stack and @i{code2} is executed (the address of the body
6400: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6401: @code{CREATE}, i.e., the address a @code{create}d word returns by
6402: default).
6403:
6404: @c anton:
6405: @c www.dictionary.com says:
6406: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6407: @c several generations of absence, usually caused by the chance
6408: @c recombination of genes. 2.An individual or a part that exhibits
6409: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6410: @c of previous behavior after a period of absence.
6411: @c
6412: @c Doesn't seem to fit.
1.29 crook 6413:
1.69 anton 6414: @c @cindex atavism in child words
1.33 anton 6415: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6416: similarly; they all have a common run-time behaviour determined by
6417: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6418: body of the child word. The structure of the data is common to all
6419: children of @code{def-word}, but the data values are specific -- and
6420: private -- to each child word. When a child word is executed, the
6421: address of its private data area is passed as a parameter on TOS to be
6422: used and manipulated@footnote{It is legitimate both to read and write to
6423: this data area.} by @i{code2}.
1.29 crook 6424:
6425: The two fragments of code that make up the defining words act (are
6426: executed) at two completely separate times:
1.1 anton 6427:
1.29 crook 6428: @itemize @bullet
6429: @item
6430: At @i{define time}, the defining word executes @i{code1} to generate a
6431: child word
6432: @item
6433: At @i{child execution time}, when a child word is invoked, @i{code2}
6434: is executed, using parameters (data) that are private and specific to
6435: the child word.
6436: @end itemize
6437:
1.44 crook 6438: Another way of understanding the behaviour of @code{def-word} and
6439: @code{name} is to say that, if you make the following definitions:
1.33 anton 6440: @example
6441: : def-word1 ( "name" -- )
6442: CREATE @i{code1} ;
6443:
6444: : action1 ( ... -- ... )
6445: @i{code2} ;
6446:
6447: def-word1 name1
6448: @end example
6449:
1.44 crook 6450: @noindent
6451: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6452:
1.29 crook 6453: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6454:
1.1 anton 6455: @example
1.29 crook 6456: : CONSTANT ( w "name" -- )
6457: CREATE ,
1.26 crook 6458: DOES> ( -- w )
6459: @@ ;
1.1 anton 6460: @end example
6461:
1.29 crook 6462: @comment There is a beautiful description of how this works and what
6463: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6464: @comment commentary on the Counting Fruits problem.
6465:
6466: When you create a constant with @code{5 CONSTANT five}, a set of
6467: define-time actions take place; first a new word @code{five} is created,
6468: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6469: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6470: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6471: no code of its own; it simply contains a data field and a pointer to the
6472: code that follows @code{DOES>} in its defining word. That makes words
6473: created in this way very compact.
6474:
6475: The final example in this section is intended to remind you that space
6476: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6477: both read and written by a Standard program@footnote{Exercise: use this
6478: example as a starting point for your own implementation of @code{Value}
6479: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6480: @code{[']}.}:
6481:
6482: @example
6483: : foo ( "name" -- )
6484: CREATE -1 ,
6485: DOES> ( -- )
1.33 anton 6486: @@ . ;
1.29 crook 6487:
6488: foo first-word
6489: foo second-word
6490:
6491: 123 ' first-word >BODY !
6492: @end example
6493:
6494: If @code{first-word} had been a @code{CREATE}d word, we could simply
6495: have executed it to get the address of its data field. However, since it
6496: was defined to have @code{DOES>} actions, its execution semantics are to
6497: perform those @code{DOES>} actions. To get the address of its data field
6498: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6499: translate the xt into the address of the data field. When you execute
6500: @code{first-word}, it will display @code{123}. When you execute
6501: @code{second-word} it will display @code{-1}.
1.26 crook 6502:
6503: @cindex stack effect of @code{DOES>}-parts
6504: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6505: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6506: the stack effect of the defined words, not the stack effect of the
6507: following code (the following code expects the address of the body on
6508: the top of stack, which is not reflected in the stack comment). This is
6509: the convention that I use and recommend (it clashes a bit with using
6510: locals declarations for stack effect specification, though).
1.1 anton 6511:
1.53 anton 6512: @menu
6513: * CREATE..DOES> applications::
6514: * CREATE..DOES> details::
1.63 anton 6515: * Advanced does> usage example::
1.155 anton 6516: * Const-does>::
1.53 anton 6517: @end menu
6518:
6519: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6520: @subsubsection Applications of @code{CREATE..DOES>}
6521: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6522:
1.26 crook 6523: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6524:
1.26 crook 6525: @cindex factoring similar colon definitions
6526: When you see a sequence of code occurring several times, and you can
6527: identify a meaning, you will factor it out as a colon definition. When
6528: you see similar colon definitions, you can factor them using
6529: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6530: that look very similar:
1.1 anton 6531: @example
1.26 crook 6532: : ori, ( reg-target reg-source n -- )
6533: 0 asm-reg-reg-imm ;
6534: : andi, ( reg-target reg-source n -- )
6535: 1 asm-reg-reg-imm ;
1.1 anton 6536: @end example
6537:
1.26 crook 6538: @noindent
6539: This could be factored with:
6540: @example
6541: : reg-reg-imm ( op-code -- )
6542: CREATE ,
6543: DOES> ( reg-target reg-source n -- )
6544: @@ asm-reg-reg-imm ;
6545:
6546: 0 reg-reg-imm ori,
6547: 1 reg-reg-imm andi,
6548: @end example
1.1 anton 6549:
1.26 crook 6550: @cindex currying
6551: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6552: supply a part of the parameters for a word (known as @dfn{currying} in
6553: the functional language community). E.g., @code{+} needs two
6554: parameters. Creating versions of @code{+} with one parameter fixed can
6555: be done like this:
1.82 anton 6556:
1.1 anton 6557: @example
1.82 anton 6558: : curry+ ( n1 "name" -- )
1.26 crook 6559: CREATE ,
6560: DOES> ( n2 -- n1+n2 )
6561: @@ + ;
6562:
6563: 3 curry+ 3+
6564: -2 curry+ 2-
1.1 anton 6565: @end example
6566:
1.91 anton 6567:
1.63 anton 6568: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6569: @subsubsection The gory details of @code{CREATE..DOES>}
6570: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6571:
1.26 crook 6572: doc-does>
1.1 anton 6573:
1.26 crook 6574: @cindex @code{DOES>} in a separate definition
6575: This means that you need not use @code{CREATE} and @code{DOES>} in the
6576: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6577: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6578: @example
6579: : does1
6580: DOES> ( ... -- ... )
1.44 crook 6581: ... ;
6582:
6583: : does2
6584: DOES> ( ... -- ... )
6585: ... ;
6586:
6587: : def-word ( ... -- ... )
6588: create ...
6589: IF
6590: does1
6591: ELSE
6592: does2
6593: ENDIF ;
6594: @end example
6595:
6596: In this example, the selection of whether to use @code{does1} or
1.69 anton 6597: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6598: @code{CREATE}d.
6599:
6600: @cindex @code{DOES>} in interpretation state
6601: In a standard program you can apply a @code{DOES>}-part only if the last
6602: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6603: will override the behaviour of the last word defined in any case. In a
6604: standard program, you can use @code{DOES>} only in a colon
6605: definition. In Gforth, you can also use it in interpretation state, in a
6606: kind of one-shot mode; for example:
6607: @example
6608: CREATE name ( ... -- ... )
6609: @i{initialization}
6610: DOES>
6611: @i{code} ;
6612: @end example
6613:
6614: @noindent
6615: is equivalent to the standard:
6616: @example
6617: :noname
6618: DOES>
6619: @i{code} ;
6620: CREATE name EXECUTE ( ... -- ... )
6621: @i{initialization}
6622: @end example
6623:
1.53 anton 6624: doc->body
6625:
1.152 pazsan 6626: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6627: @subsubsection Advanced does> usage example
6628:
6629: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6630: for disassembling instructions, that follow a very repetetive scheme:
6631:
6632: @example
6633: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6634: @var{entry-num} cells @var{table} + !
6635: @end example
6636:
6637: Of course, this inspires the idea to factor out the commonalities to
6638: allow a definition like
6639:
6640: @example
6641: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6642: @end example
6643:
6644: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6645: correlated. Moreover, before I wrote the disassembler, there already
6646: existed code that defines instructions like this:
1.63 anton 6647:
6648: @example
6649: @var{entry-num} @var{inst-format} @var{inst-name}
6650: @end example
6651:
6652: This code comes from the assembler and resides in
6653: @file{arch/mips/insts.fs}.
6654:
6655: So I had to define the @var{inst-format} words that performed the scheme
6656: above when executed. At first I chose to use run-time code-generation:
6657:
6658: @example
6659: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6660: :noname Postpone @var{disasm-operands}
6661: name Postpone sliteral Postpone type Postpone ;
6662: swap cells @var{table} + ! ;
6663: @end example
6664:
6665: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6666:
1.63 anton 6667: An alternative would have been to write this using
6668: @code{create}/@code{does>}:
6669:
6670: @example
6671: : @var{inst-format} ( entry-num "name" -- )
6672: here name string, ( entry-num c-addr ) \ parse and save "name"
6673: noname create , ( entry-num )
1.116 anton 6674: latestxt swap cells @var{table} + !
1.63 anton 6675: does> ( addr w -- )
6676: \ disassemble instruction w at addr
6677: @@ >r
6678: @var{disasm-operands}
6679: r> count type ;
6680: @end example
6681:
6682: Somehow the first solution is simpler, mainly because it's simpler to
6683: shift a string from definition-time to use-time with @code{sliteral}
6684: than with @code{string,} and friends.
6685:
6686: I wrote a lot of words following this scheme and soon thought about
6687: factoring out the commonalities among them. Note that this uses a
6688: two-level defining word, i.e., a word that defines ordinary defining
6689: words.
6690:
6691: This time a solution involving @code{postpone} and friends seemed more
6692: difficult (try it as an exercise), so I decided to use a
6693: @code{create}/@code{does>} word; since I was already at it, I also used
6694: @code{create}/@code{does>} for the lower level (try using
6695: @code{postpone} etc. as an exercise), resulting in the following
6696: definition:
6697:
6698: @example
6699: : define-format ( disasm-xt table-xt -- )
6700: \ define an instruction format that uses disasm-xt for
6701: \ disassembling and enters the defined instructions into table
6702: \ table-xt
6703: create 2,
6704: does> ( u "inst" -- )
6705: \ defines an anonymous word for disassembling instruction inst,
6706: \ and enters it as u-th entry into table-xt
6707: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6708: noname create 2, \ define anonymous word
1.116 anton 6709: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6710: does> ( addr w -- )
6711: \ disassemble instruction w at addr
6712: 2@@ >r ( addr w disasm-xt R: c-addr )
6713: execute ( R: c-addr ) \ disassemble operands
6714: r> count type ; \ print name
6715: @end example
6716:
6717: Note that the tables here (in contrast to above) do the @code{cells +}
6718: by themselves (that's why you have to pass an xt). This word is used in
6719: the following way:
6720:
6721: @example
6722: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6723: @end example
6724:
1.71 anton 6725: As shown above, the defined instruction format is then used like this:
6726:
6727: @example
6728: @var{entry-num} @var{inst-format} @var{inst-name}
6729: @end example
6730:
1.63 anton 6731: In terms of currying, this kind of two-level defining word provides the
6732: parameters in three stages: first @var{disasm-operands} and @var{table},
6733: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6734: the instruction to be disassembled.
6735:
6736: Of course this did not quite fit all the instruction format names used
6737: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6738: the parameters into the right form.
6739:
6740: If you have trouble following this section, don't worry. First, this is
6741: involved and takes time (and probably some playing around) to
6742: understand; second, this is the first two-level
6743: @code{create}/@code{does>} word I have written in seventeen years of
6744: Forth; and if I did not have @file{insts.fs} to start with, I may well
6745: have elected to use just a one-level defining word (with some repeating
6746: of parameters when using the defining word). So it is not necessary to
6747: understand this, but it may improve your understanding of Forth.
1.44 crook 6748:
6749:
1.152 pazsan 6750: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6751: @subsubsection @code{Const-does>}
6752:
6753: A frequent use of @code{create}...@code{does>} is for transferring some
6754: values from definition-time to run-time. Gforth supports this use with
6755:
6756: doc-const-does>
6757:
6758: A typical use of this word is:
6759:
6760: @example
6761: : curry+ ( n1 "name" -- )
6762: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6763: + ;
6764:
6765: 3 curry+ 3+
6766: @end example
6767:
6768: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6769: definition to run-time.
6770:
6771: The advantages of using @code{const-does>} are:
6772:
6773: @itemize
6774:
6775: @item
6776: You don't have to deal with storing and retrieving the values, i.e.,
6777: your program becomes more writable and readable.
6778:
6779: @item
6780: When using @code{does>}, you have to introduce a @code{@@} that cannot
6781: be optimized away (because you could change the data using
6782: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6783:
6784: @end itemize
6785:
6786: An ANS Forth implementation of @code{const-does>} is available in
6787: @file{compat/const-does.fs}.
6788:
6789:
1.170 pazsan 6790: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6791: @subsection Deferred Words
1.44 crook 6792: @cindex deferred words
6793:
6794: The defining word @code{Defer} allows you to define a word by name
6795: without defining its behaviour; the definition of its behaviour is
6796: deferred. Here are two situation where this can be useful:
6797:
6798: @itemize @bullet
6799: @item
6800: Where you want to allow the behaviour of a word to be altered later, and
6801: for all precompiled references to the word to change when its behaviour
6802: is changed.
6803: @item
6804: For mutual recursion; @xref{Calls and returns}.
6805: @end itemize
6806:
6807: In the following example, @code{foo} always invokes the version of
6808: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6809: always invokes the version that prints ``@code{Hello}''. There is no way
6810: of getting @code{foo} to use the later version without re-ordering the
6811: source code and recompiling it.
6812:
6813: @example
6814: : greet ." Good morning" ;
6815: : foo ... greet ... ;
6816: : greet ." Hello" ;
6817: : bar ... greet ... ;
6818: @end example
6819:
6820: This problem can be solved by defining @code{greet} as a @code{Defer}red
6821: word. The behaviour of a @code{Defer}red word can be defined and
6822: redefined at any time by using @code{IS} to associate the xt of a
6823: previously-defined word with it. The previous example becomes:
6824:
6825: @example
1.69 anton 6826: Defer greet ( -- )
1.44 crook 6827: : foo ... greet ... ;
6828: : bar ... greet ... ;
1.69 anton 6829: : greet1 ( -- ) ." Good morning" ;
6830: : greet2 ( -- ) ." Hello" ;
1.132 anton 6831: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6832: @end example
6833:
1.69 anton 6834: @progstyle
6835: You should write a stack comment for every deferred word, and put only
6836: XTs into deferred words that conform to this stack effect. Otherwise
6837: it's too difficult to use the deferred word.
6838:
1.44 crook 6839: A deferred word can be used to improve the statistics-gathering example
6840: from @ref{User-defined Defining Words}; rather than edit the
6841: application's source code to change every @code{:} to a @code{my:}, do
6842: this:
6843:
6844: @example
6845: : real: : ; \ retain access to the original
6846: defer : \ redefine as a deferred word
1.132 anton 6847: ' my: IS : \ use special version of :
1.44 crook 6848: \
6849: \ load application here
6850: \
1.132 anton 6851: ' real: IS : \ go back to the original
1.44 crook 6852: @end example
6853:
6854:
1.132 anton 6855: One thing to note is that @code{IS} has special compilation semantics,
6856: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6857:
6858: @example
6859: : set-greet ( xt -- )
1.132 anton 6860: IS greet ;
1.44 crook 6861:
6862: ' greet1 set-greet
6863: @end example
6864:
1.132 anton 6865: In situations where @code{IS} does not fit, use @code{defer!} instead.
6866:
1.69 anton 6867: A deferred word can only inherit execution semantics from the xt
6868: (because that is all that an xt can represent -- for more discussion of
6869: this @pxref{Tokens for Words}); by default it will have default
6870: interpretation and compilation semantics deriving from this execution
6871: semantics. However, you can change the interpretation and compilation
6872: semantics of the deferred word in the usual ways:
1.44 crook 6873:
6874: @example
1.132 anton 6875: : bar .... ; immediate
1.44 crook 6876: Defer fred immediate
6877: Defer jim
6878:
1.132 anton 6879: ' bar IS jim \ jim has default semantics
6880: ' bar IS fred \ fred is immediate
1.44 crook 6881: @end example
6882:
6883: doc-defer
1.132 anton 6884: doc-defer!
1.44 crook 6885: doc-is
1.132 anton 6886: doc-defer@
6887: doc-action-of
1.44 crook 6888: @comment TODO document these: what's defers [is]
6889: doc-defers
6890:
6891: @c Use @code{words-deferred} to see a list of deferred words.
6892:
1.132 anton 6893: Definitions of these words (except @code{defers}) in ANS Forth are
6894: provided in @file{compat/defer.fs}.
1.44 crook 6895:
6896:
1.170 pazsan 6897: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6898: @subsection Aliases
6899: @cindex aliases
1.1 anton 6900:
1.44 crook 6901: The defining word @code{Alias} allows you to define a word by name that
6902: has the same behaviour as some other word. Here are two situation where
6903: this can be useful:
1.1 anton 6904:
1.44 crook 6905: @itemize @bullet
6906: @item
6907: When you want access to a word's definition from a different word list
6908: (for an example of this, see the definition of the @code{Root} word list
6909: in the Gforth source).
6910: @item
6911: When you want to create a synonym; a definition that can be known by
6912: either of two names (for example, @code{THEN} and @code{ENDIF} are
6913: aliases).
6914: @end itemize
1.1 anton 6915:
1.69 anton 6916: Like deferred words, an alias has default compilation and interpretation
6917: semantics at the beginning (not the modifications of the other word),
6918: but you can change them in the usual ways (@code{immediate},
6919: @code{compile-only}). For example:
1.1 anton 6920:
6921: @example
1.44 crook 6922: : foo ... ; immediate
6923:
6924: ' foo Alias bar \ bar is not an immediate word
6925: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6926: @end example
6927:
1.44 crook 6928: Words that are aliases have the same xt, different headers in the
6929: dictionary, and consequently different name tokens (@pxref{Tokens for
6930: Words}) and possibly different immediate flags. An alias can only have
6931: default or immediate compilation semantics; you can define aliases for
6932: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6933:
1.44 crook 6934: doc-alias
1.1 anton 6935:
6936:
1.47 crook 6937: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6938: @section Interpretation and Compilation Semantics
1.26 crook 6939: @cindex semantics, interpretation and compilation
1.1 anton 6940:
1.71 anton 6941: @c !! state and ' are used without explanation
6942: @c example for immediate/compile-only? or is the tutorial enough
6943:
1.26 crook 6944: @cindex interpretation semantics
1.71 anton 6945: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6946: interpreter does when it encounters the word in interpret state. It also
6947: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6948: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6949: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6950: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6951:
1.26 crook 6952: @cindex compilation semantics
1.71 anton 6953: The @dfn{compilation semantics} of a (named) word are what the text
6954: interpreter does when it encounters the word in compile state. It also
6955: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6956: compiles@footnote{In standard terminology, ``appends to the current
6957: definition''.} the compilation semantics of @i{word}.
1.1 anton 6958:
1.26 crook 6959: @cindex execution semantics
6960: The standard also talks about @dfn{execution semantics}. They are used
6961: only for defining the interpretation and compilation semantics of many
6962: words. By default, the interpretation semantics of a word are to
6963: @code{execute} its execution semantics, and the compilation semantics of
6964: a word are to @code{compile,} its execution semantics.@footnote{In
6965: standard terminology: The default interpretation semantics are its
6966: execution semantics; the default compilation semantics are to append its
6967: execution semantics to the execution semantics of the current
6968: definition.}
6969:
1.71 anton 6970: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
6971: the text interpreter, ticked, or @code{postpone}d, so they have no
6972: interpretation or compilation semantics. Their behaviour is represented
6973: by their XT (@pxref{Tokens for Words}), and we call it execution
6974: semantics, too.
6975:
1.26 crook 6976: @comment TODO expand, make it co-operate with new sections on text interpreter.
6977:
6978: @cindex immediate words
6979: @cindex compile-only words
6980: You can change the semantics of the most-recently defined word:
6981:
1.44 crook 6982:
1.26 crook 6983: doc-immediate
6984: doc-compile-only
6985: doc-restrict
6986:
1.82 anton 6987: By convention, words with non-default compilation semantics (e.g.,
6988: immediate words) often have names surrounded with brackets (e.g.,
6989: @code{[']}, @pxref{Execution token}).
1.44 crook 6990:
1.26 crook 6991: Note that ticking (@code{'}) a compile-only word gives an error
6992: (``Interpreting a compile-only word'').
1.1 anton 6993:
1.47 crook 6994: @menu
1.67 anton 6995: * Combined words::
1.47 crook 6996: @end menu
1.44 crook 6997:
1.71 anton 6998:
1.48 anton 6999: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7000: @subsection Combined Words
7001: @cindex combined words
7002:
7003: Gforth allows you to define @dfn{combined words} -- words that have an
7004: arbitrary combination of interpretation and compilation semantics.
7005:
1.26 crook 7006: doc-interpret/compile:
1.1 anton 7007:
1.26 crook 7008: This feature was introduced for implementing @code{TO} and @code{S"}. I
7009: recommend that you do not define such words, as cute as they may be:
7010: they make it hard to get at both parts of the word in some contexts.
7011: E.g., assume you want to get an execution token for the compilation
7012: part. Instead, define two words, one that embodies the interpretation
7013: part, and one that embodies the compilation part. Once you have done
7014: that, you can define a combined word with @code{interpret/compile:} for
7015: the convenience of your users.
1.1 anton 7016:
1.26 crook 7017: You might try to use this feature to provide an optimizing
7018: implementation of the default compilation semantics of a word. For
7019: example, by defining:
1.1 anton 7020: @example
1.26 crook 7021: :noname
7022: foo bar ;
7023: :noname
7024: POSTPONE foo POSTPONE bar ;
1.29 crook 7025: interpret/compile: opti-foobar
1.1 anton 7026: @end example
1.26 crook 7027:
1.23 crook 7028: @noindent
1.26 crook 7029: as an optimizing version of:
7030:
1.1 anton 7031: @example
1.26 crook 7032: : foobar
7033: foo bar ;
1.1 anton 7034: @end example
7035:
1.26 crook 7036: Unfortunately, this does not work correctly with @code{[compile]},
7037: because @code{[compile]} assumes that the compilation semantics of all
7038: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7039: opti-foobar} would compile compilation semantics, whereas
7040: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7041:
1.26 crook 7042: @cindex state-smart words (are a bad idea)
1.82 anton 7043: @anchor{state-smartness}
1.29 crook 7044: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7045: by @code{interpret/compile:} (words are state-smart if they check
7046: @code{STATE} during execution). E.g., they would try to code
7047: @code{foobar} like this:
1.1 anton 7048:
1.26 crook 7049: @example
7050: : foobar
7051: STATE @@
7052: IF ( compilation state )
7053: POSTPONE foo POSTPONE bar
7054: ELSE
7055: foo bar
7056: ENDIF ; immediate
7057: @end example
1.1 anton 7058:
1.26 crook 7059: Although this works if @code{foobar} is only processed by the text
7060: interpreter, it does not work in other contexts (like @code{'} or
7061: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7062: for a state-smart word, not for the interpretation semantics of the
7063: original @code{foobar}; when you execute this execution token (directly
7064: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7065: state, the result will not be what you expected (i.e., it will not
7066: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7067: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7068: M. Anton Ertl,
7069: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7070: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7071:
1.26 crook 7072: @cindex defining words with arbitrary semantics combinations
7073: It is also possible to write defining words that define words with
7074: arbitrary combinations of interpretation and compilation semantics. In
7075: general, they look like this:
1.1 anton 7076:
1.26 crook 7077: @example
7078: : def-word
7079: create-interpret/compile
1.29 crook 7080: @i{code1}
1.26 crook 7081: interpretation>
1.29 crook 7082: @i{code2}
1.26 crook 7083: <interpretation
7084: compilation>
1.29 crook 7085: @i{code3}
1.26 crook 7086: <compilation ;
7087: @end example
1.1 anton 7088:
1.29 crook 7089: For a @i{word} defined with @code{def-word}, the interpretation
7090: semantics are to push the address of the body of @i{word} and perform
7091: @i{code2}, and the compilation semantics are to push the address of
7092: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7093: can also be defined like this (except that the defined constants don't
7094: behave correctly when @code{[compile]}d):
1.1 anton 7095:
1.26 crook 7096: @example
7097: : constant ( n "name" -- )
7098: create-interpret/compile
7099: ,
7100: interpretation> ( -- n )
7101: @@
7102: <interpretation
7103: compilation> ( compilation. -- ; run-time. -- n )
7104: @@ postpone literal
7105: <compilation ;
7106: @end example
1.1 anton 7107:
1.44 crook 7108:
1.26 crook 7109: doc-create-interpret/compile
7110: doc-interpretation>
7111: doc-<interpretation
7112: doc-compilation>
7113: doc-<compilation
1.1 anton 7114:
1.44 crook 7115:
1.29 crook 7116: Words defined with @code{interpret/compile:} and
1.26 crook 7117: @code{create-interpret/compile} have an extended header structure that
7118: differs from other words; however, unless you try to access them with
7119: plain address arithmetic, you should not notice this. Words for
7120: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7121: @code{'} @i{word} @code{>body} also gives you the body of a word created
7122: with @code{create-interpret/compile}.
1.1 anton 7123:
1.44 crook 7124:
1.47 crook 7125: @c -------------------------------------------------------------
1.81 anton 7126: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7127: @section Tokens for Words
7128: @cindex tokens for words
7129:
7130: This section describes the creation and use of tokens that represent
7131: words.
7132:
1.71 anton 7133: @menu
7134: * Execution token:: represents execution/interpretation semantics
7135: * Compilation token:: represents compilation semantics
7136: * Name token:: represents named words
7137: @end menu
1.47 crook 7138:
1.71 anton 7139: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7140: @subsection Execution token
1.47 crook 7141:
7142: @cindex xt
7143: @cindex execution token
1.71 anton 7144: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7145: You can use @code{execute} to invoke this behaviour.
1.47 crook 7146:
1.71 anton 7147: @cindex tick (')
7148: You can use @code{'} to get an execution token that represents the
7149: interpretation semantics of a named word:
1.47 crook 7150:
7151: @example
1.97 anton 7152: 5 ' . ( n xt )
7153: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7154: @end example
1.47 crook 7155:
1.71 anton 7156: doc-'
7157:
7158: @code{'} parses at run-time; there is also a word @code{[']} that parses
7159: when it is compiled, and compiles the resulting XT:
7160:
7161: @example
7162: : foo ['] . execute ;
7163: 5 foo
7164: : bar ' execute ; \ by contrast,
7165: 5 bar . \ ' parses "." when bar executes
7166: @end example
7167:
7168: doc-[']
7169:
7170: If you want the execution token of @i{word}, write @code{['] @i{word}}
7171: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7172: @code{'} and @code{[']} behave somewhat unusually by complaining about
7173: compile-only words (because these words have no interpretation
7174: semantics). You might get what you want by using @code{COMP' @i{word}
7175: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7176: token}).
7177:
1.116 anton 7178: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7179: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7180: for the only behaviour the word has (the execution semantics). For
1.116 anton 7181: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7182: would produce if the word was defined anonymously.
7183:
7184: @example
7185: :noname ." hello" ;
7186: execute
1.47 crook 7187: @end example
7188:
1.71 anton 7189: An XT occupies one cell and can be manipulated like any other cell.
7190:
1.47 crook 7191: @cindex code field address
7192: @cindex CFA
1.71 anton 7193: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7194: operations that produce or consume it). For old hands: In Gforth, the
7195: XT is implemented as a code field address (CFA).
7196:
7197: doc-execute
7198: doc-perform
7199:
7200: @node Compilation token, Name token, Execution token, Tokens for Words
7201: @subsection Compilation token
1.47 crook 7202:
7203: @cindex compilation token
1.71 anton 7204: @cindex CT (compilation token)
7205: Gforth represents the compilation semantics of a named word by a
1.47 crook 7206: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7207: @i{xt} is an execution token. The compilation semantics represented by
7208: the compilation token can be performed with @code{execute}, which
7209: consumes the whole compilation token, with an additional stack effect
7210: determined by the represented compilation semantics.
7211:
7212: At present, the @i{w} part of a compilation token is an execution token,
7213: and the @i{xt} part represents either @code{execute} or
7214: @code{compile,}@footnote{Depending upon the compilation semantics of the
7215: word. If the word has default compilation semantics, the @i{xt} will
7216: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7217: @i{xt} will represent @code{execute}.}. However, don't rely on that
7218: knowledge, unless necessary; future versions of Gforth may introduce
7219: unusual compilation tokens (e.g., a compilation token that represents
7220: the compilation semantics of a literal).
7221:
1.71 anton 7222: You can perform the compilation semantics represented by the compilation
7223: token with @code{execute}. You can compile the compilation semantics
7224: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7225: equivalent to @code{postpone @i{word}}.
7226:
7227: doc-[comp']
7228: doc-comp'
7229: doc-postpone,
7230:
7231: @node Name token, , Compilation token, Tokens for Words
7232: @subsection Name token
1.47 crook 7233:
7234: @cindex name token
1.116 anton 7235: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7236: token is an abstract data type that occurs as argument or result of the
7237: words below.
7238:
7239: @c !! put this elswhere?
1.47 crook 7240: @cindex name field address
7241: @cindex NFA
1.116 anton 7242: The closest thing to the nt in older Forth systems is the name field
7243: address (NFA), but there are significant differences: in older Forth
7244: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7245: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7246: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7247: is a link field in the structure identified by the name token, but
7248: searching usually uses a hash table external to these structures; the
7249: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7250: implemented as the address of that count field.
1.47 crook 7251:
7252: doc-find-name
1.116 anton 7253: doc-latest
7254: doc->name
1.47 crook 7255: doc-name>int
7256: doc-name?int
7257: doc-name>comp
7258: doc-name>string
1.109 anton 7259: doc-id.
7260: doc-.name
7261: doc-.id
1.47 crook 7262:
1.81 anton 7263: @c ----------------------------------------------------------
7264: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7265: @section Compiling words
7266: @cindex compiling words
7267: @cindex macros
7268:
7269: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7270: between compilation and run-time. E.g., you can run arbitrary code
7271: between defining words (or for computing data used by defining words
7272: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7273: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7274: running arbitrary code while compiling a colon definition (exception:
7275: you must not allot dictionary space).
7276:
7277: @menu
7278: * Literals:: Compiling data values
7279: * Macros:: Compiling words
7280: @end menu
7281:
7282: @node Literals, Macros, Compiling words, Compiling words
7283: @subsection Literals
7284: @cindex Literals
7285:
7286: The simplest and most frequent example is to compute a literal during
7287: compilation. E.g., the following definition prints an array of strings,
7288: one string per line:
7289:
7290: @example
7291: : .strings ( addr u -- ) \ gforth
7292: 2* cells bounds U+DO
7293: cr i 2@@ type
7294: 2 cells +LOOP ;
7295: @end example
1.81 anton 7296:
1.82 anton 7297: With a simple-minded compiler like Gforth's, this computes @code{2
7298: cells} on every loop iteration. You can compute this value once and for
7299: all at compile time and compile it into the definition like this:
7300:
7301: @example
7302: : .strings ( addr u -- ) \ gforth
7303: 2* cells bounds U+DO
7304: cr i 2@@ type
7305: [ 2 cells ] literal +LOOP ;
7306: @end example
7307:
7308: @code{[} switches the text interpreter to interpret state (you will get
7309: an @code{ok} prompt if you type this example interactively and insert a
7310: newline between @code{[} and @code{]}), so it performs the
7311: interpretation semantics of @code{2 cells}; this computes a number.
7312: @code{]} switches the text interpreter back into compile state. It then
7313: performs @code{Literal}'s compilation semantics, which are to compile
7314: this number into the current word. You can decompile the word with
7315: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7316:
1.82 anton 7317: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7318: *} in this way.
1.81 anton 7319:
1.82 anton 7320: doc-[
7321: doc-]
1.81 anton 7322: doc-literal
7323: doc-]L
1.82 anton 7324:
7325: There are also words for compiling other data types than single cells as
7326: literals:
7327:
1.81 anton 7328: doc-2literal
7329: doc-fliteral
1.82 anton 7330: doc-sliteral
7331:
7332: @cindex colon-sys, passing data across @code{:}
7333: @cindex @code{:}, passing data across
7334: You might be tempted to pass data from outside a colon definition to the
7335: inside on the data stack. This does not work, because @code{:} puhes a
7336: colon-sys, making stuff below unaccessible. E.g., this does not work:
7337:
7338: @example
7339: 5 : foo literal ; \ error: "unstructured"
7340: @end example
7341:
7342: Instead, you have to pass the value in some other way, e.g., through a
7343: variable:
7344:
7345: @example
7346: variable temp
7347: 5 temp !
7348: : foo [ temp @@ ] literal ;
7349: @end example
7350:
7351:
7352: @node Macros, , Literals, Compiling words
7353: @subsection Macros
7354: @cindex Macros
7355: @cindex compiling compilation semantics
7356:
7357: @code{Literal} and friends compile data values into the current
7358: definition. You can also write words that compile other words into the
7359: current definition. E.g.,
7360:
7361: @example
7362: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7363: POSTPONE + ;
7364:
7365: : foo ( n1 n2 -- n )
7366: [ compile-+ ] ;
7367: 1 2 foo .
7368: @end example
7369:
7370: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7371: What happens in this example? @code{Postpone} compiles the compilation
7372: semantics of @code{+} into @code{compile-+}; later the text interpreter
7373: executes @code{compile-+} and thus the compilation semantics of +, which
7374: compile (the execution semantics of) @code{+} into
7375: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7376: should only be executed in compile state, so this example is not
7377: guaranteed to work on all standard systems, but on any decent system it
7378: will work.}
7379:
7380: doc-postpone
7381: doc-[compile]
7382:
7383: Compiling words like @code{compile-+} are usually immediate (or similar)
7384: so you do not have to switch to interpret state to execute them;
7385: mopifying the last example accordingly produces:
7386:
7387: @example
7388: : [compile-+] ( compilation: --; interpretation: -- )
7389: \ compiled code: ( n1 n2 -- n )
7390: POSTPONE + ; immediate
7391:
7392: : foo ( n1 n2 -- n )
7393: [compile-+] ;
7394: 1 2 foo .
7395: @end example
7396:
7397: Immediate compiling words are similar to macros in other languages (in
7398: particular, Lisp). The important differences to macros in, e.g., C are:
7399:
7400: @itemize @bullet
7401:
7402: @item
7403: You use the same language for defining and processing macros, not a
7404: separate preprocessing language and processor.
7405:
7406: @item
7407: Consequently, the full power of Forth is available in macro definitions.
7408: E.g., you can perform arbitrarily complex computations, or generate
7409: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7410: Tutorial}). This power is very useful when writing a parser generators
7411: or other code-generating software.
7412:
7413: @item
7414: Macros defined using @code{postpone} etc. deal with the language at a
7415: higher level than strings; name binding happens at macro definition
7416: time, so you can avoid the pitfalls of name collisions that can happen
7417: in C macros. Of course, Forth is a liberal language and also allows to
7418: shoot yourself in the foot with text-interpreted macros like
7419:
7420: @example
7421: : [compile-+] s" +" evaluate ; immediate
7422: @end example
7423:
7424: Apart from binding the name at macro use time, using @code{evaluate}
7425: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7426: @end itemize
7427:
7428: You may want the macro to compile a number into a word. The word to do
7429: it is @code{literal}, but you have to @code{postpone} it, so its
7430: compilation semantics take effect when the macro is executed, not when
7431: it is compiled:
7432:
7433: @example
7434: : [compile-5] ( -- ) \ compiled code: ( -- n )
7435: 5 POSTPONE literal ; immediate
7436:
7437: : foo [compile-5] ;
7438: foo .
7439: @end example
7440:
7441: You may want to pass parameters to a macro, that the macro should
7442: compile into the current definition. If the parameter is a number, then
7443: you can use @code{postpone literal} (similar for other values).
7444:
7445: If you want to pass a word that is to be compiled, the usual way is to
7446: pass an execution token and @code{compile,} it:
7447:
7448: @example
7449: : twice1 ( xt -- ) \ compiled code: ... -- ...
7450: dup compile, compile, ;
7451:
7452: : 2+ ( n1 -- n2 )
7453: [ ' 1+ twice1 ] ;
7454: @end example
7455:
7456: doc-compile,
7457:
7458: An alternative available in Gforth, that allows you to pass compile-only
7459: words as parameters is to use the compilation token (@pxref{Compilation
7460: token}). The same example in this technique:
7461:
7462: @example
7463: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7464: 2dup 2>r execute 2r> execute ;
7465:
7466: : 2+ ( n1 -- n2 )
7467: [ comp' 1+ twice ] ;
7468: @end example
7469:
7470: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7471: works even if the executed compilation semantics has an effect on the
7472: data stack.
7473:
7474: You can also define complete definitions with these words; this provides
7475: an alternative to using @code{does>} (@pxref{User-defined Defining
7476: Words}). E.g., instead of
7477:
7478: @example
7479: : curry+ ( n1 "name" -- )
7480: CREATE ,
7481: DOES> ( n2 -- n1+n2 )
7482: @@ + ;
7483: @end example
7484:
7485: you could define
7486:
7487: @example
7488: : curry+ ( n1 "name" -- )
7489: \ name execution: ( n2 -- n1+n2 )
7490: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7491:
1.82 anton 7492: -3 curry+ 3-
7493: see 3-
7494: @end example
1.81 anton 7495:
1.82 anton 7496: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7497: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7498:
1.82 anton 7499: This way of writing defining words is sometimes more, sometimes less
7500: convenient than using @code{does>} (@pxref{Advanced does> usage
7501: example}). One advantage of this method is that it can be optimized
7502: better, because the compiler knows that the value compiled with
7503: @code{literal} is fixed, whereas the data associated with a
7504: @code{create}d word can be changed.
1.47 crook 7505:
1.26 crook 7506: @c ----------------------------------------------------------
1.111 anton 7507: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7508: @section The Text Interpreter
7509: @cindex interpreter - outer
7510: @cindex text interpreter
7511: @cindex outer interpreter
1.1 anton 7512:
1.34 anton 7513: @c Should we really describe all these ugly details? IMO the text
7514: @c interpreter should be much cleaner, but that may not be possible within
7515: @c ANS Forth. - anton
1.44 crook 7516: @c nac-> I wanted to explain how it works to show how you can exploit
7517: @c it in your own programs. When I was writing a cross-compiler, figuring out
7518: @c some of these gory details was very helpful to me. None of the textbooks
7519: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7520: @c seems to positively avoid going into too much detail for some of
7521: @c the internals.
1.34 anton 7522:
1.71 anton 7523: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7524: @c it is; for the ugly details, I would prefer another place. I wonder
7525: @c whether we should have a chapter before "Words" that describes some
7526: @c basic concepts referred to in words, and a chapter after "Words" that
7527: @c describes implementation details.
7528:
1.29 crook 7529: The text interpreter@footnote{This is an expanded version of the
7530: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7531: that processes input from the current input device. It is also called
7532: the outer interpreter, in contrast to the inner interpreter
7533: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7534: implementations.
1.27 crook 7535:
1.29 crook 7536: @cindex interpret state
7537: @cindex compile state
7538: The text interpreter operates in one of two states: @dfn{interpret
7539: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7540: aptly-named variable @code{state}.
1.29 crook 7541:
7542: This section starts by describing how the text interpreter behaves when
7543: it is in interpret state, processing input from the user input device --
7544: the keyboard. This is the mode that a Forth system is in after it starts
7545: up.
7546:
7547: @cindex input buffer
7548: @cindex terminal input buffer
7549: The text interpreter works from an area of memory called the @dfn{input
7550: buffer}@footnote{When the text interpreter is processing input from the
7551: keyboard, this area of memory is called the @dfn{terminal input buffer}
7552: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7553: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7554: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7555: leading spaces (called @dfn{delimiters}) then parses a string (a
7556: sequence of non-space characters) until it reaches either a space
7557: character or the end of the buffer. Having parsed a string, it makes two
7558: attempts to process it:
1.27 crook 7559:
1.29 crook 7560: @cindex dictionary
1.27 crook 7561: @itemize @bullet
7562: @item
1.29 crook 7563: It looks for the string in a @dfn{dictionary} of definitions. If the
7564: string is found, the string names a @dfn{definition} (also known as a
7565: @dfn{word}) and the dictionary search returns information that allows
7566: the text interpreter to perform the word's @dfn{interpretation
7567: semantics}. In most cases, this simply means that the word will be
7568: executed.
1.27 crook 7569: @item
7570: If the string is not found in the dictionary, the text interpreter
1.29 crook 7571: attempts to treat it as a number, using the rules described in
7572: @ref{Number Conversion}. If the string represents a legal number in the
7573: current radix, the number is pushed onto a parameter stack (the data
7574: stack for integers, the floating-point stack for floating-point
7575: numbers).
7576: @end itemize
7577:
7578: If both attempts fail, or if the word is found in the dictionary but has
7579: no interpretation semantics@footnote{This happens if the word was
7580: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7581: remainder of the input buffer, issues an error message and waits for
7582: more input. If one of the attempts succeeds, the text interpreter
7583: repeats the parsing process until the whole of the input buffer has been
7584: processed, at which point it prints the status message ``@code{ ok}''
7585: and waits for more input.
7586:
1.71 anton 7587: @c anton: this should be in the input stream subsection (or below it)
7588:
1.29 crook 7589: @cindex parse area
7590: The text interpreter keeps track of its position in the input buffer by
7591: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7592: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7593: of the input buffer. The region from offset @code{>IN @@} to the end of
7594: the input buffer is called the @dfn{parse area}@footnote{In other words,
7595: the text interpreter processes the contents of the input buffer by
7596: parsing strings from the parse area until the parse area is empty.}.
7597: This example shows how @code{>IN} changes as the text interpreter parses
7598: the input buffer:
7599:
7600: @example
7601: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7602: CR ." ->" TYPE ." <-" ; IMMEDIATE
7603:
7604: 1 2 3 remaining + remaining .
7605:
7606: : foo 1 2 3 remaining SWAP remaining ;
7607: @end example
7608:
7609: @noindent
7610: The result is:
7611:
7612: @example
7613: ->+ remaining .<-
7614: ->.<-5 ok
7615:
7616: ->SWAP remaining ;-<
7617: ->;<- ok
7618: @end example
7619:
7620: @cindex parsing words
7621: The value of @code{>IN} can also be modified by a word in the input
7622: buffer that is executed by the text interpreter. This means that a word
7623: can ``trick'' the text interpreter into either skipping a section of the
7624: input buffer@footnote{This is how parsing words work.} or into parsing a
7625: section twice. For example:
1.27 crook 7626:
1.29 crook 7627: @example
1.71 anton 7628: : lat ." <<foo>>" ;
7629: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7630: @end example
7631:
7632: @noindent
7633: When @code{flat} is executed, this output is produced@footnote{Exercise
7634: for the reader: what would happen if the @code{3} were replaced with
7635: @code{4}?}:
7636:
7637: @example
1.71 anton 7638: <<bar>><<foo>>
1.29 crook 7639: @end example
7640:
1.71 anton 7641: This technique can be used to work around some of the interoperability
7642: problems of parsing words. Of course, it's better to avoid parsing
7643: words where possible.
7644:
1.29 crook 7645: @noindent
7646: Two important notes about the behaviour of the text interpreter:
1.27 crook 7647:
7648: @itemize @bullet
7649: @item
7650: It processes each input string to completion before parsing additional
1.29 crook 7651: characters from the input buffer.
7652: @item
7653: It treats the input buffer as a read-only region (and so must your code).
7654: @end itemize
7655:
7656: @noindent
7657: When the text interpreter is in compile state, its behaviour changes in
7658: these ways:
7659:
7660: @itemize @bullet
7661: @item
7662: If a parsed string is found in the dictionary, the text interpreter will
7663: perform the word's @dfn{compilation semantics}. In most cases, this
7664: simply means that the execution semantics of the word will be appended
7665: to the current definition.
1.27 crook 7666: @item
1.29 crook 7667: When a number is encountered, it is compiled into the current definition
7668: (as a literal) rather than being pushed onto a parameter stack.
7669: @item
7670: If an error occurs, @code{state} is modified to put the text interpreter
7671: back into interpret state.
7672: @item
7673: Each time a line is entered from the keyboard, Gforth prints
7674: ``@code{ compiled}'' rather than `` @code{ok}''.
7675: @end itemize
7676:
7677: @cindex text interpreter - input sources
7678: When the text interpreter is using an input device other than the
7679: keyboard, its behaviour changes in these ways:
7680:
7681: @itemize @bullet
7682: @item
7683: When the parse area is empty, the text interpreter attempts to refill
7684: the input buffer from the input source. When the input source is
1.71 anton 7685: exhausted, the input source is set back to the previous input source.
1.29 crook 7686: @item
7687: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7688: time the parse area is emptied.
7689: @item
7690: If an error occurs, the input source is set back to the user input
7691: device.
1.27 crook 7692: @end itemize
1.21 crook 7693:
1.49 anton 7694: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7695:
1.26 crook 7696: doc->in
1.27 crook 7697: doc-source
7698:
1.26 crook 7699: doc-tib
7700: doc-#tib
1.1 anton 7701:
1.44 crook 7702:
1.26 crook 7703: @menu
1.67 anton 7704: * Input Sources::
7705: * Number Conversion::
7706: * Interpret/Compile states::
7707: * Interpreter Directives::
1.26 crook 7708: @end menu
1.1 anton 7709:
1.29 crook 7710: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7711: @subsection Input Sources
7712: @cindex input sources
7713: @cindex text interpreter - input sources
7714:
1.44 crook 7715: By default, the text interpreter processes input from the user input
1.29 crook 7716: device (the keyboard) when Forth starts up. The text interpreter can
7717: process input from any of these sources:
7718:
7719: @itemize @bullet
7720: @item
7721: The user input device -- the keyboard.
7722: @item
7723: A file, using the words described in @ref{Forth source files}.
7724: @item
7725: A block, using the words described in @ref{Blocks}.
7726: @item
7727: A text string, using @code{evaluate}.
7728: @end itemize
7729:
7730: A program can identify the current input device from the values of
7731: @code{source-id} and @code{blk}.
7732:
1.44 crook 7733:
1.29 crook 7734: doc-source-id
7735: doc-blk
7736:
7737: doc-save-input
7738: doc-restore-input
7739:
7740: doc-evaluate
1.111 anton 7741: doc-query
1.1 anton 7742:
1.29 crook 7743:
1.44 crook 7744:
1.29 crook 7745: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7746: @subsection Number Conversion
7747: @cindex number conversion
7748: @cindex double-cell numbers, input format
7749: @cindex input format for double-cell numbers
7750: @cindex single-cell numbers, input format
7751: @cindex input format for single-cell numbers
7752: @cindex floating-point numbers, input format
7753: @cindex input format for floating-point numbers
1.1 anton 7754:
1.29 crook 7755: This section describes the rules that the text interpreter uses when it
7756: tries to convert a string into a number.
1.1 anton 7757:
1.26 crook 7758: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7759: number base@footnote{For example, 0-9 when the number base is decimal or
7760: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7761:
1.26 crook 7762: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7763:
1.29 crook 7764: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7765: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7766:
1.26 crook 7767: Let * represent any number of instances of the previous character
7768: (including none).
1.1 anton 7769:
1.26 crook 7770: Let any other character represent itself.
1.1 anton 7771:
1.29 crook 7772: @noindent
1.26 crook 7773: Now, the conversion rules are:
1.21 crook 7774:
1.26 crook 7775: @itemize @bullet
7776: @item
7777: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7778: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7779: @item
7780: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7781: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7782: arithmetic. Examples are -45 -5681 -0
7783: @item
7784: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7785: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7786: (all three of these represent the same number).
1.26 crook 7787: @item
7788: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7789: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7790: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7791: -34.65 (all three of these represent the same number).
1.26 crook 7792: @item
1.29 crook 7793: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7794: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7795: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7796: number) +12.E-4
1.26 crook 7797: @end itemize
1.1 anton 7798:
1.174 anton 7799: By default, the number base used for integer number conversion is
7800: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7801: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7802: change @code{base} anywhere, make sure to save the old value and
7803: restore it afterwards; better yet, use @code{base-execute}, which does
7804: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7805: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7806:
1.29 crook 7807: doc-dpl
1.174 anton 7808: doc-base-execute
1.26 crook 7809: doc-base
7810: doc-hex
7811: doc-decimal
1.1 anton 7812:
1.26 crook 7813: @cindex '-prefix for character strings
7814: @cindex &-prefix for decimal numbers
1.133 anton 7815: @cindex #-prefix for decimal numbers
1.26 crook 7816: @cindex %-prefix for binary numbers
7817: @cindex $-prefix for hexadecimal numbers
1.133 anton 7818: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7819: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7820: prefix@footnote{Some Forth implementations provide a similar scheme by
7821: implementing @code{$} etc. as parsing words that process the subsequent
7822: number in the input stream and push it onto the stack. For example, see
7823: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7824: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7825: is required between the prefix and the number.} before the first digit
1.133 anton 7826: of an (integer) number. The following prefixes are supported:
1.1 anton 7827:
1.26 crook 7828: @itemize @bullet
7829: @item
1.35 anton 7830: @code{&} -- decimal
1.26 crook 7831: @item
1.133 anton 7832: @code{#} -- decimal
7833: @item
1.35 anton 7834: @code{%} -- binary
1.26 crook 7835: @item
1.35 anton 7836: @code{$} -- hexadecimal
1.26 crook 7837: @item
1.133 anton 7838: @code{0x} -- hexadecimal, if base<33.
7839: @item
7840: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7841: optional @code{'} may be present after the character.
1.26 crook 7842: @end itemize
1.1 anton 7843:
1.26 crook 7844: Here are some examples, with the equivalent decimal number shown after
7845: in braces:
1.1 anton 7846:
1.26 crook 7847: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7848: 'A (65),
7849: -'a' (-97),
1.26 crook 7850: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7851:
1.26 crook 7852: @cindex number conversion - traps for the unwary
1.29 crook 7853: @noindent
1.26 crook 7854: Number conversion has a number of traps for the unwary:
1.1 anton 7855:
1.26 crook 7856: @itemize @bullet
7857: @item
7858: You cannot determine the current number base using the code sequence
1.35 anton 7859: @code{base @@ .} -- the number base is always 10 in the current number
7860: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7861: @item
7862: If the number base is set to a value greater than 14 (for example,
7863: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7864: it to be intepreted as either a single-precision integer or a
7865: floating-point number (Gforth treats it as an integer). The ambiguity
7866: can be resolved by explicitly stating the sign of the mantissa and/or
7867: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7868: ambiguity arises; either representation will be treated as a
7869: floating-point number.
7870: @item
1.29 crook 7871: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7872: It is used to specify file types.
7873: @item
1.72 anton 7874: ANS Forth requires the @code{.} of a double-precision number to be the
7875: final character in the string. Gforth allows the @code{.} to be
7876: anywhere after the first digit.
1.26 crook 7877: @item
7878: The number conversion process does not check for overflow.
7879: @item
1.72 anton 7880: In an ANS Forth program @code{base} is required to be decimal when
7881: converting floating-point numbers. In Gforth, number conversion to
7882: floating-point numbers always uses base &10, irrespective of the value
7883: of @code{base}.
1.26 crook 7884: @end itemize
1.1 anton 7885:
1.49 anton 7886: You can read numbers into your programs with the words described in
1.181 anton 7887: @ref{Line input and conversion}.
1.1 anton 7888:
1.82 anton 7889: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7890: @subsection Interpret/Compile states
7891: @cindex Interpret/Compile states
1.1 anton 7892:
1.29 crook 7893: A standard program is not permitted to change @code{state}
7894: explicitly. However, it can change @code{state} implicitly, using the
7895: words @code{[} and @code{]}. When @code{[} is executed it switches
7896: @code{state} to interpret state, and therefore the text interpreter
7897: starts interpreting. When @code{]} is executed it switches @code{state}
7898: to compile state and therefore the text interpreter starts
1.44 crook 7899: compiling. The most common usage for these words is for switching into
7900: interpret state and back from within a colon definition; this technique
1.49 anton 7901: can be used to compile a literal (for an example, @pxref{Literals}) or
7902: for conditional compilation (for an example, @pxref{Interpreter
7903: Directives}).
1.44 crook 7904:
1.35 anton 7905:
7906: @c This is a bad example: It's non-standard, and it's not necessary.
7907: @c However, I can't think of a good example for switching into compile
7908: @c state when there is no current word (@code{state}-smart words are not a
7909: @c good reason). So maybe we should use an example for switching into
7910: @c interpret @code{state} in a colon def. - anton
1.44 crook 7911: @c nac-> I agree. I started out by putting in the example, then realised
7912: @c that it was non-ANS, so wrote more words around it. I hope this
7913: @c re-written version is acceptable to you. I do want to keep the example
7914: @c as it is helpful for showing what is and what is not portable, particularly
7915: @c where it outlaws a style in common use.
7916:
1.72 anton 7917: @c anton: it's more important to show what's portable. After we have done
1.83 anton 7918: @c that, we can also show what's not. In any case, I have written a
7919: @c section Compiling Words which also deals with [ ].
1.35 anton 7920:
1.95 anton 7921: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 7922:
1.95 anton 7923: @c @code{[} and @code{]} also give you the ability to switch into compile
7924: @c state and back, but we cannot think of any useful Standard application
7925: @c for this ability. Pre-ANS Forth textbooks have examples like this:
7926:
7927: @c @example
7928: @c : AA ." this is A" ;
7929: @c : BB ." this is B" ;
7930: @c : CC ." this is C" ;
7931:
7932: @c create table ] aa bb cc [
7933:
7934: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
7935: @c cells table + @@ execute ;
7936: @c @end example
7937:
7938: @c This example builds a jump table; @code{0 go} will display ``@code{this
7939: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
7940: @c defining @code{table} like this:
7941:
7942: @c @example
7943: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
7944: @c @end example
7945:
7946: @c The problem with this code is that the definition of @code{table} is not
7947: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
7948: @c @i{may} work on systems where code space and data space co-incide, the
7949: @c Standard only allows data space to be assigned for a @code{CREATE}d
7950: @c word. In addition, the Standard only allows @code{@@} to access data
7951: @c space, whilst this example is using it to access code space. The only
7952: @c portable, Standard way to build this table is to build it in data space,
7953: @c like this:
7954:
7955: @c @example
7956: @c create table ' aa , ' bb , ' cc ,
7957: @c @end example
1.29 crook 7958:
1.95 anton 7959: @c doc-state
1.44 crook 7960:
1.29 crook 7961:
1.82 anton 7962: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 7963: @subsection Interpreter Directives
7964: @cindex interpreter directives
1.72 anton 7965: @cindex conditional compilation
1.1 anton 7966:
1.29 crook 7967: These words are usually used in interpret state; typically to control
7968: which parts of a source file are processed by the text
1.26 crook 7969: interpreter. There are only a few ANS Forth Standard words, but Gforth
7970: supplements these with a rich set of immediate control structure words
7971: to compensate for the fact that the non-immediate versions can only be
1.29 crook 7972: used in compile state (@pxref{Control Structures}). Typical usages:
7973:
7974: @example
1.72 anton 7975: FALSE Constant HAVE-ASSEMBLER
1.29 crook 7976: .
7977: .
1.72 anton 7978: HAVE-ASSEMBLER [IF]
1.29 crook 7979: : ASSEMBLER-FEATURE
7980: ...
7981: ;
7982: [ENDIF]
7983: .
7984: .
7985: : SEE
7986: ... \ general-purpose SEE code
1.72 anton 7987: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 7988: ... \ assembler-specific SEE code
7989: [ [ENDIF] ]
7990: ;
7991: @end example
1.1 anton 7992:
1.44 crook 7993:
1.26 crook 7994: doc-[IF]
7995: doc-[ELSE]
7996: doc-[THEN]
7997: doc-[ENDIF]
1.1 anton 7998:
1.26 crook 7999: doc-[IFDEF]
8000: doc-[IFUNDEF]
1.1 anton 8001:
1.26 crook 8002: doc-[?DO]
8003: doc-[DO]
8004: doc-[FOR]
8005: doc-[LOOP]
8006: doc-[+LOOP]
8007: doc-[NEXT]
1.1 anton 8008:
1.26 crook 8009: doc-[BEGIN]
8010: doc-[UNTIL]
8011: doc-[AGAIN]
8012: doc-[WHILE]
8013: doc-[REPEAT]
1.1 anton 8014:
1.27 crook 8015:
1.26 crook 8016: @c -------------------------------------------------------------
1.111 anton 8017: @node The Input Stream, Word Lists, The Text Interpreter, Words
8018: @section The Input Stream
8019: @cindex input stream
8020:
8021: @c !! integrate this better with the "Text Interpreter" section
8022: The text interpreter reads from the input stream, which can come from
8023: several sources (@pxref{Input Sources}). Some words, in particular
8024: defining words, but also words like @code{'}, read parameters from the
8025: input stream instead of from the stack.
8026:
8027: Such words are called parsing words, because they parse the input
8028: stream. Parsing words are hard to use in other words, because it is
8029: hard to pass program-generated parameters through the input stream.
8030: They also usually have an unintuitive combination of interpretation and
8031: compilation semantics when implemented naively, leading to various
8032: approaches that try to produce a more intuitive behaviour
8033: (@pxref{Combined words}).
8034:
8035: It should be obvious by now that parsing words are a bad idea. If you
8036: want to implement a parsing word for convenience, also provide a factor
8037: of the word that does not parse, but takes the parameters on the stack.
8038: To implement the parsing word on top if it, you can use the following
8039: words:
8040:
8041: @c anton: these belong in the input stream section
8042: doc-parse
1.138 anton 8043: doc-parse-name
1.111 anton 8044: doc-parse-word
8045: doc-name
8046: doc-word
8047: doc-refill
8048:
8049: Conversely, if you have the bad luck (or lack of foresight) to have to
8050: deal with parsing words without having such factors, how do you pass a
8051: string that is not in the input stream to it?
8052:
8053: doc-execute-parsing
8054:
1.146 anton 8055: A definition of this word in ANS Forth is provided in
8056: @file{compat/execute-parsing.fs}.
8057:
1.111 anton 8058: If you want to run a parsing word on a file, the following word should
8059: help:
8060:
8061: doc-execute-parsing-file
8062:
8063: @c -------------------------------------------------------------
8064: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8065: @section Word Lists
8066: @cindex word lists
1.32 anton 8067: @cindex header space
1.1 anton 8068:
1.36 anton 8069: A wordlist is a list of named words; you can add new words and look up
8070: words by name (and you can remove words in a restricted way with
8071: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8072:
8073: @cindex search order stack
8074: The text interpreter searches the wordlists present in the search order
8075: (a stack of wordlists), from the top to the bottom. Within each
8076: wordlist, the search starts conceptually at the newest word; i.e., if
8077: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8078:
1.26 crook 8079: @cindex compilation word list
1.36 anton 8080: New words are added to the @dfn{compilation wordlist} (aka current
8081: wordlist).
1.1 anton 8082:
1.36 anton 8083: @cindex wid
8084: A word list is identified by a cell-sized word list identifier (@i{wid})
8085: in much the same way as a file is identified by a file handle. The
8086: numerical value of the wid has no (portable) meaning, and might change
8087: from session to session.
1.1 anton 8088:
1.29 crook 8089: The ANS Forth ``Search order'' word set is intended to provide a set of
8090: low-level tools that allow various different schemes to be
1.74 anton 8091: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8092: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8093: Forth.
1.1 anton 8094:
1.27 crook 8095: @comment TODO: locals section refers to here, saying that every word list (aka
8096: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8097: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8098:
1.45 crook 8099: @comment TODO: document markers, reveal, tables, mappedwordlist
8100:
8101: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8102: @comment word from the source files, rather than some alias.
1.44 crook 8103:
1.26 crook 8104: doc-forth-wordlist
8105: doc-definitions
8106: doc-get-current
8107: doc-set-current
8108: doc-get-order
1.185 anton 8109: doc-set-order
1.26 crook 8110: doc-wordlist
1.30 anton 8111: doc-table
1.79 anton 8112: doc->order
1.36 anton 8113: doc-previous
1.26 crook 8114: doc-also
1.185 anton 8115: doc-forth
1.26 crook 8116: doc-only
1.185 anton 8117: doc-order
1.15 anton 8118:
1.26 crook 8119: doc-find
8120: doc-search-wordlist
1.15 anton 8121:
1.26 crook 8122: doc-words
8123: doc-vlist
1.44 crook 8124: @c doc-words-deferred
1.1 anton 8125:
1.74 anton 8126: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8127: doc-root
8128: doc-vocabulary
8129: doc-seal
8130: doc-vocs
8131: doc-current
8132: doc-context
1.1 anton 8133:
1.44 crook 8134:
1.26 crook 8135: @menu
1.75 anton 8136: * Vocabularies::
1.67 anton 8137: * Why use word lists?::
1.75 anton 8138: * Word list example::
1.26 crook 8139: @end menu
8140:
1.75 anton 8141: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8142: @subsection Vocabularies
8143: @cindex Vocabularies, detailed explanation
8144:
8145: Here is an example of creating and using a new wordlist using ANS
8146: Forth words:
8147:
8148: @example
8149: wordlist constant my-new-words-wordlist
8150: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8151:
8152: \ add it to the search order
8153: also my-new-words
8154:
8155: \ alternatively, add it to the search order and make it
8156: \ the compilation word list
8157: also my-new-words definitions
8158: \ type "order" to see the problem
8159: @end example
8160:
8161: The problem with this example is that @code{order} has no way to
8162: associate the name @code{my-new-words} with the wid of the word list (in
8163: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8164: that has no associated name). There is no Standard way of associating a
8165: name with a wid.
8166:
8167: In Gforth, this example can be re-coded using @code{vocabulary}, which
8168: associates a name with a wid:
8169:
8170: @example
8171: vocabulary my-new-words
8172:
8173: \ add it to the search order
8174: also my-new-words
8175:
8176: \ alternatively, add it to the search order and make it
8177: \ the compilation word list
8178: my-new-words definitions
8179: \ type "order" to see that the problem is solved
8180: @end example
8181:
8182:
8183: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8184: @subsection Why use word lists?
8185: @cindex word lists - why use them?
8186:
1.74 anton 8187: Here are some reasons why people use wordlists:
1.26 crook 8188:
8189: @itemize @bullet
1.74 anton 8190:
8191: @c anton: Gforth's hashing implementation makes the search speed
8192: @c independent from the number of words. But it is linear with the number
8193: @c of wordlists that have to be searched, so in effect using more wordlists
8194: @c actually slows down compilation.
8195:
8196: @c @item
8197: @c To improve compilation speed by reducing the number of header space
8198: @c entries that must be searched. This is achieved by creating a new
8199: @c word list that contains all of the definitions that are used in the
8200: @c definition of a Forth system but which would not usually be used by
8201: @c programs running on that system. That word list would be on the search
8202: @c list when the Forth system was compiled but would be removed from the
8203: @c search list for normal operation. This can be a useful technique for
8204: @c low-performance systems (for example, 8-bit processors in embedded
8205: @c systems) but is unlikely to be necessary in high-performance desktop
8206: @c systems.
8207:
1.26 crook 8208: @item
8209: To prevent a set of words from being used outside the context in which
8210: they are valid. Two classic examples of this are an integrated editor
8211: (all of the edit commands are defined in a separate word list; the
8212: search order is set to the editor word list when the editor is invoked;
8213: the old search order is restored when the editor is terminated) and an
8214: integrated assembler (the op-codes for the machine are defined in a
8215: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8216:
8217: @item
8218: To organize the words of an application or library into a user-visible
8219: set (in @code{forth-wordlist} or some other common wordlist) and a set
8220: of helper words used just for the implementation (hidden in a separate
1.75 anton 8221: wordlist). This keeps @code{words}' output smaller, separates
8222: implementation and interface, and reduces the chance of name conflicts
8223: within the common wordlist.
1.74 anton 8224:
1.26 crook 8225: @item
8226: To prevent a name-space clash between multiple definitions with the same
8227: name. For example, when building a cross-compiler you might have a word
8228: @code{IF} that generates conditional code for your target system. By
8229: placing this definition in a different word list you can control whether
8230: the host system's @code{IF} or the target system's @code{IF} get used in
8231: any particular context by controlling the order of the word lists on the
8232: search order stack.
1.74 anton 8233:
1.26 crook 8234: @end itemize
1.1 anton 8235:
1.74 anton 8236: The downsides of using wordlists are:
8237:
8238: @itemize
8239:
8240: @item
8241: Debugging becomes more cumbersome.
8242:
8243: @item
8244: Name conflicts worked around with wordlists are still there, and you
8245: have to arrange the search order carefully to get the desired results;
8246: if you forget to do that, you get hard-to-find errors (as in any case
8247: where you read the code differently from the compiler; @code{see} can
1.75 anton 8248: help seeing which of several possible words the name resolves to in such
8249: cases). @code{See} displays just the name of the words, not what
8250: wordlist they belong to, so it might be misleading. Using unique names
8251: is a better approach to avoid name conflicts.
1.74 anton 8252:
8253: @item
8254: You have to explicitly undo any changes to the search order. In many
8255: cases it would be more convenient if this happened implicitly. Gforth
8256: currently does not provide such a feature, but it may do so in the
8257: future.
8258: @end itemize
8259:
8260:
1.75 anton 8261: @node Word list example, , Why use word lists?, Word Lists
8262: @subsection Word list example
8263: @cindex word lists - example
1.1 anton 8264:
1.74 anton 8265: The following example is from the
8266: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8267: garbage collector} and uses wordlists to separate public words from
8268: helper words:
8269:
8270: @example
8271: get-current ( wid )
8272: vocabulary garbage-collector also garbage-collector definitions
8273: ... \ define helper words
8274: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8275: ... \ define the public (i.e., API) words
8276: \ they can refer to the helper words
8277: previous \ restore original search order (helper words become invisible)
8278: @end example
8279:
1.26 crook 8280: @c -------------------------------------------------------------
8281: @node Environmental Queries, Files, Word Lists, Words
8282: @section Environmental Queries
8283: @cindex environmental queries
1.21 crook 8284:
1.26 crook 8285: ANS Forth introduced the idea of ``environmental queries'' as a way
8286: for a program running on a system to determine certain characteristics of the system.
8287: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8288:
1.32 anton 8289: The Standard requires that the header space used for environmental queries
8290: be distinct from the header space used for definitions.
1.21 crook 8291:
1.26 crook 8292: Typically, environmental queries are supported by creating a set of
1.29 crook 8293: definitions in a word list that is @i{only} used during environmental
1.26 crook 8294: queries; that is what Gforth does. There is no Standard way of adding
8295: definitions to the set of recognised environmental queries, but any
8296: implementation that supports the loading of optional word sets must have
8297: some mechanism for doing this (after loading the word set, the
8298: associated environmental query string must return @code{true}). In
8299: Gforth, the word list used to honour environmental queries can be
8300: manipulated just like any other word list.
1.21 crook 8301:
1.44 crook 8302:
1.26 crook 8303: doc-environment?
8304: doc-environment-wordlist
1.21 crook 8305:
1.26 crook 8306: doc-gforth
8307: doc-os-class
1.21 crook 8308:
1.44 crook 8309:
1.26 crook 8310: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8311: returning two items on the stack, querying it using @code{environment?}
8312: will return an additional item; the @code{true} flag that shows that the
8313: string was recognised.
1.21 crook 8314:
1.26 crook 8315: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8316:
1.26 crook 8317: Here are some examples of using environmental queries:
1.21 crook 8318:
1.26 crook 8319: @example
8320: s" address-unit-bits" environment? 0=
8321: [IF]
8322: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8323: [ELSE]
8324: drop \ ensure balanced stack effect
1.26 crook 8325: [THEN]
1.21 crook 8326:
1.75 anton 8327: \ this might occur in the prelude of a standard program that uses THROW
8328: s" exception" environment? [IF]
8329: 0= [IF]
8330: : throw abort" exception thrown" ;
8331: [THEN]
8332: [ELSE] \ we don't know, so make sure
8333: : throw abort" exception thrown" ;
8334: [THEN]
1.21 crook 8335:
1.26 crook 8336: s" gforth" environment? [IF] .( Gforth version ) TYPE
8337: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8338:
8339: \ a program using v*
8340: s" gforth" environment? [IF]
8341: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8342: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8343: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8344: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8345: LOOP
8346: 2drop 2drop ;
8347: [THEN]
8348: [ELSE] \
8349: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8350: ...
8351: [THEN]
1.26 crook 8352: @end example
1.21 crook 8353:
1.26 crook 8354: Here is an example of adding a definition to the environment word list:
1.21 crook 8355:
1.26 crook 8356: @example
8357: get-current environment-wordlist set-current
8358: true constant block
8359: true constant block-ext
8360: set-current
8361: @end example
1.21 crook 8362:
1.26 crook 8363: You can see what definitions are in the environment word list like this:
1.21 crook 8364:
1.26 crook 8365: @example
1.79 anton 8366: environment-wordlist >order words previous
1.26 crook 8367: @end example
1.21 crook 8368:
8369:
1.26 crook 8370: @c -------------------------------------------------------------
8371: @node Files, Blocks, Environmental Queries, Words
8372: @section Files
1.28 crook 8373: @cindex files
8374: @cindex I/O - file-handling
1.21 crook 8375:
1.26 crook 8376: Gforth provides facilities for accessing files that are stored in the
8377: host operating system's file-system. Files that are processed by Gforth
8378: can be divided into two categories:
1.21 crook 8379:
1.23 crook 8380: @itemize @bullet
8381: @item
1.29 crook 8382: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8383: @item
1.29 crook 8384: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8385: @end itemize
8386:
8387: @menu
1.48 anton 8388: * Forth source files::
8389: * General files::
1.167 anton 8390: * Redirection::
1.48 anton 8391: * Search Paths::
1.26 crook 8392: @end menu
8393:
8394: @c -------------------------------------------------------------
8395: @node Forth source files, General files, Files, Files
8396: @subsection Forth source files
8397: @cindex including files
8398: @cindex Forth source files
1.21 crook 8399:
1.26 crook 8400: The simplest way to interpret the contents of a file is to use one of
8401: these two formats:
1.21 crook 8402:
1.26 crook 8403: @example
8404: include mysource.fs
8405: s" mysource.fs" included
8406: @end example
1.21 crook 8407:
1.75 anton 8408: You usually want to include a file only if it is not included already
1.26 crook 8409: (by, say, another source file). In that case, you can use one of these
1.45 crook 8410: three formats:
1.21 crook 8411:
1.26 crook 8412: @example
8413: require mysource.fs
8414: needs mysource.fs
8415: s" mysource.fs" required
8416: @end example
1.21 crook 8417:
1.26 crook 8418: @cindex stack effect of included files
8419: @cindex including files, stack effect
1.45 crook 8420: It is good practice to write your source files such that interpreting them
8421: does not change the stack. Source files designed in this way can be used with
1.26 crook 8422: @code{required} and friends without complications. For example:
1.21 crook 8423:
1.26 crook 8424: @example
1.75 anton 8425: 1024 require foo.fs drop
1.26 crook 8426: @end example
1.21 crook 8427:
1.75 anton 8428: Here you want to pass the argument 1024 (e.g., a buffer size) to
8429: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8430: ), which allows its use with @code{require}. Of course with such
8431: parameters to required files, you have to ensure that the first
8432: @code{require} fits for all uses (i.e., @code{require} it early in the
8433: master load file).
1.44 crook 8434:
1.26 crook 8435: doc-include-file
8436: doc-included
1.28 crook 8437: doc-included?
1.26 crook 8438: doc-include
8439: doc-required
8440: doc-require
8441: doc-needs
1.75 anton 8442: @c doc-init-included-files @c internal
8443: doc-sourcefilename
8444: doc-sourceline#
1.44 crook 8445:
1.26 crook 8446: A definition in ANS Forth for @code{required} is provided in
8447: @file{compat/required.fs}.
1.21 crook 8448:
1.26 crook 8449: @c -------------------------------------------------------------
1.167 anton 8450: @node General files, Redirection, Forth source files, Files
1.26 crook 8451: @subsection General files
8452: @cindex general files
8453: @cindex file-handling
1.21 crook 8454:
1.75 anton 8455: Files are opened/created by name and type. The following file access
8456: methods (FAMs) are recognised:
1.44 crook 8457:
1.75 anton 8458: @cindex fam (file access method)
1.26 crook 8459: doc-r/o
8460: doc-r/w
8461: doc-w/o
8462: doc-bin
1.1 anton 8463:
1.44 crook 8464:
1.26 crook 8465: When a file is opened/created, it returns a file identifier,
1.29 crook 8466: @i{wfileid} that is used for all other file commands. All file
8467: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8468: successful operation and an implementation-defined non-zero value in the
8469: case of an error.
1.21 crook 8470:
1.44 crook 8471:
1.26 crook 8472: doc-open-file
8473: doc-create-file
1.21 crook 8474:
1.26 crook 8475: doc-close-file
8476: doc-delete-file
8477: doc-rename-file
8478: doc-read-file
8479: doc-read-line
1.154 anton 8480: doc-key-file
8481: doc-key?-file
1.26 crook 8482: doc-write-file
8483: doc-write-line
8484: doc-emit-file
8485: doc-flush-file
1.21 crook 8486:
1.26 crook 8487: doc-file-status
8488: doc-file-position
8489: doc-reposition-file
8490: doc-file-size
8491: doc-resize-file
1.21 crook 8492:
1.93 anton 8493: doc-slurp-file
8494: doc-slurp-fid
1.112 anton 8495: doc-stdin
8496: doc-stdout
8497: doc-stderr
1.44 crook 8498:
1.26 crook 8499: @c ---------------------------------------------------------
1.167 anton 8500: @node Redirection, Search Paths, General files, Files
8501: @subsection Redirection
8502: @cindex Redirection
8503: @cindex Input Redirection
8504: @cindex Output Redirection
8505:
8506: You can redirect the output of @code{type} and @code{emit} and all the
8507: words that use them (all output words that don't have an explicit
1.174 anton 8508: target file) to an arbitrary file with the @code{outfile-execute},
8509: used like this:
1.167 anton 8510:
8511: @example
1.174 anton 8512: : some-warning ( n -- )
8513: cr ." warning# " . ;
8514:
1.167 anton 8515: : print-some-warning ( n -- )
1.174 anton 8516: ['] some-warning stderr outfile-execute ;
1.167 anton 8517: @end example
8518:
1.174 anton 8519: After @code{some-warning} is executed, the original output direction
8520: is restored; this construct is safe against exceptions. Similarly,
8521: there is @code{infile-execute} for redirecting the input of @code{key}
8522: and its users (any input word that does not take a file explicitly).
8523:
8524: doc-outfile-execute
8525: doc-infile-execute
1.167 anton 8526:
8527: If you do not want to redirect the input or output to a file, you can
8528: also make use of the fact that @code{key}, @code{emit} and @code{type}
8529: are deferred words (@pxref{Deferred Words}). However, in that case
8530: you have to worry about the restoration and the protection against
8531: exceptions yourself; also, note that for redirecting the output in
8532: this way, you have to redirect both @code{emit} and @code{type}.
8533:
8534: @c ---------------------------------------------------------
8535: @node Search Paths, , Redirection, Files
1.26 crook 8536: @subsection Search Paths
8537: @cindex path for @code{included}
8538: @cindex file search path
8539: @cindex @code{include} search path
8540: @cindex search path for files
1.21 crook 8541:
1.26 crook 8542: If you specify an absolute filename (i.e., a filename starting with
8543: @file{/} or @file{~}, or with @file{:} in the second position (as in
8544: @samp{C:...})) for @code{included} and friends, that file is included
8545: just as you would expect.
1.21 crook 8546:
1.75 anton 8547: If the filename starts with @file{./}, this refers to the directory that
8548: the present file was @code{included} from. This allows files to include
8549: other files relative to their own position (irrespective of the current
8550: working directory or the absolute position). This feature is essential
8551: for libraries consisting of several files, where a file may include
8552: other files from the library. It corresponds to @code{#include "..."}
8553: in C. If the current input source is not a file, @file{.} refers to the
8554: directory of the innermost file being included, or, if there is no file
8555: being included, to the current working directory.
8556:
8557: For relative filenames (not starting with @file{./}), Gforth uses a
8558: search path similar to Forth's search order (@pxref{Word Lists}). It
8559: tries to find the given filename in the directories present in the path,
8560: and includes the first one it finds. There are separate search paths for
8561: Forth source files and general files. If the search path contains the
8562: directory @file{.}, this refers to the directory of the current file, or
8563: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8564:
1.26 crook 8565: Use @file{~+} to refer to the current working directory (as in the
8566: @code{bash}).
1.1 anton 8567:
1.75 anton 8568: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8569:
1.48 anton 8570: @menu
1.75 anton 8571: * Source Search Paths::
1.48 anton 8572: * General Search Paths::
8573: @end menu
8574:
1.26 crook 8575: @c ---------------------------------------------------------
1.75 anton 8576: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8577: @subsubsection Source Search Paths
8578: @cindex search path control, source files
1.5 anton 8579:
1.26 crook 8580: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8581: Gforth}). You can display it and change it using @code{fpath} in
8582: combination with the general path handling words.
1.5 anton 8583:
1.75 anton 8584: doc-fpath
8585: @c the functionality of the following words is easily available through
8586: @c fpath and the general path words. The may go away.
8587: @c doc-.fpath
8588: @c doc-fpath+
8589: @c doc-fpath=
8590: @c doc-open-fpath-file
1.44 crook 8591:
8592: @noindent
1.26 crook 8593: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8594:
1.26 crook 8595: @example
1.75 anton 8596: fpath path= /usr/lib/forth/|./
1.26 crook 8597: require timer.fs
8598: @end example
1.5 anton 8599:
1.75 anton 8600:
1.26 crook 8601: @c ---------------------------------------------------------
1.75 anton 8602: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8603: @subsubsection General Search Paths
1.75 anton 8604: @cindex search path control, source files
1.5 anton 8605:
1.26 crook 8606: Your application may need to search files in several directories, like
8607: @code{included} does. To facilitate this, Gforth allows you to define
8608: and use your own search paths, by providing generic equivalents of the
8609: Forth search path words:
1.5 anton 8610:
1.75 anton 8611: doc-open-path-file
8612: doc-path-allot
8613: doc-clear-path
8614: doc-also-path
1.26 crook 8615: doc-.path
8616: doc-path+
8617: doc-path=
1.5 anton 8618:
1.75 anton 8619: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8620:
1.75 anton 8621: Here's an example of creating an empty search path:
8622: @c
1.26 crook 8623: @example
1.75 anton 8624: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8625: @end example
1.5 anton 8626:
1.26 crook 8627: @c -------------------------------------------------------------
8628: @node Blocks, Other I/O, Files, Words
8629: @section Blocks
1.28 crook 8630: @cindex I/O - blocks
8631: @cindex blocks
8632:
8633: When you run Gforth on a modern desk-top computer, it runs under the
8634: control of an operating system which provides certain services. One of
8635: these services is @var{file services}, which allows Forth source code
8636: and data to be stored in files and read into Gforth (@pxref{Files}).
8637:
8638: Traditionally, Forth has been an important programming language on
8639: systems where it has interfaced directly to the underlying hardware with
8640: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8641: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8642:
8643: A block is a 1024-byte data area, which can be used to hold data or
8644: Forth source code. No structure is imposed on the contents of the
8645: block. A block is identified by its number; blocks are numbered
8646: contiguously from 1 to an implementation-defined maximum.
8647:
8648: A typical system that used blocks but no operating system might use a
8649: single floppy-disk drive for mass storage, with the disks formatted to
8650: provide 256-byte sectors. Blocks would be implemented by assigning the
8651: first four sectors of the disk to block 1, the second four sectors to
8652: block 2 and so on, up to the limit of the capacity of the disk. The disk
8653: would not contain any file system information, just the set of blocks.
8654:
1.29 crook 8655: @cindex blocks file
1.28 crook 8656: On systems that do provide file services, blocks are typically
1.29 crook 8657: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8658: file}. The size of the blocks file will be an exact multiple of 1024
8659: bytes, corresponding to the number of blocks it contains. This is the
8660: mechanism that Gforth uses.
8661:
1.29 crook 8662: @cindex @file{blocks.fb}
1.75 anton 8663: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8664: having specified a blocks file, Gforth defaults to the blocks file
8665: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8666: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8667:
1.29 crook 8668: @cindex block buffers
1.28 crook 8669: When you read and write blocks under program control, Gforth uses a
1.29 crook 8670: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8671: not used when you use @code{load} to interpret the contents of a block.
8672:
1.75 anton 8673: The behaviour of the block buffers is analagous to that of a cache.
8674: Each block buffer has three states:
1.28 crook 8675:
8676: @itemize @bullet
8677: @item
8678: Unassigned
8679: @item
8680: Assigned-clean
8681: @item
8682: Assigned-dirty
8683: @end itemize
8684:
1.29 crook 8685: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8686: block, the block (specified by its block number) must be assigned to a
8687: block buffer.
8688:
8689: The assignment of a block to a block buffer is performed by @code{block}
8690: or @code{buffer}. Use @code{block} when you wish to modify the existing
8691: contents of a block. Use @code{buffer} when you don't care about the
8692: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8693: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8694: with the particular block is already stored in a block buffer due to an
8695: earlier @code{block} command, @code{buffer} will return that block
8696: buffer and the existing contents of the block will be
8697: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8698: block buffer for the block.}.
1.28 crook 8699:
1.47 crook 8700: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8701: @code{buffer}, that block buffer becomes the @i{current block
8702: buffer}. Data may only be manipulated (read or written) within the
8703: current block buffer.
1.47 crook 8704:
8705: When the contents of the current block buffer has been modified it is
1.48 anton 8706: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8707: either abandon the changes (by doing nothing) or mark the block as
8708: changed (assigned-dirty), using @code{update}. Using @code{update} does
8709: not change the blocks file; it simply changes a block buffer's state to
8710: @i{assigned-dirty}. The block will be written implicitly when it's
8711: buffer is needed for another block, or explicitly by @code{flush} or
8712: @code{save-buffers}.
8713:
8714: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8715: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8716: @code{flush}.
1.28 crook 8717:
1.29 crook 8718: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8719: algorithm to assign a block buffer to a block. That means that any
8720: particular block can only be assigned to one specific block buffer,
1.29 crook 8721: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8722: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8723: the new block immediately. If it is @i{assigned-dirty} its current
8724: contents are written back to the blocks file on disk before it is
1.28 crook 8725: allocated to the new block.
8726:
8727: Although no structure is imposed on the contents of a block, it is
8728: traditional to display the contents as 16 lines each of 64 characters. A
8729: block provides a single, continuous stream of input (for example, it
8730: acts as a single parse area) -- there are no end-of-line characters
8731: within a block, and no end-of-file character at the end of a
8732: block. There are two consequences of this:
1.26 crook 8733:
1.28 crook 8734: @itemize @bullet
8735: @item
8736: The last character of one line wraps straight into the first character
8737: of the following line
8738: @item
8739: The word @code{\} -- comment to end of line -- requires special
8740: treatment; in the context of a block it causes all characters until the
8741: end of the current 64-character ``line'' to be ignored.
8742: @end itemize
8743:
8744: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8745: the current blocks file will be extended to the appropriate size and the
1.28 crook 8746: block buffer will be initialised with spaces.
8747:
1.47 crook 8748: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8749: for details) but doesn't encourage the use of blocks; the mechanism is
8750: only provided for backward compatibility -- ANS Forth requires blocks to
8751: be available when files are.
1.28 crook 8752:
8753: Common techniques that are used when working with blocks include:
8754:
8755: @itemize @bullet
8756: @item
8757: A screen editor that allows you to edit blocks without leaving the Forth
8758: environment.
8759: @item
8760: Shadow screens; where every code block has an associated block
8761: containing comments (for example: code in odd block numbers, comments in
8762: even block numbers). Typically, the block editor provides a convenient
8763: mechanism to toggle between code and comments.
8764: @item
8765: Load blocks; a single block (typically block 1) contains a number of
8766: @code{thru} commands which @code{load} the whole of the application.
8767: @end itemize
1.26 crook 8768:
1.29 crook 8769: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8770: integrated into a Forth programming environment.
1.26 crook 8771:
8772: @comment TODO what about errors on open-blocks?
1.44 crook 8773:
1.26 crook 8774: doc-open-blocks
8775: doc-use
1.75 anton 8776: doc-block-offset
1.26 crook 8777: doc-get-block-fid
8778: doc-block-position
1.28 crook 8779:
1.75 anton 8780: doc-list
1.28 crook 8781: doc-scr
8782:
1.184 anton 8783: doc-block
1.28 crook 8784: doc-buffer
8785:
1.75 anton 8786: doc-empty-buffers
8787: doc-empty-buffer
1.26 crook 8788: doc-update
1.28 crook 8789: doc-updated?
1.26 crook 8790: doc-save-buffers
1.75 anton 8791: doc-save-buffer
1.26 crook 8792: doc-flush
1.28 crook 8793:
1.26 crook 8794: doc-load
8795: doc-thru
8796: doc-+load
8797: doc-+thru
1.45 crook 8798: doc---gforthman--->
1.26 crook 8799: doc-block-included
8800:
1.44 crook 8801:
1.26 crook 8802: @c -------------------------------------------------------------
1.126 pazsan 8803: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8804: @section Other I/O
1.28 crook 8805: @cindex I/O - keyboard and display
1.26 crook 8806:
8807: @menu
8808: * Simple numeric output:: Predefined formats
8809: * Formatted numeric output:: Formatted (pictured) output
8810: * String Formats:: How Forth stores strings in memory
1.67 anton 8811: * Displaying characters and strings:: Other stuff
1.175 anton 8812: * Terminal output:: Cursor positioning etc.
1.181 anton 8813: * Single-key input::
8814: * Line input and conversion::
1.112 anton 8815: * Pipes:: How to create your own pipes
1.149 pazsan 8816: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8817: @end menu
8818:
8819: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8820: @subsection Simple numeric output
1.28 crook 8821: @cindex numeric output - simple/free-format
1.5 anton 8822:
1.26 crook 8823: The simplest output functions are those that display numbers from the
8824: data or floating-point stacks. Floating-point output is always displayed
8825: using base 10. Numbers displayed from the data stack use the value stored
8826: in @code{base}.
1.5 anton 8827:
1.44 crook 8828:
1.26 crook 8829: doc-.
8830: doc-dec.
8831: doc-hex.
8832: doc-u.
8833: doc-.r
8834: doc-u.r
8835: doc-d.
8836: doc-ud.
8837: doc-d.r
8838: doc-ud.r
8839: doc-f.
8840: doc-fe.
8841: doc-fs.
1.111 anton 8842: doc-f.rdp
1.44 crook 8843:
1.26 crook 8844: Examples of printing the number 1234.5678E23 in the different floating-point output
8845: formats are shown below:
1.5 anton 8846:
8847: @example
1.26 crook 8848: f. 123456779999999000000000000.
8849: fe. 123.456779999999E24
8850: fs. 1.23456779999999E26
1.5 anton 8851: @end example
8852:
8853:
1.26 crook 8854: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8855: @subsection Formatted numeric output
1.28 crook 8856: @cindex formatted numeric output
1.26 crook 8857: @cindex pictured numeric output
1.28 crook 8858: @cindex numeric output - formatted
1.26 crook 8859:
1.29 crook 8860: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8861: output} for formatted printing of integers. In this technique, digits
8862: are extracted from the number (using the current output radix defined by
8863: @code{base}), converted to ASCII codes and appended to a string that is
8864: built in a scratch-pad area of memory (@pxref{core-idef,
8865: Implementation-defined options, Implementation-defined
8866: options}). Arbitrary characters can be appended to the string during the
8867: extraction process. The completed string is specified by an address
8868: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8869: under program control.
1.5 anton 8870:
1.75 anton 8871: All of the integer output words described in the previous section
8872: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8873: numeric output.
1.5 anton 8874:
1.47 crook 8875: Three important things to remember about pictured numeric output:
1.5 anton 8876:
1.26 crook 8877: @itemize @bullet
8878: @item
1.28 crook 8879: It always operates on double-precision numbers; to display a
1.49 anton 8880: single-precision number, convert it first (for ways of doing this
8881: @pxref{Double precision}).
1.26 crook 8882: @item
1.28 crook 8883: It always treats the double-precision number as though it were
8884: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8885: @item
8886: The string is built up from right to left; least significant digit first.
8887: @end itemize
1.5 anton 8888:
1.44 crook 8889:
1.26 crook 8890: doc-<#
1.47 crook 8891: doc-<<#
1.26 crook 8892: doc-#
8893: doc-#s
8894: doc-hold
8895: doc-sign
8896: doc-#>
1.47 crook 8897: doc-#>>
1.5 anton 8898:
1.26 crook 8899: doc-represent
1.111 anton 8900: doc-f>str-rdp
8901: doc-f>buf-rdp
1.5 anton 8902:
1.44 crook 8903:
8904: @noindent
1.26 crook 8905: Here are some examples of using pictured numeric output:
1.5 anton 8906:
8907: @example
1.26 crook 8908: : my-u. ( u -- )
8909: \ Simplest use of pns.. behaves like Standard u.
8910: 0 \ convert to unsigned double
1.75 anton 8911: <<# \ start conversion
1.26 crook 8912: #s \ convert all digits
8913: #> \ complete conversion
1.75 anton 8914: TYPE SPACE \ display, with trailing space
8915: #>> ; \ release hold area
1.5 anton 8916:
1.26 crook 8917: : cents-only ( u -- )
8918: 0 \ convert to unsigned double
1.75 anton 8919: <<# \ start conversion
1.26 crook 8920: # # \ convert two least-significant digits
8921: #> \ complete conversion, discard other digits
1.75 anton 8922: TYPE SPACE \ display, with trailing space
8923: #>> ; \ release hold area
1.5 anton 8924:
1.26 crook 8925: : dollars-and-cents ( u -- )
8926: 0 \ convert to unsigned double
1.75 anton 8927: <<# \ start conversion
1.26 crook 8928: # # \ convert two least-significant digits
8929: [char] . hold \ insert decimal point
8930: #s \ convert remaining digits
8931: [char] $ hold \ append currency symbol
8932: #> \ complete conversion
1.75 anton 8933: TYPE SPACE \ display, with trailing space
8934: #>> ; \ release hold area
1.5 anton 8935:
1.26 crook 8936: : my-. ( n -- )
8937: \ handling negatives.. behaves like Standard .
8938: s>d \ convert to signed double
8939: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8940: <<# \ start conversion
1.26 crook 8941: #s \ convert all digits
8942: rot sign \ get at sign byte, append "-" if needed
8943: #> \ complete conversion
1.75 anton 8944: TYPE SPACE \ display, with trailing space
8945: #>> ; \ release hold area
1.5 anton 8946:
1.26 crook 8947: : account. ( n -- )
1.75 anton 8948: \ accountants don't like minus signs, they use parentheses
1.26 crook 8949: \ for negative numbers
8950: s>d \ convert to signed double
8951: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 8952: <<# \ start conversion
1.26 crook 8953: 2 pick \ get copy of sign byte
8954: 0< IF [char] ) hold THEN \ right-most character of output
8955: #s \ convert all digits
8956: rot \ get at sign byte
8957: 0< IF [char] ( hold THEN
8958: #> \ complete conversion
1.75 anton 8959: TYPE SPACE \ display, with trailing space
8960: #>> ; \ release hold area
8961:
1.5 anton 8962: @end example
8963:
1.26 crook 8964: Here are some examples of using these words:
1.5 anton 8965:
8966: @example
1.26 crook 8967: 1 my-u. 1
8968: hex -1 my-u. decimal FFFFFFFF
8969: 1 cents-only 01
8970: 1234 cents-only 34
8971: 2 dollars-and-cents $0.02
8972: 1234 dollars-and-cents $12.34
8973: 123 my-. 123
8974: -123 my. -123
8975: 123 account. 123
8976: -456 account. (456)
1.5 anton 8977: @end example
8978:
8979:
1.26 crook 8980: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
8981: @subsection String Formats
1.27 crook 8982: @cindex strings - see character strings
8983: @cindex character strings - formats
1.28 crook 8984: @cindex I/O - see character strings
1.75 anton 8985: @cindex counted strings
8986:
8987: @c anton: this does not really belong here; maybe the memory section,
8988: @c or the principles chapter
1.26 crook 8989:
1.27 crook 8990: Forth commonly uses two different methods for representing character
8991: strings:
1.26 crook 8992:
8993: @itemize @bullet
8994: @item
8995: @cindex address of counted string
1.45 crook 8996: @cindex counted string
1.29 crook 8997: As a @dfn{counted string}, represented by a @i{c-addr}. The char
8998: addressed by @i{c-addr} contains a character-count, @i{n}, of the
8999: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9000: memory.
9001: @item
1.29 crook 9002: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9003: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9004: first byte of the string.
9005: @end itemize
9006:
9007: ANS Forth encourages the use of the second format when representing
1.75 anton 9008: strings.
1.26 crook 9009:
1.44 crook 9010:
1.26 crook 9011: doc-count
9012:
1.44 crook 9013:
1.49 anton 9014: For words that move, copy and search for strings see @ref{Memory
9015: Blocks}. For words that display characters and strings see
9016: @ref{Displaying characters and strings}.
1.26 crook 9017:
1.175 anton 9018: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9019: @subsection Displaying characters and strings
1.27 crook 9020: @cindex characters - compiling and displaying
9021: @cindex character strings - compiling and displaying
1.26 crook 9022:
9023: This section starts with a glossary of Forth words and ends with a set
9024: of examples.
9025:
9026: doc-bl
9027: doc-space
9028: doc-spaces
9029: doc-emit
9030: doc-toupper
9031: doc-."
9032: doc-.(
1.98 anton 9033: doc-.\"
1.26 crook 9034: doc-type
1.44 crook 9035: doc-typewhite
1.26 crook 9036: doc-cr
1.27 crook 9037: @cindex cursor control
1.26 crook 9038: doc-s"
1.98 anton 9039: doc-s\"
1.26 crook 9040: doc-c"
9041: doc-char
9042: doc-[char]
9043:
1.44 crook 9044:
9045: @noindent
1.26 crook 9046: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9047:
9048: @example
1.26 crook 9049: .( text-1)
9050: : my-word
9051: ." text-2" cr
9052: .( text-3)
9053: ;
9054:
9055: ." text-4"
9056:
9057: : my-char
9058: [char] ALPHABET emit
9059: char emit
9060: ;
1.5 anton 9061: @end example
9062:
1.26 crook 9063: When you load this code into Gforth, the following output is generated:
1.5 anton 9064:
1.26 crook 9065: @example
1.30 anton 9066: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9067: @end example
1.5 anton 9068:
1.26 crook 9069: @itemize @bullet
9070: @item
9071: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9072: is an immediate word; it behaves in the same way whether it is used inside
9073: or outside a colon definition.
9074: @item
9075: Message @code{text-4} is displayed because of Gforth's added interpretation
9076: semantics for @code{."}.
9077: @item
1.29 crook 9078: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9079: performs the compilation semantics for @code{."} within the definition of
9080: @code{my-word}.
9081: @end itemize
1.5 anton 9082:
1.26 crook 9083: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9084:
1.26 crook 9085: @example
1.30 anton 9086: @kbd{my-word @key{RET}} text-2
1.26 crook 9087: ok
1.30 anton 9088: @kbd{my-char fred @key{RET}} Af ok
9089: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9090: @end example
1.5 anton 9091:
9092: @itemize @bullet
9093: @item
1.26 crook 9094: Message @code{text-2} is displayed because of the run-time behaviour of
9095: @code{."}.
9096: @item
9097: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9098: on the stack at run-time. @code{emit} always displays the character
9099: when @code{my-char} is executed.
9100: @item
9101: @code{char} parses a string at run-time and the second @code{emit} displays
9102: the first character of the string.
1.5 anton 9103: @item
1.26 crook 9104: If you type @code{see my-char} you can see that @code{[char]} discarded
9105: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9106: definition of @code{my-char}.
1.5 anton 9107: @end itemize
9108:
9109:
1.181 anton 9110: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9111: @subsection Terminal output
9112: @cindex output to terminal
9113: @cindex terminal output
9114:
9115: If you are outputting to a terminal, you may want to control the
9116: positioning of the cursor:
9117: @cindex cursor positioning
9118:
9119: doc-at-xy
9120:
9121: In order to know where to position the cursor, it is often helpful to
9122: know the size of the screen:
9123: @cindex terminal size
9124:
9125: doc-form
9126:
9127: And sometimes you want to use:
9128: @cindex clear screen
9129:
9130: doc-page
9131:
9132: Note that on non-terminals you should use @code{12 emit}, not
9133: @code{page}, to get a form feed.
9134:
1.5 anton 9135:
1.181 anton 9136: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9137: @subsection Single-key input
9138: @cindex single-key input
9139: @cindex input, single-key
9140:
9141: If you want to get a single printable character, you can use
9142: @code{key}; to check whether a character is available for @code{key},
9143: you can use @code{key?}.
1.5 anton 9144:
1.181 anton 9145: doc-key
9146: doc-key?
1.27 crook 9147:
1.181 anton 9148: If you want to process a mix of printable and non-printable
9149: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9150: produces a keyboard event that you have to convert into a character
9151: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9152:
9153: Typical code for using EKEY looks like this:
9154:
9155: @example
9156: ekey ekey>char if ( c )
9157: ... \ do something with the character
9158: else ekey>fkey if ( key-id )
9159: case
9160: k-up of ... endof
9161: k-f1 of ... endof
9162: k-left k-shift-mask or k-ctrl-mask or of ... endof
9163: ...
9164: endcase
9165: else ( keyboard-event )
9166: drop \ just ignore an unknown keyboard event type
9167: then then
9168: @end example
1.44 crook 9169:
1.45 crook 9170: doc-ekey
1.141 anton 9171: doc-ekey>char
1.181 anton 9172: doc-ekey>fkey
1.45 crook 9173: doc-ekey?
1.141 anton 9174:
1.181 anton 9175: The key identifiers for cursor keys are:
1.141 anton 9176:
9177: doc-k-left
9178: doc-k-right
1.185 anton 9179: doc-k-up
9180: doc-k-down
9181: doc-k-home
9182: doc-k-end
1.141 anton 9183: doc-k-prior
9184: doc-k-next
9185: doc-k-insert
9186: doc-k-delete
9187:
1.181 anton 9188: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9189:
1.181 anton 9190: doc-k-f1
9191: doc-k-f2
9192: doc-k-f3
9193: doc-k-f4
9194: doc-k-f5
9195: doc-k-f6
9196: doc-k-f7
9197: doc-k-f8
9198: doc-k-f9
9199: doc-k-f10
9200: doc-k-f11
9201: doc-k-f12
9202:
9203: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9204:
9205: You can combine these key identifiers with masks for various shift keys:
9206:
9207: doc-k-shift-mask
9208: doc-k-ctrl-mask
9209: doc-k-alt-mask
9210:
9211: Note that, even if a Forth system has @code{ekey>fkey} and the key
9212: identifier words, the keys are not necessarily available or it may not
9213: necessarily be able to report all the keys and all the possible
9214: combinations with shift masks. Therefore, write your programs in such
9215: a way that they are still useful even if the keys and key combinations
9216: cannot be pressed or are not recognized.
9217:
9218: Examples: Older keyboards often do not have an F11 and F12 key. If
9219: you run Gforth in an xterm, the xterm catches a number of combinations
9220: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9221: Gforth currently does not recognize and report combinations with
9222: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9223: above would never be entered).
9224:
9225: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9226: you need the ANSI.SYS driver to get that behaviour); it works by
9227: recognizing the escape sequences that ANSI terminals send when such a
9228: key is pressed. If you have a terminal that sends other escape
9229: sequences, you will not get useful results on Gforth. Other Forth
9230: systems may work in a different way.
9231:
9232:
9233: @node Line input and conversion, Pipes, Single-key input, Other I/O
9234: @subsection Line input and conversion
9235: @cindex line input from terminal
9236: @cindex input, linewise from terminal
9237: @cindex convertin strings to numbers
9238: @cindex I/O - see input
9239:
9240: For ways of storing character strings in memory see @ref{String Formats}.
9241:
9242: @comment TODO examples for >number >float accept key key? pad parse word refill
9243: @comment then index them
1.141 anton 9244:
9245: Words for inputting one line from the keyboard:
9246:
9247: doc-accept
9248: doc-edit-line
9249:
9250: Conversion words:
9251:
1.143 anton 9252: doc-s>number?
9253: doc-s>unumber?
1.26 crook 9254: doc->number
9255: doc->float
1.143 anton 9256:
1.141 anton 9257:
1.27 crook 9258: @comment obsolescent words..
1.141 anton 9259: Obsolescent input and conversion words:
9260:
1.27 crook 9261: doc-convert
1.26 crook 9262: doc-expect
1.27 crook 9263: doc-span
1.5 anton 9264:
9265:
1.181 anton 9266: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9267: @subsection Pipes
9268: @cindex pipes, creating your own
9269:
9270: In addition to using Gforth in pipes created by other processes
9271: (@pxref{Gforth in pipes}), you can create your own pipe with
9272: @code{open-pipe}, and read from or write to it.
9273:
9274: doc-open-pipe
9275: doc-close-pipe
9276:
9277: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9278: you don't catch this exception, Gforth will catch it and exit, usually
9279: silently (@pxref{Gforth in pipes}). Since you probably do not want
9280: this, you should wrap a @code{catch} or @code{try} block around the code
9281: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9282: problem yourself, and then return to regular processing.
9283:
9284: doc-broken-pipe-error
9285:
1.155 anton 9286: @node Xchars and Unicode, , Pipes, Other I/O
9287: @subsection Xchars and Unicode
1.149 pazsan 9288:
1.188 pazsan 9289: ASCII is only appropriate for the English language. Most western
9290: languages however fit somewhat into the Forth frame, since a byte is
9291: sufficient to encode the few special characters in each (though not
9292: always the same encoding can be used; latin-1 is most widely used,
9293: though). For other languages, different char-sets have to be used,
9294: several of them variable-width. Most prominent representant is
9295: UTF-8. Let's call these extended characters xchars. The primitive
9296: fixed-size characters stored as bytes are called pchars in this
9297: section.
9298:
9299: The xchar words add a few data types:
9300:
9301: @itemize
9302:
9303: @item
9304: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9305: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9306: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9307: character set can be used.
9308:
9309: @item
9310: @var{xc-addr} is the address of an xchar in memory. Alignment
9311: requirements are the same as @var{c-addr}. The memory representation of an
9312: xchar differs from the stack representation, and depends on the
9313: encoding used. An xchar may use a variable number of pchars in memory.
9314:
9315: @item
9316: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9317: @var{xc-addr}, @var{u} pchars long.
9318:
9319: @end itemize
9320:
9321: doc-xc-size
9322: doc-x-size
9323: doc-xc@+
9324: doc-xc!+
9325: doc-xc!+?
9326: doc-xchar+
9327: doc-xchar-
9328: doc-+x/string
9329: doc-x\string-
9330: doc--trailing-garbage
9331: doc-x-width
9332: doc-xkey
9333: doc-xemit
9334:
9335: There's a new environment query
9336:
9337: doc-xchar-encoding
1.112 anton 9338:
1.121 anton 9339: @node OS command line arguments, Locals, Other I/O, Words
9340: @section OS command line arguments
9341: @cindex OS command line arguments
9342: @cindex command line arguments, OS
9343: @cindex arguments, OS command line
9344:
9345: The usual way to pass arguments to Gforth programs on the command line
9346: is via the @option{-e} option, e.g.
9347:
9348: @example
9349: gforth -e "123 456" foo.fs -e bye
9350: @end example
9351:
9352: However, you may want to interpret the command-line arguments directly.
9353: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9354: through @code{next-arg}:
1.121 anton 9355:
1.123 anton 9356: doc-next-arg
1.121 anton 9357:
1.123 anton 9358: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9359:
9360: @example
9361: : echo ( -- )
1.122 anton 9362: begin
1.123 anton 9363: next-arg 2dup 0 0 d<> while
9364: type space
9365: repeat
9366: 2drop ;
1.121 anton 9367:
9368: echo cr bye
9369: @end example
9370:
9371: This can be invoked with
9372:
9373: @example
9374: gforth echo.fs hello world
9375: @end example
1.123 anton 9376:
9377: and it will print
9378:
9379: @example
9380: hello world
9381: @end example
9382:
9383: The next lower level of dealing with the OS command line are the
9384: following words:
9385:
9386: doc-arg
9387: doc-shift-args
9388:
9389: Finally, at the lowest level Gforth provides the following words:
9390:
9391: doc-argc
9392: doc-argv
1.121 anton 9393:
1.78 anton 9394: @c -------------------------------------------------------------
1.126 pazsan 9395: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9396: @section Locals
9397: @cindex locals
9398:
9399: Local variables can make Forth programming more enjoyable and Forth
9400: programs easier to read. Unfortunately, the locals of ANS Forth are
9401: laden with restrictions. Therefore, we provide not only the ANS Forth
9402: locals wordset, but also our own, more powerful locals wordset (we
9403: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9404:
1.78 anton 9405: The ideas in this section have also been published in M. Anton Ertl,
9406: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9407: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9408:
9409: @menu
1.78 anton 9410: * Gforth locals::
9411: * ANS Forth locals::
1.5 anton 9412: @end menu
9413:
1.78 anton 9414: @node Gforth locals, ANS Forth locals, Locals, Locals
9415: @subsection Gforth locals
9416: @cindex Gforth locals
9417: @cindex locals, Gforth style
1.5 anton 9418:
1.78 anton 9419: Locals can be defined with
1.44 crook 9420:
1.78 anton 9421: @example
9422: @{ local1 local2 ... -- comment @}
9423: @end example
9424: or
9425: @example
9426: @{ local1 local2 ... @}
9427: @end example
1.5 anton 9428:
1.78 anton 9429: E.g.,
9430: @example
9431: : max @{ n1 n2 -- n3 @}
9432: n1 n2 > if
9433: n1
9434: else
9435: n2
9436: endif ;
9437: @end example
1.44 crook 9438:
1.78 anton 9439: The similarity of locals definitions with stack comments is intended. A
9440: locals definition often replaces the stack comment of a word. The order
9441: of the locals corresponds to the order in a stack comment and everything
9442: after the @code{--} is really a comment.
1.77 anton 9443:
1.78 anton 9444: This similarity has one disadvantage: It is too easy to confuse locals
9445: declarations with stack comments, causing bugs and making them hard to
9446: find. However, this problem can be avoided by appropriate coding
9447: conventions: Do not use both notations in the same program. If you do,
9448: they should be distinguished using additional means, e.g. by position.
1.77 anton 9449:
1.78 anton 9450: @cindex types of locals
9451: @cindex locals types
9452: The name of the local may be preceded by a type specifier, e.g.,
9453: @code{F:} for a floating point value:
1.5 anton 9454:
1.78 anton 9455: @example
9456: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9457: \ complex multiplication
9458: Ar Br f* Ai Bi f* f-
9459: Ar Bi f* Ai Br f* f+ ;
9460: @end example
1.44 crook 9461:
1.78 anton 9462: @cindex flavours of locals
9463: @cindex locals flavours
9464: @cindex value-flavoured locals
9465: @cindex variable-flavoured locals
9466: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9467: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9468: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9469: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9470: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9471: produces its address (which becomes invalid when the variable's scope is
9472: left). E.g., the standard word @code{emit} can be defined in terms of
9473: @code{type} like this:
1.5 anton 9474:
1.78 anton 9475: @example
9476: : emit @{ C^ char* -- @}
9477: char* 1 type ;
9478: @end example
1.5 anton 9479:
1.78 anton 9480: @cindex default type of locals
9481: @cindex locals, default type
9482: A local without type specifier is a @code{W:} local. Both flavours of
9483: locals are initialized with values from the data or FP stack.
1.44 crook 9484:
1.78 anton 9485: Currently there is no way to define locals with user-defined data
9486: structures, but we are working on it.
1.5 anton 9487:
1.78 anton 9488: Gforth allows defining locals everywhere in a colon definition. This
9489: poses the following questions:
1.5 anton 9490:
1.78 anton 9491: @menu
9492: * Where are locals visible by name?::
9493: * How long do locals live?::
9494: * Locals programming style::
9495: * Locals implementation::
9496: @end menu
1.44 crook 9497:
1.78 anton 9498: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9499: @subsubsection Where are locals visible by name?
9500: @cindex locals visibility
9501: @cindex visibility of locals
9502: @cindex scope of locals
1.5 anton 9503:
1.78 anton 9504: Basically, the answer is that locals are visible where you would expect
9505: it in block-structured languages, and sometimes a little longer. If you
9506: want to restrict the scope of a local, enclose its definition in
9507: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9508:
9509:
1.78 anton 9510: doc-scope
9511: doc-endscope
1.5 anton 9512:
9513:
1.78 anton 9514: These words behave like control structure words, so you can use them
9515: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9516: arbitrary ways.
1.77 anton 9517:
1.78 anton 9518: If you want a more exact answer to the visibility question, here's the
9519: basic principle: A local is visible in all places that can only be
9520: reached through the definition of the local@footnote{In compiler
9521: construction terminology, all places dominated by the definition of the
9522: local.}. In other words, it is not visible in places that can be reached
9523: without going through the definition of the local. E.g., locals defined
9524: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9525: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9526: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9527:
1.78 anton 9528: The reasoning behind this solution is: We want to have the locals
9529: visible as long as it is meaningful. The user can always make the
9530: visibility shorter by using explicit scoping. In a place that can
9531: only be reached through the definition of a local, the meaning of a
9532: local name is clear. In other places it is not: How is the local
9533: initialized at the control flow path that does not contain the
9534: definition? Which local is meant, if the same name is defined twice in
9535: two independent control flow paths?
1.77 anton 9536:
1.78 anton 9537: This should be enough detail for nearly all users, so you can skip the
9538: rest of this section. If you really must know all the gory details and
9539: options, read on.
1.77 anton 9540:
1.78 anton 9541: In order to implement this rule, the compiler has to know which places
9542: are unreachable. It knows this automatically after @code{AHEAD},
9543: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9544: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9545: compiler that the control flow never reaches that place. If
9546: @code{UNREACHABLE} is not used where it could, the only consequence is
9547: that the visibility of some locals is more limited than the rule above
9548: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9549: lie to the compiler), buggy code will be produced.
1.77 anton 9550:
1.5 anton 9551:
1.78 anton 9552: doc-unreachable
1.5 anton 9553:
1.23 crook 9554:
1.78 anton 9555: Another problem with this rule is that at @code{BEGIN}, the compiler
9556: does not know which locals will be visible on the incoming
9557: back-edge. All problems discussed in the following are due to this
9558: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9559: loops as examples; the discussion also applies to @code{?DO} and other
9560: loops). Perhaps the most insidious example is:
1.26 crook 9561: @example
1.78 anton 9562: AHEAD
9563: BEGIN
9564: x
9565: [ 1 CS-ROLL ] THEN
9566: @{ x @}
9567: ...
9568: UNTIL
1.26 crook 9569: @end example
1.23 crook 9570:
1.78 anton 9571: This should be legal according to the visibility rule. The use of
9572: @code{x} can only be reached through the definition; but that appears
9573: textually below the use.
9574:
9575: From this example it is clear that the visibility rules cannot be fully
9576: implemented without major headaches. Our implementation treats common
9577: cases as advertised and the exceptions are treated in a safe way: The
9578: compiler makes a reasonable guess about the locals visible after a
9579: @code{BEGIN}; if it is too pessimistic, the
9580: user will get a spurious error about the local not being defined; if the
9581: compiler is too optimistic, it will notice this later and issue a
9582: warning. In the case above the compiler would complain about @code{x}
9583: being undefined at its use. You can see from the obscure examples in
9584: this section that it takes quite unusual control structures to get the
9585: compiler into trouble, and even then it will often do fine.
1.23 crook 9586:
1.78 anton 9587: If the @code{BEGIN} is reachable from above, the most optimistic guess
9588: is that all locals visible before the @code{BEGIN} will also be
9589: visible after the @code{BEGIN}. This guess is valid for all loops that
9590: are entered only through the @code{BEGIN}, in particular, for normal
9591: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9592: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9593: compiler. When the branch to the @code{BEGIN} is finally generated by
9594: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9595: warns the user if it was too optimistic:
1.26 crook 9596: @example
1.78 anton 9597: IF
9598: @{ x @}
9599: BEGIN
9600: \ x ?
9601: [ 1 cs-roll ] THEN
9602: ...
9603: UNTIL
1.26 crook 9604: @end example
1.23 crook 9605:
1.78 anton 9606: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9607: optimistically assumes that it lives until the @code{THEN}. It notices
9608: this difference when it compiles the @code{UNTIL} and issues a
9609: warning. The user can avoid the warning, and make sure that @code{x}
9610: is not used in the wrong area by using explicit scoping:
9611: @example
9612: IF
9613: SCOPE
9614: @{ x @}
9615: ENDSCOPE
9616: BEGIN
9617: [ 1 cs-roll ] THEN
9618: ...
9619: UNTIL
9620: @end example
1.23 crook 9621:
1.78 anton 9622: Since the guess is optimistic, there will be no spurious error messages
9623: about undefined locals.
1.44 crook 9624:
1.78 anton 9625: If the @code{BEGIN} is not reachable from above (e.g., after
9626: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9627: optimistic guess, as the locals visible after the @code{BEGIN} may be
9628: defined later. Therefore, the compiler assumes that no locals are
9629: visible after the @code{BEGIN}. However, the user can use
9630: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9631: visible at the BEGIN as at the point where the top control-flow stack
9632: item was created.
1.23 crook 9633:
1.44 crook 9634:
1.78 anton 9635: doc-assume-live
1.26 crook 9636:
1.23 crook 9637:
1.78 anton 9638: @noindent
9639: E.g.,
9640: @example
9641: @{ x @}
9642: AHEAD
9643: ASSUME-LIVE
9644: BEGIN
9645: x
9646: [ 1 CS-ROLL ] THEN
9647: ...
9648: UNTIL
9649: @end example
1.44 crook 9650:
1.78 anton 9651: Other cases where the locals are defined before the @code{BEGIN} can be
9652: handled by inserting an appropriate @code{CS-ROLL} before the
9653: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9654: behind the @code{ASSUME-LIVE}).
1.23 crook 9655:
1.78 anton 9656: Cases where locals are defined after the @code{BEGIN} (but should be
9657: visible immediately after the @code{BEGIN}) can only be handled by
9658: rearranging the loop. E.g., the ``most insidious'' example above can be
9659: arranged into:
9660: @example
9661: BEGIN
9662: @{ x @}
9663: ... 0=
9664: WHILE
9665: x
9666: REPEAT
9667: @end example
1.44 crook 9668:
1.78 anton 9669: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9670: @subsubsection How long do locals live?
9671: @cindex locals lifetime
9672: @cindex lifetime of locals
1.23 crook 9673:
1.78 anton 9674: The right answer for the lifetime question would be: A local lives at
9675: least as long as it can be accessed. For a value-flavoured local this
9676: means: until the end of its visibility. However, a variable-flavoured
9677: local could be accessed through its address far beyond its visibility
9678: scope. Ultimately, this would mean that such locals would have to be
9679: garbage collected. Since this entails un-Forth-like implementation
9680: complexities, I adopted the same cowardly solution as some other
9681: languages (e.g., C): The local lives only as long as it is visible;
9682: afterwards its address is invalid (and programs that access it
9683: afterwards are erroneous).
1.23 crook 9684:
1.78 anton 9685: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9686: @subsubsection Locals programming style
9687: @cindex locals programming style
9688: @cindex programming style, locals
1.23 crook 9689:
1.78 anton 9690: The freedom to define locals anywhere has the potential to change
9691: programming styles dramatically. In particular, the need to use the
9692: return stack for intermediate storage vanishes. Moreover, all stack
9693: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9694: determined arguments) can be eliminated: If the stack items are in the
9695: wrong order, just write a locals definition for all of them; then
9696: write the items in the order you want.
1.23 crook 9697:
1.78 anton 9698: This seems a little far-fetched and eliminating stack manipulations is
9699: unlikely to become a conscious programming objective. Still, the number
9700: of stack manipulations will be reduced dramatically if local variables
9701: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9702: a traditional implementation of @code{max}).
1.23 crook 9703:
1.78 anton 9704: This shows one potential benefit of locals: making Forth programs more
9705: readable. Of course, this benefit will only be realized if the
9706: programmers continue to honour the principle of factoring instead of
9707: using the added latitude to make the words longer.
1.23 crook 9708:
1.78 anton 9709: @cindex single-assignment style for locals
9710: Using @code{TO} can and should be avoided. Without @code{TO},
9711: every value-flavoured local has only a single assignment and many
9712: advantages of functional languages apply to Forth. I.e., programs are
9713: easier to analyse, to optimize and to read: It is clear from the
9714: definition what the local stands for, it does not turn into something
9715: different later.
1.23 crook 9716:
1.78 anton 9717: E.g., a definition using @code{TO} might look like this:
9718: @example
9719: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9720: u1 u2 min 0
9721: ?do
9722: addr1 c@@ addr2 c@@ -
9723: ?dup-if
9724: unloop exit
9725: then
9726: addr1 char+ TO addr1
9727: addr2 char+ TO addr2
9728: loop
9729: u1 u2 - ;
1.26 crook 9730: @end example
1.78 anton 9731: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9732: every loop iteration. @code{strcmp} is a typical example of the
9733: readability problems of using @code{TO}. When you start reading
9734: @code{strcmp}, you think that @code{addr1} refers to the start of the
9735: string. Only near the end of the loop you realize that it is something
9736: else.
1.23 crook 9737:
1.78 anton 9738: This can be avoided by defining two locals at the start of the loop that
9739: are initialized with the right value for the current iteration.
9740: @example
9741: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9742: addr1 addr2
9743: u1 u2 min 0
9744: ?do @{ s1 s2 @}
9745: s1 c@@ s2 c@@ -
9746: ?dup-if
9747: unloop exit
9748: then
9749: s1 char+ s2 char+
9750: loop
9751: 2drop
9752: u1 u2 - ;
9753: @end example
9754: Here it is clear from the start that @code{s1} has a different value
9755: in every loop iteration.
1.23 crook 9756:
1.78 anton 9757: @node Locals implementation, , Locals programming style, Gforth locals
9758: @subsubsection Locals implementation
9759: @cindex locals implementation
9760: @cindex implementation of locals
1.23 crook 9761:
1.78 anton 9762: @cindex locals stack
9763: Gforth uses an extra locals stack. The most compelling reason for
9764: this is that the return stack is not float-aligned; using an extra stack
9765: also eliminates the problems and restrictions of using the return stack
9766: as locals stack. Like the other stacks, the locals stack grows toward
9767: lower addresses. A few primitives allow an efficient implementation:
9768:
9769:
9770: doc-@local#
9771: doc-f@local#
9772: doc-laddr#
9773: doc-lp+!#
9774: doc-lp!
9775: doc->l
9776: doc-f>l
9777:
9778:
9779: In addition to these primitives, some specializations of these
9780: primitives for commonly occurring inline arguments are provided for
9781: efficiency reasons, e.g., @code{@@local0} as specialization of
9782: @code{@@local#} for the inline argument 0. The following compiling words
9783: compile the right specialized version, or the general version, as
9784: appropriate:
1.23 crook 9785:
1.5 anton 9786:
1.107 dvdkhlng 9787: @c doc-compile-@local
9788: @c doc-compile-f@local
1.78 anton 9789: doc-compile-lp+!
1.5 anton 9790:
9791:
1.78 anton 9792: Combinations of conditional branches and @code{lp+!#} like
9793: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9794: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9795:
1.78 anton 9796: A special area in the dictionary space is reserved for keeping the
9797: local variable names. @code{@{} switches the dictionary pointer to this
9798: area and @code{@}} switches it back and generates the locals
9799: initializing code. @code{W:} etc.@ are normal defining words. This
9800: special area is cleared at the start of every colon definition.
1.5 anton 9801:
1.78 anton 9802: @cindex word list for defining locals
9803: A special feature of Gforth's dictionary is used to implement the
9804: definition of locals without type specifiers: every word list (aka
9805: vocabulary) has its own methods for searching
9806: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9807: with a special search method: When it is searched for a word, it
9808: actually creates that word using @code{W:}. @code{@{} changes the search
9809: order to first search the word list containing @code{@}}, @code{W:} etc.,
9810: and then the word list for defining locals without type specifiers.
1.5 anton 9811:
1.78 anton 9812: The lifetime rules support a stack discipline within a colon
9813: definition: The lifetime of a local is either nested with other locals
9814: lifetimes or it does not overlap them.
1.23 crook 9815:
1.78 anton 9816: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9817: pointer manipulation is generated. Between control structure words
9818: locals definitions can push locals onto the locals stack. @code{AGAIN}
9819: is the simplest of the other three control flow words. It has to
9820: restore the locals stack depth of the corresponding @code{BEGIN}
9821: before branching. The code looks like this:
9822: @format
9823: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9824: @code{branch} <begin>
9825: @end format
1.26 crook 9826:
1.78 anton 9827: @code{UNTIL} is a little more complicated: If it branches back, it
9828: must adjust the stack just like @code{AGAIN}. But if it falls through,
9829: the locals stack must not be changed. The compiler generates the
9830: following code:
9831: @format
9832: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9833: @end format
9834: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9835:
1.78 anton 9836: @code{THEN} can produce somewhat inefficient code:
9837: @format
9838: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9839: <orig target>:
9840: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9841: @end format
9842: The second @code{lp+!#} adjusts the locals stack pointer from the
9843: level at the @i{orig} point to the level after the @code{THEN}. The
9844: first @code{lp+!#} adjusts the locals stack pointer from the current
9845: level to the level at the orig point, so the complete effect is an
9846: adjustment from the current level to the right level after the
9847: @code{THEN}.
1.26 crook 9848:
1.78 anton 9849: @cindex locals information on the control-flow stack
9850: @cindex control-flow stack items, locals information
9851: In a conventional Forth implementation a dest control-flow stack entry
9852: is just the target address and an orig entry is just the address to be
9853: patched. Our locals implementation adds a word list to every orig or dest
9854: item. It is the list of locals visible (or assumed visible) at the point
9855: described by the entry. Our implementation also adds a tag to identify
9856: the kind of entry, in particular to differentiate between live and dead
9857: (reachable and unreachable) orig entries.
1.26 crook 9858:
1.78 anton 9859: A few unusual operations have to be performed on locals word lists:
1.44 crook 9860:
1.5 anton 9861:
1.78 anton 9862: doc-common-list
9863: doc-sub-list?
9864: doc-list-size
1.52 anton 9865:
9866:
1.78 anton 9867: Several features of our locals word list implementation make these
9868: operations easy to implement: The locals word lists are organised as
9869: linked lists; the tails of these lists are shared, if the lists
9870: contain some of the same locals; and the address of a name is greater
9871: than the address of the names behind it in the list.
1.5 anton 9872:
1.78 anton 9873: Another important implementation detail is the variable
9874: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9875: determine if they can be reached directly or only through the branch
9876: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9877: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9878: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9879:
1.78 anton 9880: Counted loops are similar to other loops in most respects, but
9881: @code{LEAVE} requires special attention: It performs basically the same
9882: service as @code{AHEAD}, but it does not create a control-flow stack
9883: entry. Therefore the information has to be stored elsewhere;
9884: traditionally, the information was stored in the target fields of the
9885: branches created by the @code{LEAVE}s, by organizing these fields into a
9886: linked list. Unfortunately, this clever trick does not provide enough
9887: space for storing our extended control flow information. Therefore, we
9888: introduce another stack, the leave stack. It contains the control-flow
9889: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9890:
1.78 anton 9891: Local names are kept until the end of the colon definition, even if
9892: they are no longer visible in any control-flow path. In a few cases
9893: this may lead to increased space needs for the locals name area, but
9894: usually less than reclaiming this space would cost in code size.
1.5 anton 9895:
1.44 crook 9896:
1.78 anton 9897: @node ANS Forth locals, , Gforth locals, Locals
9898: @subsection ANS Forth locals
9899: @cindex locals, ANS Forth style
1.5 anton 9900:
1.78 anton 9901: The ANS Forth locals wordset does not define a syntax for locals, but
9902: words that make it possible to define various syntaxes. One of the
9903: possible syntaxes is a subset of the syntax we used in the Gforth locals
9904: wordset, i.e.:
1.29 crook 9905:
9906: @example
1.78 anton 9907: @{ local1 local2 ... -- comment @}
9908: @end example
9909: @noindent
9910: or
9911: @example
9912: @{ local1 local2 ... @}
1.29 crook 9913: @end example
9914:
1.78 anton 9915: The order of the locals corresponds to the order in a stack comment. The
9916: restrictions are:
1.5 anton 9917:
1.78 anton 9918: @itemize @bullet
9919: @item
9920: Locals can only be cell-sized values (no type specifiers are allowed).
9921: @item
9922: Locals can be defined only outside control structures.
9923: @item
9924: Locals can interfere with explicit usage of the return stack. For the
9925: exact (and long) rules, see the standard. If you don't use return stack
9926: accessing words in a definition using locals, you will be all right. The
9927: purpose of this rule is to make locals implementation on the return
9928: stack easier.
9929: @item
9930: The whole definition must be in one line.
9931: @end itemize
1.5 anton 9932:
1.78 anton 9933: Locals defined in ANS Forth behave like @code{VALUE}s
9934: (@pxref{Values}). I.e., they are initialized from the stack. Using their
9935: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 9936:
1.78 anton 9937: Since the syntax above is supported by Gforth directly, you need not do
9938: anything to use it. If you want to port a program using this syntax to
9939: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
9940: syntax on the other system.
1.5 anton 9941:
1.78 anton 9942: Note that a syntax shown in the standard, section A.13 looks
9943: similar, but is quite different in having the order of locals
9944: reversed. Beware!
1.5 anton 9945:
1.78 anton 9946: The ANS Forth locals wordset itself consists of one word:
1.5 anton 9947:
1.78 anton 9948: doc-(local)
1.5 anton 9949:
1.78 anton 9950: The ANS Forth locals extension wordset defines a syntax using
9951: @code{locals|}, but it is so awful that we strongly recommend not to use
9952: it. We have implemented this syntax to make porting to Gforth easy, but
9953: do not document it here. The problem with this syntax is that the locals
9954: are defined in an order reversed with respect to the standard stack
9955: comment notation, making programs harder to read, and easier to misread
9956: and miswrite. The only merit of this syntax is that it is easy to
9957: implement using the ANS Forth locals wordset.
1.53 anton 9958:
9959:
1.78 anton 9960: @c ----------------------------------------------------------
9961: @node Structures, Object-oriented Forth, Locals, Words
9962: @section Structures
9963: @cindex structures
9964: @cindex records
1.53 anton 9965:
1.78 anton 9966: This section presents the structure package that comes with Gforth. A
9967: version of the package implemented in ANS Forth is available in
9968: @file{compat/struct.fs}. This package was inspired by a posting on
9969: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
9970: possibly John Hayes). A version of this section has been published in
9971: M. Anton Ertl,
9972: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
9973: Another Forth Structures Package}, Forth Dimensions 19(3), pages
9974: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 9975:
1.78 anton 9976: @menu
9977: * Why explicit structure support?::
9978: * Structure Usage::
9979: * Structure Naming Convention::
9980: * Structure Implementation::
9981: * Structure Glossary::
1.183 anton 9982: * Forth200x Structures::
1.78 anton 9983: @end menu
1.55 anton 9984:
1.78 anton 9985: @node Why explicit structure support?, Structure Usage, Structures, Structures
9986: @subsection Why explicit structure support?
1.53 anton 9987:
1.78 anton 9988: @cindex address arithmetic for structures
9989: @cindex structures using address arithmetic
9990: If we want to use a structure containing several fields, we could simply
9991: reserve memory for it, and access the fields using address arithmetic
9992: (@pxref{Address arithmetic}). As an example, consider a structure with
9993: the following fields
1.57 anton 9994:
1.78 anton 9995: @table @code
9996: @item a
9997: is a float
9998: @item b
9999: is a cell
10000: @item c
10001: is a float
10002: @end table
1.57 anton 10003:
1.78 anton 10004: Given the (float-aligned) base address of the structure we get the
10005: address of the field
1.52 anton 10006:
1.78 anton 10007: @table @code
10008: @item a
10009: without doing anything further.
10010: @item b
10011: with @code{float+}
10012: @item c
10013: with @code{float+ cell+ faligned}
10014: @end table
1.52 anton 10015:
1.78 anton 10016: It is easy to see that this can become quite tiring.
1.52 anton 10017:
1.78 anton 10018: Moreover, it is not very readable, because seeing a
10019: @code{cell+} tells us neither which kind of structure is
10020: accessed nor what field is accessed; we have to somehow infer the kind
10021: of structure, and then look up in the documentation, which field of
10022: that structure corresponds to that offset.
1.53 anton 10023:
1.78 anton 10024: Finally, this kind of address arithmetic also causes maintenance
10025: troubles: If you add or delete a field somewhere in the middle of the
10026: structure, you have to find and change all computations for the fields
10027: afterwards.
1.52 anton 10028:
1.78 anton 10029: So, instead of using @code{cell+} and friends directly, how
10030: about storing the offsets in constants:
1.52 anton 10031:
1.78 anton 10032: @example
10033: 0 constant a-offset
10034: 0 float+ constant b-offset
10035: 0 float+ cell+ faligned c-offset
10036: @end example
1.64 pazsan 10037:
1.78 anton 10038: Now we can get the address of field @code{x} with @code{x-offset
10039: +}. This is much better in all respects. Of course, you still
10040: have to change all later offset definitions if you add a field. You can
10041: fix this by declaring the offsets in the following way:
1.57 anton 10042:
1.78 anton 10043: @example
10044: 0 constant a-offset
10045: a-offset float+ constant b-offset
10046: b-offset cell+ faligned constant c-offset
10047: @end example
1.57 anton 10048:
1.78 anton 10049: Since we always use the offsets with @code{+}, we could use a defining
10050: word @code{cfield} that includes the @code{+} in the action of the
10051: defined word:
1.64 pazsan 10052:
1.78 anton 10053: @example
10054: : cfield ( n "name" -- )
10055: create ,
10056: does> ( name execution: addr1 -- addr2 )
10057: @@ + ;
1.64 pazsan 10058:
1.78 anton 10059: 0 cfield a
10060: 0 a float+ cfield b
10061: 0 b cell+ faligned cfield c
10062: @end example
1.64 pazsan 10063:
1.78 anton 10064: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10065:
1.78 anton 10066: The structure field words now can be used quite nicely. However,
10067: their definition is still a bit cumbersome: We have to repeat the
10068: name, the information about size and alignment is distributed before
10069: and after the field definitions etc. The structure package presented
10070: here addresses these problems.
1.64 pazsan 10071:
1.78 anton 10072: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10073: @subsection Structure Usage
10074: @cindex structure usage
1.57 anton 10075:
1.78 anton 10076: @cindex @code{field} usage
10077: @cindex @code{struct} usage
10078: @cindex @code{end-struct} usage
10079: You can define a structure for a (data-less) linked list with:
1.57 anton 10080: @example
1.78 anton 10081: struct
10082: cell% field list-next
10083: end-struct list%
1.57 anton 10084: @end example
10085:
1.78 anton 10086: With the address of the list node on the stack, you can compute the
10087: address of the field that contains the address of the next node with
10088: @code{list-next}. E.g., you can determine the length of a list
10089: with:
1.57 anton 10090:
10091: @example
1.78 anton 10092: : list-length ( list -- n )
10093: \ "list" is a pointer to the first element of a linked list
10094: \ "n" is the length of the list
10095: 0 BEGIN ( list1 n1 )
10096: over
10097: WHILE ( list1 n1 )
10098: 1+ swap list-next @@ swap
10099: REPEAT
10100: nip ;
1.57 anton 10101: @end example
10102:
1.78 anton 10103: You can reserve memory for a list node in the dictionary with
10104: @code{list% %allot}, which leaves the address of the list node on the
10105: stack. For the equivalent allocation on the heap you can use @code{list%
10106: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10107: use @code{list% %allocate}). You can get the the size of a list
10108: node with @code{list% %size} and its alignment with @code{list%
10109: %alignment}.
10110:
10111: Note that in ANS Forth the body of a @code{create}d word is
10112: @code{aligned} but not necessarily @code{faligned};
10113: therefore, if you do a:
1.57 anton 10114:
10115: @example
1.78 anton 10116: create @emph{name} foo% %allot drop
1.57 anton 10117: @end example
10118:
1.78 anton 10119: @noindent
10120: then the memory alloted for @code{foo%} is guaranteed to start at the
10121: body of @code{@emph{name}} only if @code{foo%} contains only character,
10122: cell and double fields. Therefore, if your structure contains floats,
10123: better use
1.57 anton 10124:
10125: @example
1.78 anton 10126: foo% %allot constant @emph{name}
1.57 anton 10127: @end example
10128:
1.78 anton 10129: @cindex structures containing structures
10130: You can include a structure @code{foo%} as a field of
10131: another structure, like this:
1.65 anton 10132: @example
1.78 anton 10133: struct
10134: ...
10135: foo% field ...
10136: ...
10137: end-struct ...
1.65 anton 10138: @end example
1.52 anton 10139:
1.78 anton 10140: @cindex structure extension
10141: @cindex extended records
10142: Instead of starting with an empty structure, you can extend an
10143: existing structure. E.g., a plain linked list without data, as defined
10144: above, is hardly useful; You can extend it to a linked list of integers,
10145: like this:@footnote{This feature is also known as @emph{extended
10146: records}. It is the main innovation in the Oberon language; in other
10147: words, adding this feature to Modula-2 led Wirth to create a new
10148: language, write a new compiler etc. Adding this feature to Forth just
10149: required a few lines of code.}
1.52 anton 10150:
1.78 anton 10151: @example
10152: list%
10153: cell% field intlist-int
10154: end-struct intlist%
10155: @end example
1.55 anton 10156:
1.78 anton 10157: @code{intlist%} is a structure with two fields:
10158: @code{list-next} and @code{intlist-int}.
1.55 anton 10159:
1.78 anton 10160: @cindex structures containing arrays
10161: You can specify an array type containing @emph{n} elements of
10162: type @code{foo%} like this:
1.55 anton 10163:
10164: @example
1.78 anton 10165: foo% @emph{n} *
1.56 anton 10166: @end example
1.55 anton 10167:
1.78 anton 10168: You can use this array type in any place where you can use a normal
10169: type, e.g., when defining a @code{field}, or with
10170: @code{%allot}.
10171:
10172: @cindex first field optimization
10173: The first field is at the base address of a structure and the word for
10174: this field (e.g., @code{list-next}) actually does not change the address
10175: on the stack. You may be tempted to leave it away in the interest of
10176: run-time and space efficiency. This is not necessary, because the
10177: structure package optimizes this case: If you compile a first-field
10178: words, no code is generated. So, in the interest of readability and
10179: maintainability you should include the word for the field when accessing
10180: the field.
1.52 anton 10181:
10182:
1.78 anton 10183: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10184: @subsection Structure Naming Convention
10185: @cindex structure naming convention
1.52 anton 10186:
1.78 anton 10187: The field names that come to (my) mind are often quite generic, and,
10188: if used, would cause frequent name clashes. E.g., many structures
10189: probably contain a @code{counter} field. The structure names
10190: that come to (my) mind are often also the logical choice for the names
10191: of words that create such a structure.
1.52 anton 10192:
1.78 anton 10193: Therefore, I have adopted the following naming conventions:
1.52 anton 10194:
1.78 anton 10195: @itemize @bullet
10196: @cindex field naming convention
10197: @item
10198: The names of fields are of the form
10199: @code{@emph{struct}-@emph{field}}, where
10200: @code{@emph{struct}} is the basic name of the structure, and
10201: @code{@emph{field}} is the basic name of the field. You can
10202: think of field words as converting the (address of the)
10203: structure into the (address of the) field.
1.52 anton 10204:
1.78 anton 10205: @cindex structure naming convention
10206: @item
10207: The names of structures are of the form
10208: @code{@emph{struct}%}, where
10209: @code{@emph{struct}} is the basic name of the structure.
10210: @end itemize
1.52 anton 10211:
1.78 anton 10212: This naming convention does not work that well for fields of extended
10213: structures; e.g., the integer list structure has a field
10214: @code{intlist-int}, but has @code{list-next}, not
10215: @code{intlist-next}.
1.53 anton 10216:
1.78 anton 10217: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10218: @subsection Structure Implementation
10219: @cindex structure implementation
10220: @cindex implementation of structures
1.52 anton 10221:
1.78 anton 10222: The central idea in the implementation is to pass the data about the
10223: structure being built on the stack, not in some global
10224: variable. Everything else falls into place naturally once this design
10225: decision is made.
1.53 anton 10226:
1.78 anton 10227: The type description on the stack is of the form @emph{align
10228: size}. Keeping the size on the top-of-stack makes dealing with arrays
10229: very simple.
1.53 anton 10230:
1.78 anton 10231: @code{field} is a defining word that uses @code{Create}
10232: and @code{DOES>}. The body of the field contains the offset
10233: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10234:
10235: @example
1.78 anton 10236: @@ +
1.53 anton 10237: @end example
10238:
1.78 anton 10239: @noindent
10240: i.e., add the offset to the address, giving the stack effect
10241: @i{addr1 -- addr2} for a field.
10242:
10243: @cindex first field optimization, implementation
10244: This simple structure is slightly complicated by the optimization
10245: for fields with offset 0, which requires a different
10246: @code{DOES>}-part (because we cannot rely on there being
10247: something on the stack if such a field is invoked during
10248: compilation). Therefore, we put the different @code{DOES>}-parts
10249: in separate words, and decide which one to invoke based on the
10250: offset. For a zero offset, the field is basically a noop; it is
10251: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10252:
1.183 anton 10253: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10254: @subsection Structure Glossary
10255: @cindex structure glossary
1.53 anton 10256:
1.5 anton 10257:
1.78 anton 10258: doc-%align
10259: doc-%alignment
10260: doc-%alloc
10261: doc-%allocate
10262: doc-%allot
10263: doc-cell%
10264: doc-char%
10265: doc-dfloat%
10266: doc-double%
10267: doc-end-struct
10268: doc-field
10269: doc-float%
10270: doc-naligned
10271: doc-sfloat%
10272: doc-%size
10273: doc-struct
1.54 anton 10274:
10275:
1.183 anton 10276: @node Forth200x Structures, , Structure Glossary, Structures
10277: @subsection Forth200x Structures
10278: @cindex Structures in Forth200x
10279:
10280: The Forth 200x standard defines a slightly less convenient form of
10281: structures. In general (when using @code{field+}, you have to perform
10282: the alignment yourself, but there are a number of convenience words
10283: (e.g., @code{field:} that perform the alignment for you.
10284:
10285: A typical usage example is:
10286:
10287: @example
10288: 0
10289: field: s-a
10290: faligned 2 floats +field s-b
10291: constant s-struct
10292: @end example
10293:
10294: An alternative way of writing this structure is:
10295:
10296: @example
10297: begin-structure s-struct
10298: field: s-a
10299: faligned 2 floats +field s-b
10300: end-structure
10301: @end example
10302:
10303: doc-begin-structure
10304: doc-end-structure
10305: doc-+field
10306: doc-cfield:
10307: doc-field:
10308: doc-2field:
10309: doc-ffield:
10310: doc-sffield:
10311: doc-dffield:
10312:
1.26 crook 10313: @c -------------------------------------------------------------
1.78 anton 10314: @node Object-oriented Forth, Programming Tools, Structures, Words
10315: @section Object-oriented Forth
10316:
10317: Gforth comes with three packages for object-oriented programming:
10318: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10319: is preloaded, so you have to @code{include} them before use. The most
10320: important differences between these packages (and others) are discussed
10321: in @ref{Comparison with other object models}. All packages are written
10322: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10323:
1.78 anton 10324: @menu
10325: * Why object-oriented programming?::
10326: * Object-Oriented Terminology::
10327: * Objects::
10328: * OOF::
10329: * Mini-OOF::
10330: * Comparison with other object models::
10331: @end menu
1.5 anton 10332:
1.78 anton 10333: @c ----------------------------------------------------------------
10334: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10335: @subsection Why object-oriented programming?
10336: @cindex object-oriented programming motivation
10337: @cindex motivation for object-oriented programming
1.44 crook 10338:
1.78 anton 10339: Often we have to deal with several data structures (@emph{objects}),
10340: that have to be treated similarly in some respects, but differently in
10341: others. Graphical objects are the textbook example: circles, triangles,
10342: dinosaurs, icons, and others, and we may want to add more during program
10343: development. We want to apply some operations to any graphical object,
10344: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10345: has to do something different for every kind of object.
10346: @comment TODO add some other operations eg perimeter, area
10347: @comment and tie in to concrete examples later..
1.5 anton 10348:
1.78 anton 10349: We could implement @code{draw} as a big @code{CASE}
10350: control structure that executes the appropriate code depending on the
10351: kind of object to be drawn. This would be not be very elegant, and,
10352: moreover, we would have to change @code{draw} every time we add
10353: a new kind of graphical object (say, a spaceship).
1.44 crook 10354:
1.78 anton 10355: What we would rather do is: When defining spaceships, we would tell
10356: the system: ``Here's how you @code{draw} a spaceship; you figure
10357: out the rest''.
1.5 anton 10358:
1.78 anton 10359: This is the problem that all systems solve that (rightfully) call
10360: themselves object-oriented; the object-oriented packages presented here
10361: solve this problem (and not much else).
10362: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10363:
1.78 anton 10364: @c ------------------------------------------------------------------------
10365: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10366: @subsection Object-Oriented Terminology
10367: @cindex object-oriented terminology
10368: @cindex terminology for object-oriented programming
1.5 anton 10369:
1.78 anton 10370: This section is mainly for reference, so you don't have to understand
10371: all of it right away. The terminology is mainly Smalltalk-inspired. In
10372: short:
1.44 crook 10373:
1.78 anton 10374: @table @emph
10375: @cindex class
10376: @item class
10377: a data structure definition with some extras.
1.5 anton 10378:
1.78 anton 10379: @cindex object
10380: @item object
10381: an instance of the data structure described by the class definition.
1.5 anton 10382:
1.78 anton 10383: @cindex instance variables
10384: @item instance variables
10385: fields of the data structure.
1.5 anton 10386:
1.78 anton 10387: @cindex selector
10388: @cindex method selector
10389: @cindex virtual function
10390: @item selector
10391: (or @emph{method selector}) a word (e.g.,
10392: @code{draw}) that performs an operation on a variety of data
10393: structures (classes). A selector describes @emph{what} operation to
10394: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10395:
1.78 anton 10396: @cindex method
10397: @item method
10398: the concrete definition that performs the operation
10399: described by the selector for a specific class. A method specifies
10400: @emph{how} the operation is performed for a specific class.
1.5 anton 10401:
1.78 anton 10402: @cindex selector invocation
10403: @cindex message send
10404: @cindex invoking a selector
10405: @item selector invocation
10406: a call of a selector. One argument of the call (the TOS (top-of-stack))
10407: is used for determining which method is used. In Smalltalk terminology:
10408: a message (consisting of the selector and the other arguments) is sent
10409: to the object.
1.5 anton 10410:
1.78 anton 10411: @cindex receiving object
10412: @item receiving object
10413: the object used for determining the method executed by a selector
10414: invocation. In the @file{objects.fs} model, it is the object that is on
10415: the TOS when the selector is invoked. (@emph{Receiving} comes from
10416: the Smalltalk @emph{message} terminology.)
1.5 anton 10417:
1.78 anton 10418: @cindex child class
10419: @cindex parent class
10420: @cindex inheritance
10421: @item child class
10422: a class that has (@emph{inherits}) all properties (instance variables,
10423: selectors, methods) from a @emph{parent class}. In Smalltalk
10424: terminology: The subclass inherits from the superclass. In C++
10425: terminology: The derived class inherits from the base class.
1.5 anton 10426:
1.78 anton 10427: @end table
1.5 anton 10428:
1.78 anton 10429: @c If you wonder about the message sending terminology, it comes from
10430: @c a time when each object had it's own task and objects communicated via
10431: @c message passing; eventually the Smalltalk developers realized that
10432: @c they can do most things through simple (indirect) calls. They kept the
10433: @c terminology.
1.5 anton 10434:
1.78 anton 10435: @c --------------------------------------------------------------
10436: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10437: @subsection The @file{objects.fs} model
10438: @cindex objects
10439: @cindex object-oriented programming
1.26 crook 10440:
1.78 anton 10441: @cindex @file{objects.fs}
10442: @cindex @file{oof.fs}
1.26 crook 10443:
1.78 anton 10444: This section describes the @file{objects.fs} package. This material also
10445: has been published in M. Anton Ertl,
10446: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10447: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10448: 37--43.
10449: @c McKewan's and Zsoter's packages
1.26 crook 10450:
1.78 anton 10451: This section assumes that you have read @ref{Structures}.
1.5 anton 10452:
1.78 anton 10453: The techniques on which this model is based have been used to implement
10454: the parser generator, Gray, and have also been used in Gforth for
10455: implementing the various flavours of word lists (hashed or not,
10456: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10457:
10458:
1.26 crook 10459: @menu
1.78 anton 10460: * Properties of the Objects model::
10461: * Basic Objects Usage::
10462: * The Objects base class::
10463: * Creating objects::
10464: * Object-Oriented Programming Style::
10465: * Class Binding::
10466: * Method conveniences::
10467: * Classes and Scoping::
10468: * Dividing classes::
10469: * Object Interfaces::
10470: * Objects Implementation::
10471: * Objects Glossary::
1.26 crook 10472: @end menu
1.5 anton 10473:
1.78 anton 10474: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10475:
1.78 anton 10476: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10477: @subsubsection Properties of the @file{objects.fs} model
10478: @cindex @file{objects.fs} properties
1.5 anton 10479:
1.78 anton 10480: @itemize @bullet
10481: @item
10482: It is straightforward to pass objects on the stack. Passing
10483: selectors on the stack is a little less convenient, but possible.
1.44 crook 10484:
1.78 anton 10485: @item
10486: Objects are just data structures in memory, and are referenced by their
10487: address. You can create words for objects with normal defining words
10488: like @code{constant}. Likewise, there is no difference between instance
10489: variables that contain objects and those that contain other data.
1.5 anton 10490:
1.78 anton 10491: @item
10492: Late binding is efficient and easy to use.
1.44 crook 10493:
1.78 anton 10494: @item
10495: It avoids parsing, and thus avoids problems with state-smartness
10496: and reduced extensibility; for convenience there are a few parsing
10497: words, but they have non-parsing counterparts. There are also a few
10498: defining words that parse. This is hard to avoid, because all standard
10499: defining words parse (except @code{:noname}); however, such
10500: words are not as bad as many other parsing words, because they are not
10501: state-smart.
1.5 anton 10502:
1.78 anton 10503: @item
10504: It does not try to incorporate everything. It does a few things and does
10505: them well (IMO). In particular, this model was not designed to support
10506: information hiding (although it has features that may help); you can use
10507: a separate package for achieving this.
1.5 anton 10508:
1.78 anton 10509: @item
10510: It is layered; you don't have to learn and use all features to use this
10511: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10512: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10513: are optional and independent of each other.
1.5 anton 10514:
1.78 anton 10515: @item
10516: An implementation in ANS Forth is available.
1.5 anton 10517:
1.78 anton 10518: @end itemize
1.5 anton 10519:
1.44 crook 10520:
1.78 anton 10521: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10522: @subsubsection Basic @file{objects.fs} Usage
10523: @cindex basic objects usage
10524: @cindex objects, basic usage
1.5 anton 10525:
1.78 anton 10526: You can define a class for graphical objects like this:
1.44 crook 10527:
1.78 anton 10528: @cindex @code{class} usage
10529: @cindex @code{end-class} usage
10530: @cindex @code{selector} usage
1.5 anton 10531: @example
1.78 anton 10532: object class \ "object" is the parent class
10533: selector draw ( x y graphical -- )
10534: end-class graphical
10535: @end example
10536:
10537: This code defines a class @code{graphical} with an
10538: operation @code{draw}. We can perform the operation
10539: @code{draw} on any @code{graphical} object, e.g.:
10540:
10541: @example
10542: 100 100 t-rex draw
1.26 crook 10543: @end example
1.5 anton 10544:
1.78 anton 10545: @noindent
10546: where @code{t-rex} is a word (say, a constant) that produces a
10547: graphical object.
10548:
10549: @comment TODO add a 2nd operation eg perimeter.. and use for
10550: @comment a concrete example
1.5 anton 10551:
1.78 anton 10552: @cindex abstract class
10553: How do we create a graphical object? With the present definitions,
10554: we cannot create a useful graphical object. The class
10555: @code{graphical} describes graphical objects in general, but not
10556: any concrete graphical object type (C++ users would call it an
10557: @emph{abstract class}); e.g., there is no method for the selector
10558: @code{draw} in the class @code{graphical}.
1.5 anton 10559:
1.78 anton 10560: For concrete graphical objects, we define child classes of the
10561: class @code{graphical}, e.g.:
1.5 anton 10562:
1.78 anton 10563: @cindex @code{overrides} usage
10564: @cindex @code{field} usage in class definition
1.26 crook 10565: @example
1.78 anton 10566: graphical class \ "graphical" is the parent class
10567: cell% field circle-radius
1.5 anton 10568:
1.78 anton 10569: :noname ( x y circle -- )
10570: circle-radius @@ draw-circle ;
10571: overrides draw
1.5 anton 10572:
1.78 anton 10573: :noname ( n-radius circle -- )
10574: circle-radius ! ;
10575: overrides construct
1.5 anton 10576:
1.78 anton 10577: end-class circle
10578: @end example
1.44 crook 10579:
1.78 anton 10580: Here we define a class @code{circle} as a child of @code{graphical},
10581: with field @code{circle-radius} (which behaves just like a field
10582: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10583: for the selectors @code{draw} and @code{construct} (@code{construct} is
10584: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10585:
1.78 anton 10586: Now we can create a circle on the heap (i.e.,
10587: @code{allocate}d memory) with:
1.44 crook 10588:
1.78 anton 10589: @cindex @code{heap-new} usage
1.5 anton 10590: @example
1.78 anton 10591: 50 circle heap-new constant my-circle
1.5 anton 10592: @end example
10593:
1.78 anton 10594: @noindent
10595: @code{heap-new} invokes @code{construct}, thus
10596: initializing the field @code{circle-radius} with 50. We can draw
10597: this new circle at (100,100) with:
1.5 anton 10598:
10599: @example
1.78 anton 10600: 100 100 my-circle draw
1.5 anton 10601: @end example
10602:
1.78 anton 10603: @cindex selector invocation, restrictions
10604: @cindex class definition, restrictions
10605: Note: You can only invoke a selector if the object on the TOS
10606: (the receiving object) belongs to the class where the selector was
10607: defined or one of its descendents; e.g., you can invoke
10608: @code{draw} only for objects belonging to @code{graphical}
10609: or its descendents (e.g., @code{circle}). Immediately before
10610: @code{end-class}, the search order has to be the same as
10611: immediately after @code{class}.
10612:
10613: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10614: @subsubsection The @file{object.fs} base class
10615: @cindex @code{object} class
10616:
10617: When you define a class, you have to specify a parent class. So how do
10618: you start defining classes? There is one class available from the start:
10619: @code{object}. It is ancestor for all classes and so is the
10620: only class that has no parent. It has two selectors: @code{construct}
10621: and @code{print}.
10622:
10623: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10624: @subsubsection Creating objects
10625: @cindex creating objects
10626: @cindex object creation
10627: @cindex object allocation options
10628:
10629: @cindex @code{heap-new} discussion
10630: @cindex @code{dict-new} discussion
10631: @cindex @code{construct} discussion
10632: You can create and initialize an object of a class on the heap with
10633: @code{heap-new} ( ... class -- object ) and in the dictionary
10634: (allocation with @code{allot}) with @code{dict-new} (
10635: ... class -- object ). Both words invoke @code{construct}, which
10636: consumes the stack items indicated by "..." above.
10637:
10638: @cindex @code{init-object} discussion
10639: @cindex @code{class-inst-size} discussion
10640: If you want to allocate memory for an object yourself, you can get its
10641: alignment and size with @code{class-inst-size 2@@} ( class --
10642: align size ). Once you have memory for an object, you can initialize
10643: it with @code{init-object} ( ... class object -- );
10644: @code{construct} does only a part of the necessary work.
10645:
10646: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10647: @subsubsection Object-Oriented Programming Style
10648: @cindex object-oriented programming style
10649: @cindex programming style, object-oriented
1.5 anton 10650:
1.78 anton 10651: This section is not exhaustive.
1.5 anton 10652:
1.78 anton 10653: @cindex stack effects of selectors
10654: @cindex selectors and stack effects
10655: In general, it is a good idea to ensure that all methods for the
10656: same selector have the same stack effect: when you invoke a selector,
10657: you often have no idea which method will be invoked, so, unless all
10658: methods have the same stack effect, you will not know the stack effect
10659: of the selector invocation.
1.5 anton 10660:
1.78 anton 10661: One exception to this rule is methods for the selector
10662: @code{construct}. We know which method is invoked, because we
10663: specify the class to be constructed at the same place. Actually, I
10664: defined @code{construct} as a selector only to give the users a
10665: convenient way to specify initialization. The way it is used, a
10666: mechanism different from selector invocation would be more natural
10667: (but probably would take more code and more space to explain).
1.5 anton 10668:
1.78 anton 10669: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10670: @subsubsection Class Binding
10671: @cindex class binding
10672: @cindex early binding
1.5 anton 10673:
1.78 anton 10674: @cindex late binding
10675: Normal selector invocations determine the method at run-time depending
10676: on the class of the receiving object. This run-time selection is called
10677: @i{late binding}.
1.5 anton 10678:
1.78 anton 10679: Sometimes it's preferable to invoke a different method. For example,
10680: you might want to use the simple method for @code{print}ing
10681: @code{object}s instead of the possibly long-winded @code{print} method
10682: of the receiver class. You can achieve this by replacing the invocation
10683: of @code{print} with:
1.5 anton 10684:
1.78 anton 10685: @cindex @code{[bind]} usage
1.5 anton 10686: @example
1.78 anton 10687: [bind] object print
1.5 anton 10688: @end example
10689:
1.78 anton 10690: @noindent
10691: in compiled code or:
10692:
10693: @cindex @code{bind} usage
1.5 anton 10694: @example
1.78 anton 10695: bind object print
1.5 anton 10696: @end example
10697:
1.78 anton 10698: @cindex class binding, alternative to
10699: @noindent
10700: in interpreted code. Alternatively, you can define the method with a
10701: name (e.g., @code{print-object}), and then invoke it through the
10702: name. Class binding is just a (often more convenient) way to achieve
10703: the same effect; it avoids name clutter and allows you to invoke
10704: methods directly without naming them first.
1.5 anton 10705:
1.78 anton 10706: @cindex superclass binding
10707: @cindex parent class binding
10708: A frequent use of class binding is this: When we define a method
10709: for a selector, we often want the method to do what the selector does
10710: in the parent class, and a little more. There is a special word for
10711: this purpose: @code{[parent]}; @code{[parent]
10712: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10713: selector}}, where @code{@emph{parent}} is the parent
10714: class of the current class. E.g., a method definition might look like:
1.44 crook 10715:
1.78 anton 10716: @cindex @code{[parent]} usage
10717: @example
10718: :noname
10719: dup [parent] foo \ do parent's foo on the receiving object
10720: ... \ do some more
10721: ; overrides foo
10722: @end example
1.6 pazsan 10723:
1.78 anton 10724: @cindex class binding as optimization
10725: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10726: March 1997), Andrew McKewan presents class binding as an optimization
10727: technique. I recommend not using it for this purpose unless you are in
10728: an emergency. Late binding is pretty fast with this model anyway, so the
10729: benefit of using class binding is small; the cost of using class binding
10730: where it is not appropriate is reduced maintainability.
1.44 crook 10731:
1.78 anton 10732: While we are at programming style questions: You should bind
10733: selectors only to ancestor classes of the receiving object. E.g., say,
10734: you know that the receiving object is of class @code{foo} or its
10735: descendents; then you should bind only to @code{foo} and its
10736: ancestors.
1.12 anton 10737:
1.78 anton 10738: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10739: @subsubsection Method conveniences
10740: @cindex method conveniences
1.44 crook 10741:
1.78 anton 10742: In a method you usually access the receiving object pretty often. If
10743: you define the method as a plain colon definition (e.g., with
10744: @code{:noname}), you may have to do a lot of stack
10745: gymnastics. To avoid this, you can define the method with @code{m:
10746: ... ;m}. E.g., you could define the method for
10747: @code{draw}ing a @code{circle} with
1.6 pazsan 10748:
1.78 anton 10749: @cindex @code{this} usage
10750: @cindex @code{m:} usage
10751: @cindex @code{;m} usage
10752: @example
10753: m: ( x y circle -- )
10754: ( x y ) this circle-radius @@ draw-circle ;m
10755: @end example
1.6 pazsan 10756:
1.78 anton 10757: @cindex @code{exit} in @code{m: ... ;m}
10758: @cindex @code{exitm} discussion
10759: @cindex @code{catch} in @code{m: ... ;m}
10760: When this method is executed, the receiver object is removed from the
10761: stack; you can access it with @code{this} (admittedly, in this
10762: example the use of @code{m: ... ;m} offers no advantage). Note
10763: that I specify the stack effect for the whole method (i.e. including
10764: the receiver object), not just for the code between @code{m:}
10765: and @code{;m}. You cannot use @code{exit} in
10766: @code{m:...;m}; instead, use
10767: @code{exitm}.@footnote{Moreover, for any word that calls
10768: @code{catch} and was defined before loading
10769: @code{objects.fs}, you have to redefine it like I redefined
10770: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10771:
1.78 anton 10772: @cindex @code{inst-var} usage
10773: You will frequently use sequences of the form @code{this
10774: @emph{field}} (in the example above: @code{this
10775: circle-radius}). If you use the field only in this way, you can
10776: define it with @code{inst-var} and eliminate the
10777: @code{this} before the field name. E.g., the @code{circle}
10778: class above could also be defined with:
1.6 pazsan 10779:
1.78 anton 10780: @example
10781: graphical class
10782: cell% inst-var radius
1.6 pazsan 10783:
1.78 anton 10784: m: ( x y circle -- )
10785: radius @@ draw-circle ;m
10786: overrides draw
1.6 pazsan 10787:
1.78 anton 10788: m: ( n-radius circle -- )
10789: radius ! ;m
10790: overrides construct
1.6 pazsan 10791:
1.78 anton 10792: end-class circle
10793: @end example
1.6 pazsan 10794:
1.78 anton 10795: @code{radius} can only be used in @code{circle} and its
10796: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10797:
1.78 anton 10798: @cindex @code{inst-value} usage
10799: You can also define fields with @code{inst-value}, which is
10800: to @code{inst-var} what @code{value} is to
10801: @code{variable}. You can change the value of such a field with
10802: @code{[to-inst]}. E.g., we could also define the class
10803: @code{circle} like this:
1.44 crook 10804:
1.78 anton 10805: @example
10806: graphical class
10807: inst-value radius
1.6 pazsan 10808:
1.78 anton 10809: m: ( x y circle -- )
10810: radius draw-circle ;m
10811: overrides draw
1.44 crook 10812:
1.78 anton 10813: m: ( n-radius circle -- )
10814: [to-inst] radius ;m
10815: overrides construct
1.6 pazsan 10816:
1.78 anton 10817: end-class circle
10818: @end example
1.6 pazsan 10819:
1.78 anton 10820: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10821:
1.78 anton 10822: @c Finally, you can define named methods with @code{:m}. One use of this
10823: @c feature is the definition of words that occur only in one class and are
10824: @c not intended to be overridden, but which still need method context
10825: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10826: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10827:
10828:
1.78 anton 10829: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10830: @subsubsection Classes and Scoping
10831: @cindex classes and scoping
10832: @cindex scoping and classes
1.6 pazsan 10833:
1.78 anton 10834: Inheritance is frequent, unlike structure extension. This exacerbates
10835: the problem with the field name convention (@pxref{Structure Naming
10836: Convention}): One always has to remember in which class the field was
10837: originally defined; changing a part of the class structure would require
10838: changes for renaming in otherwise unaffected code.
1.6 pazsan 10839:
1.78 anton 10840: @cindex @code{inst-var} visibility
10841: @cindex @code{inst-value} visibility
10842: To solve this problem, I added a scoping mechanism (which was not in my
10843: original charter): A field defined with @code{inst-var} (or
10844: @code{inst-value}) is visible only in the class where it is defined and in
10845: the descendent classes of this class. Using such fields only makes
10846: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10847:
1.78 anton 10848: This scoping mechanism allows us to use the unadorned field name,
10849: because name clashes with unrelated words become much less likely.
1.6 pazsan 10850:
1.78 anton 10851: @cindex @code{protected} discussion
10852: @cindex @code{private} discussion
10853: Once we have this mechanism, we can also use it for controlling the
10854: visibility of other words: All words defined after
10855: @code{protected} are visible only in the current class and its
10856: descendents. @code{public} restores the compilation
10857: (i.e. @code{current}) word list that was in effect before. If you
10858: have several @code{protected}s without an intervening
10859: @code{public} or @code{set-current}, @code{public}
10860: will restore the compilation word list in effect before the first of
10861: these @code{protected}s.
1.6 pazsan 10862:
1.78 anton 10863: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10864: @subsubsection Dividing classes
10865: @cindex Dividing classes
10866: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10867:
1.78 anton 10868: You may want to do the definition of methods separate from the
10869: definition of the class, its selectors, fields, and instance variables,
10870: i.e., separate the implementation from the definition. You can do this
10871: in the following way:
1.6 pazsan 10872:
1.78 anton 10873: @example
10874: graphical class
10875: inst-value radius
10876: end-class circle
1.6 pazsan 10877:
1.78 anton 10878: ... \ do some other stuff
1.6 pazsan 10879:
1.78 anton 10880: circle methods \ now we are ready
1.44 crook 10881:
1.78 anton 10882: m: ( x y circle -- )
10883: radius draw-circle ;m
10884: overrides draw
1.6 pazsan 10885:
1.78 anton 10886: m: ( n-radius circle -- )
10887: [to-inst] radius ;m
10888: overrides construct
1.44 crook 10889:
1.78 anton 10890: end-methods
10891: @end example
1.7 pazsan 10892:
1.78 anton 10893: You can use several @code{methods}...@code{end-methods} sections. The
10894: only things you can do to the class in these sections are: defining
10895: methods, and overriding the class's selectors. You must not define new
10896: selectors or fields.
1.7 pazsan 10897:
1.78 anton 10898: Note that you often have to override a selector before using it. In
10899: particular, you usually have to override @code{construct} with a new
10900: method before you can invoke @code{heap-new} and friends. E.g., you
10901: must not create a circle before the @code{overrides construct} sequence
10902: in the example above.
1.7 pazsan 10903:
1.78 anton 10904: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10905: @subsubsection Object Interfaces
10906: @cindex object interfaces
10907: @cindex interfaces for objects
1.7 pazsan 10908:
1.78 anton 10909: In this model you can only call selectors defined in the class of the
10910: receiving objects or in one of its ancestors. If you call a selector
10911: with a receiving object that is not in one of these classes, the
10912: result is undefined; if you are lucky, the program crashes
10913: immediately.
1.7 pazsan 10914:
1.78 anton 10915: @cindex selectors common to hardly-related classes
10916: Now consider the case when you want to have a selector (or several)
10917: available in two classes: You would have to add the selector to a
10918: common ancestor class, in the worst case to @code{object}. You
10919: may not want to do this, e.g., because someone else is responsible for
10920: this ancestor class.
1.7 pazsan 10921:
1.78 anton 10922: The solution for this problem is interfaces. An interface is a
10923: collection of selectors. If a class implements an interface, the
10924: selectors become available to the class and its descendents. A class
10925: can implement an unlimited number of interfaces. For the problem
10926: discussed above, we would define an interface for the selector(s), and
10927: both classes would implement the interface.
1.7 pazsan 10928:
1.78 anton 10929: As an example, consider an interface @code{storage} for
10930: writing objects to disk and getting them back, and a class
10931: @code{foo} that implements it. The code would look like this:
1.7 pazsan 10932:
1.78 anton 10933: @cindex @code{interface} usage
10934: @cindex @code{end-interface} usage
10935: @cindex @code{implementation} usage
10936: @example
10937: interface
10938: selector write ( file object -- )
10939: selector read1 ( file object -- )
10940: end-interface storage
1.13 pazsan 10941:
1.78 anton 10942: bar class
10943: storage implementation
1.13 pazsan 10944:
1.78 anton 10945: ... overrides write
10946: ... overrides read1
10947: ...
10948: end-class foo
10949: @end example
1.13 pazsan 10950:
1.78 anton 10951: @noindent
10952: (I would add a word @code{read} @i{( file -- object )} that uses
10953: @code{read1} internally, but that's beyond the point illustrated
10954: here.)
1.13 pazsan 10955:
1.78 anton 10956: Note that you cannot use @code{protected} in an interface; and
10957: of course you cannot define fields.
1.13 pazsan 10958:
1.78 anton 10959: In the Neon model, all selectors are available for all classes;
10960: therefore it does not need interfaces. The price you pay in this model
10961: is slower late binding, and therefore, added complexity to avoid late
10962: binding.
1.13 pazsan 10963:
1.78 anton 10964: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
10965: @subsubsection @file{objects.fs} Implementation
10966: @cindex @file{objects.fs} implementation
1.13 pazsan 10967:
1.78 anton 10968: @cindex @code{object-map} discussion
10969: An object is a piece of memory, like one of the data structures
10970: described with @code{struct...end-struct}. It has a field
10971: @code{object-map} that points to the method map for the object's
10972: class.
1.13 pazsan 10973:
1.78 anton 10974: @cindex method map
10975: @cindex virtual function table
10976: The @emph{method map}@footnote{This is Self terminology; in C++
10977: terminology: virtual function table.} is an array that contains the
10978: execution tokens (@i{xt}s) of the methods for the object's class. Each
10979: selector contains an offset into a method map.
1.13 pazsan 10980:
1.78 anton 10981: @cindex @code{selector} implementation, class
10982: @code{selector} is a defining word that uses
10983: @code{CREATE} and @code{DOES>}. The body of the
10984: selector contains the offset; the @code{DOES>} action for a
10985: class selector is, basically:
1.8 pazsan 10986:
10987: @example
1.78 anton 10988: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 10989: @end example
10990:
1.78 anton 10991: Since @code{object-map} is the first field of the object, it
10992: does not generate any code. As you can see, calling a selector has a
10993: small, constant cost.
1.26 crook 10994:
1.78 anton 10995: @cindex @code{current-interface} discussion
10996: @cindex class implementation and representation
10997: A class is basically a @code{struct} combined with a method
10998: map. During the class definition the alignment and size of the class
10999: are passed on the stack, just as with @code{struct}s, so
11000: @code{field} can also be used for defining class
11001: fields. However, passing more items on the stack would be
11002: inconvenient, so @code{class} builds a data structure in memory,
11003: which is accessed through the variable
11004: @code{current-interface}. After its definition is complete, the
11005: class is represented on the stack by a pointer (e.g., as parameter for
11006: a child class definition).
1.26 crook 11007:
1.78 anton 11008: A new class starts off with the alignment and size of its parent,
11009: and a copy of the parent's method map. Defining new fields extends the
11010: size and alignment; likewise, defining new selectors extends the
11011: method map. @code{overrides} just stores a new @i{xt} in the method
11012: map at the offset given by the selector.
1.13 pazsan 11013:
1.78 anton 11014: @cindex class binding, implementation
11015: Class binding just gets the @i{xt} at the offset given by the selector
11016: from the class's method map and @code{compile,}s (in the case of
11017: @code{[bind]}) it.
1.13 pazsan 11018:
1.78 anton 11019: @cindex @code{this} implementation
11020: @cindex @code{catch} and @code{this}
11021: @cindex @code{this} and @code{catch}
11022: I implemented @code{this} as a @code{value}. At the
11023: start of an @code{m:...;m} method the old @code{this} is
11024: stored to the return stack and restored at the end; and the object on
11025: the TOS is stored @code{TO this}. This technique has one
11026: disadvantage: If the user does not leave the method via
11027: @code{;m}, but via @code{throw} or @code{exit},
11028: @code{this} is not restored (and @code{exit} may
11029: crash). To deal with the @code{throw} problem, I have redefined
11030: @code{catch} to save and restore @code{this}; the same
11031: should be done with any word that can catch an exception. As for
11032: @code{exit}, I simply forbid it (as a replacement, there is
11033: @code{exitm}).
1.13 pazsan 11034:
1.78 anton 11035: @cindex @code{inst-var} implementation
11036: @code{inst-var} is just the same as @code{field}, with
11037: a different @code{DOES>} action:
1.13 pazsan 11038: @example
1.78 anton 11039: @@ this +
1.8 pazsan 11040: @end example
1.78 anton 11041: Similar for @code{inst-value}.
1.8 pazsan 11042:
1.78 anton 11043: @cindex class scoping implementation
11044: Each class also has a word list that contains the words defined with
11045: @code{inst-var} and @code{inst-value}, and its protected
11046: words. It also has a pointer to its parent. @code{class} pushes
11047: the word lists of the class and all its ancestors onto the search order stack,
11048: and @code{end-class} drops them.
1.20 pazsan 11049:
1.78 anton 11050: @cindex interface implementation
11051: An interface is like a class without fields, parent and protected
11052: words; i.e., it just has a method map. If a class implements an
11053: interface, its method map contains a pointer to the method map of the
11054: interface. The positive offsets in the map are reserved for class
11055: methods, therefore interface map pointers have negative
11056: offsets. Interfaces have offsets that are unique throughout the
11057: system, unlike class selectors, whose offsets are only unique for the
11058: classes where the selector is available (invokable).
1.20 pazsan 11059:
1.78 anton 11060: This structure means that interface selectors have to perform one
11061: indirection more than class selectors to find their method. Their body
11062: contains the interface map pointer offset in the class method map, and
11063: the method offset in the interface method map. The
11064: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11065:
11066: @example
1.78 anton 11067: ( object selector-body )
11068: 2dup selector-interface @@ ( object selector-body object interface-offset )
11069: swap object-map @@ + @@ ( object selector-body map )
11070: swap selector-offset @@ + @@ execute
1.20 pazsan 11071: @end example
11072:
1.78 anton 11073: where @code{object-map} and @code{selector-offset} are
11074: first fields and generate no code.
1.20 pazsan 11075:
1.78 anton 11076: As a concrete example, consider the following code:
1.20 pazsan 11077:
11078: @example
1.78 anton 11079: interface
11080: selector if1sel1
11081: selector if1sel2
11082: end-interface if1
1.20 pazsan 11083:
1.78 anton 11084: object class
11085: if1 implementation
11086: selector cl1sel1
11087: cell% inst-var cl1iv1
1.20 pazsan 11088:
1.78 anton 11089: ' m1 overrides construct
11090: ' m2 overrides if1sel1
11091: ' m3 overrides if1sel2
11092: ' m4 overrides cl1sel2
11093: end-class cl1
1.20 pazsan 11094:
1.78 anton 11095: create obj1 object dict-new drop
11096: create obj2 cl1 dict-new drop
11097: @end example
1.20 pazsan 11098:
1.78 anton 11099: The data structure created by this code (including the data structure
11100: for @code{object}) is shown in the
11101: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11102: @comment TODO add this diagram..
1.20 pazsan 11103:
1.78 anton 11104: @node Objects Glossary, , Objects Implementation, Objects
11105: @subsubsection @file{objects.fs} Glossary
11106: @cindex @file{objects.fs} Glossary
1.20 pazsan 11107:
11108:
1.78 anton 11109: doc---objects-bind
11110: doc---objects-<bind>
11111: doc---objects-bind'
11112: doc---objects-[bind]
11113: doc---objects-class
11114: doc---objects-class->map
11115: doc---objects-class-inst-size
11116: doc---objects-class-override!
1.79 anton 11117: doc---objects-class-previous
11118: doc---objects-class>order
1.78 anton 11119: doc---objects-construct
11120: doc---objects-current'
11121: doc---objects-[current]
11122: doc---objects-current-interface
11123: doc---objects-dict-new
11124: doc---objects-end-class
11125: doc---objects-end-class-noname
11126: doc---objects-end-interface
11127: doc---objects-end-interface-noname
11128: doc---objects-end-methods
11129: doc---objects-exitm
11130: doc---objects-heap-new
11131: doc---objects-implementation
11132: doc---objects-init-object
11133: doc---objects-inst-value
11134: doc---objects-inst-var
11135: doc---objects-interface
11136: doc---objects-m:
11137: doc---objects-:m
11138: doc---objects-;m
11139: doc---objects-method
11140: doc---objects-methods
11141: doc---objects-object
11142: doc---objects-overrides
11143: doc---objects-[parent]
11144: doc---objects-print
11145: doc---objects-protected
11146: doc---objects-public
11147: doc---objects-selector
11148: doc---objects-this
11149: doc---objects-<to-inst>
11150: doc---objects-[to-inst]
11151: doc---objects-to-this
11152: doc---objects-xt-new
1.20 pazsan 11153:
11154:
1.78 anton 11155: @c -------------------------------------------------------------
11156: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11157: @subsection The @file{oof.fs} model
11158: @cindex oof
11159: @cindex object-oriented programming
1.20 pazsan 11160:
1.78 anton 11161: @cindex @file{objects.fs}
11162: @cindex @file{oof.fs}
1.20 pazsan 11163:
1.78 anton 11164: This section describes the @file{oof.fs} package.
1.20 pazsan 11165:
1.78 anton 11166: The package described in this section has been used in bigFORTH since 1991, and
11167: used for two large applications: a chromatographic system used to
11168: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11169:
1.78 anton 11170: You can find a description (in German) of @file{oof.fs} in @cite{Object
11171: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11172: 10(2), 1994.
1.20 pazsan 11173:
1.78 anton 11174: @menu
11175: * Properties of the OOF model::
11176: * Basic OOF Usage::
11177: * The OOF base class::
11178: * Class Declaration::
11179: * Class Implementation::
11180: @end menu
1.20 pazsan 11181:
1.78 anton 11182: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11183: @subsubsection Properties of the @file{oof.fs} model
11184: @cindex @file{oof.fs} properties
1.20 pazsan 11185:
1.78 anton 11186: @itemize @bullet
11187: @item
11188: This model combines object oriented programming with information
11189: hiding. It helps you writing large application, where scoping is
11190: necessary, because it provides class-oriented scoping.
1.20 pazsan 11191:
1.78 anton 11192: @item
11193: Named objects, object pointers, and object arrays can be created,
11194: selector invocation uses the ``object selector'' syntax. Selector invocation
11195: to objects and/or selectors on the stack is a bit less convenient, but
11196: possible.
1.44 crook 11197:
1.78 anton 11198: @item
11199: Selector invocation and instance variable usage of the active object is
11200: straightforward, since both make use of the active object.
1.44 crook 11201:
1.78 anton 11202: @item
11203: Late binding is efficient and easy to use.
1.20 pazsan 11204:
1.78 anton 11205: @item
11206: State-smart objects parse selectors. However, extensibility is provided
11207: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11208:
1.78 anton 11209: @item
11210: An implementation in ANS Forth is available.
1.20 pazsan 11211:
1.78 anton 11212: @end itemize
1.23 crook 11213:
11214:
1.78 anton 11215: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11216: @subsubsection Basic @file{oof.fs} Usage
11217: @cindex @file{oof.fs} usage
1.23 crook 11218:
1.78 anton 11219: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11220:
1.78 anton 11221: You can define a class for graphical objects like this:
1.23 crook 11222:
1.78 anton 11223: @cindex @code{class} usage
11224: @cindex @code{class;} usage
11225: @cindex @code{method} usage
11226: @example
11227: object class graphical \ "object" is the parent class
1.139 pazsan 11228: method draw ( x y -- )
1.78 anton 11229: class;
11230: @end example
1.23 crook 11231:
1.78 anton 11232: This code defines a class @code{graphical} with an
11233: operation @code{draw}. We can perform the operation
11234: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11235:
1.78 anton 11236: @example
11237: 100 100 t-rex draw
11238: @end example
1.23 crook 11239:
1.78 anton 11240: @noindent
11241: where @code{t-rex} is an object or object pointer, created with e.g.
11242: @code{graphical : t-rex}.
1.23 crook 11243:
1.78 anton 11244: @cindex abstract class
11245: How do we create a graphical object? With the present definitions,
11246: we cannot create a useful graphical object. The class
11247: @code{graphical} describes graphical objects in general, but not
11248: any concrete graphical object type (C++ users would call it an
11249: @emph{abstract class}); e.g., there is no method for the selector
11250: @code{draw} in the class @code{graphical}.
1.23 crook 11251:
1.78 anton 11252: For concrete graphical objects, we define child classes of the
11253: class @code{graphical}, e.g.:
1.23 crook 11254:
1.78 anton 11255: @example
11256: graphical class circle \ "graphical" is the parent class
11257: cell var circle-radius
11258: how:
11259: : draw ( x y -- )
11260: circle-radius @@ draw-circle ;
1.23 crook 11261:
1.139 pazsan 11262: : init ( n-radius -- )
1.78 anton 11263: circle-radius ! ;
11264: class;
11265: @end example
1.1 anton 11266:
1.78 anton 11267: Here we define a class @code{circle} as a child of @code{graphical},
11268: with a field @code{circle-radius}; it defines new methods for the
11269: selectors @code{draw} and @code{init} (@code{init} is defined in
11270: @code{object}, the parent class of @code{graphical}).
1.1 anton 11271:
1.78 anton 11272: Now we can create a circle in the dictionary with:
1.1 anton 11273:
1.78 anton 11274: @example
11275: 50 circle : my-circle
11276: @end example
1.21 crook 11277:
1.78 anton 11278: @noindent
11279: @code{:} invokes @code{init}, thus initializing the field
11280: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11281: with:
1.1 anton 11282:
1.78 anton 11283: @example
11284: 100 100 my-circle draw
11285: @end example
1.1 anton 11286:
1.78 anton 11287: @cindex selector invocation, restrictions
11288: @cindex class definition, restrictions
11289: Note: You can only invoke a selector if the receiving object belongs to
11290: the class where the selector was defined or one of its descendents;
11291: e.g., you can invoke @code{draw} only for objects belonging to
11292: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11293: mechanism will check if you try to invoke a selector that is not
11294: defined in this class hierarchy, so you'll get an error at compilation
11295: time.
1.1 anton 11296:
11297:
1.78 anton 11298: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11299: @subsubsection The @file{oof.fs} base class
11300: @cindex @file{oof.fs} base class
1.1 anton 11301:
1.78 anton 11302: When you define a class, you have to specify a parent class. So how do
11303: you start defining classes? There is one class available from the start:
11304: @code{object}. You have to use it as ancestor for all classes. It is the
11305: only class that has no parent. Classes are also objects, except that
11306: they don't have instance variables; class manipulation such as
11307: inheritance or changing definitions of a class is handled through
11308: selectors of the class @code{object}.
1.1 anton 11309:
1.78 anton 11310: @code{object} provides a number of selectors:
1.1 anton 11311:
1.78 anton 11312: @itemize @bullet
11313: @item
11314: @code{class} for subclassing, @code{definitions} to add definitions
11315: later on, and @code{class?} to get type informations (is the class a
11316: subclass of the class passed on the stack?).
1.1 anton 11317:
1.78 anton 11318: doc---object-class
11319: doc---object-definitions
11320: doc---object-class?
1.1 anton 11321:
11322:
1.26 crook 11323: @item
1.78 anton 11324: @code{init} and @code{dispose} as constructor and destructor of the
11325: object. @code{init} is invocated after the object's memory is allocated,
11326: while @code{dispose} also handles deallocation. Thus if you redefine
11327: @code{dispose}, you have to call the parent's dispose with @code{super
11328: dispose}, too.
11329:
11330: doc---object-init
11331: doc---object-dispose
11332:
1.1 anton 11333:
1.26 crook 11334: @item
1.78 anton 11335: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11336: @code{[]} to create named and unnamed objects and object arrays or
11337: object pointers.
11338:
11339: doc---object-new
11340: doc---object-new[]
11341: doc---object-:
11342: doc---object-ptr
11343: doc---object-asptr
11344: doc---object-[]
11345:
1.1 anton 11346:
1.26 crook 11347: @item
1.78 anton 11348: @code{::} and @code{super} for explicit scoping. You should use explicit
11349: scoping only for super classes or classes with the same set of instance
11350: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11351:
1.78 anton 11352: doc---object-::
11353: doc---object-super
1.21 crook 11354:
11355:
1.26 crook 11356: @item
1.78 anton 11357: @code{self} to get the address of the object
1.21 crook 11358:
1.78 anton 11359: doc---object-self
1.21 crook 11360:
11361:
1.78 anton 11362: @item
11363: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11364: pointers and instance defers.
1.21 crook 11365:
1.78 anton 11366: doc---object-bind
11367: doc---object-bound
11368: doc---object-link
11369: doc---object-is
1.21 crook 11370:
11371:
1.78 anton 11372: @item
11373: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11374: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11375:
1.78 anton 11376: doc---object-'
11377: doc---object-postpone
1.21 crook 11378:
11379:
1.78 anton 11380: @item
11381: @code{with} and @code{endwith} to select the active object from the
11382: stack, and enable its scope. Using @code{with} and @code{endwith}
11383: also allows you to create code using selector @code{postpone} without being
11384: trapped by the state-smart objects.
1.21 crook 11385:
1.78 anton 11386: doc---object-with
11387: doc---object-endwith
1.21 crook 11388:
11389:
1.78 anton 11390: @end itemize
1.21 crook 11391:
1.78 anton 11392: @node Class Declaration, Class Implementation, The OOF base class, OOF
11393: @subsubsection Class Declaration
11394: @cindex class declaration
1.21 crook 11395:
1.78 anton 11396: @itemize @bullet
11397: @item
11398: Instance variables
1.21 crook 11399:
1.78 anton 11400: doc---oof-var
1.21 crook 11401:
11402:
1.78 anton 11403: @item
11404: Object pointers
1.21 crook 11405:
1.78 anton 11406: doc---oof-ptr
11407: doc---oof-asptr
1.21 crook 11408:
11409:
1.78 anton 11410: @item
11411: Instance defers
1.21 crook 11412:
1.78 anton 11413: doc---oof-defer
1.21 crook 11414:
11415:
1.78 anton 11416: @item
11417: Method selectors
1.21 crook 11418:
1.78 anton 11419: doc---oof-early
11420: doc---oof-method
1.21 crook 11421:
11422:
1.78 anton 11423: @item
11424: Class-wide variables
1.21 crook 11425:
1.78 anton 11426: doc---oof-static
1.21 crook 11427:
11428:
1.78 anton 11429: @item
11430: End declaration
1.1 anton 11431:
1.78 anton 11432: doc---oof-how:
11433: doc---oof-class;
1.21 crook 11434:
11435:
1.78 anton 11436: @end itemize
1.21 crook 11437:
1.78 anton 11438: @c -------------------------------------------------------------
11439: @node Class Implementation, , Class Declaration, OOF
11440: @subsubsection Class Implementation
11441: @cindex class implementation
1.21 crook 11442:
1.78 anton 11443: @c -------------------------------------------------------------
11444: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11445: @subsection The @file{mini-oof.fs} model
11446: @cindex mini-oof
1.21 crook 11447:
1.78 anton 11448: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11449: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11450: and reduces to the bare minimum of features. This is based on a posting
11451: of Bernd Paysan in comp.lang.forth.
1.21 crook 11452:
1.78 anton 11453: @menu
11454: * Basic Mini-OOF Usage::
11455: * Mini-OOF Example::
11456: * Mini-OOF Implementation::
11457: @end menu
1.21 crook 11458:
1.78 anton 11459: @c -------------------------------------------------------------
11460: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11461: @subsubsection Basic @file{mini-oof.fs} Usage
11462: @cindex mini-oof usage
1.21 crook 11463:
1.78 anton 11464: There is a base class (@code{class}, which allocates one cell for the
11465: object pointer) plus seven other words: to define a method, a variable,
11466: a class; to end a class, to resolve binding, to allocate an object and
11467: to compile a class method.
11468: @comment TODO better description of the last one
1.26 crook 11469:
1.21 crook 11470:
1.78 anton 11471: doc-object
11472: doc-method
11473: doc-var
11474: doc-class
11475: doc-end-class
11476: doc-defines
11477: doc-new
11478: doc-::
1.21 crook 11479:
11480:
11481:
1.78 anton 11482: @c -------------------------------------------------------------
11483: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11484: @subsubsection Mini-OOF Example
11485: @cindex mini-oof example
1.1 anton 11486:
1.78 anton 11487: A short example shows how to use this package. This example, in slightly
11488: extended form, is supplied as @file{moof-exm.fs}
11489: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11490:
1.26 crook 11491: @example
1.78 anton 11492: object class
11493: method init
11494: method draw
11495: end-class graphical
1.26 crook 11496: @end example
1.20 pazsan 11497:
1.78 anton 11498: This code defines a class @code{graphical} with an
11499: operation @code{draw}. We can perform the operation
11500: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11501:
1.26 crook 11502: @example
1.78 anton 11503: 100 100 t-rex draw
1.26 crook 11504: @end example
1.12 anton 11505:
1.78 anton 11506: where @code{t-rex} is an object or object pointer, created with e.g.
11507: @code{graphical new Constant t-rex}.
1.12 anton 11508:
1.78 anton 11509: For concrete graphical objects, we define child classes of the
11510: class @code{graphical}, e.g.:
1.12 anton 11511:
1.26 crook 11512: @example
11513: graphical class
1.78 anton 11514: cell var circle-radius
11515: end-class circle \ "graphical" is the parent class
1.12 anton 11516:
1.78 anton 11517: :noname ( x y -- )
11518: circle-radius @@ draw-circle ; circle defines draw
11519: :noname ( r -- )
11520: circle-radius ! ; circle defines init
11521: @end example
1.12 anton 11522:
1.78 anton 11523: There is no implicit init method, so we have to define one. The creation
11524: code of the object now has to call init explicitely.
1.21 crook 11525:
1.78 anton 11526: @example
11527: circle new Constant my-circle
11528: 50 my-circle init
1.12 anton 11529: @end example
11530:
1.78 anton 11531: It is also possible to add a function to create named objects with
11532: automatic call of @code{init}, given that all objects have @code{init}
11533: on the same place:
1.38 anton 11534:
1.78 anton 11535: @example
11536: : new: ( .. o "name" -- )
11537: new dup Constant init ;
11538: 80 circle new: large-circle
11539: @end example
1.12 anton 11540:
1.78 anton 11541: We can draw this new circle at (100,100) with:
1.12 anton 11542:
1.78 anton 11543: @example
11544: 100 100 my-circle draw
11545: @end example
1.12 anton 11546:
1.78 anton 11547: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11548: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11549:
1.78 anton 11550: Object-oriented systems with late binding typically use a
11551: ``vtable''-approach: the first variable in each object is a pointer to a
11552: table, which contains the methods as function pointers. The vtable
11553: may also contain other information.
1.12 anton 11554:
1.79 anton 11555: So first, let's declare selectors:
1.37 anton 11556:
11557: @example
1.79 anton 11558: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11559: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11560: @end example
1.37 anton 11561:
1.79 anton 11562: During selector declaration, the number of selectors and instance
11563: variables is on the stack (in address units). @code{method} creates one
11564: selector and increments the selector number. To execute a selector, it
1.78 anton 11565: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11566: executes the method @i{xt} stored there. Each selector takes the object
11567: it is invoked with as top of stack parameter; it passes the parameters
11568: (including the object) unchanged to the appropriate method which should
1.78 anton 11569: consume that object.
1.37 anton 11570:
1.78 anton 11571: Now, we also have to declare instance variables
1.37 anton 11572:
1.78 anton 11573: @example
1.79 anton 11574: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11575: DOES> ( o -- addr ) @@ + ;
1.37 anton 11576: @end example
11577:
1.78 anton 11578: As before, a word is created with the current offset. Instance
11579: variables can have different sizes (cells, floats, doubles, chars), so
11580: all we do is take the size and add it to the offset. If your machine
11581: has alignment restrictions, put the proper @code{aligned} or
11582: @code{faligned} before the variable, to adjust the variable
11583: offset. That's why it is on the top of stack.
1.37 anton 11584:
1.78 anton 11585: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11586:
1.78 anton 11587: @example
11588: Create object 1 cells , 2 cells ,
1.79 anton 11589: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11590: @end example
1.12 anton 11591:
1.78 anton 11592: For inheritance, the vtable of the parent object has to be
11593: copied when a new, derived class is declared. This gives all the
11594: methods of the parent class, which can be overridden, though.
1.12 anton 11595:
1.78 anton 11596: @example
1.79 anton 11597: : end-class ( class selectors vars "name" -- )
1.78 anton 11598: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11599: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11600: @end example
1.12 anton 11601:
1.78 anton 11602: The first line creates the vtable, initialized with
11603: @code{noop}s. The second line is the inheritance mechanism, it
11604: copies the xts from the parent vtable.
1.12 anton 11605:
1.78 anton 11606: We still have no way to define new methods, let's do that now:
1.12 anton 11607:
1.26 crook 11608: @example
1.79 anton 11609: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11610: @end example
1.12 anton 11611:
1.78 anton 11612: To allocate a new object, we need a word, too:
1.12 anton 11613:
1.78 anton 11614: @example
11615: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11616: @end example
11617:
1.78 anton 11618: Sometimes derived classes want to access the method of the
11619: parent object. There are two ways to achieve this with Mini-OOF:
11620: first, you could use named words, and second, you could look up the
11621: vtable of the parent object.
1.12 anton 11622:
1.78 anton 11623: @example
11624: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11625: @end example
1.12 anton 11626:
11627:
1.78 anton 11628: Nothing can be more confusing than a good example, so here is
11629: one. First let's declare a text object (called
11630: @code{button}), that stores text and position:
1.12 anton 11631:
1.78 anton 11632: @example
11633: object class
11634: cell var text
11635: cell var len
11636: cell var x
11637: cell var y
11638: method init
11639: method draw
11640: end-class button
11641: @end example
1.12 anton 11642:
1.78 anton 11643: @noindent
11644: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11645:
1.26 crook 11646: @example
1.78 anton 11647: :noname ( o -- )
11648: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11649: button defines draw
11650: :noname ( addr u o -- )
11651: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11652: button defines init
1.26 crook 11653: @end example
1.12 anton 11654:
1.78 anton 11655: @noindent
11656: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11657: new data and no new selectors:
1.78 anton 11658:
11659: @example
11660: button class
11661: end-class bold-button
1.12 anton 11662:
1.78 anton 11663: : bold 27 emit ." [1m" ;
11664: : normal 27 emit ." [0m" ;
11665: @end example
1.1 anton 11666:
1.78 anton 11667: @noindent
11668: The class @code{bold-button} has a different draw method to
11669: @code{button}, but the new method is defined in terms of the draw method
11670: for @code{button}:
1.20 pazsan 11671:
1.78 anton 11672: @example
11673: :noname bold [ button :: draw ] normal ; bold-button defines draw
11674: @end example
1.21 crook 11675:
1.78 anton 11676: @noindent
1.79 anton 11677: Finally, create two objects and apply selectors:
1.21 crook 11678:
1.26 crook 11679: @example
1.78 anton 11680: button new Constant foo
11681: s" thin foo" foo init
11682: page
11683: foo draw
11684: bold-button new Constant bar
11685: s" fat bar" bar init
11686: 1 bar y !
11687: bar draw
1.26 crook 11688: @end example
1.21 crook 11689:
11690:
1.78 anton 11691: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11692: @subsection Comparison with other object models
11693: @cindex comparison of object models
11694: @cindex object models, comparison
11695:
11696: Many object-oriented Forth extensions have been proposed (@cite{A survey
11697: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11698: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11699: relation of the object models described here to two well-known and two
11700: closely-related (by the use of method maps) models. Andras Zsoter
11701: helped us with this section.
11702:
11703: @cindex Neon model
11704: The most popular model currently seems to be the Neon model (see
11705: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11706: 1997) by Andrew McKewan) but this model has a number of limitations
11707: @footnote{A longer version of this critique can be
11708: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11709: Dimensions, May 1997) by Anton Ertl.}:
11710:
11711: @itemize @bullet
11712: @item
11713: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11714: to pass objects on the stack.
1.21 crook 11715:
1.78 anton 11716: @item
11717: It requires that the selector parses the input stream (at
1.79 anton 11718: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11719: hard to find.
1.21 crook 11720:
1.78 anton 11721: @item
1.79 anton 11722: It allows using every selector on every object; this eliminates the
11723: need for interfaces, but makes it harder to create efficient
11724: implementations.
1.78 anton 11725: @end itemize
1.21 crook 11726:
1.78 anton 11727: @cindex Pountain's object-oriented model
11728: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11729: Press, London, 1987) by Dick Pountain. However, it is not really about
11730: object-oriented programming, because it hardly deals with late
11731: binding. Instead, it focuses on features like information hiding and
11732: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11733:
1.78 anton 11734: @cindex Zsoter's object-oriented model
1.79 anton 11735: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11736: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11737: describes a model that makes heavy use of an active object (like
11738: @code{this} in @file{objects.fs}): The active object is not only used
11739: for accessing all fields, but also specifies the receiving object of
11740: every selector invocation; you have to change the active object
11741: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11742: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11743: the method entry point is unnecessary with Zsoter's model, because the
11744: receiving object is the active object already. On the other hand, the
11745: explicit change is absolutely necessary in that model, because otherwise
11746: no one could ever change the active object. An ANS Forth implementation
11747: of this model is available through
11748: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11749:
1.78 anton 11750: @cindex @file{oof.fs}, differences to other models
11751: The @file{oof.fs} model combines information hiding and overloading
11752: resolution (by keeping names in various word lists) with object-oriented
11753: programming. It sets the active object implicitly on method entry, but
11754: also allows explicit changing (with @code{>o...o>} or with
11755: @code{with...endwith}). It uses parsing and state-smart objects and
11756: classes for resolving overloading and for early binding: the object or
11757: class parses the selector and determines the method from this. If the
11758: selector is not parsed by an object or class, it performs a call to the
11759: selector for the active object (late binding), like Zsoter's model.
11760: Fields are always accessed through the active object. The big
11761: disadvantage of this model is the parsing and the state-smartness, which
11762: reduces extensibility and increases the opportunities for subtle bugs;
11763: essentially, you are only safe if you never tick or @code{postpone} an
11764: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11765:
1.78 anton 11766: @cindex @file{mini-oof.fs}, differences to other models
11767: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11768: version of the @file{objects.fs} model, but syntactically it is a
11769: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11770:
11771:
1.78 anton 11772: @c -------------------------------------------------------------
1.150 anton 11773: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11774: @section Programming Tools
11775: @cindex programming tools
1.21 crook 11776:
1.78 anton 11777: @c !! move this and assembler down below OO stuff.
1.21 crook 11778:
1.78 anton 11779: @menu
1.150 anton 11780: * Examining:: Data and Code.
11781: * Forgetting words:: Usually before reloading.
1.78 anton 11782: * Debugging:: Simple and quick.
11783: * Assertions:: Making your programs self-checking.
11784: * Singlestep Debugger:: Executing your program word by word.
11785: @end menu
1.21 crook 11786:
1.78 anton 11787: @node Examining, Forgetting words, Programming Tools, Programming Tools
11788: @subsection Examining data and code
11789: @cindex examining data and code
11790: @cindex data examination
11791: @cindex code examination
1.44 crook 11792:
1.78 anton 11793: The following words inspect the stack non-destructively:
1.21 crook 11794:
1.78 anton 11795: doc-.s
11796: doc-f.s
1.158 anton 11797: doc-maxdepth-.s
1.44 crook 11798:
1.78 anton 11799: There is a word @code{.r} but it does @i{not} display the return stack!
11800: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11801:
1.78 anton 11802: doc-depth
11803: doc-fdepth
11804: doc-clearstack
1.124 anton 11805: doc-clearstacks
1.21 crook 11806:
1.78 anton 11807: The following words inspect memory.
1.21 crook 11808:
1.78 anton 11809: doc-?
11810: doc-dump
1.21 crook 11811:
1.78 anton 11812: And finally, @code{see} allows to inspect code:
1.21 crook 11813:
1.78 anton 11814: doc-see
11815: doc-xt-see
1.111 anton 11816: doc-simple-see
11817: doc-simple-see-range
1.182 anton 11818: doc-see-code
11819: doc-see-code-range
1.21 crook 11820:
1.78 anton 11821: @node Forgetting words, Debugging, Examining, Programming Tools
11822: @subsection Forgetting words
11823: @cindex words, forgetting
11824: @cindex forgeting words
1.21 crook 11825:
1.78 anton 11826: @c anton: other, maybe better places for this subsection: Defining Words;
11827: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11828:
1.78 anton 11829: Forth allows you to forget words (and everything that was alloted in the
11830: dictonary after them) in a LIFO manner.
1.21 crook 11831:
1.78 anton 11832: doc-marker
1.21 crook 11833:
1.78 anton 11834: The most common use of this feature is during progam development: when
11835: you change a source file, forget all the words it defined and load it
11836: again (since you also forget everything defined after the source file
11837: was loaded, you have to reload that, too). Note that effects like
11838: storing to variables and destroyed system words are not undone when you
11839: forget words. With a system like Gforth, that is fast enough at
11840: starting up and compiling, I find it more convenient to exit and restart
11841: Gforth, as this gives me a clean slate.
1.21 crook 11842:
1.78 anton 11843: Here's an example of using @code{marker} at the start of a source file
11844: that you are debugging; it ensures that you only ever have one copy of
11845: the file's definitions compiled at any time:
1.21 crook 11846:
1.78 anton 11847: @example
11848: [IFDEF] my-code
11849: my-code
11850: [ENDIF]
1.26 crook 11851:
1.78 anton 11852: marker my-code
11853: init-included-files
1.21 crook 11854:
1.78 anton 11855: \ .. definitions start here
11856: \ .
11857: \ .
11858: \ end
11859: @end example
1.21 crook 11860:
1.26 crook 11861:
1.78 anton 11862: @node Debugging, Assertions, Forgetting words, Programming Tools
11863: @subsection Debugging
11864: @cindex debugging
1.21 crook 11865:
1.78 anton 11866: Languages with a slow edit/compile/link/test development loop tend to
11867: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11868:
1.78 anton 11869: A much better (faster) way in fast-compiling languages is to add
11870: printing code at well-selected places, let the program run, look at
11871: the output, see where things went wrong, add more printing code, etc.,
11872: until the bug is found.
1.21 crook 11873:
1.78 anton 11874: The simple debugging aids provided in @file{debugs.fs}
11875: are meant to support this style of debugging.
1.21 crook 11876:
1.78 anton 11877: The word @code{~~} prints debugging information (by default the source
11878: location and the stack contents). It is easy to insert. If you use Emacs
11879: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11880: query-replace them with nothing). The deferred words
1.101 anton 11881: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11882: @code{~~}. The default source location output format works well with
11883: Emacs' compilation mode, so you can step through the program at the
11884: source level using @kbd{C-x `} (the advantage over a stepping debugger
11885: is that you can step in any direction and you know where the crash has
11886: happened or where the strange data has occurred).
1.21 crook 11887:
1.78 anton 11888: doc-~~
11889: doc-printdebugdata
1.101 anton 11890: doc-.debugline
1.21 crook 11891:
1.106 anton 11892: @cindex filenames in @code{~~} output
11893: @code{~~} (and assertions) will usually print the wrong file name if a
11894: marker is executed in the same file after their occurance. They will
11895: print @samp{*somewhere*} as file name if a marker is executed in the
11896: same file before their occurance.
11897:
11898:
1.78 anton 11899: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11900: @subsection Assertions
11901: @cindex assertions
1.21 crook 11902:
1.78 anton 11903: It is a good idea to make your programs self-checking, especially if you
11904: make an assumption that may become invalid during maintenance (for
11905: example, that a certain field of a data structure is never zero). Gforth
11906: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 11907:
11908: @example
1.78 anton 11909: assert( @i{flag} )
1.26 crook 11910: @end example
11911:
1.78 anton 11912: The code between @code{assert(} and @code{)} should compute a flag, that
11913: should be true if everything is alright and false otherwise. It should
11914: not change anything else on the stack. The overall stack effect of the
11915: assertion is @code{( -- )}. E.g.
1.21 crook 11916:
1.26 crook 11917: @example
1.78 anton 11918: assert( 1 1 + 2 = ) \ what we learn in school
11919: assert( dup 0<> ) \ assert that the top of stack is not zero
11920: assert( false ) \ this code should not be reached
1.21 crook 11921: @end example
11922:
1.78 anton 11923: The need for assertions is different at different times. During
11924: debugging, we want more checking, in production we sometimes care more
11925: for speed. Therefore, assertions can be turned off, i.e., the assertion
11926: becomes a comment. Depending on the importance of an assertion and the
11927: time it takes to check it, you may want to turn off some assertions and
11928: keep others turned on. Gforth provides several levels of assertions for
11929: this purpose:
11930:
11931:
11932: doc-assert0(
11933: doc-assert1(
11934: doc-assert2(
11935: doc-assert3(
11936: doc-assert(
11937: doc-)
1.21 crook 11938:
11939:
1.78 anton 11940: The variable @code{assert-level} specifies the highest assertions that
11941: are turned on. I.e., at the default @code{assert-level} of one,
11942: @code{assert0(} and @code{assert1(} assertions perform checking, while
11943: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 11944:
1.78 anton 11945: The value of @code{assert-level} is evaluated at compile-time, not at
11946: run-time. Therefore you cannot turn assertions on or off at run-time;
11947: you have to set the @code{assert-level} appropriately before compiling a
11948: piece of code. You can compile different pieces of code at different
11949: @code{assert-level}s (e.g., a trusted library at level 1 and
11950: newly-written code at level 3).
1.26 crook 11951:
11952:
1.78 anton 11953: doc-assert-level
1.26 crook 11954:
11955:
1.78 anton 11956: If an assertion fails, a message compatible with Emacs' compilation mode
11957: is produced and the execution is aborted (currently with @code{ABORT"}.
11958: If there is interest, we will introduce a special throw code. But if you
11959: intend to @code{catch} a specific condition, using @code{throw} is
11960: probably more appropriate than an assertion).
1.106 anton 11961:
11962: @cindex filenames in assertion output
11963: Assertions (and @code{~~}) will usually print the wrong file name if a
11964: marker is executed in the same file after their occurance. They will
11965: print @samp{*somewhere*} as file name if a marker is executed in the
11966: same file before their occurance.
1.44 crook 11967:
1.78 anton 11968: Definitions in ANS Forth for these assertion words are provided
11969: in @file{compat/assert.fs}.
1.26 crook 11970:
1.44 crook 11971:
1.78 anton 11972: @node Singlestep Debugger, , Assertions, Programming Tools
11973: @subsection Singlestep Debugger
11974: @cindex singlestep Debugger
11975: @cindex debugging Singlestep
1.44 crook 11976:
1.189 anton 11977: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 11978:
1.78 anton 11979: When you create a new word there's often the need to check whether it
11980: behaves correctly or not. You can do this by typing @code{dbg
11981: badword}. A debug session might look like this:
1.26 crook 11982:
1.78 anton 11983: @example
11984: : badword 0 DO i . LOOP ; ok
11985: 2 dbg badword
11986: : badword
11987: Scanning code...
1.44 crook 11988:
1.78 anton 11989: Nesting debugger ready!
1.44 crook 11990:
1.78 anton 11991: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
11992: 400D4740 8049F68 DO -> [ 0 ]
11993: 400D4744 804A0C8 i -> [ 1 ] 00000
11994: 400D4748 400C5E60 . -> 0 [ 0 ]
11995: 400D474C 8049D0C LOOP -> [ 0 ]
11996: 400D4744 804A0C8 i -> [ 1 ] 00001
11997: 400D4748 400C5E60 . -> 1 [ 0 ]
11998: 400D474C 8049D0C LOOP -> [ 0 ]
11999: 400D4758 804B384 ; -> ok
12000: @end example
1.21 crook 12001:
1.78 anton 12002: Each line displayed is one step. You always have to hit return to
12003: execute the next word that is displayed. If you don't want to execute
12004: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12005: an overview what keys are available:
1.44 crook 12006:
1.78 anton 12007: @table @i
1.44 crook 12008:
1.78 anton 12009: @item @key{RET}
12010: Next; Execute the next word.
1.21 crook 12011:
1.78 anton 12012: @item n
12013: Nest; Single step through next word.
1.44 crook 12014:
1.78 anton 12015: @item u
12016: Unnest; Stop debugging and execute rest of word. If we got to this word
12017: with nest, continue debugging with the calling word.
1.44 crook 12018:
1.78 anton 12019: @item d
12020: Done; Stop debugging and execute rest.
1.21 crook 12021:
1.78 anton 12022: @item s
12023: Stop; Abort immediately.
1.44 crook 12024:
1.78 anton 12025: @end table
1.44 crook 12026:
1.78 anton 12027: Debugging large application with this mechanism is very difficult, because
12028: you have to nest very deeply into the program before the interesting part
12029: begins. This takes a lot of time.
1.26 crook 12030:
1.78 anton 12031: To do it more directly put a @code{BREAK:} command into your source code.
12032: When program execution reaches @code{BREAK:} the single step debugger is
12033: invoked and you have all the features described above.
1.44 crook 12034:
1.78 anton 12035: If you have more than one part to debug it is useful to know where the
12036: program has stopped at the moment. You can do this by the
12037: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12038: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12039:
1.26 crook 12040:
1.78 anton 12041: doc-dbg
12042: doc-break:
12043: doc-break"
1.44 crook 12044:
1.150 anton 12045: @c ------------------------------------------------------------
12046: @node C Interface, Assembler and Code Words, Programming Tools, Words
12047: @section C Interface
12048: @cindex C interface
12049: @cindex foreign language interface
12050: @cindex interface to C functions
12051:
1.178 anton 12052: Note that the C interface is not yet complete; callbacks are missing,
12053: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12054:
12055: @menu
12056: * Calling C Functions::
12057: * Declaring C Functions::
1.180 anton 12058: * Calling C function pointers::
1.195 ! anton 12059: * Declaring libraries::
1.150 anton 12060: * Callbacks::
1.178 anton 12061: * C interface internals::
1.155 anton 12062: * Low-Level C Interface Words::
1.150 anton 12063: @end menu
12064:
1.151 pazsan 12065: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12066: @subsection Calling C functions
1.155 anton 12067: @cindex C functions, calls to
12068: @cindex calling C functions
1.150 anton 12069:
1.151 pazsan 12070: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12071: can call it as follows: You push the arguments on the stack(s), and
12072: then call the word for the C function. The arguments have to be
12073: pushed in the same order as the arguments appear in the C
12074: documentation (i.e., the first argument is deepest on the stack).
12075: Integer and pointer arguments have to be pushed on the data stack,
12076: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12077: by the called C function.
1.150 anton 12078:
1.155 anton 12079: On returning from the C function, the return value, if any, resides on
12080: the appropriate stack: an integer return value is pushed on the data
12081: stack, an FP return value on the FP stack, and a void return value
12082: results in not pushing anything. Note that most C functions have a
12083: return value, even if that is often not used in C; in Forth, you have
12084: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12085:
1.177 anton 12086: The C interface automatically converts between the C type and the
12087: Forth type as necessary, on a best-effort basis (in some cases, there
12088: may be some loss).
1.150 anton 12089:
12090: As an example, consider the POSIX function @code{lseek()}:
12091:
12092: @example
12093: off_t lseek(int fd, off_t offset, int whence);
12094: @end example
12095:
12096: This function takes three integer arguments, and returns an integer
12097: argument, so a Forth call for setting the current file offset to the
12098: start of the file could look like this:
12099:
12100: @example
12101: fd @@ 0 SEEK_SET lseek -1 = if
12102: ... \ error handling
12103: then
12104: @end example
12105:
12106: You might be worried that an @code{off_t} does not fit into a cell, so
12107: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12108: of the return values. In that case, in your declaration of the
12109: function (@pxref{Declaring C Functions}) you should declare it to use
12110: double-cells for the off_t argument and return value, and maybe give
12111: the resulting Forth word a different name, like @code{dlseek}; the
12112: result could be called like this:
1.150 anton 12113:
12114: @example
12115: fd @@ 0. SEEK_SET dlseek -1. d= if
12116: ... \ error handling
12117: then
12118: @end example
12119:
12120: Passing and returning structs or unions is currently not supported by
12121: our interface@footnote{If you know the calling convention of your C
12122: compiler, you usually can call such functions in some way, but that
12123: way is usually not portable between platforms, and sometimes not even
12124: between C compilers.}.
12125:
1.177 anton 12126: Calling functions with a variable number of arguments (@emph{variadic}
12127: functions, e.g., @code{printf()}) is only supported by having you
12128: declare one function-calling word for each argument pattern, and
12129: calling the appropriate word for the desired pattern.
12130:
1.150 anton 12131:
1.155 anton 12132:
1.180 anton 12133: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12134: @subsection Declaring C Functions
1.155 anton 12135: @cindex C functions, declarations
12136: @cindex declaring C functions
1.150 anton 12137:
12138: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12139: it. The declaration consists of two parts:
12140:
12141: @table @b
12142:
12143: @item The C part
1.179 anton 12144: is the C declaration of the function, or more typically and portably,
12145: a C-style @code{#include} of a file that contains the declaration of
12146: the C function.
1.177 anton 12147:
12148: @item The Forth part
12149: declares the Forth types of the parameters and the Forth word name
12150: corresponding to the C function.
12151:
12152: @end table
12153:
12154: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12155: declarations are:
12156:
12157: @example
12158: \c #define _FILE_OFFSET_BITS 64
12159: \c #include <sys/types.h>
12160: \c #include <unistd.h>
12161: c-function lseek lseek n n n -- n
12162: c-function dlseek lseek n d n -- d
12163: @end example
12164:
1.178 anton 12165: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12166: of the line is ordinary C code. You can use as many lines of C
12167: declarations as you like, and they are visible for all further
12168: function declarations.
12169:
12170: The Forth part declares each interface word with @code{c-function},
12171: followed by the Forth name of the word, the C name of the called
12172: function, and the stack effect of the word. The stack effect contains
1.178 anton 12173: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12174: exactly one type for the return value. The possible types are:
12175:
12176: @table @code
12177:
12178: @item n
12179: single-cell integer
12180:
12181: @item a
12182: address (single-cell)
12183:
12184: @item d
12185: double-cell integer
12186:
12187: @item r
12188: floating-point value
12189:
12190: @item func
12191: C function pointer
12192:
12193: @item void
12194: no value (used as return type for void functions)
12195:
12196: @end table
12197:
12198: @cindex variadic C functions
12199:
12200: To deal with variadic C functions, you can declare one Forth word for
12201: every pattern you want to use, e.g.:
12202:
12203: @example
12204: \c #include <stdio.h>
12205: c-function printf-nr printf a n r -- n
12206: c-function printf-rn printf a r n -- n
12207: @end example
12208:
12209: Note that with C functions declared as variadic (or if you don't
12210: provide a prototype), the C interface has no C type to convert to, so
12211: no automatic conversion happens, which may lead to portability
12212: problems in some cases. In such cases you can perform the conversion
12213: explicitly on the C level, e.g., as follows:
12214:
12215: @example
1.178 anton 12216: \c #define printfll(s,ll) printf(s,(long long)ll)
12217: c-function printfll printfll a n -- n
1.177 anton 12218: @end example
12219:
12220: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12221: that casts (converts) the Forth single-cell integer into a
12222: C @code{long long} before calling @code{printf()}.
1.177 anton 12223:
12224: doc-\c
12225: doc-c-function
12226:
12227: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12228: dynamic linking. If these features are not available, there are
12229: other, less convenient and less portable C interfaces in @file{lib.fs}
12230: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12231: mostly incompatible with each other and with the documented C
12232: interface; you can find some examples for the @file{lib.fs} interface
12233: in @file{lib.fs}.
1.177 anton 12234:
12235:
1.195 ! anton 12236: @node Calling C function pointers, Declaring libraries, Declaring C Functions, C Interface
1.180 anton 12237: @subsection Calling C function pointers from Forth
12238: @cindex C function pointers, calling from Forth
1.177 anton 12239:
1.180 anton 12240: If you come across a C function pointer (e.g., in some C-constructed
12241: structure) and want to call it from your Forth program, you can also
12242: use the features explained until now to achieve that, as follows:
1.150 anton 12243:
1.180 anton 12244: Let us assume that there is a C function pointer type @code{func1}
12245: defined in some header file @file{func1.h}, and you know that these
12246: functions take one integer argument and return an integer result; and
12247: you want to call functions through such pointers. Just define
1.155 anton 12248:
1.180 anton 12249: @example
12250: \c #include <func1.h>
12251: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12252: c-function call-func1 call_func1 n func -- n
12253: @end example
12254:
12255: and then you can call a function pointed to by, say @code{func1a} as
12256: follows:
12257:
12258: @example
12259: -5 func1a call-func1 .
12260: @end example
12261:
12262: In the C part, @code{call_func} is defined as a macro to avoid having
12263: to declare the exact parameter and return types, so the C compiler
12264: knows them from the declaration of @code{func1}.
12265:
12266: The Forth word @code{call-func1} is similar to @code{execute}, except
12267: that it takes a C @code{func1} pointer instead of a Forth execution
12268: token, and it is specific to @code{func1} pointers. For each type of
12269: function pointer you want to call from Forth, you have to define
12270: a separate calling word.
12271:
12272:
1.195 ! anton 12273: @node Declaring libraries, Callbacks, Calling C function pointers, C Interface
! 12274: @subsection Declaring libraries
! 12275: @cindex Shared libraries in C interface
! 12276: @cindex Dynamically linked libraries in C interface
! 12277: @cindex Libraries in C interface
! 12278:
! 12279: For calling some C functions, you need to link with a specific library
! 12280: that contains that library. E.g., the @code{sin} function requires
! 12281: linking a special library by using the command line switch @code{-lm}.
! 12282: In our C iterface you do the equivalent thing by calling
! 12283: @code{add-lib} as follows:
! 12284:
! 12285: @example
! 12286: clear-libs
! 12287: s" m" add-lib
! 12288: \c #include <math.h>
! 12289: c-function sin sin r -- r
! 12290: @end example
! 12291:
! 12292: First, you clear any libraries that may have been declared earlier
! 12293: (you don't need them for @code{sin}); then you add the @code{m}
! 12294: library (actually @code{libm.so} or somesuch) to the currently
! 12295: declared libraries; you can add as many as you need. Finally you
! 12296: declare the function as shown above. Typically you will use the same
! 12297: set of library declarations for many function declarations; you need
! 12298: to write only one set for that, right at the beginning.
! 12299:
! 12300: doc-clear-libs
! 12301: doc-add-lib
! 12302:
! 12303:
! 12304: @node Callbacks, C interface internals, Declaring libraries, C Interface
1.150 anton 12305: @subsection Callbacks
1.155 anton 12306: @cindex Callback functions written in Forth
12307: @cindex C function pointers to Forth words
12308:
1.177 anton 12309: Callbacks are not yet supported by the documented C interface. You
12310: can use the undocumented @file{lib.fs} interface for callbacks.
12311:
1.155 anton 12312: In some cases you have to pass a function pointer to a C function,
12313: i.e., the library wants to call back to your application (and the
12314: pointed-to function is called a callback function). You can pass the
12315: address of an existing C function (that you get with @code{lib-sym},
12316: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12317: function, you probably want to define the function as a Forth word.
12318:
12319: @c I don't understand the existing callback interface from the example - anton
12320:
1.165 anton 12321:
12322: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12323: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12324: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12325: @c > > C-Funktionsadresse auf dem TOS).
12326: @c >
12327: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12328: @c > gesehen habe, wozu das gut ist.
12329: @c
12330: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12331: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12332: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12333: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12334: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12335: @c demselben Prototyp.
12336:
12337:
1.178 anton 12338: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12339: @subsection How the C interface works
12340:
12341: The documented C interface works by generating a C code out of the
12342: declarations.
12343:
12344: In particular, for every Forth word declared with @code{c-function},
12345: it generates a wrapper function in C that takes the Forth data from
12346: the Forth stacks, and calls the target C function with these data as
12347: arguments. The C compiler then performs an implicit conversion
12348: between the Forth type from the stack, and the C type for the
12349: parameter, which is given by the C function prototype. After the C
12350: function returns, the return value is likewise implicitly converted to
12351: a Forth type and written back on the stack.
12352:
12353: The @code{\c} lines are literally included in the C code (but without
12354: the @code{\c}), and provide the necessary declarations so that the C
12355: compiler knows the C types and has enough information to perform the
12356: conversion.
12357:
12358: These wrapper functions are eventually compiled and dynamically linked
12359: into Gforth, and then they can be called.
12360:
1.195 ! anton 12361: The libraries added with @code{add-lib} are used in the compile
! 12362: command line to specify dependent libraries with @code{-l@var{lib}},
! 12363: causing these libraries to be dynamically linked when the wrapper
! 12364: function is linked.
! 12365:
1.177 anton 12366:
1.178 anton 12367: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12368: @subsection Low-Level C Interface Words
1.44 crook 12369:
1.155 anton 12370: doc-open-lib
12371: doc-lib-sym
1.177 anton 12372: doc-call-c
1.26 crook 12373:
1.78 anton 12374: @c -------------------------------------------------------------
1.150 anton 12375: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12376: @section Assembler and Code Words
12377: @cindex assembler
12378: @cindex code words
1.44 crook 12379:
1.78 anton 12380: @menu
12381: * Code and ;code::
12382: * Common Assembler:: Assembler Syntax
12383: * Common Disassembler::
12384: * 386 Assembler:: Deviations and special cases
12385: * Alpha Assembler:: Deviations and special cases
12386: * MIPS assembler:: Deviations and special cases
1.161 anton 12387: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12388: * ARM Assembler:: Deviations and special cases
1.78 anton 12389: * Other assemblers:: How to write them
12390: @end menu
1.21 crook 12391:
1.78 anton 12392: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12393: @subsection @code{Code} and @code{;code}
1.26 crook 12394:
1.78 anton 12395: Gforth provides some words for defining primitives (words written in
12396: machine code), and for defining the machine-code equivalent of
12397: @code{DOES>}-based defining words. However, the machine-independent
12398: nature of Gforth poses a few problems: First of all, Gforth runs on
12399: several architectures, so it can provide no standard assembler. What's
12400: worse is that the register allocation not only depends on the processor,
12401: but also on the @code{gcc} version and options used.
1.44 crook 12402:
1.78 anton 12403: The words that Gforth offers encapsulate some system dependences (e.g.,
12404: the header structure), so a system-independent assembler may be used in
12405: Gforth. If you do not have an assembler, you can compile machine code
12406: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12407: because these words emit stuff in @i{data} space; it works because
12408: Gforth has unified code/data spaces. Assembler isn't likely to be
12409: portable anyway.}.
1.21 crook 12410:
1.44 crook 12411:
1.78 anton 12412: doc-assembler
12413: doc-init-asm
12414: doc-code
12415: doc-end-code
12416: doc-;code
12417: doc-flush-icache
1.44 crook 12418:
1.21 crook 12419:
1.78 anton 12420: If @code{flush-icache} does not work correctly, @code{code} words
12421: etc. will not work (reliably), either.
1.44 crook 12422:
1.78 anton 12423: The typical usage of these @code{code} words can be shown most easily by
12424: analogy to the equivalent high-level defining words:
1.44 crook 12425:
1.78 anton 12426: @example
12427: : foo code foo
12428: <high-level Forth words> <assembler>
12429: ; end-code
12430:
12431: : bar : bar
12432: <high-level Forth words> <high-level Forth words>
12433: CREATE CREATE
12434: <high-level Forth words> <high-level Forth words>
12435: DOES> ;code
12436: <high-level Forth words> <assembler>
12437: ; end-code
12438: @end example
1.21 crook 12439:
1.78 anton 12440: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12441:
1.78 anton 12442: @cindex registers of the inner interpreter
12443: In the assembly code you will want to refer to the inner interpreter's
12444: registers (e.g., the data stack pointer) and you may want to use other
12445: registers for temporary storage. Unfortunately, the register allocation
12446: is installation-dependent.
1.44 crook 12447:
1.78 anton 12448: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12449: (return stack pointer) may be in different places in @code{gforth} and
12450: @code{gforth-fast}, or different installations. This means that you
12451: cannot write a @code{NEXT} routine that works reliably on both versions
12452: or different installations; so for doing @code{NEXT}, I recommend
12453: jumping to @code{' noop >code-address}, which contains nothing but a
12454: @code{NEXT}.
1.21 crook 12455:
1.78 anton 12456: For general accesses to the inner interpreter's registers, the easiest
12457: solution is to use explicit register declarations (@pxref{Explicit Reg
12458: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12459: all of the inner interpreter's registers: You have to compile Gforth
12460: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12461: the appropriate declarations must be present in the @code{machine.h}
12462: file (see @code{mips.h} for an example; you can find a full list of all
12463: declarable register symbols with @code{grep register engine.c}). If you
12464: give explicit registers to all variables that are declared at the
12465: beginning of @code{engine()}, you should be able to use the other
12466: caller-saved registers for temporary storage. Alternatively, you can use
12467: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12468: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12469: reserve a register (however, this restriction on register allocation may
12470: slow Gforth significantly).
1.44 crook 12471:
1.78 anton 12472: If this solution is not viable (e.g., because @code{gcc} does not allow
12473: you to explicitly declare all the registers you need), you have to find
12474: out by looking at the code where the inner interpreter's registers
12475: reside and which registers can be used for temporary storage. You can
12476: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12477:
1.78 anton 12478: In any case, it is good practice to abstract your assembly code from the
12479: actual register allocation. E.g., if the data stack pointer resides in
12480: register @code{$17}, create an alias for this register called @code{sp},
12481: and use that in your assembly code.
1.21 crook 12482:
1.78 anton 12483: @cindex code words, portable
12484: Another option for implementing normal and defining words efficiently
12485: is to add the desired functionality to the source of Gforth. For normal
12486: words you just have to edit @file{primitives} (@pxref{Automatic
12487: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12488: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12489: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12490:
1.78 anton 12491: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12492: @subsection Common Assembler
1.44 crook 12493:
1.78 anton 12494: The assemblers in Gforth generally use a postfix syntax, i.e., the
12495: instruction name follows the operands.
1.21 crook 12496:
1.78 anton 12497: The operands are passed in the usual order (the same that is used in the
12498: manual of the architecture). Since they all are Forth words, they have
12499: to be separated by spaces; you can also use Forth words to compute the
12500: operands.
1.44 crook 12501:
1.78 anton 12502: The instruction names usually end with a @code{,}. This makes it easier
12503: to visually separate instructions if you put several of them on one
12504: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12505:
1.78 anton 12506: Registers are usually specified by number; e.g., (decimal) @code{11}
12507: specifies registers R11 and F11 on the Alpha architecture (which one,
12508: depends on the instruction). The usual names are also available, e.g.,
12509: @code{s2} for R11 on Alpha.
1.21 crook 12510:
1.78 anton 12511: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12512: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12513: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12514: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12515: conditions are specified in a way specific to each assembler.
1.1 anton 12516:
1.78 anton 12517: Note that the register assignments of the Gforth engine can change
12518: between Gforth versions, or even between different compilations of the
12519: same Gforth version (e.g., if you use a different GCC version). So if
12520: you want to refer to Gforth's registers (e.g., the stack pointer or
12521: TOS), I recommend defining your own words for refering to these
12522: registers, and using them later on; then you can easily adapt to a
12523: changed register assignment. The stability of the register assignment
12524: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12525:
1.100 anton 12526: The most common use of these registers is to dispatch to the next word
12527: (the @code{next} routine). A portable way to do this is to jump to
12528: @code{' noop >code-address} (of course, this is less efficient than
12529: integrating the @code{next} code and scheduling it well).
1.1 anton 12530:
1.96 anton 12531: Another difference between Gforth version is that the top of stack is
12532: kept in memory in @code{gforth} and, on most platforms, in a register in
12533: @code{gforth-fast}.
12534:
1.78 anton 12535: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12536: @subsection Common Disassembler
1.127 anton 12537: @cindex disassembler, general
12538: @cindex gdb disassembler
1.1 anton 12539:
1.78 anton 12540: You can disassemble a @code{code} word with @code{see}
12541: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12542:
1.127 anton 12543: doc-discode
1.44 crook 12544:
1.127 anton 12545: There are two kinds of disassembler for Gforth: The Forth disassembler
12546: (available on some CPUs) and the gdb disassembler (available on
12547: platforms with @command{gdb} and @command{mktemp}). If both are
12548: available, the Forth disassembler is used by default. If you prefer
12549: the gdb disassembler, say
12550:
12551: @example
12552: ' disasm-gdb is discode
12553: @end example
12554:
12555: If neither is available, @code{discode} performs @code{dump}.
12556:
12557: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12558: assembler (i.e., same syntax, etc.). It also includes additional
12559: information in comments. In particular, the address of the instruction
12560: is given in a comment before the instruction.
1.1 anton 12561:
1.127 anton 12562: The gdb disassembler produces output in the same format as the gdb
12563: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12564: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12565: the 386 and AMD64 architectures).
12566:
1.78 anton 12567: @code{See} may display more or less than the actual code of the word,
12568: because the recognition of the end of the code is unreliable. You can
1.127 anton 12569: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12570: the code word is not immediately followed by a named word. If you have
1.116 anton 12571: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12572: to ensure that the end is recognized.
1.21 crook 12573:
1.78 anton 12574: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12575: @subsection 386 Assembler
1.44 crook 12576:
1.78 anton 12577: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12578: available under GPL, and originally part of bigFORTH.
1.21 crook 12579:
1.78 anton 12580: The 386 disassembler included in Gforth was written by Andrew McKewan
12581: and is in the public domain.
1.21 crook 12582:
1.91 anton 12583: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12584:
1.78 anton 12585: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12586:
1.78 anton 12587: The assembler includes all instruction of the Athlon, i.e. 486 core
12588: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12589: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12590: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12591:
1.78 anton 12592: There are several prefixes to switch between different operation sizes,
12593: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12594: double-word accesses. Addressing modes can be switched with @code{.wa}
12595: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12596: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12597:
1.78 anton 12598: For floating point operations, the prefixes are @code{.fs} (IEEE
12599: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12600: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12601:
1.78 anton 12602: The MMX opcodes don't have size prefixes, they are spelled out like in
12603: the Intel assembler. Instead of move from and to memory, there are
12604: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12605:
1.78 anton 12606: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12607: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12608: e.g., @code{3 #}. Here are some examples of addressing modes in various
12609: syntaxes:
1.21 crook 12610:
1.26 crook 12611: @example
1.91 anton 12612: Gforth Intel (NASM) AT&T (gas) Name
12613: .w ax ax %ax register (16 bit)
12614: ax eax %eax register (32 bit)
12615: 3 # offset 3 $3 immediate
12616: 1000 #) byte ptr 1000 1000 displacement
12617: bx ) [ebx] (%ebx) base
12618: 100 di d) 100[edi] 100(%edi) base+displacement
12619: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12620: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12621: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12622: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12623: @end example
12624:
12625: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12626: @code{DI)} to enforce 32-bit displacement fields (useful for
12627: later patching).
1.21 crook 12628:
1.78 anton 12629: Some example of instructions are:
1.1 anton 12630:
12631: @example
1.78 anton 12632: ax bx mov \ move ebx,eax
12633: 3 # ax mov \ mov eax,3
1.137 pazsan 12634: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12635: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12636: .w ax bx mov \ mov bx,ax
1.1 anton 12637: @end example
12638:
1.78 anton 12639: The following forms are supported for binary instructions:
1.1 anton 12640:
12641: @example
1.78 anton 12642: <reg> <reg> <inst>
12643: <n> # <reg> <inst>
12644: <mem> <reg> <inst>
12645: <reg> <mem> <inst>
1.136 pazsan 12646: <n> # <mem> <inst>
1.1 anton 12647: @end example
12648:
1.136 pazsan 12649: The shift/rotate syntax is:
1.1 anton 12650:
1.26 crook 12651: @example
1.78 anton 12652: <reg/mem> 1 # shl \ shortens to shift without immediate
12653: <reg/mem> 4 # shl
12654: <reg/mem> cl shl
1.26 crook 12655: @end example
1.1 anton 12656:
1.78 anton 12657: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12658: the byte version.
1.1 anton 12659:
1.78 anton 12660: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12661: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12662: pc < >= <= >}. (Note that most of these words shadow some Forth words
12663: when @code{assembler} is in front of @code{forth} in the search path,
12664: e.g., in @code{code} words). Currently the control structure words use
12665: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12666: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12667:
1.78 anton 12668: Here is an example of a @code{code} word (assumes that the stack pointer
12669: is in esi and the TOS is in ebx):
1.21 crook 12670:
1.26 crook 12671: @example
1.78 anton 12672: code my+ ( n1 n2 -- n )
12673: 4 si D) bx add
12674: 4 # si add
12675: Next
12676: end-code
1.26 crook 12677: @end example
1.21 crook 12678:
1.161 anton 12679:
1.78 anton 12680: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12681: @subsection Alpha Assembler
1.21 crook 12682:
1.78 anton 12683: The Alpha assembler and disassembler were originally written by Bernd
12684: Thallner.
1.26 crook 12685:
1.78 anton 12686: The register names @code{a0}--@code{a5} are not available to avoid
12687: shadowing hex numbers.
1.2 jwilke 12688:
1.78 anton 12689: Immediate forms of arithmetic instructions are distinguished by a
12690: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12691: does not count as arithmetic instruction).
1.2 jwilke 12692:
1.78 anton 12693: You have to specify all operands to an instruction, even those that
12694: other assemblers consider optional, e.g., the destination register for
12695: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12696:
1.78 anton 12697: You can specify conditions for @code{if,} by removing the first @code{b}
12698: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12699:
1.26 crook 12700: @example
1.78 anton 12701: 11 fgt if, \ if F11>0e
12702: ...
12703: endif,
1.26 crook 12704: @end example
1.2 jwilke 12705:
1.78 anton 12706: @code{fbgt,} gives @code{fgt}.
12707:
1.161 anton 12708: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12709: @subsection MIPS assembler
1.2 jwilke 12710:
1.78 anton 12711: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12712:
1.78 anton 12713: Currently the assembler and disassembler only cover the MIPS-I
12714: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12715:
1.78 anton 12716: The register names @code{$a0}--@code{$a3} are not available to avoid
12717: shadowing hex numbers.
1.2 jwilke 12718:
1.78 anton 12719: Because there is no way to distinguish registers from immediate values,
12720: you have to explicitly use the immediate forms of instructions, i.e.,
12721: @code{addiu,}, not just @code{addu,} (@command{as} does this
12722: implicitly).
1.2 jwilke 12723:
1.78 anton 12724: If the architecture manual specifies several formats for the instruction
12725: (e.g., for @code{jalr,}), you usually have to use the one with more
12726: arguments (i.e., two for @code{jalr,}). When in doubt, see
12727: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12728:
1.78 anton 12729: Branches and jumps in the MIPS architecture have a delay slot. You have
12730: to fill it yourself (the simplest way is to use @code{nop,}), the
12731: assembler does not do it for you (unlike @command{as}). Even
12732: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12733: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12734: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12735:
1.78 anton 12736: Note that you must not put branches, jumps, or @code{li,} into the delay
12737: slot: @code{li,} may expand to several instructions, and control flow
12738: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12739:
1.78 anton 12740: For branches the argument specifying the target is a relative address;
12741: You have to add the address of the delay slot to get the absolute
12742: address.
1.1 anton 12743:
1.78 anton 12744: The MIPS architecture also has load delay slots and restrictions on
12745: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12746: yourself to satisfy these restrictions, the assembler does not do it for
12747: you.
1.1 anton 12748:
1.78 anton 12749: You can specify the conditions for @code{if,} etc. by taking a
12750: conditional branch and leaving away the @code{b} at the start and the
12751: @code{,} at the end. E.g.,
1.1 anton 12752:
1.26 crook 12753: @example
1.78 anton 12754: 4 5 eq if,
12755: ... \ do something if $4 equals $5
12756: then,
1.26 crook 12757: @end example
1.1 anton 12758:
1.161 anton 12759:
1.193 dvdkhlng 12760: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12761: @subsection PowerPC assembler
12762:
1.162 anton 12763: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12764: Revucky.
12765:
1.162 anton 12766: This assembler does not follow the convention of ending mnemonic names
12767: with a ``,'', so some mnemonic names shadow regular Forth words (in
12768: particular: @code{and or xor fabs}); so if you want to use the Forth
12769: words, you have to make them visible first, e.g., with @code{also
12770: forth}.
12771:
1.161 anton 12772: Registers are referred to by their number, e.g., @code{9} means the
12773: integer register 9 or the FP register 9 (depending on the
12774: instruction).
12775:
12776: Because there is no way to distinguish registers from immediate values,
12777: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12778: @code{addi,}, not just @code{add,}.
1.161 anton 12779:
1.162 anton 12780: The assembler and disassembler usually support the most general form
1.161 anton 12781: of an instruction, but usually not the shorter forms (especially for
12782: branches).
12783:
12784:
1.193 dvdkhlng 12785: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12786: @subsection ARM Assembler
1.161 anton 12787:
1.193 dvdkhlng 12788: The ARM assembler included in Gforth was written from scratch by David
12789: Kuehling.
12790:
12791: The assembler includes all instruction of ARM architecture version 4,
12792: but does not (yet) have support for Thumb instructions. It also lacks
12793: support for any co-processors.
12794:
12795: The assembler uses a postfix syntax with the target operand specified
12796: last. For load/store instructions the last operand will be the
12797: register(s) to be loaded from/stored to.
12798:
12799: Registers are specified by their names @code{r0} through @code{r15},
12800: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12801: @code{fp} provided for convenience. Note that @code{ip} means intra
12802: procedure call scratch register (@code{r12}) and does not refer to the
12803: instruction pointer.
12804:
12805: Condition codes can be specified anywhere in the instruction, but will
12806: be most readable if specified just in front of the mnemonic. The 'S'
12807: flag is not a separate word, but encoded into instruction mnemonics,
12808: ie. just use @code{adds,} instead of @code{add,} if you want the
12809: status register to be updated.
12810:
12811: The following table lists the syntax of operands for general
12812: instructions:
12813:
12814: @example
12815: Gforth normal assembler description
12816: 123 # #123 immediate
12817: r12 r12 register
12818: r12 4 #LSL r12, LSL #4 shift left by immediate
12819: r12 r1 #LSL r12, LSL r1 shift left by register
12820: r12 4 #LSR r12, LSR #4 shift right by immediate
12821: r12 r1 #LSR r12, LSR r1 shift right by register
12822: r12 4 #ASR r12, ASR #4 arithmetic shift right
12823: r12 r1 #ASR r12, ASR r1 ... by register
12824: r12 4 #ROR r12, ROR #4 rotate right by immediate
12825: r12 r1 #ROR r12, ROR r1 ... by register
12826: r12 RRX r12, RRX rotate right with extend by 1
12827: @end example
12828:
12829: Memory operand syntax is listed in this table:
12830:
12831: @example
12832: Gforth normal assembler description
12833: r4 ] [r4] register
12834: r4 4 #] [r4, #+4] register with immediate offset
12835: r4 -4 #] [r4, #-4] with negative offset
12836: r4 r1 +] [r4, +r1] register with register offset
12837: r4 r1 -] [r4, -r1] with negated register offset
12838: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
12839: r4 4 #]! [r4, #+4]! immediate preincrement
12840: r4 r1 +]! [r4, +r1]! register preincrement
12841: r4 r1 -]! [r4, +r1]! register predecrement
12842: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
12843: r4 -4 ]# [r4], #-4 immediate postdecrement
12844: r4 r1 ]+ [r4], r1 register postincrement
12845: r4 r1 ]- [r4], -r1 register postdecrement
12846: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
12847: ' xyz >body [#] xyz PC-relative addressing
12848: @end example
12849:
12850: Register lists for load/store multiple instructions are started and
12851: terminated by using the words @code{@{} and @code{@}}
12852: respectivly. Between braces, register names can be listed one by one,
12853: or register ranges can be formed by using the postfix operator
12854: @code{r-r}. The @code{^} flag is not encoded in the register list
12855: operand, but instead directly encoded into the instruction mnemonic,
12856: ie. use @code{^ldm,} and @code{^stm,}.
12857:
12858: Addressing modes for load/store multiple are not encoded as
12859: instruction suffixes, but instead specified after the register that
12860: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
12861: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
12862:
12863: The following table gives some examples:
12864:
12865: @example
12866: Gforth normal assembler
12867: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
12868: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
12869: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
12870: @end example
12871:
12872: Conditions for control structure words are specified in front of a
12873: word:
12874:
12875: @example
12876: r1 r2 cmp, \ compare r1 and r2
12877: eq if, \ equal?
12878: ... \ code executed if r1 == r2
12879: then,
12880: @end example
12881:
12882: Here is an example of a @code{code} word (assumes that the stack
12883: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
12884: clobbered):
12885:
12886: @example
12887: code my+ ( n1 n2 -- n3 )
12888: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
12889: r2 r3 r3 add, \ r3 = n2+n1
12890: r9 -4 #]! r3 str, \ push r3
12891: next,
12892: end-code
12893: @end example
12894:
12895: Look at @file{arch/arm/asm-example.fs} for more examples.
12896:
12897: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 12898: @subsection Other assemblers
12899:
12900: If you want to contribute another assembler/disassembler, please contact
1.103 anton 12901: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
12902: an assembler already. If you are writing them from scratch, please use
12903: a similar syntax style as the one we use (i.e., postfix, commas at the
12904: end of the instruction names, @pxref{Common Assembler}); make the output
12905: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 12906: similar to the style we used.
12907:
12908: Hints on implementation: The most important part is to have a good test
12909: suite that contains all instructions. Once you have that, the rest is
12910: easy. For actual coding you can take a look at
12911: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
12912: the assembler and disassembler, avoiding redundancy and some potential
12913: bugs. You can also look at that file (and @pxref{Advanced does> usage
12914: example}) to get ideas how to factor a disassembler.
12915:
12916: Start with the disassembler, because it's easier to reuse data from the
12917: disassembler for the assembler than the other way round.
1.1 anton 12918:
1.78 anton 12919: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
12920: how simple it can be.
1.1 anton 12921:
1.161 anton 12922:
12923:
12924:
1.78 anton 12925: @c -------------------------------------------------------------
12926: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
12927: @section Threading Words
12928: @cindex threading words
1.1 anton 12929:
1.78 anton 12930: @cindex code address
12931: These words provide access to code addresses and other threading stuff
12932: in Gforth (and, possibly, other interpretive Forths). It more or less
12933: abstracts away the differences between direct and indirect threading
12934: (and, for direct threading, the machine dependences). However, at
12935: present this wordset is still incomplete. It is also pretty low-level;
12936: some day it will hopefully be made unnecessary by an internals wordset
12937: that abstracts implementation details away completely.
1.1 anton 12938:
1.78 anton 12939: The terminology used here stems from indirect threaded Forth systems; in
12940: such a system, the XT of a word is represented by the CFA (code field
12941: address) of a word; the CFA points to a cell that contains the code
12942: address. The code address is the address of some machine code that
12943: performs the run-time action of invoking the word (e.g., the
12944: @code{dovar:} routine pushes the address of the body of the word (a
12945: variable) on the stack
12946: ).
1.1 anton 12947:
1.78 anton 12948: @cindex code address
12949: @cindex code field address
12950: In an indirect threaded Forth, you can get the code address of @i{name}
12951: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
12952: >code-address}, independent of the threading method.
1.1 anton 12953:
1.78 anton 12954: doc-threading-method
12955: doc->code-address
12956: doc-code-address!
1.1 anton 12957:
1.78 anton 12958: @cindex @code{does>}-handler
12959: @cindex @code{does>}-code
12960: For a word defined with @code{DOES>}, the code address usually points to
12961: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
12962: routine (in Gforth on some platforms, it can also point to the dodoes
12963: routine itself). What you are typically interested in, though, is
12964: whether a word is a @code{DOES>}-defined word, and what Forth code it
12965: executes; @code{>does-code} tells you that.
1.1 anton 12966:
1.78 anton 12967: doc->does-code
1.1 anton 12968:
1.78 anton 12969: To create a @code{DOES>}-defined word with the following basic words,
12970: you have to set up a @code{DOES>}-handler with @code{does-handler!};
12971: @code{/does-handler} aus behind you have to place your executable Forth
12972: code. Finally you have to create a word and modify its behaviour with
12973: @code{does-handler!}.
1.1 anton 12974:
1.78 anton 12975: doc-does-code!
12976: doc-does-handler!
12977: doc-/does-handler
1.1 anton 12978:
1.78 anton 12979: The code addresses produced by various defining words are produced by
12980: the following words:
1.1 anton 12981:
1.78 anton 12982: doc-docol:
12983: doc-docon:
12984: doc-dovar:
12985: doc-douser:
12986: doc-dodefer:
12987: doc-dofield:
1.1 anton 12988:
1.99 anton 12989: @cindex definer
12990: The following two words generalize @code{>code-address},
12991: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
12992:
12993: doc->definer
12994: doc-definer!
12995:
1.26 crook 12996: @c -------------------------------------------------------------
1.78 anton 12997: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 12998: @section Passing Commands to the Operating System
12999: @cindex operating system - passing commands
13000: @cindex shell commands
13001:
13002: Gforth allows you to pass an arbitrary string to the host operating
13003: system shell (if such a thing exists) for execution.
13004:
13005: doc-sh
13006: doc-system
13007: doc-$?
1.23 crook 13008: doc-getenv
1.44 crook 13009:
1.26 crook 13010: @c -------------------------------------------------------------
1.47 crook 13011: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13012: @section Keeping track of Time
13013: @cindex time-related words
13014:
13015: doc-ms
13016: doc-time&date
1.79 anton 13017: doc-utime
13018: doc-cputime
1.47 crook 13019:
13020:
13021: @c -------------------------------------------------------------
13022: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 13023: @section Miscellaneous Words
13024: @cindex miscellaneous words
13025:
1.29 crook 13026: @comment TODO find homes for these
13027:
1.26 crook 13028: These section lists the ANS Forth words that are not documented
1.21 crook 13029: elsewhere in this manual. Ultimately, they all need proper homes.
13030:
1.68 anton 13031: doc-quit
1.44 crook 13032:
1.26 crook 13033: The following ANS Forth words are not currently supported by Gforth
1.27 crook 13034: (@pxref{ANS conformance}):
1.21 crook 13035:
13036: @code{EDITOR}
13037: @code{EMIT?}
13038: @code{FORGET}
13039:
1.24 anton 13040: @c ******************************************************************
13041: @node Error messages, Tools, Words, Top
13042: @chapter Error messages
13043: @cindex error messages
13044: @cindex backtrace
13045:
13046: A typical Gforth error message looks like this:
13047:
13048: @example
1.86 anton 13049: in file included from \evaluated string/:-1
1.24 anton 13050: in file included from ./yyy.fs:1
13051: ./xxx.fs:4: Invalid memory address
1.134 anton 13052: >>>bar<<<
1.79 anton 13053: Backtrace:
1.25 anton 13054: $400E664C @@
13055: $400E6664 foo
1.24 anton 13056: @end example
13057:
13058: The message identifying the error is @code{Invalid memory address}. The
13059: error happened when text-interpreting line 4 of the file
13060: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13061: word on the line where the error happened, is pointed out (with
1.134 anton 13062: @code{>>>} and @code{<<<}).
1.24 anton 13063:
13064: The file containing the error was included in line 1 of @file{./yyy.fs},
13065: and @file{yyy.fs} was included from a non-file (in this case, by giving
13066: @file{yyy.fs} as command-line parameter to Gforth).
13067:
13068: At the end of the error message you find a return stack dump that can be
13069: interpreted as a backtrace (possibly empty). On top you find the top of
13070: the return stack when the @code{throw} happened, and at the bottom you
13071: find the return stack entry just above the return stack of the topmost
13072: text interpreter.
13073:
13074: To the right of most return stack entries you see a guess for the word
13075: that pushed that return stack entry as its return address. This gives a
13076: backtrace. In our case we see that @code{bar} called @code{foo}, and
13077: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13078: address} exception).
13079:
13080: Note that the backtrace is not perfect: We don't know which return stack
13081: entries are return addresses (so we may get false positives); and in
13082: some cases (e.g., for @code{abort"}) we cannot determine from the return
13083: address the word that pushed the return address, so for some return
13084: addresses you see no names in the return stack dump.
1.25 anton 13085:
13086: @cindex @code{catch} and backtraces
13087: The return stack dump represents the return stack at the time when a
13088: specific @code{throw} was executed. In programs that make use of
13089: @code{catch}, it is not necessarily clear which @code{throw} should be
13090: used for the return stack dump (e.g., consider one @code{throw} that
13091: indicates an error, which is caught, and during recovery another error
1.160 anton 13092: happens; which @code{throw} should be used for the stack dump?).
13093: Gforth presents the return stack dump for the first @code{throw} after
13094: the last executed (not returned-to) @code{catch} or @code{nothrow};
13095: this works well in the usual case. To get the right backtrace, you
13096: usually want to insert @code{nothrow} or @code{['] false catch drop}
13097: after a @code{catch} if the error is not rethrown.
1.25 anton 13098:
13099: @cindex @code{gforth-fast} and backtraces
13100: @cindex @code{gforth-fast}, difference from @code{gforth}
13101: @cindex backtraces with @code{gforth-fast}
13102: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13103: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13104: from primitives (e.g., invalid memory address, stack empty etc.);
13105: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13106: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13107: exception caused by a primitive in @code{gforth-fast}, you will
13108: typically see no return stack dump at all; however, if the exception is
13109: caught by @code{catch} (e.g., for restoring some state), and then
13110: @code{throw}n again, the return stack dump will be for the first such
13111: @code{throw}.
1.2 jwilke 13112:
1.5 anton 13113: @c ******************************************************************
1.24 anton 13114: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13115: @chapter Tools
13116:
13117: @menu
13118: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13119: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13120: @end menu
13121:
13122: See also @ref{Emacs and Gforth}.
13123:
1.126 pazsan 13124: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13125: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13126: @cindex @file{ans-report.fs}
13127: @cindex report the words used in your program
13128: @cindex words used in your program
13129:
13130: If you want to label a Forth program as ANS Forth Program, you must
13131: document which wordsets the program uses; for extension wordsets, it is
13132: helpful to list the words the program requires from these wordsets
13133: (because Forth systems are allowed to provide only some words of them).
13134:
13135: The @file{ans-report.fs} tool makes it easy for you to determine which
13136: words from which wordset and which non-ANS words your application
13137: uses. You simply have to include @file{ans-report.fs} before loading the
13138: program you want to check. After loading your program, you can get the
13139: report with @code{print-ans-report}. A typical use is to run this as
13140: batch job like this:
13141: @example
13142: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13143: @end example
13144:
13145: The output looks like this (for @file{compat/control.fs}):
13146: @example
13147: The program uses the following words
13148: from CORE :
13149: : POSTPONE THEN ; immediate ?dup IF 0=
13150: from BLOCK-EXT :
13151: \
13152: from FILE :
13153: (
13154: @end example
13155:
13156: @subsection Caveats
13157:
13158: Note that @file{ans-report.fs} just checks which words are used, not whether
13159: they are used in an ANS Forth conforming way!
13160:
13161: Some words are defined in several wordsets in the
13162: standard. @file{ans-report.fs} reports them for only one of the
13163: wordsets, and not necessarily the one you expect. It depends on usage
13164: which wordset is the right one to specify. E.g., if you only use the
13165: compilation semantics of @code{S"}, it is a Core word; if you also use
13166: its interpretation semantics, it is a File word.
1.124 anton 13167:
13168:
1.127 anton 13169: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13170: @section Stack depth changes during interpretation
13171: @cindex @file{depth-changes.fs}
13172: @cindex depth changes during interpretation
13173: @cindex stack depth changes during interpretation
13174: @cindex items on the stack after interpretation
13175:
13176: Sometimes you notice that, after loading a file, there are items left
13177: on the stack. The tool @file{depth-changes.fs} helps you find out
13178: quickly where in the file these stack items are coming from.
13179:
13180: The simplest way of using @file{depth-changes.fs} is to include it
13181: before the file(s) you want to check, e.g.:
13182:
13183: @example
13184: gforth depth-changes.fs my-file.fs
13185: @end example
13186:
13187: This will compare the stack depths of the data and FP stack at every
13188: empty line (in interpretation state) against these depths at the last
13189: empty line (in interpretation state). If the depths are not equal,
13190: the position in the file and the stack contents are printed with
13191: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13192: change has occured in the paragraph of non-empty lines before the
13193: indicated line. It is a good idea to leave an empty line at the end
13194: of the file, so the last paragraph is checked, too.
13195:
13196: Checking only at empty lines usually works well, but sometimes you
13197: have big blocks of non-empty lines (e.g., when building a big table),
13198: and you want to know where in this block the stack depth changed. You
13199: can check all interpreted lines with
13200:
13201: @example
13202: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13203: @end example
13204:
13205: This checks the stack depth at every end-of-line. So the depth change
13206: occured in the line reported by the @code{~~} (not in the line
13207: before).
13208:
13209: Note that, while this offers better accuracy in indicating where the
13210: stack depth changes, it will often report many intentional stack depth
13211: changes (e.g., when an interpreted computation stretches across
13212: several lines). You can suppress the checking of some lines by
13213: putting backslashes at the end of these lines (not followed by white
13214: space), and using
13215:
13216: @example
13217: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13218: @end example
1.1 anton 13219:
13220: @c ******************************************************************
1.65 anton 13221: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13222: @chapter ANS conformance
13223: @cindex ANS conformance of Gforth
13224:
13225: To the best of our knowledge, Gforth is an
13226:
13227: ANS Forth System
13228: @itemize @bullet
13229: @item providing the Core Extensions word set
13230: @item providing the Block word set
13231: @item providing the Block Extensions word set
13232: @item providing the Double-Number word set
13233: @item providing the Double-Number Extensions word set
13234: @item providing the Exception word set
13235: @item providing the Exception Extensions word set
13236: @item providing the Facility word set
1.40 anton 13237: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13238: @item providing the File Access word set
13239: @item providing the File Access Extensions word set
13240: @item providing the Floating-Point word set
13241: @item providing the Floating-Point Extensions word set
13242: @item providing the Locals word set
13243: @item providing the Locals Extensions word set
13244: @item providing the Memory-Allocation word set
13245: @item providing the Memory-Allocation Extensions word set (that one's easy)
13246: @item providing the Programming-Tools word set
13247: @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
13248: @item providing the Search-Order word set
13249: @item providing the Search-Order Extensions word set
13250: @item providing the String word set
13251: @item providing the String Extensions word set (another easy one)
13252: @end itemize
13253:
1.118 anton 13254: Gforth has the following environmental restrictions:
13255:
13256: @cindex environmental restrictions
13257: @itemize @bullet
13258: @item
13259: While processing the OS command line, if an exception is not caught,
13260: Gforth exits with a non-zero exit code instyead of performing QUIT.
13261:
13262: @item
13263: When an @code{throw} is performed after a @code{query}, Gforth does not
13264: allways restore the input source specification in effect at the
13265: corresponding catch.
13266:
13267: @end itemize
13268:
13269:
1.1 anton 13270: @cindex system documentation
13271: In addition, ANS Forth systems are required to document certain
13272: implementation choices. This chapter tries to meet these
13273: requirements. In many cases it gives a way to ask the system for the
13274: information instead of providing the information directly, in
13275: particular, if the information depends on the processor, the operating
13276: system or the installation options chosen, or if they are likely to
13277: change during the maintenance of Gforth.
13278:
13279: @comment The framework for the rest has been taken from pfe.
13280:
13281: @menu
13282: * The Core Words::
13283: * The optional Block word set::
13284: * The optional Double Number word set::
13285: * The optional Exception word set::
13286: * The optional Facility word set::
13287: * The optional File-Access word set::
13288: * The optional Floating-Point word set::
13289: * The optional Locals word set::
13290: * The optional Memory-Allocation word set::
13291: * The optional Programming-Tools word set::
13292: * The optional Search-Order word set::
13293: @end menu
13294:
13295:
13296: @c =====================================================================
13297: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13298: @comment node-name, next, previous, up
13299: @section The Core Words
13300: @c =====================================================================
13301: @cindex core words, system documentation
13302: @cindex system documentation, core words
13303:
13304: @menu
13305: * core-idef:: Implementation Defined Options
13306: * core-ambcond:: Ambiguous Conditions
13307: * core-other:: Other System Documentation
13308: @end menu
13309:
13310: @c ---------------------------------------------------------------------
13311: @node core-idef, core-ambcond, The Core Words, The Core Words
13312: @subsection Implementation Defined Options
13313: @c ---------------------------------------------------------------------
13314: @cindex core words, implementation-defined options
13315: @cindex implementation-defined options, core words
13316:
13317:
13318: @table @i
13319: @item (Cell) aligned addresses:
13320: @cindex cell-aligned addresses
13321: @cindex aligned addresses
13322: processor-dependent. Gforth's alignment words perform natural alignment
13323: (e.g., an address aligned for a datum of size 8 is divisible by
13324: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13325:
13326: @item @code{EMIT} and non-graphic characters:
13327: @cindex @code{EMIT} and non-graphic characters
13328: @cindex non-graphic characters and @code{EMIT}
13329: The character is output using the C library function (actually, macro)
13330: @code{putc}.
13331:
13332: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13333: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13334: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13335: @cindex @code{ACCEPT}, editing
13336: @cindex @code{EXPECT}, editing
13337: This is modeled on the GNU readline library (@pxref{Readline
13338: Interaction, , Command Line Editing, readline, The GNU Readline
13339: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13340: producing a full word completion every time you type it (instead of
1.28 crook 13341: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13342:
13343: @item character set:
13344: @cindex character set
13345: The character set of your computer and display device. Gforth is
13346: 8-bit-clean (but some other component in your system may make trouble).
13347:
13348: @item Character-aligned address requirements:
13349: @cindex character-aligned address requirements
13350: installation-dependent. Currently a character is represented by a C
13351: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13352: (Comments on that requested).
13353:
13354: @item character-set extensions and matching of names:
13355: @cindex character-set extensions and matching of names
1.26 crook 13356: @cindex case-sensitivity for name lookup
13357: @cindex name lookup, case-sensitivity
13358: @cindex locale and case-sensitivity
1.21 crook 13359: Any character except the ASCII NUL character can be used in a
1.1 anton 13360: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13361: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13362: function is probably influenced by the locale. E.g., the @code{C} locale
13363: does not know about accents and umlauts, so they are matched
13364: case-sensitively in that locale. For portability reasons it is best to
13365: write programs such that they work in the @code{C} locale. Then one can
13366: use libraries written by a Polish programmer (who might use words
13367: containing ISO Latin-2 encoded characters) and by a French programmer
13368: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13369: funny results for some of the words (which ones, depends on the font you
13370: are using)). Also, the locale you prefer may not be available in other
13371: operating systems. Hopefully, Unicode will solve these problems one day.
13372:
13373: @item conditions under which control characters match a space delimiter:
13374: @cindex space delimiters
13375: @cindex control characters as delimiters
1.117 anton 13376: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13377: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13378: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13379: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13380: interpreter (aka text interpreter) by default, treats all white-space
13381: characters as delimiters.
13382:
1.26 crook 13383: @item format of the control-flow stack:
13384: @cindex control-flow stack, format
13385: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13386: stack item in cells is given by the constant @code{cs-item-size}. At the
13387: time of this writing, an item consists of a (pointer to a) locals list
13388: (third), an address in the code (second), and a tag for identifying the
13389: item (TOS). The following tags are used: @code{defstart},
13390: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13391: @code{scopestart}.
13392:
13393: @item conversion of digits > 35
13394: @cindex digits > 35
13395: The characters @code{[\]^_'} are the digits with the decimal value
13396: 36@minus{}41. There is no way to input many of the larger digits.
13397:
13398: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13399: @cindex @code{EXPECT}, display after end of input
13400: @cindex @code{ACCEPT}, display after end of input
13401: The cursor is moved to the end of the entered string. If the input is
13402: terminated using the @kbd{Return} key, a space is typed.
13403:
13404: @item exception abort sequence of @code{ABORT"}:
13405: @cindex exception abort sequence of @code{ABORT"}
13406: @cindex @code{ABORT"}, exception abort sequence
13407: The error string is stored into the variable @code{"error} and a
13408: @code{-2 throw} is performed.
13409:
13410: @item input line terminator:
13411: @cindex input line terminator
13412: @cindex line terminator on input
1.26 crook 13413: @cindex newline character on input
1.1 anton 13414: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13415: lines. One of these characters is typically produced when you type the
13416: @kbd{Enter} or @kbd{Return} key.
13417:
13418: @item maximum size of a counted string:
13419: @cindex maximum size of a counted string
13420: @cindex counted string, maximum size
13421: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13422: on all platforms, but this may change.
1.1 anton 13423:
13424: @item maximum size of a parsed string:
13425: @cindex maximum size of a parsed string
13426: @cindex parsed string, maximum size
13427: Given by the constant @code{/line}. Currently 255 characters.
13428:
13429: @item maximum size of a definition name, in characters:
13430: @cindex maximum size of a definition name, in characters
13431: @cindex name, maximum length
1.113 anton 13432: MAXU/8
1.1 anton 13433:
13434: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13435: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13436: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13437: MAXU/8
1.1 anton 13438:
13439: @item method of selecting the user input device:
13440: @cindex user input device, method of selecting
13441: The user input device is the standard input. There is currently no way to
13442: change it from within Gforth. However, the input can typically be
13443: redirected in the command line that starts Gforth.
13444:
13445: @item method of selecting the user output device:
13446: @cindex user output device, method of selecting
13447: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13448: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13449: output when the user output device is a terminal, otherwise the output
13450: is buffered.
1.1 anton 13451:
13452: @item methods of dictionary compilation:
13453: What are we expected to document here?
13454:
13455: @item number of bits in one address unit:
13456: @cindex number of bits in one address unit
13457: @cindex address unit, size in bits
13458: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13459: platforms.
1.1 anton 13460:
13461: @item number representation and arithmetic:
13462: @cindex number representation and arithmetic
1.79 anton 13463: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13464:
13465: @item ranges for integer types:
13466: @cindex ranges for integer types
13467: @cindex integer types, ranges
13468: Installation-dependent. Make environmental queries for @code{MAX-N},
13469: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13470: unsigned (and positive) types is 0. The lower bound for signed types on
13471: two's complement and one's complement machines machines can be computed
13472: by adding 1 to the upper bound.
13473:
13474: @item read-only data space regions:
13475: @cindex read-only data space regions
13476: @cindex data-space, read-only regions
13477: The whole Forth data space is writable.
13478:
13479: @item size of buffer at @code{WORD}:
13480: @cindex size of buffer at @code{WORD}
13481: @cindex @code{WORD} buffer size
13482: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13483: shared with the pictured numeric output string. If overwriting
13484: @code{PAD} is acceptable, it is as large as the remaining dictionary
13485: space, although only as much can be sensibly used as fits in a counted
13486: string.
13487:
13488: @item size of one cell in address units:
13489: @cindex cell size
13490: @code{1 cells .}.
13491:
13492: @item size of one character in address units:
13493: @cindex char size
1.79 anton 13494: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13495:
13496: @item size of the keyboard terminal buffer:
13497: @cindex size of the keyboard terminal buffer
13498: @cindex terminal buffer, size
13499: Varies. You can determine the size at a specific time using @code{lp@@
13500: tib - .}. It is shared with the locals stack and TIBs of files that
13501: include the current file. You can change the amount of space for TIBs
13502: and locals stack at Gforth startup with the command line option
13503: @code{-l}.
13504:
13505: @item size of the pictured numeric output buffer:
13506: @cindex size of the pictured numeric output buffer
13507: @cindex pictured numeric output buffer, size
13508: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13509: shared with @code{WORD}.
13510:
13511: @item size of the scratch area returned by @code{PAD}:
13512: @cindex size of the scratch area returned by @code{PAD}
13513: @cindex @code{PAD} size
13514: The remainder of dictionary space. @code{unused pad here - - .}.
13515:
13516: @item system case-sensitivity characteristics:
13517: @cindex case-sensitivity characteristics
1.26 crook 13518: Dictionary searches are case-insensitive (except in
1.1 anton 13519: @code{TABLE}s). However, as explained above under @i{character-set
13520: extensions}, the matching for non-ASCII characters is determined by the
13521: locale you are using. In the default @code{C} locale all non-ASCII
13522: characters are matched case-sensitively.
13523:
13524: @item system prompt:
13525: @cindex system prompt
13526: @cindex prompt
13527: @code{ ok} in interpret state, @code{ compiled} in compile state.
13528:
13529: @item division rounding:
13530: @cindex division rounding
1.166 anton 13531: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13532: division (with the default installation of Gforth). You can check
13533: this with @code{s" floored" environment? drop .}. If you write
13534: programs that need a specific division rounding, best use
13535: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13536:
13537: @item values of @code{STATE} when true:
13538: @cindex @code{STATE} values
13539: -1.
13540:
13541: @item values returned after arithmetic overflow:
13542: On two's complement machines, arithmetic is performed modulo
13543: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13544: arithmetic (with appropriate mapping for signed types). Division by
13545: zero typically results in a @code{-55 throw} (Floating-point
13546: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13547: division overflow can result in these throws, or in @code{-11 throw};
13548: in @code{gforth-fast} division overflow and divide by zero may also
13549: result in returning bogus results without producing an exception.
1.1 anton 13550:
13551: @item whether the current definition can be found after @t{DOES>}:
13552: @cindex @t{DOES>}, visibility of current definition
13553: No.
13554:
13555: @end table
13556:
13557: @c ---------------------------------------------------------------------
13558: @node core-ambcond, core-other, core-idef, The Core Words
13559: @subsection Ambiguous conditions
13560: @c ---------------------------------------------------------------------
13561: @cindex core words, ambiguous conditions
13562: @cindex ambiguous conditions, core words
13563:
13564: @table @i
13565:
13566: @item a name is neither a word nor a number:
13567: @cindex name not found
1.26 crook 13568: @cindex undefined word
1.80 anton 13569: @code{-13 throw} (Undefined word).
1.1 anton 13570:
13571: @item a definition name exceeds the maximum length allowed:
1.26 crook 13572: @cindex word name too long
1.1 anton 13573: @code{-19 throw} (Word name too long)
13574:
13575: @item addressing a region not inside the various data spaces of the forth system:
13576: @cindex Invalid memory address
1.32 anton 13577: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13578: typically readable. Accessing other addresses gives results dependent on
13579: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13580: address).
13581:
13582: @item argument type incompatible with parameter:
1.26 crook 13583: @cindex argument type mismatch
1.1 anton 13584: This is usually not caught. Some words perform checks, e.g., the control
13585: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13586: mismatch).
13587:
13588: @item attempting to obtain the execution token of a word with undefined execution semantics:
13589: @cindex Interpreting a compile-only word, for @code{'} etc.
13590: @cindex execution token of words with undefined execution semantics
13591: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13592: get an execution token for @code{compile-only-error} (which performs a
13593: @code{-14 throw} when executed).
13594:
13595: @item dividing by zero:
13596: @cindex dividing by zero
13597: @cindex floating point unidentified fault, integer division
1.80 anton 13598: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13599: zero); on other systems, this typically results in a @code{-55 throw}
13600: (Floating-point unidentified fault).
1.1 anton 13601:
13602: @item insufficient data stack or return stack space:
13603: @cindex insufficient data stack or return stack space
13604: @cindex stack overflow
1.26 crook 13605: @cindex address alignment exception, stack overflow
1.1 anton 13606: @cindex Invalid memory address, stack overflow
13607: Depending on the operating system, the installation, and the invocation
13608: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13609: it is not checked. If it is checked, you typically get a @code{-3 throw}
13610: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13611: throw} (Invalid memory address) (depending on the platform and how you
13612: achieved the overflow) as soon as the overflow happens. If it is not
13613: checked, overflows typically result in mysterious illegal memory
13614: accesses, producing @code{-9 throw} (Invalid memory address) or
13615: @code{-23 throw} (Address alignment exception); they might also destroy
13616: the internal data structure of @code{ALLOCATE} and friends, resulting in
13617: various errors in these words.
1.1 anton 13618:
13619: @item insufficient space for loop control parameters:
13620: @cindex insufficient space for loop control parameters
1.80 anton 13621: Like other return stack overflows.
1.1 anton 13622:
13623: @item insufficient space in the dictionary:
13624: @cindex insufficient space in the dictionary
13625: @cindex dictionary overflow
1.12 anton 13626: If you try to allot (either directly with @code{allot}, or indirectly
13627: with @code{,}, @code{create} etc.) more memory than available in the
13628: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13629: to access memory beyond the end of the dictionary, the results are
13630: similar to stack overflows.
1.1 anton 13631:
13632: @item interpreting a word with undefined interpretation semantics:
13633: @cindex interpreting a word with undefined interpretation semantics
13634: @cindex Interpreting a compile-only word
13635: For some words, we have defined interpretation semantics. For the
13636: others: @code{-14 throw} (Interpreting a compile-only word).
13637:
13638: @item modifying the contents of the input buffer or a string literal:
13639: @cindex modifying the contents of the input buffer or a string literal
13640: These are located in writable memory and can be modified.
13641:
13642: @item overflow of the pictured numeric output string:
13643: @cindex overflow of the pictured numeric output string
13644: @cindex pictured numeric output string, overflow
1.24 anton 13645: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13646:
13647: @item parsed string overflow:
13648: @cindex parsed string overflow
13649: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13650:
13651: @item producing a result out of range:
13652: @cindex result out of range
13653: On two's complement machines, arithmetic is performed modulo
13654: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13655: arithmetic (with appropriate mapping for signed types). Division by
13656: zero typically results in a @code{-10 throw} (divide by zero) or
13657: @code{-55 throw} (floating point unidentified fault). Overflow on
13658: division may result in these errors or in @code{-11 throw} (result out
13659: of range). @code{Gforth-fast} may silently produce bogus results on
13660: division overflow or division by zero. @code{Convert} and
1.24 anton 13661: @code{>number} currently overflow silently.
1.1 anton 13662:
13663: @item reading from an empty data or return stack:
13664: @cindex stack empty
13665: @cindex stack underflow
1.24 anton 13666: @cindex return stack underflow
1.1 anton 13667: The data stack is checked by the outer (aka text) interpreter after
13668: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13669: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13670: depending on operating system, installation, and invocation. If they are
13671: caught by a check, they typically result in @code{-4 throw} (Stack
13672: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13673: (Invalid memory address), depending on the platform and which stack
13674: underflows and by how much. Note that even if the system uses checking
13675: (through the MMU), your program may have to underflow by a significant
13676: number of stack items to trigger the reaction (the reason for this is
13677: that the MMU, and therefore the checking, works with a page-size
13678: granularity). If there is no checking, the symptoms resulting from an
13679: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13680: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13681: (Invalid memory address) and Illegal Instruction (typically @code{-260
13682: throw}).
1.1 anton 13683:
13684: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13685: @cindex unexpected end of the input buffer
13686: @cindex zero-length string as a name
13687: @cindex Attempt to use zero-length string as a name
13688: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13689: use zero-length string as a name). Words like @code{'} probably will not
13690: find what they search. Note that it is possible to create zero-length
13691: names with @code{nextname} (should it not?).
13692:
13693: @item @code{>IN} greater than input buffer:
13694: @cindex @code{>IN} greater than input buffer
13695: The next invocation of a parsing word returns a string with length 0.
13696:
13697: @item @code{RECURSE} appears after @code{DOES>}:
13698: @cindex @code{RECURSE} appears after @code{DOES>}
13699: Compiles a recursive call to the defining word, not to the defined word.
13700:
13701: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13702: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13703: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13704: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13705: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13706: the end of the file was reached), its source-id may be
13707: reused. Therefore, restoring an input source specification referencing a
13708: closed file may lead to unpredictable results instead of a @code{-12
13709: THROW}.
13710:
13711: In the future, Gforth may be able to restore input source specifications
13712: from other than the current input source.
13713:
13714: @item data space containing definitions gets de-allocated:
13715: @cindex data space containing definitions gets de-allocated
13716: Deallocation with @code{allot} is not checked. This typically results in
13717: memory access faults or execution of illegal instructions.
13718:
13719: @item data space read/write with incorrect alignment:
13720: @cindex data space read/write with incorrect alignment
13721: @cindex alignment faults
1.26 crook 13722: @cindex address alignment exception
1.1 anton 13723: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13724: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13725: alignment turned on, incorrect alignment results in a @code{-9 throw}
13726: (Invalid memory address). There are reportedly some processors with
1.12 anton 13727: alignment restrictions that do not report violations.
1.1 anton 13728:
13729: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13730: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13731: Like other alignment errors.
13732:
13733: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13734: Like other stack underflows.
13735:
13736: @item loop control parameters not available:
13737: @cindex loop control parameters not available
13738: Not checked. The counted loop words simply assume that the top of return
13739: stack items are loop control parameters and behave accordingly.
13740:
13741: @item most recent definition does not have a name (@code{IMMEDIATE}):
13742: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13743: @cindex last word was headerless
13744: @code{abort" last word was headerless"}.
13745:
13746: @item name not defined by @code{VALUE} used by @code{TO}:
13747: @cindex name not defined by @code{VALUE} used by @code{TO}
13748: @cindex @code{TO} on non-@code{VALUE}s
13749: @cindex Invalid name argument, @code{TO}
13750: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13751: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13752:
13753: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13754: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13755: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13756: @code{-13 throw} (Undefined word)
13757:
13758: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13759: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13760: Gforth behaves as if they were of the same type. I.e., you can predict
13761: the behaviour by interpreting all parameters as, e.g., signed.
13762:
13763: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13764: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13765: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13766: compilation semantics of @code{TO}.
13767:
13768: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13769: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13770: @cindex @code{WORD}, string overflow
13771: Not checked. The string will be ok, but the count will, of course,
13772: contain only the least significant bits of the length.
13773:
13774: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13775: @cindex @code{LSHIFT}, large shift counts
13776: @cindex @code{RSHIFT}, large shift counts
13777: Processor-dependent. Typical behaviours are returning 0 and using only
13778: the low bits of the shift count.
13779:
13780: @item word not defined via @code{CREATE}:
13781: @cindex @code{>BODY} of non-@code{CREATE}d words
13782: @code{>BODY} produces the PFA of the word no matter how it was defined.
13783:
13784: @cindex @code{DOES>} of non-@code{CREATE}d words
13785: @code{DOES>} changes the execution semantics of the last defined word no
13786: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13787: @code{CREATE , DOES>}.
13788:
13789: @item words improperly used outside @code{<#} and @code{#>}:
13790: Not checked. As usual, you can expect memory faults.
13791:
13792: @end table
13793:
13794:
13795: @c ---------------------------------------------------------------------
13796: @node core-other, , core-ambcond, The Core Words
13797: @subsection Other system documentation
13798: @c ---------------------------------------------------------------------
13799: @cindex other system documentation, core words
13800: @cindex core words, other system documentation
13801:
13802: @table @i
13803: @item nonstandard words using @code{PAD}:
13804: @cindex @code{PAD} use by nonstandard words
13805: None.
13806:
13807: @item operator's terminal facilities available:
13808: @cindex operator's terminal facilities available
1.80 anton 13809: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13810: and you can give commands to Gforth interactively. The actual facilities
13811: available depend on how you invoke Gforth.
13812:
13813: @item program data space available:
13814: @cindex program data space available
13815: @cindex data space available
13816: @code{UNUSED .} gives the remaining dictionary space. The total
13817: dictionary space can be specified with the @code{-m} switch
13818: (@pxref{Invoking Gforth}) when Gforth starts up.
13819:
13820: @item return stack space available:
13821: @cindex return stack space available
13822: You can compute the total return stack space in cells with
13823: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13824: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13825:
13826: @item stack space available:
13827: @cindex stack space available
13828: You can compute the total data stack space in cells with
13829: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13830: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13831:
13832: @item system dictionary space required, in address units:
13833: @cindex system dictionary space required, in address units
13834: Type @code{here forthstart - .} after startup. At the time of this
13835: writing, this gives 80080 (bytes) on a 32-bit system.
13836: @end table
13837:
13838:
13839: @c =====================================================================
13840: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13841: @section The optional Block word set
13842: @c =====================================================================
13843: @cindex system documentation, block words
13844: @cindex block words, system documentation
13845:
13846: @menu
13847: * block-idef:: Implementation Defined Options
13848: * block-ambcond:: Ambiguous Conditions
13849: * block-other:: Other System Documentation
13850: @end menu
13851:
13852:
13853: @c ---------------------------------------------------------------------
13854: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
13855: @subsection Implementation Defined Options
13856: @c ---------------------------------------------------------------------
13857: @cindex implementation-defined options, block words
13858: @cindex block words, implementation-defined options
13859:
13860: @table @i
13861: @item the format for display by @code{LIST}:
13862: @cindex @code{LIST} display format
13863: First the screen number is displayed, then 16 lines of 64 characters,
13864: each line preceded by the line number.
13865:
13866: @item the length of a line affected by @code{\}:
13867: @cindex length of a line affected by @code{\}
13868: @cindex @code{\}, line length in blocks
13869: 64 characters.
13870: @end table
13871:
13872:
13873: @c ---------------------------------------------------------------------
13874: @node block-ambcond, block-other, block-idef, The optional Block word set
13875: @subsection Ambiguous conditions
13876: @c ---------------------------------------------------------------------
13877: @cindex block words, ambiguous conditions
13878: @cindex ambiguous conditions, block words
13879:
13880: @table @i
13881: @item correct block read was not possible:
13882: @cindex block read not possible
13883: Typically results in a @code{throw} of some OS-derived value (between
13884: -512 and -2048). If the blocks file was just not long enough, blanks are
13885: supplied for the missing portion.
13886:
13887: @item I/O exception in block transfer:
13888: @cindex I/O exception in block transfer
13889: @cindex block transfer, I/O exception
13890: Typically results in a @code{throw} of some OS-derived value (between
13891: -512 and -2048).
13892:
13893: @item invalid block number:
13894: @cindex invalid block number
13895: @cindex block number invalid
13896: @code{-35 throw} (Invalid block number)
13897:
13898: @item a program directly alters the contents of @code{BLK}:
13899: @cindex @code{BLK}, altering @code{BLK}
13900: The input stream is switched to that other block, at the same
13901: position. If the storing to @code{BLK} happens when interpreting
13902: non-block input, the system will get quite confused when the block ends.
13903:
13904: @item no current block buffer for @code{UPDATE}:
13905: @cindex @code{UPDATE}, no current block buffer
13906: @code{UPDATE} has no effect.
13907:
13908: @end table
13909:
13910: @c ---------------------------------------------------------------------
13911: @node block-other, , block-ambcond, The optional Block word set
13912: @subsection Other system documentation
13913: @c ---------------------------------------------------------------------
13914: @cindex other system documentation, block words
13915: @cindex block words, other system documentation
13916:
13917: @table @i
13918: @item any restrictions a multiprogramming system places on the use of buffer addresses:
13919: No restrictions (yet).
13920:
13921: @item the number of blocks available for source and data:
13922: depends on your disk space.
13923:
13924: @end table
13925:
13926:
13927: @c =====================================================================
13928: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
13929: @section The optional Double Number word set
13930: @c =====================================================================
13931: @cindex system documentation, double words
13932: @cindex double words, system documentation
13933:
13934: @menu
13935: * double-ambcond:: Ambiguous Conditions
13936: @end menu
13937:
13938:
13939: @c ---------------------------------------------------------------------
13940: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
13941: @subsection Ambiguous conditions
13942: @c ---------------------------------------------------------------------
13943: @cindex double words, ambiguous conditions
13944: @cindex ambiguous conditions, double words
13945:
13946: @table @i
1.29 crook 13947: @item @i{d} outside of range of @i{n} in @code{D>S}:
13948: @cindex @code{D>S}, @i{d} out of range of @i{n}
13949: The least significant cell of @i{d} is produced.
1.1 anton 13950:
13951: @end table
13952:
13953:
13954: @c =====================================================================
13955: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
13956: @section The optional Exception word set
13957: @c =====================================================================
13958: @cindex system documentation, exception words
13959: @cindex exception words, system documentation
13960:
13961: @menu
13962: * exception-idef:: Implementation Defined Options
13963: @end menu
13964:
13965:
13966: @c ---------------------------------------------------------------------
13967: @node exception-idef, , The optional Exception word set, The optional Exception word set
13968: @subsection Implementation Defined Options
13969: @c ---------------------------------------------------------------------
13970: @cindex implementation-defined options, exception words
13971: @cindex exception words, implementation-defined options
13972:
13973: @table @i
13974: @item @code{THROW}-codes used in the system:
13975: @cindex @code{THROW}-codes used in the system
13976: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 13977: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 13978: codes -512@minus{}-2047 are used for OS errors (for file and memory
13979: allocation operations). The mapping from OS error numbers to throw codes
13980: is -512@minus{}@code{errno}. One side effect of this mapping is that
13981: undefined OS errors produce a message with a strange number; e.g.,
13982: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
13983: @end table
13984:
13985: @c =====================================================================
13986: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
13987: @section The optional Facility word set
13988: @c =====================================================================
13989: @cindex system documentation, facility words
13990: @cindex facility words, system documentation
13991:
13992: @menu
13993: * facility-idef:: Implementation Defined Options
13994: * facility-ambcond:: Ambiguous Conditions
13995: @end menu
13996:
13997:
13998: @c ---------------------------------------------------------------------
13999: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14000: @subsection Implementation Defined Options
14001: @c ---------------------------------------------------------------------
14002: @cindex implementation-defined options, facility words
14003: @cindex facility words, implementation-defined options
14004:
14005: @table @i
14006: @item encoding of keyboard events (@code{EKEY}):
14007: @cindex keyboard events, encoding in @code{EKEY}
14008: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 14009: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 14010: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14011: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14012: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14013: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 14014:
1.1 anton 14015:
14016: @item duration of a system clock tick:
14017: @cindex duration of a system clock tick
14018: @cindex clock tick duration
14019: System dependent. With respect to @code{MS}, the time is specified in
14020: microseconds. How well the OS and the hardware implement this, is
14021: another question.
14022:
14023: @item repeatability to be expected from the execution of @code{MS}:
14024: @cindex repeatability to be expected from the execution of @code{MS}
14025: @cindex @code{MS}, repeatability to be expected
14026: System dependent. On Unix, a lot depends on load. If the system is
14027: lightly loaded, and the delay is short enough that Gforth does not get
14028: swapped out, the performance should be acceptable. Under MS-DOS and
14029: other single-tasking systems, it should be good.
14030:
14031: @end table
14032:
14033:
14034: @c ---------------------------------------------------------------------
14035: @node facility-ambcond, , facility-idef, The optional Facility word set
14036: @subsection Ambiguous conditions
14037: @c ---------------------------------------------------------------------
14038: @cindex facility words, ambiguous conditions
14039: @cindex ambiguous conditions, facility words
14040:
14041: @table @i
14042: @item @code{AT-XY} can't be performed on user output device:
14043: @cindex @code{AT-XY} can't be performed on user output device
14044: Largely terminal dependent. No range checks are done on the arguments.
14045: No errors are reported. You may see some garbage appearing, you may see
14046: simply nothing happen.
14047:
14048: @end table
14049:
14050:
14051: @c =====================================================================
14052: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14053: @section The optional File-Access word set
14054: @c =====================================================================
14055: @cindex system documentation, file words
14056: @cindex file words, system documentation
14057:
14058: @menu
14059: * file-idef:: Implementation Defined Options
14060: * file-ambcond:: Ambiguous Conditions
14061: @end menu
14062:
14063: @c ---------------------------------------------------------------------
14064: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14065: @subsection Implementation Defined Options
14066: @c ---------------------------------------------------------------------
14067: @cindex implementation-defined options, file words
14068: @cindex file words, implementation-defined options
14069:
14070: @table @i
14071: @item file access methods used:
14072: @cindex file access methods used
14073: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14074: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14075: @code{wb}): The file is cleared, if it exists, and created, if it does
14076: not (with both @code{open-file} and @code{create-file}). Under Unix
14077: @code{create-file} creates a file with 666 permissions modified by your
14078: umask.
14079:
14080: @item file exceptions:
14081: @cindex file exceptions
14082: The file words do not raise exceptions (except, perhaps, memory access
14083: faults when you pass illegal addresses or file-ids).
14084:
14085: @item file line terminator:
14086: @cindex file line terminator
14087: System-dependent. Gforth uses C's newline character as line
14088: terminator. What the actual character code(s) of this are is
14089: system-dependent.
14090:
14091: @item file name format:
14092: @cindex file name format
14093: System dependent. Gforth just uses the file name format of your OS.
14094:
14095: @item information returned by @code{FILE-STATUS}:
14096: @cindex @code{FILE-STATUS}, returned information
14097: @code{FILE-STATUS} returns the most powerful file access mode allowed
14098: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14099: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14100: along with the returned mode.
14101:
14102: @item input file state after an exception when including source:
14103: @cindex exception when including source
14104: All files that are left via the exception are closed.
14105:
1.29 crook 14106: @item @i{ior} values and meaning:
14107: @cindex @i{ior} values and meaning
1.68 anton 14108: @cindex @i{wior} values and meaning
1.29 crook 14109: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14110: intended as throw codes. They typically are in the range
14111: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14112: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14113:
14114: @item maximum depth of file input nesting:
14115: @cindex maximum depth of file input nesting
14116: @cindex file input nesting, maximum depth
14117: limited by the amount of return stack, locals/TIB stack, and the number
14118: of open files available. This should not give you troubles.
14119:
14120: @item maximum size of input line:
14121: @cindex maximum size of input line
14122: @cindex input line size, maximum
14123: @code{/line}. Currently 255.
14124:
14125: @item methods of mapping block ranges to files:
14126: @cindex mapping block ranges to files
14127: @cindex files containing blocks
14128: @cindex blocks in files
14129: By default, blocks are accessed in the file @file{blocks.fb} in the
14130: current working directory. The file can be switched with @code{USE}.
14131:
14132: @item number of string buffers provided by @code{S"}:
14133: @cindex @code{S"}, number of string buffers
14134: 1
14135:
14136: @item size of string buffer used by @code{S"}:
14137: @cindex @code{S"}, size of string buffer
14138: @code{/line}. currently 255.
14139:
14140: @end table
14141:
14142: @c ---------------------------------------------------------------------
14143: @node file-ambcond, , file-idef, The optional File-Access word set
14144: @subsection Ambiguous conditions
14145: @c ---------------------------------------------------------------------
14146: @cindex file words, ambiguous conditions
14147: @cindex ambiguous conditions, file words
14148:
14149: @table @i
14150: @item attempting to position a file outside its boundaries:
14151: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14152: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14153: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14154:
14155: @item attempting to read from file positions not yet written:
14156: @cindex reading from file positions not yet written
14157: End-of-file, i.e., zero characters are read and no error is reported.
14158:
1.29 crook 14159: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14160: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14161: An appropriate exception may be thrown, but a memory fault or other
14162: problem is more probable.
14163:
1.29 crook 14164: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14165: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14166: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14167: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14168: thrown.
14169:
14170: @item named file cannot be opened (@code{INCLUDED}):
14171: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14172: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14173:
14174: @item requesting an unmapped block number:
14175: @cindex unmapped block numbers
14176: There are no unmapped legal block numbers. On some operating systems,
14177: writing a block with a large number may overflow the file system and
14178: have an error message as consequence.
14179:
14180: @item using @code{source-id} when @code{blk} is non-zero:
14181: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14182: @code{source-id} performs its function. Typically it will give the id of
14183: the source which loaded the block. (Better ideas?)
14184:
14185: @end table
14186:
14187:
14188: @c =====================================================================
14189: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14190: @section The optional Floating-Point word set
14191: @c =====================================================================
14192: @cindex system documentation, floating-point words
14193: @cindex floating-point words, system documentation
14194:
14195: @menu
14196: * floating-idef:: Implementation Defined Options
14197: * floating-ambcond:: Ambiguous Conditions
14198: @end menu
14199:
14200:
14201: @c ---------------------------------------------------------------------
14202: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14203: @subsection Implementation Defined Options
14204: @c ---------------------------------------------------------------------
14205: @cindex implementation-defined options, floating-point words
14206: @cindex floating-point words, implementation-defined options
14207:
14208: @table @i
14209: @item format and range of floating point numbers:
14210: @cindex format and range of floating point numbers
14211: @cindex floating point numbers, format and range
14212: System-dependent; the @code{double} type of C.
14213:
1.29 crook 14214: @item results of @code{REPRESENT} when @i{float} is out of range:
14215: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14216: System dependent; @code{REPRESENT} is implemented using the C library
14217: function @code{ecvt()} and inherits its behaviour in this respect.
14218:
14219: @item rounding or truncation of floating-point numbers:
14220: @cindex rounding of floating-point numbers
14221: @cindex truncation of floating-point numbers
14222: @cindex floating-point numbers, rounding or truncation
14223: System dependent; the rounding behaviour is inherited from the hosting C
14224: compiler. IEEE-FP-based (i.e., most) systems by default round to
14225: nearest, and break ties by rounding to even (i.e., such that the last
14226: bit of the mantissa is 0).
14227:
14228: @item size of floating-point stack:
14229: @cindex floating-point stack size
14230: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14231: the floating-point stack (in floats). You can specify this on startup
14232: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14233:
14234: @item width of floating-point stack:
14235: @cindex floating-point stack width
14236: @code{1 floats}.
14237:
14238: @end table
14239:
14240:
14241: @c ---------------------------------------------------------------------
14242: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14243: @subsection Ambiguous conditions
14244: @c ---------------------------------------------------------------------
14245: @cindex floating-point words, ambiguous conditions
14246: @cindex ambiguous conditions, floating-point words
14247:
14248: @table @i
14249: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14250: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14251: System-dependent. Typically results in a @code{-23 THROW} like other
14252: alignment violations.
14253:
14254: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14255: @cindex @code{f@@} used with an address that is not float aligned
14256: @cindex @code{f!} used with an address that is not float aligned
14257: System-dependent. Typically results in a @code{-23 THROW} like other
14258: alignment violations.
14259:
14260: @item floating-point result out of range:
14261: @cindex floating-point result out of range
1.80 anton 14262: System-dependent. Can result in a @code{-43 throw} (floating point
14263: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14264: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14265: unidentified fault), or can produce a special value representing, e.g.,
14266: Infinity.
14267:
14268: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14269: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14270: System-dependent. Typically results in an alignment fault like other
14271: alignment violations.
14272:
1.35 anton 14273: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14274: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14275: The floating-point number is converted into decimal nonetheless.
14276:
14277: @item Both arguments are equal to zero (@code{FATAN2}):
14278: @cindex @code{FATAN2}, both arguments are equal to zero
14279: System-dependent. @code{FATAN2} is implemented using the C library
14280: function @code{atan2()}.
14281:
1.29 crook 14282: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14283: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14284: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14285: because of small errors and the tan will be a very large (or very small)
14286: but finite number.
14287:
1.29 crook 14288: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14289: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14290: The result is rounded to the nearest float.
14291:
14292: @item dividing by zero:
14293: @cindex dividing by zero, floating-point
14294: @cindex floating-point dividing by zero
14295: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14296: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14297: (floating point divide by zero) or @code{-55 throw} (Floating-point
14298: unidentified fault).
1.1 anton 14299:
14300: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14301: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14302: System dependent. On IEEE-FP based systems the number is converted into
14303: an infinity.
14304:
1.29 crook 14305: @item @i{float}<1 (@code{FACOSH}):
14306: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14307: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14308: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14309:
1.29 crook 14310: @item @i{float}=<-1 (@code{FLNP1}):
14311: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14312: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14313: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14314: negative infinity for @i{float}=-1).
1.1 anton 14315:
1.29 crook 14316: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14317: @cindex @code{FLN}, @i{float}=<0
14318: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14319: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14320: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14321: negative infinity for @i{float}=0).
1.1 anton 14322:
1.29 crook 14323: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14324: @cindex @code{FASINH}, @i{float}<0
14325: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14326: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14327: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14328: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14329: C library?).
1.1 anton 14330:
1.29 crook 14331: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14332: @cindex @code{FACOS}, |@i{float}|>1
14333: @cindex @code{FASIN}, |@i{float}|>1
14334: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14335: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14336: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14337:
1.29 crook 14338: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14339: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14340: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14341: Platform-dependent; typically, some double number is produced and no
14342: error is reported.
1.1 anton 14343:
14344: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14345: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14346: @code{Precision} characters of the numeric output area are used. If
14347: @code{precision} is too high, these words will smash the data or code
14348: close to @code{here}.
1.1 anton 14349: @end table
14350:
14351: @c =====================================================================
14352: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14353: @section The optional Locals word set
14354: @c =====================================================================
14355: @cindex system documentation, locals words
14356: @cindex locals words, system documentation
14357:
14358: @menu
14359: * locals-idef:: Implementation Defined Options
14360: * locals-ambcond:: Ambiguous Conditions
14361: @end menu
14362:
14363:
14364: @c ---------------------------------------------------------------------
14365: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14366: @subsection Implementation Defined Options
14367: @c ---------------------------------------------------------------------
14368: @cindex implementation-defined options, locals words
14369: @cindex locals words, implementation-defined options
14370:
14371: @table @i
14372: @item maximum number of locals in a definition:
14373: @cindex maximum number of locals in a definition
14374: @cindex locals, maximum number in a definition
14375: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14376: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14377: characters. The number of locals in a definition is bounded by the size
14378: of locals-buffer, which contains the names of the locals.
14379:
14380: @end table
14381:
14382:
14383: @c ---------------------------------------------------------------------
14384: @node locals-ambcond, , locals-idef, The optional Locals word set
14385: @subsection Ambiguous conditions
14386: @c ---------------------------------------------------------------------
14387: @cindex locals words, ambiguous conditions
14388: @cindex ambiguous conditions, locals words
14389:
14390: @table @i
14391: @item executing a named local in interpretation state:
14392: @cindex local in interpretation state
14393: @cindex Interpreting a compile-only word, for a local
14394: Locals have no interpretation semantics. If you try to perform the
14395: interpretation semantics, you will get a @code{-14 throw} somewhere
14396: (Interpreting a compile-only word). If you perform the compilation
14397: semantics, the locals access will be compiled (irrespective of state).
14398:
1.29 crook 14399: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14400: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14401: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14402: @cindex Invalid name argument, @code{TO}
14403: @code{-32 throw} (Invalid name argument)
14404:
14405: @end table
14406:
14407:
14408: @c =====================================================================
14409: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14410: @section The optional Memory-Allocation word set
14411: @c =====================================================================
14412: @cindex system documentation, memory-allocation words
14413: @cindex memory-allocation words, system documentation
14414:
14415: @menu
14416: * memory-idef:: Implementation Defined Options
14417: @end menu
14418:
14419:
14420: @c ---------------------------------------------------------------------
14421: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14422: @subsection Implementation Defined Options
14423: @c ---------------------------------------------------------------------
14424: @cindex implementation-defined options, memory-allocation words
14425: @cindex memory-allocation words, implementation-defined options
14426:
14427: @table @i
1.29 crook 14428: @item values and meaning of @i{ior}:
14429: @cindex @i{ior} values and meaning
14430: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14431: intended as throw codes. They typically are in the range
14432: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14433: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14434:
14435: @end table
14436:
14437: @c =====================================================================
14438: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14439: @section The optional Programming-Tools word set
14440: @c =====================================================================
14441: @cindex system documentation, programming-tools words
14442: @cindex programming-tools words, system documentation
14443:
14444: @menu
14445: * programming-idef:: Implementation Defined Options
14446: * programming-ambcond:: Ambiguous Conditions
14447: @end menu
14448:
14449:
14450: @c ---------------------------------------------------------------------
14451: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14452: @subsection Implementation Defined Options
14453: @c ---------------------------------------------------------------------
14454: @cindex implementation-defined options, programming-tools words
14455: @cindex programming-tools words, implementation-defined options
14456:
14457: @table @i
14458: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14459: @cindex @code{;CODE} ending sequence
14460: @cindex @code{CODE} ending sequence
14461: @code{END-CODE}
14462:
14463: @item manner of processing input following @code{;CODE} and @code{CODE}:
14464: @cindex @code{;CODE}, processing input
14465: @cindex @code{CODE}, processing input
14466: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14467: the input is processed by the text interpreter, (starting) in interpret
14468: state.
14469:
14470: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14471: @cindex @code{ASSEMBLER}, search order capability
14472: The ANS Forth search order word set.
14473:
14474: @item source and format of display by @code{SEE}:
14475: @cindex @code{SEE}, source and format of output
1.80 anton 14476: The source for @code{see} is the executable code used by the inner
1.1 anton 14477: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14478: (and on some platforms, assembly code for primitives) as well as
14479: possible.
1.1 anton 14480:
14481: @end table
14482:
14483: @c ---------------------------------------------------------------------
14484: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14485: @subsection Ambiguous conditions
14486: @c ---------------------------------------------------------------------
14487: @cindex programming-tools words, ambiguous conditions
14488: @cindex ambiguous conditions, programming-tools words
14489:
14490: @table @i
14491:
1.21 crook 14492: @item deleting the compilation word list (@code{FORGET}):
14493: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14494: Not implemented (yet).
14495:
1.29 crook 14496: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14497: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14498: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14499: @cindex control-flow stack underflow
14500: This typically results in an @code{abort"} with a descriptive error
14501: message (may change into a @code{-22 throw} (Control structure mismatch)
14502: in the future). You may also get a memory access error. If you are
14503: unlucky, this ambiguous condition is not caught.
14504:
1.29 crook 14505: @item @i{name} can't be found (@code{FORGET}):
14506: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14507: Not implemented (yet).
14508:
1.29 crook 14509: @item @i{name} not defined via @code{CREATE}:
14510: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14511: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14512: the execution semantics of the last defined word no matter how it was
14513: defined.
14514:
14515: @item @code{POSTPONE} applied to @code{[IF]}:
14516: @cindex @code{POSTPONE} applied to @code{[IF]}
14517: @cindex @code{[IF]} and @code{POSTPONE}
14518: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14519: equivalent to @code{[IF]}.
14520:
14521: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14522: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14523: Continue in the same state of conditional compilation in the next outer
14524: input source. Currently there is no warning to the user about this.
14525:
14526: @item removing a needed definition (@code{FORGET}):
14527: @cindex @code{FORGET}, removing a needed definition
14528: Not implemented (yet).
14529:
14530: @end table
14531:
14532:
14533: @c =====================================================================
14534: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14535: @section The optional Search-Order word set
14536: @c =====================================================================
14537: @cindex system documentation, search-order words
14538: @cindex search-order words, system documentation
14539:
14540: @menu
14541: * search-idef:: Implementation Defined Options
14542: * search-ambcond:: Ambiguous Conditions
14543: @end menu
14544:
14545:
14546: @c ---------------------------------------------------------------------
14547: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14548: @subsection Implementation Defined Options
14549: @c ---------------------------------------------------------------------
14550: @cindex implementation-defined options, search-order words
14551: @cindex search-order words, implementation-defined options
14552:
14553: @table @i
14554: @item maximum number of word lists in search order:
14555: @cindex maximum number of word lists in search order
14556: @cindex search order, maximum depth
14557: @code{s" wordlists" environment? drop .}. Currently 16.
14558:
14559: @item minimum search order:
14560: @cindex minimum search order
14561: @cindex search order, minimum
14562: @code{root root}.
14563:
14564: @end table
14565:
14566: @c ---------------------------------------------------------------------
14567: @node search-ambcond, , search-idef, The optional Search-Order word set
14568: @subsection Ambiguous conditions
14569: @c ---------------------------------------------------------------------
14570: @cindex search-order words, ambiguous conditions
14571: @cindex ambiguous conditions, search-order words
14572:
14573: @table @i
1.21 crook 14574: @item changing the compilation word list (during compilation):
14575: @cindex changing the compilation word list (during compilation)
14576: @cindex compilation word list, change before definition ends
14577: The word is entered into the word list that was the compilation word list
1.1 anton 14578: at the start of the definition. Any changes to the name field (e.g.,
14579: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14580: are applied to the latest defined word (as reported by @code{latest} or
14581: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14582:
14583: @item search order empty (@code{previous}):
14584: @cindex @code{previous}, search order empty
1.26 crook 14585: @cindex vocstack empty, @code{previous}
1.1 anton 14586: @code{abort" Vocstack empty"}.
14587:
14588: @item too many word lists in search order (@code{also}):
14589: @cindex @code{also}, too many word lists in search order
1.26 crook 14590: @cindex vocstack full, @code{also}
1.1 anton 14591: @code{abort" Vocstack full"}.
14592:
14593: @end table
14594:
14595: @c ***************************************************************
1.65 anton 14596: @node Standard vs Extensions, Model, ANS conformance, Top
14597: @chapter Should I use Gforth extensions?
14598: @cindex Gforth extensions
14599:
14600: As you read through the rest of this manual, you will see documentation
14601: for @i{Standard} words, and documentation for some appealing Gforth
14602: @i{extensions}. You might ask yourself the question: @i{``Should I
14603: restrict myself to the standard, or should I use the extensions?''}
14604:
14605: The answer depends on the goals you have for the program you are working
14606: on:
14607:
14608: @itemize @bullet
14609:
14610: @item Is it just for yourself or do you want to share it with others?
14611:
14612: @item
14613: If you want to share it, do the others all use Gforth?
14614:
14615: @item
14616: If it is just for yourself, do you want to restrict yourself to Gforth?
14617:
14618: @end itemize
14619:
14620: If restricting the program to Gforth is ok, then there is no reason not
14621: to use extensions. It is still a good idea to keep to the standard
14622: where it is easy, in case you want to reuse these parts in another
14623: program that you want to be portable.
14624:
14625: If you want to be able to port the program to other Forth systems, there
14626: are the following points to consider:
14627:
14628: @itemize @bullet
14629:
14630: @item
14631: Most Forth systems that are being maintained support the ANS Forth
14632: standard. So if your program complies with the standard, it will be
14633: portable among many systems.
14634:
14635: @item
14636: A number of the Gforth extensions can be implemented in ANS Forth using
14637: public-domain files provided in the @file{compat/} directory. These are
14638: mentioned in the text in passing. There is no reason not to use these
14639: extensions, your program will still be ANS Forth compliant; just include
14640: the appropriate compat files with your program.
14641:
14642: @item
14643: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14644: analyse your program and determine what non-Standard words it relies
14645: upon. However, it does not check whether you use standard words in a
14646: non-standard way.
14647:
14648: @item
14649: Some techniques are not standardized by ANS Forth, and are hard or
14650: impossible to implement in a standard way, but can be implemented in
14651: most Forth systems easily, and usually in similar ways (e.g., accessing
14652: word headers). Forth has a rich historical precedent for programmers
14653: taking advantage of implementation-dependent features of their tools
14654: (for example, relying on a knowledge of the dictionary
14655: structure). Sometimes these techniques are necessary to extract every
14656: last bit of performance from the hardware, sometimes they are just a
14657: programming shorthand.
14658:
14659: @item
14660: Does using a Gforth extension save more work than the porting this part
14661: to other Forth systems (if any) will cost?
14662:
14663: @item
14664: Is the additional functionality worth the reduction in portability and
14665: the additional porting problems?
14666:
14667: @end itemize
14668:
14669: In order to perform these consideratios, you need to know what's
14670: standard and what's not. This manual generally states if something is
1.81 anton 14671: non-standard, but the authoritative source is the
14672: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14673: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14674: into the thought processes of the technical committee.
14675:
14676: Note also that portability between Forth systems is not the only
14677: portability issue; there is also the issue of portability between
14678: different platforms (processor/OS combinations).
14679:
14680: @c ***************************************************************
14681: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14682: @chapter Model
14683:
14684: This chapter has yet to be written. It will contain information, on
14685: which internal structures you can rely.
14686:
14687: @c ***************************************************************
14688: @node Integrating Gforth, Emacs and Gforth, Model, Top
14689: @chapter Integrating Gforth into C programs
14690:
14691: This is not yet implemented.
14692:
14693: Several people like to use Forth as scripting language for applications
14694: that are otherwise written in C, C++, or some other language.
14695:
14696: The Forth system ATLAST provides facilities for embedding it into
14697: applications; unfortunately it has several disadvantages: most
14698: importantly, it is not based on ANS Forth, and it is apparently dead
14699: (i.e., not developed further and not supported). The facilities
1.21 crook 14700: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14701: making the switch should not be hard.
14702:
14703: We also tried to design the interface such that it can easily be
14704: implemented by other Forth systems, so that we may one day arrive at a
14705: standardized interface. Such a standard interface would allow you to
14706: replace the Forth system without having to rewrite C code.
14707:
14708: You embed the Gforth interpreter by linking with the library
14709: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14710: global symbols in this library that belong to the interface, have the
14711: prefix @code{forth_}. (Global symbols that are used internally have the
14712: prefix @code{gforth_}).
14713:
14714: You can include the declarations of Forth types and the functions and
14715: variables of the interface with @code{#include <forth.h>}.
14716:
14717: Types.
14718:
14719: Variables.
14720:
14721: Data and FP Stack pointer. Area sizes.
14722:
14723: functions.
14724:
14725: forth_init(imagefile)
14726: forth_evaluate(string) exceptions?
14727: forth_goto(address) (or forth_execute(xt)?)
14728: forth_continue() (a corountining mechanism)
14729:
14730: Adding primitives.
14731:
14732: No checking.
14733:
14734: Signals?
14735:
14736: Accessing the Stacks
14737:
1.26 crook 14738: @c ******************************************************************
1.1 anton 14739: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14740: @chapter Emacs and Gforth
14741: @cindex Emacs and Gforth
14742:
14743: @cindex @file{gforth.el}
14744: @cindex @file{forth.el}
14745: @cindex Rydqvist, Goran
1.107 dvdkhlng 14746: @cindex Kuehling, David
1.1 anton 14747: @cindex comment editing commands
14748: @cindex @code{\}, editing with Emacs
14749: @cindex debug tracer editing commands
14750: @cindex @code{~~}, removal with Emacs
14751: @cindex Forth mode in Emacs
1.107 dvdkhlng 14752:
1.1 anton 14753: Gforth comes with @file{gforth.el}, an improved version of
14754: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14755: improvements are:
14756:
14757: @itemize @bullet
14758: @item
1.107 dvdkhlng 14759: A better handling of indentation.
14760: @item
14761: A custom hilighting engine for Forth-code.
1.26 crook 14762: @item
14763: Comment paragraph filling (@kbd{M-q})
14764: @item
14765: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14766: @item
14767: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14768: @item
14769: Support of the @code{info-lookup} feature for looking up the
14770: documentation of a word.
1.107 dvdkhlng 14771: @item
14772: Support for reading and writing blocks files.
1.26 crook 14773: @end itemize
14774:
1.107 dvdkhlng 14775: To get a basic description of these features, enter Forth mode and
14776: type @kbd{C-h m}.
1.1 anton 14777:
14778: @cindex source location of error or debugging output in Emacs
14779: @cindex error output, finding the source location in Emacs
14780: @cindex debugging output, finding the source location in Emacs
14781: In addition, Gforth supports Emacs quite well: The source code locations
14782: given in error messages, debugging output (from @code{~~}) and failed
14783: assertion messages are in the right format for Emacs' compilation mode
14784: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14785: Manual}) so the source location corresponding to an error or other
14786: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14787: @kbd{C-c C-c} for the error under the cursor).
14788:
1.107 dvdkhlng 14789: @cindex viewing the documentation of a word in Emacs
14790: @cindex context-sensitive help
14791: Moreover, for words documented in this manual, you can look up the
14792: glossary entry quickly by using @kbd{C-h TAB}
14793: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14794: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14795: later and does not work for words containing @code{:}.
14796:
14797: @menu
14798: * Installing gforth.el:: Making Emacs aware of Forth.
14799: * Emacs Tags:: Viewing the source of a word in Emacs.
14800: * Hilighting:: Making Forth code look prettier.
14801: * Auto-Indentation:: Customizing auto-indentation.
14802: * Blocks Files:: Reading and writing blocks files.
14803: @end menu
14804:
14805: @c ----------------------------------
1.109 anton 14806: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14807: @section Installing gforth.el
14808: @cindex @file{.emacs}
14809: @cindex @file{gforth.el}, installation
14810: To make the features from @file{gforth.el} available in Emacs, add
14811: the following lines to your @file{.emacs} file:
14812:
14813: @example
14814: (autoload 'forth-mode "gforth.el")
14815: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14816: auto-mode-alist))
14817: (autoload 'forth-block-mode "gforth.el")
14818: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14819: auto-mode-alist))
14820: (add-hook 'forth-mode-hook (function (lambda ()
14821: ;; customize variables here:
14822: (setq forth-indent-level 4)
14823: (setq forth-minor-indent-level 2)
14824: (setq forth-hilight-level 3)
14825: ;;; ...
14826: )))
14827: @end example
14828:
14829: @c ----------------------------------
14830: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14831: @section Emacs Tags
1.1 anton 14832: @cindex @file{TAGS} file
14833: @cindex @file{etags.fs}
14834: @cindex viewing the source of a word in Emacs
1.43 anton 14835: @cindex @code{require}, placement in files
14836: @cindex @code{include}, placement in files
1.107 dvdkhlng 14837: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14838: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14839: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14840: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14841: several tags files at the same time (e.g., one for the Gforth sources
14842: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14843: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14844: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14845: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14846: with @file{etags.fs}, you should avoid putting definitions both before
14847: and after @code{require} etc., otherwise you will see the same file
14848: visited several times by commands like @code{tags-search}.
1.1 anton 14849:
1.107 dvdkhlng 14850: @c ----------------------------------
14851: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
14852: @section Hilighting
14853: @cindex hilighting Forth code in Emacs
14854: @cindex highlighting Forth code in Emacs
14855: @file{gforth.el} comes with a custom source hilighting engine. When
14856: you open a file in @code{forth-mode}, it will be completely parsed,
14857: assigning faces to keywords, comments, strings etc. While you edit
14858: the file, modified regions get parsed and updated on-the-fly.
14859:
14860: Use the variable `forth-hilight-level' to change the level of
14861: decoration from 0 (no hilighting at all) to 3 (the default). Even if
14862: you set the hilighting level to 0, the parser will still work in the
14863: background, collecting information about whether regions of text are
14864: ``compiled'' or ``interpreted''. Those information are required for
14865: auto-indentation to work properly. Set `forth-disable-parser' to
14866: non-nil if your computer is too slow to handle parsing. This will
14867: have an impact on the smartness of the auto-indentation engine,
14868: though.
14869:
14870: Sometimes Forth sources define new features that should be hilighted,
14871: new control structures, defining-words etc. You can use the variable
14872: `forth-custom-words' to make @code{forth-mode} hilight additional
14873: words and constructs. See the docstring of `forth-words' for details
14874: (in Emacs, type @kbd{C-h v forth-words}).
14875:
14876: `forth-custom-words' is meant to be customized in your
14877: @file{.emacs} file. To customize hilighing in a file-specific manner,
14878: set `forth-local-words' in a local-variables section at the end of
14879: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
14880:
14881: Example:
14882: @example
14883: 0 [IF]
14884: Local Variables:
14885: forth-local-words:
14886: ((("t:") definition-starter (font-lock-keyword-face . 1)
14887: "[ \t\n]" t name (font-lock-function-name-face . 3))
14888: ((";t") definition-ender (font-lock-keyword-face . 1)))
14889: End:
14890: [THEN]
14891: @end example
14892:
14893: @c ----------------------------------
14894: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
14895: @section Auto-Indentation
14896: @cindex auto-indentation of Forth code in Emacs
14897: @cindex indentation of Forth code in Emacs
14898: @code{forth-mode} automatically tries to indent lines in a smart way,
14899: whenever you type @key{TAB} or break a line with @kbd{C-m}.
14900:
14901: Simple customization can be achieved by setting
14902: `forth-indent-level' and `forth-minor-indent-level' in your
14903: @file{.emacs} file. For historical reasons @file{gforth.el} indents
14904: per default by multiples of 4 columns. To use the more traditional
14905: 3-column indentation, add the following lines to your @file{.emacs}:
14906:
14907: @example
14908: (add-hook 'forth-mode-hook (function (lambda ()
14909: ;; customize variables here:
14910: (setq forth-indent-level 3)
14911: (setq forth-minor-indent-level 1)
14912: )))
14913: @end example
14914:
14915: If you want indentation to recognize non-default words, customize it
14916: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
14917: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
14918: v forth-indent-words}).
14919:
14920: To customize indentation in a file-specific manner, set
14921: `forth-local-indent-words' in a local-variables section at the end of
14922: your source file (@pxref{Local Variables in Files, Variables,,emacs,
14923: Emacs Manual}).
14924:
14925: Example:
14926: @example
14927: 0 [IF]
14928: Local Variables:
14929: forth-local-indent-words:
14930: ((("t:") (0 . 2) (0 . 2))
14931: ((";t") (-2 . 0) (0 . -2)))
14932: End:
14933: [THEN]
14934: @end example
14935:
14936: @c ----------------------------------
1.109 anton 14937: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 14938: @section Blocks Files
14939: @cindex blocks files, use with Emacs
14940: @code{forth-mode} Autodetects blocks files by checking whether the
14941: length of the first line exceeds 1023 characters. It then tries to
14942: convert the file into normal text format. When you save the file, it
14943: will be written to disk as normal stream-source file.
14944:
14945: If you want to write blocks files, use @code{forth-blocks-mode}. It
14946: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 14947:
1.107 dvdkhlng 14948: @itemize @bullet
14949: @item
14950: Files are written to disk in blocks file format.
14951: @item
14952: Screen numbers are displayed in the mode line (enumerated beginning
14953: with the value of `forth-block-base')
14954: @item
14955: Warnings are displayed when lines exceed 64 characters.
14956: @item
14957: The beginning of the currently edited block is marked with an
14958: overlay-arrow.
14959: @end itemize
1.41 anton 14960:
1.107 dvdkhlng 14961: There are some restrictions you should be aware of. When you open a
14962: blocks file that contains tabulator or newline characters, these
14963: characters will be translated into spaces when the file is written
14964: back to disk. If tabs or newlines are encountered during blocks file
14965: reading, an error is output to the echo area. So have a look at the
14966: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 14967:
1.107 dvdkhlng 14968: Please consult the docstring of @code{forth-blocks-mode} for more
14969: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 14970:
1.26 crook 14971: @c ******************************************************************
1.1 anton 14972: @node Image Files, Engine, Emacs and Gforth, Top
14973: @chapter Image Files
1.26 crook 14974: @cindex image file
14975: @cindex @file{.fi} files
1.1 anton 14976: @cindex precompiled Forth code
14977: @cindex dictionary in persistent form
14978: @cindex persistent form of dictionary
14979:
14980: An image file is a file containing an image of the Forth dictionary,
14981: i.e., compiled Forth code and data residing in the dictionary. By
14982: convention, we use the extension @code{.fi} for image files.
14983:
14984: @menu
1.18 anton 14985: * Image Licensing Issues:: Distribution terms for images.
14986: * Image File Background:: Why have image files?
1.67 anton 14987: * Non-Relocatable Image Files:: don't always work.
1.18 anton 14988: * Data-Relocatable Image Files:: are better.
1.67 anton 14989: * Fully Relocatable Image Files:: better yet.
1.18 anton 14990: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 14991: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 14992: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 14993: @end menu
14994:
1.18 anton 14995: @node Image Licensing Issues, Image File Background, Image Files, Image Files
14996: @section Image Licensing Issues
14997: @cindex license for images
14998: @cindex image license
14999:
15000: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15001: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15002: original image; i.e., according to copyright law it is a derived work of
15003: the original image.
15004:
15005: Since Gforth is distributed under the GNU GPL, the newly created image
15006: falls under the GNU GPL, too. In particular, this means that if you
15007: distribute the image, you have to make all of the sources for the image
1.113 anton 15008: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 15009: GNU General Public License (Section 3)}.
15010:
15011: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15012: contains only code compiled from the sources you gave it; if none of
15013: these sources is under the GPL, the terms discussed above do not apply
15014: to the image. However, if your image needs an engine (a gforth binary)
15015: that is under the GPL, you should make sure that you distribute both in
15016: a way that is at most a @emph{mere aggregation}, if you don't want the
15017: terms of the GPL to apply to the image.
15018:
15019: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 15020: @section Image File Background
15021: @cindex image file background
15022:
1.80 anton 15023: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 15024: definitions written in Forth. Since the Forth compiler itself belongs to
15025: those definitions, it is not possible to start the system with the
1.80 anton 15026: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 15027: code as an image file in nearly executable form. When Gforth starts up,
15028: a C routine loads the image file into memory, optionally relocates the
15029: addresses, then sets up the memory (stacks etc.) according to
15030: information in the image file, and (finally) starts executing Forth
15031: code.
1.1 anton 15032:
15033: The image file variants represent different compromises between the
15034: goals of making it easy to generate image files and making them
15035: portable.
15036:
15037: @cindex relocation at run-time
1.26 crook 15038: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15039: run-time. This avoids many of the complications discussed below (image
15040: files are data relocatable without further ado), but costs performance
15041: (one addition per memory access).
15042:
15043: @cindex relocation at load-time
1.26 crook 15044: By contrast, the Gforth loader performs relocation at image load time. The
15045: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15046: appropriate code-field addresses (or code addresses in the case of
15047: direct threading).
15048:
15049: There are three kinds of image files, with different degrees of
15050: relocatability: non-relocatable, data-relocatable, and fully relocatable
15051: image files.
15052:
15053: @cindex image file loader
15054: @cindex relocating loader
15055: @cindex loader for image files
15056: These image file variants have several restrictions in common; they are
15057: caused by the design of the image file loader:
15058:
15059: @itemize @bullet
15060: @item
15061: There is only one segment; in particular, this means, that an image file
15062: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15063: them). The contents of the stacks are not represented, either.
1.1 anton 15064:
15065: @item
15066: The only kinds of relocation supported are: adding the same offset to
15067: all cells that represent data addresses; and replacing special tokens
15068: with code addresses or with pieces of machine code.
15069:
15070: If any complex computations involving addresses are performed, the
15071: results cannot be represented in the image file. Several applications that
15072: use such computations come to mind:
15073: @itemize @minus
15074: @item
15075: Hashing addresses (or data structures which contain addresses) for table
15076: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15077: purpose, you will have no problem, because the hash tables are
15078: recomputed automatically when the system is started. If you use your own
15079: hash tables, you will have to do something similar.
15080:
15081: @item
15082: There's a cute implementation of doubly-linked lists that uses
15083: @code{XOR}ed addresses. You could represent such lists as singly-linked
15084: in the image file, and restore the doubly-linked representation on
15085: startup.@footnote{In my opinion, though, you should think thrice before
15086: using a doubly-linked list (whatever implementation).}
15087:
15088: @item
15089: The code addresses of run-time routines like @code{docol:} cannot be
15090: represented in the image file (because their tokens would be replaced by
15091: machine code in direct threaded implementations). As a workaround,
15092: compute these addresses at run-time with @code{>code-address} from the
15093: executions tokens of appropriate words (see the definitions of
1.80 anton 15094: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15095:
15096: @item
15097: On many architectures addresses are represented in machine code in some
15098: shifted or mangled form. You cannot put @code{CODE} words that contain
15099: absolute addresses in this form in a relocatable image file. Workarounds
15100: are representing the address in some relative form (e.g., relative to
15101: the CFA, which is present in some register), or loading the address from
15102: a place where it is stored in a non-mangled form.
15103: @end itemize
15104: @end itemize
15105:
15106: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15107: @section Non-Relocatable Image Files
15108: @cindex non-relocatable image files
1.26 crook 15109: @cindex image file, non-relocatable
1.1 anton 15110:
15111: These files are simple memory dumps of the dictionary. They are specific
15112: to the executable (i.e., @file{gforth} file) they were created
15113: with. What's worse, they are specific to the place on which the
15114: dictionary resided when the image was created. Now, there is no
15115: guarantee that the dictionary will reside at the same place the next
15116: time you start Gforth, so there's no guarantee that a non-relocatable
15117: image will work the next time (Gforth will complain instead of crashing,
15118: though).
15119:
15120: You can create a non-relocatable image file with
15121:
1.44 crook 15122:
1.1 anton 15123: doc-savesystem
15124:
1.44 crook 15125:
1.1 anton 15126: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15127: @section Data-Relocatable Image Files
15128: @cindex data-relocatable image files
1.26 crook 15129: @cindex image file, data-relocatable
1.1 anton 15130:
15131: These files contain relocatable data addresses, but fixed code addresses
15132: (instead of tokens). They are specific to the executable (i.e.,
15133: @file{gforth} file) they were created with. For direct threading on some
15134: architectures (e.g., the i386), data-relocatable images do not work. You
15135: get a data-relocatable image, if you use @file{gforthmi} with a
15136: Gforth binary that is not doubly indirect threaded (@pxref{Fully
15137: Relocatable Image Files}).
15138:
15139: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15140: @section Fully Relocatable Image Files
15141: @cindex fully relocatable image files
1.26 crook 15142: @cindex image file, fully relocatable
1.1 anton 15143:
15144: @cindex @file{kern*.fi}, relocatability
15145: @cindex @file{gforth.fi}, relocatability
15146: These image files have relocatable data addresses, and tokens for code
15147: addresses. They can be used with different binaries (e.g., with and
15148: without debugging) on the same machine, and even across machines with
15149: the same data formats (byte order, cell size, floating point
15150: format). However, they are usually specific to the version of Gforth
15151: they were created with. The files @file{gforth.fi} and @file{kernl*.fi}
15152: are fully relocatable.
15153:
15154: There are two ways to create a fully relocatable image file:
15155:
15156: @menu
1.29 crook 15157: * gforthmi:: The normal way
1.1 anton 15158: * cross.fs:: The hard way
15159: @end menu
15160:
15161: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15162: @subsection @file{gforthmi}
15163: @cindex @file{comp-i.fs}
15164: @cindex @file{gforthmi}
15165:
15166: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15167: image @i{file} that contains everything you would load by invoking
15168: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15169: @example
1.29 crook 15170: gforthmi @i{file} @i{options}
1.1 anton 15171: @end example
15172:
15173: E.g., if you want to create an image @file{asm.fi} that has the file
15174: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15175: like this:
15176:
15177: @example
15178: gforthmi asm.fi asm.fs
15179: @end example
15180:
1.27 crook 15181: @file{gforthmi} is implemented as a sh script and works like this: It
15182: produces two non-relocatable images for different addresses and then
15183: compares them. Its output reflects this: first you see the output (if
1.62 crook 15184: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15185: files, then you see the output of the comparing program: It displays the
15186: offset used for data addresses and the offset used for code addresses;
1.1 anton 15187: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15188: image files, it displays a line like this:
1.1 anton 15189:
15190: @example
15191: 78DC BFFFFA50 BFFFFA40
15192: @end example
15193:
15194: This means that at offset $78dc from @code{forthstart}, one input image
15195: contains $bffffa50, and the other contains $bffffa40. Since these cells
15196: cannot be represented correctly in the output image, you should examine
15197: these places in the dictionary and verify that these cells are dead
15198: (i.e., not read before they are written).
1.39 anton 15199:
15200: @cindex --application, @code{gforthmi} option
15201: If you insert the option @code{--application} in front of the image file
15202: name, you will get an image that uses the @code{--appl-image} option
15203: instead of the @code{--image-file} option (@pxref{Invoking
15204: Gforth}). When you execute such an image on Unix (by typing the image
15205: name as command), the Gforth engine will pass all options to the image
15206: instead of trying to interpret them as engine options.
1.1 anton 15207:
1.27 crook 15208: If you type @file{gforthmi} with no arguments, it prints some usage
15209: instructions.
15210:
1.1 anton 15211: @cindex @code{savesystem} during @file{gforthmi}
15212: @cindex @code{bye} during @file{gforthmi}
15213: @cindex doubly indirect threaded code
1.44 crook 15214: @cindex environment variables
15215: @cindex @code{GFORTHD} -- environment variable
15216: @cindex @code{GFORTH} -- environment variable
1.1 anton 15217: @cindex @code{gforth-ditc}
1.29 crook 15218: There are a few wrinkles: After processing the passed @i{options}, the
1.1 anton 15219: words @code{savesystem} and @code{bye} must be visible. A special doubly
15220: indirect threaded version of the @file{gforth} executable is used for
1.62 crook 15221: creating the non-relocatable images; you can pass the exact filename of
1.1 anton 15222: this executable through the environment variable @code{GFORTHD}
15223: (default: @file{gforth-ditc}); if you pass a version that is not doubly
15224: indirect threaded, you will not get a fully relocatable image, but a
1.27 crook 15225: data-relocatable image (because there is no code address offset). The
15226: normal @file{gforth} executable is used for creating the relocatable
15227: image; you can pass the exact filename of this executable through the
15228: environment variable @code{GFORTH}.
1.1 anton 15229:
15230: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15231: @subsection @file{cross.fs}
15232: @cindex @file{cross.fs}
15233: @cindex cross-compiler
15234: @cindex metacompiler
1.47 crook 15235: @cindex target compiler
1.1 anton 15236:
15237: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15238: programming language (@pxref{Cross Compiler}).
1.1 anton 15239:
1.47 crook 15240: @code{cross} allows you to create image files for machines with
1.1 anton 15241: different data sizes and data formats than the one used for generating
15242: the image file. You can also use it to create an application image that
15243: does not contain a Forth compiler. These features are bought with
15244: restrictions and inconveniences in programming. E.g., addresses have to
15245: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15246: order to make the code relocatable.
15247:
15248:
15249: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15250: @section Stack and Dictionary Sizes
15251: @cindex image file, stack and dictionary sizes
15252: @cindex dictionary size default
15253: @cindex stack size default
15254:
15255: If you invoke Gforth with a command line flag for the size
15256: (@pxref{Invoking Gforth}), the size you specify is stored in the
15257: dictionary. If you save the dictionary with @code{savesystem} or create
15258: an image with @file{gforthmi}, this size will become the default
15259: for the resulting image file. E.g., the following will create a
1.21 crook 15260: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15261:
15262: @example
15263: gforthmi gforth.fi -m 1M
15264: @end example
15265:
15266: In other words, if you want to set the default size for the dictionary
15267: and the stacks of an image, just invoke @file{gforthmi} with the
15268: appropriate options when creating the image.
15269:
15270: @cindex stack size, cache-friendly
15271: Note: For cache-friendly behaviour (i.e., good performance), you should
15272: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15273: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15274: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15275:
15276: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15277: @section Running Image Files
15278: @cindex running image files
15279: @cindex invoking image files
15280: @cindex image file invocation
15281:
15282: @cindex -i, invoke image file
15283: @cindex --image file, invoke image file
1.29 crook 15284: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15285: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15286: @example
1.29 crook 15287: gforth -i @i{image}
1.1 anton 15288: @end example
15289:
15290: @cindex executable image file
1.26 crook 15291: @cindex image file, executable
1.1 anton 15292: If your operating system supports starting scripts with a line of the
15293: form @code{#! ...}, you just have to type the image file name to start
15294: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15295: just a convention). I.e., to run Gforth with the image file @i{image},
15296: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15297: This works because every @code{.fi} file starts with a line of this
15298: format:
15299:
15300: @example
15301: #! /usr/local/bin/gforth-0.4.0 -i
15302: @end example
15303:
15304: The file and pathname for the Gforth engine specified on this line is
15305: the specific Gforth executable that it was built against; i.e. the value
15306: of the environment variable @code{GFORTH} at the time that
15307: @file{gforthmi} was executed.
1.1 anton 15308:
1.27 crook 15309: You can make use of the same shell capability to make a Forth source
15310: file into an executable. For example, if you place this text in a file:
1.26 crook 15311:
15312: @example
15313: #! /usr/local/bin/gforth
15314:
15315: ." Hello, world" CR
15316: bye
15317: @end example
15318:
15319: @noindent
1.27 crook 15320: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15321: directly from the command line. The sequence @code{#!} is used in two
15322: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15323: system@footnote{The Unix kernel actually recognises two types of files:
15324: executable files and files of data, where the data is processed by an
15325: interpreter that is specified on the ``interpreter line'' -- the first
15326: line of the file, starting with the sequence #!. There may be a small
15327: limit (e.g., 32) on the number of characters that may be specified on
15328: the interpreter line.} secondly it is treated as a comment character by
15329: Gforth. Because of the second usage, a space is required between
1.80 anton 15330: @code{#!} and the path to the executable (moreover, some Unixes
15331: require the sequence @code{#! /}).
1.27 crook 15332:
15333: The disadvantage of this latter technique, compared with using
1.80 anton 15334: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15335: compiled on-the-fly, each time the program is invoked.
1.26 crook 15336:
1.1 anton 15337: doc-#!
15338:
1.44 crook 15339:
1.1 anton 15340: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15341: @section Modifying the Startup Sequence
15342: @cindex startup sequence for image file
15343: @cindex image file initialization sequence
15344: @cindex initialization sequence of image file
15345:
1.120 anton 15346: You can add your own initialization to the startup sequence of an image
15347: through the deferred word @code{'cold}. @code{'cold} is invoked just
15348: before the image-specific command line processing (i.e., loading files
15349: and evaluating (@code{-e}) strings) starts.
1.1 anton 15350:
15351: A sequence for adding your initialization usually looks like this:
15352:
15353: @example
15354: :noname
15355: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15356: ... \ your stuff
15357: ; IS 'cold
15358: @end example
15359:
1.157 anton 15360: After @code{'cold}, Gforth processes the image options
15361: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15362: another deferred word. This normally prints Gforth's startup message
15363: and does nothing else.
15364:
1.1 anton 15365: @cindex turnkey image files
1.26 crook 15366: @cindex image file, turnkey applications
1.157 anton 15367: So, if you want to make a turnkey image (i.e., an image for an
15368: application instead of an extended Forth system), you can do this in
15369: two ways:
15370:
15371: @itemize @bullet
15372:
15373: @item
15374: If you want to do your interpretation of the OS command-line
15375: arguments, hook into @code{'cold}. In that case you probably also
15376: want to build the image with @code{gforthmi --application}
15377: (@pxref{gforthmi}) to keep the engine from processing OS command line
15378: options. You can then do your own command-line processing with
15379: @code{next-arg}
15380:
15381: @item
15382: If you want to have the normal Gforth processing of OS command-line
15383: arguments, hook into @code{bootmessage}.
15384:
15385: @end itemize
15386:
15387: In either case, you probably do not want the word that you execute in
15388: these hooks to exit normally, but use @code{bye} or @code{throw}.
15389: Otherwise the Gforth startup process would continue and eventually
15390: present the Forth command line to the user.
1.26 crook 15391:
15392: doc-'cold
1.157 anton 15393: doc-bootmessage
1.44 crook 15394:
1.1 anton 15395: @c ******************************************************************
1.113 anton 15396: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15397: @chapter Engine
15398: @cindex engine
15399: @cindex virtual machine
15400:
1.26 crook 15401: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15402: may be helpful for finding your way in the Gforth sources.
15403:
1.109 anton 15404: The ideas in this section have also been published in the following
15405: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15406: Forth-Tagung '93; M. Anton Ertl,
15407: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15408: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15409: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15410: Threaded code variations and optimizations (extended version)}},
15411: Forth-Tagung '02.
1.1 anton 15412:
15413: @menu
15414: * Portability::
15415: * Threading::
15416: * Primitives::
15417: * Performance::
15418: @end menu
15419:
15420: @node Portability, Threading, Engine, Engine
15421: @section Portability
15422: @cindex engine portability
15423:
1.26 crook 15424: An important goal of the Gforth Project is availability across a wide
15425: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15426: achieved this goal by manually coding the engine in assembly language
15427: for several then-popular processors. This approach is very
15428: labor-intensive and the results are short-lived due to progress in
15429: computer architecture.
1.1 anton 15430:
15431: @cindex C, using C for the engine
15432: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15433: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15434: particularly popular for UNIX-based Forths due to the large variety of
15435: architectures of UNIX machines. Unfortunately an implementation in C
15436: does not mix well with the goals of efficiency and with using
15437: traditional techniques: Indirect or direct threading cannot be expressed
15438: in C, and switch threading, the fastest technique available in C, is
15439: significantly slower. Another problem with C is that it is very
15440: cumbersome to express double integer arithmetic.
15441:
15442: @cindex GNU C for the engine
15443: @cindex long long
15444: Fortunately, there is a portable language that does not have these
15445: limitations: GNU C, the version of C processed by the GNU C compiler
15446: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15447: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15448: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15449: threading possible, its @code{long long} type (@pxref{Long Long, ,
15450: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15451: double numbers on many systems. GNU C is freely available on all
1.1 anton 15452: important (and many unimportant) UNIX machines, VMS, 80386s running
15453: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15454: on all these machines.
15455:
15456: Writing in a portable language has the reputation of producing code that
15457: is slower than assembly. For our Forth engine we repeatedly looked at
15458: the code produced by the compiler and eliminated most compiler-induced
15459: inefficiencies by appropriate changes in the source code.
15460:
15461: @cindex explicit register declarations
15462: @cindex --enable-force-reg, configuration flag
15463: @cindex -DFORCE_REG
15464: However, register allocation cannot be portably influenced by the
15465: programmer, leading to some inefficiencies on register-starved
15466: machines. We use explicit register declarations (@pxref{Explicit Reg
15467: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15468: improve the speed on some machines. They are turned on by using the
15469: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15470: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15471: machine, but also on the compiler version: On some machines some
15472: compiler versions produce incorrect code when certain explicit register
15473: declarations are used. So by default @code{-DFORCE_REG} is not used.
15474:
15475: @node Threading, Primitives, Portability, Engine
15476: @section Threading
15477: @cindex inner interpreter implementation
15478: @cindex threaded code implementation
15479:
15480: @cindex labels as values
15481: GNU C's labels as values extension (available since @code{gcc-2.0},
15482: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15483: makes it possible to take the address of @i{label} by writing
15484: @code{&&@i{label}}. This address can then be used in a statement like
15485: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15486: @code{goto x}.
15487:
1.26 crook 15488: @cindex @code{NEXT}, indirect threaded
1.1 anton 15489: @cindex indirect threaded inner interpreter
15490: @cindex inner interpreter, indirect threaded
1.26 crook 15491: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15492: @example
15493: cfa = *ip++;
15494: ca = *cfa;
15495: goto *ca;
15496: @end example
15497: @cindex instruction pointer
15498: For those unfamiliar with the names: @code{ip} is the Forth instruction
15499: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15500: execution token and points to the code field of the next word to be
15501: executed; The @code{ca} (code address) fetched from there points to some
15502: executable code, e.g., a primitive or the colon definition handler
15503: @code{docol}.
15504:
1.26 crook 15505: @cindex @code{NEXT}, direct threaded
1.1 anton 15506: @cindex direct threaded inner interpreter
15507: @cindex inner interpreter, direct threaded
15508: Direct threading is even simpler:
15509: @example
15510: ca = *ip++;
15511: goto *ca;
15512: @end example
15513:
15514: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15515: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15516:
15517: @menu
15518: * Scheduling::
15519: * Direct or Indirect Threaded?::
1.109 anton 15520: * Dynamic Superinstructions::
1.1 anton 15521: * DOES>::
15522: @end menu
15523:
15524: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15525: @subsection Scheduling
15526: @cindex inner interpreter optimization
15527:
15528: There is a little complication: Pipelined and superscalar processors,
15529: i.e., RISC and some modern CISC machines can process independent
15530: instructions while waiting for the results of an instruction. The
15531: compiler usually reorders (schedules) the instructions in a way that
15532: achieves good usage of these delay slots. However, on our first tries
15533: the compiler did not do well on scheduling primitives. E.g., for
15534: @code{+} implemented as
15535: @example
15536: n=sp[0]+sp[1];
15537: sp++;
15538: sp[0]=n;
15539: NEXT;
15540: @end example
1.81 anton 15541: the @code{NEXT} comes strictly after the other code, i.e., there is
15542: nearly no scheduling. After a little thought the problem becomes clear:
15543: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15544: addresses (and the version of @code{gcc} we used would not know it even
15545: if it was possible), so it could not move the load of the cfa above the
15546: store to the TOS. Indeed the pointers could be the same, if code on or
15547: very near the top of stack were executed. In the interest of speed we
15548: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15549: in scheduling: @code{NEXT} is divided into several parts:
15550: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15551: like:
1.1 anton 15552: @example
1.81 anton 15553: NEXT_P0;
1.1 anton 15554: n=sp[0]+sp[1];
15555: sp++;
15556: NEXT_P1;
15557: sp[0]=n;
15558: NEXT_P2;
15559: @end example
15560:
1.81 anton 15561: There are various schemes that distribute the different operations of
15562: NEXT between these parts in several ways; in general, different schemes
15563: perform best on different processors. We use a scheme for most
15564: architectures that performs well for most processors of this
1.109 anton 15565: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15566: the scheme on installation time.
15567:
1.1 anton 15568:
1.109 anton 15569: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15570: @subsection Direct or Indirect Threaded?
15571: @cindex threading, direct or indirect?
15572:
1.109 anton 15573: Threaded forth code consists of references to primitives (simple machine
15574: code routines like @code{+}) and to non-primitives (e.g., colon
15575: definitions, variables, constants); for a specific class of
15576: non-primitives (e.g., variables) there is one code routine (e.g.,
15577: @code{dovar}), but each variable needs a separate reference to its data.
15578:
15579: Traditionally Forth has been implemented as indirect threaded code,
15580: because this allows to use only one cell to reference a non-primitive
15581: (basically you point to the data, and find the code address there).
15582:
15583: @cindex primitive-centric threaded code
15584: However, threaded code in Gforth (since 0.6.0) uses two cells for
15585: non-primitives, one for the code address, and one for the data address;
15586: the data pointer is an immediate argument for the virtual machine
15587: instruction represented by the code address. We call this
15588: @emph{primitive-centric} threaded code, because all code addresses point
15589: to simple primitives. E.g., for a variable, the code address is for
15590: @code{lit} (also used for integer literals like @code{99}).
15591:
15592: Primitive-centric threaded code allows us to use (faster) direct
15593: threading as dispatch method, completely portably (direct threaded code
15594: in Gforth before 0.6.0 required architecture-specific code). It also
15595: eliminates the performance problems related to I-cache consistency that
15596: 386 implementations have with direct threaded code, and allows
15597: additional optimizations.
15598:
15599: @cindex hybrid direct/indirect threaded code
15600: There is a catch, however: the @var{xt} parameter of @code{execute} can
15601: occupy only one cell, so how do we pass non-primitives with their code
15602: @emph{and} data addresses to them? Our answer is to use indirect
15603: threaded dispatch for @code{execute} and other words that use a
15604: single-cell xt. So, normal threaded code in colon definitions uses
15605: direct threading, and @code{execute} and similar words, which dispatch
15606: to xts on the data stack, use indirect threaded code. We call this
15607: @emph{hybrid direct/indirect} threaded code.
15608:
15609: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15610: @cindex gforth engine
15611: @cindex gforth-fast engine
15612: The engines @command{gforth} and @command{gforth-fast} use hybrid
15613: direct/indirect threaded code. This means that with these engines you
15614: cannot use @code{,} to compile an xt. Instead, you have to use
15615: @code{compile,}.
15616:
15617: @cindex gforth-itc engine
1.115 anton 15618: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15619: This engine uses plain old indirect threaded code. It still compiles in
15620: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15621: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15622: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15623: and execute @code{' , is compile,}. Your program can check if it is
15624: running on a hybrid direct/indirect threaded engine or a pure indirect
15625: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15626:
15627:
15628: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15629: @subsection Dynamic Superinstructions
15630: @cindex Dynamic superinstructions with replication
15631: @cindex Superinstructions
15632: @cindex Replication
15633:
15634: The engines @command{gforth} and @command{gforth-fast} use another
15635: optimization: Dynamic superinstructions with replication. As an
15636: example, consider the following colon definition:
15637:
15638: @example
15639: : squared ( n1 -- n2 )
15640: dup * ;
15641: @end example
15642:
15643: Gforth compiles this into the threaded code sequence
15644:
15645: @example
15646: dup
15647: *
15648: ;s
15649: @end example
15650:
15651: In normal direct threaded code there is a code address occupying one
15652: cell for each of these primitives. Each code address points to a
15653: machine code routine, and the interpreter jumps to this machine code in
15654: order to execute the primitive. The routines for these three
15655: primitives are (in @command{gforth-fast} on the 386):
15656:
15657: @example
15658: Code dup
15659: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15660: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15661: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15662: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15663: end-code
15664: Code *
15665: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15666: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15667: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15668: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15669: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15670: end-code
15671: Code ;s
15672: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15673: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15674: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15675: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15676: end-code
15677: @end example
15678:
15679: With dynamic superinstructions and replication the compiler does not
15680: just lay down the threaded code, but also copies the machine code
15681: fragments, usually without the jump at the end.
15682:
15683: @example
15684: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15685: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15686: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15687: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15688: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15689: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15690: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15691: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15692: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15693: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15694: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15695: @end example
15696:
15697: Only when a threaded-code control-flow change happens (e.g., in
15698: @code{;s}), the jump is appended. This optimization eliminates many of
15699: these jumps and makes the rest much more predictable. The speedup
15700: depends on the processor and the application; on the Athlon and Pentium
15701: III this optimization typically produces a speedup by a factor of 2.
15702:
15703: The code addresses in the direct-threaded code are set to point to the
15704: appropriate points in the copied machine code, in this example like
15705: this:
1.1 anton 15706:
1.109 anton 15707: @example
15708: primitive code address
15709: dup $4057D27D
15710: * $4057D286
15711: ;s $4057D292
15712: @end example
15713:
15714: Thus there can be threaded-code jumps to any place in this piece of
15715: code. This also simplifies decompilation quite a bit.
15716:
15717: @cindex --no-dynamic command-line option
15718: @cindex --no-super command-line option
15719: You can disable this optimization with @option{--no-dynamic}. You can
15720: use the copying without eliminating the jumps (i.e., dynamic
15721: replication, but without superinstructions) with @option{--no-super};
15722: this gives the branch prediction benefit alone; the effect on
1.110 anton 15723: performance depends on the CPU; on the Athlon and Pentium III the
15724: speedup is a little less than for dynamic superinstructions with
15725: replication.
15726:
15727: @cindex patching threaded code
15728: One use of these options is if you want to patch the threaded code.
15729: With superinstructions, many of the dispatch jumps are eliminated, so
15730: patching often has no effect. These options preserve all the dispatch
15731: jumps.
1.109 anton 15732:
15733: @cindex --dynamic command-line option
1.110 anton 15734: On some machines dynamic superinstructions are disabled by default,
15735: because it is unsafe on these machines. However, if you feel
15736: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15737:
15738: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15739: @subsection DOES>
15740: @cindex @code{DOES>} implementation
15741:
1.26 crook 15742: @cindex @code{dodoes} routine
15743: @cindex @code{DOES>}-code
1.1 anton 15744: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15745: the chunk of code executed by every word defined by a
1.109 anton 15746: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15747: this is only needed if the xt of the word is @code{execute}d. The main
15748: problem here is: How to find the Forth code to be executed, i.e. the
15749: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15750: solutions:
1.1 anton 15751:
1.21 crook 15752: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15753: @code{DOES>}-code address is stored in the cell after the code address
15754: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15755: illegal in the Forth-79 and all later standards, because in fig-Forth
15756: this address lies in the body (which is illegal in these
15757: standards). However, by making the code field larger for all words this
15758: solution becomes legal again. We use this approach. Leaving a cell
15759: unused in most words is a bit wasteful, but on the machines we are
15760: targeting this is hardly a problem.
15761:
1.1 anton 15762:
15763: @node Primitives, Performance, Threading, Engine
15764: @section Primitives
15765: @cindex primitives, implementation
15766: @cindex virtual machine instructions, implementation
15767:
15768: @menu
15769: * Automatic Generation::
15770: * TOS Optimization::
15771: * Produced code::
15772: @end menu
15773:
15774: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15775: @subsection Automatic Generation
15776: @cindex primitives, automatic generation
15777:
15778: @cindex @file{prims2x.fs}
1.109 anton 15779:
1.1 anton 15780: Since the primitives are implemented in a portable language, there is no
15781: longer any need to minimize the number of primitives. On the contrary,
15782: having many primitives has an advantage: speed. In order to reduce the
15783: number of errors in primitives and to make programming them easier, we
1.109 anton 15784: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15785: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15786: generates most (and sometimes all) of the C code for a primitive from
15787: the stack effect notation. The source for a primitive has the following
15788: form:
1.1 anton 15789:
15790: @cindex primitive source format
15791: @format
1.58 anton 15792: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15793: [@code{""}@i{glossary entry}@code{""}]
15794: @i{C code}
1.1 anton 15795: [@code{:}
1.29 crook 15796: @i{Forth code}]
1.1 anton 15797: @end format
15798:
15799: The items in brackets are optional. The category and glossary fields
15800: are there for generating the documentation, the Forth code is there
15801: for manual implementations on machines without GNU C. E.g., the source
15802: for the primitive @code{+} is:
15803: @example
1.58 anton 15804: + ( n1 n2 -- n ) core plus
1.1 anton 15805: n = n1+n2;
15806: @end example
15807:
15808: This looks like a specification, but in fact @code{n = n1+n2} is C
15809: code. Our primitive generation tool extracts a lot of information from
15810: the stack effect notations@footnote{We use a one-stack notation, even
15811: though we have separate data and floating-point stacks; The separate
15812: notation can be generated easily from the unified notation.}: The number
15813: of items popped from and pushed on the stack, their type, and by what
15814: name they are referred to in the C code. It then generates a C code
15815: prelude and postlude for each primitive. The final C code for @code{+}
15816: looks like this:
15817:
15818: @example
1.46 pazsan 15819: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15820: /* */ /* documentation */
1.81 anton 15821: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15822: @{
15823: DEF_CA /* definition of variable ca (indirect threading) */
15824: Cell n1; /* definitions of variables */
15825: Cell n2;
15826: Cell n;
1.81 anton 15827: NEXT_P0; /* NEXT part 0 */
1.1 anton 15828: n1 = (Cell) sp[1]; /* input */
15829: n2 = (Cell) TOS;
15830: sp += 1; /* stack adjustment */
15831: @{
15832: n = n1+n2; /* C code taken from the source */
15833: @}
15834: NEXT_P1; /* NEXT part 1 */
15835: TOS = (Cell)n; /* output */
15836: NEXT_P2; /* NEXT part 2 */
15837: @}
15838: @end example
15839:
15840: This looks long and inefficient, but the GNU C compiler optimizes quite
15841: well and produces optimal code for @code{+} on, e.g., the R3000 and the
15842: HP RISC machines: Defining the @code{n}s does not produce any code, and
15843: using them as intermediate storage also adds no cost.
15844:
1.26 crook 15845: There are also other optimizations that are not illustrated by this
15846: example: assignments between simple variables are usually for free (copy
1.1 anton 15847: propagation). If one of the stack items is not used by the primitive
15848: (e.g. in @code{drop}), the compiler eliminates the load from the stack
15849: (dead code elimination). On the other hand, there are some things that
15850: the compiler does not do, therefore they are performed by
15851: @file{prims2x.fs}: The compiler does not optimize code away that stores
15852: a stack item to the place where it just came from (e.g., @code{over}).
15853:
15854: While programming a primitive is usually easy, there are a few cases
15855: where the programmer has to take the actions of the generator into
15856: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 15857: fall through to @code{NEXT}.
1.109 anton 15858:
15859: For more information
1.1 anton 15860:
15861: @node TOS Optimization, Produced code, Automatic Generation, Primitives
15862: @subsection TOS Optimization
15863: @cindex TOS optimization for primitives
15864: @cindex primitives, keeping the TOS in a register
15865:
15866: An important optimization for stack machine emulators, e.g., Forth
15867: engines, is keeping one or more of the top stack items in
1.29 crook 15868: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
15869: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 15870: @itemize @bullet
15871: @item
1.29 crook 15872: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 15873: due to fewer loads from and stores to the stack.
1.29 crook 15874: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
15875: @i{y<n}, due to additional moves between registers.
1.1 anton 15876: @end itemize
15877:
15878: @cindex -DUSE_TOS
15879: @cindex -DUSE_NO_TOS
15880: In particular, keeping one item in a register is never a disadvantage,
15881: if there are enough registers. Keeping two items in registers is a
15882: disadvantage for frequent words like @code{?branch}, constants,
15883: variables, literals and @code{i}. Therefore our generator only produces
15884: code that keeps zero or one items in registers. The generated C code
15885: covers both cases; the selection between these alternatives is made at
15886: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
15887: code for @code{+} is just a simple variable name in the one-item case,
15888: otherwise it is a macro that expands into @code{sp[0]}. Note that the
15889: GNU C compiler tries to keep simple variables like @code{TOS} in
15890: registers, and it usually succeeds, if there are enough registers.
15891:
15892: @cindex -DUSE_FTOS
15893: @cindex -DUSE_NO_FTOS
15894: The primitive generator performs the TOS optimization for the
15895: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
15896: operations the benefit of this optimization is even larger:
15897: floating-point operations take quite long on most processors, but can be
15898: performed in parallel with other operations as long as their results are
15899: not used. If the FP-TOS is kept in a register, this works. If
15900: it is kept on the stack, i.e., in memory, the store into memory has to
15901: wait for the result of the floating-point operation, lengthening the
15902: execution time of the primitive considerably.
15903:
15904: The TOS optimization makes the automatic generation of primitives a
15905: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
15906: @code{TOS} is not sufficient. There are some special cases to
15907: consider:
15908: @itemize @bullet
15909: @item In the case of @code{dup ( w -- w w )} the generator must not
15910: eliminate the store to the original location of the item on the stack,
15911: if the TOS optimization is turned on.
15912: @item Primitives with stack effects of the form @code{--}
1.29 crook 15913: @i{out1}...@i{outy} must store the TOS to the stack at the start.
15914: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 15915: must load the TOS from the stack at the end. But for the null stack
15916: effect @code{--} no stores or loads should be generated.
15917: @end itemize
15918:
15919: @node Produced code, , TOS Optimization, Primitives
15920: @subsection Produced code
15921: @cindex primitives, assembly code listing
15922:
15923: @cindex @file{engine.s}
15924: To see what assembly code is produced for the primitives on your machine
15925: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 15926: look at the resulting file @file{engine.s}. Alternatively, you can also
15927: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 15928:
15929: @node Performance, , Primitives, Engine
15930: @section Performance
15931: @cindex performance of some Forth interpreters
15932: @cindex engine performance
15933: @cindex benchmarking Forth systems
15934: @cindex Gforth performance
15935:
15936: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 15937: impossible to write a significantly faster threaded-code engine.
1.1 anton 15938:
15939: On register-starved machines like the 386 architecture processors
15940: improvements are possible, because @code{gcc} does not utilize the
15941: registers as well as a human, even with explicit register declarations;
15942: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
15943: and hand-tuned it for the 486; this system is 1.19 times faster on the
15944: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 15945: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
15946: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
15947: registers fit in real registers (and we can even afford to use the TOS
15948: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 15949: earlier results. And dynamic superinstructions provide another speedup
15950: (but only around a factor 1.2 on the 486).
1.1 anton 15951:
15952: @cindex Win32Forth performance
15953: @cindex NT Forth performance
15954: @cindex eforth performance
15955: @cindex ThisForth performance
15956: @cindex PFE performance
15957: @cindex TILE performance
1.81 anton 15958: The potential advantage of assembly language implementations is not
1.112 anton 15959: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 15960: (direct threaded, compiled with @code{gcc-2.95.1} and
15961: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
15962: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
15963: (with and without peephole (aka pinhole) optimization of the threaded
15964: code); all these systems were written in assembly language. We also
15965: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
15966: with @code{gcc-2.6.3} with the default configuration for Linux:
15967: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
15968: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
15969: employs peephole optimization of the threaded code) and TILE (compiled
15970: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
15971: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
15972: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
15973: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
15974: then extended it to run the benchmarks, added the peephole optimizer,
15975: ran the benchmarks and reported the results.
1.40 anton 15976:
1.1 anton 15977: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
15978: matrix multiplication come from the Stanford integer benchmarks and have
15979: been translated into Forth by Martin Fraeman; we used the versions
15980: included in the TILE Forth package, but with bigger data set sizes; and
15981: a recursive Fibonacci number computation for benchmarking calling
15982: performance. The following table shows the time taken for the benchmarks
15983: scaled by the time taken by Gforth (in other words, it shows the speedup
15984: factor that Gforth achieved over the other systems).
15985:
15986: @example
1.112 anton 15987: relative Win32- NT eforth This-
15988: time Gforth Forth Forth eforth +opt PFE Forth TILE
15989: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
15990: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
15991: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
15992: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 15993: @end example
15994:
1.26 crook 15995: You may be quite surprised by the good performance of Gforth when
15996: compared with systems written in assembly language. One important reason
15997: for the disappointing performance of these other systems is probably
15998: that they are not written optimally for the 486 (e.g., they use the
15999: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16000: but costly method for relocating the Forth image: like @code{cforth}, it
16001: computes the actual addresses at run time, resulting in two address
16002: computations per @code{NEXT} (@pxref{Image File Background}).
16003:
1.1 anton 16004: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16005: explained with the self-imposed restriction of the latter systems to
16006: standard C, which makes efficient threading impossible (however, the
1.4 anton 16007: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 16008: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16009: Moreover, current C compilers have a hard time optimizing other aspects
16010: of the ThisForth and the TILE source.
16011:
1.26 crook 16012: The performance of Gforth on 386 architecture processors varies widely
16013: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16014: allocate any of the virtual machine registers into real machine
16015: registers by itself and would not work correctly with explicit register
1.112 anton 16016: declarations, giving a significantly slower engine (on a 486DX2/66
16017: running the Sieve) than the one measured above.
1.1 anton 16018:
1.26 crook 16019: Note that there have been several releases of Win32Forth since the
16020: release presented here, so the results presented above may have little
1.40 anton 16021: predictive value for the performance of Win32Forth today (results for
16022: the current release on an i486DX2/66 are welcome).
1.1 anton 16023:
16024: @cindex @file{Benchres}
1.66 anton 16025: In
16026: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16027: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 16028: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 16029: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16030: several native code systems; that version of Gforth is slower on a 486
1.112 anton 16031: than the version used here. You can find a newer version of these
16032: measurements at
1.47 crook 16033: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 16034: find numbers for Gforth on various machines in @file{Benchres}.
16035:
1.26 crook 16036: @c ******************************************************************
1.113 anton 16037: @c @node Binding to System Library, Cross Compiler, Engine, Top
16038: @c @chapter Binding to System Library
1.13 pazsan 16039:
1.113 anton 16040: @c ****************************************************************
16041: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16042: @chapter Cross Compiler
1.47 crook 16043: @cindex @file{cross.fs}
16044: @cindex cross-compiler
16045: @cindex metacompiler
16046: @cindex target compiler
1.13 pazsan 16047:
1.46 pazsan 16048: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16049: mostly written in Forth, including crucial parts like the outer
16050: interpreter and compiler, it needs compiled Forth code to get
16051: started. The cross compiler allows to create new images for other
16052: architectures, even running under another Forth system.
1.13 pazsan 16053:
16054: @menu
1.67 anton 16055: * Using the Cross Compiler::
16056: * How the Cross Compiler Works::
1.13 pazsan 16057: @end menu
16058:
1.21 crook 16059: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16060: @section Using the Cross Compiler
1.46 pazsan 16061:
16062: The cross compiler uses a language that resembles Forth, but isn't. The
16063: main difference is that you can execute Forth code after definition,
16064: while you usually can't execute the code compiled by cross, because the
16065: code you are compiling is typically for a different computer than the
16066: one you are compiling on.
16067:
1.81 anton 16068: @c anton: This chapter is somewhat different from waht I would expect: I
16069: @c would expect an explanation of the cross language and how to create an
16070: @c application image with it. The section explains some aspects of
16071: @c creating a Gforth kernel.
16072:
1.46 pazsan 16073: The Makefile is already set up to allow you to create kernels for new
16074: architectures with a simple make command. The generic kernels using the
16075: GCC compiled virtual machine are created in the normal build process
16076: with @code{make}. To create a embedded Gforth executable for e.g. the
16077: 8086 processor (running on a DOS machine), type
16078:
16079: @example
16080: make kernl-8086.fi
16081: @end example
16082:
16083: This will use the machine description from the @file{arch/8086}
16084: directory to create a new kernel. A machine file may look like that:
16085:
16086: @example
16087: \ Parameter for target systems 06oct92py
16088:
16089: 4 Constant cell \ cell size in bytes
16090: 2 Constant cell<< \ cell shift to bytes
16091: 5 Constant cell>bit \ cell shift to bits
16092: 8 Constant bits/char \ bits per character
16093: 8 Constant bits/byte \ bits per byte [default: 8]
16094: 8 Constant float \ bytes per float
16095: 8 Constant /maxalign \ maximum alignment in bytes
16096: false Constant bigendian \ byte order
16097: ( true=big, false=little )
16098:
16099: include machpc.fs \ feature list
16100: @end example
16101:
16102: This part is obligatory for the cross compiler itself, the feature list
16103: is used by the kernel to conditionally compile some features in and out,
16104: depending on whether the target supports these features.
16105:
16106: There are some optional features, if you define your own primitives,
16107: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16108: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16109: @code{prims-include} includes primitives, and @code{>boot} prepares for
16110: booting.
16111:
16112: @example
16113: : asm-include ." Include assembler" cr
16114: s" arch/8086/asm.fs" included ;
16115:
16116: : prims-include ." Include primitives" cr
16117: s" arch/8086/prim.fs" included ;
16118:
16119: : >boot ." Prepare booting" cr
16120: s" ' boot >body into-forth 1+ !" evaluate ;
16121: @end example
16122:
16123: These words are used as sort of macro during the cross compilation in
1.81 anton 16124: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16125: be possible --- but more complicated --- to write a new kernel project
16126: file, too.
16127:
16128: @file{kernel/main.fs} expects the machine description file name on the
16129: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16130: @code{mach-file} leaves a counted string on the stack, or
16131: @code{machine-file} leaves an address, count pair of the filename on the
16132: stack.
16133:
16134: The feature list is typically controlled using @code{SetValue}, generic
16135: files that are used by several projects can use @code{DefaultValue}
16136: instead. Both functions work like @code{Value}, when the value isn't
16137: defined, but @code{SetValue} works like @code{to} if the value is
16138: defined, and @code{DefaultValue} doesn't set anything, if the value is
16139: defined.
16140:
16141: @example
16142: \ generic mach file for pc gforth 03sep97jaw
16143:
16144: true DefaultValue NIL \ relocating
16145:
16146: >ENVIRON
16147:
16148: true DefaultValue file \ controls the presence of the
16149: \ file access wordset
16150: true DefaultValue OS \ flag to indicate a operating system
16151:
16152: true DefaultValue prims \ true: primitives are c-code
16153:
16154: true DefaultValue floating \ floating point wordset is present
16155:
16156: true DefaultValue glocals \ gforth locals are present
16157: \ will be loaded
16158: true DefaultValue dcomps \ double number comparisons
16159:
16160: true DefaultValue hash \ hashing primitives are loaded/present
16161:
16162: true DefaultValue xconds \ used together with glocals,
16163: \ special conditionals supporting gforths'
16164: \ local variables
16165: true DefaultValue header \ save a header information
16166:
16167: true DefaultValue backtrace \ enables backtrace code
16168:
16169: false DefaultValue ec
16170: false DefaultValue crlf
16171:
16172: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16173:
16174: &16 KB DefaultValue stack-size
16175: &15 KB &512 + DefaultValue fstack-size
16176: &15 KB DefaultValue rstack-size
16177: &14 KB &512 + DefaultValue lstack-size
16178: @end example
1.13 pazsan 16179:
1.48 anton 16180: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16181: @section How the Cross Compiler Works
1.13 pazsan 16182:
16183: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16184: @appendix Bugs
1.1 anton 16185: @cindex bug reporting
16186:
1.21 crook 16187: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16188:
1.103 anton 16189: If you find a bug, please submit a bug report through
16190: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16191:
16192: @itemize @bullet
16193: @item
1.81 anton 16194: A program (or a sequence of keyboard commands) that reproduces the bug.
16195: @item
16196: A description of what you think constitutes the buggy behaviour.
16197: @item
1.21 crook 16198: The Gforth version used (it is announced at the start of an
16199: interactive Gforth session).
16200: @item
16201: The machine and operating system (on Unix
16202: systems @code{uname -a} will report this information).
16203: @item
1.81 anton 16204: The installation options (you can find the configure options at the
16205: start of @file{config.status}) and configuration (@code{configure}
16206: output or @file{config.cache}).
1.21 crook 16207: @item
16208: A complete list of changes (if any) you (or your installer) have made to the
16209: Gforth sources.
16210: @end itemize
1.1 anton 16211:
16212: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16213: to Report Bugs, gcc.info, GNU C Manual}.
16214:
16215:
1.21 crook 16216: @node Origin, Forth-related information, Bugs, Top
16217: @appendix Authors and Ancestors of Gforth
1.1 anton 16218:
16219: @section Authors and Contributors
16220: @cindex authors of Gforth
16221: @cindex contributors to Gforth
16222:
16223: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16224: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16225: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16226: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16227: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16228: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16229: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16230: working on automatic support for calling C libraries. Helpful comments
16231: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16232: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16233: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16234: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16235: comments from many others; thank you all, sorry for not listing you
16236: here (but digging through my mailbox to extract your names is on my
16237: to-do list).
1.1 anton 16238:
16239: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16240: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16241: was developed across the Internet, and its authors did not meet
1.20 pazsan 16242: physically for the first 4 years of development.
1.1 anton 16243:
16244: @section Pedigree
1.26 crook 16245: @cindex pedigree of Gforth
1.1 anton 16246:
1.81 anton 16247: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16248: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16249:
1.20 pazsan 16250: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16251: 32 bit native code version of VolksForth for the Atari ST, written
16252: mostly by Dietrich Weineck.
16253:
1.81 anton 16254: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16255: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16256: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16257:
1.147 anton 16258: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16259: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16260:
16261: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16262: 1979. Robert Selzer and Bill Ragsdale developed the original
16263: implementation of fig-Forth for the 6502 based on microForth.
16264:
16265: The principal architect of microForth was Dean Sanderson. microForth was
16266: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16267: the 1802, and subsequently implemented on the 8080, the 6800 and the
16268: Z80.
16269:
16270: All earlier Forth systems were custom-made, usually by Charles Moore,
16271: who discovered (as he puts it) Forth during the late 60s. The first full
16272: Forth existed in 1971.
16273:
1.81 anton 16274: A part of the information in this section comes from
16275: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16276: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16277: Charles H. Moore, presented at the HOPL-II conference and preprinted
16278: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16279: genealogical information about Forth there. For a more general (and
16280: graphical) Forth family tree look see
16281: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16282: Forth Family Tree and Timeline}.
1.1 anton 16283:
1.81 anton 16284: @c ------------------------------------------------------------------
1.113 anton 16285: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16286: @appendix Other Forth-related information
16287: @cindex Forth-related information
16288:
1.81 anton 16289: @c anton: I threw most of this stuff out, because it can be found through
16290: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16291:
16292: @cindex comp.lang.forth
16293: @cindex frequently asked questions
1.81 anton 16294: There is an active news group (comp.lang.forth) discussing Forth
16295: (including Gforth) and Forth-related issues. Its
16296: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16297: (frequently asked questions and their answers) contains a lot of
16298: information on Forth. You should read it before posting to
16299: comp.lang.forth.
1.21 crook 16300:
1.81 anton 16301: The ANS Forth standard is most usable in its
16302: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16303:
1.113 anton 16304: @c ---------------------------------------------------
16305: @node Licenses, Word Index, Forth-related information, Top
16306: @appendix Licenses
16307:
16308: @menu
16309: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16310: * Copying:: GPL (for copying this software).
1.113 anton 16311: @end menu
16312:
1.192 anton 16313: @node GNU Free Documentation License, Copying, Licenses, Licenses
16314: @appendixsec GNU Free Documentation License
1.113 anton 16315: @include fdl.texi
16316:
1.192 anton 16317: @node Copying, , GNU Free Documentation License, Licenses
16318: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16319: @include gpl.texi
16320:
16321:
16322:
1.81 anton 16323: @c ------------------------------------------------------------------
1.113 anton 16324: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16325: @unnumbered Word Index
16326:
1.26 crook 16327: This index is a list of Forth words that have ``glossary'' entries
16328: within this manual. Each word is listed with its stack effect and
16329: wordset.
1.1 anton 16330:
16331: @printindex fn
16332:
1.81 anton 16333: @c anton: the name index seems superfluous given the word and concept indices.
16334:
16335: @c @node Name Index, Concept Index, Word Index, Top
16336: @c @unnumbered Name Index
1.41 anton 16337:
1.81 anton 16338: @c This index is a list of Forth words that have ``glossary'' entries
16339: @c within this manual.
1.41 anton 16340:
1.81 anton 16341: @c @printindex ky
1.41 anton 16342:
1.113 anton 16343: @c -------------------------------------------------------
1.81 anton 16344: @node Concept Index, , Word Index, Top
1.1 anton 16345: @unnumbered Concept and Word Index
16346:
1.26 crook 16347: Not all entries listed in this index are present verbatim in the
16348: text. This index also duplicates, in abbreviated form, all of the words
16349: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16350:
16351: @printindex cp
16352:
16353: @bye
1.81 anton 16354:
16355:
1.1 anton 16356:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>