Annotation of gforth/doc/gforth.ds, revision 1.210
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.208 anton 64: Copyright @copyright{} 1995, 1996, 1997, 1998, 2000, 2003, 2004,2005,2006,2007,2008,2009 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.204 anton 148: * Startup speed:: When 14ms is not fast enough ...
1.48 anton 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.196 anton 413: * Defining library interfaces::
414: * Declaring OS-level libraries::
1.155 anton 415: * Callbacks::
1.178 anton 416: * C interface internals::
1.155 anton 417: * Low-Level C Interface Words::
418:
1.78 anton 419: Assembler and Code Words
420:
421: * Code and ;code::
422: * Common Assembler:: Assembler Syntax
423: * Common Disassembler::
424: * 386 Assembler:: Deviations and special cases
425: * Alpha Assembler:: Deviations and special cases
426: * MIPS assembler:: Deviations and special cases
1.167 anton 427: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 428: * ARM Assembler:: Deviations and special cases
1.78 anton 429: * Other assemblers:: How to write them
430:
1.12 anton 431: Tools
432:
433: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 434: * Stack depth changes:: Where does this stack item come from?
1.12 anton 435:
436: ANS conformance
437:
438: * The Core Words::
439: * The optional Block word set::
440: * The optional Double Number word set::
441: * The optional Exception word set::
442: * The optional Facility word set::
443: * The optional File-Access word set::
444: * The optional Floating-Point word set::
445: * The optional Locals word set::
446: * The optional Memory-Allocation word set::
447: * The optional Programming-Tools word set::
448: * The optional Search-Order word set::
449:
450: The Core Words
451:
452: * core-idef:: Implementation Defined Options
453: * core-ambcond:: Ambiguous Conditions
454: * core-other:: Other System Documentation
455:
456: The optional Block word set
457:
458: * block-idef:: Implementation Defined Options
459: * block-ambcond:: Ambiguous Conditions
460: * block-other:: Other System Documentation
461:
462: The optional Double Number word set
463:
464: * double-ambcond:: Ambiguous Conditions
465:
466: The optional Exception word set
467:
468: * exception-idef:: Implementation Defined Options
469:
470: The optional Facility word set
471:
472: * facility-idef:: Implementation Defined Options
473: * facility-ambcond:: Ambiguous Conditions
474:
475: The optional File-Access word set
476:
477: * file-idef:: Implementation Defined Options
478: * file-ambcond:: Ambiguous Conditions
479:
480: The optional Floating-Point word set
481:
482: * floating-idef:: Implementation Defined Options
483: * floating-ambcond:: Ambiguous Conditions
484:
485: The optional Locals word set
486:
487: * locals-idef:: Implementation Defined Options
488: * locals-ambcond:: Ambiguous Conditions
489:
490: The optional Memory-Allocation word set
491:
492: * memory-idef:: Implementation Defined Options
493:
494: The optional Programming-Tools word set
495:
496: * programming-idef:: Implementation Defined Options
497: * programming-ambcond:: Ambiguous Conditions
498:
499: The optional Search-Order word set
500:
501: * search-idef:: Implementation Defined Options
502: * search-ambcond:: Ambiguous Conditions
503:
1.109 anton 504: Emacs and Gforth
505:
506: * Installing gforth.el:: Making Emacs aware of Forth.
507: * Emacs Tags:: Viewing the source of a word in Emacs.
508: * Hilighting:: Making Forth code look prettier.
509: * Auto-Indentation:: Customizing auto-indentation.
510: * Blocks Files:: Reading and writing blocks files.
511:
1.12 anton 512: Image Files
513:
1.24 anton 514: * Image Licensing Issues:: Distribution terms for images.
515: * Image File Background:: Why have image files?
1.67 anton 516: * Non-Relocatable Image Files:: don't always work.
1.24 anton 517: * Data-Relocatable Image Files:: are better.
1.67 anton 518: * Fully Relocatable Image Files:: better yet.
1.24 anton 519: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.32 anton 520: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.24 anton 521: * Modifying the Startup Sequence:: and turnkey applications.
1.12 anton 522:
523: Fully Relocatable Image Files
524:
1.27 crook 525: * gforthmi:: The normal way
1.12 anton 526: * cross.fs:: The hard way
527:
528: Engine
529:
530: * Portability::
531: * Threading::
532: * Primitives::
533: * Performance::
534:
535: Threading
536:
537: * Scheduling::
538: * Direct or Indirect Threaded?::
1.109 anton 539: * Dynamic Superinstructions::
1.12 anton 540: * DOES>::
541:
542: Primitives
543:
544: * Automatic Generation::
545: * TOS Optimization::
546: * Produced code::
1.13 pazsan 547:
548: Cross Compiler
549:
1.67 anton 550: * Using the Cross Compiler::
551: * How the Cross Compiler Works::
1.13 pazsan 552:
1.113 anton 553: Licenses
554:
555: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 556: * Copying:: GPL (for copying this software).
1.113 anton 557:
1.24 anton 558: @end detailmenu
1.1 anton 559: @end menu
560:
1.113 anton 561: @c ----------------------------------------------------------
1.1 anton 562: @iftex
563: @unnumbered Preface
564: @cindex Preface
1.21 crook 565: This manual documents Gforth. Some introductory material is provided for
566: readers who are unfamiliar with Forth or who are migrating to Gforth
567: from other Forth compilers. However, this manual is primarily a
568: reference manual.
1.1 anton 569: @end iftex
570:
1.28 crook 571: @comment TODO much more blurb here.
1.26 crook 572:
573: @c ******************************************************************
1.113 anton 574: @node Goals, Gforth Environment, Top, Top
1.26 crook 575: @comment node-name, next, previous, up
576: @chapter Goals of Gforth
577: @cindex goals of the Gforth project
578: The goal of the Gforth Project is to develop a standard model for
579: ANS Forth. This can be split into several subgoals:
580:
581: @itemize @bullet
582: @item
583: Gforth should conform to the ANS Forth Standard.
584: @item
585: It should be a model, i.e. it should define all the
586: implementation-dependent things.
587: @item
588: It should become standard, i.e. widely accepted and used. This goal
589: is the most difficult one.
590: @end itemize
591:
592: To achieve these goals Gforth should be
593: @itemize @bullet
594: @item
595: Similar to previous models (fig-Forth, F83)
596: @item
597: Powerful. It should provide for all the things that are considered
598: necessary today and even some that are not yet considered necessary.
599: @item
600: Efficient. It should not get the reputation of being exceptionally
601: slow.
602: @item
603: Free.
604: @item
605: Available on many machines/easy to port.
606: @end itemize
607:
608: Have we achieved these goals? Gforth conforms to the ANS Forth
609: standard. It may be considered a model, but we have not yet documented
610: which parts of the model are stable and which parts we are likely to
611: change. It certainly has not yet become a de facto standard, but it
612: appears to be quite popular. It has some similarities to and some
613: differences from previous models. It has some powerful features, but not
614: yet everything that we envisioned. We certainly have achieved our
1.65 anton 615: execution speed goals (@pxref{Performance})@footnote{However, in 1998
616: the bar was raised when the major commercial Forth vendors switched to
617: native code compilers.}. It is free and available on many machines.
1.29 crook 618:
1.26 crook 619: @c ******************************************************************
1.48 anton 620: @node Gforth Environment, Tutorial, Goals, Top
1.29 crook 621: @chapter Gforth Environment
622: @cindex Gforth environment
1.21 crook 623:
1.45 crook 624: Note: ultimately, the Gforth man page will be auto-generated from the
1.29 crook 625: material in this chapter.
1.21 crook 626:
627: @menu
1.29 crook 628: * Invoking Gforth:: Getting in
629: * Leaving Gforth:: Getting out
630: * Command-line editing::
1.48 anton 631: * Environment variables:: that affect how Gforth starts up
1.29 crook 632: * Gforth Files:: What gets installed and where
1.112 anton 633: * Gforth in pipes::
1.204 anton 634: * Startup speed:: When 14ms is not fast enough ...
1.21 crook 635: @end menu
636:
1.49 anton 637: For related information about the creation of images see @ref{Image Files}.
1.29 crook 638:
1.21 crook 639: @comment ----------------------------------------------
1.48 anton 640: @node Invoking Gforth, Leaving Gforth, Gforth Environment, Gforth Environment
1.29 crook 641: @section Invoking Gforth
642: @cindex invoking Gforth
643: @cindex running Gforth
644: @cindex command-line options
645: @cindex options on the command line
646: @cindex flags on the command line
1.21 crook 647:
1.30 anton 648: Gforth is made up of two parts; an executable ``engine'' (named
1.109 anton 649: @command{gforth} or @command{gforth-fast}) and an image file. To start it, you
1.30 anton 650: will usually just say @code{gforth} -- this automatically loads the
651: default image file @file{gforth.fi}. In many other cases the default
652: Gforth image will be invoked like this:
1.21 crook 653: @example
1.30 anton 654: gforth [file | -e forth-code] ...
1.21 crook 655: @end example
1.29 crook 656: @noindent
657: This interprets the contents of the files and the Forth code in the order they
658: are given.
1.21 crook 659:
1.109 anton 660: In addition to the @command{gforth} engine, there is also an engine
661: called @command{gforth-fast}, which is faster, but gives less
662: informative error messages (@pxref{Error messages}) and may catch some
1.166 anton 663: errors (in particular, stack underflows and integer division errors)
664: later or not at all. You should use it for debugged,
1.109 anton 665: performance-critical programs.
666:
667: Moreover, there is an engine called @command{gforth-itc}, which is
668: useful in some backwards-compatibility situations (@pxref{Direct or
669: Indirect Threaded?}).
1.30 anton 670:
1.29 crook 671: In general, the command line looks like this:
1.21 crook 672:
673: @example
1.30 anton 674: gforth[-fast] [engine options] [image options]
1.21 crook 675: @end example
676:
1.30 anton 677: The engine options must come before the rest of the command
1.29 crook 678: line. They are:
1.26 crook 679:
1.29 crook 680: @table @code
681: @cindex -i, command-line option
682: @cindex --image-file, command-line option
683: @item --image-file @i{file}
684: @itemx -i @i{file}
685: Loads the Forth image @i{file} instead of the default
686: @file{gforth.fi} (@pxref{Image Files}).
1.21 crook 687:
1.39 anton 688: @cindex --appl-image, command-line option
689: @item --appl-image @i{file}
690: Loads the image @i{file} and leaves all further command-line arguments
1.65 anton 691: to the image (instead of processing them as engine options). This is
692: useful for building executable application images on Unix, built with
1.39 anton 693: @code{gforthmi --application ...}.
694:
1.29 crook 695: @cindex --path, command-line option
696: @cindex -p, command-line option
697: @item --path @i{path}
698: @itemx -p @i{path}
699: Uses @i{path} for searching the image file and Forth source code files
700: instead of the default in the environment variable @code{GFORTHPATH} or
701: the path specified at installation time (e.g.,
702: @file{/usr/local/share/gforth/0.2.0:.}). A path is given as a list of
703: directories, separated by @samp{:} (on Unix) or @samp{;} (on other OSs).
1.21 crook 704:
1.29 crook 705: @cindex --dictionary-size, command-line option
706: @cindex -m, command-line option
707: @cindex @i{size} parameters for command-line options
708: @cindex size of the dictionary and the stacks
709: @item --dictionary-size @i{size}
710: @itemx -m @i{size}
711: Allocate @i{size} space for the Forth dictionary space instead of
712: using the default specified in the image (typically 256K). The
713: @i{size} specification for this and subsequent options consists of
714: an integer and a unit (e.g.,
715: @code{4M}). The unit can be one of @code{b} (bytes), @code{e} (element
716: size, in this case Cells), @code{k} (kilobytes), @code{M} (Megabytes),
717: @code{G} (Gigabytes), and @code{T} (Terabytes). If no unit is specified,
718: @code{e} is used.
1.21 crook 719:
1.29 crook 720: @cindex --data-stack-size, command-line option
721: @cindex -d, command-line option
722: @item --data-stack-size @i{size}
723: @itemx -d @i{size}
724: Allocate @i{size} space for the data stack instead of using the
725: default specified in the image (typically 16K).
1.21 crook 726:
1.29 crook 727: @cindex --return-stack-size, command-line option
728: @cindex -r, command-line option
729: @item --return-stack-size @i{size}
730: @itemx -r @i{size}
731: Allocate @i{size} space for the return stack instead of using the
732: default specified in the image (typically 15K).
1.21 crook 733:
1.29 crook 734: @cindex --fp-stack-size, command-line option
735: @cindex -f, command-line option
736: @item --fp-stack-size @i{size}
737: @itemx -f @i{size}
738: Allocate @i{size} space for the floating point stack instead of
739: using the default specified in the image (typically 15.5K). In this case
740: the unit specifier @code{e} refers to floating point numbers.
1.21 crook 741:
1.48 anton 742: @cindex --locals-stack-size, command-line option
743: @cindex -l, command-line option
744: @item --locals-stack-size @i{size}
745: @itemx -l @i{size}
746: Allocate @i{size} space for the locals stack instead of using the
747: default specified in the image (typically 14.5K).
748:
1.176 anton 749: @cindex --vm-commit, command-line option
750: @cindex overcommit memory for dictionary and stacks
751: @cindex memory overcommit for dictionary and stacks
752: @item --vm-commit
753: Normally, Gforth tries to start up even if there is not enough virtual
754: memory for the dictionary and the stacks (using @code{MAP_NORESERVE}
755: on OSs that support it); so you can ask for a really big dictionary
756: and/or stacks, and as long as you don't use more virtual memory than
757: is available, everything will be fine (but if you use more, processes
758: get killed). With this option you just use the default allocation
759: policy of the OS; for OSs that don't overcommit (e.g., Solaris), this
760: means that you cannot and should not ask for as big dictionary and
761: stacks, but once Gforth successfully starts up, out-of-memory won't
762: kill it.
763:
1.48 anton 764: @cindex -h, command-line option
765: @cindex --help, command-line option
766: @item --help
767: @itemx -h
768: Print a message about the command-line options
769:
770: @cindex -v, command-line option
771: @cindex --version, command-line option
772: @item --version
773: @itemx -v
774: Print version and exit
775:
776: @cindex --debug, command-line option
777: @item --debug
778: Print some information useful for debugging on startup.
779:
780: @cindex --offset-image, command-line option
781: @item --offset-image
782: Start the dictionary at a slightly different position than would be used
783: otherwise (useful for creating data-relocatable images,
784: @pxref{Data-Relocatable Image Files}).
785:
786: @cindex --no-offset-im, command-line option
787: @item --no-offset-im
788: Start the dictionary at the normal position.
789:
790: @cindex --clear-dictionary, command-line option
791: @item --clear-dictionary
792: Initialize all bytes in the dictionary to 0 before loading the image
793: (@pxref{Data-Relocatable Image Files}).
794:
795: @cindex --die-on-signal, command-line-option
796: @item --die-on-signal
797: Normally Gforth handles most signals (e.g., the user interrupt SIGINT,
798: or the segmentation violation SIGSEGV) by translating it into a Forth
799: @code{THROW}. With this option, Gforth exits if it receives such a
800: signal. This option is useful when the engine and/or the image might be
801: severely broken (such that it causes another signal before recovering
802: from the first); this option avoids endless loops in such cases.
1.109 anton 803:
1.119 anton 804: @cindex --no-dynamic, command-line option
805: @cindex --dynamic, command-line option
1.109 anton 806: @item --no-dynamic
807: @item --dynamic
808: Disable or enable dynamic superinstructions with replication
809: (@pxref{Dynamic Superinstructions}).
810:
1.119 anton 811: @cindex --no-super, command-line option
1.109 anton 812: @item --no-super
1.110 anton 813: Disable dynamic superinstructions, use just dynamic replication; this is
814: useful if you want to patch threaded code (@pxref{Dynamic
815: Superinstructions}).
1.119 anton 816:
817: @cindex --ss-number, command-line option
818: @item --ss-number=@var{N}
819: Use only the first @var{N} static superinstructions compiled into the
820: engine (default: use them all; note that only @code{gforth-fast} has
821: any). This option is useful for measuring the performance impact of
822: static superinstructions.
823:
824: @cindex --ss-min-..., command-line options
825: @item --ss-min-codesize
826: @item --ss-min-ls
827: @item --ss-min-lsu
828: @item --ss-min-nexts
829: Use specified metric for determining the cost of a primitive or static
830: superinstruction for static superinstruction selection. @code{Codesize}
831: is the native code size of the primive or static superinstruction,
832: @code{ls} is the number of loads and stores, @code{lsu} is the number of
833: loads, stores, and updates, and @code{nexts} is the number of dispatches
834: (not taking dynamic superinstructions into account), i.e. every
835: primitive or static superinstruction has cost 1. Default:
836: @code{codesize} if you use dynamic code generation, otherwise
837: @code{nexts}.
838:
839: @cindex --ss-greedy, command-line option
840: @item --ss-greedy
841: This option is useful for measuring the performance impact of static
842: superinstructions. By default, an optimal shortest-path algorithm is
843: used for selecting static superinstructions. With @option{--ss-greedy}
844: this algorithm is modified to assume that anything after the static
845: superinstruction currently under consideration is not combined into
846: static superinstructions. With @option{--ss-min-nexts} this produces
847: the same result as a greedy algorithm that always selects the longest
848: superinstruction available at the moment. E.g., if there are
849: superinstructions AB and BCD, then for the sequence A B C D the optimal
850: algorithm will select A BCD and the greedy algorithm will select AB C D.
851:
852: @cindex --print-metrics, command-line option
853: @item --print-metrics
854: Prints some metrics used during static superinstruction selection:
855: @code{code size} is the actual size of the dynamically generated code.
856: @code{Metric codesize} is the sum of the codesize metrics as seen by
857: static superinstruction selection; there is a difference from @code{code
858: size}, because not all primitives and static superinstructions are
859: compiled into dynamically generated code, and because of markers. The
860: other metrics correspond to the @option{ss-min-...} options. This
861: option is useful for evaluating the effects of the @option{--ss-...}
862: options.
1.109 anton 863:
1.48 anton 864: @end table
865:
866: @cindex loading files at startup
867: @cindex executing code on startup
868: @cindex batch processing with Gforth
869: As explained above, the image-specific command-line arguments for the
870: default image @file{gforth.fi} consist of a sequence of filenames and
871: @code{-e @var{forth-code}} options that are interpreted in the sequence
872: in which they are given. The @code{-e @var{forth-code}} or
1.121 anton 873: @code{--evaluate @var{forth-code}} option evaluates the Forth code. This
874: option takes only one argument; if you want to evaluate more Forth
875: words, you have to quote them or use @code{-e} several times. To exit
1.48 anton 876: after processing the command line (instead of entering interactive mode)
1.121 anton 877: append @code{-e bye} to the command line. You can also process the
878: command-line arguments with a Forth program (@pxref{OS command line
879: arguments}).
1.48 anton 880:
881: @cindex versions, invoking other versions of Gforth
882: If you have several versions of Gforth installed, @code{gforth} will
883: invoke the version that was installed last. @code{gforth-@i{version}}
884: invokes a specific version. If your environment contains the variable
885: @code{GFORTHPATH}, you may want to override it by using the
886: @code{--path} option.
887:
888: Not yet implemented:
889: On startup the system first executes the system initialization file
890: (unless the option @code{--no-init-file} is given; note that the system
891: resulting from using this option may not be ANS Forth conformant). Then
892: the user initialization file @file{.gforth.fs} is executed, unless the
1.62 crook 893: option @code{--no-rc} is given; this file is searched for in @file{.},
1.48 anton 894: then in @file{~}, then in the normal path (see above).
895:
896:
897:
898: @comment ----------------------------------------------
899: @node Leaving Gforth, Command-line editing, Invoking Gforth, Gforth Environment
900: @section Leaving Gforth
901: @cindex Gforth - leaving
902: @cindex leaving Gforth
903:
904: You can leave Gforth by typing @code{bye} or @kbd{Ctrl-d} (at the start
905: of a line) or (if you invoked Gforth with the @code{--die-on-signal}
906: option) @kbd{Ctrl-c}. When you leave Gforth, all of your definitions and
1.49 anton 907: data are discarded. For ways of saving the state of the system before
908: leaving Gforth see @ref{Image Files}.
1.48 anton 909:
910: doc-bye
911:
912:
913: @comment ----------------------------------------------
1.65 anton 914: @node Command-line editing, Environment variables, Leaving Gforth, Gforth Environment
1.48 anton 915: @section Command-line editing
916: @cindex command-line editing
917:
918: Gforth maintains a history file that records every line that you type to
919: the text interpreter. This file is preserved between sessions, and is
920: used to provide a command-line recall facility; if you type @kbd{Ctrl-P}
921: repeatedly you can recall successively older commands from this (or
922: previous) session(s). The full list of command-line editing facilities is:
923:
924: @itemize @bullet
925: @item
926: @kbd{Ctrl-p} (``previous'') (or up-arrow) to recall successively older
927: commands from the history buffer.
928: @item
929: @kbd{Ctrl-n} (``next'') (or down-arrow) to recall successively newer commands
930: from the history buffer.
931: @item
932: @kbd{Ctrl-f} (or right-arrow) to move the cursor right, non-destructively.
933: @item
934: @kbd{Ctrl-b} (or left-arrow) to move the cursor left, non-destructively.
935: @item
936: @kbd{Ctrl-h} (backspace) to delete the character to the left of the cursor,
937: closing up the line.
938: @item
939: @kbd{Ctrl-k} to delete (``kill'') from the cursor to the end of the line.
940: @item
941: @kbd{Ctrl-a} to move the cursor to the start of the line.
942: @item
943: @kbd{Ctrl-e} to move the cursor to the end of the line.
944: @item
945: @key{RET} (@kbd{Ctrl-m}) or @key{LFD} (@kbd{Ctrl-j}) to submit the current
946: line.
947: @item
948: @key{TAB} to step through all possible full-word completions of the word
949: currently being typed.
950: @item
1.65 anton 951: @kbd{Ctrl-d} on an empty line line to terminate Gforth (gracefully,
952: using @code{bye}).
953: @item
954: @kbd{Ctrl-x} (or @code{Ctrl-d} on a non-empty line) to delete the
955: character under the cursor.
1.48 anton 956: @end itemize
957:
958: When editing, displayable characters are inserted to the left of the
959: cursor position; the line is always in ``insert'' (as opposed to
960: ``overstrike'') mode.
961:
962: @cindex history file
963: @cindex @file{.gforth-history}
964: On Unix systems, the history file is @file{~/.gforth-history} by
965: default@footnote{i.e. it is stored in the user's home directory.}. You
966: can find out the name and location of your history file using:
967:
968: @example
969: history-file type \ Unix-class systems
970:
971: history-file type \ Other systems
972: history-dir type
973: @end example
974:
975: If you enter long definitions by hand, you can use a text editor to
976: paste them out of the history file into a Forth source file for reuse at
977: a later time.
978:
979: Gforth never trims the size of the history file, so you should do this
980: periodically, if necessary.
981:
982: @comment this is all defined in history.fs
983: @comment NAC TODO the ctrl-D behaviour can either do a bye or a beep.. how is that option
984: @comment chosen?
985:
986:
987: @comment ----------------------------------------------
1.65 anton 988: @node Environment variables, Gforth Files, Command-line editing, Gforth Environment
1.48 anton 989: @section Environment variables
990: @cindex environment variables
991:
992: Gforth uses these environment variables:
993:
994: @itemize @bullet
995: @item
996: @cindex @code{GFORTHHIST} -- environment variable
997: @code{GFORTHHIST} -- (Unix systems only) specifies the directory in which to
998: open/create the history file, @file{.gforth-history}. Default:
999: @code{$HOME}.
1000:
1001: @item
1002: @cindex @code{GFORTHPATH} -- environment variable
1003: @code{GFORTHPATH} -- specifies the path used when searching for the gforth image file and
1004: for Forth source-code files.
1005:
1006: @item
1.147 anton 1007: @cindex @code{LANG} -- environment variable
1008: @code{LANG} -- see @code{LC_CTYPE}
1009:
1010: @item
1011: @cindex @code{LC_ALL} -- environment variable
1012: @code{LC_ALL} -- see @code{LC_CTYPE}
1013:
1014: @item
1015: @cindex @code{LC_CTYPE} -- environment variable
1016: @code{LC_CTYPE} -- If this variable contains ``UTF-8'' on Gforth
1017: startup, Gforth uses the UTF-8 encoding for strings internally and
1018: expects its input and produces its output in UTF-8 encoding, otherwise
1019: the encoding is 8bit (see @pxref{Xchars and Unicode}). If this
1020: environment variable is unset, Gforth looks in @code{LC_ALL}, and if
1021: that is unset, in @code{LANG}.
1022:
1023: @item
1.129 anton 1024: @cindex @code{GFORTHSYSTEMPREFIX} -- environment variable
1025:
1026: @code{GFORTHSYSTEMPREFIX} -- specifies what to prepend to the argument
1027: of @code{system} before passing it to C's @code{system()}. Default:
1.130 anton 1028: @code{"./$COMSPEC /c "} on Windows, @code{""} on other OSs. The prefix
1.129 anton 1029: and the command are directly concatenated, so if a space between them is
1030: necessary, append it to the prefix.
1031:
1032: @item
1.48 anton 1033: @cindex @code{GFORTH} -- environment variable
1.49 anton 1034: @code{GFORTH} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1035:
1036: @item
1037: @cindex @code{GFORTHD} -- environment variable
1.62 crook 1038: @code{GFORTHD} -- used by @file{gforthmi}, @xref{gforthmi}.
1.48 anton 1039:
1040: @item
1041: @cindex @code{TMP}, @code{TEMP} - environment variable
1042: @code{TMP}, @code{TEMP} - (non-Unix systems only) used as a potential
1043: location for the history file.
1044: @end itemize
1045:
1046: @comment also POSIXELY_CORRECT LINES COLUMNS HOME but no interest in
1047: @comment mentioning these.
1048:
1049: All the Gforth environment variables default to sensible values if they
1050: are not set.
1051:
1052:
1053: @comment ----------------------------------------------
1.112 anton 1054: @node Gforth Files, Gforth in pipes, Environment variables, Gforth Environment
1.48 anton 1055: @section Gforth files
1056: @cindex Gforth files
1057:
1058: When you install Gforth on a Unix system, it installs files in these
1059: locations by default:
1060:
1061: @itemize @bullet
1062: @item
1063: @file{/usr/local/bin/gforth}
1064: @item
1065: @file{/usr/local/bin/gforthmi}
1066: @item
1067: @file{/usr/local/man/man1/gforth.1} - man page.
1068: @item
1069: @file{/usr/local/info} - the Info version of this manual.
1070: @item
1071: @file{/usr/local/lib/gforth/<version>/...} - Gforth @file{.fi} files.
1072: @item
1073: @file{/usr/local/share/gforth/<version>/TAGS} - Emacs TAGS file.
1074: @item
1075: @file{/usr/local/share/gforth/<version>/...} - Gforth source files.
1076: @item
1077: @file{.../emacs/site-lisp/gforth.el} - Emacs gforth mode.
1078: @end itemize
1079:
1080: You can select different places for installation by using
1081: @code{configure} options (listed with @code{configure --help}).
1082:
1083: @comment ----------------------------------------------
1.112 anton 1084: @node Gforth in pipes, Startup speed, Gforth Files, Gforth Environment
1085: @section Gforth in pipes
1086: @cindex pipes, Gforth as part of
1087:
1088: Gforth can be used in pipes created elsewhere (described here). It can
1089: also create pipes on its own (@pxref{Pipes}).
1090:
1091: @cindex input from pipes
1092: If you pipe into Gforth, your program should read with @code{read-file}
1093: or @code{read-line} from @code{stdin} (@pxref{General files}).
1094: @code{Key} does not recognize the end of input. Words like
1095: @code{accept} echo the input and are therefore usually not useful for
1096: reading from a pipe. You have to invoke the Forth program with an OS
1097: command-line option, as you have no chance to use the Forth command line
1098: (the text interpreter would try to interpret the pipe input).
1099:
1100: @cindex output in pipes
1101: You can output to a pipe with @code{type}, @code{emit}, @code{cr} etc.
1102:
1103: @cindex silent exiting from Gforth
1104: When you write to a pipe that has been closed at the other end, Gforth
1105: receives a SIGPIPE signal (``pipe broken''). Gforth translates this
1106: into the exception @code{broken-pipe-error}. If your application does
1107: not catch that exception, the system catches it and exits, usually
1108: silently (unless you were working on the Forth command line; then it
1109: prints an error message and exits). This is usually the desired
1110: behaviour.
1111:
1112: If you do not like this behaviour, you have to catch the exception
1113: yourself, and react to it.
1114:
1115: Here's an example of an invocation of Gforth that is usable in a pipe:
1116:
1117: @example
1118: gforth -e ": foo begin pad dup 10 stdin read-file throw dup while \
1119: type repeat ; foo bye"
1120: @end example
1121:
1122: This example just copies the input verbatim to the output. A very
1123: simple pipe containing this example looks like this:
1124:
1125: @example
1126: cat startup.fs |
1127: gforth -e ": foo begin pad dup 80 stdin read-file throw dup while \
1128: type repeat ; foo bye"|
1129: head
1130: @end example
1131:
1132: @cindex stderr and pipes
1133: Pipes involving Gforth's @code{stderr} output do not work.
1134:
1135: @comment ----------------------------------------------
1136: @node Startup speed, , Gforth in pipes, Gforth Environment
1.48 anton 1137: @section Startup speed
1138: @cindex Startup speed
1139: @cindex speed, startup
1140:
1141: If Gforth is used for CGI scripts or in shell scripts, its startup
1.204 anton 1142: speed may become a problem. On a 3GHz Core 2 Duo E8400 under 64-bit
1143: Linux 2.6.27.8 with libc-2.7, @code{gforth-fast -e bye} takes 13.1ms
1144: user and 1.2ms system time (@code{gforth -e bye} is faster on startup
1145: with about 3.4ms user time and 1.2ms system time, because it subsumes
1146: some of the options discussed below).
1.48 anton 1147:
1148: If startup speed is a problem, you may consider the following ways to
1149: improve it; or you may consider ways to reduce the number of startups
1.204 anton 1150: (for example, by using Fast-CGI). Note that the first steps below
1151: improve the startup time at the cost of run-time (including
1152: compile-time), so whether they are profitable depends on the balance
1153: of these times in your application.
1154:
1155: An easy step that influences Gforth startup speed is the use of a
1156: number of options that increase run-time, but decrease image-loading
1157: time.
1158:
1159: The first of these that you should try is @code{--ss-number=0
1160: --ss-states=1} because this option buys relatively little run-time
1161: speedup and costs quite a bit of time at startup. @code{gforth-fast
1162: --ss-number=0 --ss-states=1 -e bye} takes about 2.8ms user and 1.5ms
1163: system time.
1.48 anton 1164:
1.204 anton 1165: The next option is @code{--no-dynamic} which has a substantial impact
1166: on run-time (about a factor of 2 on several platforms), but still
1167: makes startup speed a little faster: @code{gforth-fast --ss-number=0
1168: --ss-states=1 --no-dynamic -e bye} consumes about 2.6ms user and 1.2ms
1169: system time.
1170:
1171: The next step to improve startup speed is to use a data-relocatable
1172: image (@pxref{Data-Relocatable Image Files}). This avoids the
1173: relocation cost for the code in the image (but not for the data).
1174: Note that the image is then specific to the particular binary you are
1175: using (i.e., whether it is @code{gforth}, @code{gforth-fast}, and even
1176: the particular build). You create the data-relocatable image that
1177: works with @code{./gforth-fast} with @code{GFORTHD="./gforth-fast
1178: --no-dynamic" gforthmi gforthdr.fi} (the @code{--no-dynamic} is
1179: required here or the image will not work). And you run it with
1180: @code{gforth-fast -i gforthdr.fi ... -e bye} (the flags discussed
1181: above don't matter here, because they only come into play on
1182: relocatable code). @code{gforth-fast -i gforthdr.fi -e bye} takes
1183: about 1.1ms user and 1.2ms system time.
1184:
1185: One step further is to avoid all relocation cost and part of the
1186: copy-on-write cost through using a non-relocatable image
1187: (@pxref{Non-Relocatable Image Files}). However, this has the
1188: disadvantage that it does not work on operating systems with address
1189: space randomization (the default in, e.g., Linux nowadays), or if the
1190: dictionary moves for any other reason (e.g., because of a change of
1191: the OS kernel or an updated library), so we cannot really recommend
1192: it. You create a non-relocatable image with @code{gforth-fast
1193: --no-dynamic -e "savesystem gforthnr.fi bye"} (the @code{--no-dynamic}
1194: is required here, too). And you run it with @code{gforth-fast -i
1195: gforthnr.fi ... -e bye} (again the flags discussed above don't
1196: matter). @code{gforth-fast -i gforthdr.fi -e bye} takes
1197: about 0.9ms user and 0.9ms system time.
1198:
1199: If the script you want to execute contains a significant amount of
1200: code, it may be profitable to compile it into the image to avoid the
1201: cost of compiling it at startup time.
1.48 anton 1202:
1203: @c ******************************************************************
1204: @node Tutorial, Introduction, Gforth Environment, Top
1205: @chapter Forth Tutorial
1206: @cindex Tutorial
1207: @cindex Forth Tutorial
1208:
1.67 anton 1209: @c Topics from nac's Introduction that could be mentioned:
1210: @c press <ret> after each line
1211: @c Prompt
1212: @c numbers vs. words in dictionary on text interpretation
1213: @c what happens on redefinition
1214: @c parsing words (in particular, defining words)
1215:
1.83 anton 1216: The difference of this chapter from the Introduction
1217: (@pxref{Introduction}) is that this tutorial is more fast-paced, should
1218: be used while sitting in front of a computer, and covers much more
1219: material, but does not explain how the Forth system works.
1220:
1.62 crook 1221: This tutorial can be used with any ANS-compliant Forth; any
1.206 anton 1222: Gforth-specific features are marked as such and you can skip them if
1223: you work with another Forth. This tutorial does not explain all
1224: features of Forth, just enough to get you started and give you some
1225: ideas about the facilities available in Forth. Read the rest of the
1226: manual when you are through this.
1.48 anton 1227:
1228: The intended way to use this tutorial is that you work through it while
1229: sitting in front of the console, take a look at the examples and predict
1230: what they will do, then try them out; if the outcome is not as expected,
1231: find out why (e.g., by trying out variations of the example), so you
1232: understand what's going on. There are also some assignments that you
1233: should solve.
1234:
1235: This tutorial assumes that you have programmed before and know what,
1236: e.g., a loop is.
1237:
1238: @c !! explain compat library
1239:
1240: @menu
1241: * Starting Gforth Tutorial::
1242: * Syntax Tutorial::
1243: * Crash Course Tutorial::
1244: * Stack Tutorial::
1245: * Arithmetics Tutorial::
1246: * Stack Manipulation Tutorial::
1247: * Using files for Forth code Tutorial::
1248: * Comments Tutorial::
1249: * Colon Definitions Tutorial::
1250: * Decompilation Tutorial::
1251: * Stack-Effect Comments Tutorial::
1252: * Types Tutorial::
1253: * Factoring Tutorial::
1254: * Designing the stack effect Tutorial::
1255: * Local Variables Tutorial::
1256: * Conditional execution Tutorial::
1257: * Flags and Comparisons Tutorial::
1258: * General Loops Tutorial::
1259: * Counted loops Tutorial::
1260: * Recursion Tutorial::
1261: * Leaving definitions or loops Tutorial::
1262: * Return Stack Tutorial::
1263: * Memory Tutorial::
1264: * Characters and Strings Tutorial::
1265: * Alignment Tutorial::
1.190 anton 1266: * Floating Point Tutorial::
1.87 anton 1267: * Files Tutorial::
1.48 anton 1268: * Interpretation and Compilation Semantics and Immediacy Tutorial::
1269: * Execution Tokens Tutorial::
1270: * Exceptions Tutorial::
1271: * Defining Words Tutorial::
1272: * Arrays and Records Tutorial::
1273: * POSTPONE Tutorial::
1274: * Literal Tutorial::
1275: * Advanced macros Tutorial::
1276: * Compilation Tokens Tutorial::
1277: * Wordlists and Search Order Tutorial::
1278: @end menu
1279:
1280: @node Starting Gforth Tutorial, Syntax Tutorial, Tutorial, Tutorial
1281: @section Starting Gforth
1.66 anton 1282: @cindex starting Gforth tutorial
1.48 anton 1283: You can start Gforth by typing its name:
1284:
1285: @example
1286: gforth
1287: @end example
1288:
1289: That puts you into interactive mode; you can leave Gforth by typing
1290: @code{bye}. While in Gforth, you can edit the command line and access
1291: the command line history with cursor keys, similar to bash.
1292:
1293:
1294: @node Syntax Tutorial, Crash Course Tutorial, Starting Gforth Tutorial, Tutorial
1295: @section Syntax
1.66 anton 1296: @cindex syntax tutorial
1.48 anton 1297:
1.171 anton 1298: A @dfn{word} is a sequence of arbitrary characters (except white
1.48 anton 1299: space). Words are separated by white space. E.g., each of the
1300: following lines contains exactly one word:
1301:
1302: @example
1303: word
1304: !@@#$%^&*()
1305: 1234567890
1306: 5!a
1307: @end example
1308:
1.205 anton 1309: A frequent beginner's error is to leave out necessary white space,
1.48 anton 1310: resulting in an error like @samp{Undefined word}; so if you see such an
1311: error, check if you have put spaces wherever necessary.
1312:
1313: @example
1314: ." hello, world" \ correct
1315: ."hello, world" \ gives an "Undefined word" error
1316: @end example
1317:
1.65 anton 1318: Gforth and most other Forth systems ignore differences in case (they are
1.48 anton 1319: case-insensitive), i.e., @samp{word} is the same as @samp{Word}. If
1320: your system is case-sensitive, you may have to type all the examples
1321: given here in upper case.
1322:
1323:
1324: @node Crash Course Tutorial, Stack Tutorial, Syntax Tutorial, Tutorial
1325: @section Crash Course
1326:
1.209 anton 1327: Forth does not prevent you from shooting yourself in the foot. Let's
1328: try a few ways to crash Gforth:
1.48 anton 1329:
1330: @example
1331: 0 0 !
1332: here execute
1333: ' catch >body 20 erase abort
1334: ' (quit) >body 20 erase
1335: @end example
1336:
1.209 anton 1337: The last two examples are guaranteed to destroy important parts of
1338: Gforth (and most other systems), so you better leave Gforth afterwards
1339: (if it has not finished by itself). On some systems you may have to
1340: kill gforth from outside (e.g., in Unix with @code{kill}).
1341:
1342: You will find out later what these lines do and then you will get an
1343: idea why they produce crashes.
1.48 anton 1344:
1345: Now that you know how to produce crashes (and that there's not much to
1346: them), let's learn how to produce meaningful programs.
1347:
1348:
1349: @node Stack Tutorial, Arithmetics Tutorial, Crash Course Tutorial, Tutorial
1350: @section Stack
1.66 anton 1351: @cindex stack tutorial
1.48 anton 1352:
1353: The most obvious feature of Forth is the stack. When you type in a
1.205 anton 1354: number, it is pushed on the stack. You can display the contents of the
1.48 anton 1355: stack with @code{.s}.
1356:
1357: @example
1358: 1 2 .s
1359: 3 .s
1360: @end example
1361:
1362: @code{.s} displays the top-of-stack to the right, i.e., the numbers
1363: appear in @code{.s} output as they appeared in the input.
1364:
1.205 anton 1365: You can print the top element of the stack with @code{.}.
1.48 anton 1366:
1367: @example
1368: 1 2 3 . . .
1369: @end example
1370:
1371: In general, words consume their stack arguments (@code{.s} is an
1372: exception).
1373:
1.141 anton 1374: @quotation Assignment
1.48 anton 1375: What does the stack contain after @code{5 6 7 .}?
1.141 anton 1376: @end quotation
1.48 anton 1377:
1378:
1379: @node Arithmetics Tutorial, Stack Manipulation Tutorial, Stack Tutorial, Tutorial
1380: @section Arithmetics
1.66 anton 1381: @cindex arithmetics tutorial
1.48 anton 1382:
1383: The words @code{+}, @code{-}, @code{*}, @code{/}, and @code{mod} always
1384: operate on the top two stack items:
1385:
1386: @example
1.67 anton 1387: 2 2 .s
1388: + .s
1389: .
1.48 anton 1390: 2 1 - .
1391: 7 3 mod .
1392: @end example
1393:
1394: The operands of @code{-}, @code{/}, and @code{mod} are in the same order
1395: as in the corresponding infix expression (this is generally the case in
1396: Forth).
1397:
1398: Parentheses are superfluous (and not available), because the order of
1399: the words unambiguously determines the order of evaluation and the
1400: operands:
1401:
1402: @example
1403: 3 4 + 5 * .
1404: 3 4 5 * + .
1405: @end example
1406:
1.141 anton 1407: @quotation Assignment
1.48 anton 1408: What are the infix expressions corresponding to the Forth code above?
1409: Write @code{6-7*8+9} in Forth notation@footnote{This notation is also
1410: known as Postfix or RPN (Reverse Polish Notation).}.
1.141 anton 1411: @end quotation
1.48 anton 1412:
1413: To change the sign, use @code{negate}:
1414:
1415: @example
1416: 2 negate .
1417: @end example
1418:
1.141 anton 1419: @quotation Assignment
1.48 anton 1420: Convert -(-3)*4-5 to Forth.
1.141 anton 1421: @end quotation
1.48 anton 1422:
1423: @code{/mod} performs both @code{/} and @code{mod}.
1424:
1425: @example
1426: 7 3 /mod . .
1427: @end example
1428:
1.66 anton 1429: Reference: @ref{Arithmetic}.
1430:
1431:
1.48 anton 1432: @node Stack Manipulation Tutorial, Using files for Forth code Tutorial, Arithmetics Tutorial, Tutorial
1433: @section Stack Manipulation
1.66 anton 1434: @cindex stack manipulation tutorial
1.48 anton 1435:
1436: Stack manipulation words rearrange the data on the stack.
1437:
1438: @example
1439: 1 .s drop .s
1440: 1 .s dup .s drop drop .s
1441: 1 2 .s over .s drop drop drop
1442: 1 2 .s swap .s drop drop
1443: 1 2 3 .s rot .s drop drop drop
1444: @end example
1445:
1446: These are the most important stack manipulation words. There are also
1447: variants that manipulate twice as many stack items:
1448:
1449: @example
1450: 1 2 3 4 .s 2swap .s 2drop 2drop
1451: @end example
1452:
1453: Two more stack manipulation words are:
1454:
1455: @example
1456: 1 2 .s nip .s drop
1457: 1 2 .s tuck .s 2drop drop
1458: @end example
1459:
1.141 anton 1460: @quotation Assignment
1.48 anton 1461: Replace @code{nip} and @code{tuck} with combinations of other stack
1462: manipulation words.
1463:
1464: @example
1465: Given: How do you get:
1466: 1 2 3 3 2 1
1467: 1 2 3 1 2 3 2
1468: 1 2 3 1 2 3 3
1469: 1 2 3 1 3 3
1470: 1 2 3 2 1 3
1471: 1 2 3 4 4 3 2 1
1472: 1 2 3 1 2 3 1 2 3
1473: 1 2 3 4 1 2 3 4 1 2
1474: 1 2 3
1475: 1 2 3 1 2 3 4
1476: 1 2 3 1 3
1477: @end example
1.141 anton 1478: @end quotation
1.48 anton 1479:
1480: @example
1481: 5 dup * .
1482: @end example
1483:
1.141 anton 1484: @quotation Assignment
1.48 anton 1485: Write 17^3 and 17^4 in Forth, without writing @code{17} more than once.
1486: Write a piece of Forth code that expects two numbers on the stack
1487: (@var{a} and @var{b}, with @var{b} on top) and computes
1488: @code{(a-b)(a+1)}.
1.141 anton 1489: @end quotation
1.48 anton 1490:
1.66 anton 1491: Reference: @ref{Stack Manipulation}.
1492:
1493:
1.48 anton 1494: @node Using files for Forth code Tutorial, Comments Tutorial, Stack Manipulation Tutorial, Tutorial
1495: @section Using files for Forth code
1.66 anton 1496: @cindex loading Forth code, tutorial
1497: @cindex files containing Forth code, tutorial
1.48 anton 1498:
1499: While working at the Forth command line is convenient for one-line
1500: examples and short one-off code, you probably want to store your source
1501: code in files for convenient editing and persistence. You can use your
1502: favourite editor (Gforth includes Emacs support, @pxref{Emacs and
1.102 anton 1503: Gforth}) to create @var{file.fs} and use
1.48 anton 1504:
1505: @example
1.102 anton 1506: s" @var{file.fs}" included
1.48 anton 1507: @end example
1508:
1509: to load it into your Forth system. The file name extension I use for
1510: Forth files is @samp{.fs}.
1511:
1512: You can easily start Gforth with some files loaded like this:
1513:
1514: @example
1.102 anton 1515: gforth @var{file1.fs} @var{file2.fs}
1.48 anton 1516: @end example
1517:
1518: If an error occurs during loading these files, Gforth terminates,
1519: whereas an error during @code{INCLUDED} within Gforth usually gives you
1520: a Gforth command line. Starting the Forth system every time gives you a
1521: clean start every time, without interference from the results of earlier
1522: tries.
1523:
1524: I often put all the tests in a file, then load the code and run the
1525: tests with
1526:
1527: @example
1.102 anton 1528: gforth @var{code.fs} @var{tests.fs} -e bye
1.48 anton 1529: @end example
1530:
1531: (often by performing this command with @kbd{C-x C-e} in Emacs). The
1532: @code{-e bye} ensures that Gforth terminates afterwards so that I can
1533: restart this command without ado.
1534:
1535: The advantage of this approach is that the tests can be repeated easily
1536: every time the program ist changed, making it easy to catch bugs
1537: introduced by the change.
1538:
1.66 anton 1539: Reference: @ref{Forth source files}.
1540:
1.48 anton 1541:
1542: @node Comments Tutorial, Colon Definitions Tutorial, Using files for Forth code Tutorial, Tutorial
1543: @section Comments
1.66 anton 1544: @cindex comments tutorial
1.48 anton 1545:
1546: @example
1547: \ That's a comment; it ends at the end of the line
1548: ( Another comment; it ends here: ) .s
1549: @end example
1550:
1551: @code{\} and @code{(} are ordinary Forth words and therefore have to be
1552: separated with white space from the following text.
1553:
1554: @example
1555: \This gives an "Undefined word" error
1556: @end example
1557:
1558: The first @code{)} ends a comment started with @code{(}, so you cannot
1559: nest @code{(}-comments; and you cannot comment out text containing a
1560: @code{)} with @code{( ... )}@footnote{therefore it's a good idea to
1561: avoid @code{)} in word names.}.
1562:
1563: I use @code{\}-comments for descriptive text and for commenting out code
1564: of one or more line; I use @code{(}-comments for describing the stack
1565: effect, the stack contents, or for commenting out sub-line pieces of
1566: code.
1567:
1568: The Emacs mode @file{gforth.el} (@pxref{Emacs and Gforth}) supports
1569: these uses by commenting out a region with @kbd{C-x \}, uncommenting a
1570: region with @kbd{C-u C-x \}, and filling a @code{\}-commented region
1571: with @kbd{M-q}.
1572:
1.66 anton 1573: Reference: @ref{Comments}.
1574:
1.48 anton 1575:
1576: @node Colon Definitions Tutorial, Decompilation Tutorial, Comments Tutorial, Tutorial
1577: @section Colon Definitions
1.66 anton 1578: @cindex colon definitions, tutorial
1579: @cindex definitions, tutorial
1580: @cindex procedures, tutorial
1581: @cindex functions, tutorial
1.48 anton 1582:
1583: are similar to procedures and functions in other programming languages.
1584:
1585: @example
1586: : squared ( n -- n^2 )
1587: dup * ;
1588: 5 squared .
1589: 7 squared .
1590: @end example
1591:
1592: @code{:} starts the colon definition; its name is @code{squared}. The
1593: following comment describes its stack effect. The words @code{dup *}
1594: are not executed, but compiled into the definition. @code{;} ends the
1595: colon definition.
1596:
1597: The newly-defined word can be used like any other word, including using
1598: it in other definitions:
1599:
1600: @example
1601: : cubed ( n -- n^3 )
1602: dup squared * ;
1603: -5 cubed .
1604: : fourth-power ( n -- n^4 )
1605: squared squared ;
1606: 3 fourth-power .
1607: @end example
1608:
1.141 anton 1609: @quotation Assignment
1.48 anton 1610: Write colon definitions for @code{nip}, @code{tuck}, @code{negate}, and
1611: @code{/mod} in terms of other Forth words, and check if they work (hint:
1612: test your tests on the originals first). Don't let the
1613: @samp{redefined}-Messages spook you, they are just warnings.
1.141 anton 1614: @end quotation
1.48 anton 1615:
1.66 anton 1616: Reference: @ref{Colon Definitions}.
1617:
1.48 anton 1618:
1619: @node Decompilation Tutorial, Stack-Effect Comments Tutorial, Colon Definitions Tutorial, Tutorial
1620: @section Decompilation
1.66 anton 1621: @cindex decompilation tutorial
1622: @cindex see tutorial
1.48 anton 1623:
1624: You can decompile colon definitions with @code{see}:
1625:
1626: @example
1627: see squared
1628: see cubed
1629: @end example
1630:
1631: In Gforth @code{see} shows you a reconstruction of the source code from
1632: the executable code. Informations that were present in the source, but
1633: not in the executable code, are lost (e.g., comments).
1634:
1.65 anton 1635: You can also decompile the predefined words:
1636:
1637: @example
1638: see .
1639: see +
1640: @end example
1641:
1642:
1.48 anton 1643: @node Stack-Effect Comments Tutorial, Types Tutorial, Decompilation Tutorial, Tutorial
1644: @section Stack-Effect Comments
1.66 anton 1645: @cindex stack-effect comments, tutorial
1646: @cindex --, tutorial
1.48 anton 1647: By convention the comment after the name of a definition describes the
1.171 anton 1648: stack effect: The part in front of the @samp{--} describes the state of
1.48 anton 1649: the stack before the execution of the definition, i.e., the parameters
1650: that are passed into the colon definition; the part behind the @samp{--}
1651: is the state of the stack after the execution of the definition, i.e.,
1652: the results of the definition. The stack comment only shows the top
1653: stack items that the definition accesses and/or changes.
1654:
1655: You should put a correct stack effect on every definition, even if it is
1656: just @code{( -- )}. You should also add some descriptive comment to
1657: more complicated words (I usually do this in the lines following
1658: @code{:}). If you don't do this, your code becomes unreadable (because
1.117 anton 1659: you have to work through every definition before you can understand
1.48 anton 1660: any).
1661:
1.141 anton 1662: @quotation Assignment
1.48 anton 1663: The stack effect of @code{swap} can be written like this: @code{x1 x2 --
1664: x2 x1}. Describe the stack effect of @code{-}, @code{drop}, @code{dup},
1665: @code{over}, @code{rot}, @code{nip}, and @code{tuck}. Hint: When you
1.65 anton 1666: are done, you can compare your stack effects to those in this manual
1.48 anton 1667: (@pxref{Word Index}).
1.141 anton 1668: @end quotation
1.48 anton 1669:
1670: Sometimes programmers put comments at various places in colon
1671: definitions that describe the contents of the stack at that place (stack
1672: comments); i.e., they are like the first part of a stack-effect
1673: comment. E.g.,
1674:
1675: @example
1676: : cubed ( n -- n^3 )
1677: dup squared ( n n^2 ) * ;
1678: @end example
1679:
1680: In this case the stack comment is pretty superfluous, because the word
1681: is simple enough. If you think it would be a good idea to add such a
1682: comment to increase readability, you should also consider factoring the
1683: word into several simpler words (@pxref{Factoring Tutorial,,
1.60 anton 1684: Factoring}), which typically eliminates the need for the stack comment;
1.48 anton 1685: however, if you decide not to refactor it, then having such a comment is
1686: better than not having it.
1687:
1688: The names of the stack items in stack-effect and stack comments in the
1689: standard, in this manual, and in many programs specify the type through
1690: a type prefix, similar to Fortran and Hungarian notation. The most
1691: frequent prefixes are:
1692:
1693: @table @code
1694: @item n
1695: signed integer
1696: @item u
1697: unsigned integer
1698: @item c
1699: character
1700: @item f
1701: Boolean flags, i.e. @code{false} or @code{true}.
1702: @item a-addr,a-
1703: Cell-aligned address
1704: @item c-addr,c-
1705: Char-aligned address (note that a Char may have two bytes in Windows NT)
1706: @item xt
1707: Execution token, same size as Cell
1708: @item w,x
1709: Cell, can contain an integer or an address. It usually takes 32, 64 or
1710: 16 bits (depending on your platform and Forth system). A cell is more
1711: commonly known as machine word, but the term @emph{word} already means
1712: something different in Forth.
1713: @item d
1714: signed double-cell integer
1715: @item ud
1716: unsigned double-cell integer
1717: @item r
1718: Float (on the FP stack)
1719: @end table
1720:
1721: You can find a more complete list in @ref{Notation}.
1722:
1.141 anton 1723: @quotation Assignment
1.48 anton 1724: Write stack-effect comments for all definitions you have written up to
1725: now.
1.141 anton 1726: @end quotation
1.48 anton 1727:
1728:
1729: @node Types Tutorial, Factoring Tutorial, Stack-Effect Comments Tutorial, Tutorial
1730: @section Types
1.66 anton 1731: @cindex types tutorial
1.48 anton 1732:
1733: In Forth the names of the operations are not overloaded; so similar
1734: operations on different types need different names; e.g., @code{+} adds
1735: integers, and you have to use @code{f+} to add floating-point numbers.
1736: The following prefixes are often used for related operations on
1737: different types:
1738:
1739: @table @code
1740: @item (none)
1741: signed integer
1742: @item u
1743: unsigned integer
1744: @item c
1745: character
1746: @item d
1747: signed double-cell integer
1748: @item ud, du
1749: unsigned double-cell integer
1750: @item 2
1751: two cells (not-necessarily double-cell numbers)
1752: @item m, um
1753: mixed single-cell and double-cell operations
1754: @item f
1755: floating-point (note that in stack comments @samp{f} represents flags,
1.210 ! anton 1756: and @samp{r} represents FP numbers; also, you need to include the
! 1757: exponent part in literal FP numbers, @pxref{Floating Point Tutorial}).
1.48 anton 1758: @end table
1759:
1760: If there are no differences between the signed and the unsigned variant
1761: (e.g., for @code{+}), there is only the prefix-less variant.
1762:
1763: Forth does not perform type checking, neither at compile time, nor at
1.210 ! anton 1764: run time. If you use the wrong operation, the data are interpreted
1.48 anton 1765: incorrectly:
1766:
1767: @example
1768: -1 u.
1769: @end example
1770:
1771: If you have only experience with type-checked languages until now, and
1772: have heard how important type-checking is, don't panic! In my
1773: experience (and that of other Forthers), type errors in Forth code are
1774: usually easy to find (once you get used to it), the increased vigilance
1775: of the programmer tends to catch some harder errors in addition to most
1776: type errors, and you never have to work around the type system, so in
1777: most situations the lack of type-checking seems to be a win (projects to
1778: add type checking to Forth have not caught on).
1779:
1780:
1781: @node Factoring Tutorial, Designing the stack effect Tutorial, Types Tutorial, Tutorial
1782: @section Factoring
1.66 anton 1783: @cindex factoring tutorial
1.48 anton 1784:
1785: If you try to write longer definitions, you will soon find it hard to
1786: keep track of the stack contents. Therefore, good Forth programmers
1787: tend to write only short definitions (e.g., three lines). The art of
1788: finding meaningful short definitions is known as factoring (as in
1789: factoring polynomials).
1790:
1791: Well-factored programs offer additional advantages: smaller, more
1792: general words, are easier to test and debug and can be reused more and
1793: better than larger, specialized words.
1794:
1795: So, if you run into difficulties with stack management, when writing
1796: code, try to define meaningful factors for the word, and define the word
1797: in terms of those. Even if a factor contains only two words, it is
1798: often helpful.
1799:
1.65 anton 1800: Good factoring is not easy, and it takes some practice to get the knack
1801: for it; but even experienced Forth programmers often don't find the
1802: right solution right away, but only when rewriting the program. So, if
1803: you don't come up with a good solution immediately, keep trying, don't
1804: despair.
1.48 anton 1805:
1806: @c example !!
1807:
1808:
1809: @node Designing the stack effect Tutorial, Local Variables Tutorial, Factoring Tutorial, Tutorial
1810: @section Designing the stack effect
1.66 anton 1811: @cindex Stack effect design, tutorial
1812: @cindex design of stack effects, tutorial
1.48 anton 1813:
1814: In other languages you can use an arbitrary order of parameters for a
1.65 anton 1815: function; and since there is only one result, you don't have to deal with
1.48 anton 1816: the order of results, either.
1817:
1.117 anton 1818: In Forth (and other stack-based languages, e.g., PostScript) the
1.48 anton 1819: parameter and result order of a definition is important and should be
1820: designed well. The general guideline is to design the stack effect such
1821: that the word is simple to use in most cases, even if that complicates
1822: the implementation of the word. Some concrete rules are:
1823:
1824: @itemize @bullet
1825:
1826: @item
1827: Words consume all of their parameters (e.g., @code{.}).
1828:
1829: @item
1830: If there is a convention on the order of parameters (e.g., from
1831: mathematics or another programming language), stick with it (e.g.,
1832: @code{-}).
1833:
1834: @item
1835: If one parameter usually requires only a short computation (e.g., it is
1836: a constant), pass it on the top of the stack. Conversely, parameters
1837: that usually require a long sequence of code to compute should be passed
1838: as the bottom (i.e., first) parameter. This makes the code easier to
1.171 anton 1839: read, because the reader does not need to keep track of the bottom item
1.48 anton 1840: through a long sequence of code (or, alternatively, through stack
1.49 anton 1841: manipulations). E.g., @code{!} (store, @pxref{Memory}) expects the
1.48 anton 1842: address on top of the stack because it is usually simpler to compute
1843: than the stored value (often the address is just a variable).
1844:
1845: @item
1846: Similarly, results that are usually consumed quickly should be returned
1847: on the top of stack, whereas a result that is often used in long
1848: computations should be passed as bottom result. E.g., the file words
1849: like @code{open-file} return the error code on the top of stack, because
1850: it is usually consumed quickly by @code{throw}; moreover, the error code
1851: has to be checked before doing anything with the other results.
1852:
1853: @end itemize
1854:
1855: These rules are just general guidelines, don't lose sight of the overall
1856: goal to make the words easy to use. E.g., if the convention rule
1857: conflicts with the computation-length rule, you might decide in favour
1858: of the convention if the word will be used rarely, and in favour of the
1859: computation-length rule if the word will be used frequently (because
1860: with frequent use the cost of breaking the computation-length rule would
1861: be quite high, and frequent use makes it easier to remember an
1862: unconventional order).
1863:
1864: @c example !! structure package
1865:
1.65 anton 1866:
1.48 anton 1867: @node Local Variables Tutorial, Conditional execution Tutorial, Designing the stack effect Tutorial, Tutorial
1868: @section Local Variables
1.66 anton 1869: @cindex local variables, tutorial
1.48 anton 1870:
1871: You can define local variables (@emph{locals}) in a colon definition:
1872:
1873: @example
1874: : swap @{ a b -- b a @}
1875: b a ;
1876: 1 2 swap .s 2drop
1877: @end example
1878:
1879: (If your Forth system does not support this syntax, include
1.187 anton 1880: @file{compat/anslocal.fs} first).
1.48 anton 1881:
1882: In this example @code{@{ a b -- b a @}} is the locals definition; it
1883: takes two cells from the stack, puts the top of stack in @code{b} and
1884: the next stack element in @code{a}. @code{--} starts a comment ending
1885: with @code{@}}. After the locals definition, using the name of the
1886: local will push its value on the stack. You can leave the comment
1887: part (@code{-- b a}) away:
1888:
1889: @example
1890: : swap ( x1 x2 -- x2 x1 )
1891: @{ a b @} b a ;
1892: @end example
1893:
1894: In Gforth you can have several locals definitions, anywhere in a colon
1895: definition; in contrast, in a standard program you can have only one
1896: locals definition per colon definition, and that locals definition must
1.163 anton 1897: be outside any control structure.
1.48 anton 1898:
1899: With locals you can write slightly longer definitions without running
1900: into stack trouble. However, I recommend trying to write colon
1901: definitions without locals for exercise purposes to help you gain the
1902: essential factoring skills.
1903:
1.141 anton 1904: @quotation Assignment
1.48 anton 1905: Rewrite your definitions until now with locals
1.141 anton 1906: @end quotation
1.48 anton 1907:
1.66 anton 1908: Reference: @ref{Locals}.
1909:
1.48 anton 1910:
1911: @node Conditional execution Tutorial, Flags and Comparisons Tutorial, Local Variables Tutorial, Tutorial
1912: @section Conditional execution
1.66 anton 1913: @cindex conditionals, tutorial
1914: @cindex if, tutorial
1.48 anton 1915:
1916: In Forth you can use control structures only inside colon definitions.
1917: An @code{if}-structure looks like this:
1918:
1919: @example
1920: : abs ( n1 -- +n2 )
1921: dup 0 < if
1922: negate
1923: endif ;
1924: 5 abs .
1925: -5 abs .
1926: @end example
1927:
1928: @code{if} takes a flag from the stack. If the flag is non-zero (true),
1929: the following code is performed, otherwise execution continues after the
1.51 pazsan 1930: @code{endif} (or @code{else}). @code{<} compares the top two stack
1.171 anton 1931: elements and produces a flag:
1.48 anton 1932:
1933: @example
1934: 1 2 < .
1935: 2 1 < .
1936: 1 1 < .
1937: @end example
1938:
1939: Actually the standard name for @code{endif} is @code{then}. This
1940: tutorial presents the examples using @code{endif}, because this is often
1941: less confusing for people familiar with other programming languages
1942: where @code{then} has a different meaning. If your system does not have
1943: @code{endif}, define it with
1944:
1945: @example
1946: : endif postpone then ; immediate
1947: @end example
1948:
1949: You can optionally use an @code{else}-part:
1950:
1951: @example
1952: : min ( n1 n2 -- n )
1953: 2dup < if
1954: drop
1955: else
1956: nip
1957: endif ;
1958: 2 3 min .
1959: 3 2 min .
1960: @end example
1961:
1.141 anton 1962: @quotation Assignment
1.48 anton 1963: Write @code{min} without @code{else}-part (hint: what's the definition
1964: of @code{nip}?).
1.141 anton 1965: @end quotation
1.48 anton 1966:
1.66 anton 1967: Reference: @ref{Selection}.
1968:
1.48 anton 1969:
1970: @node Flags and Comparisons Tutorial, General Loops Tutorial, Conditional execution Tutorial, Tutorial
1971: @section Flags and Comparisons
1.66 anton 1972: @cindex flags tutorial
1973: @cindex comparison tutorial
1.48 anton 1974:
1975: In a false-flag all bits are clear (0 when interpreted as integer). In
1976: a canonical true-flag all bits are set (-1 as a twos-complement signed
1977: integer); in many contexts (e.g., @code{if}) any non-zero value is
1978: treated as true flag.
1979:
1980: @example
1981: false .
1982: true .
1983: true hex u. decimal
1984: @end example
1985:
1986: Comparison words produce canonical flags:
1987:
1988: @example
1989: 1 1 = .
1990: 1 0= .
1991: 0 1 < .
1992: 0 0 < .
1993: -1 1 u< . \ type error, u< interprets -1 as large unsigned number
1994: -1 1 < .
1995: @end example
1996:
1.66 anton 1997: Gforth supports all combinations of the prefixes @code{0 u d d0 du f f0}
1998: (or none) and the comparisons @code{= <> < > <= >=}. Only a part of
1999: these combinations are standard (for details see the standard,
2000: @ref{Numeric comparison}, @ref{Floating Point} or @ref{Word Index}).
1.48 anton 2001:
1.171 anton 2002: You can use @code{and or xor invert} as operations on canonical flags.
2003: Actually they are bitwise operations:
1.48 anton 2004:
2005: @example
2006: 1 2 and .
2007: 1 2 or .
2008: 1 3 xor .
2009: 1 invert .
2010: @end example
2011:
2012: You can convert a zero/non-zero flag into a canonical flag with
2013: @code{0<>} (and complement it on the way with @code{0=}).
2014:
2015: @example
2016: 1 0= .
2017: 1 0<> .
2018: @end example
2019:
1.65 anton 2020: You can use the all-bits-set feature of canonical flags and the bitwise
1.48 anton 2021: operation of the Boolean operations to avoid @code{if}s:
2022:
2023: @example
2024: : foo ( n1 -- n2 )
2025: 0= if
2026: 14
2027: else
2028: 0
2029: endif ;
2030: 0 foo .
2031: 1 foo .
2032:
2033: : foo ( n1 -- n2 )
2034: 0= 14 and ;
2035: 0 foo .
2036: 1 foo .
2037: @end example
2038:
1.141 anton 2039: @quotation Assignment
1.48 anton 2040: Write @code{min} without @code{if}.
1.141 anton 2041: @end quotation
1.48 anton 2042:
1.66 anton 2043: For reference, see @ref{Boolean Flags}, @ref{Numeric comparison}, and
2044: @ref{Bitwise operations}.
2045:
1.48 anton 2046:
2047: @node General Loops Tutorial, Counted loops Tutorial, Flags and Comparisons Tutorial, Tutorial
2048: @section General Loops
1.66 anton 2049: @cindex loops, indefinite, tutorial
1.48 anton 2050:
2051: The endless loop is the most simple one:
2052:
2053: @example
2054: : endless ( -- )
2055: 0 begin
2056: dup . 1+
2057: again ;
2058: endless
2059: @end example
2060:
2061: Terminate this loop by pressing @kbd{Ctrl-C} (in Gforth). @code{begin}
2062: does nothing at run-time, @code{again} jumps back to @code{begin}.
2063:
2064: A loop with one exit at any place looks like this:
2065:
2066: @example
2067: : log2 ( +n1 -- n2 )
2068: \ logarithmus dualis of n1>0, rounded down to the next integer
2069: assert( dup 0> )
2070: 2/ 0 begin
2071: over 0> while
2072: 1+ swap 2/ swap
2073: repeat
2074: nip ;
2075: 7 log2 .
2076: 8 log2 .
2077: @end example
2078:
2079: At run-time @code{while} consumes a flag; if it is 0, execution
1.51 pazsan 2080: continues behind the @code{repeat}; if the flag is non-zero, execution
1.48 anton 2081: continues behind the @code{while}. @code{Repeat} jumps back to
2082: @code{begin}, just like @code{again}.
2083:
2084: In Forth there are many combinations/abbreviations, like @code{1+}.
1.90 anton 2085: However, @code{2/} is not one of them; it shifts its argument right by
1.48 anton 2086: one bit (arithmetic shift right):
2087:
2088: @example
2089: -5 2 / .
2090: -5 2/ .
2091: @end example
2092:
2093: @code{assert(} is no standard word, but you can get it on systems other
1.198 anton 2094: than Gforth by including @file{compat/assert.fs}. You can see what it
1.48 anton 2095: does by trying
2096:
2097: @example
2098: 0 log2 .
2099: @end example
2100:
2101: Here's a loop with an exit at the end:
2102:
2103: @example
2104: : log2 ( +n1 -- n2 )
2105: \ logarithmus dualis of n1>0, rounded down to the next integer
2106: assert( dup 0 > )
2107: -1 begin
2108: 1+ swap 2/ swap
2109: over 0 <=
2110: until
2111: nip ;
2112: @end example
2113:
2114: @code{Until} consumes a flag; if it is non-zero, execution continues at
2115: the @code{begin}, otherwise after the @code{until}.
2116:
1.141 anton 2117: @quotation Assignment
1.48 anton 2118: Write a definition for computing the greatest common divisor.
1.141 anton 2119: @end quotation
1.48 anton 2120:
1.66 anton 2121: Reference: @ref{Simple Loops}.
2122:
1.48 anton 2123:
2124: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2125: @section Counted loops
1.66 anton 2126: @cindex loops, counted, tutorial
1.48 anton 2127:
2128: @example
2129: : ^ ( n1 u -- n )
1.171 anton 2130: \ n = the uth power of n1
1.48 anton 2131: 1 swap 0 u+do
2132: over *
2133: loop
2134: nip ;
2135: 3 2 ^ .
2136: 4 3 ^ .
2137: @end example
2138:
2139: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2140: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2141: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2142: times (or not at all, if @code{u3-u4<0}).
2143:
2144: You can see the stack effect design rules at work in the stack effect of
2145: the loop start words: Since the start value of the loop is more
2146: frequently constant than the end value, the start value is passed on
2147: the top-of-stack.
2148:
2149: You can access the counter of a counted loop with @code{i}:
2150:
2151: @example
2152: : fac ( u -- u! )
2153: 1 swap 1+ 1 u+do
2154: i *
2155: loop ;
2156: 5 fac .
2157: 7 fac .
2158: @end example
2159:
2160: There is also @code{+do}, which expects signed numbers (important for
2161: deciding whether to enter the loop).
2162:
1.141 anton 2163: @quotation Assignment
1.48 anton 2164: Write a definition for computing the nth Fibonacci number.
1.141 anton 2165: @end quotation
1.48 anton 2166:
1.65 anton 2167: You can also use increments other than 1:
2168:
2169: @example
2170: : up2 ( n1 n2 -- )
2171: +do
2172: i .
2173: 2 +loop ;
2174: 10 0 up2
2175:
2176: : down2 ( n1 n2 -- )
2177: -do
2178: i .
2179: 2 -loop ;
2180: 0 10 down2
2181: @end example
1.48 anton 2182:
1.66 anton 2183: Reference: @ref{Counted Loops}.
2184:
1.48 anton 2185:
2186: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2187: @section Recursion
1.66 anton 2188: @cindex recursion tutorial
1.48 anton 2189:
2190: Usually the name of a definition is not visible in the definition; but
2191: earlier definitions are usually visible:
2192:
2193: @example
1.166 anton 2194: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2195: : / ( n1 n2 -- n )
2196: dup 0= if
2197: -10 throw \ report division by zero
2198: endif
2199: / \ old version
2200: ;
2201: 1 0 /
2202: @end example
2203:
2204: For recursive definitions you can use @code{recursive} (non-standard) or
2205: @code{recurse}:
2206:
2207: @example
2208: : fac1 ( n -- n! ) recursive
2209: dup 0> if
2210: dup 1- fac1 *
2211: else
2212: drop 1
2213: endif ;
2214: 7 fac1 .
2215:
2216: : fac2 ( n -- n! )
2217: dup 0> if
2218: dup 1- recurse *
2219: else
2220: drop 1
2221: endif ;
2222: 8 fac2 .
2223: @end example
2224:
1.141 anton 2225: @quotation Assignment
1.48 anton 2226: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2227: @end quotation
1.48 anton 2228:
1.66 anton 2229: Reference (including indirect recursion): @xref{Calls and returns}.
2230:
1.48 anton 2231:
2232: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2233: @section Leaving definitions or loops
1.66 anton 2234: @cindex leaving definitions, tutorial
2235: @cindex leaving loops, tutorial
1.48 anton 2236:
2237: @code{EXIT} exits the current definition right away. For every counted
2238: loop that is left in this way, an @code{UNLOOP} has to be performed
2239: before the @code{EXIT}:
2240:
2241: @c !! real examples
2242: @example
2243: : ...
2244: ... u+do
2245: ... if
2246: ... unloop exit
2247: endif
2248: ...
2249: loop
2250: ... ;
2251: @end example
2252:
2253: @code{LEAVE} leaves the innermost counted loop right away:
2254:
2255: @example
2256: : ...
2257: ... u+do
2258: ... if
2259: ... leave
2260: endif
2261: ...
2262: loop
2263: ... ;
2264: @end example
2265:
1.65 anton 2266: @c !! example
1.48 anton 2267:
1.66 anton 2268: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2269:
2270:
1.48 anton 2271: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2272: @section Return Stack
1.66 anton 2273: @cindex return stack tutorial
1.48 anton 2274:
2275: In addition to the data stack Forth also has a second stack, the return
2276: stack; most Forth systems store the return addresses of procedure calls
2277: there (thus its name). Programmers can also use this stack:
2278:
2279: @example
2280: : foo ( n1 n2 -- )
2281: .s
2282: >r .s
1.50 anton 2283: r@@ .
1.48 anton 2284: >r .s
1.50 anton 2285: r@@ .
1.48 anton 2286: r> .
1.50 anton 2287: r@@ .
1.48 anton 2288: r> . ;
2289: 1 2 foo
2290: @end example
2291:
2292: @code{>r} takes an element from the data stack and pushes it onto the
2293: return stack; conversely, @code{r>} moves an elementm from the return to
2294: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2295: on the data stack.
1.48 anton 2296:
2297: Forth programmers usually use the return stack for storing data
2298: temporarily, if using the data stack alone would be too complex, and
2299: factoring and locals are not an option:
2300:
2301: @example
2302: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2303: rot >r rot r> ;
2304: @end example
2305:
2306: The return address of the definition and the loop control parameters of
2307: counted loops usually reside on the return stack, so you have to take
2308: all items, that you have pushed on the return stack in a colon
2309: definition or counted loop, from the return stack before the definition
2310: or loop ends. You cannot access items that you pushed on the return
2311: stack outside some definition or loop within the definition of loop.
2312:
2313: If you miscount the return stack items, this usually ends in a crash:
2314:
2315: @example
2316: : crash ( n -- )
2317: >r ;
2318: 5 crash
2319: @end example
2320:
2321: You cannot mix using locals and using the return stack (according to the
2322: standard; Gforth has no problem). However, they solve the same
2323: problems, so this shouldn't be an issue.
2324:
1.141 anton 2325: @quotation Assignment
1.48 anton 2326: Can you rewrite any of the definitions you wrote until now in a better
2327: way using the return stack?
1.141 anton 2328: @end quotation
1.48 anton 2329:
1.66 anton 2330: Reference: @ref{Return stack}.
2331:
1.48 anton 2332:
2333: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2334: @section Memory
1.66 anton 2335: @cindex memory access/allocation tutorial
1.48 anton 2336:
2337: You can create a global variable @code{v} with
2338:
2339: @example
2340: variable v ( -- addr )
2341: @end example
2342:
2343: @code{v} pushes the address of a cell in memory on the stack. This cell
2344: was reserved by @code{variable}. You can use @code{!} (store) to store
2345: values into this cell and @code{@@} (fetch) to load the value from the
2346: stack into memory:
2347:
2348: @example
2349: v .
2350: 5 v ! .s
1.50 anton 2351: v @@ .
1.48 anton 2352: @end example
2353:
1.65 anton 2354: You can see a raw dump of memory with @code{dump}:
2355:
2356: @example
2357: v 1 cells .s dump
2358: @end example
2359:
2360: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2361: generally, address units (aus)) that @code{n1 cells} occupy. You can
2362: also reserve more memory:
1.48 anton 2363:
2364: @example
2365: create v2 20 cells allot
1.65 anton 2366: v2 20 cells dump
1.48 anton 2367: @end example
2368:
1.65 anton 2369: creates a word @code{v2} and reserves 20 uninitialized cells; the
2370: address pushed by @code{v2} points to the start of these 20 cells. You
2371: can use address arithmetic to access these cells:
1.48 anton 2372:
2373: @example
2374: 3 v2 5 cells + !
1.65 anton 2375: v2 20 cells dump
1.48 anton 2376: @end example
2377:
2378: You can reserve and initialize memory with @code{,}:
2379:
2380: @example
2381: create v3
2382: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2383: v3 @@ .
2384: v3 cell+ @@ .
2385: v3 2 cells + @@ .
1.65 anton 2386: v3 5 cells dump
1.48 anton 2387: @end example
2388:
1.141 anton 2389: @quotation Assignment
1.48 anton 2390: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2391: @code{u} cells, with the first of these cells at @code{addr}, the next
2392: one at @code{addr cell+} etc.
1.141 anton 2393: @end quotation
1.48 anton 2394:
2395: You can also reserve memory without creating a new word:
2396:
2397: @example
1.60 anton 2398: here 10 cells allot .
2399: here .
1.48 anton 2400: @end example
2401:
2402: @code{Here} pushes the start address of the memory area. You should
2403: store it somewhere, or you will have a hard time finding the memory area
2404: again.
2405:
2406: @code{Allot} manages dictionary memory. The dictionary memory contains
2407: the system's data structures for words etc. on Gforth and most other
2408: Forth systems. It is managed like a stack: You can free the memory that
2409: you have just @code{allot}ed with
2410:
2411: @example
2412: -10 cells allot
1.60 anton 2413: here .
1.48 anton 2414: @end example
2415:
2416: Note that you cannot do this if you have created a new word in the
2417: meantime (because then your @code{allot}ed memory is no longer on the
2418: top of the dictionary ``stack'').
2419:
2420: Alternatively, you can use @code{allocate} and @code{free} which allow
2421: freeing memory in any order:
2422:
2423: @example
2424: 10 cells allocate throw .s
2425: 20 cells allocate throw .s
2426: swap
2427: free throw
2428: free throw
2429: @end example
2430:
2431: The @code{throw}s deal with errors (e.g., out of memory).
2432:
1.65 anton 2433: And there is also a
2434: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2435: garbage collector}, which eliminates the need to @code{free} memory
2436: explicitly.
1.48 anton 2437:
1.66 anton 2438: Reference: @ref{Memory}.
2439:
1.48 anton 2440:
2441: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2442: @section Characters and Strings
1.66 anton 2443: @cindex strings tutorial
2444: @cindex characters tutorial
1.48 anton 2445:
2446: On the stack characters take up a cell, like numbers. In memory they
2447: have their own size (one 8-bit byte on most systems), and therefore
2448: require their own words for memory access:
2449:
2450: @example
2451: create v4
2452: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2453: v4 4 chars + c@@ .
1.65 anton 2454: v4 5 chars dump
1.48 anton 2455: @end example
2456:
2457: The preferred representation of strings on the stack is @code{addr
2458: u-count}, where @code{addr} is the address of the first character and
2459: @code{u-count} is the number of characters in the string.
2460:
2461: @example
2462: v4 5 type
2463: @end example
2464:
2465: You get a string constant with
2466:
2467: @example
2468: s" hello, world" .s
2469: type
2470: @end example
2471:
2472: Make sure you have a space between @code{s"} and the string; @code{s"}
2473: is a normal Forth word and must be delimited with white space (try what
2474: happens when you remove the space).
2475:
2476: However, this interpretive use of @code{s"} is quite restricted: the
2477: string exists only until the next call of @code{s"} (some Forth systems
2478: keep more than one of these strings, but usually they still have a
1.62 crook 2479: limited lifetime).
1.48 anton 2480:
2481: @example
2482: s" hello," s" world" .s
2483: type
2484: type
2485: @end example
2486:
1.62 crook 2487: You can also use @code{s"} in a definition, and the resulting
2488: strings then live forever (well, for as long as the definition):
1.48 anton 2489:
2490: @example
2491: : foo s" hello," s" world" ;
2492: foo .s
2493: type
2494: type
2495: @end example
2496:
1.141 anton 2497: @quotation Assignment
1.48 anton 2498: @code{Emit ( c -- )} types @code{c} as character (not a number).
2499: Implement @code{type ( addr u -- )}.
1.141 anton 2500: @end quotation
1.48 anton 2501:
1.66 anton 2502: Reference: @ref{Memory Blocks}.
2503:
2504:
1.190 anton 2505: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2506: @section Alignment
1.66 anton 2507: @cindex alignment tutorial
2508: @cindex memory alignment tutorial
1.48 anton 2509:
2510: On many processors cells have to be aligned in memory, if you want to
2511: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2512: not require alignment, access to aligned cells is faster).
1.48 anton 2513:
2514: @code{Create} aligns @code{here} (i.e., the place where the next
2515: allocation will occur, and that the @code{create}d word points to).
2516: Likewise, the memory produced by @code{allocate} starts at an aligned
2517: address. Adding a number of @code{cells} to an aligned address produces
2518: another aligned address.
2519:
2520: However, address arithmetic involving @code{char+} and @code{chars} can
2521: create an address that is not cell-aligned. @code{Aligned ( addr --
2522: a-addr )} produces the next aligned address:
2523:
2524: @example
1.50 anton 2525: v3 char+ aligned .s @@ .
2526: v3 char+ .s @@ .
1.48 anton 2527: @end example
2528:
2529: Similarly, @code{align} advances @code{here} to the next aligned
2530: address:
2531:
2532: @example
2533: create v5 97 c,
2534: here .
2535: align here .
2536: 1000 ,
2537: @end example
2538:
2539: Note that you should use aligned addresses even if your processor does
2540: not require them, if you want your program to be portable.
2541:
1.66 anton 2542: Reference: @ref{Address arithmetic}.
2543:
1.190 anton 2544: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2545: @section Floating Point
2546: @cindex floating point tutorial
2547: @cindex FP tutorial
2548:
2549: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2550: might expect, but there are a few things worth noting:
2551:
2552: The first point is not specific to Forth, but so important and yet not
2553: universally known that I mention it here: FP numbers are not reals.
2554: Many properties (e.g., arithmetic laws) that reals have and that one
2555: expects of all kinds of numbers do not hold for FP numbers. If you
2556: want to use FP computations, you should learn about their problems and
2557: how to avoid them; a good starting point is @cite{David Goldberg,
2558: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2559: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2560: Computing Surveys 23(1):5@minus{}48, March 1991}.
2561:
2562: In Forth source code literal FP numbers need an exponent, e.g.,
1.210 ! anton 2563: @code{1e0}; this can also be written shorter as @code{1e}, longer as
! 2564: @code{+1.0e+0}, and many variations in between. The reason for this is
! 2565: that, for historical reasons, Forth interprets a decimal point alone
! 2566: (e.g., @code{1.}) as indicating a double-cell integer. Examples:
! 2567:
! 2568: @example
! 2569: 2e 2e f+ f.
! 2570: @end example
! 2571:
! 2572: Another requirement for literal FP numbers is that the current base is
1.190 anton 2573: decimal; with a hex base @code{1e} is interpreted as an integer.
2574:
2575: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2576: ANS Forth system may implement the FP stack on the data stack, but
2577: virtually all systems implement a separate FP stack; and programming
2578: in a way that accommodates all models is so cumbersome that nobody
2579: does it.} One advantage of this model is that cells are not in the
2580: way when accessing FP values, and vice versa. Forth has a set of
2581: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2582: frot} and (non-standard) @code{fnip ftuck fpick}.
2583:
2584: FP arithmetic words are prefixed with @code{F}. There is the usual
2585: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2586: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2587: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2588: computation results are usually inaccurate, so exact comparison is
2589: usually a mistake, and one should use approximate comparison.
2590: Unfortunately, @code{f~}, the standard word for that purpose, is not
2591: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2592: well.
2593:
2594: And of course there are words for accessing FP numbers in memory
2595: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2596: faligned}). There are also variants of these words with an @code{sf}
2597: and @code{df} prefix for accessing IEEE format single-precision and
2598: double-precision numbers in memory; their main purpose is for
2599: accessing external FP data (e.g., that has been read from or will be
2600: written to a file).
2601:
2602: Here is an example of a dot-product word and its use:
2603:
2604: @example
2605: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2606: >r swap 2swap swap 0e r> 0 ?DO
2607: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2608: LOOP
2609: 2drop 2drop ;
1.48 anton 2610:
1.190 anton 2611: create v 1.23e f, 4.56e f, 7.89e f,
2612:
2613: v 1 floats v 1 floats 3 v* f.
2614: @end example
2615:
2616: @quotation Assignment
2617: Write a program to solve a quadratic equation. Then read @cite{Henry
2618: G. Baker,
2619: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2620: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2621: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2622: program. Finally, find a test case where the original and the
2623: improved version produce different results.
2624: @end quotation
2625:
2626: Reference: @ref{Floating Point}; @ref{Floating point stack};
2627: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2628: arithmetic}.
2629:
2630: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2631: @section Files
2632: @cindex files tutorial
2633:
2634: This section gives a short introduction into how to use files inside
2635: Forth. It's broken up into five easy steps:
2636:
2637: @enumerate 1
2638: @item Opened an ASCII text file for input
2639: @item Opened a file for output
2640: @item Read input file until string matched (or some other condition matched)
2641: @item Wrote some lines from input ( modified or not) to output
2642: @item Closed the files.
2643: @end enumerate
2644:
1.153 anton 2645: Reference: @ref{General files}.
2646:
1.84 pazsan 2647: @subsection Open file for input
2648:
2649: @example
2650: s" foo.in" r/o open-file throw Value fd-in
2651: @end example
2652:
2653: @subsection Create file for output
2654:
2655: @example
2656: s" foo.out" w/o create-file throw Value fd-out
2657: @end example
2658:
2659: The available file modes are r/o for read-only access, r/w for
2660: read-write access, and w/o for write-only access. You could open both
2661: files with r/w, too, if you like. All file words return error codes; for
2662: most applications, it's best to pass there error codes with @code{throw}
2663: to the outer error handler.
2664:
2665: If you want words for opening and assigning, define them as follows:
2666:
2667: @example
2668: 0 Value fd-in
2669: 0 Value fd-out
2670: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2671: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2672: @end example
2673:
2674: Usage example:
2675:
2676: @example
2677: s" foo.in" open-input
2678: s" foo.out" open-output
2679: @end example
2680:
2681: @subsection Scan file for a particular line
2682:
2683: @example
2684: 256 Constant max-line
2685: Create line-buffer max-line 2 + allot
2686:
2687: : scan-file ( addr u -- )
2688: begin
2689: line-buffer max-line fd-in read-line throw
2690: while
2691: >r 2dup line-buffer r> compare 0=
2692: until
2693: else
2694: drop
2695: then
2696: 2drop ;
2697: @end example
2698:
2699: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2700: the buffer at addr, and returns the number of bytes read, a flag that is
2701: false when the end of file is reached, and an error code.
1.84 pazsan 2702:
2703: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2704: returns zero if both strings are equal. It returns a positive number if
2705: the first string is lexically greater, a negative if the second string
2706: is lexically greater.
2707:
2708: We haven't seen this loop here; it has two exits. Since the @code{while}
2709: exits with the number of bytes read on the stack, we have to clean up
2710: that separately; that's after the @code{else}.
2711:
2712: Usage example:
2713:
2714: @example
2715: s" The text I search is here" scan-file
2716: @end example
2717:
2718: @subsection Copy input to output
2719:
2720: @example
2721: : copy-file ( -- )
2722: begin
2723: line-buffer max-line fd-in read-line throw
2724: while
1.194 anton 2725: line-buffer swap fd-out write-line throw
1.84 pazsan 2726: repeat ;
2727: @end example
1.194 anton 2728: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2729:
2730: @subsection Close files
2731:
2732: @example
2733: fd-in close-file throw
2734: fd-out close-file throw
2735: @end example
2736:
2737: Likewise, you can put that into definitions, too:
2738:
2739: @example
2740: : close-input ( -- ) fd-in close-file throw ;
2741: : close-output ( -- ) fd-out close-file throw ;
2742: @end example
2743:
1.141 anton 2744: @quotation Assignment
1.84 pazsan 2745: How could you modify @code{copy-file} so that it copies until a second line is
2746: matched? Can you write a program that extracts a section of a text file,
2747: given the line that starts and the line that terminates that section?
1.141 anton 2748: @end quotation
1.84 pazsan 2749:
2750: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2751: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2752: @cindex semantics tutorial
2753: @cindex interpretation semantics tutorial
2754: @cindex compilation semantics tutorial
2755: @cindex immediate, tutorial
1.48 anton 2756:
2757: When a word is compiled, it behaves differently from being interpreted.
2758: E.g., consider @code{+}:
2759:
2760: @example
2761: 1 2 + .
2762: : foo + ;
2763: @end example
2764:
2765: These two behaviours are known as compilation and interpretation
2766: semantics. For normal words (e.g., @code{+}), the compilation semantics
2767: is to append the interpretation semantics to the currently defined word
2768: (@code{foo} in the example above). I.e., when @code{foo} is executed
2769: later, the interpretation semantics of @code{+} (i.e., adding two
2770: numbers) will be performed.
2771:
2772: However, there are words with non-default compilation semantics, e.g.,
2773: the control-flow words like @code{if}. You can use @code{immediate} to
2774: change the compilation semantics of the last defined word to be equal to
2775: the interpretation semantics:
2776:
2777: @example
2778: : [FOO] ( -- )
2779: 5 . ; immediate
2780:
2781: [FOO]
2782: : bar ( -- )
2783: [FOO] ;
2784: bar
2785: see bar
2786: @end example
2787:
1.198 anton 2788: Two conventions to mark words with non-default compilation semantics are
1.48 anton 2789: names with brackets (more frequently used) and to write them all in
2790: upper case (less frequently used).
2791:
2792: In Gforth (and many other systems) you can also remove the
2793: interpretation semantics with @code{compile-only} (the compilation
2794: semantics is derived from the original interpretation semantics):
2795:
2796: @example
2797: : flip ( -- )
2798: 6 . ; compile-only \ but not immediate
2799: flip
2800:
2801: : flop ( -- )
2802: flip ;
2803: flop
2804: @end example
2805:
2806: In this example the interpretation semantics of @code{flop} is equal to
2807: the original interpretation semantics of @code{flip}.
2808:
2809: The text interpreter has two states: in interpret state, it performs the
2810: interpretation semantics of words it encounters; in compile state, it
2811: performs the compilation semantics of these words.
2812:
2813: Among other things, @code{:} switches into compile state, and @code{;}
2814: switches back to interpret state. They contain the factors @code{]}
2815: (switch to compile state) and @code{[} (switch to interpret state), that
2816: do nothing but switch the state.
2817:
2818: @example
2819: : xxx ( -- )
2820: [ 5 . ]
2821: ;
2822:
2823: xxx
2824: see xxx
2825: @end example
2826:
2827: These brackets are also the source of the naming convention mentioned
2828: above.
2829:
1.66 anton 2830: Reference: @ref{Interpretation and Compilation Semantics}.
2831:
1.48 anton 2832:
2833: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2834: @section Execution Tokens
1.66 anton 2835: @cindex execution tokens tutorial
2836: @cindex XT tutorial
1.48 anton 2837:
2838: @code{' word} gives you the execution token (XT) of a word. The XT is a
2839: cell representing the interpretation semantics of a word. You can
2840: execute this semantics with @code{execute}:
2841:
2842: @example
2843: ' + .s
2844: 1 2 rot execute .
2845: @end example
2846:
2847: The XT is similar to a function pointer in C. However, parameter
2848: passing through the stack makes it a little more flexible:
2849:
2850: @example
2851: : map-array ( ... addr u xt -- ... )
1.50 anton 2852: \ executes xt ( ... x -- ... ) for every element of the array starting
2853: \ at addr and containing u elements
1.48 anton 2854: @{ xt @}
2855: cells over + swap ?do
1.50 anton 2856: i @@ xt execute
1.48 anton 2857: 1 cells +loop ;
2858:
2859: create a 3 , 4 , 2 , -1 , 4 ,
2860: a 5 ' . map-array .s
2861: 0 a 5 ' + map-array .
2862: s" max-n" environment? drop .s
2863: a 5 ' min map-array .
2864: @end example
2865:
2866: You can use map-array with the XTs of words that consume one element
2867: more than they produce. In theory you can also use it with other XTs,
2868: but the stack effect then depends on the size of the array, which is
2869: hard to understand.
2870:
1.51 pazsan 2871: Since XTs are cell-sized, you can store them in memory and manipulate
2872: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2873: word with @code{compile,}:
2874:
2875: @example
2876: : foo1 ( n1 n2 -- n )
2877: [ ' + compile, ] ;
2878: see foo
2879: @end example
2880:
2881: This is non-standard, because @code{compile,} has no compilation
2882: semantics in the standard, but it works in good Forth systems. For the
2883: broken ones, use
2884:
2885: @example
2886: : [compile,] compile, ; immediate
2887:
2888: : foo1 ( n1 n2 -- n )
2889: [ ' + ] [compile,] ;
2890: see foo
2891: @end example
2892:
2893: @code{'} is a word with default compilation semantics; it parses the
2894: next word when its interpretation semantics are executed, not during
2895: compilation:
2896:
2897: @example
2898: : foo ( -- xt )
2899: ' ;
2900: see foo
2901: : bar ( ... "word" -- ... )
2902: ' execute ;
2903: see bar
1.60 anton 2904: 1 2 bar + .
1.48 anton 2905: @end example
2906:
2907: You often want to parse a word during compilation and compile its XT so
2908: it will be pushed on the stack at run-time. @code{[']} does this:
2909:
2910: @example
2911: : xt-+ ( -- xt )
2912: ['] + ;
2913: see xt-+
2914: 1 2 xt-+ execute .
2915: @end example
2916:
2917: Many programmers tend to see @code{'} and the word it parses as one
2918: unit, and expect it to behave like @code{[']} when compiled, and are
2919: confused by the actual behaviour. If you are, just remember that the
2920: Forth system just takes @code{'} as one unit and has no idea that it is
2921: a parsing word (attempts to convenience programmers in this issue have
2922: usually resulted in even worse pitfalls, see
1.66 anton 2923: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2924: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2925:
2926: Note that the state of the interpreter does not come into play when
1.51 pazsan 2927: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2928: compile state, it still gives you the interpretation semantics. And
2929: whatever that state is, @code{execute} performs the semantics
1.66 anton 2930: represented by the XT (i.e., for XTs produced with @code{'} the
2931: interpretation semantics).
2932:
2933: Reference: @ref{Tokens for Words}.
1.48 anton 2934:
2935:
2936: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2937: @section Exceptions
1.66 anton 2938: @cindex exceptions tutorial
1.48 anton 2939:
2940: @code{throw ( n -- )} causes an exception unless n is zero.
2941:
2942: @example
2943: 100 throw .s
2944: 0 throw .s
2945: @end example
2946:
2947: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2948: it catches exceptions and pushes the number of the exception on the
2949: stack (or 0, if the xt executed without exception). If there was an
2950: exception, the stacks have the same depth as when entering @code{catch}:
2951:
2952: @example
2953: .s
2954: 3 0 ' / catch .s
2955: 3 2 ' / catch .s
2956: @end example
2957:
1.141 anton 2958: @quotation Assignment
1.48 anton 2959: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2960: @end quotation
1.48 anton 2961:
2962: @code{Throw} always jumps to the dynamically next enclosing
2963: @code{catch}, even if it has to leave several call levels to achieve
2964: this:
2965:
2966: @example
2967: : foo 100 throw ;
2968: : foo1 foo ." after foo" ;
1.51 pazsan 2969: : bar ['] foo1 catch ;
1.60 anton 2970: bar .
1.48 anton 2971: @end example
2972:
2973: It is often important to restore a value upon leaving a definition, even
2974: if the definition is left through an exception. You can ensure this
2975: like this:
2976:
2977: @example
2978: : ...
2979: save-x
1.51 pazsan 2980: ['] word-changing-x catch ( ... n )
1.48 anton 2981: restore-x
2982: ( ... n ) throw ;
2983: @end example
2984:
1.172 anton 2985: However, this is still not safe against, e.g., the user pressing
2986: @kbd{Ctrl-C} when execution is between the @code{catch} and
2987: @code{restore-x}.
2988:
2989: Gforth provides an alternative exception handling syntax that is safe
2990: against such cases: @code{try ... restore ... endtry}. If the code
2991: between @code{try} and @code{endtry} has an exception, the stack
2992: depths are restored, the exception number is pushed on the stack, and
2993: the execution continues right after @code{restore}.
1.48 anton 2994:
1.172 anton 2995: The safer equivalent to the restoration code above is
1.48 anton 2996:
2997: @example
2998: : ...
2999: save-x
3000: try
1.92 anton 3001: word-changing-x 0
1.172 anton 3002: restore
3003: restore-x
3004: endtry
1.48 anton 3005: throw ;
3006: @end example
3007:
1.66 anton 3008: Reference: @ref{Exception Handling}.
3009:
1.48 anton 3010:
3011: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3012: @section Defining Words
1.66 anton 3013: @cindex defining words tutorial
3014: @cindex does> tutorial
3015: @cindex create...does> tutorial
3016:
3017: @c before semantics?
1.48 anton 3018:
3019: @code{:}, @code{create}, and @code{variable} are definition words: They
3020: define other words. @code{Constant} is another definition word:
3021:
3022: @example
3023: 5 constant foo
3024: foo .
3025: @end example
3026:
3027: You can also use the prefixes @code{2} (double-cell) and @code{f}
3028: (floating point) with @code{variable} and @code{constant}.
3029:
3030: You can also define your own defining words. E.g.:
3031:
3032: @example
3033: : variable ( "name" -- )
3034: create 0 , ;
3035: @end example
3036:
3037: You can also define defining words that create words that do something
3038: other than just producing their address:
3039:
3040: @example
3041: : constant ( n "name" -- )
3042: create ,
3043: does> ( -- n )
1.50 anton 3044: ( addr ) @@ ;
1.48 anton 3045:
3046: 5 constant foo
3047: foo .
3048: @end example
3049:
3050: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3051: @code{does>} replaces @code{;}, but it also does something else: It
3052: changes the last defined word such that it pushes the address of the
3053: body of the word and then performs the code after the @code{does>}
3054: whenever it is called.
3055:
3056: In the example above, @code{constant} uses @code{,} to store 5 into the
3057: body of @code{foo}. When @code{foo} executes, it pushes the address of
3058: the body onto the stack, then (in the code after the @code{does>})
3059: fetches the 5 from there.
3060:
3061: The stack comment near the @code{does>} reflects the stack effect of the
3062: defined word, not the stack effect of the code after the @code{does>}
3063: (the difference is that the code expects the address of the body that
3064: the stack comment does not show).
3065:
3066: You can use these definition words to do factoring in cases that involve
3067: (other) definition words. E.g., a field offset is always added to an
3068: address. Instead of defining
3069:
3070: @example
3071: 2 cells constant offset-field1
3072: @end example
3073:
3074: and using this like
3075:
3076: @example
3077: ( addr ) offset-field1 +
3078: @end example
3079:
3080: you can define a definition word
3081:
3082: @example
3083: : simple-field ( n "name" -- )
3084: create ,
3085: does> ( n1 -- n1+n )
1.50 anton 3086: ( addr ) @@ + ;
1.48 anton 3087: @end example
1.21 crook 3088:
1.48 anton 3089: Definition and use of field offsets now look like this:
1.21 crook 3090:
1.48 anton 3091: @example
3092: 2 cells simple-field field1
1.60 anton 3093: create mystruct 4 cells allot
3094: mystruct .s field1 .s drop
1.48 anton 3095: @end example
1.21 crook 3096:
1.48 anton 3097: If you want to do something with the word without performing the code
3098: after the @code{does>}, you can access the body of a @code{create}d word
3099: with @code{>body ( xt -- addr )}:
1.21 crook 3100:
1.48 anton 3101: @example
3102: : value ( n "name" -- )
3103: create ,
3104: does> ( -- n1 )
1.50 anton 3105: @@ ;
1.48 anton 3106: : to ( n "name" -- )
3107: ' >body ! ;
1.21 crook 3108:
1.48 anton 3109: 5 value foo
3110: foo .
3111: 7 to foo
3112: foo .
3113: @end example
1.21 crook 3114:
1.141 anton 3115: @quotation Assignment
1.48 anton 3116: Define @code{defer ( "name" -- )}, which creates a word that stores an
3117: XT (at the start the XT of @code{abort}), and upon execution
3118: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3119: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3120: recursion is one application of @code{defer}.
1.141 anton 3121: @end quotation
1.29 crook 3122:
1.66 anton 3123: Reference: @ref{User-defined Defining Words}.
3124:
3125:
1.48 anton 3126: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3127: @section Arrays and Records
1.66 anton 3128: @cindex arrays tutorial
3129: @cindex records tutorial
3130: @cindex structs tutorial
1.29 crook 3131:
1.48 anton 3132: Forth has no standard words for defining data structures such as arrays
3133: and records (structs in C terminology), but you can build them yourself
3134: based on address arithmetic. You can also define words for defining
3135: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3136:
1.48 anton 3137: One of the first projects a Forth newcomer sets out upon when learning
3138: about defining words is an array defining word (possibly for
3139: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3140: learn something from it. However, don't be disappointed when you later
3141: learn that you have little use for these words (inappropriate use would
1.198 anton 3142: be even worse). I have not found a set of useful array words yet;
1.48 anton 3143: the needs are just too diverse, and named, global arrays (the result of
3144: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3145: consider how to pass them as parameters). Another such project is a set
3146: of words to help dealing with strings.
1.29 crook 3147:
1.48 anton 3148: On the other hand, there is a useful set of record words, and it has
3149: been defined in @file{compat/struct.fs}; these words are predefined in
3150: Gforth. They are explained in depth elsewhere in this manual (see
3151: @pxref{Structures}). The @code{simple-field} example above is
3152: simplified variant of fields in this package.
1.21 crook 3153:
3154:
1.48 anton 3155: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3156: @section @code{POSTPONE}
1.66 anton 3157: @cindex postpone tutorial
1.21 crook 3158:
1.48 anton 3159: You can compile the compilation semantics (instead of compiling the
3160: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3161:
1.48 anton 3162: @example
3163: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3164: POSTPONE + ; immediate
1.48 anton 3165: : foo ( n1 n2 -- n )
3166: MY-+ ;
3167: 1 2 foo .
3168: see foo
3169: @end example
1.21 crook 3170:
1.48 anton 3171: During the definition of @code{foo} the text interpreter performs the
3172: compilation semantics of @code{MY-+}, which performs the compilation
3173: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3174:
3175: This example also displays separate stack comments for the compilation
3176: semantics and for the stack effect of the compiled code. For words with
3177: default compilation semantics these stack effects are usually not
3178: displayed; the stack effect of the compilation semantics is always
3179: @code{( -- )} for these words, the stack effect for the compiled code is
3180: the stack effect of the interpretation semantics.
3181:
3182: Note that the state of the interpreter does not come into play when
3183: performing the compilation semantics in this way. You can also perform
3184: it interpretively, e.g.:
3185:
3186: @example
3187: : foo2 ( n1 n2 -- n )
3188: [ MY-+ ] ;
3189: 1 2 foo .
3190: see foo
3191: @end example
1.21 crook 3192:
1.48 anton 3193: However, there are some broken Forth systems where this does not always
1.62 crook 3194: work, and therefore this practice was been declared non-standard in
1.48 anton 3195: 1999.
3196: @c !! repair.fs
3197:
3198: Here is another example for using @code{POSTPONE}:
1.44 crook 3199:
1.48 anton 3200: @example
3201: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3202: POSTPONE negate POSTPONE + ; immediate compile-only
3203: : bar ( n1 n2 -- n )
3204: MY-- ;
3205: 2 1 bar .
3206: see bar
3207: @end example
1.21 crook 3208:
1.48 anton 3209: You can define @code{ENDIF} in this way:
1.21 crook 3210:
1.48 anton 3211: @example
3212: : ENDIF ( Compilation: orig -- )
3213: POSTPONE then ; immediate
3214: @end example
1.21 crook 3215:
1.141 anton 3216: @quotation Assignment
1.48 anton 3217: Write @code{MY-2DUP} that has compilation semantics equivalent to
3218: @code{2dup}, but compiles @code{over over}.
1.141 anton 3219: @end quotation
1.29 crook 3220:
1.66 anton 3221: @c !! @xref{Macros} for reference
3222:
3223:
1.48 anton 3224: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3225: @section @code{Literal}
1.66 anton 3226: @cindex literal tutorial
1.29 crook 3227:
1.48 anton 3228: You cannot @code{POSTPONE} numbers:
1.21 crook 3229:
1.48 anton 3230: @example
3231: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3232: @end example
3233:
1.48 anton 3234: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3235:
1.48 anton 3236: @example
3237: : [FOO] ( compilation: --; run-time: -- n )
3238: 500 POSTPONE literal ; immediate
1.29 crook 3239:
1.60 anton 3240: : flip [FOO] ;
1.48 anton 3241: flip .
3242: see flip
3243: @end example
1.29 crook 3244:
1.48 anton 3245: @code{LITERAL} consumes a number at compile-time (when it's compilation
3246: semantics are executed) and pushes it at run-time (when the code it
3247: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3248: number computed at compile time into the current word:
1.29 crook 3249:
1.48 anton 3250: @example
3251: : bar ( -- n )
3252: [ 2 2 + ] literal ;
3253: see bar
3254: @end example
1.29 crook 3255:
1.141 anton 3256: @quotation Assignment
1.48 anton 3257: Write @code{]L} which allows writing the example above as @code{: bar (
3258: -- n ) [ 2 2 + ]L ;}
1.141 anton 3259: @end quotation
1.48 anton 3260:
1.66 anton 3261: @c !! @xref{Macros} for reference
3262:
1.48 anton 3263:
3264: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3265: @section Advanced macros
1.66 anton 3266: @cindex macros, advanced tutorial
3267: @cindex run-time code generation, tutorial
1.48 anton 3268:
1.66 anton 3269: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3270: Execution Tokens}. It frequently performs @code{execute}, a relatively
3271: expensive operation in some Forth implementations. You can use
1.48 anton 3272: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3273: and produce a word that contains the word to be performed directly:
3274:
3275: @c use ]] ... [[
3276: @example
3277: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3278: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3279: \ array beginning at addr and containing u elements
3280: @{ xt @}
3281: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3282: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3283: 1 cells POSTPONE literal POSTPONE +loop ;
3284:
3285: : sum-array ( addr u -- n )
3286: 0 rot rot [ ' + compile-map-array ] ;
3287: see sum-array
3288: a 5 sum-array .
3289: @end example
3290:
3291: You can use the full power of Forth for generating the code; here's an
3292: example where the code is generated in a loop:
3293:
3294: @example
3295: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3296: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3297: POSTPONE tuck POSTPONE @@
1.48 anton 3298: POSTPONE literal POSTPONE * POSTPONE +
3299: POSTPONE swap POSTPONE cell+ ;
3300:
3301: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3302: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3303: 0 postpone literal postpone swap
3304: [ ' compile-vmul-step compile-map-array ]
3305: postpone drop ;
3306: see compile-vmul
3307:
3308: : a-vmul ( addr -- n )
1.51 pazsan 3309: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3310: [ a 5 compile-vmul ] ;
3311: see a-vmul
3312: a a-vmul .
3313: @end example
3314:
3315: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3316: also use @code{map-array} instead (try it now!).
1.48 anton 3317:
3318: You can use this technique for efficient multiplication of large
3319: matrices. In matrix multiplication, you multiply every line of one
3320: matrix with every column of the other matrix. You can generate the code
3321: for one line once, and use it for every column. The only downside of
3322: this technique is that it is cumbersome to recover the memory consumed
3323: by the generated code when you are done (and in more complicated cases
3324: it is not possible portably).
3325:
1.66 anton 3326: @c !! @xref{Macros} for reference
3327:
3328:
1.48 anton 3329: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3330: @section Compilation Tokens
1.66 anton 3331: @cindex compilation tokens, tutorial
3332: @cindex CT, tutorial
1.48 anton 3333:
3334: This section is Gforth-specific. You can skip it.
3335:
3336: @code{' word compile,} compiles the interpretation semantics. For words
3337: with default compilation semantics this is the same as performing the
3338: compilation semantics. To represent the compilation semantics of other
3339: words (e.g., words like @code{if} that have no interpretation
3340: semantics), Gforth has the concept of a compilation token (CT,
3341: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3342: You can perform the compilation semantics represented by a CT with
3343: @code{execute}:
1.29 crook 3344:
1.48 anton 3345: @example
3346: : foo2 ( n1 n2 -- n )
3347: [ comp' + execute ] ;
3348: see foo
3349: @end example
1.29 crook 3350:
1.48 anton 3351: You can compile the compilation semantics represented by a CT with
3352: @code{postpone,}:
1.30 anton 3353:
1.48 anton 3354: @example
3355: : foo3 ( -- )
3356: [ comp' + postpone, ] ;
3357: see foo3
3358: @end example
1.30 anton 3359:
1.51 pazsan 3360: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3361: @code{comp'} is particularly useful for words that have no
3362: interpretation semantics:
1.29 crook 3363:
1.30 anton 3364: @example
1.48 anton 3365: ' if
1.60 anton 3366: comp' if .s 2drop
1.30 anton 3367: @end example
3368:
1.66 anton 3369: Reference: @ref{Tokens for Words}.
3370:
1.29 crook 3371:
1.48 anton 3372: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3373: @section Wordlists and Search Order
1.66 anton 3374: @cindex wordlists tutorial
3375: @cindex search order, tutorial
1.48 anton 3376:
3377: The dictionary is not just a memory area that allows you to allocate
3378: memory with @code{allot}, it also contains the Forth words, arranged in
3379: several wordlists. When searching for a word in a wordlist,
3380: conceptually you start searching at the youngest and proceed towards
3381: older words (in reality most systems nowadays use hash-tables); i.e., if
3382: you define a word with the same name as an older word, the new word
3383: shadows the older word.
3384:
3385: Which wordlists are searched in which order is determined by the search
3386: order. You can display the search order with @code{order}. It displays
3387: first the search order, starting with the wordlist searched first, then
3388: it displays the wordlist that will contain newly defined words.
1.21 crook 3389:
1.48 anton 3390: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3391:
1.48 anton 3392: @example
3393: wordlist constant mywords
3394: @end example
1.21 crook 3395:
1.48 anton 3396: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3397: defined words (the @emph{current} wordlist):
1.21 crook 3398:
1.48 anton 3399: @example
3400: mywords set-current
3401: order
3402: @end example
1.26 crook 3403:
1.48 anton 3404: Gforth does not display a name for the wordlist in @code{mywords}
3405: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3406:
1.48 anton 3407: You can get the current wordlist with @code{get-current ( -- wid)}. If
3408: you want to put something into a specific wordlist without overall
3409: effect on the current wordlist, this typically looks like this:
1.21 crook 3410:
1.48 anton 3411: @example
3412: get-current mywords set-current ( wid )
3413: create someword
3414: ( wid ) set-current
3415: @end example
1.21 crook 3416:
1.48 anton 3417: You can write the search order with @code{set-order ( wid1 .. widn n --
3418: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3419: searched wordlist is topmost.
1.21 crook 3420:
1.48 anton 3421: @example
3422: get-order mywords swap 1+ set-order
3423: order
3424: @end example
1.21 crook 3425:
1.48 anton 3426: Yes, the order of wordlists in the output of @code{order} is reversed
3427: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3428:
1.141 anton 3429: @quotation Assignment
1.48 anton 3430: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3431: wordlist to the search order. Define @code{previous ( -- )}, which
3432: removes the first searched wordlist from the search order. Experiment
3433: with boundary conditions (you will see some crashes or situations that
3434: are hard or impossible to leave).
1.141 anton 3435: @end quotation
1.21 crook 3436:
1.48 anton 3437: The search order is a powerful foundation for providing features similar
3438: to Modula-2 modules and C++ namespaces. However, trying to modularize
3439: programs in this way has disadvantages for debugging and reuse/factoring
3440: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3441: though). These disadvantages are not so clear in other
1.82 anton 3442: languages/programming environments, because these languages are not so
1.48 anton 3443: strong in debugging and reuse.
1.21 crook 3444:
1.66 anton 3445: @c !! example
3446:
3447: Reference: @ref{Word Lists}.
1.21 crook 3448:
1.29 crook 3449: @c ******************************************************************
1.48 anton 3450: @node Introduction, Words, Tutorial, Top
1.29 crook 3451: @comment node-name, next, previous, up
3452: @chapter An Introduction to ANS Forth
3453: @cindex Forth - an introduction
1.21 crook 3454:
1.83 anton 3455: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3456: that it is slower-paced in its examples, but uses them to dive deep into
3457: explaining Forth internals (not covered by the Tutorial). Apart from
3458: that, this chapter covers far less material. It is suitable for reading
3459: without using a computer.
3460:
1.29 crook 3461: The primary purpose of this manual is to document Gforth. However, since
3462: Forth is not a widely-known language and there is a lack of up-to-date
3463: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3464: material. For other sources of Forth-related
3465: information, see @ref{Forth-related information}.
1.21 crook 3466:
1.29 crook 3467: The examples in this section should work on any ANS Forth; the
3468: output shown was produced using Gforth. Each example attempts to
3469: reproduce the exact output that Gforth produces. If you try out the
3470: examples (and you should), what you should type is shown @kbd{like this}
3471: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3472: that, where the example shows @key{RET} it means that you should
1.29 crook 3473: press the ``carriage return'' key. Unfortunately, some output formats for
3474: this manual cannot show the difference between @kbd{this} and
3475: @code{this} which will make trying out the examples harder (but not
3476: impossible).
1.21 crook 3477:
1.29 crook 3478: Forth is an unusual language. It provides an interactive development
3479: environment which includes both an interpreter and compiler. Forth
3480: programming style encourages you to break a problem down into many
3481: @cindex factoring
3482: small fragments (@dfn{factoring}), and then to develop and test each
3483: fragment interactively. Forth advocates assert that breaking the
3484: edit-compile-test cycle used by conventional programming languages can
3485: lead to great productivity improvements.
1.21 crook 3486:
1.29 crook 3487: @menu
1.67 anton 3488: * Introducing the Text Interpreter::
3489: * Stacks and Postfix notation::
3490: * Your first definition::
3491: * How does that work?::
3492: * Forth is written in Forth::
3493: * Review - elements of a Forth system::
3494: * Where to go next::
3495: * Exercises::
1.29 crook 3496: @end menu
1.21 crook 3497:
1.29 crook 3498: @comment ----------------------------------------------
3499: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3500: @section Introducing the Text Interpreter
3501: @cindex text interpreter
3502: @cindex outer interpreter
1.21 crook 3503:
1.30 anton 3504: @c IMO this is too detailed and the pace is too slow for
3505: @c an introduction. If you know German, take a look at
3506: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3507: @c to see how I do it - anton
3508:
1.44 crook 3509: @c nac-> Where I have accepted your comments 100% and modified the text
3510: @c accordingly, I have deleted your comments. Elsewhere I have added a
3511: @c response like this to attempt to rationalise what I have done. Of
3512: @c course, this is a very clumsy mechanism for something that would be
3513: @c done far more efficiently over a beer. Please delete any dialogue
3514: @c you consider closed.
3515:
1.29 crook 3516: When you invoke the Forth image, you will see a startup banner printed
3517: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3518: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3519: its command line interpreter, which is called the @dfn{Text Interpreter}
3520: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3521: about the text interpreter as you read through this chapter, for more
3522: detail @pxref{The Text Interpreter}).
1.21 crook 3523:
1.29 crook 3524: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3525: input. Type a number and press the @key{RET} key:
1.21 crook 3526:
1.26 crook 3527: @example
1.30 anton 3528: @kbd{45@key{RET}} ok
1.26 crook 3529: @end example
1.21 crook 3530:
1.29 crook 3531: Rather than give you a prompt to invite you to input something, the text
3532: interpreter prints a status message @i{after} it has processed a line
3533: of input. The status message in this case (``@code{ ok}'' followed by
3534: carriage-return) indicates that the text interpreter was able to process
3535: all of your input successfully. Now type something illegal:
3536:
3537: @example
1.30 anton 3538: @kbd{qwer341@key{RET}}
1.134 anton 3539: *the terminal*:2: Undefined word
3540: >>>qwer341<<<
3541: Backtrace:
3542: $2A95B42A20 throw
3543: $2A95B57FB8 no.extensions
1.29 crook 3544: @end example
1.23 crook 3545:
1.134 anton 3546: The exact text, other than the ``Undefined word'' may differ slightly
3547: on your system, but the effect is the same; when the text interpreter
1.29 crook 3548: detects an error, it discards any remaining text on a line, resets
1.134 anton 3549: certain internal state and prints an error message. For a detailed
3550: description of error messages see @ref{Error messages}.
1.23 crook 3551:
1.29 crook 3552: The text interpreter waits for you to press carriage-return, and then
3553: processes your input line. Starting at the beginning of the line, it
3554: breaks the line into groups of characters separated by spaces. For each
3555: group of characters in turn, it makes two attempts to do something:
1.23 crook 3556:
1.29 crook 3557: @itemize @bullet
3558: @item
1.44 crook 3559: @cindex name dictionary
1.29 crook 3560: It tries to treat it as a command. It does this by searching a @dfn{name
3561: dictionary}. If the group of characters matches an entry in the name
3562: dictionary, the name dictionary provides the text interpreter with
3563: information that allows the text interpreter perform some actions. In
3564: Forth jargon, we say that the group
3565: @cindex word
3566: @cindex definition
3567: @cindex execution token
3568: @cindex xt
3569: of characters names a @dfn{word}, that the dictionary search returns an
3570: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3571: word, and that the text interpreter executes the xt. Often, the terms
3572: @dfn{word} and @dfn{definition} are used interchangeably.
3573: @item
3574: If the text interpreter fails to find a match in the name dictionary, it
3575: tries to treat the group of characters as a number in the current number
3576: base (when you start up Forth, the current number base is base 10). If
3577: the group of characters legitimately represents a number, the text
3578: interpreter pushes the number onto a stack (we'll learn more about that
3579: in the next section).
3580: @end itemize
1.23 crook 3581:
1.29 crook 3582: If the text interpreter is unable to do either of these things with any
3583: group of characters, it discards the group of characters and the rest of
3584: the line, then prints an error message. If the text interpreter reaches
3585: the end of the line without error, it prints the status message ``@code{ ok}''
3586: followed by carriage-return.
1.21 crook 3587:
1.29 crook 3588: This is the simplest command we can give to the text interpreter:
1.23 crook 3589:
3590: @example
1.30 anton 3591: @key{RET} ok
1.23 crook 3592: @end example
1.21 crook 3593:
1.29 crook 3594: The text interpreter did everything we asked it to do (nothing) without
3595: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3596: command:
1.21 crook 3597:
1.23 crook 3598: @example
1.30 anton 3599: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3600: *the terminal*:3: Undefined word
3601: 12 dup >>>fred<<< dup
3602: Backtrace:
3603: $2A95B42A20 throw
3604: $2A95B57FB8 no.extensions
1.23 crook 3605: @end example
1.21 crook 3606:
1.29 crook 3607: When you press the carriage-return key, the text interpreter starts to
3608: work its way along the line:
1.21 crook 3609:
1.29 crook 3610: @itemize @bullet
3611: @item
3612: When it gets to the space after the @code{2}, it takes the group of
3613: characters @code{12} and looks them up in the name
3614: dictionary@footnote{We can't tell if it found them or not, but assume
3615: for now that it did not}. There is no match for this group of characters
3616: in the name dictionary, so it tries to treat them as a number. It is
3617: able to do this successfully, so it puts the number, 12, ``on the stack''
3618: (whatever that means).
3619: @item
3620: The text interpreter resumes scanning the line and gets the next group
3621: of characters, @code{dup}. It looks it up in the name dictionary and
3622: (you'll have to take my word for this) finds it, and executes the word
3623: @code{dup} (whatever that means).
3624: @item
3625: Once again, the text interpreter resumes scanning the line and gets the
3626: group of characters @code{fred}. It looks them up in the name
3627: dictionary, but can't find them. It tries to treat them as a number, but
3628: they don't represent any legal number.
3629: @end itemize
1.21 crook 3630:
1.29 crook 3631: At this point, the text interpreter gives up and prints an error
3632: message. The error message shows exactly how far the text interpreter
3633: got in processing the line. In particular, it shows that the text
3634: interpreter made no attempt to do anything with the final character
3635: group, @code{dup}, even though we have good reason to believe that the
3636: text interpreter would have no problem looking that word up and
3637: executing it a second time.
1.21 crook 3638:
3639:
1.29 crook 3640: @comment ----------------------------------------------
3641: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3642: @section Stacks, postfix notation and parameter passing
3643: @cindex text interpreter
3644: @cindex outer interpreter
1.21 crook 3645:
1.29 crook 3646: In procedural programming languages (like C and Pascal), the
3647: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3648: functions or procedures are called with @dfn{explicit parameters}. For
3649: example, in C we might write:
1.21 crook 3650:
1.23 crook 3651: @example
1.29 crook 3652: total = total + new_volume(length,height,depth);
1.23 crook 3653: @end example
1.21 crook 3654:
1.23 crook 3655: @noindent
1.29 crook 3656: where new_volume is a function-call to another piece of code, and total,
3657: length, height and depth are all variables. length, height and depth are
3658: parameters to the function-call.
1.21 crook 3659:
1.29 crook 3660: In Forth, the equivalent of the function or procedure is the
3661: @dfn{definition} and parameters are implicitly passed between
3662: definitions using a shared stack that is visible to the
3663: programmer. Although Forth does support variables, the existence of the
3664: stack means that they are used far less often than in most other
3665: programming languages. When the text interpreter encounters a number, it
3666: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3667: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3668: used for any operation is implied unambiguously by the operation being
3669: performed. The stack used for all integer operations is called the @dfn{data
3670: stack} and, since this is the stack used most commonly, references to
3671: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3672:
1.29 crook 3673: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3674:
1.23 crook 3675: @example
1.30 anton 3676: @kbd{1 2 3@key{RET}} ok
1.23 crook 3677: @end example
1.21 crook 3678:
1.29 crook 3679: Then this instructs the text interpreter to placed three numbers on the
3680: (data) stack. An analogy for the behaviour of the stack is to take a
3681: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3682: the table. The 3 was the last card onto the pile (``last-in'') and if
3683: you take a card off the pile then, unless you're prepared to fiddle a
3684: bit, the card that you take off will be the 3 (``first-out''). The
3685: number that will be first-out of the stack is called the @dfn{top of
3686: stack}, which
3687: @cindex TOS definition
3688: is often abbreviated to @dfn{TOS}.
1.21 crook 3689:
1.29 crook 3690: To understand how parameters are passed in Forth, consider the
3691: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3692: be surprised to learn that this definition performs addition. More
3693: precisely, it adds two number together and produces a result. Where does
3694: it get the two numbers from? It takes the top two numbers off the
3695: stack. Where does it place the result? On the stack. You can act-out the
3696: behaviour of @code{+} with your playing cards like this:
1.21 crook 3697:
3698: @itemize @bullet
3699: @item
1.29 crook 3700: Pick up two cards from the stack on the table
1.21 crook 3701: @item
1.29 crook 3702: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3703: numbers''
1.21 crook 3704: @item
1.29 crook 3705: Decide that the answer is 5
1.21 crook 3706: @item
1.29 crook 3707: Shuffle the two cards back into the pack and find a 5
1.21 crook 3708: @item
1.29 crook 3709: Put a 5 on the remaining ace that's on the table.
1.21 crook 3710: @end itemize
3711:
1.29 crook 3712: If you don't have a pack of cards handy but you do have Forth running,
3713: you can use the definition @code{.s} to show the current state of the stack,
3714: without affecting the stack. Type:
1.21 crook 3715:
3716: @example
1.124 anton 3717: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3718: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3719: @end example
3720:
1.124 anton 3721: The text interpreter looks up the word @code{clearstacks} and executes
3722: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3723: left on it by earlier examples. The text interpreter pushes each of the
3724: three numbers in turn onto the stack. Finally, the text interpreter
3725: looks up the word @code{.s} and executes it. The effect of executing
3726: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3727: followed by a list of all the items on the stack; the item on the far
3728: right-hand side is the TOS.
1.21 crook 3729:
1.29 crook 3730: You can now type:
1.21 crook 3731:
1.29 crook 3732: @example
1.30 anton 3733: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3734: @end example
1.21 crook 3735:
1.29 crook 3736: @noindent
3737: which is correct; there are now 2 items on the stack and the result of
3738: the addition is 5.
1.23 crook 3739:
1.29 crook 3740: If you're playing with cards, try doing a second addition: pick up the
3741: two cards, work out that their sum is 6, shuffle them into the pack,
3742: look for a 6 and place that on the table. You now have just one item on
3743: the stack. What happens if you try to do a third addition? Pick up the
3744: first card, pick up the second card -- ah! There is no second card. This
3745: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3746: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3747: Underflow or an Invalid Memory Address error).
1.23 crook 3748:
1.29 crook 3749: The opposite situation to a stack underflow is a @dfn{stack overflow},
3750: which simply accepts that there is a finite amount of storage space
3751: reserved for the stack. To stretch the playing card analogy, if you had
3752: enough packs of cards and you piled the cards up on the table, you would
3753: eventually be unable to add another card; you'd hit the ceiling. Gforth
3754: allows you to set the maximum size of the stacks. In general, the only
3755: time that you will get a stack overflow is because a definition has a
3756: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3757:
1.29 crook 3758: There's one final use for the playing card analogy. If you model your
3759: stack using a pack of playing cards, the maximum number of items on
3760: your stack will be 52 (I assume you didn't use the Joker). The maximum
3761: @i{value} of any item on the stack is 13 (the King). In fact, the only
3762: possible numbers are positive integer numbers 1 through 13; you can't
3763: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3764: think about some of the cards, you can accommodate different
3765: numbers. For example, you could think of the Jack as representing 0,
3766: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3767: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3768: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3769:
1.29 crook 3770: In that analogy, the limit was the amount of information that a single
3771: stack entry could hold, and Forth has a similar limit. In Forth, the
3772: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3773: implementation dependent and affects the maximum value that a stack
3774: entry can hold. A Standard Forth provides a cell size of at least
3775: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3776:
1.29 crook 3777: Forth does not do any type checking for you, so you are free to
3778: manipulate and combine stack items in any way you wish. A convenient way
3779: of treating stack items is as 2's complement signed integers, and that
3780: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3781:
1.29 crook 3782: @example
1.30 anton 3783: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3784: @end example
1.21 crook 3785:
1.29 crook 3786: If you use numbers and definitions like @code{+} in order to turn Forth
3787: into a great big pocket calculator, you will realise that it's rather
3788: different from a normal calculator. Rather than typing 2 + 3 = you had
3789: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3790: result). The terminology used to describe this difference is to say that
3791: your calculator uses @dfn{Infix Notation} (parameters and operators are
3792: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3793: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3794:
1.29 crook 3795: Whilst postfix notation might look confusing to begin with, it has
3796: several important advantages:
1.21 crook 3797:
1.23 crook 3798: @itemize @bullet
3799: @item
1.29 crook 3800: it is unambiguous
1.23 crook 3801: @item
1.29 crook 3802: it is more concise
1.23 crook 3803: @item
1.29 crook 3804: it fits naturally with a stack-based system
1.23 crook 3805: @end itemize
1.21 crook 3806:
1.29 crook 3807: To examine these claims in more detail, consider these sums:
1.21 crook 3808:
1.29 crook 3809: @example
3810: 6 + 5 * 4 =
3811: 4 * 5 + 6 =
3812: @end example
1.21 crook 3813:
1.29 crook 3814: If you're just learning maths or your maths is very rusty, you will
3815: probably come up with the answer 44 for the first and 26 for the
3816: second. If you are a bit of a whizz at maths you will remember the
3817: @i{convention} that multiplication takes precendence over addition, and
3818: you'd come up with the answer 26 both times. To explain the answer 26
3819: to someone who got the answer 44, you'd probably rewrite the first sum
3820: like this:
1.21 crook 3821:
1.29 crook 3822: @example
3823: 6 + (5 * 4) =
3824: @end example
1.21 crook 3825:
1.29 crook 3826: If what you really wanted was to perform the addition before the
3827: multiplication, you would have to use parentheses to force it.
1.21 crook 3828:
1.29 crook 3829: If you did the first two sums on a pocket calculator you would probably
3830: get the right answers, unless you were very cautious and entered them using
3831: these keystroke sequences:
1.21 crook 3832:
1.29 crook 3833: 6 + 5 = * 4 =
3834: 4 * 5 = + 6 =
1.21 crook 3835:
1.29 crook 3836: Postfix notation is unambiguous because the order that the operators
3837: are applied is always explicit; that also means that parentheses are
3838: never required. The operators are @i{active} (the act of quoting the
3839: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3840:
1.29 crook 3841: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3842: equivalent ways:
1.26 crook 3843:
3844: @example
1.29 crook 3845: 6 5 4 * + or:
3846: 5 4 * 6 +
1.26 crook 3847: @end example
1.23 crook 3848:
1.29 crook 3849: An important thing that you should notice about this notation is that
3850: the @i{order} of the numbers does not change; if you want to subtract
3851: 2 from 10 you type @code{10 2 -}.
1.1 anton 3852:
1.29 crook 3853: The reason that Forth uses postfix notation is very simple to explain: it
3854: makes the implementation extremely simple, and it follows naturally from
3855: using the stack as a mechanism for passing parameters. Another way of
3856: thinking about this is to realise that all Forth definitions are
3857: @i{active}; they execute as they are encountered by the text
3858: interpreter. The result of this is that the syntax of Forth is trivially
3859: simple.
1.1 anton 3860:
3861:
3862:
1.29 crook 3863: @comment ----------------------------------------------
3864: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3865: @section Your first Forth definition
3866: @cindex first definition
1.1 anton 3867:
1.29 crook 3868: Until now, the examples we've seen have been trivial; we've just been
3869: using Forth as a bigger-than-pocket calculator. Also, each calculation
3870: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3871: again@footnote{That's not quite true. If you press the up-arrow key on
3872: your keyboard you should be able to scroll back to any earlier command,
3873: edit it and re-enter it.} In this section we'll see how to add new
3874: words to Forth's vocabulary.
1.1 anton 3875:
1.29 crook 3876: The easiest way to create a new word is to use a @dfn{colon
3877: definition}. We'll define a few and try them out before worrying too
3878: much about how they work. Try typing in these examples; be careful to
3879: copy the spaces accurately:
1.1 anton 3880:
1.29 crook 3881: @example
3882: : add-two 2 + . ;
3883: : greet ." Hello and welcome" ;
3884: : demo 5 add-two ;
3885: @end example
1.1 anton 3886:
1.29 crook 3887: @noindent
3888: Now try them out:
1.1 anton 3889:
1.29 crook 3890: @example
1.30 anton 3891: @kbd{greet@key{RET}} Hello and welcome ok
3892: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3893: @kbd{4 add-two@key{RET}} 6 ok
3894: @kbd{demo@key{RET}} 7 ok
3895: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3896: @end example
1.1 anton 3897:
1.29 crook 3898: The first new thing that we've introduced here is the pair of words
3899: @code{:} and @code{;}. These are used to start and terminate a new
3900: definition, respectively. The first word after the @code{:} is the name
3901: for the new definition.
1.1 anton 3902:
1.29 crook 3903: As you can see from the examples, a definition is built up of words that
3904: have already been defined; Forth makes no distinction between
3905: definitions that existed when you started the system up, and those that
3906: you define yourself.
1.1 anton 3907:
1.29 crook 3908: The examples also introduce the words @code{.} (dot), @code{."}
3909: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3910: the stack and displays it. It's like @code{.s} except that it only
3911: displays the top item of the stack and it is destructive; after it has
3912: executed, the number is no longer on the stack. There is always one
3913: space printed after the number, and no spaces before it. Dot-quote
3914: defines a string (a sequence of characters) that will be printed when
3915: the word is executed. The string can contain any printable characters
3916: except @code{"}. A @code{"} has a special function; it is not a Forth
3917: word but it acts as a delimiter (the way that delimiters work is
3918: described in the next section). Finally, @code{dup} duplicates the value
3919: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3920:
1.29 crook 3921: We already know that the text interpreter searches through the
3922: dictionary to locate names. If you've followed the examples earlier, you
3923: will already have a definition called @code{add-two}. Lets try modifying
3924: it by typing in a new definition:
1.1 anton 3925:
1.29 crook 3926: @example
1.30 anton 3927: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3928: @end example
1.5 anton 3929:
1.29 crook 3930: Forth recognised that we were defining a word that already exists, and
3931: printed a message to warn us of that fact. Let's try out the new
3932: definition:
1.5 anton 3933:
1.29 crook 3934: @example
1.30 anton 3935: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3936: @end example
1.1 anton 3937:
1.29 crook 3938: @noindent
3939: All that we've actually done here, though, is to create a new
3940: definition, with a particular name. The fact that there was already a
3941: definition with the same name did not make any difference to the way
3942: that the new definition was created (except that Forth printed a warning
3943: message). The old definition of add-two still exists (try @code{demo}
3944: again to see that this is true). Any new definition will use the new
3945: definition of @code{add-two}, but old definitions continue to use the
3946: version that already existed at the time that they were @code{compiled}.
1.1 anton 3947:
1.29 crook 3948: Before you go on to the next section, try defining and redefining some
3949: words of your own.
1.1 anton 3950:
1.29 crook 3951: @comment ----------------------------------------------
3952: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3953: @section How does that work?
3954: @cindex parsing words
1.1 anton 3955:
1.30 anton 3956: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3957:
3958: @c Is it a good idea to talk about the interpretation semantics of a
3959: @c number? We don't have an xt to go along with it. - anton
3960:
3961: @c Now that I have eliminated execution semantics, I wonder if it would not
3962: @c be better to keep them (or add run-time semantics), to make it easier to
3963: @c explain what compilation semantics usually does. - anton
3964:
1.44 crook 3965: @c nac-> I removed the term ``default compilation sematics'' from the
3966: @c introductory chapter. Removing ``execution semantics'' was making
3967: @c everything simpler to explain, then I think the use of this term made
3968: @c everything more complex again. I replaced it with ``default
3969: @c semantics'' (which is used elsewhere in the manual) by which I mean
3970: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3971: @c flag set''.
3972:
3973: @c anton: I have eliminated default semantics (except in one place where it
3974: @c means "default interpretation and compilation semantics"), because it
3975: @c makes no sense in the presence of combined words. I reverted to
3976: @c "execution semantics" where necessary.
3977:
3978: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3979: @c section (and, unusually for me, I think I even made it shorter!). See
3980: @c what you think -- I know I have not addressed your primary concern
3981: @c that it is too heavy-going for an introduction. From what I understood
3982: @c of your course notes it looks as though they might be a good framework.
3983: @c Things that I've tried to capture here are some things that came as a
3984: @c great revelation here when I first understood them. Also, I like the
3985: @c fact that a very simple code example shows up almost all of the issues
3986: @c that you need to understand to see how Forth works. That's unique and
3987: @c worthwhile to emphasise.
3988:
1.83 anton 3989: @c anton: I think it's a good idea to present the details, especially those
3990: @c that you found to be a revelation, and probably the tutorial tries to be
3991: @c too superficial and does not get some of the things across that make
3992: @c Forth special. I do believe that most of the time these things should
3993: @c be discussed at the end of a section or in separate sections instead of
3994: @c in the middle of a section (e.g., the stuff you added in "User-defined
3995: @c defining words" leads in a completely different direction from the rest
3996: @c of the section).
3997:
1.29 crook 3998: Now we're going to take another look at the definition of @code{add-two}
3999: from the previous section. From our knowledge of the way that the text
4000: interpreter works, we would have expected this result when we tried to
4001: define @code{add-two}:
1.21 crook 4002:
1.29 crook 4003: @example
1.44 crook 4004: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 4005: *the terminal*:4: Undefined word
4006: : >>>add-two<<< 2 + . ;
1.29 crook 4007: @end example
1.28 crook 4008:
1.29 crook 4009: The reason that this didn't happen is bound up in the way that @code{:}
4010: works. The word @code{:} does two special things. The first special
4011: thing that it does prevents the text interpreter from ever seeing the
4012: characters @code{add-two}. The text interpreter uses a variable called
4013: @cindex modifying >IN
1.44 crook 4014: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4015: input line. When it encounters the word @code{:} it behaves in exactly
4016: the same way as it does for any other word; it looks it up in the name
4017: dictionary, finds its xt and executes it. When @code{:} executes, it
4018: looks at the input buffer, finds the word @code{add-two} and advances the
4019: value of @code{>IN} to point past it. It then does some other stuff
4020: associated with creating the new definition (including creating an entry
4021: for @code{add-two} in the name dictionary). When the execution of @code{:}
4022: completes, control returns to the text interpreter, which is oblivious
4023: to the fact that it has been tricked into ignoring part of the input
4024: line.
1.21 crook 4025:
1.29 crook 4026: @cindex parsing words
4027: Words like @code{:} -- words that advance the value of @code{>IN} and so
4028: prevent the text interpreter from acting on the whole of the input line
4029: -- are called @dfn{parsing words}.
1.21 crook 4030:
1.29 crook 4031: @cindex @code{state} - effect on the text interpreter
4032: @cindex text interpreter - effect of state
4033: The second special thing that @code{:} does is change the value of a
4034: variable called @code{state}, which affects the way that the text
4035: interpreter behaves. When Gforth starts up, @code{state} has the value
4036: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4037: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4038: the text interpreter is said to be @dfn{compiling}.
4039:
4040: In this example, the text interpreter is compiling when it processes the
4041: string ``@code{2 + . ;}''. It still breaks the string down into
4042: character sequences in the same way. However, instead of pushing the
4043: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4044: into the definition of @code{add-two} that will make the number @code{2} get
4045: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4046: the behaviours of @code{+} and @code{.} are also compiled into the
4047: definition.
4048:
4049: One category of words don't get compiled. These so-called @dfn{immediate
4050: words} get executed (performed @i{now}) regardless of whether the text
4051: interpreter is interpreting or compiling. The word @code{;} is an
4052: immediate word. Rather than being compiled into the definition, it
4053: executes. Its effect is to terminate the current definition, which
4054: includes changing the value of @code{state} back to 0.
4055:
4056: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4057: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4058: definition.
1.28 crook 4059:
1.30 anton 4060: In Forth, every word or number can be described in terms of two
1.29 crook 4061: properties:
1.28 crook 4062:
4063: @itemize @bullet
4064: @item
1.29 crook 4065: @cindex interpretation semantics
1.44 crook 4066: Its @dfn{interpretation semantics} describe how it will behave when the
4067: text interpreter encounters it in @dfn{interpret} state. The
4068: interpretation semantics of a word are represented by an @dfn{execution
4069: token}.
1.28 crook 4070: @item
1.29 crook 4071: @cindex compilation semantics
1.44 crook 4072: Its @dfn{compilation semantics} describe how it will behave when the
4073: text interpreter encounters it in @dfn{compile} state. The compilation
4074: semantics of a word are represented in an implementation-dependent way;
4075: Gforth uses a @dfn{compilation token}.
1.29 crook 4076: @end itemize
4077:
4078: @noindent
4079: Numbers are always treated in a fixed way:
4080:
4081: @itemize @bullet
1.28 crook 4082: @item
1.44 crook 4083: When the number is @dfn{interpreted}, its behaviour is to push the
4084: number onto the stack.
1.28 crook 4085: @item
1.30 anton 4086: When the number is @dfn{compiled}, a piece of code is appended to the
4087: current definition that pushes the number when it runs. (In other words,
4088: the compilation semantics of a number are to postpone its interpretation
4089: semantics until the run-time of the definition that it is being compiled
4090: into.)
1.29 crook 4091: @end itemize
4092:
1.44 crook 4093: Words don't behave in such a regular way, but most have @i{default
4094: semantics} which means that they behave like this:
1.29 crook 4095:
4096: @itemize @bullet
1.28 crook 4097: @item
1.30 anton 4098: The @dfn{interpretation semantics} of the word are to do something useful.
4099: @item
1.29 crook 4100: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4101: @dfn{interpretation semantics} to the current definition (so that its
4102: run-time behaviour is to do something useful).
1.28 crook 4103: @end itemize
4104:
1.30 anton 4105: @cindex immediate words
1.44 crook 4106: The actual behaviour of any particular word can be controlled by using
4107: the words @code{immediate} and @code{compile-only} when the word is
4108: defined. These words set flags in the name dictionary entry of the most
4109: recently defined word, and these flags are retrieved by the text
4110: interpreter when it finds the word in the name dictionary.
4111:
4112: A word that is marked as @dfn{immediate} has compilation semantics that
4113: are identical to its interpretation semantics. In other words, it
4114: behaves like this:
1.29 crook 4115:
4116: @itemize @bullet
4117: @item
1.30 anton 4118: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4119: @item
1.30 anton 4120: The @dfn{compilation semantics} of the word are to do something useful
4121: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4122: @end itemize
1.28 crook 4123:
1.44 crook 4124: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4125: performing the interpretation semantics of the word directly; an attempt
4126: to do so will generate an error. It is never necessary to use
4127: @code{compile-only} (and it is not even part of ANS Forth, though it is
4128: provided by many implementations) but it is good etiquette to apply it
4129: to a word that will not behave correctly (and might have unexpected
4130: side-effects) in interpret state. For example, it is only legal to use
4131: the conditional word @code{IF} within a definition. If you forget this
4132: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4133: @code{compile-only} allows the text interpreter to generate a helpful
4134: error message rather than subjecting you to the consequences of your
4135: folly.
4136:
1.29 crook 4137: This example shows the difference between an immediate and a
4138: non-immediate word:
1.28 crook 4139:
1.29 crook 4140: @example
4141: : show-state state @@ . ;
4142: : show-state-now show-state ; immediate
4143: : word1 show-state ;
4144: : word2 show-state-now ;
1.28 crook 4145: @end example
1.23 crook 4146:
1.29 crook 4147: The word @code{immediate} after the definition of @code{show-state-now}
4148: makes that word an immediate word. These definitions introduce a new
4149: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4150: variable, and leaves it on the stack. Therefore, the behaviour of
4151: @code{show-state} is to print a number that represents the current value
4152: of @code{state}.
1.28 crook 4153:
1.29 crook 4154: When you execute @code{word1}, it prints the number 0, indicating that
4155: the system is interpreting. When the text interpreter compiled the
4156: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4157: compilation semantics are to append its interpretation semantics to the
1.29 crook 4158: current definition. When you execute @code{word1}, it performs the
1.30 anton 4159: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4160: (and therefore @code{show-state}) are executed, the system is
4161: interpreting.
1.28 crook 4162:
1.30 anton 4163: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4164: you should have seen the number -1 printed, followed by ``@code{
4165: ok}''. When the text interpreter compiled the definition of
4166: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4167: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4168: semantics. It is executed straight away (even before the text
4169: interpreter has moved on to process another group of characters; the
4170: @code{;} in this example). The effect of executing it are to display the
4171: value of @code{state} @i{at the time that the definition of}
4172: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4173: system is compiling at this time. If you execute @code{word2} it does
4174: nothing at all.
1.28 crook 4175:
1.29 crook 4176: @cindex @code{."}, how it works
4177: Before leaving the subject of immediate words, consider the behaviour of
4178: @code{."} in the definition of @code{greet}, in the previous
4179: section. This word is both a parsing word and an immediate word. Notice
4180: that there is a space between @code{."} and the start of the text
4181: @code{Hello and welcome}, but that there is no space between the last
4182: letter of @code{welcome} and the @code{"} character. The reason for this
4183: is that @code{."} is a Forth word; it must have a space after it so that
4184: the text interpreter can identify it. The @code{"} is not a Forth word;
4185: it is a @dfn{delimiter}. The examples earlier show that, when the string
4186: is displayed, there is neither a space before the @code{H} nor after the
4187: @code{e}. Since @code{."} is an immediate word, it executes at the time
4188: that @code{greet} is defined. When it executes, its behaviour is to
4189: search forward in the input line looking for the delimiter. When it
4190: finds the delimiter, it updates @code{>IN} to point past the
4191: delimiter. It also compiles some magic code into the definition of
4192: @code{greet}; the xt of a run-time routine that prints a text string. It
4193: compiles the string @code{Hello and welcome} into memory so that it is
4194: available to be printed later. When the text interpreter gains control,
4195: the next word it finds in the input stream is @code{;} and so it
4196: terminates the definition of @code{greet}.
1.28 crook 4197:
4198:
4199: @comment ----------------------------------------------
1.29 crook 4200: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4201: @section Forth is written in Forth
4202: @cindex structure of Forth programs
4203:
4204: When you start up a Forth compiler, a large number of definitions
4205: already exist. In Forth, you develop a new application using bottom-up
4206: programming techniques to create new definitions that are defined in
4207: terms of existing definitions. As you create each definition you can
4208: test and debug it interactively.
4209:
4210: If you have tried out the examples in this section, you will probably
4211: have typed them in by hand; when you leave Gforth, your definitions will
4212: be lost. You can avoid this by using a text editor to enter Forth source
4213: code into a file, and then loading code from the file using
1.49 anton 4214: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4215: processed by the text interpreter, just as though you had typed it in by
4216: hand@footnote{Actually, there are some subtle differences -- see
4217: @ref{The Text Interpreter}.}.
4218:
4219: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4220: files for program entry (@pxref{Blocks}).
1.28 crook 4221:
1.29 crook 4222: In common with many, if not most, Forth compilers, most of Gforth is
4223: actually written in Forth. All of the @file{.fs} files in the
4224: installation directory@footnote{For example,
1.30 anton 4225: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4226: study to see examples of Forth programming.
1.28 crook 4227:
1.29 crook 4228: Gforth maintains a history file that records every line that you type to
4229: the text interpreter. This file is preserved between sessions, and is
4230: used to provide a command-line recall facility. If you enter long
4231: definitions by hand, you can use a text editor to paste them out of the
4232: history file into a Forth source file for reuse at a later time
1.49 anton 4233: (for more information @pxref{Command-line editing}).
1.28 crook 4234:
4235:
4236: @comment ----------------------------------------------
1.29 crook 4237: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4238: @section Review - elements of a Forth system
4239: @cindex elements of a Forth system
1.28 crook 4240:
1.29 crook 4241: To summarise this chapter:
1.28 crook 4242:
4243: @itemize @bullet
4244: @item
1.29 crook 4245: Forth programs use @dfn{factoring} to break a problem down into small
4246: fragments called @dfn{words} or @dfn{definitions}.
4247: @item
4248: Forth program development is an interactive process.
4249: @item
4250: The main command loop that accepts input, and controls both
4251: interpretation and compilation, is called the @dfn{text interpreter}
4252: (also known as the @dfn{outer interpreter}).
4253: @item
4254: Forth has a very simple syntax, consisting of words and numbers
4255: separated by spaces or carriage-return characters. Any additional syntax
4256: is imposed by @dfn{parsing words}.
4257: @item
4258: Forth uses a stack to pass parameters between words. As a result, it
4259: uses postfix notation.
4260: @item
4261: To use a word that has previously been defined, the text interpreter
4262: searches for the word in the @dfn{name dictionary}.
4263: @item
1.30 anton 4264: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4265: @item
1.29 crook 4266: The text interpreter uses the value of @code{state} to select between
4267: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4268: semantics} of a word that it encounters.
1.28 crook 4269: @item
1.30 anton 4270: The relationship between the @dfn{interpretation semantics} and
4271: @dfn{compilation semantics} for a word
1.29 crook 4272: depend upon the way in which the word was defined (for example, whether
4273: it is an @dfn{immediate} word).
1.28 crook 4274: @item
1.29 crook 4275: Forth definitions can be implemented in Forth (called @dfn{high-level
4276: definitions}) or in some other way (usually a lower-level language and
4277: as a result often called @dfn{low-level definitions}, @dfn{code
4278: definitions} or @dfn{primitives}).
1.28 crook 4279: @item
1.29 crook 4280: Many Forth systems are implemented mainly in Forth.
1.28 crook 4281: @end itemize
4282:
4283:
1.29 crook 4284: @comment ----------------------------------------------
1.48 anton 4285: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4286: @section Where To Go Next
4287: @cindex where to go next
1.28 crook 4288:
1.29 crook 4289: Amazing as it may seem, if you have read (and understood) this far, you
4290: know almost all the fundamentals about the inner workings of a Forth
4291: system. You certainly know enough to be able to read and understand the
4292: rest of this manual and the ANS Forth document, to learn more about the
4293: facilities that Forth in general and Gforth in particular provide. Even
4294: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4295: However, that's not a good idea just yet... better to try writing some
1.29 crook 4296: programs in Gforth.
1.28 crook 4297:
1.29 crook 4298: Forth has such a rich vocabulary that it can be hard to know where to
4299: start in learning it. This section suggests a few sets of words that are
4300: enough to write small but useful programs. Use the word index in this
4301: document to learn more about each word, then try it out and try to write
4302: small definitions using it. Start by experimenting with these words:
1.28 crook 4303:
4304: @itemize @bullet
4305: @item
1.29 crook 4306: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4307: @item
4308: Comparison: @code{MIN MAX =}
4309: @item
4310: Logic: @code{AND OR XOR NOT}
4311: @item
4312: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4313: @item
1.29 crook 4314: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4315: @item
1.29 crook 4316: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4317: @item
1.29 crook 4318: Defining words: @code{: ; CREATE}
1.28 crook 4319: @item
1.29 crook 4320: Memory allocation words: @code{ALLOT ,}
1.28 crook 4321: @item
1.29 crook 4322: Tools: @code{SEE WORDS .S MARKER}
4323: @end itemize
4324:
4325: When you have mastered those, go on to:
4326:
4327: @itemize @bullet
1.28 crook 4328: @item
1.29 crook 4329: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4330: @item
1.29 crook 4331: Memory access: @code{@@ !}
1.28 crook 4332: @end itemize
1.23 crook 4333:
1.29 crook 4334: When you have mastered these, there's nothing for it but to read through
4335: the whole of this manual and find out what you've missed.
4336:
4337: @comment ----------------------------------------------
1.48 anton 4338: @node Exercises, , Where to go next, Introduction
1.29 crook 4339: @section Exercises
4340: @cindex exercises
4341:
4342: TODO: provide a set of programming excercises linked into the stuff done
4343: already and into other sections of the manual. Provide solutions to all
4344: the exercises in a .fs file in the distribution.
4345:
4346: @c Get some inspiration from Starting Forth and Kelly&Spies.
4347:
4348: @c excercises:
4349: @c 1. take inches and convert to feet and inches.
4350: @c 2. take temperature and convert from fahrenheight to celcius;
4351: @c may need to care about symmetric vs floored??
4352: @c 3. take input line and do character substitution
4353: @c to encipher or decipher
4354: @c 4. as above but work on a file for in and out
4355: @c 5. take input line and convert to pig-latin
4356: @c
4357: @c thing of sets of things to exercise then come up with
4358: @c problems that need those things.
4359:
4360:
1.26 crook 4361: @c ******************************************************************
1.29 crook 4362: @node Words, Error messages, Introduction, Top
1.1 anton 4363: @chapter Forth Words
1.26 crook 4364: @cindex words
1.1 anton 4365:
4366: @menu
4367: * Notation::
1.65 anton 4368: * Case insensitivity::
4369: * Comments::
4370: * Boolean Flags::
1.1 anton 4371: * Arithmetic::
4372: * Stack Manipulation::
1.5 anton 4373: * Memory::
1.1 anton 4374: * Control Structures::
4375: * Defining Words::
1.65 anton 4376: * Interpretation and Compilation Semantics::
1.47 crook 4377: * Tokens for Words::
1.81 anton 4378: * Compiling words::
1.65 anton 4379: * The Text Interpreter::
1.111 anton 4380: * The Input Stream::
1.65 anton 4381: * Word Lists::
4382: * Environmental Queries::
1.12 anton 4383: * Files::
4384: * Blocks::
4385: * Other I/O::
1.121 anton 4386: * OS command line arguments::
1.78 anton 4387: * Locals::
4388: * Structures::
4389: * Object-oriented Forth::
1.12 anton 4390: * Programming Tools::
1.150 anton 4391: * C Interface::
1.12 anton 4392: * Assembler and Code Words::
4393: * Threading Words::
1.65 anton 4394: * Passing Commands to the OS::
4395: * Keeping track of Time::
4396: * Miscellaneous Words::
1.1 anton 4397: @end menu
4398:
1.65 anton 4399: @node Notation, Case insensitivity, Words, Words
1.1 anton 4400: @section Notation
4401: @cindex notation of glossary entries
4402: @cindex format of glossary entries
4403: @cindex glossary notation format
4404: @cindex word glossary entry format
4405:
4406: The Forth words are described in this section in the glossary notation
1.67 anton 4407: that has become a de-facto standard for Forth texts:
1.1 anton 4408:
4409: @format
1.29 crook 4410: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4411: @end format
1.29 crook 4412: @i{Description}
1.1 anton 4413:
4414: @table @var
4415: @item word
1.28 crook 4416: The name of the word.
1.1 anton 4417:
4418: @item Stack effect
4419: @cindex stack effect
1.29 crook 4420: The stack effect is written in the notation @code{@i{before} --
4421: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4422: stack entries before and after the execution of the word. The rest of
4423: the stack is not touched by the word. The top of stack is rightmost,
4424: i.e., a stack sequence is written as it is typed in. Note that Gforth
4425: uses a separate floating point stack, but a unified stack
1.29 crook 4426: notation. Also, return stack effects are not shown in @i{stack
4427: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4428: the type and/or the function of the item. See below for a discussion of
4429: the types.
4430:
4431: All words have two stack effects: A compile-time stack effect and a
4432: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4433: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4434: this standard behaviour, or the word does other unusual things at
4435: compile time, both stack effects are shown; otherwise only the run-time
4436: stack effect is shown.
4437:
4438: @cindex pronounciation of words
4439: @item pronunciation
4440: How the word is pronounced.
4441:
4442: @cindex wordset
1.67 anton 4443: @cindex environment wordset
1.1 anton 4444: @item wordset
1.21 crook 4445: The ANS Forth standard is divided into several word sets. A standard
4446: system need not support all of them. Therefore, in theory, the fewer
4447: word sets your program uses the more portable it will be. However, we
4448: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4449: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4450: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4451: describes words that will work in future releases of Gforth;
4452: @code{gforth-internal} words are more volatile. Environmental query
4453: strings are also displayed like words; you can recognize them by the
1.21 crook 4454: @code{environment} in the word set field.
1.1 anton 4455:
4456: @item Description
4457: A description of the behaviour of the word.
4458: @end table
4459:
4460: @cindex types of stack items
4461: @cindex stack item types
4462: The type of a stack item is specified by the character(s) the name
4463: starts with:
4464:
4465: @table @code
4466: @item f
4467: @cindex @code{f}, stack item type
4468: Boolean flags, i.e. @code{false} or @code{true}.
4469: @item c
4470: @cindex @code{c}, stack item type
4471: Char
4472: @item w
4473: @cindex @code{w}, stack item type
4474: Cell, can contain an integer or an address
4475: @item n
4476: @cindex @code{n}, stack item type
4477: signed integer
4478: @item u
4479: @cindex @code{u}, stack item type
4480: unsigned integer
4481: @item d
4482: @cindex @code{d}, stack item type
4483: double sized signed integer
4484: @item ud
4485: @cindex @code{ud}, stack item type
4486: double sized unsigned integer
4487: @item r
4488: @cindex @code{r}, stack item type
4489: Float (on the FP stack)
1.21 crook 4490: @item a-
1.1 anton 4491: @cindex @code{a_}, stack item type
4492: Cell-aligned address
1.21 crook 4493: @item c-
1.1 anton 4494: @cindex @code{c_}, stack item type
4495: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4496: @item f-
1.1 anton 4497: @cindex @code{f_}, stack item type
4498: Float-aligned address
1.21 crook 4499: @item df-
1.1 anton 4500: @cindex @code{df_}, stack item type
4501: Address aligned for IEEE double precision float
1.21 crook 4502: @item sf-
1.1 anton 4503: @cindex @code{sf_}, stack item type
4504: Address aligned for IEEE single precision float
4505: @item xt
4506: @cindex @code{xt}, stack item type
4507: Execution token, same size as Cell
4508: @item wid
4509: @cindex @code{wid}, stack item type
1.21 crook 4510: Word list ID, same size as Cell
1.68 anton 4511: @item ior, wior
4512: @cindex ior type description
4513: @cindex wior type description
4514: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4515: @item f83name
4516: @cindex @code{f83name}, stack item type
4517: Pointer to a name structure
4518: @item "
4519: @cindex @code{"}, stack item type
1.12 anton 4520: string in the input stream (not on the stack). The terminating character
4521: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4522: quotes.
4523: @end table
4524:
1.65 anton 4525: @comment ----------------------------------------------
4526: @node Case insensitivity, Comments, Notation, Words
4527: @section Case insensitivity
4528: @cindex case sensitivity
4529: @cindex upper and lower case
4530:
4531: Gforth is case-insensitive; you can enter definitions and invoke
4532: Standard words using upper, lower or mixed case (however,
4533: @pxref{core-idef, Implementation-defined options, Implementation-defined
4534: options}).
4535:
4536: ANS Forth only @i{requires} implementations to recognise Standard words
4537: when they are typed entirely in upper case. Therefore, a Standard
4538: program must use upper case for all Standard words. You can use whatever
4539: case you like for words that you define, but in a Standard program you
4540: have to use the words in the same case that you defined them.
4541:
4542: Gforth supports case sensitivity through @code{table}s (case-sensitive
4543: wordlists, @pxref{Word Lists}).
4544:
4545: Two people have asked how to convert Gforth to be case-sensitive; while
4546: we think this is a bad idea, you can change all wordlists into tables
4547: like this:
4548:
4549: @example
4550: ' table-find forth-wordlist wordlist-map @ !
4551: @end example
4552:
4553: Note that you now have to type the predefined words in the same case
4554: that we defined them, which are varying. You may want to convert them
4555: to your favourite case before doing this operation (I won't explain how,
4556: because if you are even contemplating doing this, you'd better have
4557: enough knowledge of Forth systems to know this already).
4558:
4559: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4560: @section Comments
1.26 crook 4561: @cindex comments
1.21 crook 4562:
1.29 crook 4563: Forth supports two styles of comment; the traditional @i{in-line} comment,
4564: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4565:
1.44 crook 4566:
1.23 crook 4567: doc-(
1.21 crook 4568: doc-\
1.23 crook 4569: doc-\G
1.21 crook 4570:
1.44 crook 4571:
1.21 crook 4572: @node Boolean Flags, Arithmetic, Comments, Words
4573: @section Boolean Flags
1.26 crook 4574: @cindex Boolean flags
1.21 crook 4575:
4576: A Boolean flag is cell-sized. A cell with all bits clear represents the
4577: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4578: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4579: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4580: @c on and off to Memory?
4581: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4582:
1.21 crook 4583: doc-true
4584: doc-false
1.29 crook 4585: doc-on
4586: doc-off
1.21 crook 4587:
1.44 crook 4588:
1.21 crook 4589: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4590: @section Arithmetic
4591: @cindex arithmetic words
4592:
4593: @cindex division with potentially negative operands
4594: Forth arithmetic is not checked, i.e., you will not hear about integer
4595: overflow on addition or multiplication, you may hear about division by
4596: zero if you are lucky. The operator is written after the operands, but
4597: the operands are still in the original order. I.e., the infix @code{2-1}
4598: corresponds to @code{2 1 -}. Forth offers a variety of division
4599: operators. If you perform division with potentially negative operands,
4600: you do not want to use @code{/} or @code{/mod} with its undefined
4601: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4602: former, @pxref{Mixed precision}).
1.26 crook 4603: @comment TODO discuss the different division forms and the std approach
1.1 anton 4604:
4605: @menu
4606: * Single precision::
1.67 anton 4607: * Double precision:: Double-cell integer arithmetic
1.1 anton 4608: * Bitwise operations::
1.67 anton 4609: * Numeric comparison::
1.29 crook 4610: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4611: * Floating Point::
4612: @end menu
4613:
1.67 anton 4614: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4615: @subsection Single precision
4616: @cindex single precision arithmetic words
4617:
1.67 anton 4618: @c !! cell undefined
4619:
4620: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4621: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4622: treat them. For the rules used by the text interpreter for recognising
4623: single-precision integers see @ref{Number Conversion}.
1.21 crook 4624:
1.67 anton 4625: These words are all defined for signed operands, but some of them also
4626: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4627: @code{*}.
1.44 crook 4628:
1.1 anton 4629: doc-+
1.21 crook 4630: doc-1+
1.128 anton 4631: doc-under+
1.1 anton 4632: doc--
1.21 crook 4633: doc-1-
1.1 anton 4634: doc-*
4635: doc-/
4636: doc-mod
4637: doc-/mod
4638: doc-negate
4639: doc-abs
4640: doc-min
4641: doc-max
1.27 crook 4642: doc-floored
1.1 anton 4643:
1.44 crook 4644:
1.67 anton 4645: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4646: @subsection Double precision
4647: @cindex double precision arithmetic words
4648:
1.49 anton 4649: For the rules used by the text interpreter for
4650: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4651:
4652: A double precision number is represented by a cell pair, with the most
1.67 anton 4653: significant cell at the TOS. It is trivial to convert an unsigned single
4654: to a double: simply push a @code{0} onto the TOS. Since numbers are
4655: represented by Gforth using 2's complement arithmetic, converting a
4656: signed single to a (signed) double requires sign-extension across the
4657: most significant cell. This can be achieved using @code{s>d}. The moral
4658: of the story is that you cannot convert a number without knowing whether
4659: it represents an unsigned or a signed number.
1.21 crook 4660:
1.67 anton 4661: These words are all defined for signed operands, but some of them also
4662: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4663:
1.21 crook 4664: doc-s>d
1.67 anton 4665: doc-d>s
1.21 crook 4666: doc-d+
4667: doc-d-
4668: doc-dnegate
4669: doc-dabs
4670: doc-dmin
4671: doc-dmax
4672:
1.44 crook 4673:
1.67 anton 4674: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4675: @subsection Bitwise operations
4676: @cindex bitwise operation words
4677:
4678:
4679: doc-and
4680: doc-or
4681: doc-xor
4682: doc-invert
4683: doc-lshift
4684: doc-rshift
4685: doc-2*
4686: doc-d2*
4687: doc-2/
4688: doc-d2/
4689:
4690:
4691: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4692: @subsection Numeric comparison
4693: @cindex numeric comparison words
4694:
1.67 anton 4695: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4696: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4697:
1.28 crook 4698: doc-<
4699: doc-<=
4700: doc-<>
4701: doc-=
4702: doc->
4703: doc->=
4704:
1.21 crook 4705: doc-0<
1.23 crook 4706: doc-0<=
1.21 crook 4707: doc-0<>
4708: doc-0=
1.23 crook 4709: doc-0>
4710: doc-0>=
1.28 crook 4711:
4712: doc-u<
4713: doc-u<=
1.44 crook 4714: @c u<> and u= exist but are the same as <> and =
1.31 anton 4715: @c doc-u<>
4716: @c doc-u=
1.28 crook 4717: doc-u>
4718: doc-u>=
4719:
4720: doc-within
4721:
4722: doc-d<
4723: doc-d<=
4724: doc-d<>
4725: doc-d=
4726: doc-d>
4727: doc-d>=
1.23 crook 4728:
1.21 crook 4729: doc-d0<
1.23 crook 4730: doc-d0<=
4731: doc-d0<>
1.21 crook 4732: doc-d0=
1.23 crook 4733: doc-d0>
4734: doc-d0>=
4735:
1.21 crook 4736: doc-du<
1.28 crook 4737: doc-du<=
1.44 crook 4738: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4739: @c doc-du<>
4740: @c doc-du=
1.28 crook 4741: doc-du>
4742: doc-du>=
1.1 anton 4743:
1.44 crook 4744:
1.21 crook 4745: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4746: @subsection Mixed precision
4747: @cindex mixed precision arithmetic words
4748:
1.44 crook 4749:
1.1 anton 4750: doc-m+
4751: doc-*/
4752: doc-*/mod
4753: doc-m*
4754: doc-um*
4755: doc-m*/
4756: doc-um/mod
4757: doc-fm/mod
4758: doc-sm/rem
4759:
1.44 crook 4760:
1.21 crook 4761: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4762: @subsection Floating Point
4763: @cindex floating point arithmetic words
4764:
1.49 anton 4765: For the rules used by the text interpreter for
4766: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4767:
1.67 anton 4768: Gforth has a separate floating point stack, but the documentation uses
4769: the unified notation.@footnote{It's easy to generate the separate
4770: notation from that by just separating the floating-point numbers out:
4771: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4772: r3 )}.}
1.1 anton 4773:
4774: @cindex floating-point arithmetic, pitfalls
4775: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4776: unwary (e.g., floating point addition is not associative) and even a
4777: few for the wary. You should not use them unless you know what you are
4778: doing or you don't care that the results you get are totally bogus. If
4779: you want to learn about the problems of floating point numbers (and
4780: how to avoid them), you might start with @cite{David Goldberg,
4781: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4782: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4783: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4784:
1.44 crook 4785:
1.21 crook 4786: doc-d>f
4787: doc-f>d
1.1 anton 4788: doc-f+
4789: doc-f-
4790: doc-f*
4791: doc-f/
4792: doc-fnegate
4793: doc-fabs
4794: doc-fmax
4795: doc-fmin
4796: doc-floor
4797: doc-fround
4798: doc-f**
4799: doc-fsqrt
4800: doc-fexp
4801: doc-fexpm1
4802: doc-fln
4803: doc-flnp1
4804: doc-flog
4805: doc-falog
1.32 anton 4806: doc-f2*
4807: doc-f2/
4808: doc-1/f
4809: doc-precision
4810: doc-set-precision
4811:
4812: @cindex angles in trigonometric operations
4813: @cindex trigonometric operations
4814: Angles in floating point operations are given in radians (a full circle
4815: has 2 pi radians).
4816:
1.1 anton 4817: doc-fsin
4818: doc-fcos
4819: doc-fsincos
4820: doc-ftan
4821: doc-fasin
4822: doc-facos
4823: doc-fatan
4824: doc-fatan2
4825: doc-fsinh
4826: doc-fcosh
4827: doc-ftanh
4828: doc-fasinh
4829: doc-facosh
4830: doc-fatanh
1.21 crook 4831: doc-pi
1.28 crook 4832:
1.32 anton 4833: @cindex equality of floats
4834: @cindex floating-point comparisons
1.31 anton 4835: One particular problem with floating-point arithmetic is that comparison
4836: for equality often fails when you would expect it to succeed. For this
4837: reason approximate equality is often preferred (but you still have to
1.67 anton 4838: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4839: differently from what you might expect. The comparison words are:
1.31 anton 4840:
4841: doc-f~rel
4842: doc-f~abs
1.68 anton 4843: doc-f~
1.31 anton 4844: doc-f=
4845: doc-f<>
4846:
4847: doc-f<
4848: doc-f<=
4849: doc-f>
4850: doc-f>=
4851:
1.21 crook 4852: doc-f0<
1.28 crook 4853: doc-f0<=
4854: doc-f0<>
1.21 crook 4855: doc-f0=
1.28 crook 4856: doc-f0>
4857: doc-f0>=
4858:
1.1 anton 4859:
4860: @node Stack Manipulation, Memory, Arithmetic, Words
4861: @section Stack Manipulation
4862: @cindex stack manipulation words
4863:
4864: @cindex floating-point stack in the standard
1.21 crook 4865: Gforth maintains a number of separate stacks:
4866:
1.29 crook 4867: @cindex data stack
4868: @cindex parameter stack
1.21 crook 4869: @itemize @bullet
4870: @item
1.29 crook 4871: A data stack (also known as the @dfn{parameter stack}) -- for
4872: characters, cells, addresses, and double cells.
1.21 crook 4873:
1.29 crook 4874: @cindex floating-point stack
1.21 crook 4875: @item
1.44 crook 4876: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4877:
1.29 crook 4878: @cindex return stack
1.21 crook 4879: @item
1.44 crook 4880: A return stack -- for holding the return addresses of colon
1.32 anton 4881: definitions and other (non-FP) data.
1.21 crook 4882:
1.29 crook 4883: @cindex locals stack
1.21 crook 4884: @item
1.44 crook 4885: A locals stack -- for holding local variables.
1.21 crook 4886: @end itemize
4887:
1.1 anton 4888: @menu
4889: * Data stack::
4890: * Floating point stack::
4891: * Return stack::
4892: * Locals stack::
4893: * Stack pointer manipulation::
4894: @end menu
4895:
4896: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4897: @subsection Data stack
4898: @cindex data stack manipulation words
4899: @cindex stack manipulations words, data stack
4900:
1.44 crook 4901:
1.1 anton 4902: doc-drop
4903: doc-nip
4904: doc-dup
4905: doc-over
4906: doc-tuck
4907: doc-swap
1.21 crook 4908: doc-pick
1.1 anton 4909: doc-rot
4910: doc--rot
4911: doc-?dup
4912: doc-roll
4913: doc-2drop
4914: doc-2nip
4915: doc-2dup
4916: doc-2over
4917: doc-2tuck
4918: doc-2swap
4919: doc-2rot
4920:
1.44 crook 4921:
1.1 anton 4922: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4923: @subsection Floating point stack
4924: @cindex floating-point stack manipulation words
4925: @cindex stack manipulation words, floating-point stack
4926:
1.32 anton 4927: Whilst every sane Forth has a separate floating-point stack, it is not
4928: strictly required; an ANS Forth system could theoretically keep
4929: floating-point numbers on the data stack. As an additional difficulty,
4930: you don't know how many cells a floating-point number takes. It is
4931: reportedly possible to write words in a way that they work also for a
4932: unified stack model, but we do not recommend trying it. Instead, just
4933: say that your program has an environmental dependency on a separate
4934: floating-point stack.
4935:
4936: doc-floating-stack
4937:
1.1 anton 4938: doc-fdrop
4939: doc-fnip
4940: doc-fdup
4941: doc-fover
4942: doc-ftuck
4943: doc-fswap
1.21 crook 4944: doc-fpick
1.1 anton 4945: doc-frot
4946:
1.44 crook 4947:
1.1 anton 4948: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4949: @subsection Return stack
4950: @cindex return stack manipulation words
4951: @cindex stack manipulation words, return stack
4952:
1.32 anton 4953: @cindex return stack and locals
4954: @cindex locals and return stack
4955: A Forth system is allowed to keep local variables on the
4956: return stack. This is reasonable, as local variables usually eliminate
4957: the need to use the return stack explicitly. So, if you want to produce
4958: a standard compliant program and you are using local variables in a
4959: word, forget about return stack manipulations in that word (refer to the
4960: standard document for the exact rules).
4961:
1.1 anton 4962: doc->r
4963: doc-r>
4964: doc-r@
4965: doc-rdrop
4966: doc-2>r
4967: doc-2r>
4968: doc-2r@
4969: doc-2rdrop
4970:
1.44 crook 4971:
1.1 anton 4972: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4973: @subsection Locals stack
4974:
1.78 anton 4975: Gforth uses an extra locals stack. It is described, along with the
4976: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4977:
1.1 anton 4978: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4979: @subsection Stack pointer manipulation
4980: @cindex stack pointer manipulation words
4981:
1.44 crook 4982: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4983: doc-sp0
1.1 anton 4984: doc-sp@
4985: doc-sp!
1.21 crook 4986: doc-fp0
1.1 anton 4987: doc-fp@
4988: doc-fp!
1.21 crook 4989: doc-rp0
1.1 anton 4990: doc-rp@
4991: doc-rp!
1.21 crook 4992: doc-lp0
1.1 anton 4993: doc-lp@
4994: doc-lp!
4995:
1.44 crook 4996:
1.1 anton 4997: @node Memory, Control Structures, Stack Manipulation, Words
4998: @section Memory
1.26 crook 4999: @cindex memory words
1.1 anton 5000:
1.32 anton 5001: @menu
5002: * Memory model::
5003: * Dictionary allocation::
5004: * Heap Allocation::
5005: * Memory Access::
5006: * Address arithmetic::
5007: * Memory Blocks::
5008: @end menu
5009:
1.67 anton 5010: In addition to the standard Forth memory allocation words, there is also
5011: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5012: garbage collector}.
5013:
1.32 anton 5014: @node Memory model, Dictionary allocation, Memory, Memory
5015: @subsection ANS Forth and Gforth memory models
5016:
5017: @c The ANS Forth description is a mess (e.g., is the heap part of
5018: @c the dictionary?), so let's not stick to closely with it.
5019:
1.67 anton 5020: ANS Forth considers a Forth system as consisting of several address
5021: spaces, of which only @dfn{data space} is managed and accessible with
5022: the memory words. Memory not necessarily in data space includes the
5023: stacks, the code (called code space) and the headers (called name
5024: space). In Gforth everything is in data space, but the code for the
5025: primitives is usually read-only.
1.32 anton 5026:
5027: Data space is divided into a number of areas: The (data space portion of
5028: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5029: refer to the search data structure embodied in word lists and headers,
5030: because it is used for looking up names, just as you would in a
5031: conventional dictionary.}, the heap, and a number of system-allocated
5032: buffers.
5033:
1.68 anton 5034: @cindex address arithmetic restrictions, ANS vs. Gforth
5035: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5036: In ANS Forth data space is also divided into contiguous regions. You
5037: can only use address arithmetic within a contiguous region, not between
5038: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5039: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5040: allocation}).
5041:
5042: Gforth provides one big address space, and address arithmetic can be
5043: performed between any addresses. However, in the dictionary headers or
5044: code are interleaved with data, so almost the only contiguous data space
5045: regions there are those described by ANS Forth as contiguous; but you
5046: can be sure that the dictionary is allocated towards increasing
5047: addresses even between contiguous regions. The memory order of
5048: allocations in the heap is platform-dependent (and possibly different
5049: from one run to the next).
5050:
1.27 crook 5051:
1.32 anton 5052: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5053: @subsection Dictionary allocation
1.27 crook 5054: @cindex reserving data space
5055: @cindex data space - reserving some
5056:
1.32 anton 5057: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5058: you want to deallocate X, you also deallocate everything
5059: allocated after X.
5060:
1.68 anton 5061: @cindex contiguous regions in dictionary allocation
1.32 anton 5062: The allocations using the words below are contiguous and grow the region
5063: towards increasing addresses. Other words that allocate dictionary
5064: memory of any kind (i.e., defining words including @code{:noname}) end
5065: the contiguous region and start a new one.
5066:
5067: In ANS Forth only @code{create}d words are guaranteed to produce an
5068: address that is the start of the following contiguous region. In
5069: particular, the cell allocated by @code{variable} is not guaranteed to
5070: be contiguous with following @code{allot}ed memory.
5071:
5072: You can deallocate memory by using @code{allot} with a negative argument
5073: (with some restrictions, see @code{allot}). For larger deallocations use
5074: @code{marker}.
1.27 crook 5075:
1.29 crook 5076:
1.27 crook 5077: doc-here
5078: doc-unused
5079: doc-allot
5080: doc-c,
1.29 crook 5081: doc-f,
1.27 crook 5082: doc-,
5083: doc-2,
5084:
1.32 anton 5085: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5086: course you should allocate memory in an aligned way, too. I.e., before
5087: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5088: The words below align @code{here} if it is not already. Basically it is
5089: only already aligned for a type, if the last allocation was a multiple
5090: of the size of this type and if @code{here} was aligned for this type
5091: before.
5092:
5093: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5094: ANS Forth (@code{maxalign}ed in Gforth).
5095:
5096: doc-align
5097: doc-falign
5098: doc-sfalign
5099: doc-dfalign
5100: doc-maxalign
5101: doc-cfalign
5102:
5103:
5104: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5105: @subsection Heap allocation
5106: @cindex heap allocation
5107: @cindex dynamic allocation of memory
5108: @cindex memory-allocation word set
5109:
1.68 anton 5110: @cindex contiguous regions and heap allocation
1.32 anton 5111: Heap allocation supports deallocation of allocated memory in any
5112: order. Dictionary allocation is not affected by it (i.e., it does not
5113: end a contiguous region). In Gforth, these words are implemented using
5114: the standard C library calls malloc(), free() and resize().
5115:
1.68 anton 5116: The memory region produced by one invocation of @code{allocate} or
5117: @code{resize} is internally contiguous. There is no contiguity between
5118: such a region and any other region (including others allocated from the
5119: heap).
5120:
1.32 anton 5121: doc-allocate
5122: doc-free
5123: doc-resize
5124:
1.27 crook 5125:
1.32 anton 5126: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5127: @subsection Memory Access
5128: @cindex memory access words
5129:
5130: doc-@
5131: doc-!
5132: doc-+!
5133: doc-c@
5134: doc-c!
5135: doc-2@
5136: doc-2!
5137: doc-f@
5138: doc-f!
5139: doc-sf@
5140: doc-sf!
5141: doc-df@
5142: doc-df!
1.144 anton 5143: doc-sw@
5144: doc-uw@
5145: doc-w!
5146: doc-sl@
5147: doc-ul@
5148: doc-l!
1.68 anton 5149:
1.32 anton 5150: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5151: @subsection Address arithmetic
1.1 anton 5152: @cindex address arithmetic words
5153:
1.67 anton 5154: Address arithmetic is the foundation on which you can build data
5155: structures like arrays, records (@pxref{Structures}) and objects
5156: (@pxref{Object-oriented Forth}).
1.32 anton 5157:
1.68 anton 5158: @cindex address unit
5159: @cindex au (address unit)
1.1 anton 5160: ANS Forth does not specify the sizes of the data types. Instead, it
5161: offers a number of words for computing sizes and doing address
1.29 crook 5162: arithmetic. Address arithmetic is performed in terms of address units
5163: (aus); on most systems the address unit is one byte. Note that a
5164: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5165: platforms where it is a noop, it compiles to nothing).
1.1 anton 5166:
1.67 anton 5167: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5168: you have the address of a cell, perform @code{1 cells +}, and you will
5169: have the address of the next cell.
5170:
1.68 anton 5171: @cindex contiguous regions and address arithmetic
1.67 anton 5172: In ANS Forth you can perform address arithmetic only within a contiguous
5173: region, i.e., if you have an address into one region, you can only add
5174: and subtract such that the result is still within the region; you can
5175: only subtract or compare addresses from within the same contiguous
5176: region. Reasons: several contiguous regions can be arranged in memory
5177: in any way; on segmented systems addresses may have unusual
5178: representations, such that address arithmetic only works within a
5179: region. Gforth provides a few more guarantees (linear address space,
5180: dictionary grows upwards), but in general I have found it easy to stay
5181: within contiguous regions (exception: computing and comparing to the
5182: address just beyond the end of an array).
5183:
1.1 anton 5184: @cindex alignment of addresses for types
5185: ANS Forth also defines words for aligning addresses for specific
5186: types. Many computers require that accesses to specific data types
5187: must only occur at specific addresses; e.g., that cells may only be
5188: accessed at addresses divisible by 4. Even if a machine allows unaligned
5189: accesses, it can usually perform aligned accesses faster.
5190:
5191: For the performance-conscious: alignment operations are usually only
5192: necessary during the definition of a data structure, not during the
5193: (more frequent) accesses to it.
5194:
5195: ANS Forth defines no words for character-aligning addresses. This is not
5196: an oversight, but reflects the fact that addresses that are not
5197: char-aligned have no use in the standard and therefore will not be
5198: created.
5199:
5200: @cindex @code{CREATE} and alignment
1.29 crook 5201: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5202: are cell-aligned; in addition, Gforth guarantees that these addresses
5203: are aligned for all purposes.
5204:
1.26 crook 5205: Note that the ANS Forth word @code{char} has nothing to do with address
5206: arithmetic.
1.1 anton 5207:
1.44 crook 5208:
1.1 anton 5209: doc-chars
5210: doc-char+
5211: doc-cells
5212: doc-cell+
5213: doc-cell
5214: doc-aligned
5215: doc-floats
5216: doc-float+
5217: doc-float
5218: doc-faligned
5219: doc-sfloats
5220: doc-sfloat+
5221: doc-sfaligned
5222: doc-dfloats
5223: doc-dfloat+
5224: doc-dfaligned
5225: doc-maxaligned
5226: doc-cfaligned
5227: doc-address-unit-bits
1.145 anton 5228: doc-/w
5229: doc-/l
1.44 crook 5230:
1.32 anton 5231: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5232: @subsection Memory Blocks
5233: @cindex memory block words
1.27 crook 5234: @cindex character strings - moving and copying
5235:
1.49 anton 5236: Memory blocks often represent character strings; For ways of storing
5237: character strings in memory see @ref{String Formats}. For other
5238: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5239:
1.67 anton 5240: A few of these words work on address unit blocks. In that case, you
5241: usually have to insert @code{CHARS} before the word when working on
5242: character strings. Most words work on character blocks, and expect a
5243: char-aligned address.
5244:
5245: When copying characters between overlapping memory regions, use
5246: @code{chars move} or choose carefully between @code{cmove} and
5247: @code{cmove>}.
1.44 crook 5248:
1.1 anton 5249: doc-move
5250: doc-erase
5251: doc-cmove
5252: doc-cmove>
5253: doc-fill
5254: doc-blank
1.21 crook 5255: doc-compare
1.111 anton 5256: doc-str=
5257: doc-str<
5258: doc-string-prefix?
1.21 crook 5259: doc-search
1.27 crook 5260: doc--trailing
5261: doc-/string
1.82 anton 5262: doc-bounds
1.141 anton 5263: doc-pad
1.111 anton 5264:
1.27 crook 5265: @comment TODO examples
5266:
1.1 anton 5267:
1.26 crook 5268: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5269: @section Control Structures
5270: @cindex control structures
5271:
1.33 anton 5272: Control structures in Forth cannot be used interpretively, only in a
5273: colon definition@footnote{To be precise, they have no interpretation
5274: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5275: not like this limitation, but have not seen a satisfying way around it
5276: yet, although many schemes have been proposed.
1.1 anton 5277:
5278: @menu
1.33 anton 5279: * Selection:: IF ... ELSE ... ENDIF
5280: * Simple Loops:: BEGIN ...
1.29 crook 5281: * Counted Loops:: DO
1.67 anton 5282: * Arbitrary control structures::
5283: * Calls and returns::
1.1 anton 5284: * Exception Handling::
5285: @end menu
5286:
5287: @node Selection, Simple Loops, Control Structures, Control Structures
5288: @subsection Selection
5289: @cindex selection control structures
5290: @cindex control structures for selection
5291:
5292: @cindex @code{IF} control structure
5293: @example
1.29 crook 5294: @i{flag}
1.1 anton 5295: IF
1.29 crook 5296: @i{code}
1.1 anton 5297: ENDIF
5298: @end example
1.21 crook 5299: @noindent
1.33 anton 5300:
1.44 crook 5301: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5302: with any bit set represents truth) @i{code} is executed.
1.33 anton 5303:
1.1 anton 5304: @example
1.29 crook 5305: @i{flag}
1.1 anton 5306: IF
1.29 crook 5307: @i{code1}
1.1 anton 5308: ELSE
1.29 crook 5309: @i{code2}
1.1 anton 5310: ENDIF
5311: @end example
5312:
1.44 crook 5313: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5314: executed.
1.33 anton 5315:
1.1 anton 5316: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5317: standard, and @code{ENDIF} is not, although it is quite popular. We
5318: recommend using @code{ENDIF}, because it is less confusing for people
5319: who also know other languages (and is not prone to reinforcing negative
5320: prejudices against Forth in these people). Adding @code{ENDIF} to a
5321: system that only supplies @code{THEN} is simple:
5322: @example
1.82 anton 5323: : ENDIF POSTPONE then ; immediate
1.1 anton 5324: @end example
5325:
5326: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5327: (adv.)} has the following meanings:
5328: @quotation
5329: ... 2b: following next after in order ... 3d: as a necessary consequence
5330: (if you were there, then you saw them).
5331: @end quotation
5332: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5333: and many other programming languages has the meaning 3d.]
5334:
1.21 crook 5335: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5336: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5337: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5338: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5339: @file{compat/control.fs}.
5340:
5341: @cindex @code{CASE} control structure
5342: @example
1.29 crook 5343: @i{n}
1.1 anton 5344: CASE
1.29 crook 5345: @i{n1} OF @i{code1} ENDOF
5346: @i{n2} OF @i{code2} ENDOF
1.1 anton 5347: @dots{}
1.68 anton 5348: ( n ) @i{default-code} ( n )
1.131 anton 5349: ENDCASE ( )
1.1 anton 5350: @end example
5351:
1.131 anton 5352: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If
5353: no @i{ni} matches, the optional @i{default-code} is executed. The
5354: optional default case can be added by simply writing the code after
5355: the last @code{ENDOF}. It may use @i{n}, which is on top of the stack,
5356: but must not consume it. The value @i{n} is consumed by this
5357: construction (either by a OF that matches, or by the ENDCASE, if no OF
5358: matches).
1.1 anton 5359:
1.69 anton 5360: @progstyle
1.131 anton 5361: To keep the code understandable, you should ensure that you change the
5362: stack in the same way (wrt. number and types of stack items consumed
5363: and pushed) on all paths through a selection construct.
1.69 anton 5364:
1.1 anton 5365: @node Simple Loops, Counted Loops, Selection, Control Structures
5366: @subsection Simple Loops
5367: @cindex simple loops
5368: @cindex loops without count
5369:
5370: @cindex @code{WHILE} loop
5371: @example
5372: BEGIN
1.29 crook 5373: @i{code1}
5374: @i{flag}
1.1 anton 5375: WHILE
1.29 crook 5376: @i{code2}
1.1 anton 5377: REPEAT
5378: @end example
5379:
1.29 crook 5380: @i{code1} is executed and @i{flag} is computed. If it is true,
5381: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5382: false, execution continues after the @code{REPEAT}.
5383:
5384: @cindex @code{UNTIL} loop
5385: @example
5386: BEGIN
1.29 crook 5387: @i{code}
5388: @i{flag}
1.1 anton 5389: UNTIL
5390: @end example
5391:
1.29 crook 5392: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5393:
1.69 anton 5394: @progstyle
5395: To keep the code understandable, a complete iteration of the loop should
5396: not change the number and types of the items on the stacks.
5397:
1.1 anton 5398: @cindex endless loop
5399: @cindex loops, endless
5400: @example
5401: BEGIN
1.29 crook 5402: @i{code}
1.1 anton 5403: AGAIN
5404: @end example
5405:
5406: This is an endless loop.
5407:
5408: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5409: @subsection Counted Loops
5410: @cindex counted loops
5411: @cindex loops, counted
5412: @cindex @code{DO} loops
5413:
5414: The basic counted loop is:
5415: @example
1.29 crook 5416: @i{limit} @i{start}
1.1 anton 5417: ?DO
1.29 crook 5418: @i{body}
1.1 anton 5419: LOOP
5420: @end example
5421:
1.29 crook 5422: This performs one iteration for every integer, starting from @i{start}
5423: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5424: accessed with @code{i}. For example, the loop:
1.1 anton 5425: @example
5426: 10 0 ?DO
5427: i .
5428: LOOP
5429: @end example
1.21 crook 5430: @noindent
5431: prints @code{0 1 2 3 4 5 6 7 8 9}
5432:
1.1 anton 5433: The index of the innermost loop can be accessed with @code{i}, the index
5434: of the next loop with @code{j}, and the index of the third loop with
5435: @code{k}.
5436:
1.44 crook 5437:
1.1 anton 5438: doc-i
5439: doc-j
5440: doc-k
5441:
1.44 crook 5442:
1.1 anton 5443: The loop control data are kept on the return stack, so there are some
1.21 crook 5444: restrictions on mixing return stack accesses and counted loop words. In
5445: particuler, if you put values on the return stack outside the loop, you
5446: cannot read them inside the loop@footnote{well, not in a way that is
5447: portable.}. If you put values on the return stack within a loop, you
5448: have to remove them before the end of the loop and before accessing the
5449: index of the loop.
1.1 anton 5450:
5451: There are several variations on the counted loop:
5452:
1.21 crook 5453: @itemize @bullet
5454: @item
5455: @code{LEAVE} leaves the innermost counted loop immediately; execution
5456: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5457:
5458: @example
5459: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5460: @end example
5461: prints @code{0 1 2 3}
5462:
1.1 anton 5463:
1.21 crook 5464: @item
5465: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5466: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5467: return stack so @code{EXIT} can get to its return address. For example:
5468:
5469: @example
5470: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5471: @end example
5472: prints @code{0 1 2 3}
5473:
5474:
5475: @item
1.29 crook 5476: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5477: (and @code{LOOP} iterates until they become equal by wrap-around
5478: arithmetic). This behaviour is usually not what you want. Therefore,
5479: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5480: @code{?DO}), which do not enter the loop if @i{start} is greater than
5481: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5482: unsigned loop parameters.
5483:
1.21 crook 5484: @item
5485: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5486: the loop, independent of the loop parameters. Do not use @code{DO}, even
5487: if you know that the loop is entered in any case. Such knowledge tends
5488: to become invalid during maintenance of a program, and then the
5489: @code{DO} will make trouble.
5490:
5491: @item
1.29 crook 5492: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5493: index by @i{n} instead of by 1. The loop is terminated when the border
5494: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5495:
1.21 crook 5496: @example
5497: 4 0 +DO i . 2 +LOOP
5498: @end example
5499: @noindent
5500: prints @code{0 2}
5501:
5502: @example
5503: 4 1 +DO i . 2 +LOOP
5504: @end example
5505: @noindent
5506: prints @code{1 3}
1.1 anton 5507:
1.68 anton 5508: @item
1.1 anton 5509: @cindex negative increment for counted loops
5510: @cindex counted loops with negative increment
1.29 crook 5511: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5512:
1.21 crook 5513: @example
5514: -1 0 ?DO i . -1 +LOOP
5515: @end example
5516: @noindent
5517: prints @code{0 -1}
1.1 anton 5518:
1.21 crook 5519: @example
5520: 0 0 ?DO i . -1 +LOOP
5521: @end example
5522: prints nothing.
1.1 anton 5523:
1.29 crook 5524: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5525: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5526: index by @i{u} each iteration. The loop is terminated when the border
5527: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5528: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5529:
1.21 crook 5530: @example
5531: -2 0 -DO i . 1 -LOOP
5532: @end example
5533: @noindent
5534: prints @code{0 -1}
1.1 anton 5535:
1.21 crook 5536: @example
5537: -1 0 -DO i . 1 -LOOP
5538: @end example
5539: @noindent
5540: prints @code{0}
5541:
5542: @example
5543: 0 0 -DO i . 1 -LOOP
5544: @end example
5545: @noindent
5546: prints nothing.
1.1 anton 5547:
1.21 crook 5548: @end itemize
1.1 anton 5549:
5550: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5551: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5552: for these words that uses only standard words is provided in
5553: @file{compat/loops.fs}.
1.1 anton 5554:
5555:
5556: @cindex @code{FOR} loops
1.26 crook 5557: Another counted loop is:
1.1 anton 5558: @example
1.29 crook 5559: @i{n}
1.1 anton 5560: FOR
1.29 crook 5561: @i{body}
1.1 anton 5562: NEXT
5563: @end example
5564: This is the preferred loop of native code compiler writers who are too
1.26 crook 5565: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5566: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5567: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5568: Forth systems may behave differently, even if they support @code{FOR}
5569: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5570:
5571: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5572: @subsection Arbitrary control structures
5573: @cindex control structures, user-defined
5574:
5575: @cindex control-flow stack
5576: ANS Forth permits and supports using control structures in a non-nested
5577: way. Information about incomplete control structures is stored on the
5578: control-flow stack. This stack may be implemented on the Forth data
5579: stack, and this is what we have done in Gforth.
5580:
5581: @cindex @code{orig}, control-flow stack item
5582: @cindex @code{dest}, control-flow stack item
5583: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5584: entry represents a backward branch target. A few words are the basis for
5585: building any control structure possible (except control structures that
5586: need storage, like calls, coroutines, and backtracking).
5587:
1.44 crook 5588:
1.1 anton 5589: doc-if
5590: doc-ahead
5591: doc-then
5592: doc-begin
5593: doc-until
5594: doc-again
5595: doc-cs-pick
5596: doc-cs-roll
5597:
1.44 crook 5598:
1.21 crook 5599: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5600: manipulate the control-flow stack in a portable way. Without them, you
5601: would need to know how many stack items are occupied by a control-flow
5602: entry (many systems use one cell. In Gforth they currently take three,
5603: but this may change in the future).
5604:
1.1 anton 5605: Some standard control structure words are built from these words:
5606:
1.44 crook 5607:
1.1 anton 5608: doc-else
5609: doc-while
5610: doc-repeat
5611:
1.44 crook 5612:
5613: @noindent
1.1 anton 5614: Gforth adds some more control-structure words:
5615:
1.44 crook 5616:
1.1 anton 5617: doc-endif
5618: doc-?dup-if
5619: doc-?dup-0=-if
5620:
1.44 crook 5621:
5622: @noindent
1.1 anton 5623: Counted loop words constitute a separate group of words:
5624:
1.44 crook 5625:
1.1 anton 5626: doc-?do
5627: doc-+do
5628: doc-u+do
5629: doc--do
5630: doc-u-do
5631: doc-do
5632: doc-for
5633: doc-loop
5634: doc-+loop
5635: doc--loop
5636: doc-next
5637: doc-leave
5638: doc-?leave
5639: doc-unloop
5640: doc-done
5641:
1.44 crook 5642:
1.21 crook 5643: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5644: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5645: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5646: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5647: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5648: resolved (by using one of the loop-ending words or @code{DONE}).
5649:
1.44 crook 5650: @noindent
1.26 crook 5651: Another group of control structure words are:
1.1 anton 5652:
1.44 crook 5653:
1.1 anton 5654: doc-case
5655: doc-endcase
5656: doc-of
5657: doc-endof
5658:
1.44 crook 5659:
1.21 crook 5660: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5661: @code{CS-ROLL}.
1.1 anton 5662:
5663: @subsubsection Programming Style
1.47 crook 5664: @cindex control structures programming style
5665: @cindex programming style, arbitrary control structures
1.1 anton 5666:
5667: In order to ensure readability we recommend that you do not create
5668: arbitrary control structures directly, but define new control structure
5669: words for the control structure you want and use these words in your
1.26 crook 5670: program. For example, instead of writing:
1.1 anton 5671:
5672: @example
1.26 crook 5673: BEGIN
1.1 anton 5674: ...
1.26 crook 5675: IF [ 1 CS-ROLL ]
1.1 anton 5676: ...
1.26 crook 5677: AGAIN THEN
1.1 anton 5678: @end example
5679:
1.21 crook 5680: @noindent
1.1 anton 5681: we recommend defining control structure words, e.g.,
5682:
5683: @example
1.26 crook 5684: : WHILE ( DEST -- ORIG DEST )
5685: POSTPONE IF
5686: 1 CS-ROLL ; immediate
5687:
5688: : REPEAT ( orig dest -- )
5689: POSTPONE AGAIN
5690: POSTPONE THEN ; immediate
1.1 anton 5691: @end example
5692:
1.21 crook 5693: @noindent
1.1 anton 5694: and then using these to create the control structure:
5695:
5696: @example
1.26 crook 5697: BEGIN
1.1 anton 5698: ...
1.26 crook 5699: WHILE
1.1 anton 5700: ...
1.26 crook 5701: REPEAT
1.1 anton 5702: @end example
5703:
5704: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5705: @code{WHILE} are predefined, so in this example it would not be
5706: necessary to define them.
5707:
5708: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5709: @subsection Calls and returns
5710: @cindex calling a definition
5711: @cindex returning from a definition
5712:
1.3 anton 5713: @cindex recursive definitions
5714: A definition can be called simply be writing the name of the definition
1.26 crook 5715: to be called. Normally a definition is invisible during its own
1.3 anton 5716: definition. If you want to write a directly recursive definition, you
1.26 crook 5717: can use @code{recursive} to make the current definition visible, or
5718: @code{recurse} to call the current definition directly.
1.3 anton 5719:
1.44 crook 5720:
1.3 anton 5721: doc-recursive
5722: doc-recurse
5723:
1.44 crook 5724:
1.21 crook 5725: @comment TODO add example of the two recursion methods
1.12 anton 5726: @quotation
5727: @progstyle
5728: I prefer using @code{recursive} to @code{recurse}, because calling the
5729: definition by name is more descriptive (if the name is well-chosen) than
5730: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5731: implementation, it is much better to read (and think) ``now sort the
5732: partitions'' than to read ``now do a recursive call''.
5733: @end quotation
1.3 anton 5734:
1.29 crook 5735: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5736:
5737: @example
1.28 crook 5738: Defer foo
1.3 anton 5739:
5740: : bar ( ... -- ... )
5741: ... foo ... ;
5742:
5743: :noname ( ... -- ... )
5744: ... bar ... ;
5745: IS foo
5746: @end example
5747:
1.170 pazsan 5748: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5749:
1.26 crook 5750: The current definition returns control to the calling definition when
1.33 anton 5751: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5752:
5753: doc-exit
5754: doc-;s
5755:
1.44 crook 5756:
1.1 anton 5757: @node Exception Handling, , Calls and returns, Control Structures
5758: @subsection Exception Handling
1.26 crook 5759: @cindex exceptions
1.1 anton 5760:
1.68 anton 5761: @c quit is a very bad idea for error handling,
5762: @c because it does not translate into a THROW
5763: @c it also does not belong into this chapter
5764:
5765: If a word detects an error condition that it cannot handle, it can
5766: @code{throw} an exception. In the simplest case, this will terminate
5767: your program, and report an appropriate error.
1.21 crook 5768:
1.68 anton 5769: doc-throw
1.1 anton 5770:
1.69 anton 5771: @code{Throw} consumes a cell-sized error number on the stack. There are
5772: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5773: Gforth (and most other systems) you can use the iors produced by various
5774: words as error numbers (e.g., a typical use of @code{allocate} is
5775: @code{allocate throw}). Gforth also provides the word @code{exception}
5776: to define your own error numbers (with decent error reporting); an ANS
5777: Forth version of this word (but without the error messages) is available
5778: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5779: numbers (anything outside the range -4095..0), but won't get nice error
5780: messages, only numbers. For example, try:
5781:
5782: @example
1.69 anton 5783: -10 throw \ ANS defined
5784: -267 throw \ system defined
5785: s" my error" exception throw \ user defined
5786: 7 throw \ arbitrary number
1.68 anton 5787: @end example
5788:
5789: doc---exception-exception
1.1 anton 5790:
1.69 anton 5791: A common idiom to @code{THROW} a specific error if a flag is true is
5792: this:
5793:
5794: @example
5795: @code{( flag ) 0<> @i{errno} and throw}
5796: @end example
5797:
5798: Your program can provide exception handlers to catch exceptions. An
5799: exception handler can be used to correct the problem, or to clean up
5800: some data structures and just throw the exception to the next exception
5801: handler. Note that @code{throw} jumps to the dynamically innermost
5802: exception handler. The system's exception handler is outermost, and just
5803: prints an error and restarts command-line interpretation (or, in batch
5804: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5805:
1.68 anton 5806: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5807:
1.68 anton 5808: doc-catch
1.160 anton 5809: doc-nothrow
1.68 anton 5810:
5811: The most common use of exception handlers is to clean up the state when
5812: an error happens. E.g.,
1.1 anton 5813:
1.26 crook 5814: @example
1.68 anton 5815: base @ >r hex \ actually the hex should be inside foo, or we h
5816: ['] foo catch ( nerror|0 )
5817: r> base !
1.69 anton 5818: ( nerror|0 ) throw \ pass it on
1.26 crook 5819: @end example
1.1 anton 5820:
1.69 anton 5821: A use of @code{catch} for handling the error @code{myerror} might look
5822: like this:
1.44 crook 5823:
1.68 anton 5824: @example
1.69 anton 5825: ['] foo catch
5826: CASE
1.160 anton 5827: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5828: dup throw \ default: pass other errors on, do nothing on non-errors
5829: ENDCASE
1.68 anton 5830: @end example
1.44 crook 5831:
1.68 anton 5832: Having to wrap the code into a separate word is often cumbersome,
5833: therefore Gforth provides an alternative syntax:
1.1 anton 5834:
5835: @example
1.69 anton 5836: TRY
1.68 anton 5837: @i{code1}
1.172 anton 5838: IFERROR
5839: @i{code2}
5840: THEN
5841: @i{code3}
1.69 anton 5842: ENDTRY
1.1 anton 5843: @end example
5844:
1.172 anton 5845: This performs @i{code1}. If @i{code1} completes normally, execution
1.201 anton 5846: continues with @i{code3}. If there is an exception in @i{code1} or
5847: before @code{endtry}, the stacks are reset to the depth during
1.172 anton 5848: @code{try}, the throw value is pushed on the data stack, and execution
1.201 anton 5849: constinues at @i{code2}, and finally falls through to @i{code3}.
1.26 crook 5850:
1.68 anton 5851: doc-try
5852: doc-endtry
1.172 anton 5853: doc-iferror
5854:
5855: If you don't need @i{code2}, you can write @code{restore} instead of
5856: @code{iferror then}:
5857:
5858: @example
5859: TRY
5860: @i{code1}
5861: RESTORE
5862: @i{code3}
5863: ENDTRY
5864: @end example
1.26 crook 5865:
1.172 anton 5866: @cindex unwind-protect
1.69 anton 5867: The cleanup example from above in this syntax:
1.26 crook 5868:
1.68 anton 5869: @example
1.174 anton 5870: base @@ @{ oldbase @}
1.172 anton 5871: TRY
1.68 anton 5872: hex foo \ now the hex is placed correctly
1.69 anton 5873: 0 \ value for throw
1.172 anton 5874: RESTORE
5875: oldbase base !
5876: ENDTRY
5877: throw
1.1 anton 5878: @end example
5879:
1.172 anton 5880: An additional advantage of this variant is that an exception between
5881: @code{restore} and @code{endtry} (e.g., from the user pressing
5882: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5883: so the base will be restored under all circumstances.
5884:
5885: However, you have to ensure that this code does not cause an exception
5886: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5887: Moreover, you should also make sure that the stack contents needed by
5888: the @code{iferror}/@code{restore} code exist everywhere between
5889: @code{try} and @code{endtry}; in our example this is achived by
5890: putting the data in a local before the @code{try} (you cannot use the
5891: return stack because the exception frame (@i{sys1}) is in the way
5892: there).
5893:
5894: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5895:
5896: @cindex @code{recover} (old Gforth versions)
5897: If you do not want this exception-restarting behaviour, you achieve
5898: this as follows:
5899:
5900: @example
5901: TRY
5902: @i{code1}
5903: ENDTRY-IFERROR
5904: @i{code2}
5905: THEN
5906: @end example
5907:
5908: If there is an exception in @i{code1}, then @i{code2} is executed,
5909: otherwise execution continues behind the @code{then} (or in a possible
5910: @code{else} branch). This corresponds to the construct
5911:
5912: @example
5913: TRY
5914: @i{code1}
5915: RECOVER
5916: @i{code2}
5917: ENDTRY
5918: @end example
5919:
5920: in Gforth before version 0.7. So you can directly replace
5921: @code{recover}-using code; however, we recommend that you check if it
5922: would not be better to use one of the other @code{try} variants while
5923: you are at it.
5924:
1.173 anton 5925: To ease the transition, Gforth provides two compatibility files:
5926: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5927: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5928: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5929: ... endtry} syntax on new systems, so you can use that file as a
5930: stopgap to run old programs. Both files work on any system (they just
5931: do nothing if the system already has the syntax it implements), so you
5932: can unconditionally @code{require} one of these files, even if you use
5933: a mix old and new systems.
5934:
1.172 anton 5935: doc-restore
5936: doc-endtry-iferror
5937:
5938: Here's the error handling example:
1.1 anton 5939:
1.68 anton 5940: @example
1.69 anton 5941: TRY
1.68 anton 5942: foo
1.172 anton 5943: ENDTRY-IFERROR
1.69 anton 5944: CASE
1.160 anton 5945: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5946: throw \ pass other errors on
5947: ENDCASE
1.172 anton 5948: THEN
1.68 anton 5949: @end example
1.1 anton 5950:
1.69 anton 5951: @progstyle
5952: As usual, you should ensure that the stack depth is statically known at
5953: the end: either after the @code{throw} for passing on errors, or after
5954: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5955: selection construct for handling the error).
5956:
1.68 anton 5957: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5958: and you can provide an error message. @code{Abort} just produces an
5959: ``Aborted'' error.
1.1 anton 5960:
1.68 anton 5961: The problem with these words is that exception handlers cannot
5962: differentiate between different @code{abort"}s; they just look like
5963: @code{-2 throw} to them (the error message cannot be accessed by
5964: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5965: exception handlers.
1.44 crook 5966:
1.68 anton 5967: doc-abort"
1.26 crook 5968: doc-abort
1.29 crook 5969:
5970:
1.44 crook 5971:
1.29 crook 5972: @c -------------------------------------------------------------
1.47 crook 5973: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5974: @section Defining Words
5975: @cindex defining words
5976:
1.47 crook 5977: Defining words are used to extend Forth by creating new entries in the dictionary.
5978:
1.29 crook 5979: @menu
1.67 anton 5980: * CREATE::
1.44 crook 5981: * Variables:: Variables and user variables
1.67 anton 5982: * Constants::
1.44 crook 5983: * Values:: Initialised variables
1.67 anton 5984: * Colon Definitions::
1.44 crook 5985: * Anonymous Definitions:: Definitions without names
1.69 anton 5986: * Supplying names:: Passing definition names as strings
1.67 anton 5987: * User-defined Defining Words::
1.170 pazsan 5988: * Deferred Words:: Allow forward references
1.67 anton 5989: * Aliases::
1.29 crook 5990: @end menu
5991:
1.44 crook 5992: @node CREATE, Variables, Defining Words, Defining Words
5993: @subsection @code{CREATE}
1.29 crook 5994: @cindex simple defining words
5995: @cindex defining words, simple
5996:
5997: Defining words are used to create new entries in the dictionary. The
5998: simplest defining word is @code{CREATE}. @code{CREATE} is used like
5999: this:
6000:
6001: @example
6002: CREATE new-word1
6003: @end example
6004:
1.69 anton 6005: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6006: input stream (@code{new-word1} in our example). It generates a
6007: dictionary entry for @code{new-word1}. When @code{new-word1} is
6008: executed, all that it does is leave an address on the stack. The address
6009: represents the value of the data space pointer (@code{HERE}) at the time
6010: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6011: associating a name with the address of a region of memory.
1.29 crook 6012:
1.34 anton 6013: doc-create
6014:
1.69 anton 6015: Note that in ANS Forth guarantees only for @code{create} that its body
6016: is in dictionary data space (i.e., where @code{here}, @code{allot}
6017: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6018: @code{create}d words can be modified with @code{does>}
6019: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6020: can only be applied to @code{create}d words.
6021:
1.29 crook 6022: By extending this example to reserve some memory in data space, we end
1.69 anton 6023: up with something like a @i{variable}. Here are two different ways to do
6024: it:
1.29 crook 6025:
6026: @example
6027: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6028: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6029: @end example
6030:
6031: The variable can be examined and modified using @code{@@} (``fetch'') and
6032: @code{!} (``store'') like this:
6033:
6034: @example
6035: new-word2 @@ . \ get address, fetch from it and display
6036: 1234 new-word2 ! \ new value, get address, store to it
6037: @end example
6038:
1.44 crook 6039: @cindex arrays
6040: A similar mechanism can be used to create arrays. For example, an
6041: 80-character text input buffer:
1.29 crook 6042:
6043: @example
1.44 crook 6044: CREATE text-buf 80 chars allot
6045:
1.168 anton 6046: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6047: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6048: @end example
1.29 crook 6049:
1.44 crook 6050: You can build arbitrarily complex data structures by allocating
1.49 anton 6051: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6052: learn about some Gforth tools that make it easier,
1.49 anton 6053: @xref{Structures}.
1.44 crook 6054:
6055:
6056: @node Variables, Constants, CREATE, Defining Words
6057: @subsection Variables
6058: @cindex variables
6059:
6060: The previous section showed how a sequence of commands could be used to
6061: generate a variable. As a final refinement, the whole code sequence can
6062: be wrapped up in a defining word (pre-empting the subject of the next
6063: section), making it easier to create new variables:
6064:
6065: @example
6066: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6067: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6068:
6069: myvariableX foo \ variable foo starts off with an unknown value
6070: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6071:
6072: 45 3 * foo ! \ set foo to 135
6073: 1234 joe ! \ set joe to 1234
6074: 3 joe +! \ increment joe by 3.. to 1237
6075: @end example
6076:
6077: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6078: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6079: guarantee that a @code{Variable} is initialised when it is created
6080: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6081: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6082: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6083: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6084: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6085: store a boolean, you can use @code{on} and @code{off} to toggle its
6086: state.
1.29 crook 6087:
1.34 anton 6088: doc-variable
6089: doc-2variable
6090: doc-fvariable
6091:
1.29 crook 6092: @cindex user variables
6093: @cindex user space
6094: The defining word @code{User} behaves in the same way as @code{Variable}.
6095: The difference is that it reserves space in @i{user (data) space} rather
6096: than normal data space. In a Forth system that has a multi-tasker, each
6097: task has its own set of user variables.
6098:
1.34 anton 6099: doc-user
1.67 anton 6100: @c doc-udp
6101: @c doc-uallot
1.34 anton 6102:
1.29 crook 6103: @comment TODO is that stuff about user variables strictly correct? Is it
6104: @comment just terminal tasks that have user variables?
6105: @comment should document tasker.fs (with some examples) elsewhere
6106: @comment in this manual, then expand on user space and user variables.
6107:
1.44 crook 6108: @node Constants, Values, Variables, Defining Words
6109: @subsection Constants
6110: @cindex constants
6111:
6112: @code{Constant} allows you to declare a fixed value and refer to it by
6113: name. For example:
1.29 crook 6114:
6115: @example
6116: 12 Constant INCHES-PER-FOOT
6117: 3E+08 fconstant SPEED-O-LIGHT
6118: @end example
6119:
6120: A @code{Variable} can be both read and written, so its run-time
6121: behaviour is to supply an address through which its current value can be
6122: manipulated. In contrast, the value of a @code{Constant} cannot be
6123: changed once it has been declared@footnote{Well, often it can be -- but
6124: not in a Standard, portable way. It's safer to use a @code{Value} (read
6125: on).} so it's not necessary to supply the address -- it is more
6126: efficient to return the value of the constant directly. That's exactly
6127: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6128: the top of the stack (You can find one
6129: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6130:
1.69 anton 6131: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6132: double and floating-point constants, respectively.
6133:
1.34 anton 6134: doc-constant
6135: doc-2constant
6136: doc-fconstant
6137:
6138: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6139: @c nac-> How could that not be true in an ANS Forth? You can't define a
6140: @c constant, use it and then delete the definition of the constant..
1.69 anton 6141:
6142: @c anton->An ANS Forth system can compile a constant to a literal; On
6143: @c decompilation you would see only the number, just as if it had been used
6144: @c in the first place. The word will stay, of course, but it will only be
6145: @c used by the text interpreter (no run-time duties, except when it is
6146: @c POSTPONEd or somesuch).
6147:
6148: @c nac:
1.44 crook 6149: @c I agree that it's rather deep, but IMO it is an important difference
6150: @c relative to other programming languages.. often it's annoying: it
6151: @c certainly changes my programming style relative to C.
6152:
1.69 anton 6153: @c anton: In what way?
6154:
1.29 crook 6155: Constants in Forth behave differently from their equivalents in other
6156: programming languages. In other languages, a constant (such as an EQU in
6157: assembler or a #define in C) only exists at compile-time; in the
6158: executable program the constant has been translated into an absolute
6159: number and, unless you are using a symbolic debugger, it's impossible to
6160: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6161: an entry in the header space and remains there after the code that uses
6162: it has been defined. In fact, it must remain in the dictionary since it
6163: has run-time duties to perform. For example:
1.29 crook 6164:
6165: @example
6166: 12 Constant INCHES-PER-FOOT
6167: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6168: @end example
6169:
6170: @cindex in-lining of constants
6171: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6172: associated with the constant @code{INCHES-PER-FOOT}. If you use
6173: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6174: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6175: attempt to optimise constants by in-lining them where they are used. You
6176: can force Gforth to in-line a constant like this:
6177:
6178: @example
6179: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6180: @end example
6181:
6182: If you use @code{see} to decompile @i{this} version of
6183: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6184: longer present. To understand how this works, read
6185: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6186:
6187: In-lining constants in this way might improve execution time
6188: fractionally, and can ensure that a constant is now only referenced at
6189: compile-time. However, the definition of the constant still remains in
6190: the dictionary. Some Forth compilers provide a mechanism for controlling
6191: a second dictionary for holding transient words such that this second
6192: dictionary can be deleted later in order to recover memory
6193: space. However, there is no standard way of doing this.
6194:
6195:
1.44 crook 6196: @node Values, Colon Definitions, Constants, Defining Words
6197: @subsection Values
6198: @cindex values
1.34 anton 6199:
1.69 anton 6200: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6201: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6202: (not in ANS Forth) you can access (and change) a @code{value} also with
6203: @code{>body}.
6204:
6205: Here are some
6206: examples:
1.29 crook 6207:
6208: @example
1.69 anton 6209: 12 Value APPLES \ Define APPLES with an initial value of 12
6210: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6211: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6212: APPLES \ puts 35 on the top of the stack.
1.29 crook 6213: @end example
6214:
1.44 crook 6215: doc-value
6216: doc-to
1.29 crook 6217:
1.35 anton 6218:
1.69 anton 6219:
1.44 crook 6220: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6221: @subsection Colon Definitions
6222: @cindex colon definitions
1.35 anton 6223:
6224: @example
1.44 crook 6225: : name ( ... -- ... )
6226: word1 word2 word3 ;
1.29 crook 6227: @end example
6228:
1.44 crook 6229: @noindent
6230: Creates a word called @code{name} that, upon execution, executes
6231: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6232:
1.49 anton 6233: The explanation above is somewhat superficial. For simple examples of
6234: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6235: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6236: Compilation Semantics}.
1.29 crook 6237:
1.44 crook 6238: doc-:
6239: doc-;
1.1 anton 6240:
1.34 anton 6241:
1.69 anton 6242: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6243: @subsection Anonymous Definitions
6244: @cindex colon definitions
6245: @cindex defining words without name
1.34 anton 6246:
1.44 crook 6247: Sometimes you want to define an @dfn{anonymous word}; a word without a
6248: name. You can do this with:
1.1 anton 6249:
1.44 crook 6250: doc-:noname
1.1 anton 6251:
1.44 crook 6252: This leaves the execution token for the word on the stack after the
6253: closing @code{;}. Here's an example in which a deferred word is
6254: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6255:
1.29 crook 6256: @example
1.44 crook 6257: Defer deferred
6258: :noname ( ... -- ... )
6259: ... ;
6260: IS deferred
1.29 crook 6261: @end example
1.26 crook 6262:
1.44 crook 6263: @noindent
6264: Gforth provides an alternative way of doing this, using two separate
6265: words:
1.27 crook 6266:
1.44 crook 6267: doc-noname
6268: @cindex execution token of last defined word
1.116 anton 6269: doc-latestxt
1.1 anton 6270:
1.44 crook 6271: @noindent
6272: The previous example can be rewritten using @code{noname} and
1.116 anton 6273: @code{latestxt}:
1.1 anton 6274:
1.26 crook 6275: @example
1.44 crook 6276: Defer deferred
6277: noname : ( ... -- ... )
6278: ... ;
1.116 anton 6279: latestxt IS deferred
1.26 crook 6280: @end example
1.1 anton 6281:
1.29 crook 6282: @noindent
1.44 crook 6283: @code{noname} works with any defining word, not just @code{:}.
6284:
1.116 anton 6285: @code{latestxt} also works when the last word was not defined as
1.71 anton 6286: @code{noname}. It does not work for combined words, though. It also has
6287: the useful property that is is valid as soon as the header for a
6288: definition has been built. Thus:
1.44 crook 6289:
6290: @example
1.116 anton 6291: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6292: @end example
1.1 anton 6293:
1.44 crook 6294: @noindent
6295: prints 3 numbers; the last two are the same.
1.26 crook 6296:
1.69 anton 6297: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6298: @subsection Supplying the name of a defined word
6299: @cindex names for defined words
6300: @cindex defining words, name given in a string
6301:
6302: By default, a defining word takes the name for the defined word from the
6303: input stream. Sometimes you want to supply the name from a string. You
6304: can do this with:
6305:
6306: doc-nextname
6307:
6308: For example:
6309:
6310: @example
6311: s" foo" nextname create
6312: @end example
6313:
6314: @noindent
6315: is equivalent to:
6316:
6317: @example
6318: create foo
6319: @end example
6320:
6321: @noindent
6322: @code{nextname} works with any defining word.
6323:
1.1 anton 6324:
1.170 pazsan 6325: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6326: @subsection User-defined Defining Words
6327: @cindex user-defined defining words
6328: @cindex defining words, user-defined
1.1 anton 6329:
1.29 crook 6330: You can create a new defining word by wrapping defining-time code around
6331: an existing defining word and putting the sequence in a colon
1.69 anton 6332: definition.
6333:
6334: @c anton: This example is very complex and leads in a quite different
6335: @c direction from the CREATE-DOES> stuff that follows. It should probably
6336: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6337: @c subsection of Defining Words)
6338:
6339: For example, suppose that you have a word @code{stats} that
1.29 crook 6340: gathers statistics about colon definitions given the @i{xt} of the
6341: definition, and you want every colon definition in your application to
6342: make a call to @code{stats}. You can define and use a new version of
6343: @code{:} like this:
6344:
6345: @example
6346: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6347: ... ; \ other code
6348:
1.116 anton 6349: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6350:
6351: my: foo + - ;
6352: @end example
6353:
6354: When @code{foo} is defined using @code{my:} these steps occur:
6355:
6356: @itemize @bullet
6357: @item
6358: @code{my:} is executed.
6359: @item
6360: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6361: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6362: the input stream for a name, builds a dictionary header for the name
6363: @code{foo} and switches @code{state} from interpret to compile.
6364: @item
1.116 anton 6365: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6366: being defined -- @code{foo} -- onto the stack.
6367: @item
6368: The code that was produced by @code{postpone literal} is executed; this
6369: causes the value on the stack to be compiled as a literal in the code
6370: area of @code{foo}.
6371: @item
6372: The code @code{['] stats} compiles a literal into the definition of
6373: @code{my:}. When @code{compile,} is executed, that literal -- the
6374: execution token for @code{stats} -- is layed down in the code area of
6375: @code{foo} , following the literal@footnote{Strictly speaking, the
6376: mechanism that @code{compile,} uses to convert an @i{xt} into something
6377: in the code area is implementation-dependent. A threaded implementation
6378: might spit out the execution token directly whilst another
6379: implementation might spit out a native code sequence.}.
6380: @item
6381: At this point, the execution of @code{my:} is complete, and control
6382: returns to the text interpreter. The text interpreter is in compile
6383: state, so subsequent text @code{+ -} is compiled into the definition of
6384: @code{foo} and the @code{;} terminates the definition as always.
6385: @end itemize
6386:
6387: You can use @code{see} to decompile a word that was defined using
6388: @code{my:} and see how it is different from a normal @code{:}
6389: definition. For example:
6390:
6391: @example
6392: : bar + - ; \ like foo but using : rather than my:
6393: see bar
6394: : bar
6395: + - ;
6396: see foo
6397: : foo
6398: 107645672 stats + - ;
6399:
1.140 anton 6400: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6401: @end example
6402:
6403: You can use techniques like this to make new defining words in terms of
6404: @i{any} existing defining word.
1.1 anton 6405:
6406:
1.29 crook 6407: @cindex defining defining words
1.26 crook 6408: @cindex @code{CREATE} ... @code{DOES>}
6409: If you want the words defined with your defining words to behave
6410: differently from words defined with standard defining words, you can
6411: write your defining word like this:
1.1 anton 6412:
6413: @example
1.26 crook 6414: : def-word ( "name" -- )
1.29 crook 6415: CREATE @i{code1}
1.26 crook 6416: DOES> ( ... -- ... )
1.29 crook 6417: @i{code2} ;
1.26 crook 6418:
6419: def-word name
1.1 anton 6420: @end example
6421:
1.29 crook 6422: @cindex child words
6423: This fragment defines a @dfn{defining word} @code{def-word} and then
6424: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6425: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6426: is not executed at this time. The word @code{name} is sometimes called a
6427: @dfn{child} of @code{def-word}.
6428:
6429: When you execute @code{name}, the address of the body of @code{name} is
6430: put on the data stack and @i{code2} is executed (the address of the body
6431: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6432: @code{CREATE}, i.e., the address a @code{create}d word returns by
6433: default).
6434:
6435: @c anton:
6436: @c www.dictionary.com says:
6437: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6438: @c several generations of absence, usually caused by the chance
6439: @c recombination of genes. 2.An individual or a part that exhibits
6440: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6441: @c of previous behavior after a period of absence.
6442: @c
6443: @c Doesn't seem to fit.
1.29 crook 6444:
1.69 anton 6445: @c @cindex atavism in child words
1.33 anton 6446: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6447: similarly; they all have a common run-time behaviour determined by
6448: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6449: body of the child word. The structure of the data is common to all
6450: children of @code{def-word}, but the data values are specific -- and
6451: private -- to each child word. When a child word is executed, the
6452: address of its private data area is passed as a parameter on TOS to be
6453: used and manipulated@footnote{It is legitimate both to read and write to
6454: this data area.} by @i{code2}.
1.29 crook 6455:
6456: The two fragments of code that make up the defining words act (are
6457: executed) at two completely separate times:
1.1 anton 6458:
1.29 crook 6459: @itemize @bullet
6460: @item
6461: At @i{define time}, the defining word executes @i{code1} to generate a
6462: child word
6463: @item
6464: At @i{child execution time}, when a child word is invoked, @i{code2}
6465: is executed, using parameters (data) that are private and specific to
6466: the child word.
6467: @end itemize
6468:
1.44 crook 6469: Another way of understanding the behaviour of @code{def-word} and
6470: @code{name} is to say that, if you make the following definitions:
1.33 anton 6471: @example
6472: : def-word1 ( "name" -- )
6473: CREATE @i{code1} ;
6474:
6475: : action1 ( ... -- ... )
6476: @i{code2} ;
6477:
6478: def-word1 name1
6479: @end example
6480:
1.44 crook 6481: @noindent
6482: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6483:
1.29 crook 6484: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6485:
1.1 anton 6486: @example
1.29 crook 6487: : CONSTANT ( w "name" -- )
6488: CREATE ,
1.26 crook 6489: DOES> ( -- w )
6490: @@ ;
1.1 anton 6491: @end example
6492:
1.29 crook 6493: @comment There is a beautiful description of how this works and what
6494: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6495: @comment commentary on the Counting Fruits problem.
6496:
6497: When you create a constant with @code{5 CONSTANT five}, a set of
6498: define-time actions take place; first a new word @code{five} is created,
6499: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6500: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6501: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6502: no code of its own; it simply contains a data field and a pointer to the
6503: code that follows @code{DOES>} in its defining word. That makes words
6504: created in this way very compact.
6505:
6506: The final example in this section is intended to remind you that space
6507: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6508: both read and written by a Standard program@footnote{Exercise: use this
6509: example as a starting point for your own implementation of @code{Value}
6510: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6511: @code{[']}.}:
6512:
6513: @example
6514: : foo ( "name" -- )
6515: CREATE -1 ,
6516: DOES> ( -- )
1.33 anton 6517: @@ . ;
1.29 crook 6518:
6519: foo first-word
6520: foo second-word
6521:
6522: 123 ' first-word >BODY !
6523: @end example
6524:
6525: If @code{first-word} had been a @code{CREATE}d word, we could simply
6526: have executed it to get the address of its data field. However, since it
6527: was defined to have @code{DOES>} actions, its execution semantics are to
6528: perform those @code{DOES>} actions. To get the address of its data field
6529: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6530: translate the xt into the address of the data field. When you execute
6531: @code{first-word}, it will display @code{123}. When you execute
6532: @code{second-word} it will display @code{-1}.
1.26 crook 6533:
6534: @cindex stack effect of @code{DOES>}-parts
6535: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6536: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6537: the stack effect of the defined words, not the stack effect of the
6538: following code (the following code expects the address of the body on
6539: the top of stack, which is not reflected in the stack comment). This is
6540: the convention that I use and recommend (it clashes a bit with using
6541: locals declarations for stack effect specification, though).
1.1 anton 6542:
1.53 anton 6543: @menu
6544: * CREATE..DOES> applications::
6545: * CREATE..DOES> details::
1.63 anton 6546: * Advanced does> usage example::
1.155 anton 6547: * Const-does>::
1.53 anton 6548: @end menu
6549:
6550: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6551: @subsubsection Applications of @code{CREATE..DOES>}
6552: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6553:
1.26 crook 6554: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6555:
1.26 crook 6556: @cindex factoring similar colon definitions
6557: When you see a sequence of code occurring several times, and you can
6558: identify a meaning, you will factor it out as a colon definition. When
6559: you see similar colon definitions, you can factor them using
6560: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6561: that look very similar:
1.1 anton 6562: @example
1.26 crook 6563: : ori, ( reg-target reg-source n -- )
6564: 0 asm-reg-reg-imm ;
6565: : andi, ( reg-target reg-source n -- )
6566: 1 asm-reg-reg-imm ;
1.1 anton 6567: @end example
6568:
1.26 crook 6569: @noindent
6570: This could be factored with:
6571: @example
6572: : reg-reg-imm ( op-code -- )
6573: CREATE ,
6574: DOES> ( reg-target reg-source n -- )
6575: @@ asm-reg-reg-imm ;
6576:
6577: 0 reg-reg-imm ori,
6578: 1 reg-reg-imm andi,
6579: @end example
1.1 anton 6580:
1.26 crook 6581: @cindex currying
6582: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6583: supply a part of the parameters for a word (known as @dfn{currying} in
6584: the functional language community). E.g., @code{+} needs two
6585: parameters. Creating versions of @code{+} with one parameter fixed can
6586: be done like this:
1.82 anton 6587:
1.1 anton 6588: @example
1.82 anton 6589: : curry+ ( n1 "name" -- )
1.26 crook 6590: CREATE ,
6591: DOES> ( n2 -- n1+n2 )
6592: @@ + ;
6593:
6594: 3 curry+ 3+
6595: -2 curry+ 2-
1.1 anton 6596: @end example
6597:
1.91 anton 6598:
1.63 anton 6599: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6600: @subsubsection The gory details of @code{CREATE..DOES>}
6601: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6602:
1.26 crook 6603: doc-does>
1.1 anton 6604:
1.26 crook 6605: @cindex @code{DOES>} in a separate definition
6606: This means that you need not use @code{CREATE} and @code{DOES>} in the
6607: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6608: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6609: @example
6610: : does1
6611: DOES> ( ... -- ... )
1.44 crook 6612: ... ;
6613:
6614: : does2
6615: DOES> ( ... -- ... )
6616: ... ;
6617:
6618: : def-word ( ... -- ... )
6619: create ...
6620: IF
6621: does1
6622: ELSE
6623: does2
6624: ENDIF ;
6625: @end example
6626:
6627: In this example, the selection of whether to use @code{does1} or
1.69 anton 6628: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6629: @code{CREATE}d.
6630:
6631: @cindex @code{DOES>} in interpretation state
6632: In a standard program you can apply a @code{DOES>}-part only if the last
6633: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6634: will override the behaviour of the last word defined in any case. In a
6635: standard program, you can use @code{DOES>} only in a colon
6636: definition. In Gforth, you can also use it in interpretation state, in a
6637: kind of one-shot mode; for example:
6638: @example
6639: CREATE name ( ... -- ... )
6640: @i{initialization}
6641: DOES>
6642: @i{code} ;
6643: @end example
6644:
6645: @noindent
6646: is equivalent to the standard:
6647: @example
6648: :noname
6649: DOES>
6650: @i{code} ;
6651: CREATE name EXECUTE ( ... -- ... )
6652: @i{initialization}
6653: @end example
6654:
1.53 anton 6655: doc->body
6656:
1.152 pazsan 6657: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6658: @subsubsection Advanced does> usage example
6659:
6660: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6661: for disassembling instructions, that follow a very repetetive scheme:
6662:
6663: @example
6664: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6665: @var{entry-num} cells @var{table} + !
6666: @end example
6667:
6668: Of course, this inspires the idea to factor out the commonalities to
6669: allow a definition like
6670:
6671: @example
6672: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6673: @end example
6674:
6675: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6676: correlated. Moreover, before I wrote the disassembler, there already
6677: existed code that defines instructions like this:
1.63 anton 6678:
6679: @example
6680: @var{entry-num} @var{inst-format} @var{inst-name}
6681: @end example
6682:
6683: This code comes from the assembler and resides in
6684: @file{arch/mips/insts.fs}.
6685:
6686: So I had to define the @var{inst-format} words that performed the scheme
6687: above when executed. At first I chose to use run-time code-generation:
6688:
6689: @example
6690: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6691: :noname Postpone @var{disasm-operands}
6692: name Postpone sliteral Postpone type Postpone ;
6693: swap cells @var{table} + ! ;
6694: @end example
6695:
6696: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6697:
1.63 anton 6698: An alternative would have been to write this using
6699: @code{create}/@code{does>}:
6700:
6701: @example
6702: : @var{inst-format} ( entry-num "name" -- )
6703: here name string, ( entry-num c-addr ) \ parse and save "name"
6704: noname create , ( entry-num )
1.116 anton 6705: latestxt swap cells @var{table} + !
1.63 anton 6706: does> ( addr w -- )
6707: \ disassemble instruction w at addr
6708: @@ >r
6709: @var{disasm-operands}
6710: r> count type ;
6711: @end example
6712:
6713: Somehow the first solution is simpler, mainly because it's simpler to
6714: shift a string from definition-time to use-time with @code{sliteral}
6715: than with @code{string,} and friends.
6716:
6717: I wrote a lot of words following this scheme and soon thought about
6718: factoring out the commonalities among them. Note that this uses a
6719: two-level defining word, i.e., a word that defines ordinary defining
6720: words.
6721:
6722: This time a solution involving @code{postpone} and friends seemed more
6723: difficult (try it as an exercise), so I decided to use a
6724: @code{create}/@code{does>} word; since I was already at it, I also used
6725: @code{create}/@code{does>} for the lower level (try using
6726: @code{postpone} etc. as an exercise), resulting in the following
6727: definition:
6728:
6729: @example
6730: : define-format ( disasm-xt table-xt -- )
6731: \ define an instruction format that uses disasm-xt for
6732: \ disassembling and enters the defined instructions into table
6733: \ table-xt
6734: create 2,
6735: does> ( u "inst" -- )
6736: \ defines an anonymous word for disassembling instruction inst,
6737: \ and enters it as u-th entry into table-xt
6738: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6739: noname create 2, \ define anonymous word
1.116 anton 6740: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6741: does> ( addr w -- )
6742: \ disassemble instruction w at addr
6743: 2@@ >r ( addr w disasm-xt R: c-addr )
6744: execute ( R: c-addr ) \ disassemble operands
6745: r> count type ; \ print name
6746: @end example
6747:
6748: Note that the tables here (in contrast to above) do the @code{cells +}
6749: by themselves (that's why you have to pass an xt). This word is used in
6750: the following way:
6751:
6752: @example
6753: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6754: @end example
6755:
1.71 anton 6756: As shown above, the defined instruction format is then used like this:
6757:
6758: @example
6759: @var{entry-num} @var{inst-format} @var{inst-name}
6760: @end example
6761:
1.63 anton 6762: In terms of currying, this kind of two-level defining word provides the
6763: parameters in three stages: first @var{disasm-operands} and @var{table},
6764: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6765: the instruction to be disassembled.
6766:
6767: Of course this did not quite fit all the instruction format names used
6768: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6769: the parameters into the right form.
6770:
6771: If you have trouble following this section, don't worry. First, this is
6772: involved and takes time (and probably some playing around) to
6773: understand; second, this is the first two-level
6774: @code{create}/@code{does>} word I have written in seventeen years of
6775: Forth; and if I did not have @file{insts.fs} to start with, I may well
6776: have elected to use just a one-level defining word (with some repeating
6777: of parameters when using the defining word). So it is not necessary to
6778: understand this, but it may improve your understanding of Forth.
1.44 crook 6779:
6780:
1.152 pazsan 6781: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6782: @subsubsection @code{Const-does>}
6783:
6784: A frequent use of @code{create}...@code{does>} is for transferring some
6785: values from definition-time to run-time. Gforth supports this use with
6786:
6787: doc-const-does>
6788:
6789: A typical use of this word is:
6790:
6791: @example
6792: : curry+ ( n1 "name" -- )
6793: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6794: + ;
6795:
6796: 3 curry+ 3+
6797: @end example
6798:
6799: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6800: definition to run-time.
6801:
6802: The advantages of using @code{const-does>} are:
6803:
6804: @itemize
6805:
6806: @item
6807: You don't have to deal with storing and retrieving the values, i.e.,
6808: your program becomes more writable and readable.
6809:
6810: @item
6811: When using @code{does>}, you have to introduce a @code{@@} that cannot
6812: be optimized away (because you could change the data using
6813: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6814:
6815: @end itemize
6816:
6817: An ANS Forth implementation of @code{const-does>} is available in
6818: @file{compat/const-does.fs}.
6819:
6820:
1.170 pazsan 6821: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6822: @subsection Deferred Words
1.44 crook 6823: @cindex deferred words
6824:
6825: The defining word @code{Defer} allows you to define a word by name
6826: without defining its behaviour; the definition of its behaviour is
6827: deferred. Here are two situation where this can be useful:
6828:
6829: @itemize @bullet
6830: @item
6831: Where you want to allow the behaviour of a word to be altered later, and
6832: for all precompiled references to the word to change when its behaviour
6833: is changed.
6834: @item
6835: For mutual recursion; @xref{Calls and returns}.
6836: @end itemize
6837:
6838: In the following example, @code{foo} always invokes the version of
6839: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6840: always invokes the version that prints ``@code{Hello}''. There is no way
6841: of getting @code{foo} to use the later version without re-ordering the
6842: source code and recompiling it.
6843:
6844: @example
6845: : greet ." Good morning" ;
6846: : foo ... greet ... ;
6847: : greet ." Hello" ;
6848: : bar ... greet ... ;
6849: @end example
6850:
6851: This problem can be solved by defining @code{greet} as a @code{Defer}red
6852: word. The behaviour of a @code{Defer}red word can be defined and
6853: redefined at any time by using @code{IS} to associate the xt of a
6854: previously-defined word with it. The previous example becomes:
6855:
6856: @example
1.69 anton 6857: Defer greet ( -- )
1.44 crook 6858: : foo ... greet ... ;
6859: : bar ... greet ... ;
1.69 anton 6860: : greet1 ( -- ) ." Good morning" ;
6861: : greet2 ( -- ) ." Hello" ;
1.132 anton 6862: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6863: @end example
6864:
1.69 anton 6865: @progstyle
6866: You should write a stack comment for every deferred word, and put only
6867: XTs into deferred words that conform to this stack effect. Otherwise
6868: it's too difficult to use the deferred word.
6869:
1.44 crook 6870: A deferred word can be used to improve the statistics-gathering example
6871: from @ref{User-defined Defining Words}; rather than edit the
6872: application's source code to change every @code{:} to a @code{my:}, do
6873: this:
6874:
6875: @example
6876: : real: : ; \ retain access to the original
6877: defer : \ redefine as a deferred word
1.132 anton 6878: ' my: IS : \ use special version of :
1.44 crook 6879: \
6880: \ load application here
6881: \
1.132 anton 6882: ' real: IS : \ go back to the original
1.44 crook 6883: @end example
6884:
6885:
1.132 anton 6886: One thing to note is that @code{IS} has special compilation semantics,
6887: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6888:
6889: @example
6890: : set-greet ( xt -- )
1.132 anton 6891: IS greet ;
1.44 crook 6892:
6893: ' greet1 set-greet
6894: @end example
6895:
1.132 anton 6896: In situations where @code{IS} does not fit, use @code{defer!} instead.
6897:
1.69 anton 6898: A deferred word can only inherit execution semantics from the xt
6899: (because that is all that an xt can represent -- for more discussion of
6900: this @pxref{Tokens for Words}); by default it will have default
6901: interpretation and compilation semantics deriving from this execution
6902: semantics. However, you can change the interpretation and compilation
6903: semantics of the deferred word in the usual ways:
1.44 crook 6904:
6905: @example
1.132 anton 6906: : bar .... ; immediate
1.44 crook 6907: Defer fred immediate
6908: Defer jim
6909:
1.132 anton 6910: ' bar IS jim \ jim has default semantics
6911: ' bar IS fred \ fred is immediate
1.44 crook 6912: @end example
6913:
6914: doc-defer
1.132 anton 6915: doc-defer!
1.44 crook 6916: doc-is
1.132 anton 6917: doc-defer@
6918: doc-action-of
1.44 crook 6919: @comment TODO document these: what's defers [is]
6920: doc-defers
6921:
6922: @c Use @code{words-deferred} to see a list of deferred words.
6923:
1.132 anton 6924: Definitions of these words (except @code{defers}) in ANS Forth are
6925: provided in @file{compat/defer.fs}.
1.44 crook 6926:
6927:
1.170 pazsan 6928: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6929: @subsection Aliases
6930: @cindex aliases
1.1 anton 6931:
1.44 crook 6932: The defining word @code{Alias} allows you to define a word by name that
6933: has the same behaviour as some other word. Here are two situation where
6934: this can be useful:
1.1 anton 6935:
1.44 crook 6936: @itemize @bullet
6937: @item
6938: When you want access to a word's definition from a different word list
6939: (for an example of this, see the definition of the @code{Root} word list
6940: in the Gforth source).
6941: @item
6942: When you want to create a synonym; a definition that can be known by
6943: either of two names (for example, @code{THEN} and @code{ENDIF} are
6944: aliases).
6945: @end itemize
1.1 anton 6946:
1.69 anton 6947: Like deferred words, an alias has default compilation and interpretation
6948: semantics at the beginning (not the modifications of the other word),
6949: but you can change them in the usual ways (@code{immediate},
6950: @code{compile-only}). For example:
1.1 anton 6951:
6952: @example
1.44 crook 6953: : foo ... ; immediate
6954:
6955: ' foo Alias bar \ bar is not an immediate word
6956: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6957: @end example
6958:
1.44 crook 6959: Words that are aliases have the same xt, different headers in the
6960: dictionary, and consequently different name tokens (@pxref{Tokens for
6961: Words}) and possibly different immediate flags. An alias can only have
6962: default or immediate compilation semantics; you can define aliases for
6963: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6964:
1.44 crook 6965: doc-alias
1.1 anton 6966:
6967:
1.47 crook 6968: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6969: @section Interpretation and Compilation Semantics
1.26 crook 6970: @cindex semantics, interpretation and compilation
1.1 anton 6971:
1.71 anton 6972: @c !! state and ' are used without explanation
6973: @c example for immediate/compile-only? or is the tutorial enough
6974:
1.26 crook 6975: @cindex interpretation semantics
1.71 anton 6976: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6977: interpreter does when it encounters the word in interpret state. It also
6978: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6979: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6980: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 6981: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 6982:
1.26 crook 6983: @cindex compilation semantics
1.71 anton 6984: The @dfn{compilation semantics} of a (named) word are what the text
6985: interpreter does when it encounters the word in compile state. It also
6986: appears in other contexts, e.g, @code{POSTPONE @i{word}}
6987: compiles@footnote{In standard terminology, ``appends to the current
6988: definition''.} the compilation semantics of @i{word}.
1.1 anton 6989:
1.26 crook 6990: @cindex execution semantics
6991: The standard also talks about @dfn{execution semantics}. They are used
6992: only for defining the interpretation and compilation semantics of many
6993: words. By default, the interpretation semantics of a word are to
6994: @code{execute} its execution semantics, and the compilation semantics of
6995: a word are to @code{compile,} its execution semantics.@footnote{In
6996: standard terminology: The default interpretation semantics are its
6997: execution semantics; the default compilation semantics are to append its
6998: execution semantics to the execution semantics of the current
6999: definition.}
7000:
1.71 anton 7001: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7002: the text interpreter, ticked, or @code{postpone}d, so they have no
7003: interpretation or compilation semantics. Their behaviour is represented
7004: by their XT (@pxref{Tokens for Words}), and we call it execution
7005: semantics, too.
7006:
1.26 crook 7007: @comment TODO expand, make it co-operate with new sections on text interpreter.
7008:
7009: @cindex immediate words
7010: @cindex compile-only words
7011: You can change the semantics of the most-recently defined word:
7012:
1.44 crook 7013:
1.26 crook 7014: doc-immediate
7015: doc-compile-only
7016: doc-restrict
7017:
1.82 anton 7018: By convention, words with non-default compilation semantics (e.g.,
7019: immediate words) often have names surrounded with brackets (e.g.,
7020: @code{[']}, @pxref{Execution token}).
1.44 crook 7021:
1.26 crook 7022: Note that ticking (@code{'}) a compile-only word gives an error
7023: (``Interpreting a compile-only word'').
1.1 anton 7024:
1.47 crook 7025: @menu
1.67 anton 7026: * Combined words::
1.47 crook 7027: @end menu
1.44 crook 7028:
1.71 anton 7029:
1.48 anton 7030: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7031: @subsection Combined Words
7032: @cindex combined words
7033:
7034: Gforth allows you to define @dfn{combined words} -- words that have an
7035: arbitrary combination of interpretation and compilation semantics.
7036:
1.26 crook 7037: doc-interpret/compile:
1.1 anton 7038:
1.26 crook 7039: This feature was introduced for implementing @code{TO} and @code{S"}. I
7040: recommend that you do not define such words, as cute as they may be:
7041: they make it hard to get at both parts of the word in some contexts.
7042: E.g., assume you want to get an execution token for the compilation
7043: part. Instead, define two words, one that embodies the interpretation
7044: part, and one that embodies the compilation part. Once you have done
7045: that, you can define a combined word with @code{interpret/compile:} for
7046: the convenience of your users.
1.1 anton 7047:
1.26 crook 7048: You might try to use this feature to provide an optimizing
7049: implementation of the default compilation semantics of a word. For
7050: example, by defining:
1.1 anton 7051: @example
1.26 crook 7052: :noname
7053: foo bar ;
7054: :noname
7055: POSTPONE foo POSTPONE bar ;
1.29 crook 7056: interpret/compile: opti-foobar
1.1 anton 7057: @end example
1.26 crook 7058:
1.23 crook 7059: @noindent
1.26 crook 7060: as an optimizing version of:
7061:
1.1 anton 7062: @example
1.26 crook 7063: : foobar
7064: foo bar ;
1.1 anton 7065: @end example
7066:
1.26 crook 7067: Unfortunately, this does not work correctly with @code{[compile]},
7068: because @code{[compile]} assumes that the compilation semantics of all
7069: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7070: opti-foobar} would compile compilation semantics, whereas
7071: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7072:
1.26 crook 7073: @cindex state-smart words (are a bad idea)
1.82 anton 7074: @anchor{state-smartness}
1.29 crook 7075: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7076: by @code{interpret/compile:} (words are state-smart if they check
7077: @code{STATE} during execution). E.g., they would try to code
7078: @code{foobar} like this:
1.1 anton 7079:
1.26 crook 7080: @example
7081: : foobar
7082: STATE @@
7083: IF ( compilation state )
7084: POSTPONE foo POSTPONE bar
7085: ELSE
7086: foo bar
7087: ENDIF ; immediate
7088: @end example
1.1 anton 7089:
1.26 crook 7090: Although this works if @code{foobar} is only processed by the text
7091: interpreter, it does not work in other contexts (like @code{'} or
7092: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7093: for a state-smart word, not for the interpretation semantics of the
7094: original @code{foobar}; when you execute this execution token (directly
7095: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7096: state, the result will not be what you expected (i.e., it will not
7097: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7098: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7099: M. Anton Ertl,
7100: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7101: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7102:
1.26 crook 7103: @cindex defining words with arbitrary semantics combinations
7104: It is also possible to write defining words that define words with
7105: arbitrary combinations of interpretation and compilation semantics. In
7106: general, they look like this:
1.1 anton 7107:
1.26 crook 7108: @example
7109: : def-word
7110: create-interpret/compile
1.29 crook 7111: @i{code1}
1.26 crook 7112: interpretation>
1.29 crook 7113: @i{code2}
1.26 crook 7114: <interpretation
7115: compilation>
1.29 crook 7116: @i{code3}
1.26 crook 7117: <compilation ;
7118: @end example
1.1 anton 7119:
1.29 crook 7120: For a @i{word} defined with @code{def-word}, the interpretation
7121: semantics are to push the address of the body of @i{word} and perform
7122: @i{code2}, and the compilation semantics are to push the address of
7123: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7124: can also be defined like this (except that the defined constants don't
7125: behave correctly when @code{[compile]}d):
1.1 anton 7126:
1.26 crook 7127: @example
7128: : constant ( n "name" -- )
7129: create-interpret/compile
7130: ,
7131: interpretation> ( -- n )
7132: @@
7133: <interpretation
7134: compilation> ( compilation. -- ; run-time. -- n )
7135: @@ postpone literal
7136: <compilation ;
7137: @end example
1.1 anton 7138:
1.44 crook 7139:
1.26 crook 7140: doc-create-interpret/compile
7141: doc-interpretation>
7142: doc-<interpretation
7143: doc-compilation>
7144: doc-<compilation
1.1 anton 7145:
1.44 crook 7146:
1.29 crook 7147: Words defined with @code{interpret/compile:} and
1.26 crook 7148: @code{create-interpret/compile} have an extended header structure that
7149: differs from other words; however, unless you try to access them with
7150: plain address arithmetic, you should not notice this. Words for
7151: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7152: @code{'} @i{word} @code{>body} also gives you the body of a word created
7153: with @code{create-interpret/compile}.
1.1 anton 7154:
1.44 crook 7155:
1.47 crook 7156: @c -------------------------------------------------------------
1.81 anton 7157: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7158: @section Tokens for Words
7159: @cindex tokens for words
7160:
7161: This section describes the creation and use of tokens that represent
7162: words.
7163:
1.71 anton 7164: @menu
7165: * Execution token:: represents execution/interpretation semantics
7166: * Compilation token:: represents compilation semantics
7167: * Name token:: represents named words
7168: @end menu
1.47 crook 7169:
1.71 anton 7170: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7171: @subsection Execution token
1.47 crook 7172:
7173: @cindex xt
7174: @cindex execution token
1.71 anton 7175: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7176: You can use @code{execute} to invoke this behaviour.
1.47 crook 7177:
1.71 anton 7178: @cindex tick (')
7179: You can use @code{'} to get an execution token that represents the
7180: interpretation semantics of a named word:
1.47 crook 7181:
7182: @example
1.97 anton 7183: 5 ' . ( n xt )
7184: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7185: @end example
1.47 crook 7186:
1.71 anton 7187: doc-'
7188:
7189: @code{'} parses at run-time; there is also a word @code{[']} that parses
7190: when it is compiled, and compiles the resulting XT:
7191:
7192: @example
7193: : foo ['] . execute ;
7194: 5 foo
7195: : bar ' execute ; \ by contrast,
7196: 5 bar . \ ' parses "." when bar executes
7197: @end example
7198:
7199: doc-[']
7200:
7201: If you want the execution token of @i{word}, write @code{['] @i{word}}
7202: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7203: @code{'} and @code{[']} behave somewhat unusually by complaining about
7204: compile-only words (because these words have no interpretation
7205: semantics). You might get what you want by using @code{COMP' @i{word}
7206: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7207: token}).
7208:
1.116 anton 7209: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7210: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7211: for the only behaviour the word has (the execution semantics). For
1.116 anton 7212: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7213: would produce if the word was defined anonymously.
7214:
7215: @example
7216: :noname ." hello" ;
7217: execute
1.47 crook 7218: @end example
7219:
1.71 anton 7220: An XT occupies one cell and can be manipulated like any other cell.
7221:
1.47 crook 7222: @cindex code field address
7223: @cindex CFA
1.71 anton 7224: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7225: operations that produce or consume it). For old hands: In Gforth, the
7226: XT is implemented as a code field address (CFA).
7227:
7228: doc-execute
7229: doc-perform
7230:
7231: @node Compilation token, Name token, Execution token, Tokens for Words
7232: @subsection Compilation token
1.47 crook 7233:
7234: @cindex compilation token
1.71 anton 7235: @cindex CT (compilation token)
7236: Gforth represents the compilation semantics of a named word by a
1.47 crook 7237: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7238: @i{xt} is an execution token. The compilation semantics represented by
7239: the compilation token can be performed with @code{execute}, which
7240: consumes the whole compilation token, with an additional stack effect
7241: determined by the represented compilation semantics.
7242:
7243: At present, the @i{w} part of a compilation token is an execution token,
7244: and the @i{xt} part represents either @code{execute} or
7245: @code{compile,}@footnote{Depending upon the compilation semantics of the
7246: word. If the word has default compilation semantics, the @i{xt} will
7247: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7248: @i{xt} will represent @code{execute}.}. However, don't rely on that
7249: knowledge, unless necessary; future versions of Gforth may introduce
7250: unusual compilation tokens (e.g., a compilation token that represents
7251: the compilation semantics of a literal).
7252:
1.71 anton 7253: You can perform the compilation semantics represented by the compilation
7254: token with @code{execute}. You can compile the compilation semantics
7255: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7256: equivalent to @code{postpone @i{word}}.
7257:
7258: doc-[comp']
7259: doc-comp'
7260: doc-postpone,
7261:
7262: @node Name token, , Compilation token, Tokens for Words
7263: @subsection Name token
1.47 crook 7264:
7265: @cindex name token
1.116 anton 7266: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7267: token is an abstract data type that occurs as argument or result of the
7268: words below.
7269:
7270: @c !! put this elswhere?
1.47 crook 7271: @cindex name field address
7272: @cindex NFA
1.116 anton 7273: The closest thing to the nt in older Forth systems is the name field
7274: address (NFA), but there are significant differences: in older Forth
7275: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7276: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7277: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7278: is a link field in the structure identified by the name token, but
7279: searching usually uses a hash table external to these structures; the
7280: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7281: implemented as the address of that count field.
1.47 crook 7282:
7283: doc-find-name
1.116 anton 7284: doc-latest
7285: doc->name
1.47 crook 7286: doc-name>int
7287: doc-name?int
7288: doc-name>comp
7289: doc-name>string
1.109 anton 7290: doc-id.
7291: doc-.name
7292: doc-.id
1.47 crook 7293:
1.81 anton 7294: @c ----------------------------------------------------------
7295: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7296: @section Compiling words
7297: @cindex compiling words
7298: @cindex macros
7299:
7300: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7301: between compilation and run-time. E.g., you can run arbitrary code
7302: between defining words (or for computing data used by defining words
7303: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7304: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7305: running arbitrary code while compiling a colon definition (exception:
7306: you must not allot dictionary space).
7307:
7308: @menu
7309: * Literals:: Compiling data values
7310: * Macros:: Compiling words
7311: @end menu
7312:
7313: @node Literals, Macros, Compiling words, Compiling words
7314: @subsection Literals
7315: @cindex Literals
7316:
7317: The simplest and most frequent example is to compute a literal during
7318: compilation. E.g., the following definition prints an array of strings,
7319: one string per line:
7320:
7321: @example
7322: : .strings ( addr u -- ) \ gforth
7323: 2* cells bounds U+DO
7324: cr i 2@@ type
7325: 2 cells +LOOP ;
7326: @end example
1.81 anton 7327:
1.82 anton 7328: With a simple-minded compiler like Gforth's, this computes @code{2
7329: cells} on every loop iteration. You can compute this value once and for
7330: all at compile time and compile it into the definition like this:
7331:
7332: @example
7333: : .strings ( addr u -- ) \ gforth
7334: 2* cells bounds U+DO
7335: cr i 2@@ type
7336: [ 2 cells ] literal +LOOP ;
7337: @end example
7338:
7339: @code{[} switches the text interpreter to interpret state (you will get
7340: an @code{ok} prompt if you type this example interactively and insert a
7341: newline between @code{[} and @code{]}), so it performs the
7342: interpretation semantics of @code{2 cells}; this computes a number.
7343: @code{]} switches the text interpreter back into compile state. It then
7344: performs @code{Literal}'s compilation semantics, which are to compile
7345: this number into the current word. You can decompile the word with
7346: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7347:
1.82 anton 7348: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7349: *} in this way.
1.81 anton 7350:
1.82 anton 7351: doc-[
7352: doc-]
1.81 anton 7353: doc-literal
7354: doc-]L
1.82 anton 7355:
7356: There are also words for compiling other data types than single cells as
7357: literals:
7358:
1.81 anton 7359: doc-2literal
7360: doc-fliteral
1.82 anton 7361: doc-sliteral
7362:
7363: @cindex colon-sys, passing data across @code{:}
7364: @cindex @code{:}, passing data across
7365: You might be tempted to pass data from outside a colon definition to the
7366: inside on the data stack. This does not work, because @code{:} puhes a
7367: colon-sys, making stuff below unaccessible. E.g., this does not work:
7368:
7369: @example
7370: 5 : foo literal ; \ error: "unstructured"
7371: @end example
7372:
7373: Instead, you have to pass the value in some other way, e.g., through a
7374: variable:
7375:
7376: @example
7377: variable temp
7378: 5 temp !
7379: : foo [ temp @@ ] literal ;
7380: @end example
7381:
7382:
7383: @node Macros, , Literals, Compiling words
7384: @subsection Macros
7385: @cindex Macros
7386: @cindex compiling compilation semantics
7387:
7388: @code{Literal} and friends compile data values into the current
7389: definition. You can also write words that compile other words into the
7390: current definition. E.g.,
7391:
7392: @example
7393: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7394: POSTPONE + ;
7395:
7396: : foo ( n1 n2 -- n )
7397: [ compile-+ ] ;
7398: 1 2 foo .
7399: @end example
7400:
7401: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7402: What happens in this example? @code{Postpone} compiles the compilation
7403: semantics of @code{+} into @code{compile-+}; later the text interpreter
7404: executes @code{compile-+} and thus the compilation semantics of +, which
7405: compile (the execution semantics of) @code{+} into
7406: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7407: should only be executed in compile state, so this example is not
7408: guaranteed to work on all standard systems, but on any decent system it
7409: will work.}
7410:
7411: doc-postpone
7412:
7413: Compiling words like @code{compile-+} are usually immediate (or similar)
7414: so you do not have to switch to interpret state to execute them;
1.206 anton 7415: modifying the last example accordingly produces:
1.82 anton 7416:
7417: @example
7418: : [compile-+] ( compilation: --; interpretation: -- )
7419: \ compiled code: ( n1 n2 -- n )
7420: POSTPONE + ; immediate
7421:
7422: : foo ( n1 n2 -- n )
7423: [compile-+] ;
7424: 1 2 foo .
7425: @end example
7426:
1.206 anton 7427: You will occassionally find the need to POSTPONE several words;
7428: putting POSTPONE before each such word is cumbersome, so Gforth
7429: provides a more convenient syntax: @code{]] ... [[}. This
7430: allows us to write @code{[compile-+]} as:
7431:
7432: @example
7433: : [compile-+] ( compilation: --; interpretation: -- )
7434: ]] + [[ ; immediate
7435: @end example
7436:
7437: doc-]]
7438: doc-[[
7439:
7440: The unusual direction of the brackets indicates their function:
7441: @code{]]} switches from compilation to postponing (i.e., compilation
7442: of compilation), just like @code{]} switches from immediate execution
7443: (interpretation) to compilation. Conversely, @code{[[} switches from
7444: postponing to compilation, ananlogous to @code{[} which switches from
7445: compilation to immediate execution.
7446:
7447: The real advantage of @code{]] }...@code{ [[} becomes apparent when
7448: there are many words to POSTPONE. E.g., the word
7449: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
7450: written much shorter as follows:
7451:
7452: @example
7453: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
7454: \ at run-time, execute xt ( ... x -- ... ) for each element of the
7455: \ array beginning at addr and containing u elements
7456: @{ xt @}
7457: ]] cells over + swap ?do
7458: i @@ [[ xt compile,
7459: 1 cells ]]L +loop [[ ;
7460: @end example
7461:
7462: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
7463: There are also other shortcuts
7464:
7465: doc-]]L
7466: doc-]]2L
7467: doc-]]FL
7468: doc-]]SL
7469:
7470: Note that parsing words don't parse at postpone time; if you want to
7471: provide the parsed string right away, you have to switch back to
7472: compilation:
7473:
7474: @example
7475: ]] ... [[ s" some string" ]]2L ... [[
7476: ]] ... [[ ['] + ]]L ... [[
7477: @end example
7478:
7479: Definitions of @code{]]} and friends in ANS Forth are provided in
7480: @file{compat/macros.fs}.
7481:
1.82 anton 7482: Immediate compiling words are similar to macros in other languages (in
7483: particular, Lisp). The important differences to macros in, e.g., C are:
7484:
7485: @itemize @bullet
7486:
7487: @item
7488: You use the same language for defining and processing macros, not a
7489: separate preprocessing language and processor.
7490:
7491: @item
7492: Consequently, the full power of Forth is available in macro definitions.
7493: E.g., you can perform arbitrarily complex computations, or generate
7494: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7495: Tutorial}). This power is very useful when writing a parser generators
7496: or other code-generating software.
7497:
7498: @item
7499: Macros defined using @code{postpone} etc. deal with the language at a
7500: higher level than strings; name binding happens at macro definition
7501: time, so you can avoid the pitfalls of name collisions that can happen
7502: in C macros. Of course, Forth is a liberal language and also allows to
7503: shoot yourself in the foot with text-interpreted macros like
7504:
7505: @example
7506: : [compile-+] s" +" evaluate ; immediate
7507: @end example
7508:
7509: Apart from binding the name at macro use time, using @code{evaluate}
7510: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7511: @end itemize
7512:
7513: You may want the macro to compile a number into a word. The word to do
7514: it is @code{literal}, but you have to @code{postpone} it, so its
7515: compilation semantics take effect when the macro is executed, not when
7516: it is compiled:
7517:
7518: @example
7519: : [compile-5] ( -- ) \ compiled code: ( -- n )
7520: 5 POSTPONE literal ; immediate
7521:
7522: : foo [compile-5] ;
7523: foo .
7524: @end example
7525:
7526: You may want to pass parameters to a macro, that the macro should
7527: compile into the current definition. If the parameter is a number, then
7528: you can use @code{postpone literal} (similar for other values).
7529:
7530: If you want to pass a word that is to be compiled, the usual way is to
7531: pass an execution token and @code{compile,} it:
7532:
7533: @example
7534: : twice1 ( xt -- ) \ compiled code: ... -- ...
7535: dup compile, compile, ;
7536:
7537: : 2+ ( n1 -- n2 )
7538: [ ' 1+ twice1 ] ;
7539: @end example
7540:
7541: doc-compile,
7542:
7543: An alternative available in Gforth, that allows you to pass compile-only
7544: words as parameters is to use the compilation token (@pxref{Compilation
7545: token}). The same example in this technique:
7546:
7547: @example
7548: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7549: 2dup 2>r execute 2r> execute ;
7550:
7551: : 2+ ( n1 -- n2 )
7552: [ comp' 1+ twice ] ;
7553: @end example
7554:
7555: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7556: works even if the executed compilation semantics has an effect on the
7557: data stack.
7558:
7559: You can also define complete definitions with these words; this provides
7560: an alternative to using @code{does>} (@pxref{User-defined Defining
7561: Words}). E.g., instead of
7562:
7563: @example
7564: : curry+ ( n1 "name" -- )
7565: CREATE ,
7566: DOES> ( n2 -- n1+n2 )
7567: @@ + ;
7568: @end example
7569:
7570: you could define
7571:
7572: @example
7573: : curry+ ( n1 "name" -- )
7574: \ name execution: ( n2 -- n1+n2 )
7575: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7576:
1.82 anton 7577: -3 curry+ 3-
7578: see 3-
7579: @end example
1.81 anton 7580:
1.82 anton 7581: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7582: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7583:
1.82 anton 7584: This way of writing defining words is sometimes more, sometimes less
7585: convenient than using @code{does>} (@pxref{Advanced does> usage
7586: example}). One advantage of this method is that it can be optimized
7587: better, because the compiler knows that the value compiled with
7588: @code{literal} is fixed, whereas the data associated with a
7589: @code{create}d word can be changed.
1.47 crook 7590:
1.206 anton 7591: @c doc-[compile] !! not properly documented
7592:
1.26 crook 7593: @c ----------------------------------------------------------
1.111 anton 7594: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7595: @section The Text Interpreter
7596: @cindex interpreter - outer
7597: @cindex text interpreter
7598: @cindex outer interpreter
1.1 anton 7599:
1.34 anton 7600: @c Should we really describe all these ugly details? IMO the text
7601: @c interpreter should be much cleaner, but that may not be possible within
7602: @c ANS Forth. - anton
1.44 crook 7603: @c nac-> I wanted to explain how it works to show how you can exploit
7604: @c it in your own programs. When I was writing a cross-compiler, figuring out
7605: @c some of these gory details was very helpful to me. None of the textbooks
7606: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7607: @c seems to positively avoid going into too much detail for some of
7608: @c the internals.
1.34 anton 7609:
1.71 anton 7610: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7611: @c it is; for the ugly details, I would prefer another place. I wonder
7612: @c whether we should have a chapter before "Words" that describes some
7613: @c basic concepts referred to in words, and a chapter after "Words" that
7614: @c describes implementation details.
7615:
1.29 crook 7616: The text interpreter@footnote{This is an expanded version of the
7617: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7618: that processes input from the current input device. It is also called
7619: the outer interpreter, in contrast to the inner interpreter
7620: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7621: implementations.
1.27 crook 7622:
1.29 crook 7623: @cindex interpret state
7624: @cindex compile state
7625: The text interpreter operates in one of two states: @dfn{interpret
7626: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7627: aptly-named variable @code{state}.
1.29 crook 7628:
7629: This section starts by describing how the text interpreter behaves when
7630: it is in interpret state, processing input from the user input device --
7631: the keyboard. This is the mode that a Forth system is in after it starts
7632: up.
7633:
7634: @cindex input buffer
7635: @cindex terminal input buffer
7636: The text interpreter works from an area of memory called the @dfn{input
7637: buffer}@footnote{When the text interpreter is processing input from the
7638: keyboard, this area of memory is called the @dfn{terminal input buffer}
7639: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7640: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7641: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7642: leading spaces (called @dfn{delimiters}) then parses a string (a
7643: sequence of non-space characters) until it reaches either a space
7644: character or the end of the buffer. Having parsed a string, it makes two
7645: attempts to process it:
1.27 crook 7646:
1.29 crook 7647: @cindex dictionary
1.27 crook 7648: @itemize @bullet
7649: @item
1.29 crook 7650: It looks for the string in a @dfn{dictionary} of definitions. If the
7651: string is found, the string names a @dfn{definition} (also known as a
7652: @dfn{word}) and the dictionary search returns information that allows
7653: the text interpreter to perform the word's @dfn{interpretation
7654: semantics}. In most cases, this simply means that the word will be
7655: executed.
1.27 crook 7656: @item
7657: If the string is not found in the dictionary, the text interpreter
1.29 crook 7658: attempts to treat it as a number, using the rules described in
7659: @ref{Number Conversion}. If the string represents a legal number in the
7660: current radix, the number is pushed onto a parameter stack (the data
7661: stack for integers, the floating-point stack for floating-point
7662: numbers).
7663: @end itemize
7664:
7665: If both attempts fail, or if the word is found in the dictionary but has
7666: no interpretation semantics@footnote{This happens if the word was
7667: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7668: remainder of the input buffer, issues an error message and waits for
7669: more input. If one of the attempts succeeds, the text interpreter
7670: repeats the parsing process until the whole of the input buffer has been
7671: processed, at which point it prints the status message ``@code{ ok}''
7672: and waits for more input.
7673:
1.71 anton 7674: @c anton: this should be in the input stream subsection (or below it)
7675:
1.29 crook 7676: @cindex parse area
7677: The text interpreter keeps track of its position in the input buffer by
7678: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7679: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7680: of the input buffer. The region from offset @code{>IN @@} to the end of
7681: the input buffer is called the @dfn{parse area}@footnote{In other words,
7682: the text interpreter processes the contents of the input buffer by
7683: parsing strings from the parse area until the parse area is empty.}.
7684: This example shows how @code{>IN} changes as the text interpreter parses
7685: the input buffer:
7686:
7687: @example
7688: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7689: CR ." ->" TYPE ." <-" ; IMMEDIATE
7690:
7691: 1 2 3 remaining + remaining .
7692:
7693: : foo 1 2 3 remaining SWAP remaining ;
7694: @end example
7695:
7696: @noindent
7697: The result is:
7698:
7699: @example
7700: ->+ remaining .<-
7701: ->.<-5 ok
7702:
7703: ->SWAP remaining ;-<
7704: ->;<- ok
7705: @end example
7706:
7707: @cindex parsing words
7708: The value of @code{>IN} can also be modified by a word in the input
7709: buffer that is executed by the text interpreter. This means that a word
7710: can ``trick'' the text interpreter into either skipping a section of the
7711: input buffer@footnote{This is how parsing words work.} or into parsing a
7712: section twice. For example:
1.27 crook 7713:
1.29 crook 7714: @example
1.71 anton 7715: : lat ." <<foo>>" ;
7716: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7717: @end example
7718:
7719: @noindent
7720: When @code{flat} is executed, this output is produced@footnote{Exercise
7721: for the reader: what would happen if the @code{3} were replaced with
7722: @code{4}?}:
7723:
7724: @example
1.71 anton 7725: <<bar>><<foo>>
1.29 crook 7726: @end example
7727:
1.71 anton 7728: This technique can be used to work around some of the interoperability
7729: problems of parsing words. Of course, it's better to avoid parsing
7730: words where possible.
7731:
1.29 crook 7732: @noindent
7733: Two important notes about the behaviour of the text interpreter:
1.27 crook 7734:
7735: @itemize @bullet
7736: @item
7737: It processes each input string to completion before parsing additional
1.29 crook 7738: characters from the input buffer.
7739: @item
7740: It treats the input buffer as a read-only region (and so must your code).
7741: @end itemize
7742:
7743: @noindent
7744: When the text interpreter is in compile state, its behaviour changes in
7745: these ways:
7746:
7747: @itemize @bullet
7748: @item
7749: If a parsed string is found in the dictionary, the text interpreter will
7750: perform the word's @dfn{compilation semantics}. In most cases, this
7751: simply means that the execution semantics of the word will be appended
7752: to the current definition.
1.27 crook 7753: @item
1.29 crook 7754: When a number is encountered, it is compiled into the current definition
7755: (as a literal) rather than being pushed onto a parameter stack.
7756: @item
7757: If an error occurs, @code{state} is modified to put the text interpreter
7758: back into interpret state.
7759: @item
7760: Each time a line is entered from the keyboard, Gforth prints
7761: ``@code{ compiled}'' rather than `` @code{ok}''.
7762: @end itemize
7763:
7764: @cindex text interpreter - input sources
7765: When the text interpreter is using an input device other than the
7766: keyboard, its behaviour changes in these ways:
7767:
7768: @itemize @bullet
7769: @item
7770: When the parse area is empty, the text interpreter attempts to refill
7771: the input buffer from the input source. When the input source is
1.71 anton 7772: exhausted, the input source is set back to the previous input source.
1.29 crook 7773: @item
7774: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7775: time the parse area is emptied.
7776: @item
7777: If an error occurs, the input source is set back to the user input
7778: device.
1.27 crook 7779: @end itemize
1.21 crook 7780:
1.49 anton 7781: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7782:
1.26 crook 7783: doc->in
1.27 crook 7784: doc-source
7785:
1.26 crook 7786: doc-tib
7787: doc-#tib
1.1 anton 7788:
1.44 crook 7789:
1.26 crook 7790: @menu
1.67 anton 7791: * Input Sources::
7792: * Number Conversion::
7793: * Interpret/Compile states::
7794: * Interpreter Directives::
1.26 crook 7795: @end menu
1.1 anton 7796:
1.29 crook 7797: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7798: @subsection Input Sources
7799: @cindex input sources
7800: @cindex text interpreter - input sources
7801:
1.44 crook 7802: By default, the text interpreter processes input from the user input
1.29 crook 7803: device (the keyboard) when Forth starts up. The text interpreter can
7804: process input from any of these sources:
7805:
7806: @itemize @bullet
7807: @item
7808: The user input device -- the keyboard.
7809: @item
7810: A file, using the words described in @ref{Forth source files}.
7811: @item
7812: A block, using the words described in @ref{Blocks}.
7813: @item
7814: A text string, using @code{evaluate}.
7815: @end itemize
7816:
7817: A program can identify the current input device from the values of
7818: @code{source-id} and @code{blk}.
7819:
1.44 crook 7820:
1.29 crook 7821: doc-source-id
7822: doc-blk
7823:
7824: doc-save-input
7825: doc-restore-input
7826:
7827: doc-evaluate
1.111 anton 7828: doc-query
1.1 anton 7829:
1.29 crook 7830:
1.44 crook 7831:
1.29 crook 7832: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7833: @subsection Number Conversion
7834: @cindex number conversion
7835: @cindex double-cell numbers, input format
7836: @cindex input format for double-cell numbers
7837: @cindex single-cell numbers, input format
7838: @cindex input format for single-cell numbers
7839: @cindex floating-point numbers, input format
7840: @cindex input format for floating-point numbers
1.1 anton 7841:
1.29 crook 7842: This section describes the rules that the text interpreter uses when it
7843: tries to convert a string into a number.
1.1 anton 7844:
1.26 crook 7845: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7846: number base@footnote{For example, 0-9 when the number base is decimal or
7847: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7848:
1.26 crook 7849: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7850:
1.29 crook 7851: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7852: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7853:
1.26 crook 7854: Let * represent any number of instances of the previous character
7855: (including none).
1.1 anton 7856:
1.26 crook 7857: Let any other character represent itself.
1.1 anton 7858:
1.29 crook 7859: @noindent
1.26 crook 7860: Now, the conversion rules are:
1.21 crook 7861:
1.26 crook 7862: @itemize @bullet
7863: @item
7864: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7865: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7866: @item
7867: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7868: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7869: arithmetic. Examples are -45 -5681 -0
7870: @item
7871: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7872: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7873: (all three of these represent the same number).
1.26 crook 7874: @item
7875: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7876: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7877: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7878: -34.65 (all three of these represent the same number).
1.26 crook 7879: @item
1.29 crook 7880: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7881: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7882: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7883: number) +12.E-4
1.26 crook 7884: @end itemize
1.1 anton 7885:
1.174 anton 7886: By default, the number base used for integer number conversion is
7887: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7888: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7889: change @code{base} anywhere, make sure to save the old value and
7890: restore it afterwards; better yet, use @code{base-execute}, which does
7891: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7892: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7893:
1.29 crook 7894: doc-dpl
1.174 anton 7895: doc-base-execute
1.26 crook 7896: doc-base
7897: doc-hex
7898: doc-decimal
1.1 anton 7899:
1.26 crook 7900: @cindex '-prefix for character strings
7901: @cindex &-prefix for decimal numbers
1.133 anton 7902: @cindex #-prefix for decimal numbers
1.26 crook 7903: @cindex %-prefix for binary numbers
7904: @cindex $-prefix for hexadecimal numbers
1.133 anton 7905: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7906: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7907: prefix@footnote{Some Forth implementations provide a similar scheme by
7908: implementing @code{$} etc. as parsing words that process the subsequent
7909: number in the input stream and push it onto the stack. For example, see
7910: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7911: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7912: is required between the prefix and the number.} before the first digit
1.133 anton 7913: of an (integer) number. The following prefixes are supported:
1.1 anton 7914:
1.26 crook 7915: @itemize @bullet
7916: @item
1.35 anton 7917: @code{&} -- decimal
1.26 crook 7918: @item
1.133 anton 7919: @code{#} -- decimal
7920: @item
1.35 anton 7921: @code{%} -- binary
1.26 crook 7922: @item
1.35 anton 7923: @code{$} -- hexadecimal
1.26 crook 7924: @item
1.133 anton 7925: @code{0x} -- hexadecimal, if base<33.
7926: @item
7927: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7928: optional @code{'} may be present after the character.
1.26 crook 7929: @end itemize
1.1 anton 7930:
1.26 crook 7931: Here are some examples, with the equivalent decimal number shown after
7932: in braces:
1.1 anton 7933:
1.26 crook 7934: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7935: 'A (65),
7936: -'a' (-97),
1.26 crook 7937: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7938:
1.26 crook 7939: @cindex number conversion - traps for the unwary
1.29 crook 7940: @noindent
1.26 crook 7941: Number conversion has a number of traps for the unwary:
1.1 anton 7942:
1.26 crook 7943: @itemize @bullet
7944: @item
7945: You cannot determine the current number base using the code sequence
1.35 anton 7946: @code{base @@ .} -- the number base is always 10 in the current number
7947: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7948: @item
7949: If the number base is set to a value greater than 14 (for example,
7950: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7951: it to be intepreted as either a single-precision integer or a
7952: floating-point number (Gforth treats it as an integer). The ambiguity
7953: can be resolved by explicitly stating the sign of the mantissa and/or
7954: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7955: ambiguity arises; either representation will be treated as a
7956: floating-point number.
7957: @item
1.29 crook 7958: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7959: It is used to specify file types.
7960: @item
1.72 anton 7961: ANS Forth requires the @code{.} of a double-precision number to be the
7962: final character in the string. Gforth allows the @code{.} to be
7963: anywhere after the first digit.
1.26 crook 7964: @item
7965: The number conversion process does not check for overflow.
7966: @item
1.72 anton 7967: In an ANS Forth program @code{base} is required to be decimal when
7968: converting floating-point numbers. In Gforth, number conversion to
7969: floating-point numbers always uses base &10, irrespective of the value
7970: of @code{base}.
1.26 crook 7971: @end itemize
1.1 anton 7972:
1.49 anton 7973: You can read numbers into your programs with the words described in
1.181 anton 7974: @ref{Line input and conversion}.
1.1 anton 7975:
1.82 anton 7976: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7977: @subsection Interpret/Compile states
7978: @cindex Interpret/Compile states
1.1 anton 7979:
1.29 crook 7980: A standard program is not permitted to change @code{state}
7981: explicitly. However, it can change @code{state} implicitly, using the
7982: words @code{[} and @code{]}. When @code{[} is executed it switches
7983: @code{state} to interpret state, and therefore the text interpreter
7984: starts interpreting. When @code{]} is executed it switches @code{state}
7985: to compile state and therefore the text interpreter starts
1.44 crook 7986: compiling. The most common usage for these words is for switching into
7987: interpret state and back from within a colon definition; this technique
1.49 anton 7988: can be used to compile a literal (for an example, @pxref{Literals}) or
7989: for conditional compilation (for an example, @pxref{Interpreter
7990: Directives}).
1.44 crook 7991:
1.35 anton 7992:
7993: @c This is a bad example: It's non-standard, and it's not necessary.
7994: @c However, I can't think of a good example for switching into compile
7995: @c state when there is no current word (@code{state}-smart words are not a
7996: @c good reason). So maybe we should use an example for switching into
7997: @c interpret @code{state} in a colon def. - anton
1.44 crook 7998: @c nac-> I agree. I started out by putting in the example, then realised
7999: @c that it was non-ANS, so wrote more words around it. I hope this
8000: @c re-written version is acceptable to you. I do want to keep the example
8001: @c as it is helpful for showing what is and what is not portable, particularly
8002: @c where it outlaws a style in common use.
8003:
1.72 anton 8004: @c anton: it's more important to show what's portable. After we have done
1.83 anton 8005: @c that, we can also show what's not. In any case, I have written a
8006: @c section Compiling Words which also deals with [ ].
1.35 anton 8007:
1.95 anton 8008: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 8009:
1.95 anton 8010: @c @code{[} and @code{]} also give you the ability to switch into compile
8011: @c state and back, but we cannot think of any useful Standard application
8012: @c for this ability. Pre-ANS Forth textbooks have examples like this:
8013:
8014: @c @example
8015: @c : AA ." this is A" ;
8016: @c : BB ." this is B" ;
8017: @c : CC ." this is C" ;
8018:
8019: @c create table ] aa bb cc [
8020:
8021: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
8022: @c cells table + @@ execute ;
8023: @c @end example
8024:
8025: @c This example builds a jump table; @code{0 go} will display ``@code{this
8026: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8027: @c defining @code{table} like this:
8028:
8029: @c @example
8030: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8031: @c @end example
8032:
8033: @c The problem with this code is that the definition of @code{table} is not
8034: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8035: @c @i{may} work on systems where code space and data space co-incide, the
8036: @c Standard only allows data space to be assigned for a @code{CREATE}d
8037: @c word. In addition, the Standard only allows @code{@@} to access data
8038: @c space, whilst this example is using it to access code space. The only
8039: @c portable, Standard way to build this table is to build it in data space,
8040: @c like this:
8041:
8042: @c @example
8043: @c create table ' aa , ' bb , ' cc ,
8044: @c @end example
1.29 crook 8045:
1.95 anton 8046: @c doc-state
1.44 crook 8047:
1.29 crook 8048:
1.82 anton 8049: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 8050: @subsection Interpreter Directives
8051: @cindex interpreter directives
1.72 anton 8052: @cindex conditional compilation
1.1 anton 8053:
1.29 crook 8054: These words are usually used in interpret state; typically to control
8055: which parts of a source file are processed by the text
1.26 crook 8056: interpreter. There are only a few ANS Forth Standard words, but Gforth
8057: supplements these with a rich set of immediate control structure words
8058: to compensate for the fact that the non-immediate versions can only be
1.29 crook 8059: used in compile state (@pxref{Control Structures}). Typical usages:
8060:
8061: @example
1.72 anton 8062: FALSE Constant HAVE-ASSEMBLER
1.29 crook 8063: .
8064: .
1.72 anton 8065: HAVE-ASSEMBLER [IF]
1.29 crook 8066: : ASSEMBLER-FEATURE
8067: ...
8068: ;
8069: [ENDIF]
8070: .
8071: .
8072: : SEE
8073: ... \ general-purpose SEE code
1.72 anton 8074: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8075: ... \ assembler-specific SEE code
8076: [ [ENDIF] ]
8077: ;
8078: @end example
1.1 anton 8079:
1.44 crook 8080:
1.26 crook 8081: doc-[IF]
8082: doc-[ELSE]
8083: doc-[THEN]
8084: doc-[ENDIF]
1.1 anton 8085:
1.26 crook 8086: doc-[IFDEF]
8087: doc-[IFUNDEF]
1.1 anton 8088:
1.26 crook 8089: doc-[?DO]
8090: doc-[DO]
8091: doc-[FOR]
8092: doc-[LOOP]
8093: doc-[+LOOP]
8094: doc-[NEXT]
1.1 anton 8095:
1.26 crook 8096: doc-[BEGIN]
8097: doc-[UNTIL]
8098: doc-[AGAIN]
8099: doc-[WHILE]
8100: doc-[REPEAT]
1.1 anton 8101:
1.27 crook 8102:
1.26 crook 8103: @c -------------------------------------------------------------
1.111 anton 8104: @node The Input Stream, Word Lists, The Text Interpreter, Words
8105: @section The Input Stream
8106: @cindex input stream
8107:
8108: @c !! integrate this better with the "Text Interpreter" section
8109: The text interpreter reads from the input stream, which can come from
8110: several sources (@pxref{Input Sources}). Some words, in particular
8111: defining words, but also words like @code{'}, read parameters from the
8112: input stream instead of from the stack.
8113:
8114: Such words are called parsing words, because they parse the input
8115: stream. Parsing words are hard to use in other words, because it is
8116: hard to pass program-generated parameters through the input stream.
8117: They also usually have an unintuitive combination of interpretation and
8118: compilation semantics when implemented naively, leading to various
8119: approaches that try to produce a more intuitive behaviour
8120: (@pxref{Combined words}).
8121:
8122: It should be obvious by now that parsing words are a bad idea. If you
8123: want to implement a parsing word for convenience, also provide a factor
8124: of the word that does not parse, but takes the parameters on the stack.
8125: To implement the parsing word on top if it, you can use the following
8126: words:
8127:
8128: @c anton: these belong in the input stream section
8129: doc-parse
1.138 anton 8130: doc-parse-name
1.111 anton 8131: doc-parse-word
8132: doc-name
8133: doc-word
8134: doc-refill
8135:
8136: Conversely, if you have the bad luck (or lack of foresight) to have to
8137: deal with parsing words without having such factors, how do you pass a
8138: string that is not in the input stream to it?
8139:
8140: doc-execute-parsing
8141:
1.146 anton 8142: A definition of this word in ANS Forth is provided in
8143: @file{compat/execute-parsing.fs}.
8144:
1.111 anton 8145: If you want to run a parsing word on a file, the following word should
8146: help:
8147:
8148: doc-execute-parsing-file
8149:
8150: @c -------------------------------------------------------------
8151: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8152: @section Word Lists
8153: @cindex word lists
1.32 anton 8154: @cindex header space
1.1 anton 8155:
1.36 anton 8156: A wordlist is a list of named words; you can add new words and look up
8157: words by name (and you can remove words in a restricted way with
8158: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8159:
8160: @cindex search order stack
8161: The text interpreter searches the wordlists present in the search order
8162: (a stack of wordlists), from the top to the bottom. Within each
8163: wordlist, the search starts conceptually at the newest word; i.e., if
8164: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8165:
1.26 crook 8166: @cindex compilation word list
1.36 anton 8167: New words are added to the @dfn{compilation wordlist} (aka current
8168: wordlist).
1.1 anton 8169:
1.36 anton 8170: @cindex wid
8171: A word list is identified by a cell-sized word list identifier (@i{wid})
8172: in much the same way as a file is identified by a file handle. The
8173: numerical value of the wid has no (portable) meaning, and might change
8174: from session to session.
1.1 anton 8175:
1.29 crook 8176: The ANS Forth ``Search order'' word set is intended to provide a set of
8177: low-level tools that allow various different schemes to be
1.74 anton 8178: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8179: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8180: Forth.
1.1 anton 8181:
1.27 crook 8182: @comment TODO: locals section refers to here, saying that every word list (aka
8183: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8184: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8185:
1.45 crook 8186: @comment TODO: document markers, reveal, tables, mappedwordlist
8187:
8188: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8189: @comment word from the source files, rather than some alias.
1.44 crook 8190:
1.26 crook 8191: doc-forth-wordlist
8192: doc-definitions
8193: doc-get-current
8194: doc-set-current
8195: doc-get-order
1.185 anton 8196: doc-set-order
1.26 crook 8197: doc-wordlist
1.30 anton 8198: doc-table
1.79 anton 8199: doc->order
1.36 anton 8200: doc-previous
1.26 crook 8201: doc-also
1.185 anton 8202: doc-forth
1.26 crook 8203: doc-only
1.185 anton 8204: doc-order
1.15 anton 8205:
1.26 crook 8206: doc-find
8207: doc-search-wordlist
1.15 anton 8208:
1.26 crook 8209: doc-words
8210: doc-vlist
1.44 crook 8211: @c doc-words-deferred
1.1 anton 8212:
1.74 anton 8213: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8214: doc-root
8215: doc-vocabulary
8216: doc-seal
8217: doc-vocs
8218: doc-current
8219: doc-context
1.1 anton 8220:
1.44 crook 8221:
1.26 crook 8222: @menu
1.75 anton 8223: * Vocabularies::
1.67 anton 8224: * Why use word lists?::
1.75 anton 8225: * Word list example::
1.26 crook 8226: @end menu
8227:
1.75 anton 8228: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8229: @subsection Vocabularies
8230: @cindex Vocabularies, detailed explanation
8231:
8232: Here is an example of creating and using a new wordlist using ANS
8233: Forth words:
8234:
8235: @example
8236: wordlist constant my-new-words-wordlist
8237: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8238:
8239: \ add it to the search order
8240: also my-new-words
8241:
8242: \ alternatively, add it to the search order and make it
8243: \ the compilation word list
8244: also my-new-words definitions
8245: \ type "order" to see the problem
8246: @end example
8247:
8248: The problem with this example is that @code{order} has no way to
8249: associate the name @code{my-new-words} with the wid of the word list (in
8250: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8251: that has no associated name). There is no Standard way of associating a
8252: name with a wid.
8253:
8254: In Gforth, this example can be re-coded using @code{vocabulary}, which
8255: associates a name with a wid:
8256:
8257: @example
8258: vocabulary my-new-words
8259:
8260: \ add it to the search order
8261: also my-new-words
8262:
8263: \ alternatively, add it to the search order and make it
8264: \ the compilation word list
8265: my-new-words definitions
8266: \ type "order" to see that the problem is solved
8267: @end example
8268:
8269:
8270: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8271: @subsection Why use word lists?
8272: @cindex word lists - why use them?
8273:
1.74 anton 8274: Here are some reasons why people use wordlists:
1.26 crook 8275:
8276: @itemize @bullet
1.74 anton 8277:
8278: @c anton: Gforth's hashing implementation makes the search speed
8279: @c independent from the number of words. But it is linear with the number
8280: @c of wordlists that have to be searched, so in effect using more wordlists
8281: @c actually slows down compilation.
8282:
8283: @c @item
8284: @c To improve compilation speed by reducing the number of header space
8285: @c entries that must be searched. This is achieved by creating a new
8286: @c word list that contains all of the definitions that are used in the
8287: @c definition of a Forth system but which would not usually be used by
8288: @c programs running on that system. That word list would be on the search
8289: @c list when the Forth system was compiled but would be removed from the
8290: @c search list for normal operation. This can be a useful technique for
8291: @c low-performance systems (for example, 8-bit processors in embedded
8292: @c systems) but is unlikely to be necessary in high-performance desktop
8293: @c systems.
8294:
1.26 crook 8295: @item
8296: To prevent a set of words from being used outside the context in which
8297: they are valid. Two classic examples of this are an integrated editor
8298: (all of the edit commands are defined in a separate word list; the
8299: search order is set to the editor word list when the editor is invoked;
8300: the old search order is restored when the editor is terminated) and an
8301: integrated assembler (the op-codes for the machine are defined in a
8302: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8303:
8304: @item
8305: To organize the words of an application or library into a user-visible
8306: set (in @code{forth-wordlist} or some other common wordlist) and a set
8307: of helper words used just for the implementation (hidden in a separate
1.75 anton 8308: wordlist). This keeps @code{words}' output smaller, separates
8309: implementation and interface, and reduces the chance of name conflicts
8310: within the common wordlist.
1.74 anton 8311:
1.26 crook 8312: @item
8313: To prevent a name-space clash between multiple definitions with the same
8314: name. For example, when building a cross-compiler you might have a word
8315: @code{IF} that generates conditional code for your target system. By
8316: placing this definition in a different word list you can control whether
8317: the host system's @code{IF} or the target system's @code{IF} get used in
8318: any particular context by controlling the order of the word lists on the
8319: search order stack.
1.74 anton 8320:
1.26 crook 8321: @end itemize
1.1 anton 8322:
1.74 anton 8323: The downsides of using wordlists are:
8324:
8325: @itemize
8326:
8327: @item
8328: Debugging becomes more cumbersome.
8329:
8330: @item
8331: Name conflicts worked around with wordlists are still there, and you
8332: have to arrange the search order carefully to get the desired results;
8333: if you forget to do that, you get hard-to-find errors (as in any case
8334: where you read the code differently from the compiler; @code{see} can
1.75 anton 8335: help seeing which of several possible words the name resolves to in such
8336: cases). @code{See} displays just the name of the words, not what
8337: wordlist they belong to, so it might be misleading. Using unique names
8338: is a better approach to avoid name conflicts.
1.74 anton 8339:
8340: @item
8341: You have to explicitly undo any changes to the search order. In many
8342: cases it would be more convenient if this happened implicitly. Gforth
8343: currently does not provide such a feature, but it may do so in the
8344: future.
8345: @end itemize
8346:
8347:
1.75 anton 8348: @node Word list example, , Why use word lists?, Word Lists
8349: @subsection Word list example
8350: @cindex word lists - example
1.1 anton 8351:
1.74 anton 8352: The following example is from the
8353: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8354: garbage collector} and uses wordlists to separate public words from
8355: helper words:
8356:
8357: @example
8358: get-current ( wid )
8359: vocabulary garbage-collector also garbage-collector definitions
8360: ... \ define helper words
8361: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8362: ... \ define the public (i.e., API) words
8363: \ they can refer to the helper words
8364: previous \ restore original search order (helper words become invisible)
8365: @end example
8366:
1.26 crook 8367: @c -------------------------------------------------------------
8368: @node Environmental Queries, Files, Word Lists, Words
8369: @section Environmental Queries
8370: @cindex environmental queries
1.21 crook 8371:
1.26 crook 8372: ANS Forth introduced the idea of ``environmental queries'' as a way
8373: for a program running on a system to determine certain characteristics of the system.
8374: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8375:
1.32 anton 8376: The Standard requires that the header space used for environmental queries
8377: be distinct from the header space used for definitions.
1.21 crook 8378:
1.26 crook 8379: Typically, environmental queries are supported by creating a set of
1.29 crook 8380: definitions in a word list that is @i{only} used during environmental
1.26 crook 8381: queries; that is what Gforth does. There is no Standard way of adding
8382: definitions to the set of recognised environmental queries, but any
8383: implementation that supports the loading of optional word sets must have
8384: some mechanism for doing this (after loading the word set, the
8385: associated environmental query string must return @code{true}). In
8386: Gforth, the word list used to honour environmental queries can be
8387: manipulated just like any other word list.
1.21 crook 8388:
1.44 crook 8389:
1.26 crook 8390: doc-environment?
8391: doc-environment-wordlist
1.21 crook 8392:
1.26 crook 8393: doc-gforth
8394: doc-os-class
1.21 crook 8395:
1.44 crook 8396:
1.26 crook 8397: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8398: returning two items on the stack, querying it using @code{environment?}
8399: will return an additional item; the @code{true} flag that shows that the
8400: string was recognised.
1.21 crook 8401:
1.26 crook 8402: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8403:
1.26 crook 8404: Here are some examples of using environmental queries:
1.21 crook 8405:
1.26 crook 8406: @example
8407: s" address-unit-bits" environment? 0=
8408: [IF]
8409: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8410: [ELSE]
8411: drop \ ensure balanced stack effect
1.26 crook 8412: [THEN]
1.21 crook 8413:
1.75 anton 8414: \ this might occur in the prelude of a standard program that uses THROW
8415: s" exception" environment? [IF]
8416: 0= [IF]
8417: : throw abort" exception thrown" ;
8418: [THEN]
8419: [ELSE] \ we don't know, so make sure
8420: : throw abort" exception thrown" ;
8421: [THEN]
1.21 crook 8422:
1.26 crook 8423: s" gforth" environment? [IF] .( Gforth version ) TYPE
8424: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8425:
8426: \ a program using v*
8427: s" gforth" environment? [IF]
8428: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8429: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8430: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8431: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8432: LOOP
8433: 2drop 2drop ;
8434: [THEN]
8435: [ELSE] \
8436: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8437: ...
8438: [THEN]
1.26 crook 8439: @end example
1.21 crook 8440:
1.26 crook 8441: Here is an example of adding a definition to the environment word list:
1.21 crook 8442:
1.26 crook 8443: @example
8444: get-current environment-wordlist set-current
8445: true constant block
8446: true constant block-ext
8447: set-current
8448: @end example
1.21 crook 8449:
1.26 crook 8450: You can see what definitions are in the environment word list like this:
1.21 crook 8451:
1.26 crook 8452: @example
1.79 anton 8453: environment-wordlist >order words previous
1.26 crook 8454: @end example
1.21 crook 8455:
8456:
1.26 crook 8457: @c -------------------------------------------------------------
8458: @node Files, Blocks, Environmental Queries, Words
8459: @section Files
1.28 crook 8460: @cindex files
8461: @cindex I/O - file-handling
1.21 crook 8462:
1.26 crook 8463: Gforth provides facilities for accessing files that are stored in the
8464: host operating system's file-system. Files that are processed by Gforth
8465: can be divided into two categories:
1.21 crook 8466:
1.23 crook 8467: @itemize @bullet
8468: @item
1.29 crook 8469: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8470: @item
1.29 crook 8471: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8472: @end itemize
8473:
8474: @menu
1.48 anton 8475: * Forth source files::
8476: * General files::
1.167 anton 8477: * Redirection::
1.48 anton 8478: * Search Paths::
1.26 crook 8479: @end menu
8480:
8481: @c -------------------------------------------------------------
8482: @node Forth source files, General files, Files, Files
8483: @subsection Forth source files
8484: @cindex including files
8485: @cindex Forth source files
1.21 crook 8486:
1.26 crook 8487: The simplest way to interpret the contents of a file is to use one of
8488: these two formats:
1.21 crook 8489:
1.26 crook 8490: @example
8491: include mysource.fs
8492: s" mysource.fs" included
8493: @end example
1.21 crook 8494:
1.75 anton 8495: You usually want to include a file only if it is not included already
1.26 crook 8496: (by, say, another source file). In that case, you can use one of these
1.45 crook 8497: three formats:
1.21 crook 8498:
1.26 crook 8499: @example
8500: require mysource.fs
8501: needs mysource.fs
8502: s" mysource.fs" required
8503: @end example
1.21 crook 8504:
1.26 crook 8505: @cindex stack effect of included files
8506: @cindex including files, stack effect
1.45 crook 8507: It is good practice to write your source files such that interpreting them
8508: does not change the stack. Source files designed in this way can be used with
1.26 crook 8509: @code{required} and friends without complications. For example:
1.21 crook 8510:
1.26 crook 8511: @example
1.75 anton 8512: 1024 require foo.fs drop
1.26 crook 8513: @end example
1.21 crook 8514:
1.75 anton 8515: Here you want to pass the argument 1024 (e.g., a buffer size) to
8516: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8517: ), which allows its use with @code{require}. Of course with such
8518: parameters to required files, you have to ensure that the first
8519: @code{require} fits for all uses (i.e., @code{require} it early in the
8520: master load file).
1.44 crook 8521:
1.26 crook 8522: doc-include-file
8523: doc-included
1.28 crook 8524: doc-included?
1.26 crook 8525: doc-include
8526: doc-required
8527: doc-require
8528: doc-needs
1.75 anton 8529: @c doc-init-included-files @c internal
8530: doc-sourcefilename
8531: doc-sourceline#
1.44 crook 8532:
1.26 crook 8533: A definition in ANS Forth for @code{required} is provided in
8534: @file{compat/required.fs}.
1.21 crook 8535:
1.26 crook 8536: @c -------------------------------------------------------------
1.167 anton 8537: @node General files, Redirection, Forth source files, Files
1.26 crook 8538: @subsection General files
8539: @cindex general files
8540: @cindex file-handling
1.21 crook 8541:
1.75 anton 8542: Files are opened/created by name and type. The following file access
8543: methods (FAMs) are recognised:
1.44 crook 8544:
1.75 anton 8545: @cindex fam (file access method)
1.26 crook 8546: doc-r/o
8547: doc-r/w
8548: doc-w/o
8549: doc-bin
1.1 anton 8550:
1.44 crook 8551:
1.26 crook 8552: When a file is opened/created, it returns a file identifier,
1.29 crook 8553: @i{wfileid} that is used for all other file commands. All file
8554: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8555: successful operation and an implementation-defined non-zero value in the
8556: case of an error.
1.21 crook 8557:
1.44 crook 8558:
1.26 crook 8559: doc-open-file
8560: doc-create-file
1.21 crook 8561:
1.26 crook 8562: doc-close-file
8563: doc-delete-file
8564: doc-rename-file
8565: doc-read-file
8566: doc-read-line
1.154 anton 8567: doc-key-file
8568: doc-key?-file
1.26 crook 8569: doc-write-file
8570: doc-write-line
8571: doc-emit-file
8572: doc-flush-file
1.21 crook 8573:
1.26 crook 8574: doc-file-status
8575: doc-file-position
8576: doc-reposition-file
8577: doc-file-size
8578: doc-resize-file
1.21 crook 8579:
1.93 anton 8580: doc-slurp-file
8581: doc-slurp-fid
1.112 anton 8582: doc-stdin
8583: doc-stdout
8584: doc-stderr
1.44 crook 8585:
1.26 crook 8586: @c ---------------------------------------------------------
1.167 anton 8587: @node Redirection, Search Paths, General files, Files
8588: @subsection Redirection
8589: @cindex Redirection
8590: @cindex Input Redirection
8591: @cindex Output Redirection
8592:
8593: You can redirect the output of @code{type} and @code{emit} and all the
8594: words that use them (all output words that don't have an explicit
1.174 anton 8595: target file) to an arbitrary file with the @code{outfile-execute},
8596: used like this:
1.167 anton 8597:
8598: @example
1.174 anton 8599: : some-warning ( n -- )
8600: cr ." warning# " . ;
8601:
1.167 anton 8602: : print-some-warning ( n -- )
1.174 anton 8603: ['] some-warning stderr outfile-execute ;
1.167 anton 8604: @end example
8605:
1.174 anton 8606: After @code{some-warning} is executed, the original output direction
8607: is restored; this construct is safe against exceptions. Similarly,
8608: there is @code{infile-execute} for redirecting the input of @code{key}
8609: and its users (any input word that does not take a file explicitly).
8610:
8611: doc-outfile-execute
8612: doc-infile-execute
1.167 anton 8613:
8614: If you do not want to redirect the input or output to a file, you can
8615: also make use of the fact that @code{key}, @code{emit} and @code{type}
8616: are deferred words (@pxref{Deferred Words}). However, in that case
8617: you have to worry about the restoration and the protection against
8618: exceptions yourself; also, note that for redirecting the output in
8619: this way, you have to redirect both @code{emit} and @code{type}.
8620:
8621: @c ---------------------------------------------------------
8622: @node Search Paths, , Redirection, Files
1.26 crook 8623: @subsection Search Paths
8624: @cindex path for @code{included}
8625: @cindex file search path
8626: @cindex @code{include} search path
8627: @cindex search path for files
1.21 crook 8628:
1.26 crook 8629: If you specify an absolute filename (i.e., a filename starting with
8630: @file{/} or @file{~}, or with @file{:} in the second position (as in
8631: @samp{C:...})) for @code{included} and friends, that file is included
8632: just as you would expect.
1.21 crook 8633:
1.75 anton 8634: If the filename starts with @file{./}, this refers to the directory that
8635: the present file was @code{included} from. This allows files to include
8636: other files relative to their own position (irrespective of the current
8637: working directory or the absolute position). This feature is essential
8638: for libraries consisting of several files, where a file may include
8639: other files from the library. It corresponds to @code{#include "..."}
8640: in C. If the current input source is not a file, @file{.} refers to the
8641: directory of the innermost file being included, or, if there is no file
8642: being included, to the current working directory.
8643:
8644: For relative filenames (not starting with @file{./}), Gforth uses a
8645: search path similar to Forth's search order (@pxref{Word Lists}). It
8646: tries to find the given filename in the directories present in the path,
8647: and includes the first one it finds. There are separate search paths for
8648: Forth source files and general files. If the search path contains the
8649: directory @file{.}, this refers to the directory of the current file, or
8650: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8651:
1.26 crook 8652: Use @file{~+} to refer to the current working directory (as in the
8653: @code{bash}).
1.1 anton 8654:
1.75 anton 8655: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8656:
1.48 anton 8657: @menu
1.75 anton 8658: * Source Search Paths::
1.48 anton 8659: * General Search Paths::
8660: @end menu
8661:
1.26 crook 8662: @c ---------------------------------------------------------
1.75 anton 8663: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8664: @subsubsection Source Search Paths
8665: @cindex search path control, source files
1.5 anton 8666:
1.26 crook 8667: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8668: Gforth}). You can display it and change it using @code{fpath} in
8669: combination with the general path handling words.
1.5 anton 8670:
1.75 anton 8671: doc-fpath
8672: @c the functionality of the following words is easily available through
8673: @c fpath and the general path words. The may go away.
8674: @c doc-.fpath
8675: @c doc-fpath+
8676: @c doc-fpath=
8677: @c doc-open-fpath-file
1.44 crook 8678:
8679: @noindent
1.26 crook 8680: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8681:
1.26 crook 8682: @example
1.75 anton 8683: fpath path= /usr/lib/forth/|./
1.26 crook 8684: require timer.fs
8685: @end example
1.5 anton 8686:
1.75 anton 8687:
1.26 crook 8688: @c ---------------------------------------------------------
1.75 anton 8689: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8690: @subsubsection General Search Paths
1.75 anton 8691: @cindex search path control, source files
1.5 anton 8692:
1.26 crook 8693: Your application may need to search files in several directories, like
8694: @code{included} does. To facilitate this, Gforth allows you to define
8695: and use your own search paths, by providing generic equivalents of the
8696: Forth search path words:
1.5 anton 8697:
1.75 anton 8698: doc-open-path-file
8699: doc-path-allot
8700: doc-clear-path
8701: doc-also-path
1.26 crook 8702: doc-.path
8703: doc-path+
8704: doc-path=
1.5 anton 8705:
1.75 anton 8706: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8707:
1.75 anton 8708: Here's an example of creating an empty search path:
8709: @c
1.26 crook 8710: @example
1.75 anton 8711: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8712: @end example
1.5 anton 8713:
1.26 crook 8714: @c -------------------------------------------------------------
8715: @node Blocks, Other I/O, Files, Words
8716: @section Blocks
1.28 crook 8717: @cindex I/O - blocks
8718: @cindex blocks
8719:
8720: When you run Gforth on a modern desk-top computer, it runs under the
8721: control of an operating system which provides certain services. One of
8722: these services is @var{file services}, which allows Forth source code
8723: and data to be stored in files and read into Gforth (@pxref{Files}).
8724:
8725: Traditionally, Forth has been an important programming language on
8726: systems where it has interfaced directly to the underlying hardware with
8727: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8728: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8729:
8730: A block is a 1024-byte data area, which can be used to hold data or
8731: Forth source code. No structure is imposed on the contents of the
8732: block. A block is identified by its number; blocks are numbered
8733: contiguously from 1 to an implementation-defined maximum.
8734:
8735: A typical system that used blocks but no operating system might use a
8736: single floppy-disk drive for mass storage, with the disks formatted to
8737: provide 256-byte sectors. Blocks would be implemented by assigning the
8738: first four sectors of the disk to block 1, the second four sectors to
8739: block 2 and so on, up to the limit of the capacity of the disk. The disk
8740: would not contain any file system information, just the set of blocks.
8741:
1.29 crook 8742: @cindex blocks file
1.28 crook 8743: On systems that do provide file services, blocks are typically
1.29 crook 8744: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8745: file}. The size of the blocks file will be an exact multiple of 1024
8746: bytes, corresponding to the number of blocks it contains. This is the
8747: mechanism that Gforth uses.
8748:
1.29 crook 8749: @cindex @file{blocks.fb}
1.75 anton 8750: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8751: having specified a blocks file, Gforth defaults to the blocks file
8752: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8753: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8754:
1.29 crook 8755: @cindex block buffers
1.28 crook 8756: When you read and write blocks under program control, Gforth uses a
1.29 crook 8757: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8758: not used when you use @code{load} to interpret the contents of a block.
8759:
1.75 anton 8760: The behaviour of the block buffers is analagous to that of a cache.
8761: Each block buffer has three states:
1.28 crook 8762:
8763: @itemize @bullet
8764: @item
8765: Unassigned
8766: @item
8767: Assigned-clean
8768: @item
8769: Assigned-dirty
8770: @end itemize
8771:
1.29 crook 8772: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8773: block, the block (specified by its block number) must be assigned to a
8774: block buffer.
8775:
8776: The assignment of a block to a block buffer is performed by @code{block}
8777: or @code{buffer}. Use @code{block} when you wish to modify the existing
8778: contents of a block. Use @code{buffer} when you don't care about the
8779: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8780: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8781: with the particular block is already stored in a block buffer due to an
8782: earlier @code{block} command, @code{buffer} will return that block
8783: buffer and the existing contents of the block will be
8784: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8785: block buffer for the block.}.
1.28 crook 8786:
1.47 crook 8787: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8788: @code{buffer}, that block buffer becomes the @i{current block
8789: buffer}. Data may only be manipulated (read or written) within the
8790: current block buffer.
1.47 crook 8791:
8792: When the contents of the current block buffer has been modified it is
1.48 anton 8793: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8794: either abandon the changes (by doing nothing) or mark the block as
8795: changed (assigned-dirty), using @code{update}. Using @code{update} does
8796: not change the blocks file; it simply changes a block buffer's state to
8797: @i{assigned-dirty}. The block will be written implicitly when it's
8798: buffer is needed for another block, or explicitly by @code{flush} or
8799: @code{save-buffers}.
8800:
8801: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8802: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8803: @code{flush}.
1.28 crook 8804:
1.29 crook 8805: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8806: algorithm to assign a block buffer to a block. That means that any
8807: particular block can only be assigned to one specific block buffer,
1.29 crook 8808: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8809: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8810: the new block immediately. If it is @i{assigned-dirty} its current
8811: contents are written back to the blocks file on disk before it is
1.28 crook 8812: allocated to the new block.
8813:
8814: Although no structure is imposed on the contents of a block, it is
8815: traditional to display the contents as 16 lines each of 64 characters. A
8816: block provides a single, continuous stream of input (for example, it
8817: acts as a single parse area) -- there are no end-of-line characters
8818: within a block, and no end-of-file character at the end of a
8819: block. There are two consequences of this:
1.26 crook 8820:
1.28 crook 8821: @itemize @bullet
8822: @item
8823: The last character of one line wraps straight into the first character
8824: of the following line
8825: @item
8826: The word @code{\} -- comment to end of line -- requires special
8827: treatment; in the context of a block it causes all characters until the
8828: end of the current 64-character ``line'' to be ignored.
8829: @end itemize
8830:
8831: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8832: the current blocks file will be extended to the appropriate size and the
1.28 crook 8833: block buffer will be initialised with spaces.
8834:
1.47 crook 8835: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8836: for details) but doesn't encourage the use of blocks; the mechanism is
8837: only provided for backward compatibility -- ANS Forth requires blocks to
8838: be available when files are.
1.28 crook 8839:
8840: Common techniques that are used when working with blocks include:
8841:
8842: @itemize @bullet
8843: @item
8844: A screen editor that allows you to edit blocks without leaving the Forth
8845: environment.
8846: @item
8847: Shadow screens; where every code block has an associated block
8848: containing comments (for example: code in odd block numbers, comments in
8849: even block numbers). Typically, the block editor provides a convenient
8850: mechanism to toggle between code and comments.
8851: @item
8852: Load blocks; a single block (typically block 1) contains a number of
8853: @code{thru} commands which @code{load} the whole of the application.
8854: @end itemize
1.26 crook 8855:
1.29 crook 8856: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8857: integrated into a Forth programming environment.
1.26 crook 8858:
8859: @comment TODO what about errors on open-blocks?
1.44 crook 8860:
1.26 crook 8861: doc-open-blocks
8862: doc-use
1.75 anton 8863: doc-block-offset
1.26 crook 8864: doc-get-block-fid
8865: doc-block-position
1.28 crook 8866:
1.75 anton 8867: doc-list
1.28 crook 8868: doc-scr
8869:
1.184 anton 8870: doc-block
1.28 crook 8871: doc-buffer
8872:
1.75 anton 8873: doc-empty-buffers
8874: doc-empty-buffer
1.26 crook 8875: doc-update
1.28 crook 8876: doc-updated?
1.26 crook 8877: doc-save-buffers
1.75 anton 8878: doc-save-buffer
1.26 crook 8879: doc-flush
1.28 crook 8880:
1.26 crook 8881: doc-load
8882: doc-thru
8883: doc-+load
8884: doc-+thru
1.45 crook 8885: doc---gforthman--->
1.26 crook 8886: doc-block-included
8887:
1.44 crook 8888:
1.26 crook 8889: @c -------------------------------------------------------------
1.126 pazsan 8890: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8891: @section Other I/O
1.28 crook 8892: @cindex I/O - keyboard and display
1.26 crook 8893:
8894: @menu
8895: * Simple numeric output:: Predefined formats
8896: * Formatted numeric output:: Formatted (pictured) output
8897: * String Formats:: How Forth stores strings in memory
1.67 anton 8898: * Displaying characters and strings:: Other stuff
1.175 anton 8899: * Terminal output:: Cursor positioning etc.
1.181 anton 8900: * Single-key input::
8901: * Line input and conversion::
1.112 anton 8902: * Pipes:: How to create your own pipes
1.149 pazsan 8903: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8904: @end menu
8905:
8906: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8907: @subsection Simple numeric output
1.28 crook 8908: @cindex numeric output - simple/free-format
1.5 anton 8909:
1.26 crook 8910: The simplest output functions are those that display numbers from the
8911: data or floating-point stacks. Floating-point output is always displayed
8912: using base 10. Numbers displayed from the data stack use the value stored
8913: in @code{base}.
1.5 anton 8914:
1.44 crook 8915:
1.26 crook 8916: doc-.
8917: doc-dec.
8918: doc-hex.
8919: doc-u.
8920: doc-.r
8921: doc-u.r
8922: doc-d.
8923: doc-ud.
8924: doc-d.r
8925: doc-ud.r
8926: doc-f.
8927: doc-fe.
8928: doc-fs.
1.111 anton 8929: doc-f.rdp
1.44 crook 8930:
1.26 crook 8931: Examples of printing the number 1234.5678E23 in the different floating-point output
8932: formats are shown below:
1.5 anton 8933:
8934: @example
1.26 crook 8935: f. 123456779999999000000000000.
8936: fe. 123.456779999999E24
8937: fs. 1.23456779999999E26
1.5 anton 8938: @end example
8939:
8940:
1.26 crook 8941: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8942: @subsection Formatted numeric output
1.28 crook 8943: @cindex formatted numeric output
1.26 crook 8944: @cindex pictured numeric output
1.28 crook 8945: @cindex numeric output - formatted
1.26 crook 8946:
1.29 crook 8947: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8948: output} for formatted printing of integers. In this technique, digits
8949: are extracted from the number (using the current output radix defined by
8950: @code{base}), converted to ASCII codes and appended to a string that is
8951: built in a scratch-pad area of memory (@pxref{core-idef,
8952: Implementation-defined options, Implementation-defined
8953: options}). Arbitrary characters can be appended to the string during the
8954: extraction process. The completed string is specified by an address
8955: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8956: under program control.
1.5 anton 8957:
1.75 anton 8958: All of the integer output words described in the previous section
8959: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8960: numeric output.
1.5 anton 8961:
1.47 crook 8962: Three important things to remember about pictured numeric output:
1.5 anton 8963:
1.26 crook 8964: @itemize @bullet
8965: @item
1.28 crook 8966: It always operates on double-precision numbers; to display a
1.49 anton 8967: single-precision number, convert it first (for ways of doing this
8968: @pxref{Double precision}).
1.26 crook 8969: @item
1.28 crook 8970: It always treats the double-precision number as though it were
8971: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8972: @item
8973: The string is built up from right to left; least significant digit first.
8974: @end itemize
1.5 anton 8975:
1.44 crook 8976:
1.26 crook 8977: doc-<#
1.47 crook 8978: doc-<<#
1.26 crook 8979: doc-#
8980: doc-#s
8981: doc-hold
8982: doc-sign
8983: doc-#>
1.47 crook 8984: doc-#>>
1.5 anton 8985:
1.26 crook 8986: doc-represent
1.111 anton 8987: doc-f>str-rdp
8988: doc-f>buf-rdp
1.5 anton 8989:
1.44 crook 8990:
8991: @noindent
1.26 crook 8992: Here are some examples of using pictured numeric output:
1.5 anton 8993:
8994: @example
1.26 crook 8995: : my-u. ( u -- )
8996: \ Simplest use of pns.. behaves like Standard u.
8997: 0 \ convert to unsigned double
1.75 anton 8998: <<# \ start conversion
1.26 crook 8999: #s \ convert all digits
9000: #> \ complete conversion
1.75 anton 9001: TYPE SPACE \ display, with trailing space
9002: #>> ; \ release hold area
1.5 anton 9003:
1.26 crook 9004: : cents-only ( u -- )
9005: 0 \ convert to unsigned double
1.75 anton 9006: <<# \ start conversion
1.26 crook 9007: # # \ convert two least-significant digits
9008: #> \ complete conversion, discard other digits
1.75 anton 9009: TYPE SPACE \ display, with trailing space
9010: #>> ; \ release hold area
1.5 anton 9011:
1.26 crook 9012: : dollars-and-cents ( u -- )
9013: 0 \ convert to unsigned double
1.75 anton 9014: <<# \ start conversion
1.26 crook 9015: # # \ convert two least-significant digits
9016: [char] . hold \ insert decimal point
9017: #s \ convert remaining digits
9018: [char] $ hold \ append currency symbol
9019: #> \ complete conversion
1.75 anton 9020: TYPE SPACE \ display, with trailing space
9021: #>> ; \ release hold area
1.5 anton 9022:
1.26 crook 9023: : my-. ( n -- )
9024: \ handling negatives.. behaves like Standard .
9025: s>d \ convert to signed double
9026: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9027: <<# \ start conversion
1.26 crook 9028: #s \ convert all digits
9029: rot sign \ get at sign byte, append "-" if needed
9030: #> \ complete conversion
1.75 anton 9031: TYPE SPACE \ display, with trailing space
9032: #>> ; \ release hold area
1.5 anton 9033:
1.26 crook 9034: : account. ( n -- )
1.75 anton 9035: \ accountants don't like minus signs, they use parentheses
1.26 crook 9036: \ for negative numbers
9037: s>d \ convert to signed double
9038: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9039: <<# \ start conversion
1.26 crook 9040: 2 pick \ get copy of sign byte
9041: 0< IF [char] ) hold THEN \ right-most character of output
9042: #s \ convert all digits
9043: rot \ get at sign byte
9044: 0< IF [char] ( hold THEN
9045: #> \ complete conversion
1.75 anton 9046: TYPE SPACE \ display, with trailing space
9047: #>> ; \ release hold area
9048:
1.5 anton 9049: @end example
9050:
1.26 crook 9051: Here are some examples of using these words:
1.5 anton 9052:
9053: @example
1.26 crook 9054: 1 my-u. 1
9055: hex -1 my-u. decimal FFFFFFFF
9056: 1 cents-only 01
9057: 1234 cents-only 34
9058: 2 dollars-and-cents $0.02
9059: 1234 dollars-and-cents $12.34
9060: 123 my-. 123
9061: -123 my. -123
9062: 123 account. 123
9063: -456 account. (456)
1.5 anton 9064: @end example
9065:
9066:
1.26 crook 9067: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9068: @subsection String Formats
1.27 crook 9069: @cindex strings - see character strings
9070: @cindex character strings - formats
1.28 crook 9071: @cindex I/O - see character strings
1.75 anton 9072: @cindex counted strings
9073:
9074: @c anton: this does not really belong here; maybe the memory section,
9075: @c or the principles chapter
1.26 crook 9076:
1.27 crook 9077: Forth commonly uses two different methods for representing character
9078: strings:
1.26 crook 9079:
9080: @itemize @bullet
9081: @item
9082: @cindex address of counted string
1.45 crook 9083: @cindex counted string
1.29 crook 9084: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9085: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9086: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9087: memory.
9088: @item
1.29 crook 9089: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9090: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9091: first byte of the string.
9092: @end itemize
9093:
9094: ANS Forth encourages the use of the second format when representing
1.75 anton 9095: strings.
1.26 crook 9096:
1.44 crook 9097:
1.26 crook 9098: doc-count
9099:
1.44 crook 9100:
1.49 anton 9101: For words that move, copy and search for strings see @ref{Memory
9102: Blocks}. For words that display characters and strings see
9103: @ref{Displaying characters and strings}.
1.26 crook 9104:
1.175 anton 9105: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9106: @subsection Displaying characters and strings
1.27 crook 9107: @cindex characters - compiling and displaying
9108: @cindex character strings - compiling and displaying
1.26 crook 9109:
9110: This section starts with a glossary of Forth words and ends with a set
9111: of examples.
9112:
9113: doc-bl
9114: doc-space
9115: doc-spaces
9116: doc-emit
9117: doc-toupper
9118: doc-."
9119: doc-.(
1.98 anton 9120: doc-.\"
1.26 crook 9121: doc-type
1.44 crook 9122: doc-typewhite
1.26 crook 9123: doc-cr
1.27 crook 9124: @cindex cursor control
1.26 crook 9125: doc-s"
1.98 anton 9126: doc-s\"
1.26 crook 9127: doc-c"
9128: doc-char
9129: doc-[char]
9130:
1.44 crook 9131:
9132: @noindent
1.26 crook 9133: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9134:
9135: @example
1.26 crook 9136: .( text-1)
9137: : my-word
9138: ." text-2" cr
9139: .( text-3)
9140: ;
9141:
9142: ." text-4"
9143:
9144: : my-char
9145: [char] ALPHABET emit
9146: char emit
9147: ;
1.5 anton 9148: @end example
9149:
1.26 crook 9150: When you load this code into Gforth, the following output is generated:
1.5 anton 9151:
1.26 crook 9152: @example
1.30 anton 9153: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9154: @end example
1.5 anton 9155:
1.26 crook 9156: @itemize @bullet
9157: @item
9158: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9159: is an immediate word; it behaves in the same way whether it is used inside
9160: or outside a colon definition.
9161: @item
9162: Message @code{text-4} is displayed because of Gforth's added interpretation
9163: semantics for @code{."}.
9164: @item
1.29 crook 9165: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9166: performs the compilation semantics for @code{."} within the definition of
9167: @code{my-word}.
9168: @end itemize
1.5 anton 9169:
1.26 crook 9170: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9171:
1.26 crook 9172: @example
1.30 anton 9173: @kbd{my-word @key{RET}} text-2
1.26 crook 9174: ok
1.30 anton 9175: @kbd{my-char fred @key{RET}} Af ok
9176: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9177: @end example
1.5 anton 9178:
9179: @itemize @bullet
9180: @item
1.26 crook 9181: Message @code{text-2} is displayed because of the run-time behaviour of
9182: @code{."}.
9183: @item
9184: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9185: on the stack at run-time. @code{emit} always displays the character
9186: when @code{my-char} is executed.
9187: @item
9188: @code{char} parses a string at run-time and the second @code{emit} displays
9189: the first character of the string.
1.5 anton 9190: @item
1.26 crook 9191: If you type @code{see my-char} you can see that @code{[char]} discarded
9192: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9193: definition of @code{my-char}.
1.5 anton 9194: @end itemize
9195:
9196:
1.181 anton 9197: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9198: @subsection Terminal output
9199: @cindex output to terminal
9200: @cindex terminal output
9201:
9202: If you are outputting to a terminal, you may want to control the
9203: positioning of the cursor:
9204: @cindex cursor positioning
9205:
9206: doc-at-xy
9207:
9208: In order to know where to position the cursor, it is often helpful to
9209: know the size of the screen:
9210: @cindex terminal size
9211:
9212: doc-form
9213:
9214: And sometimes you want to use:
9215: @cindex clear screen
9216:
9217: doc-page
9218:
9219: Note that on non-terminals you should use @code{12 emit}, not
9220: @code{page}, to get a form feed.
9221:
1.5 anton 9222:
1.181 anton 9223: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9224: @subsection Single-key input
9225: @cindex single-key input
9226: @cindex input, single-key
9227:
9228: If you want to get a single printable character, you can use
9229: @code{key}; to check whether a character is available for @code{key},
9230: you can use @code{key?}.
1.5 anton 9231:
1.181 anton 9232: doc-key
9233: doc-key?
1.27 crook 9234:
1.181 anton 9235: If you want to process a mix of printable and non-printable
9236: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9237: produces a keyboard event that you have to convert into a character
9238: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9239:
9240: Typical code for using EKEY looks like this:
9241:
9242: @example
9243: ekey ekey>char if ( c )
9244: ... \ do something with the character
9245: else ekey>fkey if ( key-id )
9246: case
9247: k-up of ... endof
9248: k-f1 of ... endof
9249: k-left k-shift-mask or k-ctrl-mask or of ... endof
9250: ...
9251: endcase
9252: else ( keyboard-event )
9253: drop \ just ignore an unknown keyboard event type
9254: then then
9255: @end example
1.44 crook 9256:
1.45 crook 9257: doc-ekey
1.141 anton 9258: doc-ekey>char
1.181 anton 9259: doc-ekey>fkey
1.45 crook 9260: doc-ekey?
1.141 anton 9261:
1.181 anton 9262: The key identifiers for cursor keys are:
1.141 anton 9263:
9264: doc-k-left
9265: doc-k-right
1.185 anton 9266: doc-k-up
9267: doc-k-down
9268: doc-k-home
9269: doc-k-end
1.141 anton 9270: doc-k-prior
9271: doc-k-next
9272: doc-k-insert
9273: doc-k-delete
9274:
1.181 anton 9275: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9276:
1.181 anton 9277: doc-k-f1
9278: doc-k-f2
9279: doc-k-f3
9280: doc-k-f4
9281: doc-k-f5
9282: doc-k-f6
9283: doc-k-f7
9284: doc-k-f8
9285: doc-k-f9
9286: doc-k-f10
9287: doc-k-f11
9288: doc-k-f12
9289:
9290: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9291:
9292: You can combine these key identifiers with masks for various shift keys:
9293:
9294: doc-k-shift-mask
9295: doc-k-ctrl-mask
9296: doc-k-alt-mask
9297:
9298: Note that, even if a Forth system has @code{ekey>fkey} and the key
9299: identifier words, the keys are not necessarily available or it may not
9300: necessarily be able to report all the keys and all the possible
9301: combinations with shift masks. Therefore, write your programs in such
9302: a way that they are still useful even if the keys and key combinations
9303: cannot be pressed or are not recognized.
9304:
9305: Examples: Older keyboards often do not have an F11 and F12 key. If
9306: you run Gforth in an xterm, the xterm catches a number of combinations
9307: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9308: Gforth currently does not recognize and report combinations with
9309: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9310: above would never be entered).
9311:
9312: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9313: you need the ANSI.SYS driver to get that behaviour); it works by
9314: recognizing the escape sequences that ANSI terminals send when such a
9315: key is pressed. If you have a terminal that sends other escape
9316: sequences, you will not get useful results on Gforth. Other Forth
9317: systems may work in a different way.
9318:
1.200 anton 9319: Gforth also provides a few words for outputting names of function
9320: keys:
9321:
9322: doc-fkey.
9323: doc-simple-fkey-string
9324:
1.181 anton 9325:
9326: @node Line input and conversion, Pipes, Single-key input, Other I/O
9327: @subsection Line input and conversion
9328: @cindex line input from terminal
9329: @cindex input, linewise from terminal
9330: @cindex convertin strings to numbers
9331: @cindex I/O - see input
9332:
9333: For ways of storing character strings in memory see @ref{String Formats}.
9334:
9335: @comment TODO examples for >number >float accept key key? pad parse word refill
9336: @comment then index them
1.141 anton 9337:
9338: Words for inputting one line from the keyboard:
9339:
9340: doc-accept
9341: doc-edit-line
9342:
9343: Conversion words:
9344:
1.143 anton 9345: doc-s>number?
9346: doc-s>unumber?
1.26 crook 9347: doc->number
9348: doc->float
1.143 anton 9349:
1.141 anton 9350:
1.27 crook 9351: @comment obsolescent words..
1.141 anton 9352: Obsolescent input and conversion words:
9353:
1.27 crook 9354: doc-convert
1.26 crook 9355: doc-expect
1.27 crook 9356: doc-span
1.5 anton 9357:
9358:
1.181 anton 9359: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9360: @subsection Pipes
9361: @cindex pipes, creating your own
9362:
9363: In addition to using Gforth in pipes created by other processes
9364: (@pxref{Gforth in pipes}), you can create your own pipe with
9365: @code{open-pipe}, and read from or write to it.
9366:
9367: doc-open-pipe
9368: doc-close-pipe
9369:
9370: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9371: you don't catch this exception, Gforth will catch it and exit, usually
9372: silently (@pxref{Gforth in pipes}). Since you probably do not want
9373: this, you should wrap a @code{catch} or @code{try} block around the code
9374: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9375: problem yourself, and then return to regular processing.
9376:
9377: doc-broken-pipe-error
9378:
1.155 anton 9379: @node Xchars and Unicode, , Pipes, Other I/O
9380: @subsection Xchars and Unicode
1.149 pazsan 9381:
1.188 pazsan 9382: ASCII is only appropriate for the English language. Most western
9383: languages however fit somewhat into the Forth frame, since a byte is
9384: sufficient to encode the few special characters in each (though not
9385: always the same encoding can be used; latin-1 is most widely used,
9386: though). For other languages, different char-sets have to be used,
9387: several of them variable-width. Most prominent representant is
9388: UTF-8. Let's call these extended characters xchars. The primitive
9389: fixed-size characters stored as bytes are called pchars in this
9390: section.
9391:
9392: The xchar words add a few data types:
9393:
9394: @itemize
9395:
9396: @item
9397: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9398: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9399: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9400: character set can be used.
9401:
9402: @item
9403: @var{xc-addr} is the address of an xchar in memory. Alignment
9404: requirements are the same as @var{c-addr}. The memory representation of an
9405: xchar differs from the stack representation, and depends on the
9406: encoding used. An xchar may use a variable number of pchars in memory.
9407:
9408: @item
9409: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9410: @var{xc-addr}, @var{u} pchars long.
9411:
9412: @end itemize
9413:
9414: doc-xc-size
9415: doc-x-size
9416: doc-xc@+
9417: doc-xc!+?
9418: doc-xchar+
9419: doc-xchar-
9420: doc-+x/string
9421: doc-x\string-
9422: doc--trailing-garbage
9423: doc-x-width
9424: doc-xkey
9425: doc-xemit
9426:
9427: There's a new environment query
9428:
9429: doc-xchar-encoding
1.112 anton 9430:
1.121 anton 9431: @node OS command line arguments, Locals, Other I/O, Words
9432: @section OS command line arguments
9433: @cindex OS command line arguments
9434: @cindex command line arguments, OS
9435: @cindex arguments, OS command line
9436:
9437: The usual way to pass arguments to Gforth programs on the command line
9438: is via the @option{-e} option, e.g.
9439:
9440: @example
9441: gforth -e "123 456" foo.fs -e bye
9442: @end example
9443:
9444: However, you may want to interpret the command-line arguments directly.
9445: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9446: through @code{next-arg}:
1.121 anton 9447:
1.123 anton 9448: doc-next-arg
1.121 anton 9449:
1.123 anton 9450: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9451:
9452: @example
9453: : echo ( -- )
1.122 anton 9454: begin
1.123 anton 9455: next-arg 2dup 0 0 d<> while
9456: type space
9457: repeat
9458: 2drop ;
1.121 anton 9459:
9460: echo cr bye
9461: @end example
9462:
9463: This can be invoked with
9464:
9465: @example
9466: gforth echo.fs hello world
9467: @end example
1.123 anton 9468:
9469: and it will print
9470:
9471: @example
9472: hello world
9473: @end example
9474:
9475: The next lower level of dealing with the OS command line are the
9476: following words:
9477:
9478: doc-arg
9479: doc-shift-args
9480:
9481: Finally, at the lowest level Gforth provides the following words:
9482:
9483: doc-argc
9484: doc-argv
1.121 anton 9485:
1.78 anton 9486: @c -------------------------------------------------------------
1.126 pazsan 9487: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9488: @section Locals
9489: @cindex locals
9490:
9491: Local variables can make Forth programming more enjoyable and Forth
9492: programs easier to read. Unfortunately, the locals of ANS Forth are
9493: laden with restrictions. Therefore, we provide not only the ANS Forth
9494: locals wordset, but also our own, more powerful locals wordset (we
9495: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9496:
1.78 anton 9497: The ideas in this section have also been published in M. Anton Ertl,
9498: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9499: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9500:
9501: @menu
1.78 anton 9502: * Gforth locals::
9503: * ANS Forth locals::
1.5 anton 9504: @end menu
9505:
1.78 anton 9506: @node Gforth locals, ANS Forth locals, Locals, Locals
9507: @subsection Gforth locals
9508: @cindex Gforth locals
9509: @cindex locals, Gforth style
1.5 anton 9510:
1.78 anton 9511: Locals can be defined with
1.44 crook 9512:
1.78 anton 9513: @example
9514: @{ local1 local2 ... -- comment @}
9515: @end example
9516: or
9517: @example
9518: @{ local1 local2 ... @}
9519: @end example
1.5 anton 9520:
1.78 anton 9521: E.g.,
9522: @example
9523: : max @{ n1 n2 -- n3 @}
9524: n1 n2 > if
9525: n1
9526: else
9527: n2
9528: endif ;
9529: @end example
1.44 crook 9530:
1.78 anton 9531: The similarity of locals definitions with stack comments is intended. A
9532: locals definition often replaces the stack comment of a word. The order
9533: of the locals corresponds to the order in a stack comment and everything
9534: after the @code{--} is really a comment.
1.77 anton 9535:
1.78 anton 9536: This similarity has one disadvantage: It is too easy to confuse locals
9537: declarations with stack comments, causing bugs and making them hard to
9538: find. However, this problem can be avoided by appropriate coding
9539: conventions: Do not use both notations in the same program. If you do,
9540: they should be distinguished using additional means, e.g. by position.
1.77 anton 9541:
1.78 anton 9542: @cindex types of locals
9543: @cindex locals types
9544: The name of the local may be preceded by a type specifier, e.g.,
9545: @code{F:} for a floating point value:
1.5 anton 9546:
1.78 anton 9547: @example
9548: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9549: \ complex multiplication
9550: Ar Br f* Ai Bi f* f-
9551: Ar Bi f* Ai Br f* f+ ;
9552: @end example
1.44 crook 9553:
1.78 anton 9554: @cindex flavours of locals
9555: @cindex locals flavours
9556: @cindex value-flavoured locals
9557: @cindex variable-flavoured locals
9558: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9559: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9560: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9561: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9562: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9563: produces its address (which becomes invalid when the variable's scope is
9564: left). E.g., the standard word @code{emit} can be defined in terms of
9565: @code{type} like this:
1.5 anton 9566:
1.78 anton 9567: @example
9568: : emit @{ C^ char* -- @}
9569: char* 1 type ;
9570: @end example
1.5 anton 9571:
1.78 anton 9572: @cindex default type of locals
9573: @cindex locals, default type
9574: A local without type specifier is a @code{W:} local. Both flavours of
9575: locals are initialized with values from the data or FP stack.
1.44 crook 9576:
1.78 anton 9577: Currently there is no way to define locals with user-defined data
9578: structures, but we are working on it.
1.5 anton 9579:
1.78 anton 9580: Gforth allows defining locals everywhere in a colon definition. This
9581: poses the following questions:
1.5 anton 9582:
1.78 anton 9583: @menu
9584: * Where are locals visible by name?::
9585: * How long do locals live?::
9586: * Locals programming style::
9587: * Locals implementation::
9588: @end menu
1.44 crook 9589:
1.78 anton 9590: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9591: @subsubsection Where are locals visible by name?
9592: @cindex locals visibility
9593: @cindex visibility of locals
9594: @cindex scope of locals
1.5 anton 9595:
1.78 anton 9596: Basically, the answer is that locals are visible where you would expect
9597: it in block-structured languages, and sometimes a little longer. If you
9598: want to restrict the scope of a local, enclose its definition in
9599: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9600:
9601:
1.78 anton 9602: doc-scope
9603: doc-endscope
1.5 anton 9604:
9605:
1.78 anton 9606: These words behave like control structure words, so you can use them
9607: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9608: arbitrary ways.
1.77 anton 9609:
1.78 anton 9610: If you want a more exact answer to the visibility question, here's the
9611: basic principle: A local is visible in all places that can only be
9612: reached through the definition of the local@footnote{In compiler
9613: construction terminology, all places dominated by the definition of the
9614: local.}. In other words, it is not visible in places that can be reached
9615: without going through the definition of the local. E.g., locals defined
9616: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9617: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9618: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9619:
1.78 anton 9620: The reasoning behind this solution is: We want to have the locals
9621: visible as long as it is meaningful. The user can always make the
9622: visibility shorter by using explicit scoping. In a place that can
9623: only be reached through the definition of a local, the meaning of a
9624: local name is clear. In other places it is not: How is the local
9625: initialized at the control flow path that does not contain the
9626: definition? Which local is meant, if the same name is defined twice in
9627: two independent control flow paths?
1.77 anton 9628:
1.78 anton 9629: This should be enough detail for nearly all users, so you can skip the
9630: rest of this section. If you really must know all the gory details and
9631: options, read on.
1.77 anton 9632:
1.78 anton 9633: In order to implement this rule, the compiler has to know which places
9634: are unreachable. It knows this automatically after @code{AHEAD},
9635: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9636: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9637: compiler that the control flow never reaches that place. If
9638: @code{UNREACHABLE} is not used where it could, the only consequence is
9639: that the visibility of some locals is more limited than the rule above
9640: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9641: lie to the compiler), buggy code will be produced.
1.77 anton 9642:
1.5 anton 9643:
1.78 anton 9644: doc-unreachable
1.5 anton 9645:
1.23 crook 9646:
1.78 anton 9647: Another problem with this rule is that at @code{BEGIN}, the compiler
9648: does not know which locals will be visible on the incoming
9649: back-edge. All problems discussed in the following are due to this
9650: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9651: loops as examples; the discussion also applies to @code{?DO} and other
9652: loops). Perhaps the most insidious example is:
1.26 crook 9653: @example
1.78 anton 9654: AHEAD
9655: BEGIN
9656: x
9657: [ 1 CS-ROLL ] THEN
9658: @{ x @}
9659: ...
9660: UNTIL
1.26 crook 9661: @end example
1.23 crook 9662:
1.78 anton 9663: This should be legal according to the visibility rule. The use of
9664: @code{x} can only be reached through the definition; but that appears
9665: textually below the use.
9666:
9667: From this example it is clear that the visibility rules cannot be fully
9668: implemented without major headaches. Our implementation treats common
9669: cases as advertised and the exceptions are treated in a safe way: The
9670: compiler makes a reasonable guess about the locals visible after a
9671: @code{BEGIN}; if it is too pessimistic, the
9672: user will get a spurious error about the local not being defined; if the
9673: compiler is too optimistic, it will notice this later and issue a
9674: warning. In the case above the compiler would complain about @code{x}
9675: being undefined at its use. You can see from the obscure examples in
9676: this section that it takes quite unusual control structures to get the
9677: compiler into trouble, and even then it will often do fine.
1.23 crook 9678:
1.78 anton 9679: If the @code{BEGIN} is reachable from above, the most optimistic guess
9680: is that all locals visible before the @code{BEGIN} will also be
9681: visible after the @code{BEGIN}. This guess is valid for all loops that
9682: are entered only through the @code{BEGIN}, in particular, for normal
9683: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9684: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9685: compiler. When the branch to the @code{BEGIN} is finally generated by
9686: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9687: warns the user if it was too optimistic:
1.26 crook 9688: @example
1.78 anton 9689: IF
9690: @{ x @}
9691: BEGIN
9692: \ x ?
9693: [ 1 cs-roll ] THEN
9694: ...
9695: UNTIL
1.26 crook 9696: @end example
1.23 crook 9697:
1.78 anton 9698: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9699: optimistically assumes that it lives until the @code{THEN}. It notices
9700: this difference when it compiles the @code{UNTIL} and issues a
9701: warning. The user can avoid the warning, and make sure that @code{x}
9702: is not used in the wrong area by using explicit scoping:
9703: @example
9704: IF
9705: SCOPE
9706: @{ x @}
9707: ENDSCOPE
9708: BEGIN
9709: [ 1 cs-roll ] THEN
9710: ...
9711: UNTIL
9712: @end example
1.23 crook 9713:
1.78 anton 9714: Since the guess is optimistic, there will be no spurious error messages
9715: about undefined locals.
1.44 crook 9716:
1.78 anton 9717: If the @code{BEGIN} is not reachable from above (e.g., after
9718: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9719: optimistic guess, as the locals visible after the @code{BEGIN} may be
9720: defined later. Therefore, the compiler assumes that no locals are
9721: visible after the @code{BEGIN}. However, the user can use
9722: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9723: visible at the BEGIN as at the point where the top control-flow stack
9724: item was created.
1.23 crook 9725:
1.44 crook 9726:
1.78 anton 9727: doc-assume-live
1.26 crook 9728:
1.23 crook 9729:
1.78 anton 9730: @noindent
9731: E.g.,
9732: @example
9733: @{ x @}
9734: AHEAD
9735: ASSUME-LIVE
9736: BEGIN
9737: x
9738: [ 1 CS-ROLL ] THEN
9739: ...
9740: UNTIL
9741: @end example
1.44 crook 9742:
1.78 anton 9743: Other cases where the locals are defined before the @code{BEGIN} can be
9744: handled by inserting an appropriate @code{CS-ROLL} before the
9745: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9746: behind the @code{ASSUME-LIVE}).
1.23 crook 9747:
1.78 anton 9748: Cases where locals are defined after the @code{BEGIN} (but should be
9749: visible immediately after the @code{BEGIN}) can only be handled by
9750: rearranging the loop. E.g., the ``most insidious'' example above can be
9751: arranged into:
9752: @example
9753: BEGIN
9754: @{ x @}
9755: ... 0=
9756: WHILE
9757: x
9758: REPEAT
9759: @end example
1.44 crook 9760:
1.78 anton 9761: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9762: @subsubsection How long do locals live?
9763: @cindex locals lifetime
9764: @cindex lifetime of locals
1.23 crook 9765:
1.78 anton 9766: The right answer for the lifetime question would be: A local lives at
9767: least as long as it can be accessed. For a value-flavoured local this
9768: means: until the end of its visibility. However, a variable-flavoured
9769: local could be accessed through its address far beyond its visibility
9770: scope. Ultimately, this would mean that such locals would have to be
9771: garbage collected. Since this entails un-Forth-like implementation
9772: complexities, I adopted the same cowardly solution as some other
9773: languages (e.g., C): The local lives only as long as it is visible;
9774: afterwards its address is invalid (and programs that access it
9775: afterwards are erroneous).
1.23 crook 9776:
1.78 anton 9777: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9778: @subsubsection Locals programming style
9779: @cindex locals programming style
9780: @cindex programming style, locals
1.23 crook 9781:
1.78 anton 9782: The freedom to define locals anywhere has the potential to change
9783: programming styles dramatically. In particular, the need to use the
9784: return stack for intermediate storage vanishes. Moreover, all stack
9785: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9786: determined arguments) can be eliminated: If the stack items are in the
9787: wrong order, just write a locals definition for all of them; then
9788: write the items in the order you want.
1.23 crook 9789:
1.78 anton 9790: This seems a little far-fetched and eliminating stack manipulations is
9791: unlikely to become a conscious programming objective. Still, the number
9792: of stack manipulations will be reduced dramatically if local variables
9793: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9794: a traditional implementation of @code{max}).
1.23 crook 9795:
1.78 anton 9796: This shows one potential benefit of locals: making Forth programs more
9797: readable. Of course, this benefit will only be realized if the
9798: programmers continue to honour the principle of factoring instead of
9799: using the added latitude to make the words longer.
1.23 crook 9800:
1.78 anton 9801: @cindex single-assignment style for locals
9802: Using @code{TO} can and should be avoided. Without @code{TO},
9803: every value-flavoured local has only a single assignment and many
9804: advantages of functional languages apply to Forth. I.e., programs are
9805: easier to analyse, to optimize and to read: It is clear from the
9806: definition what the local stands for, it does not turn into something
9807: different later.
1.23 crook 9808:
1.78 anton 9809: E.g., a definition using @code{TO} might look like this:
9810: @example
9811: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9812: u1 u2 min 0
9813: ?do
9814: addr1 c@@ addr2 c@@ -
9815: ?dup-if
9816: unloop exit
9817: then
9818: addr1 char+ TO addr1
9819: addr2 char+ TO addr2
9820: loop
9821: u1 u2 - ;
1.26 crook 9822: @end example
1.78 anton 9823: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9824: every loop iteration. @code{strcmp} is a typical example of the
9825: readability problems of using @code{TO}. When you start reading
9826: @code{strcmp}, you think that @code{addr1} refers to the start of the
9827: string. Only near the end of the loop you realize that it is something
9828: else.
1.23 crook 9829:
1.78 anton 9830: This can be avoided by defining two locals at the start of the loop that
9831: are initialized with the right value for the current iteration.
9832: @example
9833: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9834: addr1 addr2
9835: u1 u2 min 0
9836: ?do @{ s1 s2 @}
9837: s1 c@@ s2 c@@ -
9838: ?dup-if
9839: unloop exit
9840: then
9841: s1 char+ s2 char+
9842: loop
9843: 2drop
9844: u1 u2 - ;
9845: @end example
9846: Here it is clear from the start that @code{s1} has a different value
9847: in every loop iteration.
1.23 crook 9848:
1.78 anton 9849: @node Locals implementation, , Locals programming style, Gforth locals
9850: @subsubsection Locals implementation
9851: @cindex locals implementation
9852: @cindex implementation of locals
1.23 crook 9853:
1.78 anton 9854: @cindex locals stack
9855: Gforth uses an extra locals stack. The most compelling reason for
9856: this is that the return stack is not float-aligned; using an extra stack
9857: also eliminates the problems and restrictions of using the return stack
9858: as locals stack. Like the other stacks, the locals stack grows toward
9859: lower addresses. A few primitives allow an efficient implementation:
9860:
9861:
9862: doc-@local#
9863: doc-f@local#
9864: doc-laddr#
9865: doc-lp+!#
9866: doc-lp!
9867: doc->l
9868: doc-f>l
9869:
9870:
9871: In addition to these primitives, some specializations of these
9872: primitives for commonly occurring inline arguments are provided for
9873: efficiency reasons, e.g., @code{@@local0} as specialization of
9874: @code{@@local#} for the inline argument 0. The following compiling words
9875: compile the right specialized version, or the general version, as
9876: appropriate:
1.23 crook 9877:
1.5 anton 9878:
1.107 dvdkhlng 9879: @c doc-compile-@local
9880: @c doc-compile-f@local
1.78 anton 9881: doc-compile-lp+!
1.5 anton 9882:
9883:
1.78 anton 9884: Combinations of conditional branches and @code{lp+!#} like
9885: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9886: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9887:
1.78 anton 9888: A special area in the dictionary space is reserved for keeping the
9889: local variable names. @code{@{} switches the dictionary pointer to this
9890: area and @code{@}} switches it back and generates the locals
9891: initializing code. @code{W:} etc.@ are normal defining words. This
9892: special area is cleared at the start of every colon definition.
1.5 anton 9893:
1.78 anton 9894: @cindex word list for defining locals
9895: A special feature of Gforth's dictionary is used to implement the
9896: definition of locals without type specifiers: every word list (aka
9897: vocabulary) has its own methods for searching
9898: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9899: with a special search method: When it is searched for a word, it
9900: actually creates that word using @code{W:}. @code{@{} changes the search
9901: order to first search the word list containing @code{@}}, @code{W:} etc.,
9902: and then the word list for defining locals without type specifiers.
1.5 anton 9903:
1.78 anton 9904: The lifetime rules support a stack discipline within a colon
9905: definition: The lifetime of a local is either nested with other locals
9906: lifetimes or it does not overlap them.
1.23 crook 9907:
1.78 anton 9908: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9909: pointer manipulation is generated. Between control structure words
9910: locals definitions can push locals onto the locals stack. @code{AGAIN}
9911: is the simplest of the other three control flow words. It has to
9912: restore the locals stack depth of the corresponding @code{BEGIN}
9913: before branching. The code looks like this:
9914: @format
9915: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9916: @code{branch} <begin>
9917: @end format
1.26 crook 9918:
1.78 anton 9919: @code{UNTIL} is a little more complicated: If it branches back, it
9920: must adjust the stack just like @code{AGAIN}. But if it falls through,
9921: the locals stack must not be changed. The compiler generates the
9922: following code:
9923: @format
9924: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9925: @end format
9926: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9927:
1.78 anton 9928: @code{THEN} can produce somewhat inefficient code:
9929: @format
9930: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9931: <orig target>:
9932: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9933: @end format
9934: The second @code{lp+!#} adjusts the locals stack pointer from the
9935: level at the @i{orig} point to the level after the @code{THEN}. The
9936: first @code{lp+!#} adjusts the locals stack pointer from the current
9937: level to the level at the orig point, so the complete effect is an
9938: adjustment from the current level to the right level after the
9939: @code{THEN}.
1.26 crook 9940:
1.78 anton 9941: @cindex locals information on the control-flow stack
9942: @cindex control-flow stack items, locals information
9943: In a conventional Forth implementation a dest control-flow stack entry
9944: is just the target address and an orig entry is just the address to be
9945: patched. Our locals implementation adds a word list to every orig or dest
9946: item. It is the list of locals visible (or assumed visible) at the point
9947: described by the entry. Our implementation also adds a tag to identify
9948: the kind of entry, in particular to differentiate between live and dead
9949: (reachable and unreachable) orig entries.
1.26 crook 9950:
1.78 anton 9951: A few unusual operations have to be performed on locals word lists:
1.44 crook 9952:
1.5 anton 9953:
1.78 anton 9954: doc-common-list
9955: doc-sub-list?
9956: doc-list-size
1.52 anton 9957:
9958:
1.78 anton 9959: Several features of our locals word list implementation make these
9960: operations easy to implement: The locals word lists are organised as
9961: linked lists; the tails of these lists are shared, if the lists
9962: contain some of the same locals; and the address of a name is greater
9963: than the address of the names behind it in the list.
1.5 anton 9964:
1.78 anton 9965: Another important implementation detail is the variable
9966: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9967: determine if they can be reached directly or only through the branch
9968: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9969: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9970: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9971:
1.78 anton 9972: Counted loops are similar to other loops in most respects, but
9973: @code{LEAVE} requires special attention: It performs basically the same
9974: service as @code{AHEAD}, but it does not create a control-flow stack
9975: entry. Therefore the information has to be stored elsewhere;
9976: traditionally, the information was stored in the target fields of the
9977: branches created by the @code{LEAVE}s, by organizing these fields into a
9978: linked list. Unfortunately, this clever trick does not provide enough
9979: space for storing our extended control flow information. Therefore, we
9980: introduce another stack, the leave stack. It contains the control-flow
9981: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 9982:
1.78 anton 9983: Local names are kept until the end of the colon definition, even if
9984: they are no longer visible in any control-flow path. In a few cases
9985: this may lead to increased space needs for the locals name area, but
9986: usually less than reclaiming this space would cost in code size.
1.5 anton 9987:
1.44 crook 9988:
1.78 anton 9989: @node ANS Forth locals, , Gforth locals, Locals
9990: @subsection ANS Forth locals
9991: @cindex locals, ANS Forth style
1.5 anton 9992:
1.78 anton 9993: The ANS Forth locals wordset does not define a syntax for locals, but
9994: words that make it possible to define various syntaxes. One of the
9995: possible syntaxes is a subset of the syntax we used in the Gforth locals
9996: wordset, i.e.:
1.29 crook 9997:
9998: @example
1.78 anton 9999: @{ local1 local2 ... -- comment @}
10000: @end example
10001: @noindent
10002: or
10003: @example
10004: @{ local1 local2 ... @}
1.29 crook 10005: @end example
10006:
1.78 anton 10007: The order of the locals corresponds to the order in a stack comment. The
10008: restrictions are:
1.5 anton 10009:
1.78 anton 10010: @itemize @bullet
10011: @item
10012: Locals can only be cell-sized values (no type specifiers are allowed).
10013: @item
10014: Locals can be defined only outside control structures.
10015: @item
10016: Locals can interfere with explicit usage of the return stack. For the
10017: exact (and long) rules, see the standard. If you don't use return stack
10018: accessing words in a definition using locals, you will be all right. The
10019: purpose of this rule is to make locals implementation on the return
10020: stack easier.
10021: @item
10022: The whole definition must be in one line.
10023: @end itemize
1.5 anton 10024:
1.78 anton 10025: Locals defined in ANS Forth behave like @code{VALUE}s
10026: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10027: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 10028:
1.78 anton 10029: Since the syntax above is supported by Gforth directly, you need not do
10030: anything to use it. If you want to port a program using this syntax to
10031: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10032: syntax on the other system.
1.5 anton 10033:
1.78 anton 10034: Note that a syntax shown in the standard, section A.13 looks
10035: similar, but is quite different in having the order of locals
10036: reversed. Beware!
1.5 anton 10037:
1.78 anton 10038: The ANS Forth locals wordset itself consists of one word:
1.5 anton 10039:
1.78 anton 10040: doc-(local)
1.5 anton 10041:
1.78 anton 10042: The ANS Forth locals extension wordset defines a syntax using
10043: @code{locals|}, but it is so awful that we strongly recommend not to use
10044: it. We have implemented this syntax to make porting to Gforth easy, but
10045: do not document it here. The problem with this syntax is that the locals
10046: are defined in an order reversed with respect to the standard stack
10047: comment notation, making programs harder to read, and easier to misread
10048: and miswrite. The only merit of this syntax is that it is easy to
10049: implement using the ANS Forth locals wordset.
1.53 anton 10050:
10051:
1.78 anton 10052: @c ----------------------------------------------------------
10053: @node Structures, Object-oriented Forth, Locals, Words
10054: @section Structures
10055: @cindex structures
10056: @cindex records
1.53 anton 10057:
1.78 anton 10058: This section presents the structure package that comes with Gforth. A
10059: version of the package implemented in ANS Forth is available in
10060: @file{compat/struct.fs}. This package was inspired by a posting on
10061: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10062: possibly John Hayes). A version of this section has been published in
10063: M. Anton Ertl,
10064: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10065: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10066: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 10067:
1.78 anton 10068: @menu
10069: * Why explicit structure support?::
10070: * Structure Usage::
10071: * Structure Naming Convention::
10072: * Structure Implementation::
10073: * Structure Glossary::
1.183 anton 10074: * Forth200x Structures::
1.78 anton 10075: @end menu
1.55 anton 10076:
1.78 anton 10077: @node Why explicit structure support?, Structure Usage, Structures, Structures
10078: @subsection Why explicit structure support?
1.53 anton 10079:
1.78 anton 10080: @cindex address arithmetic for structures
10081: @cindex structures using address arithmetic
10082: If we want to use a structure containing several fields, we could simply
10083: reserve memory for it, and access the fields using address arithmetic
10084: (@pxref{Address arithmetic}). As an example, consider a structure with
10085: the following fields
1.57 anton 10086:
1.78 anton 10087: @table @code
10088: @item a
10089: is a float
10090: @item b
10091: is a cell
10092: @item c
10093: is a float
10094: @end table
1.57 anton 10095:
1.78 anton 10096: Given the (float-aligned) base address of the structure we get the
10097: address of the field
1.52 anton 10098:
1.78 anton 10099: @table @code
10100: @item a
10101: without doing anything further.
10102: @item b
10103: with @code{float+}
10104: @item c
10105: with @code{float+ cell+ faligned}
10106: @end table
1.52 anton 10107:
1.78 anton 10108: It is easy to see that this can become quite tiring.
1.52 anton 10109:
1.78 anton 10110: Moreover, it is not very readable, because seeing a
10111: @code{cell+} tells us neither which kind of structure is
10112: accessed nor what field is accessed; we have to somehow infer the kind
10113: of structure, and then look up in the documentation, which field of
10114: that structure corresponds to that offset.
1.53 anton 10115:
1.78 anton 10116: Finally, this kind of address arithmetic also causes maintenance
10117: troubles: If you add or delete a field somewhere in the middle of the
10118: structure, you have to find and change all computations for the fields
10119: afterwards.
1.52 anton 10120:
1.78 anton 10121: So, instead of using @code{cell+} and friends directly, how
10122: about storing the offsets in constants:
1.52 anton 10123:
1.78 anton 10124: @example
10125: 0 constant a-offset
10126: 0 float+ constant b-offset
10127: 0 float+ cell+ faligned c-offset
10128: @end example
1.64 pazsan 10129:
1.78 anton 10130: Now we can get the address of field @code{x} with @code{x-offset
10131: +}. This is much better in all respects. Of course, you still
10132: have to change all later offset definitions if you add a field. You can
10133: fix this by declaring the offsets in the following way:
1.57 anton 10134:
1.78 anton 10135: @example
10136: 0 constant a-offset
10137: a-offset float+ constant b-offset
10138: b-offset cell+ faligned constant c-offset
10139: @end example
1.57 anton 10140:
1.78 anton 10141: Since we always use the offsets with @code{+}, we could use a defining
10142: word @code{cfield} that includes the @code{+} in the action of the
10143: defined word:
1.64 pazsan 10144:
1.78 anton 10145: @example
10146: : cfield ( n "name" -- )
10147: create ,
10148: does> ( name execution: addr1 -- addr2 )
10149: @@ + ;
1.64 pazsan 10150:
1.78 anton 10151: 0 cfield a
10152: 0 a float+ cfield b
10153: 0 b cell+ faligned cfield c
10154: @end example
1.64 pazsan 10155:
1.78 anton 10156: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10157:
1.78 anton 10158: The structure field words now can be used quite nicely. However,
10159: their definition is still a bit cumbersome: We have to repeat the
10160: name, the information about size and alignment is distributed before
10161: and after the field definitions etc. The structure package presented
10162: here addresses these problems.
1.64 pazsan 10163:
1.78 anton 10164: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10165: @subsection Structure Usage
10166: @cindex structure usage
1.57 anton 10167:
1.78 anton 10168: @cindex @code{field} usage
10169: @cindex @code{struct} usage
10170: @cindex @code{end-struct} usage
10171: You can define a structure for a (data-less) linked list with:
1.57 anton 10172: @example
1.78 anton 10173: struct
10174: cell% field list-next
10175: end-struct list%
1.57 anton 10176: @end example
10177:
1.78 anton 10178: With the address of the list node on the stack, you can compute the
10179: address of the field that contains the address of the next node with
10180: @code{list-next}. E.g., you can determine the length of a list
10181: with:
1.57 anton 10182:
10183: @example
1.78 anton 10184: : list-length ( list -- n )
10185: \ "list" is a pointer to the first element of a linked list
10186: \ "n" is the length of the list
10187: 0 BEGIN ( list1 n1 )
10188: over
10189: WHILE ( list1 n1 )
10190: 1+ swap list-next @@ swap
10191: REPEAT
10192: nip ;
1.57 anton 10193: @end example
10194:
1.78 anton 10195: You can reserve memory for a list node in the dictionary with
10196: @code{list% %allot}, which leaves the address of the list node on the
10197: stack. For the equivalent allocation on the heap you can use @code{list%
10198: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10199: use @code{list% %allocate}). You can get the the size of a list
10200: node with @code{list% %size} and its alignment with @code{list%
10201: %alignment}.
10202:
10203: Note that in ANS Forth the body of a @code{create}d word is
10204: @code{aligned} but not necessarily @code{faligned};
10205: therefore, if you do a:
1.57 anton 10206:
10207: @example
1.78 anton 10208: create @emph{name} foo% %allot drop
1.57 anton 10209: @end example
10210:
1.78 anton 10211: @noindent
10212: then the memory alloted for @code{foo%} is guaranteed to start at the
10213: body of @code{@emph{name}} only if @code{foo%} contains only character,
10214: cell and double fields. Therefore, if your structure contains floats,
10215: better use
1.57 anton 10216:
10217: @example
1.78 anton 10218: foo% %allot constant @emph{name}
1.57 anton 10219: @end example
10220:
1.78 anton 10221: @cindex structures containing structures
10222: You can include a structure @code{foo%} as a field of
10223: another structure, like this:
1.65 anton 10224: @example
1.78 anton 10225: struct
10226: ...
10227: foo% field ...
10228: ...
10229: end-struct ...
1.65 anton 10230: @end example
1.52 anton 10231:
1.78 anton 10232: @cindex structure extension
10233: @cindex extended records
10234: Instead of starting with an empty structure, you can extend an
10235: existing structure. E.g., a plain linked list without data, as defined
10236: above, is hardly useful; You can extend it to a linked list of integers,
10237: like this:@footnote{This feature is also known as @emph{extended
10238: records}. It is the main innovation in the Oberon language; in other
10239: words, adding this feature to Modula-2 led Wirth to create a new
10240: language, write a new compiler etc. Adding this feature to Forth just
10241: required a few lines of code.}
1.52 anton 10242:
1.78 anton 10243: @example
10244: list%
10245: cell% field intlist-int
10246: end-struct intlist%
10247: @end example
1.55 anton 10248:
1.78 anton 10249: @code{intlist%} is a structure with two fields:
10250: @code{list-next} and @code{intlist-int}.
1.55 anton 10251:
1.78 anton 10252: @cindex structures containing arrays
10253: You can specify an array type containing @emph{n} elements of
10254: type @code{foo%} like this:
1.55 anton 10255:
10256: @example
1.78 anton 10257: foo% @emph{n} *
1.56 anton 10258: @end example
1.55 anton 10259:
1.78 anton 10260: You can use this array type in any place where you can use a normal
10261: type, e.g., when defining a @code{field}, or with
10262: @code{%allot}.
10263:
10264: @cindex first field optimization
10265: The first field is at the base address of a structure and the word for
10266: this field (e.g., @code{list-next}) actually does not change the address
10267: on the stack. You may be tempted to leave it away in the interest of
10268: run-time and space efficiency. This is not necessary, because the
10269: structure package optimizes this case: If you compile a first-field
10270: words, no code is generated. So, in the interest of readability and
10271: maintainability you should include the word for the field when accessing
10272: the field.
1.52 anton 10273:
10274:
1.78 anton 10275: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10276: @subsection Structure Naming Convention
10277: @cindex structure naming convention
1.52 anton 10278:
1.78 anton 10279: The field names that come to (my) mind are often quite generic, and,
10280: if used, would cause frequent name clashes. E.g., many structures
10281: probably contain a @code{counter} field. The structure names
10282: that come to (my) mind are often also the logical choice for the names
10283: of words that create such a structure.
1.52 anton 10284:
1.78 anton 10285: Therefore, I have adopted the following naming conventions:
1.52 anton 10286:
1.78 anton 10287: @itemize @bullet
10288: @cindex field naming convention
10289: @item
10290: The names of fields are of the form
10291: @code{@emph{struct}-@emph{field}}, where
10292: @code{@emph{struct}} is the basic name of the structure, and
10293: @code{@emph{field}} is the basic name of the field. You can
10294: think of field words as converting the (address of the)
10295: structure into the (address of the) field.
1.52 anton 10296:
1.78 anton 10297: @cindex structure naming convention
10298: @item
10299: The names of structures are of the form
10300: @code{@emph{struct}%}, where
10301: @code{@emph{struct}} is the basic name of the structure.
10302: @end itemize
1.52 anton 10303:
1.78 anton 10304: This naming convention does not work that well for fields of extended
10305: structures; e.g., the integer list structure has a field
10306: @code{intlist-int}, but has @code{list-next}, not
10307: @code{intlist-next}.
1.53 anton 10308:
1.78 anton 10309: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10310: @subsection Structure Implementation
10311: @cindex structure implementation
10312: @cindex implementation of structures
1.52 anton 10313:
1.78 anton 10314: The central idea in the implementation is to pass the data about the
10315: structure being built on the stack, not in some global
10316: variable. Everything else falls into place naturally once this design
10317: decision is made.
1.53 anton 10318:
1.78 anton 10319: The type description on the stack is of the form @emph{align
10320: size}. Keeping the size on the top-of-stack makes dealing with arrays
10321: very simple.
1.53 anton 10322:
1.78 anton 10323: @code{field} is a defining word that uses @code{Create}
10324: and @code{DOES>}. The body of the field contains the offset
10325: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10326:
10327: @example
1.78 anton 10328: @@ +
1.53 anton 10329: @end example
10330:
1.78 anton 10331: @noindent
10332: i.e., add the offset to the address, giving the stack effect
10333: @i{addr1 -- addr2} for a field.
10334:
10335: @cindex first field optimization, implementation
10336: This simple structure is slightly complicated by the optimization
10337: for fields with offset 0, which requires a different
10338: @code{DOES>}-part (because we cannot rely on there being
10339: something on the stack if such a field is invoked during
10340: compilation). Therefore, we put the different @code{DOES>}-parts
10341: in separate words, and decide which one to invoke based on the
10342: offset. For a zero offset, the field is basically a noop; it is
10343: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10344:
1.183 anton 10345: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10346: @subsection Structure Glossary
10347: @cindex structure glossary
1.53 anton 10348:
1.5 anton 10349:
1.78 anton 10350: doc-%align
10351: doc-%alignment
10352: doc-%alloc
10353: doc-%allocate
10354: doc-%allot
10355: doc-cell%
10356: doc-char%
10357: doc-dfloat%
10358: doc-double%
10359: doc-end-struct
10360: doc-field
10361: doc-float%
10362: doc-naligned
10363: doc-sfloat%
10364: doc-%size
10365: doc-struct
1.54 anton 10366:
10367:
1.183 anton 10368: @node Forth200x Structures, , Structure Glossary, Structures
10369: @subsection Forth200x Structures
10370: @cindex Structures in Forth200x
10371:
10372: The Forth 200x standard defines a slightly less convenient form of
10373: structures. In general (when using @code{field+}, you have to perform
10374: the alignment yourself, but there are a number of convenience words
10375: (e.g., @code{field:} that perform the alignment for you.
10376:
10377: A typical usage example is:
10378:
10379: @example
10380: 0
10381: field: s-a
10382: faligned 2 floats +field s-b
10383: constant s-struct
10384: @end example
10385:
10386: An alternative way of writing this structure is:
10387:
10388: @example
10389: begin-structure s-struct
10390: field: s-a
10391: faligned 2 floats +field s-b
10392: end-structure
10393: @end example
10394:
10395: doc-begin-structure
10396: doc-end-structure
10397: doc-+field
10398: doc-cfield:
10399: doc-field:
10400: doc-2field:
10401: doc-ffield:
10402: doc-sffield:
10403: doc-dffield:
10404:
1.26 crook 10405: @c -------------------------------------------------------------
1.78 anton 10406: @node Object-oriented Forth, Programming Tools, Structures, Words
10407: @section Object-oriented Forth
10408:
10409: Gforth comes with three packages for object-oriented programming:
10410: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10411: is preloaded, so you have to @code{include} them before use. The most
10412: important differences between these packages (and others) are discussed
10413: in @ref{Comparison with other object models}. All packages are written
10414: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10415:
1.78 anton 10416: @menu
10417: * Why object-oriented programming?::
10418: * Object-Oriented Terminology::
10419: * Objects::
10420: * OOF::
10421: * Mini-OOF::
10422: * Comparison with other object models::
10423: @end menu
1.5 anton 10424:
1.78 anton 10425: @c ----------------------------------------------------------------
10426: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10427: @subsection Why object-oriented programming?
10428: @cindex object-oriented programming motivation
10429: @cindex motivation for object-oriented programming
1.44 crook 10430:
1.78 anton 10431: Often we have to deal with several data structures (@emph{objects}),
10432: that have to be treated similarly in some respects, but differently in
10433: others. Graphical objects are the textbook example: circles, triangles,
10434: dinosaurs, icons, and others, and we may want to add more during program
10435: development. We want to apply some operations to any graphical object,
10436: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10437: has to do something different for every kind of object.
10438: @comment TODO add some other operations eg perimeter, area
10439: @comment and tie in to concrete examples later..
1.5 anton 10440:
1.78 anton 10441: We could implement @code{draw} as a big @code{CASE}
10442: control structure that executes the appropriate code depending on the
10443: kind of object to be drawn. This would be not be very elegant, and,
10444: moreover, we would have to change @code{draw} every time we add
10445: a new kind of graphical object (say, a spaceship).
1.44 crook 10446:
1.78 anton 10447: What we would rather do is: When defining spaceships, we would tell
10448: the system: ``Here's how you @code{draw} a spaceship; you figure
10449: out the rest''.
1.5 anton 10450:
1.78 anton 10451: This is the problem that all systems solve that (rightfully) call
10452: themselves object-oriented; the object-oriented packages presented here
10453: solve this problem (and not much else).
10454: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10455:
1.78 anton 10456: @c ------------------------------------------------------------------------
10457: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10458: @subsection Object-Oriented Terminology
10459: @cindex object-oriented terminology
10460: @cindex terminology for object-oriented programming
1.5 anton 10461:
1.78 anton 10462: This section is mainly for reference, so you don't have to understand
10463: all of it right away. The terminology is mainly Smalltalk-inspired. In
10464: short:
1.44 crook 10465:
1.78 anton 10466: @table @emph
10467: @cindex class
10468: @item class
10469: a data structure definition with some extras.
1.5 anton 10470:
1.78 anton 10471: @cindex object
10472: @item object
10473: an instance of the data structure described by the class definition.
1.5 anton 10474:
1.78 anton 10475: @cindex instance variables
10476: @item instance variables
10477: fields of the data structure.
1.5 anton 10478:
1.78 anton 10479: @cindex selector
10480: @cindex method selector
10481: @cindex virtual function
10482: @item selector
10483: (or @emph{method selector}) a word (e.g.,
10484: @code{draw}) that performs an operation on a variety of data
10485: structures (classes). A selector describes @emph{what} operation to
10486: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10487:
1.78 anton 10488: @cindex method
10489: @item method
10490: the concrete definition that performs the operation
10491: described by the selector for a specific class. A method specifies
10492: @emph{how} the operation is performed for a specific class.
1.5 anton 10493:
1.78 anton 10494: @cindex selector invocation
10495: @cindex message send
10496: @cindex invoking a selector
10497: @item selector invocation
10498: a call of a selector. One argument of the call (the TOS (top-of-stack))
10499: is used for determining which method is used. In Smalltalk terminology:
10500: a message (consisting of the selector and the other arguments) is sent
10501: to the object.
1.5 anton 10502:
1.78 anton 10503: @cindex receiving object
10504: @item receiving object
10505: the object used for determining the method executed by a selector
10506: invocation. In the @file{objects.fs} model, it is the object that is on
10507: the TOS when the selector is invoked. (@emph{Receiving} comes from
10508: the Smalltalk @emph{message} terminology.)
1.5 anton 10509:
1.78 anton 10510: @cindex child class
10511: @cindex parent class
10512: @cindex inheritance
10513: @item child class
10514: a class that has (@emph{inherits}) all properties (instance variables,
10515: selectors, methods) from a @emph{parent class}. In Smalltalk
10516: terminology: The subclass inherits from the superclass. In C++
10517: terminology: The derived class inherits from the base class.
1.5 anton 10518:
1.78 anton 10519: @end table
1.5 anton 10520:
1.78 anton 10521: @c If you wonder about the message sending terminology, it comes from
10522: @c a time when each object had it's own task and objects communicated via
10523: @c message passing; eventually the Smalltalk developers realized that
10524: @c they can do most things through simple (indirect) calls. They kept the
10525: @c terminology.
1.5 anton 10526:
1.78 anton 10527: @c --------------------------------------------------------------
10528: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10529: @subsection The @file{objects.fs} model
10530: @cindex objects
10531: @cindex object-oriented programming
1.26 crook 10532:
1.78 anton 10533: @cindex @file{objects.fs}
10534: @cindex @file{oof.fs}
1.26 crook 10535:
1.78 anton 10536: This section describes the @file{objects.fs} package. This material also
10537: has been published in M. Anton Ertl,
10538: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10539: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10540: 37--43.
10541: @c McKewan's and Zsoter's packages
1.26 crook 10542:
1.78 anton 10543: This section assumes that you have read @ref{Structures}.
1.5 anton 10544:
1.78 anton 10545: The techniques on which this model is based have been used to implement
10546: the parser generator, Gray, and have also been used in Gforth for
10547: implementing the various flavours of word lists (hashed or not,
10548: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10549:
10550:
1.26 crook 10551: @menu
1.78 anton 10552: * Properties of the Objects model::
10553: * Basic Objects Usage::
10554: * The Objects base class::
10555: * Creating objects::
10556: * Object-Oriented Programming Style::
10557: * Class Binding::
10558: * Method conveniences::
10559: * Classes and Scoping::
10560: * Dividing classes::
10561: * Object Interfaces::
10562: * Objects Implementation::
10563: * Objects Glossary::
1.26 crook 10564: @end menu
1.5 anton 10565:
1.78 anton 10566: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10567:
1.78 anton 10568: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10569: @subsubsection Properties of the @file{objects.fs} model
10570: @cindex @file{objects.fs} properties
1.5 anton 10571:
1.78 anton 10572: @itemize @bullet
10573: @item
10574: It is straightforward to pass objects on the stack. Passing
10575: selectors on the stack is a little less convenient, but possible.
1.44 crook 10576:
1.78 anton 10577: @item
10578: Objects are just data structures in memory, and are referenced by their
10579: address. You can create words for objects with normal defining words
10580: like @code{constant}. Likewise, there is no difference between instance
10581: variables that contain objects and those that contain other data.
1.5 anton 10582:
1.78 anton 10583: @item
10584: Late binding is efficient and easy to use.
1.44 crook 10585:
1.78 anton 10586: @item
10587: It avoids parsing, and thus avoids problems with state-smartness
10588: and reduced extensibility; for convenience there are a few parsing
10589: words, but they have non-parsing counterparts. There are also a few
10590: defining words that parse. This is hard to avoid, because all standard
10591: defining words parse (except @code{:noname}); however, such
10592: words are not as bad as many other parsing words, because they are not
10593: state-smart.
1.5 anton 10594:
1.78 anton 10595: @item
10596: It does not try to incorporate everything. It does a few things and does
10597: them well (IMO). In particular, this model was not designed to support
10598: information hiding (although it has features that may help); you can use
10599: a separate package for achieving this.
1.5 anton 10600:
1.78 anton 10601: @item
10602: It is layered; you don't have to learn and use all features to use this
10603: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10604: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10605: are optional and independent of each other.
1.5 anton 10606:
1.78 anton 10607: @item
10608: An implementation in ANS Forth is available.
1.5 anton 10609:
1.78 anton 10610: @end itemize
1.5 anton 10611:
1.44 crook 10612:
1.78 anton 10613: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10614: @subsubsection Basic @file{objects.fs} Usage
10615: @cindex basic objects usage
10616: @cindex objects, basic usage
1.5 anton 10617:
1.78 anton 10618: You can define a class for graphical objects like this:
1.44 crook 10619:
1.78 anton 10620: @cindex @code{class} usage
10621: @cindex @code{end-class} usage
10622: @cindex @code{selector} usage
1.5 anton 10623: @example
1.78 anton 10624: object class \ "object" is the parent class
10625: selector draw ( x y graphical -- )
10626: end-class graphical
10627: @end example
10628:
10629: This code defines a class @code{graphical} with an
10630: operation @code{draw}. We can perform the operation
10631: @code{draw} on any @code{graphical} object, e.g.:
10632:
10633: @example
10634: 100 100 t-rex draw
1.26 crook 10635: @end example
1.5 anton 10636:
1.78 anton 10637: @noindent
10638: where @code{t-rex} is a word (say, a constant) that produces a
10639: graphical object.
10640:
10641: @comment TODO add a 2nd operation eg perimeter.. and use for
10642: @comment a concrete example
1.5 anton 10643:
1.78 anton 10644: @cindex abstract class
10645: How do we create a graphical object? With the present definitions,
10646: we cannot create a useful graphical object. The class
10647: @code{graphical} describes graphical objects in general, but not
10648: any concrete graphical object type (C++ users would call it an
10649: @emph{abstract class}); e.g., there is no method for the selector
10650: @code{draw} in the class @code{graphical}.
1.5 anton 10651:
1.78 anton 10652: For concrete graphical objects, we define child classes of the
10653: class @code{graphical}, e.g.:
1.5 anton 10654:
1.78 anton 10655: @cindex @code{overrides} usage
10656: @cindex @code{field} usage in class definition
1.26 crook 10657: @example
1.78 anton 10658: graphical class \ "graphical" is the parent class
10659: cell% field circle-radius
1.5 anton 10660:
1.78 anton 10661: :noname ( x y circle -- )
10662: circle-radius @@ draw-circle ;
10663: overrides draw
1.5 anton 10664:
1.78 anton 10665: :noname ( n-radius circle -- )
10666: circle-radius ! ;
10667: overrides construct
1.5 anton 10668:
1.78 anton 10669: end-class circle
10670: @end example
1.44 crook 10671:
1.78 anton 10672: Here we define a class @code{circle} as a child of @code{graphical},
10673: with field @code{circle-radius} (which behaves just like a field
10674: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10675: for the selectors @code{draw} and @code{construct} (@code{construct} is
10676: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10677:
1.78 anton 10678: Now we can create a circle on the heap (i.e.,
10679: @code{allocate}d memory) with:
1.44 crook 10680:
1.78 anton 10681: @cindex @code{heap-new} usage
1.5 anton 10682: @example
1.78 anton 10683: 50 circle heap-new constant my-circle
1.5 anton 10684: @end example
10685:
1.78 anton 10686: @noindent
10687: @code{heap-new} invokes @code{construct}, thus
10688: initializing the field @code{circle-radius} with 50. We can draw
10689: this new circle at (100,100) with:
1.5 anton 10690:
10691: @example
1.78 anton 10692: 100 100 my-circle draw
1.5 anton 10693: @end example
10694:
1.78 anton 10695: @cindex selector invocation, restrictions
10696: @cindex class definition, restrictions
10697: Note: You can only invoke a selector if the object on the TOS
10698: (the receiving object) belongs to the class where the selector was
10699: defined or one of its descendents; e.g., you can invoke
10700: @code{draw} only for objects belonging to @code{graphical}
10701: or its descendents (e.g., @code{circle}). Immediately before
10702: @code{end-class}, the search order has to be the same as
10703: immediately after @code{class}.
10704:
10705: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10706: @subsubsection The @file{object.fs} base class
10707: @cindex @code{object} class
10708:
10709: When you define a class, you have to specify a parent class. So how do
10710: you start defining classes? There is one class available from the start:
10711: @code{object}. It is ancestor for all classes and so is the
10712: only class that has no parent. It has two selectors: @code{construct}
10713: and @code{print}.
10714:
10715: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10716: @subsubsection Creating objects
10717: @cindex creating objects
10718: @cindex object creation
10719: @cindex object allocation options
10720:
10721: @cindex @code{heap-new} discussion
10722: @cindex @code{dict-new} discussion
10723: @cindex @code{construct} discussion
10724: You can create and initialize an object of a class on the heap with
10725: @code{heap-new} ( ... class -- object ) and in the dictionary
10726: (allocation with @code{allot}) with @code{dict-new} (
10727: ... class -- object ). Both words invoke @code{construct}, which
10728: consumes the stack items indicated by "..." above.
10729:
10730: @cindex @code{init-object} discussion
10731: @cindex @code{class-inst-size} discussion
10732: If you want to allocate memory for an object yourself, you can get its
10733: alignment and size with @code{class-inst-size 2@@} ( class --
10734: align size ). Once you have memory for an object, you can initialize
10735: it with @code{init-object} ( ... class object -- );
10736: @code{construct} does only a part of the necessary work.
10737:
10738: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10739: @subsubsection Object-Oriented Programming Style
10740: @cindex object-oriented programming style
10741: @cindex programming style, object-oriented
1.5 anton 10742:
1.78 anton 10743: This section is not exhaustive.
1.5 anton 10744:
1.78 anton 10745: @cindex stack effects of selectors
10746: @cindex selectors and stack effects
10747: In general, it is a good idea to ensure that all methods for the
10748: same selector have the same stack effect: when you invoke a selector,
10749: you often have no idea which method will be invoked, so, unless all
10750: methods have the same stack effect, you will not know the stack effect
10751: of the selector invocation.
1.5 anton 10752:
1.78 anton 10753: One exception to this rule is methods for the selector
10754: @code{construct}. We know which method is invoked, because we
10755: specify the class to be constructed at the same place. Actually, I
10756: defined @code{construct} as a selector only to give the users a
10757: convenient way to specify initialization. The way it is used, a
10758: mechanism different from selector invocation would be more natural
10759: (but probably would take more code and more space to explain).
1.5 anton 10760:
1.78 anton 10761: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10762: @subsubsection Class Binding
10763: @cindex class binding
10764: @cindex early binding
1.5 anton 10765:
1.78 anton 10766: @cindex late binding
10767: Normal selector invocations determine the method at run-time depending
10768: on the class of the receiving object. This run-time selection is called
10769: @i{late binding}.
1.5 anton 10770:
1.78 anton 10771: Sometimes it's preferable to invoke a different method. For example,
10772: you might want to use the simple method for @code{print}ing
10773: @code{object}s instead of the possibly long-winded @code{print} method
10774: of the receiver class. You can achieve this by replacing the invocation
10775: of @code{print} with:
1.5 anton 10776:
1.78 anton 10777: @cindex @code{[bind]} usage
1.5 anton 10778: @example
1.78 anton 10779: [bind] object print
1.5 anton 10780: @end example
10781:
1.78 anton 10782: @noindent
10783: in compiled code or:
10784:
10785: @cindex @code{bind} usage
1.5 anton 10786: @example
1.78 anton 10787: bind object print
1.5 anton 10788: @end example
10789:
1.78 anton 10790: @cindex class binding, alternative to
10791: @noindent
10792: in interpreted code. Alternatively, you can define the method with a
10793: name (e.g., @code{print-object}), and then invoke it through the
10794: name. Class binding is just a (often more convenient) way to achieve
10795: the same effect; it avoids name clutter and allows you to invoke
10796: methods directly without naming them first.
1.5 anton 10797:
1.78 anton 10798: @cindex superclass binding
10799: @cindex parent class binding
10800: A frequent use of class binding is this: When we define a method
10801: for a selector, we often want the method to do what the selector does
10802: in the parent class, and a little more. There is a special word for
10803: this purpose: @code{[parent]}; @code{[parent]
10804: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10805: selector}}, where @code{@emph{parent}} is the parent
10806: class of the current class. E.g., a method definition might look like:
1.44 crook 10807:
1.78 anton 10808: @cindex @code{[parent]} usage
10809: @example
10810: :noname
10811: dup [parent] foo \ do parent's foo on the receiving object
10812: ... \ do some more
10813: ; overrides foo
10814: @end example
1.6 pazsan 10815:
1.78 anton 10816: @cindex class binding as optimization
10817: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10818: March 1997), Andrew McKewan presents class binding as an optimization
10819: technique. I recommend not using it for this purpose unless you are in
10820: an emergency. Late binding is pretty fast with this model anyway, so the
10821: benefit of using class binding is small; the cost of using class binding
10822: where it is not appropriate is reduced maintainability.
1.44 crook 10823:
1.78 anton 10824: While we are at programming style questions: You should bind
10825: selectors only to ancestor classes of the receiving object. E.g., say,
10826: you know that the receiving object is of class @code{foo} or its
10827: descendents; then you should bind only to @code{foo} and its
10828: ancestors.
1.12 anton 10829:
1.78 anton 10830: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10831: @subsubsection Method conveniences
10832: @cindex method conveniences
1.44 crook 10833:
1.78 anton 10834: In a method you usually access the receiving object pretty often. If
10835: you define the method as a plain colon definition (e.g., with
10836: @code{:noname}), you may have to do a lot of stack
10837: gymnastics. To avoid this, you can define the method with @code{m:
10838: ... ;m}. E.g., you could define the method for
10839: @code{draw}ing a @code{circle} with
1.6 pazsan 10840:
1.78 anton 10841: @cindex @code{this} usage
10842: @cindex @code{m:} usage
10843: @cindex @code{;m} usage
10844: @example
10845: m: ( x y circle -- )
10846: ( x y ) this circle-radius @@ draw-circle ;m
10847: @end example
1.6 pazsan 10848:
1.78 anton 10849: @cindex @code{exit} in @code{m: ... ;m}
10850: @cindex @code{exitm} discussion
10851: @cindex @code{catch} in @code{m: ... ;m}
10852: When this method is executed, the receiver object is removed from the
10853: stack; you can access it with @code{this} (admittedly, in this
10854: example the use of @code{m: ... ;m} offers no advantage). Note
10855: that I specify the stack effect for the whole method (i.e. including
10856: the receiver object), not just for the code between @code{m:}
10857: and @code{;m}. You cannot use @code{exit} in
10858: @code{m:...;m}; instead, use
10859: @code{exitm}.@footnote{Moreover, for any word that calls
10860: @code{catch} and was defined before loading
10861: @code{objects.fs}, you have to redefine it like I redefined
10862: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10863:
1.78 anton 10864: @cindex @code{inst-var} usage
10865: You will frequently use sequences of the form @code{this
10866: @emph{field}} (in the example above: @code{this
10867: circle-radius}). If you use the field only in this way, you can
10868: define it with @code{inst-var} and eliminate the
10869: @code{this} before the field name. E.g., the @code{circle}
10870: class above could also be defined with:
1.6 pazsan 10871:
1.78 anton 10872: @example
10873: graphical class
10874: cell% inst-var radius
1.6 pazsan 10875:
1.78 anton 10876: m: ( x y circle -- )
10877: radius @@ draw-circle ;m
10878: overrides draw
1.6 pazsan 10879:
1.78 anton 10880: m: ( n-radius circle -- )
10881: radius ! ;m
10882: overrides construct
1.6 pazsan 10883:
1.78 anton 10884: end-class circle
10885: @end example
1.6 pazsan 10886:
1.78 anton 10887: @code{radius} can only be used in @code{circle} and its
10888: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10889:
1.78 anton 10890: @cindex @code{inst-value} usage
10891: You can also define fields with @code{inst-value}, which is
10892: to @code{inst-var} what @code{value} is to
10893: @code{variable}. You can change the value of such a field with
10894: @code{[to-inst]}. E.g., we could also define the class
10895: @code{circle} like this:
1.44 crook 10896:
1.78 anton 10897: @example
10898: graphical class
10899: inst-value radius
1.6 pazsan 10900:
1.78 anton 10901: m: ( x y circle -- )
10902: radius draw-circle ;m
10903: overrides draw
1.44 crook 10904:
1.78 anton 10905: m: ( n-radius circle -- )
10906: [to-inst] radius ;m
10907: overrides construct
1.6 pazsan 10908:
1.78 anton 10909: end-class circle
10910: @end example
1.6 pazsan 10911:
1.78 anton 10912: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10913:
1.78 anton 10914: @c Finally, you can define named methods with @code{:m}. One use of this
10915: @c feature is the definition of words that occur only in one class and are
10916: @c not intended to be overridden, but which still need method context
10917: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10918: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10919:
10920:
1.78 anton 10921: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10922: @subsubsection Classes and Scoping
10923: @cindex classes and scoping
10924: @cindex scoping and classes
1.6 pazsan 10925:
1.78 anton 10926: Inheritance is frequent, unlike structure extension. This exacerbates
10927: the problem with the field name convention (@pxref{Structure Naming
10928: Convention}): One always has to remember in which class the field was
10929: originally defined; changing a part of the class structure would require
10930: changes for renaming in otherwise unaffected code.
1.6 pazsan 10931:
1.78 anton 10932: @cindex @code{inst-var} visibility
10933: @cindex @code{inst-value} visibility
10934: To solve this problem, I added a scoping mechanism (which was not in my
10935: original charter): A field defined with @code{inst-var} (or
10936: @code{inst-value}) is visible only in the class where it is defined and in
10937: the descendent classes of this class. Using such fields only makes
10938: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10939:
1.78 anton 10940: This scoping mechanism allows us to use the unadorned field name,
10941: because name clashes with unrelated words become much less likely.
1.6 pazsan 10942:
1.78 anton 10943: @cindex @code{protected} discussion
10944: @cindex @code{private} discussion
10945: Once we have this mechanism, we can also use it for controlling the
10946: visibility of other words: All words defined after
10947: @code{protected} are visible only in the current class and its
10948: descendents. @code{public} restores the compilation
10949: (i.e. @code{current}) word list that was in effect before. If you
10950: have several @code{protected}s without an intervening
10951: @code{public} or @code{set-current}, @code{public}
10952: will restore the compilation word list in effect before the first of
10953: these @code{protected}s.
1.6 pazsan 10954:
1.78 anton 10955: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10956: @subsubsection Dividing classes
10957: @cindex Dividing classes
10958: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10959:
1.78 anton 10960: You may want to do the definition of methods separate from the
10961: definition of the class, its selectors, fields, and instance variables,
10962: i.e., separate the implementation from the definition. You can do this
10963: in the following way:
1.6 pazsan 10964:
1.78 anton 10965: @example
10966: graphical class
10967: inst-value radius
10968: end-class circle
1.6 pazsan 10969:
1.78 anton 10970: ... \ do some other stuff
1.6 pazsan 10971:
1.78 anton 10972: circle methods \ now we are ready
1.44 crook 10973:
1.78 anton 10974: m: ( x y circle -- )
10975: radius draw-circle ;m
10976: overrides draw
1.6 pazsan 10977:
1.78 anton 10978: m: ( n-radius circle -- )
10979: [to-inst] radius ;m
10980: overrides construct
1.44 crook 10981:
1.78 anton 10982: end-methods
10983: @end example
1.7 pazsan 10984:
1.78 anton 10985: You can use several @code{methods}...@code{end-methods} sections. The
10986: only things you can do to the class in these sections are: defining
10987: methods, and overriding the class's selectors. You must not define new
10988: selectors or fields.
1.7 pazsan 10989:
1.78 anton 10990: Note that you often have to override a selector before using it. In
10991: particular, you usually have to override @code{construct} with a new
10992: method before you can invoke @code{heap-new} and friends. E.g., you
10993: must not create a circle before the @code{overrides construct} sequence
10994: in the example above.
1.7 pazsan 10995:
1.78 anton 10996: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
10997: @subsubsection Object Interfaces
10998: @cindex object interfaces
10999: @cindex interfaces for objects
1.7 pazsan 11000:
1.78 anton 11001: In this model you can only call selectors defined in the class of the
11002: receiving objects or in one of its ancestors. If you call a selector
11003: with a receiving object that is not in one of these classes, the
11004: result is undefined; if you are lucky, the program crashes
11005: immediately.
1.7 pazsan 11006:
1.78 anton 11007: @cindex selectors common to hardly-related classes
11008: Now consider the case when you want to have a selector (or several)
11009: available in two classes: You would have to add the selector to a
11010: common ancestor class, in the worst case to @code{object}. You
11011: may not want to do this, e.g., because someone else is responsible for
11012: this ancestor class.
1.7 pazsan 11013:
1.78 anton 11014: The solution for this problem is interfaces. An interface is a
11015: collection of selectors. If a class implements an interface, the
11016: selectors become available to the class and its descendents. A class
11017: can implement an unlimited number of interfaces. For the problem
11018: discussed above, we would define an interface for the selector(s), and
11019: both classes would implement the interface.
1.7 pazsan 11020:
1.78 anton 11021: As an example, consider an interface @code{storage} for
11022: writing objects to disk and getting them back, and a class
11023: @code{foo} that implements it. The code would look like this:
1.7 pazsan 11024:
1.78 anton 11025: @cindex @code{interface} usage
11026: @cindex @code{end-interface} usage
11027: @cindex @code{implementation} usage
11028: @example
11029: interface
11030: selector write ( file object -- )
11031: selector read1 ( file object -- )
11032: end-interface storage
1.13 pazsan 11033:
1.78 anton 11034: bar class
11035: storage implementation
1.13 pazsan 11036:
1.78 anton 11037: ... overrides write
11038: ... overrides read1
11039: ...
11040: end-class foo
11041: @end example
1.13 pazsan 11042:
1.78 anton 11043: @noindent
11044: (I would add a word @code{read} @i{( file -- object )} that uses
11045: @code{read1} internally, but that's beyond the point illustrated
11046: here.)
1.13 pazsan 11047:
1.78 anton 11048: Note that you cannot use @code{protected} in an interface; and
11049: of course you cannot define fields.
1.13 pazsan 11050:
1.78 anton 11051: In the Neon model, all selectors are available for all classes;
11052: therefore it does not need interfaces. The price you pay in this model
11053: is slower late binding, and therefore, added complexity to avoid late
11054: binding.
1.13 pazsan 11055:
1.78 anton 11056: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11057: @subsubsection @file{objects.fs} Implementation
11058: @cindex @file{objects.fs} implementation
1.13 pazsan 11059:
1.78 anton 11060: @cindex @code{object-map} discussion
11061: An object is a piece of memory, like one of the data structures
11062: described with @code{struct...end-struct}. It has a field
11063: @code{object-map} that points to the method map for the object's
11064: class.
1.13 pazsan 11065:
1.78 anton 11066: @cindex method map
11067: @cindex virtual function table
11068: The @emph{method map}@footnote{This is Self terminology; in C++
11069: terminology: virtual function table.} is an array that contains the
11070: execution tokens (@i{xt}s) of the methods for the object's class. Each
11071: selector contains an offset into a method map.
1.13 pazsan 11072:
1.78 anton 11073: @cindex @code{selector} implementation, class
11074: @code{selector} is a defining word that uses
11075: @code{CREATE} and @code{DOES>}. The body of the
11076: selector contains the offset; the @code{DOES>} action for a
11077: class selector is, basically:
1.8 pazsan 11078:
11079: @example
1.78 anton 11080: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 11081: @end example
11082:
1.78 anton 11083: Since @code{object-map} is the first field of the object, it
11084: does not generate any code. As you can see, calling a selector has a
11085: small, constant cost.
1.26 crook 11086:
1.78 anton 11087: @cindex @code{current-interface} discussion
11088: @cindex class implementation and representation
11089: A class is basically a @code{struct} combined with a method
11090: map. During the class definition the alignment and size of the class
11091: are passed on the stack, just as with @code{struct}s, so
11092: @code{field} can also be used for defining class
11093: fields. However, passing more items on the stack would be
11094: inconvenient, so @code{class} builds a data structure in memory,
11095: which is accessed through the variable
11096: @code{current-interface}. After its definition is complete, the
11097: class is represented on the stack by a pointer (e.g., as parameter for
11098: a child class definition).
1.26 crook 11099:
1.78 anton 11100: A new class starts off with the alignment and size of its parent,
11101: and a copy of the parent's method map. Defining new fields extends the
11102: size and alignment; likewise, defining new selectors extends the
11103: method map. @code{overrides} just stores a new @i{xt} in the method
11104: map at the offset given by the selector.
1.13 pazsan 11105:
1.78 anton 11106: @cindex class binding, implementation
11107: Class binding just gets the @i{xt} at the offset given by the selector
11108: from the class's method map and @code{compile,}s (in the case of
11109: @code{[bind]}) it.
1.13 pazsan 11110:
1.78 anton 11111: @cindex @code{this} implementation
11112: @cindex @code{catch} and @code{this}
11113: @cindex @code{this} and @code{catch}
11114: I implemented @code{this} as a @code{value}. At the
11115: start of an @code{m:...;m} method the old @code{this} is
11116: stored to the return stack and restored at the end; and the object on
11117: the TOS is stored @code{TO this}. This technique has one
11118: disadvantage: If the user does not leave the method via
11119: @code{;m}, but via @code{throw} or @code{exit},
11120: @code{this} is not restored (and @code{exit} may
11121: crash). To deal with the @code{throw} problem, I have redefined
11122: @code{catch} to save and restore @code{this}; the same
11123: should be done with any word that can catch an exception. As for
11124: @code{exit}, I simply forbid it (as a replacement, there is
11125: @code{exitm}).
1.13 pazsan 11126:
1.78 anton 11127: @cindex @code{inst-var} implementation
11128: @code{inst-var} is just the same as @code{field}, with
11129: a different @code{DOES>} action:
1.13 pazsan 11130: @example
1.78 anton 11131: @@ this +
1.8 pazsan 11132: @end example
1.78 anton 11133: Similar for @code{inst-value}.
1.8 pazsan 11134:
1.78 anton 11135: @cindex class scoping implementation
11136: Each class also has a word list that contains the words defined with
11137: @code{inst-var} and @code{inst-value}, and its protected
11138: words. It also has a pointer to its parent. @code{class} pushes
11139: the word lists of the class and all its ancestors onto the search order stack,
11140: and @code{end-class} drops them.
1.20 pazsan 11141:
1.78 anton 11142: @cindex interface implementation
11143: An interface is like a class without fields, parent and protected
11144: words; i.e., it just has a method map. If a class implements an
11145: interface, its method map contains a pointer to the method map of the
11146: interface. The positive offsets in the map are reserved for class
11147: methods, therefore interface map pointers have negative
11148: offsets. Interfaces have offsets that are unique throughout the
11149: system, unlike class selectors, whose offsets are only unique for the
11150: classes where the selector is available (invokable).
1.20 pazsan 11151:
1.78 anton 11152: This structure means that interface selectors have to perform one
11153: indirection more than class selectors to find their method. Their body
11154: contains the interface map pointer offset in the class method map, and
11155: the method offset in the interface method map. The
11156: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11157:
11158: @example
1.78 anton 11159: ( object selector-body )
11160: 2dup selector-interface @@ ( object selector-body object interface-offset )
11161: swap object-map @@ + @@ ( object selector-body map )
11162: swap selector-offset @@ + @@ execute
1.20 pazsan 11163: @end example
11164:
1.78 anton 11165: where @code{object-map} and @code{selector-offset} are
11166: first fields and generate no code.
1.20 pazsan 11167:
1.78 anton 11168: As a concrete example, consider the following code:
1.20 pazsan 11169:
11170: @example
1.78 anton 11171: interface
11172: selector if1sel1
11173: selector if1sel2
11174: end-interface if1
1.20 pazsan 11175:
1.78 anton 11176: object class
11177: if1 implementation
11178: selector cl1sel1
11179: cell% inst-var cl1iv1
1.20 pazsan 11180:
1.78 anton 11181: ' m1 overrides construct
11182: ' m2 overrides if1sel1
11183: ' m3 overrides if1sel2
11184: ' m4 overrides cl1sel2
11185: end-class cl1
1.20 pazsan 11186:
1.78 anton 11187: create obj1 object dict-new drop
11188: create obj2 cl1 dict-new drop
11189: @end example
1.20 pazsan 11190:
1.78 anton 11191: The data structure created by this code (including the data structure
11192: for @code{object}) is shown in the
11193: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11194: @comment TODO add this diagram..
1.20 pazsan 11195:
1.78 anton 11196: @node Objects Glossary, , Objects Implementation, Objects
11197: @subsubsection @file{objects.fs} Glossary
11198: @cindex @file{objects.fs} Glossary
1.20 pazsan 11199:
11200:
1.78 anton 11201: doc---objects-bind
11202: doc---objects-<bind>
11203: doc---objects-bind'
11204: doc---objects-[bind]
11205: doc---objects-class
11206: doc---objects-class->map
11207: doc---objects-class-inst-size
11208: doc---objects-class-override!
1.79 anton 11209: doc---objects-class-previous
11210: doc---objects-class>order
1.78 anton 11211: doc---objects-construct
11212: doc---objects-current'
11213: doc---objects-[current]
11214: doc---objects-current-interface
11215: doc---objects-dict-new
11216: doc---objects-end-class
11217: doc---objects-end-class-noname
11218: doc---objects-end-interface
11219: doc---objects-end-interface-noname
11220: doc---objects-end-methods
11221: doc---objects-exitm
11222: doc---objects-heap-new
11223: doc---objects-implementation
11224: doc---objects-init-object
11225: doc---objects-inst-value
11226: doc---objects-inst-var
11227: doc---objects-interface
11228: doc---objects-m:
11229: doc---objects-:m
11230: doc---objects-;m
11231: doc---objects-method
11232: doc---objects-methods
11233: doc---objects-object
11234: doc---objects-overrides
11235: doc---objects-[parent]
11236: doc---objects-print
11237: doc---objects-protected
11238: doc---objects-public
11239: doc---objects-selector
11240: doc---objects-this
11241: doc---objects-<to-inst>
11242: doc---objects-[to-inst]
11243: doc---objects-to-this
11244: doc---objects-xt-new
1.20 pazsan 11245:
11246:
1.78 anton 11247: @c -------------------------------------------------------------
11248: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11249: @subsection The @file{oof.fs} model
11250: @cindex oof
11251: @cindex object-oriented programming
1.20 pazsan 11252:
1.78 anton 11253: @cindex @file{objects.fs}
11254: @cindex @file{oof.fs}
1.20 pazsan 11255:
1.78 anton 11256: This section describes the @file{oof.fs} package.
1.20 pazsan 11257:
1.78 anton 11258: The package described in this section has been used in bigFORTH since 1991, and
11259: used for two large applications: a chromatographic system used to
11260: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11261:
1.78 anton 11262: You can find a description (in German) of @file{oof.fs} in @cite{Object
11263: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11264: 10(2), 1994.
1.20 pazsan 11265:
1.78 anton 11266: @menu
11267: * Properties of the OOF model::
11268: * Basic OOF Usage::
11269: * The OOF base class::
11270: * Class Declaration::
11271: * Class Implementation::
11272: @end menu
1.20 pazsan 11273:
1.78 anton 11274: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11275: @subsubsection Properties of the @file{oof.fs} model
11276: @cindex @file{oof.fs} properties
1.20 pazsan 11277:
1.78 anton 11278: @itemize @bullet
11279: @item
11280: This model combines object oriented programming with information
11281: hiding. It helps you writing large application, where scoping is
11282: necessary, because it provides class-oriented scoping.
1.20 pazsan 11283:
1.78 anton 11284: @item
11285: Named objects, object pointers, and object arrays can be created,
11286: selector invocation uses the ``object selector'' syntax. Selector invocation
11287: to objects and/or selectors on the stack is a bit less convenient, but
11288: possible.
1.44 crook 11289:
1.78 anton 11290: @item
11291: Selector invocation and instance variable usage of the active object is
11292: straightforward, since both make use of the active object.
1.44 crook 11293:
1.78 anton 11294: @item
11295: Late binding is efficient and easy to use.
1.20 pazsan 11296:
1.78 anton 11297: @item
11298: State-smart objects parse selectors. However, extensibility is provided
11299: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11300:
1.78 anton 11301: @item
11302: An implementation in ANS Forth is available.
1.20 pazsan 11303:
1.78 anton 11304: @end itemize
1.23 crook 11305:
11306:
1.78 anton 11307: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11308: @subsubsection Basic @file{oof.fs} Usage
11309: @cindex @file{oof.fs} usage
1.23 crook 11310:
1.78 anton 11311: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11312:
1.78 anton 11313: You can define a class for graphical objects like this:
1.23 crook 11314:
1.78 anton 11315: @cindex @code{class} usage
11316: @cindex @code{class;} usage
11317: @cindex @code{method} usage
11318: @example
11319: object class graphical \ "object" is the parent class
1.139 pazsan 11320: method draw ( x y -- )
1.78 anton 11321: class;
11322: @end example
1.23 crook 11323:
1.78 anton 11324: This code defines a class @code{graphical} with an
11325: operation @code{draw}. We can perform the operation
11326: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11327:
1.78 anton 11328: @example
11329: 100 100 t-rex draw
11330: @end example
1.23 crook 11331:
1.78 anton 11332: @noindent
11333: where @code{t-rex} is an object or object pointer, created with e.g.
11334: @code{graphical : t-rex}.
1.23 crook 11335:
1.78 anton 11336: @cindex abstract class
11337: How do we create a graphical object? With the present definitions,
11338: we cannot create a useful graphical object. The class
11339: @code{graphical} describes graphical objects in general, but not
11340: any concrete graphical object type (C++ users would call it an
11341: @emph{abstract class}); e.g., there is no method for the selector
11342: @code{draw} in the class @code{graphical}.
1.23 crook 11343:
1.78 anton 11344: For concrete graphical objects, we define child classes of the
11345: class @code{graphical}, e.g.:
1.23 crook 11346:
1.78 anton 11347: @example
11348: graphical class circle \ "graphical" is the parent class
11349: cell var circle-radius
11350: how:
11351: : draw ( x y -- )
11352: circle-radius @@ draw-circle ;
1.23 crook 11353:
1.139 pazsan 11354: : init ( n-radius -- )
1.78 anton 11355: circle-radius ! ;
11356: class;
11357: @end example
1.1 anton 11358:
1.78 anton 11359: Here we define a class @code{circle} as a child of @code{graphical},
11360: with a field @code{circle-radius}; it defines new methods for the
11361: selectors @code{draw} and @code{init} (@code{init} is defined in
11362: @code{object}, the parent class of @code{graphical}).
1.1 anton 11363:
1.78 anton 11364: Now we can create a circle in the dictionary with:
1.1 anton 11365:
1.78 anton 11366: @example
11367: 50 circle : my-circle
11368: @end example
1.21 crook 11369:
1.78 anton 11370: @noindent
11371: @code{:} invokes @code{init}, thus initializing the field
11372: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11373: with:
1.1 anton 11374:
1.78 anton 11375: @example
11376: 100 100 my-circle draw
11377: @end example
1.1 anton 11378:
1.78 anton 11379: @cindex selector invocation, restrictions
11380: @cindex class definition, restrictions
11381: Note: You can only invoke a selector if the receiving object belongs to
11382: the class where the selector was defined or one of its descendents;
11383: e.g., you can invoke @code{draw} only for objects belonging to
11384: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11385: mechanism will check if you try to invoke a selector that is not
11386: defined in this class hierarchy, so you'll get an error at compilation
11387: time.
1.1 anton 11388:
11389:
1.78 anton 11390: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11391: @subsubsection The @file{oof.fs} base class
11392: @cindex @file{oof.fs} base class
1.1 anton 11393:
1.78 anton 11394: When you define a class, you have to specify a parent class. So how do
11395: you start defining classes? There is one class available from the start:
11396: @code{object}. You have to use it as ancestor for all classes. It is the
11397: only class that has no parent. Classes are also objects, except that
11398: they don't have instance variables; class manipulation such as
11399: inheritance or changing definitions of a class is handled through
11400: selectors of the class @code{object}.
1.1 anton 11401:
1.78 anton 11402: @code{object} provides a number of selectors:
1.1 anton 11403:
1.78 anton 11404: @itemize @bullet
11405: @item
11406: @code{class} for subclassing, @code{definitions} to add definitions
11407: later on, and @code{class?} to get type informations (is the class a
11408: subclass of the class passed on the stack?).
1.1 anton 11409:
1.78 anton 11410: doc---object-class
11411: doc---object-definitions
11412: doc---object-class?
1.1 anton 11413:
11414:
1.26 crook 11415: @item
1.78 anton 11416: @code{init} and @code{dispose} as constructor and destructor of the
11417: object. @code{init} is invocated after the object's memory is allocated,
11418: while @code{dispose} also handles deallocation. Thus if you redefine
11419: @code{dispose}, you have to call the parent's dispose with @code{super
11420: dispose}, too.
11421:
11422: doc---object-init
11423: doc---object-dispose
11424:
1.1 anton 11425:
1.26 crook 11426: @item
1.78 anton 11427: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11428: @code{[]} to create named and unnamed objects and object arrays or
11429: object pointers.
11430:
11431: doc---object-new
11432: doc---object-new[]
11433: doc---object-:
11434: doc---object-ptr
11435: doc---object-asptr
11436: doc---object-[]
11437:
1.1 anton 11438:
1.26 crook 11439: @item
1.78 anton 11440: @code{::} and @code{super} for explicit scoping. You should use explicit
11441: scoping only for super classes or classes with the same set of instance
11442: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11443:
1.78 anton 11444: doc---object-::
11445: doc---object-super
1.21 crook 11446:
11447:
1.26 crook 11448: @item
1.78 anton 11449: @code{self} to get the address of the object
1.21 crook 11450:
1.78 anton 11451: doc---object-self
1.21 crook 11452:
11453:
1.78 anton 11454: @item
11455: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11456: pointers and instance defers.
1.21 crook 11457:
1.78 anton 11458: doc---object-bind
11459: doc---object-bound
11460: doc---object-link
11461: doc---object-is
1.21 crook 11462:
11463:
1.78 anton 11464: @item
11465: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11466: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11467:
1.78 anton 11468: doc---object-'
11469: doc---object-postpone
1.21 crook 11470:
11471:
1.78 anton 11472: @item
11473: @code{with} and @code{endwith} to select the active object from the
11474: stack, and enable its scope. Using @code{with} and @code{endwith}
11475: also allows you to create code using selector @code{postpone} without being
11476: trapped by the state-smart objects.
1.21 crook 11477:
1.78 anton 11478: doc---object-with
11479: doc---object-endwith
1.21 crook 11480:
11481:
1.78 anton 11482: @end itemize
1.21 crook 11483:
1.78 anton 11484: @node Class Declaration, Class Implementation, The OOF base class, OOF
11485: @subsubsection Class Declaration
11486: @cindex class declaration
1.21 crook 11487:
1.78 anton 11488: @itemize @bullet
11489: @item
11490: Instance variables
1.21 crook 11491:
1.78 anton 11492: doc---oof-var
1.21 crook 11493:
11494:
1.78 anton 11495: @item
11496: Object pointers
1.21 crook 11497:
1.78 anton 11498: doc---oof-ptr
11499: doc---oof-asptr
1.21 crook 11500:
11501:
1.78 anton 11502: @item
11503: Instance defers
1.21 crook 11504:
1.78 anton 11505: doc---oof-defer
1.21 crook 11506:
11507:
1.78 anton 11508: @item
11509: Method selectors
1.21 crook 11510:
1.78 anton 11511: doc---oof-early
11512: doc---oof-method
1.21 crook 11513:
11514:
1.78 anton 11515: @item
11516: Class-wide variables
1.21 crook 11517:
1.78 anton 11518: doc---oof-static
1.21 crook 11519:
11520:
1.78 anton 11521: @item
11522: End declaration
1.1 anton 11523:
1.78 anton 11524: doc---oof-how:
11525: doc---oof-class;
1.21 crook 11526:
11527:
1.78 anton 11528: @end itemize
1.21 crook 11529:
1.78 anton 11530: @c -------------------------------------------------------------
11531: @node Class Implementation, , Class Declaration, OOF
11532: @subsubsection Class Implementation
11533: @cindex class implementation
1.21 crook 11534:
1.78 anton 11535: @c -------------------------------------------------------------
11536: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11537: @subsection The @file{mini-oof.fs} model
11538: @cindex mini-oof
1.21 crook 11539:
1.78 anton 11540: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11541: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11542: and reduces to the bare minimum of features. This is based on a posting
11543: of Bernd Paysan in comp.lang.forth.
1.21 crook 11544:
1.78 anton 11545: @menu
11546: * Basic Mini-OOF Usage::
11547: * Mini-OOF Example::
11548: * Mini-OOF Implementation::
11549: @end menu
1.21 crook 11550:
1.78 anton 11551: @c -------------------------------------------------------------
11552: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11553: @subsubsection Basic @file{mini-oof.fs} Usage
11554: @cindex mini-oof usage
1.21 crook 11555:
1.78 anton 11556: There is a base class (@code{class}, which allocates one cell for the
11557: object pointer) plus seven other words: to define a method, a variable,
11558: a class; to end a class, to resolve binding, to allocate an object and
11559: to compile a class method.
11560: @comment TODO better description of the last one
1.26 crook 11561:
1.21 crook 11562:
1.78 anton 11563: doc-object
11564: doc-method
11565: doc-var
11566: doc-class
11567: doc-end-class
11568: doc-defines
11569: doc-new
11570: doc-::
1.21 crook 11571:
11572:
11573:
1.78 anton 11574: @c -------------------------------------------------------------
11575: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11576: @subsubsection Mini-OOF Example
11577: @cindex mini-oof example
1.1 anton 11578:
1.78 anton 11579: A short example shows how to use this package. This example, in slightly
11580: extended form, is supplied as @file{moof-exm.fs}
11581: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11582:
1.26 crook 11583: @example
1.78 anton 11584: object class
11585: method init
11586: method draw
11587: end-class graphical
1.26 crook 11588: @end example
1.20 pazsan 11589:
1.78 anton 11590: This code defines a class @code{graphical} with an
11591: operation @code{draw}. We can perform the operation
11592: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11593:
1.26 crook 11594: @example
1.78 anton 11595: 100 100 t-rex draw
1.26 crook 11596: @end example
1.12 anton 11597:
1.78 anton 11598: where @code{t-rex} is an object or object pointer, created with e.g.
11599: @code{graphical new Constant t-rex}.
1.12 anton 11600:
1.78 anton 11601: For concrete graphical objects, we define child classes of the
11602: class @code{graphical}, e.g.:
1.12 anton 11603:
1.26 crook 11604: @example
11605: graphical class
1.78 anton 11606: cell var circle-radius
11607: end-class circle \ "graphical" is the parent class
1.12 anton 11608:
1.78 anton 11609: :noname ( x y -- )
11610: circle-radius @@ draw-circle ; circle defines draw
11611: :noname ( r -- )
11612: circle-radius ! ; circle defines init
11613: @end example
1.12 anton 11614:
1.78 anton 11615: There is no implicit init method, so we have to define one. The creation
11616: code of the object now has to call init explicitely.
1.21 crook 11617:
1.78 anton 11618: @example
11619: circle new Constant my-circle
11620: 50 my-circle init
1.12 anton 11621: @end example
11622:
1.78 anton 11623: It is also possible to add a function to create named objects with
11624: automatic call of @code{init}, given that all objects have @code{init}
11625: on the same place:
1.38 anton 11626:
1.78 anton 11627: @example
11628: : new: ( .. o "name" -- )
11629: new dup Constant init ;
11630: 80 circle new: large-circle
11631: @end example
1.12 anton 11632:
1.78 anton 11633: We can draw this new circle at (100,100) with:
1.12 anton 11634:
1.78 anton 11635: @example
11636: 100 100 my-circle draw
11637: @end example
1.12 anton 11638:
1.78 anton 11639: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11640: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11641:
1.78 anton 11642: Object-oriented systems with late binding typically use a
11643: ``vtable''-approach: the first variable in each object is a pointer to a
11644: table, which contains the methods as function pointers. The vtable
11645: may also contain other information.
1.12 anton 11646:
1.79 anton 11647: So first, let's declare selectors:
1.37 anton 11648:
11649: @example
1.79 anton 11650: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11651: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11652: @end example
1.37 anton 11653:
1.79 anton 11654: During selector declaration, the number of selectors and instance
11655: variables is on the stack (in address units). @code{method} creates one
11656: selector and increments the selector number. To execute a selector, it
1.78 anton 11657: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11658: executes the method @i{xt} stored there. Each selector takes the object
11659: it is invoked with as top of stack parameter; it passes the parameters
11660: (including the object) unchanged to the appropriate method which should
1.78 anton 11661: consume that object.
1.37 anton 11662:
1.78 anton 11663: Now, we also have to declare instance variables
1.37 anton 11664:
1.78 anton 11665: @example
1.79 anton 11666: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11667: DOES> ( o -- addr ) @@ + ;
1.37 anton 11668: @end example
11669:
1.78 anton 11670: As before, a word is created with the current offset. Instance
11671: variables can have different sizes (cells, floats, doubles, chars), so
11672: all we do is take the size and add it to the offset. If your machine
11673: has alignment restrictions, put the proper @code{aligned} or
11674: @code{faligned} before the variable, to adjust the variable
11675: offset. That's why it is on the top of stack.
1.37 anton 11676:
1.78 anton 11677: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11678:
1.78 anton 11679: @example
11680: Create object 1 cells , 2 cells ,
1.79 anton 11681: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11682: @end example
1.12 anton 11683:
1.78 anton 11684: For inheritance, the vtable of the parent object has to be
11685: copied when a new, derived class is declared. This gives all the
11686: methods of the parent class, which can be overridden, though.
1.12 anton 11687:
1.78 anton 11688: @example
1.79 anton 11689: : end-class ( class selectors vars "name" -- )
1.78 anton 11690: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11691: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11692: @end example
1.12 anton 11693:
1.78 anton 11694: The first line creates the vtable, initialized with
11695: @code{noop}s. The second line is the inheritance mechanism, it
11696: copies the xts from the parent vtable.
1.12 anton 11697:
1.78 anton 11698: We still have no way to define new methods, let's do that now:
1.12 anton 11699:
1.26 crook 11700: @example
1.79 anton 11701: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11702: @end example
1.12 anton 11703:
1.78 anton 11704: To allocate a new object, we need a word, too:
1.12 anton 11705:
1.78 anton 11706: @example
11707: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11708: @end example
11709:
1.78 anton 11710: Sometimes derived classes want to access the method of the
11711: parent object. There are two ways to achieve this with Mini-OOF:
11712: first, you could use named words, and second, you could look up the
11713: vtable of the parent object.
1.12 anton 11714:
1.78 anton 11715: @example
11716: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11717: @end example
1.12 anton 11718:
11719:
1.78 anton 11720: Nothing can be more confusing than a good example, so here is
11721: one. First let's declare a text object (called
11722: @code{button}), that stores text and position:
1.12 anton 11723:
1.78 anton 11724: @example
11725: object class
11726: cell var text
11727: cell var len
11728: cell var x
11729: cell var y
11730: method init
11731: method draw
11732: end-class button
11733: @end example
1.12 anton 11734:
1.78 anton 11735: @noindent
11736: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11737:
1.26 crook 11738: @example
1.78 anton 11739: :noname ( o -- )
11740: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11741: button defines draw
11742: :noname ( addr u o -- )
11743: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11744: button defines init
1.26 crook 11745: @end example
1.12 anton 11746:
1.78 anton 11747: @noindent
11748: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11749: new data and no new selectors:
1.78 anton 11750:
11751: @example
11752: button class
11753: end-class bold-button
1.12 anton 11754:
1.78 anton 11755: : bold 27 emit ." [1m" ;
11756: : normal 27 emit ." [0m" ;
11757: @end example
1.1 anton 11758:
1.78 anton 11759: @noindent
11760: The class @code{bold-button} has a different draw method to
11761: @code{button}, but the new method is defined in terms of the draw method
11762: for @code{button}:
1.20 pazsan 11763:
1.78 anton 11764: @example
11765: :noname bold [ button :: draw ] normal ; bold-button defines draw
11766: @end example
1.21 crook 11767:
1.78 anton 11768: @noindent
1.79 anton 11769: Finally, create two objects and apply selectors:
1.21 crook 11770:
1.26 crook 11771: @example
1.78 anton 11772: button new Constant foo
11773: s" thin foo" foo init
11774: page
11775: foo draw
11776: bold-button new Constant bar
11777: s" fat bar" bar init
11778: 1 bar y !
11779: bar draw
1.26 crook 11780: @end example
1.21 crook 11781:
11782:
1.78 anton 11783: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11784: @subsection Comparison with other object models
11785: @cindex comparison of object models
11786: @cindex object models, comparison
11787:
11788: Many object-oriented Forth extensions have been proposed (@cite{A survey
11789: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11790: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11791: relation of the object models described here to two well-known and two
11792: closely-related (by the use of method maps) models. Andras Zsoter
11793: helped us with this section.
11794:
11795: @cindex Neon model
11796: The most popular model currently seems to be the Neon model (see
11797: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11798: 1997) by Andrew McKewan) but this model has a number of limitations
11799: @footnote{A longer version of this critique can be
11800: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11801: Dimensions, May 1997) by Anton Ertl.}:
11802:
11803: @itemize @bullet
11804: @item
11805: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11806: to pass objects on the stack.
1.21 crook 11807:
1.78 anton 11808: @item
11809: It requires that the selector parses the input stream (at
1.79 anton 11810: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11811: hard to find.
1.21 crook 11812:
1.78 anton 11813: @item
1.79 anton 11814: It allows using every selector on every object; this eliminates the
11815: need for interfaces, but makes it harder to create efficient
11816: implementations.
1.78 anton 11817: @end itemize
1.21 crook 11818:
1.78 anton 11819: @cindex Pountain's object-oriented model
11820: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11821: Press, London, 1987) by Dick Pountain. However, it is not really about
11822: object-oriented programming, because it hardly deals with late
11823: binding. Instead, it focuses on features like information hiding and
11824: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11825:
1.78 anton 11826: @cindex Zsoter's object-oriented model
1.79 anton 11827: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11828: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11829: describes a model that makes heavy use of an active object (like
11830: @code{this} in @file{objects.fs}): The active object is not only used
11831: for accessing all fields, but also specifies the receiving object of
11832: every selector invocation; you have to change the active object
11833: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11834: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11835: the method entry point is unnecessary with Zsoter's model, because the
11836: receiving object is the active object already. On the other hand, the
11837: explicit change is absolutely necessary in that model, because otherwise
11838: no one could ever change the active object. An ANS Forth implementation
11839: of this model is available through
11840: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11841:
1.78 anton 11842: @cindex @file{oof.fs}, differences to other models
11843: The @file{oof.fs} model combines information hiding and overloading
11844: resolution (by keeping names in various word lists) with object-oriented
11845: programming. It sets the active object implicitly on method entry, but
11846: also allows explicit changing (with @code{>o...o>} or with
11847: @code{with...endwith}). It uses parsing and state-smart objects and
11848: classes for resolving overloading and for early binding: the object or
11849: class parses the selector and determines the method from this. If the
11850: selector is not parsed by an object or class, it performs a call to the
11851: selector for the active object (late binding), like Zsoter's model.
11852: Fields are always accessed through the active object. The big
11853: disadvantage of this model is the parsing and the state-smartness, which
11854: reduces extensibility and increases the opportunities for subtle bugs;
11855: essentially, you are only safe if you never tick or @code{postpone} an
11856: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11857:
1.78 anton 11858: @cindex @file{mini-oof.fs}, differences to other models
11859: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11860: version of the @file{objects.fs} model, but syntactically it is a
11861: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11862:
11863:
1.78 anton 11864: @c -------------------------------------------------------------
1.150 anton 11865: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11866: @section Programming Tools
11867: @cindex programming tools
1.21 crook 11868:
1.78 anton 11869: @c !! move this and assembler down below OO stuff.
1.21 crook 11870:
1.78 anton 11871: @menu
1.150 anton 11872: * Examining:: Data and Code.
11873: * Forgetting words:: Usually before reloading.
1.78 anton 11874: * Debugging:: Simple and quick.
11875: * Assertions:: Making your programs self-checking.
11876: * Singlestep Debugger:: Executing your program word by word.
11877: @end menu
1.21 crook 11878:
1.78 anton 11879: @node Examining, Forgetting words, Programming Tools, Programming Tools
11880: @subsection Examining data and code
11881: @cindex examining data and code
11882: @cindex data examination
11883: @cindex code examination
1.44 crook 11884:
1.78 anton 11885: The following words inspect the stack non-destructively:
1.21 crook 11886:
1.78 anton 11887: doc-.s
11888: doc-f.s
1.158 anton 11889: doc-maxdepth-.s
1.44 crook 11890:
1.78 anton 11891: There is a word @code{.r} but it does @i{not} display the return stack!
11892: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11893:
1.78 anton 11894: doc-depth
11895: doc-fdepth
11896: doc-clearstack
1.124 anton 11897: doc-clearstacks
1.21 crook 11898:
1.78 anton 11899: The following words inspect memory.
1.21 crook 11900:
1.78 anton 11901: doc-?
11902: doc-dump
1.21 crook 11903:
1.78 anton 11904: And finally, @code{see} allows to inspect code:
1.21 crook 11905:
1.78 anton 11906: doc-see
11907: doc-xt-see
1.111 anton 11908: doc-simple-see
11909: doc-simple-see-range
1.182 anton 11910: doc-see-code
11911: doc-see-code-range
1.21 crook 11912:
1.78 anton 11913: @node Forgetting words, Debugging, Examining, Programming Tools
11914: @subsection Forgetting words
11915: @cindex words, forgetting
11916: @cindex forgeting words
1.21 crook 11917:
1.78 anton 11918: @c anton: other, maybe better places for this subsection: Defining Words;
11919: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11920:
1.78 anton 11921: Forth allows you to forget words (and everything that was alloted in the
11922: dictonary after them) in a LIFO manner.
1.21 crook 11923:
1.78 anton 11924: doc-marker
1.21 crook 11925:
1.78 anton 11926: The most common use of this feature is during progam development: when
11927: you change a source file, forget all the words it defined and load it
11928: again (since you also forget everything defined after the source file
11929: was loaded, you have to reload that, too). Note that effects like
11930: storing to variables and destroyed system words are not undone when you
11931: forget words. With a system like Gforth, that is fast enough at
11932: starting up and compiling, I find it more convenient to exit and restart
11933: Gforth, as this gives me a clean slate.
1.21 crook 11934:
1.78 anton 11935: Here's an example of using @code{marker} at the start of a source file
11936: that you are debugging; it ensures that you only ever have one copy of
11937: the file's definitions compiled at any time:
1.21 crook 11938:
1.78 anton 11939: @example
11940: [IFDEF] my-code
11941: my-code
11942: [ENDIF]
1.26 crook 11943:
1.78 anton 11944: marker my-code
11945: init-included-files
1.21 crook 11946:
1.78 anton 11947: \ .. definitions start here
11948: \ .
11949: \ .
11950: \ end
11951: @end example
1.21 crook 11952:
1.26 crook 11953:
1.78 anton 11954: @node Debugging, Assertions, Forgetting words, Programming Tools
11955: @subsection Debugging
11956: @cindex debugging
1.21 crook 11957:
1.78 anton 11958: Languages with a slow edit/compile/link/test development loop tend to
11959: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11960:
1.78 anton 11961: A much better (faster) way in fast-compiling languages is to add
11962: printing code at well-selected places, let the program run, look at
11963: the output, see where things went wrong, add more printing code, etc.,
11964: until the bug is found.
1.21 crook 11965:
1.78 anton 11966: The simple debugging aids provided in @file{debugs.fs}
11967: are meant to support this style of debugging.
1.21 crook 11968:
1.78 anton 11969: The word @code{~~} prints debugging information (by default the source
11970: location and the stack contents). It is easy to insert. If you use Emacs
11971: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11972: query-replace them with nothing). The deferred words
1.101 anton 11973: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11974: @code{~~}. The default source location output format works well with
11975: Emacs' compilation mode, so you can step through the program at the
11976: source level using @kbd{C-x `} (the advantage over a stepping debugger
11977: is that you can step in any direction and you know where the crash has
11978: happened or where the strange data has occurred).
1.21 crook 11979:
1.78 anton 11980: doc-~~
11981: doc-printdebugdata
1.101 anton 11982: doc-.debugline
1.203 anton 11983: doc-debug-fid
1.21 crook 11984:
1.106 anton 11985: @cindex filenames in @code{~~} output
11986: @code{~~} (and assertions) will usually print the wrong file name if a
11987: marker is executed in the same file after their occurance. They will
11988: print @samp{*somewhere*} as file name if a marker is executed in the
11989: same file before their occurance.
11990:
11991:
1.78 anton 11992: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
11993: @subsection Assertions
11994: @cindex assertions
1.21 crook 11995:
1.78 anton 11996: It is a good idea to make your programs self-checking, especially if you
11997: make an assumption that may become invalid during maintenance (for
11998: example, that a certain field of a data structure is never zero). Gforth
11999: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 12000:
12001: @example
1.78 anton 12002: assert( @i{flag} )
1.26 crook 12003: @end example
12004:
1.78 anton 12005: The code between @code{assert(} and @code{)} should compute a flag, that
12006: should be true if everything is alright and false otherwise. It should
12007: not change anything else on the stack. The overall stack effect of the
12008: assertion is @code{( -- )}. E.g.
1.21 crook 12009:
1.26 crook 12010: @example
1.78 anton 12011: assert( 1 1 + 2 = ) \ what we learn in school
12012: assert( dup 0<> ) \ assert that the top of stack is not zero
12013: assert( false ) \ this code should not be reached
1.21 crook 12014: @end example
12015:
1.78 anton 12016: The need for assertions is different at different times. During
12017: debugging, we want more checking, in production we sometimes care more
12018: for speed. Therefore, assertions can be turned off, i.e., the assertion
12019: becomes a comment. Depending on the importance of an assertion and the
12020: time it takes to check it, you may want to turn off some assertions and
12021: keep others turned on. Gforth provides several levels of assertions for
12022: this purpose:
12023:
12024:
12025: doc-assert0(
12026: doc-assert1(
12027: doc-assert2(
12028: doc-assert3(
12029: doc-assert(
12030: doc-)
1.21 crook 12031:
12032:
1.78 anton 12033: The variable @code{assert-level} specifies the highest assertions that
12034: are turned on. I.e., at the default @code{assert-level} of one,
12035: @code{assert0(} and @code{assert1(} assertions perform checking, while
12036: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 12037:
1.78 anton 12038: The value of @code{assert-level} is evaluated at compile-time, not at
12039: run-time. Therefore you cannot turn assertions on or off at run-time;
12040: you have to set the @code{assert-level} appropriately before compiling a
12041: piece of code. You can compile different pieces of code at different
12042: @code{assert-level}s (e.g., a trusted library at level 1 and
12043: newly-written code at level 3).
1.26 crook 12044:
12045:
1.78 anton 12046: doc-assert-level
1.26 crook 12047:
12048:
1.78 anton 12049: If an assertion fails, a message compatible with Emacs' compilation mode
12050: is produced and the execution is aborted (currently with @code{ABORT"}.
12051: If there is interest, we will introduce a special throw code. But if you
12052: intend to @code{catch} a specific condition, using @code{throw} is
12053: probably more appropriate than an assertion).
1.106 anton 12054:
12055: @cindex filenames in assertion output
12056: Assertions (and @code{~~}) will usually print the wrong file name if a
12057: marker is executed in the same file after their occurance. They will
12058: print @samp{*somewhere*} as file name if a marker is executed in the
12059: same file before their occurance.
1.44 crook 12060:
1.78 anton 12061: Definitions in ANS Forth for these assertion words are provided
12062: in @file{compat/assert.fs}.
1.26 crook 12063:
1.44 crook 12064:
1.78 anton 12065: @node Singlestep Debugger, , Assertions, Programming Tools
12066: @subsection Singlestep Debugger
12067: @cindex singlestep Debugger
12068: @cindex debugging Singlestep
1.44 crook 12069:
1.189 anton 12070: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 12071:
1.78 anton 12072: When you create a new word there's often the need to check whether it
12073: behaves correctly or not. You can do this by typing @code{dbg
12074: badword}. A debug session might look like this:
1.26 crook 12075:
1.78 anton 12076: @example
12077: : badword 0 DO i . LOOP ; ok
12078: 2 dbg badword
12079: : badword
12080: Scanning code...
1.44 crook 12081:
1.78 anton 12082: Nesting debugger ready!
1.44 crook 12083:
1.78 anton 12084: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
12085: 400D4740 8049F68 DO -> [ 0 ]
12086: 400D4744 804A0C8 i -> [ 1 ] 00000
12087: 400D4748 400C5E60 . -> 0 [ 0 ]
12088: 400D474C 8049D0C LOOP -> [ 0 ]
12089: 400D4744 804A0C8 i -> [ 1 ] 00001
12090: 400D4748 400C5E60 . -> 1 [ 0 ]
12091: 400D474C 8049D0C LOOP -> [ 0 ]
12092: 400D4758 804B384 ; -> ok
12093: @end example
1.21 crook 12094:
1.78 anton 12095: Each line displayed is one step. You always have to hit return to
12096: execute the next word that is displayed. If you don't want to execute
12097: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12098: an overview what keys are available:
1.44 crook 12099:
1.78 anton 12100: @table @i
1.44 crook 12101:
1.78 anton 12102: @item @key{RET}
12103: Next; Execute the next word.
1.21 crook 12104:
1.78 anton 12105: @item n
12106: Nest; Single step through next word.
1.44 crook 12107:
1.78 anton 12108: @item u
12109: Unnest; Stop debugging and execute rest of word. If we got to this word
12110: with nest, continue debugging with the calling word.
1.44 crook 12111:
1.78 anton 12112: @item d
12113: Done; Stop debugging and execute rest.
1.21 crook 12114:
1.78 anton 12115: @item s
12116: Stop; Abort immediately.
1.44 crook 12117:
1.78 anton 12118: @end table
1.44 crook 12119:
1.78 anton 12120: Debugging large application with this mechanism is very difficult, because
12121: you have to nest very deeply into the program before the interesting part
12122: begins. This takes a lot of time.
1.26 crook 12123:
1.78 anton 12124: To do it more directly put a @code{BREAK:} command into your source code.
12125: When program execution reaches @code{BREAK:} the single step debugger is
12126: invoked and you have all the features described above.
1.44 crook 12127:
1.78 anton 12128: If you have more than one part to debug it is useful to know where the
12129: program has stopped at the moment. You can do this by the
12130: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12131: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12132:
1.26 crook 12133:
1.78 anton 12134: doc-dbg
12135: doc-break:
12136: doc-break"
1.44 crook 12137:
1.150 anton 12138: @c ------------------------------------------------------------
12139: @node C Interface, Assembler and Code Words, Programming Tools, Words
12140: @section C Interface
12141: @cindex C interface
12142: @cindex foreign language interface
12143: @cindex interface to C functions
12144:
1.178 anton 12145: Note that the C interface is not yet complete; callbacks are missing,
12146: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12147:
12148: @menu
12149: * Calling C Functions::
12150: * Declaring C Functions::
1.180 anton 12151: * Calling C function pointers::
1.196 anton 12152: * Defining library interfaces::
12153: * Declaring OS-level libraries::
1.150 anton 12154: * Callbacks::
1.178 anton 12155: * C interface internals::
1.155 anton 12156: * Low-Level C Interface Words::
1.150 anton 12157: @end menu
12158:
1.151 pazsan 12159: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12160: @subsection Calling C functions
1.155 anton 12161: @cindex C functions, calls to
12162: @cindex calling C functions
1.150 anton 12163:
1.151 pazsan 12164: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12165: can call it as follows: You push the arguments on the stack(s), and
12166: then call the word for the C function. The arguments have to be
12167: pushed in the same order as the arguments appear in the C
12168: documentation (i.e., the first argument is deepest on the stack).
12169: Integer and pointer arguments have to be pushed on the data stack,
12170: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12171: by the called C function.
1.150 anton 12172:
1.155 anton 12173: On returning from the C function, the return value, if any, resides on
12174: the appropriate stack: an integer return value is pushed on the data
12175: stack, an FP return value on the FP stack, and a void return value
12176: results in not pushing anything. Note that most C functions have a
12177: return value, even if that is often not used in C; in Forth, you have
12178: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12179:
1.177 anton 12180: The C interface automatically converts between the C type and the
12181: Forth type as necessary, on a best-effort basis (in some cases, there
12182: may be some loss).
1.150 anton 12183:
12184: As an example, consider the POSIX function @code{lseek()}:
12185:
12186: @example
12187: off_t lseek(int fd, off_t offset, int whence);
12188: @end example
12189:
12190: This function takes three integer arguments, and returns an integer
12191: argument, so a Forth call for setting the current file offset to the
12192: start of the file could look like this:
12193:
12194: @example
12195: fd @@ 0 SEEK_SET lseek -1 = if
12196: ... \ error handling
12197: then
12198: @end example
12199:
12200: You might be worried that an @code{off_t} does not fit into a cell, so
12201: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12202: of the return values. In that case, in your declaration of the
12203: function (@pxref{Declaring C Functions}) you should declare it to use
12204: double-cells for the off_t argument and return value, and maybe give
12205: the resulting Forth word a different name, like @code{dlseek}; the
12206: result could be called like this:
1.150 anton 12207:
12208: @example
12209: fd @@ 0. SEEK_SET dlseek -1. d= if
12210: ... \ error handling
12211: then
12212: @end example
12213:
12214: Passing and returning structs or unions is currently not supported by
12215: our interface@footnote{If you know the calling convention of your C
12216: compiler, you usually can call such functions in some way, but that
12217: way is usually not portable between platforms, and sometimes not even
12218: between C compilers.}.
12219:
1.177 anton 12220: Calling functions with a variable number of arguments (@emph{variadic}
12221: functions, e.g., @code{printf()}) is only supported by having you
12222: declare one function-calling word for each argument pattern, and
12223: calling the appropriate word for the desired pattern.
12224:
1.150 anton 12225:
1.155 anton 12226:
1.180 anton 12227: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12228: @subsection Declaring C Functions
1.155 anton 12229: @cindex C functions, declarations
12230: @cindex declaring C functions
1.150 anton 12231:
12232: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12233: it. The declaration consists of two parts:
12234:
12235: @table @b
12236:
12237: @item The C part
1.179 anton 12238: is the C declaration of the function, or more typically and portably,
12239: a C-style @code{#include} of a file that contains the declaration of
12240: the C function.
1.177 anton 12241:
12242: @item The Forth part
12243: declares the Forth types of the parameters and the Forth word name
12244: corresponding to the C function.
12245:
12246: @end table
12247:
12248: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12249: declarations are:
12250:
12251: @example
12252: \c #define _FILE_OFFSET_BITS 64
12253: \c #include <sys/types.h>
12254: \c #include <unistd.h>
12255: c-function lseek lseek n n n -- n
12256: c-function dlseek lseek n d n -- d
12257: @end example
12258:
1.178 anton 12259: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12260: of the line is ordinary C code. You can use as many lines of C
12261: declarations as you like, and they are visible for all further
12262: function declarations.
12263:
12264: The Forth part declares each interface word with @code{c-function},
12265: followed by the Forth name of the word, the C name of the called
12266: function, and the stack effect of the word. The stack effect contains
1.178 anton 12267: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12268: exactly one type for the return value. The possible types are:
12269:
12270: @table @code
12271:
12272: @item n
12273: single-cell integer
12274:
12275: @item a
12276: address (single-cell)
12277:
12278: @item d
12279: double-cell integer
12280:
12281: @item r
12282: floating-point value
12283:
12284: @item func
12285: C function pointer
12286:
12287: @item void
12288: no value (used as return type for void functions)
12289:
12290: @end table
12291:
12292: @cindex variadic C functions
12293:
12294: To deal with variadic C functions, you can declare one Forth word for
12295: every pattern you want to use, e.g.:
12296:
12297: @example
12298: \c #include <stdio.h>
12299: c-function printf-nr printf a n r -- n
12300: c-function printf-rn printf a r n -- n
12301: @end example
12302:
12303: Note that with C functions declared as variadic (or if you don't
12304: provide a prototype), the C interface has no C type to convert to, so
12305: no automatic conversion happens, which may lead to portability
12306: problems in some cases. In such cases you can perform the conversion
12307: explicitly on the C level, e.g., as follows:
12308:
12309: @example
1.178 anton 12310: \c #define printfll(s,ll) printf(s,(long long)ll)
12311: c-function printfll printfll a n -- n
1.177 anton 12312: @end example
12313:
12314: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12315: that casts (converts) the Forth single-cell integer into a
12316: C @code{long long} before calling @code{printf()}.
1.177 anton 12317:
12318: doc-\c
12319: doc-c-function
1.207 pazsan 12320: doc-c-value
12321: doc-c-variable
1.177 anton 12322:
12323: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12324: dynamic linking. If these features are not available, there are
12325: other, less convenient and less portable C interfaces in @file{lib.fs}
12326: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12327: mostly incompatible with each other and with the documented C
12328: interface; you can find some examples for the @file{lib.fs} interface
12329: in @file{lib.fs}.
1.177 anton 12330:
12331:
1.196 anton 12332: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180 anton 12333: @subsection Calling C function pointers from Forth
12334: @cindex C function pointers, calling from Forth
1.177 anton 12335:
1.180 anton 12336: If you come across a C function pointer (e.g., in some C-constructed
12337: structure) and want to call it from your Forth program, you can also
12338: use the features explained until now to achieve that, as follows:
1.150 anton 12339:
1.180 anton 12340: Let us assume that there is a C function pointer type @code{func1}
12341: defined in some header file @file{func1.h}, and you know that these
12342: functions take one integer argument and return an integer result; and
12343: you want to call functions through such pointers. Just define
1.155 anton 12344:
1.180 anton 12345: @example
12346: \c #include <func1.h>
12347: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12348: c-function call-func1 call_func1 n func -- n
12349: @end example
12350:
12351: and then you can call a function pointed to by, say @code{func1a} as
12352: follows:
12353:
12354: @example
12355: -5 func1a call-func1 .
12356: @end example
12357:
12358: In the C part, @code{call_func} is defined as a macro to avoid having
12359: to declare the exact parameter and return types, so the C compiler
12360: knows them from the declaration of @code{func1}.
12361:
12362: The Forth word @code{call-func1} is similar to @code{execute}, except
12363: that it takes a C @code{func1} pointer instead of a Forth execution
12364: token, and it is specific to @code{func1} pointers. For each type of
12365: function pointer you want to call from Forth, you have to define
12366: a separate calling word.
12367:
12368:
1.196 anton 12369: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12370: @subsection Defining library interfaces
12371: @cindex giving a name to a library interface
12372: @cindex library interface names
12373:
12374: You can give a name to a bunch of C function declarations (a library
12375: interface), as follows:
12376:
12377: @example
12378: c-library lseek-lib
12379: \c #define _FILE_OFFSET_BITS 64
12380: ...
12381: end-c-library
12382: @end example
12383:
1.202 anton 12384: The effect of giving such a name to the interface is that the names of
12385: the generated files will contain that name, and when you use the
12386: interface a second time, it will use the existing files instead of
12387: generating and compiling them again, saving you time. Note that even
12388: if you change the declarations, the old (stale) files will be used,
12389: probably leading to errors. So, during development of the
12390: declarations we recommend not using @code{c-library}. Normally these
12391: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12392: that directory you can get rid of stale files.
12393:
12394: Note that you should use @code{c-library} before everything else
12395: having anything to do with that library, as it resets some setup
12396: stuff. The idea is that the typical use is to put each
12397: @code{c-library}...@code{end-library} unit in its own file, and to be
12398: able to include these files in any order.
1.196 anton 12399:
12400: Note that the library name is not allocated in the dictionary and
12401: therefore does not shadow dictionary names. It is used in the file
12402: system, so you have to use naming conventions appropriate for file
12403: systems. Also, you must not call a function you declare after
12404: @code{c-library} before you perform @code{end-c-library}.
12405:
12406: A major benefit of these named library interfaces is that, once they
12407: are generated, the tools used to generated them (in particular, the C
12408: compiler and libtool) are no longer needed, so the interface can be
12409: used even on machines that do not have the tools installed.
12410:
12411: doc-c-library-name
12412: doc-c-library
12413: doc-end-c-library
12414:
12415:
12416: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12417: @subsection Declaring OS-level libraries
1.195 anton 12418: @cindex Shared libraries in C interface
12419: @cindex Dynamically linked libraries in C interface
12420: @cindex Libraries in C interface
12421:
1.196 anton 12422: For calling some C functions, you need to link with a specific
12423: OS-level library that contains that function. E.g., the @code{sin}
12424: function requires linking a special library by using the command line
12425: switch @code{-lm}. In our C iterface you do the equivalent thing by
12426: calling @code{add-lib} as follows:
1.195 anton 12427:
12428: @example
12429: clear-libs
12430: s" m" add-lib
12431: \c #include <math.h>
12432: c-function sin sin r -- r
12433: @end example
12434:
12435: First, you clear any libraries that may have been declared earlier
12436: (you don't need them for @code{sin}); then you add the @code{m}
12437: library (actually @code{libm.so} or somesuch) to the currently
12438: declared libraries; you can add as many as you need. Finally you
12439: declare the function as shown above. Typically you will use the same
12440: set of library declarations for many function declarations; you need
12441: to write only one set for that, right at the beginning.
12442:
1.196 anton 12443: Note that you must not call @code{clear-libs} inside
12444: @code{c-library...end-c-library}; however, @code{c-library} performs
12445: the function of @code{clear-libs}, so @code{clear-libs} is not
12446: necessary, and you usually want to put @code{add-lib} calls inside
12447: @code{c-library...end-c-library}.
12448:
1.195 anton 12449: doc-clear-libs
12450: doc-add-lib
12451:
12452:
1.196 anton 12453: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150 anton 12454: @subsection Callbacks
1.155 anton 12455: @cindex Callback functions written in Forth
12456: @cindex C function pointers to Forth words
12457:
1.177 anton 12458: Callbacks are not yet supported by the documented C interface. You
12459: can use the undocumented @file{lib.fs} interface for callbacks.
12460:
1.155 anton 12461: In some cases you have to pass a function pointer to a C function,
12462: i.e., the library wants to call back to your application (and the
12463: pointed-to function is called a callback function). You can pass the
12464: address of an existing C function (that you get with @code{lib-sym},
12465: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12466: function, you probably want to define the function as a Forth word.
12467:
12468: @c I don't understand the existing callback interface from the example - anton
12469:
1.165 anton 12470:
12471: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12472: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12473: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12474: @c > > C-Funktionsadresse auf dem TOS).
12475: @c >
12476: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12477: @c > gesehen habe, wozu das gut ist.
12478: @c
12479: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12480: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12481: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12482: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12483: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12484: @c demselben Prototyp.
12485:
12486:
1.178 anton 12487: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12488: @subsection How the C interface works
12489:
12490: The documented C interface works by generating a C code out of the
12491: declarations.
12492:
12493: In particular, for every Forth word declared with @code{c-function},
12494: it generates a wrapper function in C that takes the Forth data from
12495: the Forth stacks, and calls the target C function with these data as
12496: arguments. The C compiler then performs an implicit conversion
12497: between the Forth type from the stack, and the C type for the
12498: parameter, which is given by the C function prototype. After the C
12499: function returns, the return value is likewise implicitly converted to
12500: a Forth type and written back on the stack.
12501:
12502: The @code{\c} lines are literally included in the C code (but without
12503: the @code{\c}), and provide the necessary declarations so that the C
12504: compiler knows the C types and has enough information to perform the
12505: conversion.
12506:
12507: These wrapper functions are eventually compiled and dynamically linked
12508: into Gforth, and then they can be called.
12509:
1.195 anton 12510: The libraries added with @code{add-lib} are used in the compile
12511: command line to specify dependent libraries with @code{-l@var{lib}},
12512: causing these libraries to be dynamically linked when the wrapper
12513: function is linked.
12514:
1.177 anton 12515:
1.178 anton 12516: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12517: @subsection Low-Level C Interface Words
1.44 crook 12518:
1.155 anton 12519: doc-open-lib
12520: doc-lib-sym
1.196 anton 12521: doc-lib-error
1.177 anton 12522: doc-call-c
1.26 crook 12523:
1.78 anton 12524: @c -------------------------------------------------------------
1.150 anton 12525: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12526: @section Assembler and Code Words
12527: @cindex assembler
12528: @cindex code words
1.44 crook 12529:
1.78 anton 12530: @menu
12531: * Code and ;code::
12532: * Common Assembler:: Assembler Syntax
12533: * Common Disassembler::
12534: * 386 Assembler:: Deviations and special cases
12535: * Alpha Assembler:: Deviations and special cases
12536: * MIPS assembler:: Deviations and special cases
1.161 anton 12537: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12538: * ARM Assembler:: Deviations and special cases
1.78 anton 12539: * Other assemblers:: How to write them
12540: @end menu
1.21 crook 12541:
1.78 anton 12542: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12543: @subsection @code{Code} and @code{;code}
1.26 crook 12544:
1.78 anton 12545: Gforth provides some words for defining primitives (words written in
12546: machine code), and for defining the machine-code equivalent of
12547: @code{DOES>}-based defining words. However, the machine-independent
12548: nature of Gforth poses a few problems: First of all, Gforth runs on
12549: several architectures, so it can provide no standard assembler. What's
12550: worse is that the register allocation not only depends on the processor,
12551: but also on the @code{gcc} version and options used.
1.44 crook 12552:
1.78 anton 12553: The words that Gforth offers encapsulate some system dependences (e.g.,
12554: the header structure), so a system-independent assembler may be used in
12555: Gforth. If you do not have an assembler, you can compile machine code
12556: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12557: because these words emit stuff in @i{data} space; it works because
12558: Gforth has unified code/data spaces. Assembler isn't likely to be
12559: portable anyway.}.
1.21 crook 12560:
1.44 crook 12561:
1.78 anton 12562: doc-assembler
12563: doc-init-asm
12564: doc-code
12565: doc-end-code
12566: doc-;code
12567: doc-flush-icache
1.44 crook 12568:
1.21 crook 12569:
1.78 anton 12570: If @code{flush-icache} does not work correctly, @code{code} words
12571: etc. will not work (reliably), either.
1.44 crook 12572:
1.78 anton 12573: The typical usage of these @code{code} words can be shown most easily by
12574: analogy to the equivalent high-level defining words:
1.44 crook 12575:
1.78 anton 12576: @example
12577: : foo code foo
12578: <high-level Forth words> <assembler>
12579: ; end-code
12580:
12581: : bar : bar
12582: <high-level Forth words> <high-level Forth words>
12583: CREATE CREATE
12584: <high-level Forth words> <high-level Forth words>
12585: DOES> ;code
12586: <high-level Forth words> <assembler>
12587: ; end-code
12588: @end example
1.21 crook 12589:
1.78 anton 12590: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12591:
1.78 anton 12592: @cindex registers of the inner interpreter
12593: In the assembly code you will want to refer to the inner interpreter's
12594: registers (e.g., the data stack pointer) and you may want to use other
12595: registers for temporary storage. Unfortunately, the register allocation
12596: is installation-dependent.
1.44 crook 12597:
1.78 anton 12598: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12599: (return stack pointer) may be in different places in @code{gforth} and
12600: @code{gforth-fast}, or different installations. This means that you
12601: cannot write a @code{NEXT} routine that works reliably on both versions
12602: or different installations; so for doing @code{NEXT}, I recommend
12603: jumping to @code{' noop >code-address}, which contains nothing but a
12604: @code{NEXT}.
1.21 crook 12605:
1.78 anton 12606: For general accesses to the inner interpreter's registers, the easiest
12607: solution is to use explicit register declarations (@pxref{Explicit Reg
12608: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12609: all of the inner interpreter's registers: You have to compile Gforth
12610: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12611: the appropriate declarations must be present in the @code{machine.h}
12612: file (see @code{mips.h} for an example; you can find a full list of all
12613: declarable register symbols with @code{grep register engine.c}). If you
12614: give explicit registers to all variables that are declared at the
12615: beginning of @code{engine()}, you should be able to use the other
12616: caller-saved registers for temporary storage. Alternatively, you can use
12617: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12618: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12619: reserve a register (however, this restriction on register allocation may
12620: slow Gforth significantly).
1.44 crook 12621:
1.78 anton 12622: If this solution is not viable (e.g., because @code{gcc} does not allow
12623: you to explicitly declare all the registers you need), you have to find
12624: out by looking at the code where the inner interpreter's registers
12625: reside and which registers can be used for temporary storage. You can
12626: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12627:
1.78 anton 12628: In any case, it is good practice to abstract your assembly code from the
12629: actual register allocation. E.g., if the data stack pointer resides in
12630: register @code{$17}, create an alias for this register called @code{sp},
12631: and use that in your assembly code.
1.21 crook 12632:
1.78 anton 12633: @cindex code words, portable
12634: Another option for implementing normal and defining words efficiently
12635: is to add the desired functionality to the source of Gforth. For normal
12636: words you just have to edit @file{primitives} (@pxref{Automatic
12637: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12638: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12639: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12640:
1.78 anton 12641: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12642: @subsection Common Assembler
1.44 crook 12643:
1.78 anton 12644: The assemblers in Gforth generally use a postfix syntax, i.e., the
12645: instruction name follows the operands.
1.21 crook 12646:
1.78 anton 12647: The operands are passed in the usual order (the same that is used in the
12648: manual of the architecture). Since they all are Forth words, they have
12649: to be separated by spaces; you can also use Forth words to compute the
12650: operands.
1.44 crook 12651:
1.78 anton 12652: The instruction names usually end with a @code{,}. This makes it easier
12653: to visually separate instructions if you put several of them on one
12654: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12655:
1.78 anton 12656: Registers are usually specified by number; e.g., (decimal) @code{11}
12657: specifies registers R11 and F11 on the Alpha architecture (which one,
12658: depends on the instruction). The usual names are also available, e.g.,
12659: @code{s2} for R11 on Alpha.
1.21 crook 12660:
1.78 anton 12661: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12662: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12663: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12664: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12665: conditions are specified in a way specific to each assembler.
1.1 anton 12666:
1.78 anton 12667: Note that the register assignments of the Gforth engine can change
12668: between Gforth versions, or even between different compilations of the
12669: same Gforth version (e.g., if you use a different GCC version). So if
12670: you want to refer to Gforth's registers (e.g., the stack pointer or
12671: TOS), I recommend defining your own words for refering to these
12672: registers, and using them later on; then you can easily adapt to a
12673: changed register assignment. The stability of the register assignment
12674: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12675:
1.100 anton 12676: The most common use of these registers is to dispatch to the next word
12677: (the @code{next} routine). A portable way to do this is to jump to
12678: @code{' noop >code-address} (of course, this is less efficient than
12679: integrating the @code{next} code and scheduling it well).
1.1 anton 12680:
1.96 anton 12681: Another difference between Gforth version is that the top of stack is
12682: kept in memory in @code{gforth} and, on most platforms, in a register in
12683: @code{gforth-fast}.
12684:
1.78 anton 12685: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12686: @subsection Common Disassembler
1.127 anton 12687: @cindex disassembler, general
12688: @cindex gdb disassembler
1.1 anton 12689:
1.78 anton 12690: You can disassemble a @code{code} word with @code{see}
12691: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12692:
1.127 anton 12693: doc-discode
1.44 crook 12694:
1.127 anton 12695: There are two kinds of disassembler for Gforth: The Forth disassembler
12696: (available on some CPUs) and the gdb disassembler (available on
12697: platforms with @command{gdb} and @command{mktemp}). If both are
12698: available, the Forth disassembler is used by default. If you prefer
12699: the gdb disassembler, say
12700:
12701: @example
12702: ' disasm-gdb is discode
12703: @end example
12704:
12705: If neither is available, @code{discode} performs @code{dump}.
12706:
12707: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12708: assembler (i.e., same syntax, etc.). It also includes additional
12709: information in comments. In particular, the address of the instruction
12710: is given in a comment before the instruction.
1.1 anton 12711:
1.127 anton 12712: The gdb disassembler produces output in the same format as the gdb
12713: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12714: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12715: the 386 and AMD64 architectures).
12716:
1.78 anton 12717: @code{See} may display more or less than the actual code of the word,
12718: because the recognition of the end of the code is unreliable. You can
1.127 anton 12719: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12720: the code word is not immediately followed by a named word. If you have
1.116 anton 12721: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12722: to ensure that the end is recognized.
1.21 crook 12723:
1.78 anton 12724: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12725: @subsection 386 Assembler
1.44 crook 12726:
1.78 anton 12727: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12728: available under GPL, and originally part of bigFORTH.
1.21 crook 12729:
1.78 anton 12730: The 386 disassembler included in Gforth was written by Andrew McKewan
12731: and is in the public domain.
1.21 crook 12732:
1.91 anton 12733: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12734:
1.78 anton 12735: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12736:
1.78 anton 12737: The assembler includes all instruction of the Athlon, i.e. 486 core
12738: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12739: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12740: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12741:
1.78 anton 12742: There are several prefixes to switch between different operation sizes,
12743: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12744: double-word accesses. Addressing modes can be switched with @code{.wa}
12745: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12746: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12747:
1.78 anton 12748: For floating point operations, the prefixes are @code{.fs} (IEEE
12749: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12750: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12751:
1.78 anton 12752: The MMX opcodes don't have size prefixes, they are spelled out like in
12753: the Intel assembler. Instead of move from and to memory, there are
12754: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12755:
1.78 anton 12756: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12757: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12758: e.g., @code{3 #}. Here are some examples of addressing modes in various
12759: syntaxes:
1.21 crook 12760:
1.26 crook 12761: @example
1.91 anton 12762: Gforth Intel (NASM) AT&T (gas) Name
12763: .w ax ax %ax register (16 bit)
12764: ax eax %eax register (32 bit)
12765: 3 # offset 3 $3 immediate
12766: 1000 #) byte ptr 1000 1000 displacement
12767: bx ) [ebx] (%ebx) base
12768: 100 di d) 100[edi] 100(%edi) base+displacement
12769: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12770: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12771: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12772: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12773: @end example
12774:
12775: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12776: @code{DI)} to enforce 32-bit displacement fields (useful for
12777: later patching).
1.21 crook 12778:
1.78 anton 12779: Some example of instructions are:
1.1 anton 12780:
12781: @example
1.78 anton 12782: ax bx mov \ move ebx,eax
12783: 3 # ax mov \ mov eax,3
1.137 pazsan 12784: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12785: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12786: .w ax bx mov \ mov bx,ax
1.1 anton 12787: @end example
12788:
1.78 anton 12789: The following forms are supported for binary instructions:
1.1 anton 12790:
12791: @example
1.78 anton 12792: <reg> <reg> <inst>
12793: <n> # <reg> <inst>
12794: <mem> <reg> <inst>
12795: <reg> <mem> <inst>
1.136 pazsan 12796: <n> # <mem> <inst>
1.1 anton 12797: @end example
12798:
1.136 pazsan 12799: The shift/rotate syntax is:
1.1 anton 12800:
1.26 crook 12801: @example
1.78 anton 12802: <reg/mem> 1 # shl \ shortens to shift without immediate
12803: <reg/mem> 4 # shl
12804: <reg/mem> cl shl
1.26 crook 12805: @end example
1.1 anton 12806:
1.78 anton 12807: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12808: the byte version.
1.1 anton 12809:
1.78 anton 12810: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12811: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12812: pc < >= <= >}. (Note that most of these words shadow some Forth words
12813: when @code{assembler} is in front of @code{forth} in the search path,
12814: e.g., in @code{code} words). Currently the control structure words use
12815: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12816: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12817:
1.78 anton 12818: Here is an example of a @code{code} word (assumes that the stack pointer
12819: is in esi and the TOS is in ebx):
1.21 crook 12820:
1.26 crook 12821: @example
1.78 anton 12822: code my+ ( n1 n2 -- n )
12823: 4 si D) bx add
12824: 4 # si add
12825: Next
12826: end-code
1.26 crook 12827: @end example
1.21 crook 12828:
1.161 anton 12829:
1.78 anton 12830: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12831: @subsection Alpha Assembler
1.21 crook 12832:
1.78 anton 12833: The Alpha assembler and disassembler were originally written by Bernd
12834: Thallner.
1.26 crook 12835:
1.78 anton 12836: The register names @code{a0}--@code{a5} are not available to avoid
12837: shadowing hex numbers.
1.2 jwilke 12838:
1.78 anton 12839: Immediate forms of arithmetic instructions are distinguished by a
12840: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12841: does not count as arithmetic instruction).
1.2 jwilke 12842:
1.78 anton 12843: You have to specify all operands to an instruction, even those that
12844: other assemblers consider optional, e.g., the destination register for
12845: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12846:
1.78 anton 12847: You can specify conditions for @code{if,} by removing the first @code{b}
12848: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12849:
1.26 crook 12850: @example
1.78 anton 12851: 11 fgt if, \ if F11>0e
12852: ...
12853: endif,
1.26 crook 12854: @end example
1.2 jwilke 12855:
1.78 anton 12856: @code{fbgt,} gives @code{fgt}.
12857:
1.161 anton 12858: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12859: @subsection MIPS assembler
1.2 jwilke 12860:
1.78 anton 12861: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12862:
1.78 anton 12863: Currently the assembler and disassembler only cover the MIPS-I
12864: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12865:
1.78 anton 12866: The register names @code{$a0}--@code{$a3} are not available to avoid
12867: shadowing hex numbers.
1.2 jwilke 12868:
1.78 anton 12869: Because there is no way to distinguish registers from immediate values,
12870: you have to explicitly use the immediate forms of instructions, i.e.,
12871: @code{addiu,}, not just @code{addu,} (@command{as} does this
12872: implicitly).
1.2 jwilke 12873:
1.78 anton 12874: If the architecture manual specifies several formats for the instruction
12875: (e.g., for @code{jalr,}), you usually have to use the one with more
12876: arguments (i.e., two for @code{jalr,}). When in doubt, see
12877: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12878:
1.78 anton 12879: Branches and jumps in the MIPS architecture have a delay slot. You have
12880: to fill it yourself (the simplest way is to use @code{nop,}), the
12881: assembler does not do it for you (unlike @command{as}). Even
12882: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12883: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12884: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12885:
1.78 anton 12886: Note that you must not put branches, jumps, or @code{li,} into the delay
12887: slot: @code{li,} may expand to several instructions, and control flow
12888: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12889:
1.78 anton 12890: For branches the argument specifying the target is a relative address;
12891: You have to add the address of the delay slot to get the absolute
12892: address.
1.1 anton 12893:
1.78 anton 12894: The MIPS architecture also has load delay slots and restrictions on
12895: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12896: yourself to satisfy these restrictions, the assembler does not do it for
12897: you.
1.1 anton 12898:
1.78 anton 12899: You can specify the conditions for @code{if,} etc. by taking a
12900: conditional branch and leaving away the @code{b} at the start and the
12901: @code{,} at the end. E.g.,
1.1 anton 12902:
1.26 crook 12903: @example
1.78 anton 12904: 4 5 eq if,
12905: ... \ do something if $4 equals $5
12906: then,
1.26 crook 12907: @end example
1.1 anton 12908:
1.161 anton 12909:
1.193 dvdkhlng 12910: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12911: @subsection PowerPC assembler
12912:
1.162 anton 12913: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12914: Revucky.
12915:
1.162 anton 12916: This assembler does not follow the convention of ending mnemonic names
12917: with a ``,'', so some mnemonic names shadow regular Forth words (in
12918: particular: @code{and or xor fabs}); so if you want to use the Forth
12919: words, you have to make them visible first, e.g., with @code{also
12920: forth}.
12921:
1.161 anton 12922: Registers are referred to by their number, e.g., @code{9} means the
12923: integer register 9 or the FP register 9 (depending on the
12924: instruction).
12925:
12926: Because there is no way to distinguish registers from immediate values,
12927: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12928: @code{addi,}, not just @code{add,}.
1.161 anton 12929:
1.162 anton 12930: The assembler and disassembler usually support the most general form
1.161 anton 12931: of an instruction, but usually not the shorter forms (especially for
12932: branches).
12933:
12934:
1.193 dvdkhlng 12935: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12936: @subsection ARM Assembler
1.161 anton 12937:
1.193 dvdkhlng 12938: The ARM assembler included in Gforth was written from scratch by David
12939: Kuehling.
12940:
12941: The assembler includes all instruction of ARM architecture version 4,
12942: but does not (yet) have support for Thumb instructions. It also lacks
12943: support for any co-processors.
12944:
12945: The assembler uses a postfix syntax with the target operand specified
12946: last. For load/store instructions the last operand will be the
12947: register(s) to be loaded from/stored to.
12948:
12949: Registers are specified by their names @code{r0} through @code{r15},
12950: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12951: @code{fp} provided for convenience. Note that @code{ip} means intra
12952: procedure call scratch register (@code{r12}) and does not refer to the
12953: instruction pointer.
12954:
12955: Condition codes can be specified anywhere in the instruction, but will
12956: be most readable if specified just in front of the mnemonic. The 'S'
12957: flag is not a separate word, but encoded into instruction mnemonics,
12958: ie. just use @code{adds,} instead of @code{add,} if you want the
12959: status register to be updated.
12960:
12961: The following table lists the syntax of operands for general
12962: instructions:
12963:
12964: @example
12965: Gforth normal assembler description
12966: 123 # #123 immediate
12967: r12 r12 register
12968: r12 4 #LSL r12, LSL #4 shift left by immediate
12969: r12 r1 #LSL r12, LSL r1 shift left by register
12970: r12 4 #LSR r12, LSR #4 shift right by immediate
12971: r12 r1 #LSR r12, LSR r1 shift right by register
12972: r12 4 #ASR r12, ASR #4 arithmetic shift right
12973: r12 r1 #ASR r12, ASR r1 ... by register
12974: r12 4 #ROR r12, ROR #4 rotate right by immediate
12975: r12 r1 #ROR r12, ROR r1 ... by register
12976: r12 RRX r12, RRX rotate right with extend by 1
12977: @end example
12978:
12979: Memory operand syntax is listed in this table:
12980:
12981: @example
12982: Gforth normal assembler description
12983: r4 ] [r4] register
12984: r4 4 #] [r4, #+4] register with immediate offset
12985: r4 -4 #] [r4, #-4] with negative offset
12986: r4 r1 +] [r4, +r1] register with register offset
12987: r4 r1 -] [r4, -r1] with negated register offset
12988: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
12989: r4 4 #]! [r4, #+4]! immediate preincrement
12990: r4 r1 +]! [r4, +r1]! register preincrement
12991: r4 r1 -]! [r4, +r1]! register predecrement
12992: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
12993: r4 -4 ]# [r4], #-4 immediate postdecrement
12994: r4 r1 ]+ [r4], r1 register postincrement
12995: r4 r1 ]- [r4], -r1 register postdecrement
12996: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
12997: ' xyz >body [#] xyz PC-relative addressing
12998: @end example
12999:
13000: Register lists for load/store multiple instructions are started and
13001: terminated by using the words @code{@{} and @code{@}}
13002: respectivly. Between braces, register names can be listed one by one,
13003: or register ranges can be formed by using the postfix operator
13004: @code{r-r}. The @code{^} flag is not encoded in the register list
13005: operand, but instead directly encoded into the instruction mnemonic,
13006: ie. use @code{^ldm,} and @code{^stm,}.
13007:
13008: Addressing modes for load/store multiple are not encoded as
13009: instruction suffixes, but instead specified after the register that
13010: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
13011: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
13012:
13013: The following table gives some examples:
13014:
13015: @example
13016: Gforth normal assembler
13017: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
13018: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
13019: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
13020: @end example
13021:
13022: Conditions for control structure words are specified in front of a
13023: word:
13024:
13025: @example
13026: r1 r2 cmp, \ compare r1 and r2
13027: eq if, \ equal?
13028: ... \ code executed if r1 == r2
13029: then,
13030: @end example
13031:
13032: Here is an example of a @code{code} word (assumes that the stack
13033: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
13034: clobbered):
13035:
13036: @example
13037: code my+ ( n1 n2 -- n3 )
13038: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
13039: r2 r3 r3 add, \ r3 = n2+n1
13040: r9 -4 #]! r3 str, \ push r3
13041: next,
13042: end-code
13043: @end example
13044:
13045: Look at @file{arch/arm/asm-example.fs} for more examples.
13046:
13047: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 13048: @subsection Other assemblers
13049:
13050: If you want to contribute another assembler/disassembler, please contact
1.103 anton 13051: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13052: an assembler already. If you are writing them from scratch, please use
13053: a similar syntax style as the one we use (i.e., postfix, commas at the
13054: end of the instruction names, @pxref{Common Assembler}); make the output
13055: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 13056: similar to the style we used.
13057:
13058: Hints on implementation: The most important part is to have a good test
13059: suite that contains all instructions. Once you have that, the rest is
13060: easy. For actual coding you can take a look at
13061: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13062: the assembler and disassembler, avoiding redundancy and some potential
13063: bugs. You can also look at that file (and @pxref{Advanced does> usage
13064: example}) to get ideas how to factor a disassembler.
13065:
13066: Start with the disassembler, because it's easier to reuse data from the
13067: disassembler for the assembler than the other way round.
1.1 anton 13068:
1.78 anton 13069: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13070: how simple it can be.
1.1 anton 13071:
1.161 anton 13072:
13073:
13074:
1.78 anton 13075: @c -------------------------------------------------------------
13076: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13077: @section Threading Words
13078: @cindex threading words
1.1 anton 13079:
1.78 anton 13080: @cindex code address
13081: These words provide access to code addresses and other threading stuff
13082: in Gforth (and, possibly, other interpretive Forths). It more or less
13083: abstracts away the differences between direct and indirect threading
13084: (and, for direct threading, the machine dependences). However, at
13085: present this wordset is still incomplete. It is also pretty low-level;
13086: some day it will hopefully be made unnecessary by an internals wordset
13087: that abstracts implementation details away completely.
1.1 anton 13088:
1.78 anton 13089: The terminology used here stems from indirect threaded Forth systems; in
13090: such a system, the XT of a word is represented by the CFA (code field
13091: address) of a word; the CFA points to a cell that contains the code
13092: address. The code address is the address of some machine code that
13093: performs the run-time action of invoking the word (e.g., the
13094: @code{dovar:} routine pushes the address of the body of the word (a
13095: variable) on the stack
13096: ).
1.1 anton 13097:
1.78 anton 13098: @cindex code address
13099: @cindex code field address
13100: In an indirect threaded Forth, you can get the code address of @i{name}
13101: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13102: >code-address}, independent of the threading method.
1.1 anton 13103:
1.78 anton 13104: doc-threading-method
13105: doc->code-address
13106: doc-code-address!
1.1 anton 13107:
1.78 anton 13108: @cindex @code{does>}-handler
13109: @cindex @code{does>}-code
13110: For a word defined with @code{DOES>}, the code address usually points to
13111: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13112: routine (in Gforth on some platforms, it can also point to the dodoes
13113: routine itself). What you are typically interested in, though, is
13114: whether a word is a @code{DOES>}-defined word, and what Forth code it
13115: executes; @code{>does-code} tells you that.
1.1 anton 13116:
1.78 anton 13117: doc->does-code
1.1 anton 13118:
1.78 anton 13119: To create a @code{DOES>}-defined word with the following basic words,
13120: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13121: @code{/does-handler} aus behind you have to place your executable Forth
13122: code. Finally you have to create a word and modify its behaviour with
13123: @code{does-handler!}.
1.1 anton 13124:
1.78 anton 13125: doc-does-code!
13126: doc-does-handler!
13127: doc-/does-handler
1.1 anton 13128:
1.78 anton 13129: The code addresses produced by various defining words are produced by
13130: the following words:
1.1 anton 13131:
1.78 anton 13132: doc-docol:
13133: doc-docon:
13134: doc-dovar:
13135: doc-douser:
13136: doc-dodefer:
13137: doc-dofield:
1.1 anton 13138:
1.99 anton 13139: @cindex definer
13140: The following two words generalize @code{>code-address},
13141: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13142:
13143: doc->definer
13144: doc-definer!
13145:
1.26 crook 13146: @c -------------------------------------------------------------
1.78 anton 13147: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 13148: @section Passing Commands to the Operating System
13149: @cindex operating system - passing commands
13150: @cindex shell commands
13151:
13152: Gforth allows you to pass an arbitrary string to the host operating
13153: system shell (if such a thing exists) for execution.
13154:
13155: doc-sh
13156: doc-system
13157: doc-$?
1.23 crook 13158: doc-getenv
1.44 crook 13159:
1.26 crook 13160: @c -------------------------------------------------------------
1.47 crook 13161: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13162: @section Keeping track of Time
13163: @cindex time-related words
13164:
13165: doc-ms
13166: doc-time&date
1.79 anton 13167: doc-utime
13168: doc-cputime
1.47 crook 13169:
13170:
13171: @c -------------------------------------------------------------
13172: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 13173: @section Miscellaneous Words
13174: @cindex miscellaneous words
13175:
1.29 crook 13176: @comment TODO find homes for these
13177:
1.26 crook 13178: These section lists the ANS Forth words that are not documented
1.21 crook 13179: elsewhere in this manual. Ultimately, they all need proper homes.
13180:
1.68 anton 13181: doc-quit
1.44 crook 13182:
1.26 crook 13183: The following ANS Forth words are not currently supported by Gforth
1.27 crook 13184: (@pxref{ANS conformance}):
1.21 crook 13185:
13186: @code{EDITOR}
13187: @code{EMIT?}
13188: @code{FORGET}
13189:
1.24 anton 13190: @c ******************************************************************
13191: @node Error messages, Tools, Words, Top
13192: @chapter Error messages
13193: @cindex error messages
13194: @cindex backtrace
13195:
13196: A typical Gforth error message looks like this:
13197:
13198: @example
1.86 anton 13199: in file included from \evaluated string/:-1
1.24 anton 13200: in file included from ./yyy.fs:1
13201: ./xxx.fs:4: Invalid memory address
1.134 anton 13202: >>>bar<<<
1.79 anton 13203: Backtrace:
1.25 anton 13204: $400E664C @@
13205: $400E6664 foo
1.24 anton 13206: @end example
13207:
13208: The message identifying the error is @code{Invalid memory address}. The
13209: error happened when text-interpreting line 4 of the file
13210: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13211: word on the line where the error happened, is pointed out (with
1.134 anton 13212: @code{>>>} and @code{<<<}).
1.24 anton 13213:
13214: The file containing the error was included in line 1 of @file{./yyy.fs},
13215: and @file{yyy.fs} was included from a non-file (in this case, by giving
13216: @file{yyy.fs} as command-line parameter to Gforth).
13217:
13218: At the end of the error message you find a return stack dump that can be
13219: interpreted as a backtrace (possibly empty). On top you find the top of
13220: the return stack when the @code{throw} happened, and at the bottom you
13221: find the return stack entry just above the return stack of the topmost
13222: text interpreter.
13223:
13224: To the right of most return stack entries you see a guess for the word
13225: that pushed that return stack entry as its return address. This gives a
13226: backtrace. In our case we see that @code{bar} called @code{foo}, and
13227: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13228: address} exception).
13229:
13230: Note that the backtrace is not perfect: We don't know which return stack
13231: entries are return addresses (so we may get false positives); and in
13232: some cases (e.g., for @code{abort"}) we cannot determine from the return
13233: address the word that pushed the return address, so for some return
13234: addresses you see no names in the return stack dump.
1.25 anton 13235:
13236: @cindex @code{catch} and backtraces
13237: The return stack dump represents the return stack at the time when a
13238: specific @code{throw} was executed. In programs that make use of
13239: @code{catch}, it is not necessarily clear which @code{throw} should be
13240: used for the return stack dump (e.g., consider one @code{throw} that
13241: indicates an error, which is caught, and during recovery another error
1.160 anton 13242: happens; which @code{throw} should be used for the stack dump?).
13243: Gforth presents the return stack dump for the first @code{throw} after
13244: the last executed (not returned-to) @code{catch} or @code{nothrow};
13245: this works well in the usual case. To get the right backtrace, you
13246: usually want to insert @code{nothrow} or @code{['] false catch drop}
13247: after a @code{catch} if the error is not rethrown.
1.25 anton 13248:
13249: @cindex @code{gforth-fast} and backtraces
13250: @cindex @code{gforth-fast}, difference from @code{gforth}
13251: @cindex backtraces with @code{gforth-fast}
13252: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13253: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13254: from primitives (e.g., invalid memory address, stack empty etc.);
13255: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13256: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13257: exception caused by a primitive in @code{gforth-fast}, you will
13258: typically see no return stack dump at all; however, if the exception is
13259: caught by @code{catch} (e.g., for restoring some state), and then
13260: @code{throw}n again, the return stack dump will be for the first such
13261: @code{throw}.
1.2 jwilke 13262:
1.5 anton 13263: @c ******************************************************************
1.24 anton 13264: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13265: @chapter Tools
13266:
13267: @menu
13268: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13269: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13270: @end menu
13271:
13272: See also @ref{Emacs and Gforth}.
13273:
1.126 pazsan 13274: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13275: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13276: @cindex @file{ans-report.fs}
13277: @cindex report the words used in your program
13278: @cindex words used in your program
13279:
13280: If you want to label a Forth program as ANS Forth Program, you must
13281: document which wordsets the program uses; for extension wordsets, it is
13282: helpful to list the words the program requires from these wordsets
13283: (because Forth systems are allowed to provide only some words of them).
13284:
13285: The @file{ans-report.fs} tool makes it easy for you to determine which
13286: words from which wordset and which non-ANS words your application
13287: uses. You simply have to include @file{ans-report.fs} before loading the
13288: program you want to check. After loading your program, you can get the
13289: report with @code{print-ans-report}. A typical use is to run this as
13290: batch job like this:
13291: @example
13292: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13293: @end example
13294:
13295: The output looks like this (for @file{compat/control.fs}):
13296: @example
13297: The program uses the following words
13298: from CORE :
13299: : POSTPONE THEN ; immediate ?dup IF 0=
13300: from BLOCK-EXT :
13301: \
13302: from FILE :
13303: (
13304: @end example
13305:
13306: @subsection Caveats
13307:
13308: Note that @file{ans-report.fs} just checks which words are used, not whether
13309: they are used in an ANS Forth conforming way!
13310:
13311: Some words are defined in several wordsets in the
13312: standard. @file{ans-report.fs} reports them for only one of the
13313: wordsets, and not necessarily the one you expect. It depends on usage
13314: which wordset is the right one to specify. E.g., if you only use the
13315: compilation semantics of @code{S"}, it is a Core word; if you also use
13316: its interpretation semantics, it is a File word.
1.124 anton 13317:
13318:
1.127 anton 13319: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13320: @section Stack depth changes during interpretation
13321: @cindex @file{depth-changes.fs}
13322: @cindex depth changes during interpretation
13323: @cindex stack depth changes during interpretation
13324: @cindex items on the stack after interpretation
13325:
13326: Sometimes you notice that, after loading a file, there are items left
13327: on the stack. The tool @file{depth-changes.fs} helps you find out
13328: quickly where in the file these stack items are coming from.
13329:
13330: The simplest way of using @file{depth-changes.fs} is to include it
13331: before the file(s) you want to check, e.g.:
13332:
13333: @example
13334: gforth depth-changes.fs my-file.fs
13335: @end example
13336:
13337: This will compare the stack depths of the data and FP stack at every
13338: empty line (in interpretation state) against these depths at the last
13339: empty line (in interpretation state). If the depths are not equal,
13340: the position in the file and the stack contents are printed with
13341: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13342: change has occured in the paragraph of non-empty lines before the
13343: indicated line. It is a good idea to leave an empty line at the end
13344: of the file, so the last paragraph is checked, too.
13345:
13346: Checking only at empty lines usually works well, but sometimes you
13347: have big blocks of non-empty lines (e.g., when building a big table),
13348: and you want to know where in this block the stack depth changed. You
13349: can check all interpreted lines with
13350:
13351: @example
13352: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13353: @end example
13354:
13355: This checks the stack depth at every end-of-line. So the depth change
13356: occured in the line reported by the @code{~~} (not in the line
13357: before).
13358:
13359: Note that, while this offers better accuracy in indicating where the
13360: stack depth changes, it will often report many intentional stack depth
13361: changes (e.g., when an interpreted computation stretches across
13362: several lines). You can suppress the checking of some lines by
13363: putting backslashes at the end of these lines (not followed by white
13364: space), and using
13365:
13366: @example
13367: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13368: @end example
1.1 anton 13369:
13370: @c ******************************************************************
1.65 anton 13371: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13372: @chapter ANS conformance
13373: @cindex ANS conformance of Gforth
13374:
13375: To the best of our knowledge, Gforth is an
13376:
13377: ANS Forth System
13378: @itemize @bullet
13379: @item providing the Core Extensions word set
13380: @item providing the Block word set
13381: @item providing the Block Extensions word set
13382: @item providing the Double-Number word set
13383: @item providing the Double-Number Extensions word set
13384: @item providing the Exception word set
13385: @item providing the Exception Extensions word set
13386: @item providing the Facility word set
1.40 anton 13387: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13388: @item providing the File Access word set
13389: @item providing the File Access Extensions word set
13390: @item providing the Floating-Point word set
13391: @item providing the Floating-Point Extensions word set
13392: @item providing the Locals word set
13393: @item providing the Locals Extensions word set
13394: @item providing the Memory-Allocation word set
13395: @item providing the Memory-Allocation Extensions word set (that one's easy)
13396: @item providing the Programming-Tools word set
13397: @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
13398: @item providing the Search-Order word set
13399: @item providing the Search-Order Extensions word set
13400: @item providing the String word set
13401: @item providing the String Extensions word set (another easy one)
13402: @end itemize
13403:
1.118 anton 13404: Gforth has the following environmental restrictions:
13405:
13406: @cindex environmental restrictions
13407: @itemize @bullet
13408: @item
13409: While processing the OS command line, if an exception is not caught,
13410: Gforth exits with a non-zero exit code instyead of performing QUIT.
13411:
13412: @item
13413: When an @code{throw} is performed after a @code{query}, Gforth does not
13414: allways restore the input source specification in effect at the
13415: corresponding catch.
13416:
13417: @end itemize
13418:
13419:
1.1 anton 13420: @cindex system documentation
13421: In addition, ANS Forth systems are required to document certain
13422: implementation choices. This chapter tries to meet these
13423: requirements. In many cases it gives a way to ask the system for the
13424: information instead of providing the information directly, in
13425: particular, if the information depends on the processor, the operating
13426: system or the installation options chosen, or if they are likely to
13427: change during the maintenance of Gforth.
13428:
13429: @comment The framework for the rest has been taken from pfe.
13430:
13431: @menu
13432: * The Core Words::
13433: * The optional Block word set::
13434: * The optional Double Number word set::
13435: * The optional Exception word set::
13436: * The optional Facility word set::
13437: * The optional File-Access word set::
13438: * The optional Floating-Point word set::
13439: * The optional Locals word set::
13440: * The optional Memory-Allocation word set::
13441: * The optional Programming-Tools word set::
13442: * The optional Search-Order word set::
13443: @end menu
13444:
13445:
13446: @c =====================================================================
13447: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13448: @comment node-name, next, previous, up
13449: @section The Core Words
13450: @c =====================================================================
13451: @cindex core words, system documentation
13452: @cindex system documentation, core words
13453:
13454: @menu
13455: * core-idef:: Implementation Defined Options
13456: * core-ambcond:: Ambiguous Conditions
13457: * core-other:: Other System Documentation
13458: @end menu
13459:
13460: @c ---------------------------------------------------------------------
13461: @node core-idef, core-ambcond, The Core Words, The Core Words
13462: @subsection Implementation Defined Options
13463: @c ---------------------------------------------------------------------
13464: @cindex core words, implementation-defined options
13465: @cindex implementation-defined options, core words
13466:
13467:
13468: @table @i
13469: @item (Cell) aligned addresses:
13470: @cindex cell-aligned addresses
13471: @cindex aligned addresses
13472: processor-dependent. Gforth's alignment words perform natural alignment
13473: (e.g., an address aligned for a datum of size 8 is divisible by
13474: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13475:
13476: @item @code{EMIT} and non-graphic characters:
13477: @cindex @code{EMIT} and non-graphic characters
13478: @cindex non-graphic characters and @code{EMIT}
13479: The character is output using the C library function (actually, macro)
13480: @code{putc}.
13481:
13482: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13483: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13484: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13485: @cindex @code{ACCEPT}, editing
13486: @cindex @code{EXPECT}, editing
13487: This is modeled on the GNU readline library (@pxref{Readline
13488: Interaction, , Command Line Editing, readline, The GNU Readline
13489: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13490: producing a full word completion every time you type it (instead of
1.28 crook 13491: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13492:
13493: @item character set:
13494: @cindex character set
13495: The character set of your computer and display device. Gforth is
13496: 8-bit-clean (but some other component in your system may make trouble).
13497:
13498: @item Character-aligned address requirements:
13499: @cindex character-aligned address requirements
13500: installation-dependent. Currently a character is represented by a C
13501: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13502: (Comments on that requested).
13503:
13504: @item character-set extensions and matching of names:
13505: @cindex character-set extensions and matching of names
1.26 crook 13506: @cindex case-sensitivity for name lookup
13507: @cindex name lookup, case-sensitivity
13508: @cindex locale and case-sensitivity
1.21 crook 13509: Any character except the ASCII NUL character can be used in a
1.1 anton 13510: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13511: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13512: function is probably influenced by the locale. E.g., the @code{C} locale
13513: does not know about accents and umlauts, so they are matched
13514: case-sensitively in that locale. For portability reasons it is best to
13515: write programs such that they work in the @code{C} locale. Then one can
13516: use libraries written by a Polish programmer (who might use words
13517: containing ISO Latin-2 encoded characters) and by a French programmer
13518: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13519: funny results for some of the words (which ones, depends on the font you
13520: are using)). Also, the locale you prefer may not be available in other
13521: operating systems. Hopefully, Unicode will solve these problems one day.
13522:
13523: @item conditions under which control characters match a space delimiter:
13524: @cindex space delimiters
13525: @cindex control characters as delimiters
1.117 anton 13526: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13527: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13528: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13529: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13530: interpreter (aka text interpreter) by default, treats all white-space
13531: characters as delimiters.
13532:
1.26 crook 13533: @item format of the control-flow stack:
13534: @cindex control-flow stack, format
13535: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13536: stack item in cells is given by the constant @code{cs-item-size}. At the
13537: time of this writing, an item consists of a (pointer to a) locals list
13538: (third), an address in the code (second), and a tag for identifying the
13539: item (TOS). The following tags are used: @code{defstart},
13540: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13541: @code{scopestart}.
13542:
13543: @item conversion of digits > 35
13544: @cindex digits > 35
13545: The characters @code{[\]^_'} are the digits with the decimal value
13546: 36@minus{}41. There is no way to input many of the larger digits.
13547:
13548: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13549: @cindex @code{EXPECT}, display after end of input
13550: @cindex @code{ACCEPT}, display after end of input
13551: The cursor is moved to the end of the entered string. If the input is
13552: terminated using the @kbd{Return} key, a space is typed.
13553:
13554: @item exception abort sequence of @code{ABORT"}:
13555: @cindex exception abort sequence of @code{ABORT"}
13556: @cindex @code{ABORT"}, exception abort sequence
13557: The error string is stored into the variable @code{"error} and a
13558: @code{-2 throw} is performed.
13559:
13560: @item input line terminator:
13561: @cindex input line terminator
13562: @cindex line terminator on input
1.26 crook 13563: @cindex newline character on input
1.1 anton 13564: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13565: lines. One of these characters is typically produced when you type the
13566: @kbd{Enter} or @kbd{Return} key.
13567:
13568: @item maximum size of a counted string:
13569: @cindex maximum size of a counted string
13570: @cindex counted string, maximum size
13571: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13572: on all platforms, but this may change.
1.1 anton 13573:
13574: @item maximum size of a parsed string:
13575: @cindex maximum size of a parsed string
13576: @cindex parsed string, maximum size
13577: Given by the constant @code{/line}. Currently 255 characters.
13578:
13579: @item maximum size of a definition name, in characters:
13580: @cindex maximum size of a definition name, in characters
13581: @cindex name, maximum length
1.113 anton 13582: MAXU/8
1.1 anton 13583:
13584: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13585: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13586: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13587: MAXU/8
1.1 anton 13588:
13589: @item method of selecting the user input device:
13590: @cindex user input device, method of selecting
13591: The user input device is the standard input. There is currently no way to
13592: change it from within Gforth. However, the input can typically be
13593: redirected in the command line that starts Gforth.
13594:
13595: @item method of selecting the user output device:
13596: @cindex user output device, method of selecting
13597: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13598: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13599: output when the user output device is a terminal, otherwise the output
13600: is buffered.
1.1 anton 13601:
13602: @item methods of dictionary compilation:
13603: What are we expected to document here?
13604:
13605: @item number of bits in one address unit:
13606: @cindex number of bits in one address unit
13607: @cindex address unit, size in bits
13608: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13609: platforms.
1.1 anton 13610:
13611: @item number representation and arithmetic:
13612: @cindex number representation and arithmetic
1.79 anton 13613: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13614:
13615: @item ranges for integer types:
13616: @cindex ranges for integer types
13617: @cindex integer types, ranges
13618: Installation-dependent. Make environmental queries for @code{MAX-N},
13619: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13620: unsigned (and positive) types is 0. The lower bound for signed types on
13621: two's complement and one's complement machines machines can be computed
13622: by adding 1 to the upper bound.
13623:
13624: @item read-only data space regions:
13625: @cindex read-only data space regions
13626: @cindex data-space, read-only regions
13627: The whole Forth data space is writable.
13628:
13629: @item size of buffer at @code{WORD}:
13630: @cindex size of buffer at @code{WORD}
13631: @cindex @code{WORD} buffer size
13632: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13633: shared with the pictured numeric output string. If overwriting
13634: @code{PAD} is acceptable, it is as large as the remaining dictionary
13635: space, although only as much can be sensibly used as fits in a counted
13636: string.
13637:
13638: @item size of one cell in address units:
13639: @cindex cell size
13640: @code{1 cells .}.
13641:
13642: @item size of one character in address units:
13643: @cindex char size
1.79 anton 13644: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13645:
13646: @item size of the keyboard terminal buffer:
13647: @cindex size of the keyboard terminal buffer
13648: @cindex terminal buffer, size
13649: Varies. You can determine the size at a specific time using @code{lp@@
13650: tib - .}. It is shared with the locals stack and TIBs of files that
13651: include the current file. You can change the amount of space for TIBs
13652: and locals stack at Gforth startup with the command line option
13653: @code{-l}.
13654:
13655: @item size of the pictured numeric output buffer:
13656: @cindex size of the pictured numeric output buffer
13657: @cindex pictured numeric output buffer, size
13658: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13659: shared with @code{WORD}.
13660:
13661: @item size of the scratch area returned by @code{PAD}:
13662: @cindex size of the scratch area returned by @code{PAD}
13663: @cindex @code{PAD} size
13664: The remainder of dictionary space. @code{unused pad here - - .}.
13665:
13666: @item system case-sensitivity characteristics:
13667: @cindex case-sensitivity characteristics
1.26 crook 13668: Dictionary searches are case-insensitive (except in
1.1 anton 13669: @code{TABLE}s). However, as explained above under @i{character-set
13670: extensions}, the matching for non-ASCII characters is determined by the
13671: locale you are using. In the default @code{C} locale all non-ASCII
13672: characters are matched case-sensitively.
13673:
13674: @item system prompt:
13675: @cindex system prompt
13676: @cindex prompt
13677: @code{ ok} in interpret state, @code{ compiled} in compile state.
13678:
13679: @item division rounding:
13680: @cindex division rounding
1.166 anton 13681: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13682: division (with the default installation of Gforth). You can check
13683: this with @code{s" floored" environment? drop .}. If you write
13684: programs that need a specific division rounding, best use
13685: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13686:
13687: @item values of @code{STATE} when true:
13688: @cindex @code{STATE} values
13689: -1.
13690:
13691: @item values returned after arithmetic overflow:
13692: On two's complement machines, arithmetic is performed modulo
13693: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13694: arithmetic (with appropriate mapping for signed types). Division by
13695: zero typically results in a @code{-55 throw} (Floating-point
13696: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13697: division overflow can result in these throws, or in @code{-11 throw};
13698: in @code{gforth-fast} division overflow and divide by zero may also
13699: result in returning bogus results without producing an exception.
1.1 anton 13700:
13701: @item whether the current definition can be found after @t{DOES>}:
13702: @cindex @t{DOES>}, visibility of current definition
13703: No.
13704:
13705: @end table
13706:
13707: @c ---------------------------------------------------------------------
13708: @node core-ambcond, core-other, core-idef, The Core Words
13709: @subsection Ambiguous conditions
13710: @c ---------------------------------------------------------------------
13711: @cindex core words, ambiguous conditions
13712: @cindex ambiguous conditions, core words
13713:
13714: @table @i
13715:
13716: @item a name is neither a word nor a number:
13717: @cindex name not found
1.26 crook 13718: @cindex undefined word
1.80 anton 13719: @code{-13 throw} (Undefined word).
1.1 anton 13720:
13721: @item a definition name exceeds the maximum length allowed:
1.26 crook 13722: @cindex word name too long
1.1 anton 13723: @code{-19 throw} (Word name too long)
13724:
13725: @item addressing a region not inside the various data spaces of the forth system:
13726: @cindex Invalid memory address
1.32 anton 13727: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13728: typically readable. Accessing other addresses gives results dependent on
13729: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13730: address).
13731:
13732: @item argument type incompatible with parameter:
1.26 crook 13733: @cindex argument type mismatch
1.1 anton 13734: This is usually not caught. Some words perform checks, e.g., the control
13735: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13736: mismatch).
13737:
13738: @item attempting to obtain the execution token of a word with undefined execution semantics:
13739: @cindex Interpreting a compile-only word, for @code{'} etc.
13740: @cindex execution token of words with undefined execution semantics
13741: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13742: get an execution token for @code{compile-only-error} (which performs a
13743: @code{-14 throw} when executed).
13744:
13745: @item dividing by zero:
13746: @cindex dividing by zero
13747: @cindex floating point unidentified fault, integer division
1.80 anton 13748: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13749: zero); on other systems, this typically results in a @code{-55 throw}
13750: (Floating-point unidentified fault).
1.1 anton 13751:
13752: @item insufficient data stack or return stack space:
13753: @cindex insufficient data stack or return stack space
13754: @cindex stack overflow
1.26 crook 13755: @cindex address alignment exception, stack overflow
1.1 anton 13756: @cindex Invalid memory address, stack overflow
13757: Depending on the operating system, the installation, and the invocation
13758: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13759: it is not checked. If it is checked, you typically get a @code{-3 throw}
13760: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13761: throw} (Invalid memory address) (depending on the platform and how you
13762: achieved the overflow) as soon as the overflow happens. If it is not
13763: checked, overflows typically result in mysterious illegal memory
13764: accesses, producing @code{-9 throw} (Invalid memory address) or
13765: @code{-23 throw} (Address alignment exception); they might also destroy
13766: the internal data structure of @code{ALLOCATE} and friends, resulting in
13767: various errors in these words.
1.1 anton 13768:
13769: @item insufficient space for loop control parameters:
13770: @cindex insufficient space for loop control parameters
1.80 anton 13771: Like other return stack overflows.
1.1 anton 13772:
13773: @item insufficient space in the dictionary:
13774: @cindex insufficient space in the dictionary
13775: @cindex dictionary overflow
1.12 anton 13776: If you try to allot (either directly with @code{allot}, or indirectly
13777: with @code{,}, @code{create} etc.) more memory than available in the
13778: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13779: to access memory beyond the end of the dictionary, the results are
13780: similar to stack overflows.
1.1 anton 13781:
13782: @item interpreting a word with undefined interpretation semantics:
13783: @cindex interpreting a word with undefined interpretation semantics
13784: @cindex Interpreting a compile-only word
13785: For some words, we have defined interpretation semantics. For the
13786: others: @code{-14 throw} (Interpreting a compile-only word).
13787:
13788: @item modifying the contents of the input buffer or a string literal:
13789: @cindex modifying the contents of the input buffer or a string literal
13790: These are located in writable memory and can be modified.
13791:
13792: @item overflow of the pictured numeric output string:
13793: @cindex overflow of the pictured numeric output string
13794: @cindex pictured numeric output string, overflow
1.24 anton 13795: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13796:
13797: @item parsed string overflow:
13798: @cindex parsed string overflow
13799: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13800:
13801: @item producing a result out of range:
13802: @cindex result out of range
13803: On two's complement machines, arithmetic is performed modulo
13804: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13805: arithmetic (with appropriate mapping for signed types). Division by
13806: zero typically results in a @code{-10 throw} (divide by zero) or
13807: @code{-55 throw} (floating point unidentified fault). Overflow on
13808: division may result in these errors or in @code{-11 throw} (result out
13809: of range). @code{Gforth-fast} may silently produce bogus results on
13810: division overflow or division by zero. @code{Convert} and
1.24 anton 13811: @code{>number} currently overflow silently.
1.1 anton 13812:
13813: @item reading from an empty data or return stack:
13814: @cindex stack empty
13815: @cindex stack underflow
1.24 anton 13816: @cindex return stack underflow
1.1 anton 13817: The data stack is checked by the outer (aka text) interpreter after
13818: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13819: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13820: depending on operating system, installation, and invocation. If they are
13821: caught by a check, they typically result in @code{-4 throw} (Stack
13822: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13823: (Invalid memory address), depending on the platform and which stack
13824: underflows and by how much. Note that even if the system uses checking
13825: (through the MMU), your program may have to underflow by a significant
13826: number of stack items to trigger the reaction (the reason for this is
13827: that the MMU, and therefore the checking, works with a page-size
13828: granularity). If there is no checking, the symptoms resulting from an
13829: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13830: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13831: (Invalid memory address) and Illegal Instruction (typically @code{-260
13832: throw}).
1.1 anton 13833:
13834: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13835: @cindex unexpected end of the input buffer
13836: @cindex zero-length string as a name
13837: @cindex Attempt to use zero-length string as a name
13838: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13839: use zero-length string as a name). Words like @code{'} probably will not
13840: find what they search. Note that it is possible to create zero-length
13841: names with @code{nextname} (should it not?).
13842:
13843: @item @code{>IN} greater than input buffer:
13844: @cindex @code{>IN} greater than input buffer
13845: The next invocation of a parsing word returns a string with length 0.
13846:
13847: @item @code{RECURSE} appears after @code{DOES>}:
13848: @cindex @code{RECURSE} appears after @code{DOES>}
13849: Compiles a recursive call to the defining word, not to the defined word.
13850:
13851: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13852: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13853: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13854: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13855: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13856: the end of the file was reached), its source-id may be
13857: reused. Therefore, restoring an input source specification referencing a
13858: closed file may lead to unpredictable results instead of a @code{-12
13859: THROW}.
13860:
13861: In the future, Gforth may be able to restore input source specifications
13862: from other than the current input source.
13863:
13864: @item data space containing definitions gets de-allocated:
13865: @cindex data space containing definitions gets de-allocated
13866: Deallocation with @code{allot} is not checked. This typically results in
13867: memory access faults or execution of illegal instructions.
13868:
13869: @item data space read/write with incorrect alignment:
13870: @cindex data space read/write with incorrect alignment
13871: @cindex alignment faults
1.26 crook 13872: @cindex address alignment exception
1.1 anton 13873: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13874: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13875: alignment turned on, incorrect alignment results in a @code{-9 throw}
13876: (Invalid memory address). There are reportedly some processors with
1.12 anton 13877: alignment restrictions that do not report violations.
1.1 anton 13878:
13879: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13880: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13881: Like other alignment errors.
13882:
13883: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13884: Like other stack underflows.
13885:
13886: @item loop control parameters not available:
13887: @cindex loop control parameters not available
13888: Not checked. The counted loop words simply assume that the top of return
13889: stack items are loop control parameters and behave accordingly.
13890:
13891: @item most recent definition does not have a name (@code{IMMEDIATE}):
13892: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13893: @cindex last word was headerless
13894: @code{abort" last word was headerless"}.
13895:
13896: @item name not defined by @code{VALUE} used by @code{TO}:
13897: @cindex name not defined by @code{VALUE} used by @code{TO}
13898: @cindex @code{TO} on non-@code{VALUE}s
13899: @cindex Invalid name argument, @code{TO}
13900: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13901: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13902:
13903: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13904: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13905: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13906: @code{-13 throw} (Undefined word)
13907:
13908: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13909: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13910: Gforth behaves as if they were of the same type. I.e., you can predict
13911: the behaviour by interpreting all parameters as, e.g., signed.
13912:
13913: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13914: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13915: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13916: compilation semantics of @code{TO}.
13917:
13918: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13919: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13920: @cindex @code{WORD}, string overflow
13921: Not checked. The string will be ok, but the count will, of course,
13922: contain only the least significant bits of the length.
13923:
13924: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13925: @cindex @code{LSHIFT}, large shift counts
13926: @cindex @code{RSHIFT}, large shift counts
13927: Processor-dependent. Typical behaviours are returning 0 and using only
13928: the low bits of the shift count.
13929:
13930: @item word not defined via @code{CREATE}:
13931: @cindex @code{>BODY} of non-@code{CREATE}d words
13932: @code{>BODY} produces the PFA of the word no matter how it was defined.
13933:
13934: @cindex @code{DOES>} of non-@code{CREATE}d words
13935: @code{DOES>} changes the execution semantics of the last defined word no
13936: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13937: @code{CREATE , DOES>}.
13938:
13939: @item words improperly used outside @code{<#} and @code{#>}:
13940: Not checked. As usual, you can expect memory faults.
13941:
13942: @end table
13943:
13944:
13945: @c ---------------------------------------------------------------------
13946: @node core-other, , core-ambcond, The Core Words
13947: @subsection Other system documentation
13948: @c ---------------------------------------------------------------------
13949: @cindex other system documentation, core words
13950: @cindex core words, other system documentation
13951:
13952: @table @i
13953: @item nonstandard words using @code{PAD}:
13954: @cindex @code{PAD} use by nonstandard words
13955: None.
13956:
13957: @item operator's terminal facilities available:
13958: @cindex operator's terminal facilities available
1.80 anton 13959: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13960: and you can give commands to Gforth interactively. The actual facilities
13961: available depend on how you invoke Gforth.
13962:
13963: @item program data space available:
13964: @cindex program data space available
13965: @cindex data space available
13966: @code{UNUSED .} gives the remaining dictionary space. The total
13967: dictionary space can be specified with the @code{-m} switch
13968: (@pxref{Invoking Gforth}) when Gforth starts up.
13969:
13970: @item return stack space available:
13971: @cindex return stack space available
13972: You can compute the total return stack space in cells with
13973: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13974: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13975:
13976: @item stack space available:
13977: @cindex stack space available
13978: You can compute the total data stack space in cells with
13979: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13980: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
13981:
13982: @item system dictionary space required, in address units:
13983: @cindex system dictionary space required, in address units
13984: Type @code{here forthstart - .} after startup. At the time of this
13985: writing, this gives 80080 (bytes) on a 32-bit system.
13986: @end table
13987:
13988:
13989: @c =====================================================================
13990: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
13991: @section The optional Block word set
13992: @c =====================================================================
13993: @cindex system documentation, block words
13994: @cindex block words, system documentation
13995:
13996: @menu
13997: * block-idef:: Implementation Defined Options
13998: * block-ambcond:: Ambiguous Conditions
13999: * block-other:: Other System Documentation
14000: @end menu
14001:
14002:
14003: @c ---------------------------------------------------------------------
14004: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14005: @subsection Implementation Defined Options
14006: @c ---------------------------------------------------------------------
14007: @cindex implementation-defined options, block words
14008: @cindex block words, implementation-defined options
14009:
14010: @table @i
14011: @item the format for display by @code{LIST}:
14012: @cindex @code{LIST} display format
14013: First the screen number is displayed, then 16 lines of 64 characters,
14014: each line preceded by the line number.
14015:
14016: @item the length of a line affected by @code{\}:
14017: @cindex length of a line affected by @code{\}
14018: @cindex @code{\}, line length in blocks
14019: 64 characters.
14020: @end table
14021:
14022:
14023: @c ---------------------------------------------------------------------
14024: @node block-ambcond, block-other, block-idef, The optional Block word set
14025: @subsection Ambiguous conditions
14026: @c ---------------------------------------------------------------------
14027: @cindex block words, ambiguous conditions
14028: @cindex ambiguous conditions, block words
14029:
14030: @table @i
14031: @item correct block read was not possible:
14032: @cindex block read not possible
14033: Typically results in a @code{throw} of some OS-derived value (between
14034: -512 and -2048). If the blocks file was just not long enough, blanks are
14035: supplied for the missing portion.
14036:
14037: @item I/O exception in block transfer:
14038: @cindex I/O exception in block transfer
14039: @cindex block transfer, I/O exception
14040: Typically results in a @code{throw} of some OS-derived value (between
14041: -512 and -2048).
14042:
14043: @item invalid block number:
14044: @cindex invalid block number
14045: @cindex block number invalid
14046: @code{-35 throw} (Invalid block number)
14047:
14048: @item a program directly alters the contents of @code{BLK}:
14049: @cindex @code{BLK}, altering @code{BLK}
14050: The input stream is switched to that other block, at the same
14051: position. If the storing to @code{BLK} happens when interpreting
14052: non-block input, the system will get quite confused when the block ends.
14053:
14054: @item no current block buffer for @code{UPDATE}:
14055: @cindex @code{UPDATE}, no current block buffer
14056: @code{UPDATE} has no effect.
14057:
14058: @end table
14059:
14060: @c ---------------------------------------------------------------------
14061: @node block-other, , block-ambcond, The optional Block word set
14062: @subsection Other system documentation
14063: @c ---------------------------------------------------------------------
14064: @cindex other system documentation, block words
14065: @cindex block words, other system documentation
14066:
14067: @table @i
14068: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14069: No restrictions (yet).
14070:
14071: @item the number of blocks available for source and data:
14072: depends on your disk space.
14073:
14074: @end table
14075:
14076:
14077: @c =====================================================================
14078: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14079: @section The optional Double Number word set
14080: @c =====================================================================
14081: @cindex system documentation, double words
14082: @cindex double words, system documentation
14083:
14084: @menu
14085: * double-ambcond:: Ambiguous Conditions
14086: @end menu
14087:
14088:
14089: @c ---------------------------------------------------------------------
14090: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
14091: @subsection Ambiguous conditions
14092: @c ---------------------------------------------------------------------
14093: @cindex double words, ambiguous conditions
14094: @cindex ambiguous conditions, double words
14095:
14096: @table @i
1.29 crook 14097: @item @i{d} outside of range of @i{n} in @code{D>S}:
14098: @cindex @code{D>S}, @i{d} out of range of @i{n}
14099: The least significant cell of @i{d} is produced.
1.1 anton 14100:
14101: @end table
14102:
14103:
14104: @c =====================================================================
14105: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14106: @section The optional Exception word set
14107: @c =====================================================================
14108: @cindex system documentation, exception words
14109: @cindex exception words, system documentation
14110:
14111: @menu
14112: * exception-idef:: Implementation Defined Options
14113: @end menu
14114:
14115:
14116: @c ---------------------------------------------------------------------
14117: @node exception-idef, , The optional Exception word set, The optional Exception word set
14118: @subsection Implementation Defined Options
14119: @c ---------------------------------------------------------------------
14120: @cindex implementation-defined options, exception words
14121: @cindex exception words, implementation-defined options
14122:
14123: @table @i
14124: @item @code{THROW}-codes used in the system:
14125: @cindex @code{THROW}-codes used in the system
14126: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 14127: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 14128: codes -512@minus{}-2047 are used for OS errors (for file and memory
14129: allocation operations). The mapping from OS error numbers to throw codes
14130: is -512@minus{}@code{errno}. One side effect of this mapping is that
14131: undefined OS errors produce a message with a strange number; e.g.,
14132: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14133: @end table
14134:
14135: @c =====================================================================
14136: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14137: @section The optional Facility word set
14138: @c =====================================================================
14139: @cindex system documentation, facility words
14140: @cindex facility words, system documentation
14141:
14142: @menu
14143: * facility-idef:: Implementation Defined Options
14144: * facility-ambcond:: Ambiguous Conditions
14145: @end menu
14146:
14147:
14148: @c ---------------------------------------------------------------------
14149: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14150: @subsection Implementation Defined Options
14151: @c ---------------------------------------------------------------------
14152: @cindex implementation-defined options, facility words
14153: @cindex facility words, implementation-defined options
14154:
14155: @table @i
14156: @item encoding of keyboard events (@code{EKEY}):
14157: @cindex keyboard events, encoding in @code{EKEY}
14158: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 14159: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 14160: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14161: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14162: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14163: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 14164:
1.1 anton 14165:
14166: @item duration of a system clock tick:
14167: @cindex duration of a system clock tick
14168: @cindex clock tick duration
14169: System dependent. With respect to @code{MS}, the time is specified in
14170: microseconds. How well the OS and the hardware implement this, is
14171: another question.
14172:
14173: @item repeatability to be expected from the execution of @code{MS}:
14174: @cindex repeatability to be expected from the execution of @code{MS}
14175: @cindex @code{MS}, repeatability to be expected
14176: System dependent. On Unix, a lot depends on load. If the system is
14177: lightly loaded, and the delay is short enough that Gforth does not get
14178: swapped out, the performance should be acceptable. Under MS-DOS and
14179: other single-tasking systems, it should be good.
14180:
14181: @end table
14182:
14183:
14184: @c ---------------------------------------------------------------------
14185: @node facility-ambcond, , facility-idef, The optional Facility word set
14186: @subsection Ambiguous conditions
14187: @c ---------------------------------------------------------------------
14188: @cindex facility words, ambiguous conditions
14189: @cindex ambiguous conditions, facility words
14190:
14191: @table @i
14192: @item @code{AT-XY} can't be performed on user output device:
14193: @cindex @code{AT-XY} can't be performed on user output device
14194: Largely terminal dependent. No range checks are done on the arguments.
14195: No errors are reported. You may see some garbage appearing, you may see
14196: simply nothing happen.
14197:
14198: @end table
14199:
14200:
14201: @c =====================================================================
14202: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14203: @section The optional File-Access word set
14204: @c =====================================================================
14205: @cindex system documentation, file words
14206: @cindex file words, system documentation
14207:
14208: @menu
14209: * file-idef:: Implementation Defined Options
14210: * file-ambcond:: Ambiguous Conditions
14211: @end menu
14212:
14213: @c ---------------------------------------------------------------------
14214: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14215: @subsection Implementation Defined Options
14216: @c ---------------------------------------------------------------------
14217: @cindex implementation-defined options, file words
14218: @cindex file words, implementation-defined options
14219:
14220: @table @i
14221: @item file access methods used:
14222: @cindex file access methods used
14223: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14224: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14225: @code{wb}): The file is cleared, if it exists, and created, if it does
14226: not (with both @code{open-file} and @code{create-file}). Under Unix
14227: @code{create-file} creates a file with 666 permissions modified by your
14228: umask.
14229:
14230: @item file exceptions:
14231: @cindex file exceptions
14232: The file words do not raise exceptions (except, perhaps, memory access
14233: faults when you pass illegal addresses or file-ids).
14234:
14235: @item file line terminator:
14236: @cindex file line terminator
14237: System-dependent. Gforth uses C's newline character as line
14238: terminator. What the actual character code(s) of this are is
14239: system-dependent.
14240:
14241: @item file name format:
14242: @cindex file name format
14243: System dependent. Gforth just uses the file name format of your OS.
14244:
14245: @item information returned by @code{FILE-STATUS}:
14246: @cindex @code{FILE-STATUS}, returned information
14247: @code{FILE-STATUS} returns the most powerful file access mode allowed
14248: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14249: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14250: along with the returned mode.
14251:
14252: @item input file state after an exception when including source:
14253: @cindex exception when including source
14254: All files that are left via the exception are closed.
14255:
1.29 crook 14256: @item @i{ior} values and meaning:
14257: @cindex @i{ior} values and meaning
1.68 anton 14258: @cindex @i{wior} values and meaning
1.29 crook 14259: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14260: intended as throw codes. They typically are in the range
14261: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14262: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14263:
14264: @item maximum depth of file input nesting:
14265: @cindex maximum depth of file input nesting
14266: @cindex file input nesting, maximum depth
14267: limited by the amount of return stack, locals/TIB stack, and the number
14268: of open files available. This should not give you troubles.
14269:
14270: @item maximum size of input line:
14271: @cindex maximum size of input line
14272: @cindex input line size, maximum
14273: @code{/line}. Currently 255.
14274:
14275: @item methods of mapping block ranges to files:
14276: @cindex mapping block ranges to files
14277: @cindex files containing blocks
14278: @cindex blocks in files
14279: By default, blocks are accessed in the file @file{blocks.fb} in the
14280: current working directory. The file can be switched with @code{USE}.
14281:
14282: @item number of string buffers provided by @code{S"}:
14283: @cindex @code{S"}, number of string buffers
14284: 1
14285:
14286: @item size of string buffer used by @code{S"}:
14287: @cindex @code{S"}, size of string buffer
14288: @code{/line}. currently 255.
14289:
14290: @end table
14291:
14292: @c ---------------------------------------------------------------------
14293: @node file-ambcond, , file-idef, The optional File-Access word set
14294: @subsection Ambiguous conditions
14295: @c ---------------------------------------------------------------------
14296: @cindex file words, ambiguous conditions
14297: @cindex ambiguous conditions, file words
14298:
14299: @table @i
14300: @item attempting to position a file outside its boundaries:
14301: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14302: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14303: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14304:
14305: @item attempting to read from file positions not yet written:
14306: @cindex reading from file positions not yet written
14307: End-of-file, i.e., zero characters are read and no error is reported.
14308:
1.29 crook 14309: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14310: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14311: An appropriate exception may be thrown, but a memory fault or other
14312: problem is more probable.
14313:
1.29 crook 14314: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14315: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14316: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14317: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14318: thrown.
14319:
14320: @item named file cannot be opened (@code{INCLUDED}):
14321: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14322: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14323:
14324: @item requesting an unmapped block number:
14325: @cindex unmapped block numbers
14326: There are no unmapped legal block numbers. On some operating systems,
14327: writing a block with a large number may overflow the file system and
14328: have an error message as consequence.
14329:
14330: @item using @code{source-id} when @code{blk} is non-zero:
14331: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14332: @code{source-id} performs its function. Typically it will give the id of
14333: the source which loaded the block. (Better ideas?)
14334:
14335: @end table
14336:
14337:
14338: @c =====================================================================
14339: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14340: @section The optional Floating-Point word set
14341: @c =====================================================================
14342: @cindex system documentation, floating-point words
14343: @cindex floating-point words, system documentation
14344:
14345: @menu
14346: * floating-idef:: Implementation Defined Options
14347: * floating-ambcond:: Ambiguous Conditions
14348: @end menu
14349:
14350:
14351: @c ---------------------------------------------------------------------
14352: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14353: @subsection Implementation Defined Options
14354: @c ---------------------------------------------------------------------
14355: @cindex implementation-defined options, floating-point words
14356: @cindex floating-point words, implementation-defined options
14357:
14358: @table @i
14359: @item format and range of floating point numbers:
14360: @cindex format and range of floating point numbers
14361: @cindex floating point numbers, format and range
14362: System-dependent; the @code{double} type of C.
14363:
1.29 crook 14364: @item results of @code{REPRESENT} when @i{float} is out of range:
14365: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14366: System dependent; @code{REPRESENT} is implemented using the C library
14367: function @code{ecvt()} and inherits its behaviour in this respect.
14368:
14369: @item rounding or truncation of floating-point numbers:
14370: @cindex rounding of floating-point numbers
14371: @cindex truncation of floating-point numbers
14372: @cindex floating-point numbers, rounding or truncation
14373: System dependent; the rounding behaviour is inherited from the hosting C
14374: compiler. IEEE-FP-based (i.e., most) systems by default round to
14375: nearest, and break ties by rounding to even (i.e., such that the last
14376: bit of the mantissa is 0).
14377:
14378: @item size of floating-point stack:
14379: @cindex floating-point stack size
14380: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14381: the floating-point stack (in floats). You can specify this on startup
14382: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14383:
14384: @item width of floating-point stack:
14385: @cindex floating-point stack width
14386: @code{1 floats}.
14387:
14388: @end table
14389:
14390:
14391: @c ---------------------------------------------------------------------
14392: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14393: @subsection Ambiguous conditions
14394: @c ---------------------------------------------------------------------
14395: @cindex floating-point words, ambiguous conditions
14396: @cindex ambiguous conditions, floating-point words
14397:
14398: @table @i
14399: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14400: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14401: System-dependent. Typically results in a @code{-23 THROW} like other
14402: alignment violations.
14403:
14404: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14405: @cindex @code{f@@} used with an address that is not float aligned
14406: @cindex @code{f!} used with an address that is not float aligned
14407: System-dependent. Typically results in a @code{-23 THROW} like other
14408: alignment violations.
14409:
14410: @item floating-point result out of range:
14411: @cindex floating-point result out of range
1.80 anton 14412: System-dependent. Can result in a @code{-43 throw} (floating point
14413: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14414: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14415: unidentified fault), or can produce a special value representing, e.g.,
14416: Infinity.
14417:
14418: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14419: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14420: System-dependent. Typically results in an alignment fault like other
14421: alignment violations.
14422:
1.35 anton 14423: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14424: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14425: The floating-point number is converted into decimal nonetheless.
14426:
14427: @item Both arguments are equal to zero (@code{FATAN2}):
14428: @cindex @code{FATAN2}, both arguments are equal to zero
14429: System-dependent. @code{FATAN2} is implemented using the C library
14430: function @code{atan2()}.
14431:
1.29 crook 14432: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14433: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14434: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14435: because of small errors and the tan will be a very large (or very small)
14436: but finite number.
14437:
1.29 crook 14438: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14439: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14440: The result is rounded to the nearest float.
14441:
14442: @item dividing by zero:
14443: @cindex dividing by zero, floating-point
14444: @cindex floating-point dividing by zero
14445: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14446: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14447: (floating point divide by zero) or @code{-55 throw} (Floating-point
14448: unidentified fault).
1.1 anton 14449:
14450: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14451: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14452: System dependent. On IEEE-FP based systems the number is converted into
14453: an infinity.
14454:
1.29 crook 14455: @item @i{float}<1 (@code{FACOSH}):
14456: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14457: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14458: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14459:
1.29 crook 14460: @item @i{float}=<-1 (@code{FLNP1}):
14461: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14462: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14463: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14464: negative infinity for @i{float}=-1).
1.1 anton 14465:
1.29 crook 14466: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14467: @cindex @code{FLN}, @i{float}=<0
14468: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14469: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14470: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14471: negative infinity for @i{float}=0).
1.1 anton 14472:
1.29 crook 14473: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14474: @cindex @code{FASINH}, @i{float}<0
14475: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14476: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14477: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14478: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14479: C library?).
1.1 anton 14480:
1.29 crook 14481: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14482: @cindex @code{FACOS}, |@i{float}|>1
14483: @cindex @code{FASIN}, |@i{float}|>1
14484: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14485: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14486: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14487:
1.29 crook 14488: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14489: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14490: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14491: Platform-dependent; typically, some double number is produced and no
14492: error is reported.
1.1 anton 14493:
14494: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14495: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14496: @code{Precision} characters of the numeric output area are used. If
14497: @code{precision} is too high, these words will smash the data or code
14498: close to @code{here}.
1.1 anton 14499: @end table
14500:
14501: @c =====================================================================
14502: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14503: @section The optional Locals word set
14504: @c =====================================================================
14505: @cindex system documentation, locals words
14506: @cindex locals words, system documentation
14507:
14508: @menu
14509: * locals-idef:: Implementation Defined Options
14510: * locals-ambcond:: Ambiguous Conditions
14511: @end menu
14512:
14513:
14514: @c ---------------------------------------------------------------------
14515: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14516: @subsection Implementation Defined Options
14517: @c ---------------------------------------------------------------------
14518: @cindex implementation-defined options, locals words
14519: @cindex locals words, implementation-defined options
14520:
14521: @table @i
14522: @item maximum number of locals in a definition:
14523: @cindex maximum number of locals in a definition
14524: @cindex locals, maximum number in a definition
14525: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14526: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14527: characters. The number of locals in a definition is bounded by the size
14528: of locals-buffer, which contains the names of the locals.
14529:
14530: @end table
14531:
14532:
14533: @c ---------------------------------------------------------------------
14534: @node locals-ambcond, , locals-idef, The optional Locals word set
14535: @subsection Ambiguous conditions
14536: @c ---------------------------------------------------------------------
14537: @cindex locals words, ambiguous conditions
14538: @cindex ambiguous conditions, locals words
14539:
14540: @table @i
14541: @item executing a named local in interpretation state:
14542: @cindex local in interpretation state
14543: @cindex Interpreting a compile-only word, for a local
14544: Locals have no interpretation semantics. If you try to perform the
14545: interpretation semantics, you will get a @code{-14 throw} somewhere
14546: (Interpreting a compile-only word). If you perform the compilation
14547: semantics, the locals access will be compiled (irrespective of state).
14548:
1.29 crook 14549: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14550: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14551: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14552: @cindex Invalid name argument, @code{TO}
14553: @code{-32 throw} (Invalid name argument)
14554:
14555: @end table
14556:
14557:
14558: @c =====================================================================
14559: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14560: @section The optional Memory-Allocation word set
14561: @c =====================================================================
14562: @cindex system documentation, memory-allocation words
14563: @cindex memory-allocation words, system documentation
14564:
14565: @menu
14566: * memory-idef:: Implementation Defined Options
14567: @end menu
14568:
14569:
14570: @c ---------------------------------------------------------------------
14571: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14572: @subsection Implementation Defined Options
14573: @c ---------------------------------------------------------------------
14574: @cindex implementation-defined options, memory-allocation words
14575: @cindex memory-allocation words, implementation-defined options
14576:
14577: @table @i
1.29 crook 14578: @item values and meaning of @i{ior}:
14579: @cindex @i{ior} values and meaning
14580: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14581: intended as throw codes. They typically are in the range
14582: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14583: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14584:
14585: @end table
14586:
14587: @c =====================================================================
14588: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14589: @section The optional Programming-Tools word set
14590: @c =====================================================================
14591: @cindex system documentation, programming-tools words
14592: @cindex programming-tools words, system documentation
14593:
14594: @menu
14595: * programming-idef:: Implementation Defined Options
14596: * programming-ambcond:: Ambiguous Conditions
14597: @end menu
14598:
14599:
14600: @c ---------------------------------------------------------------------
14601: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14602: @subsection Implementation Defined Options
14603: @c ---------------------------------------------------------------------
14604: @cindex implementation-defined options, programming-tools words
14605: @cindex programming-tools words, implementation-defined options
14606:
14607: @table @i
14608: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14609: @cindex @code{;CODE} ending sequence
14610: @cindex @code{CODE} ending sequence
14611: @code{END-CODE}
14612:
14613: @item manner of processing input following @code{;CODE} and @code{CODE}:
14614: @cindex @code{;CODE}, processing input
14615: @cindex @code{CODE}, processing input
14616: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14617: the input is processed by the text interpreter, (starting) in interpret
14618: state.
14619:
14620: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14621: @cindex @code{ASSEMBLER}, search order capability
14622: The ANS Forth search order word set.
14623:
14624: @item source and format of display by @code{SEE}:
14625: @cindex @code{SEE}, source and format of output
1.80 anton 14626: The source for @code{see} is the executable code used by the inner
1.1 anton 14627: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14628: (and on some platforms, assembly code for primitives) as well as
14629: possible.
1.1 anton 14630:
14631: @end table
14632:
14633: @c ---------------------------------------------------------------------
14634: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14635: @subsection Ambiguous conditions
14636: @c ---------------------------------------------------------------------
14637: @cindex programming-tools words, ambiguous conditions
14638: @cindex ambiguous conditions, programming-tools words
14639:
14640: @table @i
14641:
1.21 crook 14642: @item deleting the compilation word list (@code{FORGET}):
14643: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14644: Not implemented (yet).
14645:
1.29 crook 14646: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14647: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14648: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14649: @cindex control-flow stack underflow
14650: This typically results in an @code{abort"} with a descriptive error
14651: message (may change into a @code{-22 throw} (Control structure mismatch)
14652: in the future). You may also get a memory access error. If you are
14653: unlucky, this ambiguous condition is not caught.
14654:
1.29 crook 14655: @item @i{name} can't be found (@code{FORGET}):
14656: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14657: Not implemented (yet).
14658:
1.29 crook 14659: @item @i{name} not defined via @code{CREATE}:
14660: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14661: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14662: the execution semantics of the last defined word no matter how it was
14663: defined.
14664:
14665: @item @code{POSTPONE} applied to @code{[IF]}:
14666: @cindex @code{POSTPONE} applied to @code{[IF]}
14667: @cindex @code{[IF]} and @code{POSTPONE}
14668: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14669: equivalent to @code{[IF]}.
14670:
14671: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14672: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14673: Continue in the same state of conditional compilation in the next outer
14674: input source. Currently there is no warning to the user about this.
14675:
14676: @item removing a needed definition (@code{FORGET}):
14677: @cindex @code{FORGET}, removing a needed definition
14678: Not implemented (yet).
14679:
14680: @end table
14681:
14682:
14683: @c =====================================================================
14684: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14685: @section The optional Search-Order word set
14686: @c =====================================================================
14687: @cindex system documentation, search-order words
14688: @cindex search-order words, system documentation
14689:
14690: @menu
14691: * search-idef:: Implementation Defined Options
14692: * search-ambcond:: Ambiguous Conditions
14693: @end menu
14694:
14695:
14696: @c ---------------------------------------------------------------------
14697: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14698: @subsection Implementation Defined Options
14699: @c ---------------------------------------------------------------------
14700: @cindex implementation-defined options, search-order words
14701: @cindex search-order words, implementation-defined options
14702:
14703: @table @i
14704: @item maximum number of word lists in search order:
14705: @cindex maximum number of word lists in search order
14706: @cindex search order, maximum depth
14707: @code{s" wordlists" environment? drop .}. Currently 16.
14708:
14709: @item minimum search order:
14710: @cindex minimum search order
14711: @cindex search order, minimum
14712: @code{root root}.
14713:
14714: @end table
14715:
14716: @c ---------------------------------------------------------------------
14717: @node search-ambcond, , search-idef, The optional Search-Order word set
14718: @subsection Ambiguous conditions
14719: @c ---------------------------------------------------------------------
14720: @cindex search-order words, ambiguous conditions
14721: @cindex ambiguous conditions, search-order words
14722:
14723: @table @i
1.21 crook 14724: @item changing the compilation word list (during compilation):
14725: @cindex changing the compilation word list (during compilation)
14726: @cindex compilation word list, change before definition ends
14727: The word is entered into the word list that was the compilation word list
1.1 anton 14728: at the start of the definition. Any changes to the name field (e.g.,
14729: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14730: are applied to the latest defined word (as reported by @code{latest} or
14731: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14732:
14733: @item search order empty (@code{previous}):
14734: @cindex @code{previous}, search order empty
1.26 crook 14735: @cindex vocstack empty, @code{previous}
1.1 anton 14736: @code{abort" Vocstack empty"}.
14737:
14738: @item too many word lists in search order (@code{also}):
14739: @cindex @code{also}, too many word lists in search order
1.26 crook 14740: @cindex vocstack full, @code{also}
1.1 anton 14741: @code{abort" Vocstack full"}.
14742:
14743: @end table
14744:
14745: @c ***************************************************************
1.65 anton 14746: @node Standard vs Extensions, Model, ANS conformance, Top
14747: @chapter Should I use Gforth extensions?
14748: @cindex Gforth extensions
14749:
14750: As you read through the rest of this manual, you will see documentation
14751: for @i{Standard} words, and documentation for some appealing Gforth
14752: @i{extensions}. You might ask yourself the question: @i{``Should I
14753: restrict myself to the standard, or should I use the extensions?''}
14754:
14755: The answer depends on the goals you have for the program you are working
14756: on:
14757:
14758: @itemize @bullet
14759:
14760: @item Is it just for yourself or do you want to share it with others?
14761:
14762: @item
14763: If you want to share it, do the others all use Gforth?
14764:
14765: @item
14766: If it is just for yourself, do you want to restrict yourself to Gforth?
14767:
14768: @end itemize
14769:
14770: If restricting the program to Gforth is ok, then there is no reason not
14771: to use extensions. It is still a good idea to keep to the standard
14772: where it is easy, in case you want to reuse these parts in another
14773: program that you want to be portable.
14774:
14775: If you want to be able to port the program to other Forth systems, there
14776: are the following points to consider:
14777:
14778: @itemize @bullet
14779:
14780: @item
14781: Most Forth systems that are being maintained support the ANS Forth
14782: standard. So if your program complies with the standard, it will be
14783: portable among many systems.
14784:
14785: @item
14786: A number of the Gforth extensions can be implemented in ANS Forth using
14787: public-domain files provided in the @file{compat/} directory. These are
14788: mentioned in the text in passing. There is no reason not to use these
14789: extensions, your program will still be ANS Forth compliant; just include
14790: the appropriate compat files with your program.
14791:
14792: @item
14793: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14794: analyse your program and determine what non-Standard words it relies
14795: upon. However, it does not check whether you use standard words in a
14796: non-standard way.
14797:
14798: @item
14799: Some techniques are not standardized by ANS Forth, and are hard or
14800: impossible to implement in a standard way, but can be implemented in
14801: most Forth systems easily, and usually in similar ways (e.g., accessing
14802: word headers). Forth has a rich historical precedent for programmers
14803: taking advantage of implementation-dependent features of their tools
14804: (for example, relying on a knowledge of the dictionary
14805: structure). Sometimes these techniques are necessary to extract every
14806: last bit of performance from the hardware, sometimes they are just a
14807: programming shorthand.
14808:
14809: @item
14810: Does using a Gforth extension save more work than the porting this part
14811: to other Forth systems (if any) will cost?
14812:
14813: @item
14814: Is the additional functionality worth the reduction in portability and
14815: the additional porting problems?
14816:
14817: @end itemize
14818:
14819: In order to perform these consideratios, you need to know what's
14820: standard and what's not. This manual generally states if something is
1.81 anton 14821: non-standard, but the authoritative source is the
14822: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14823: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14824: into the thought processes of the technical committee.
14825:
14826: Note also that portability between Forth systems is not the only
14827: portability issue; there is also the issue of portability between
14828: different platforms (processor/OS combinations).
14829:
14830: @c ***************************************************************
14831: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14832: @chapter Model
14833:
14834: This chapter has yet to be written. It will contain information, on
14835: which internal structures you can rely.
14836:
14837: @c ***************************************************************
14838: @node Integrating Gforth, Emacs and Gforth, Model, Top
14839: @chapter Integrating Gforth into C programs
14840:
14841: This is not yet implemented.
14842:
14843: Several people like to use Forth as scripting language for applications
14844: that are otherwise written in C, C++, or some other language.
14845:
14846: The Forth system ATLAST provides facilities for embedding it into
14847: applications; unfortunately it has several disadvantages: most
14848: importantly, it is not based on ANS Forth, and it is apparently dead
14849: (i.e., not developed further and not supported). The facilities
1.21 crook 14850: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14851: making the switch should not be hard.
14852:
14853: We also tried to design the interface such that it can easily be
14854: implemented by other Forth systems, so that we may one day arrive at a
14855: standardized interface. Such a standard interface would allow you to
14856: replace the Forth system without having to rewrite C code.
14857:
14858: You embed the Gforth interpreter by linking with the library
14859: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14860: global symbols in this library that belong to the interface, have the
14861: prefix @code{forth_}. (Global symbols that are used internally have the
14862: prefix @code{gforth_}).
14863:
14864: You can include the declarations of Forth types and the functions and
14865: variables of the interface with @code{#include <forth.h>}.
14866:
14867: Types.
14868:
14869: Variables.
14870:
14871: Data and FP Stack pointer. Area sizes.
14872:
14873: functions.
14874:
14875: forth_init(imagefile)
14876: forth_evaluate(string) exceptions?
14877: forth_goto(address) (or forth_execute(xt)?)
14878: forth_continue() (a corountining mechanism)
14879:
14880: Adding primitives.
14881:
14882: No checking.
14883:
14884: Signals?
14885:
14886: Accessing the Stacks
14887:
1.26 crook 14888: @c ******************************************************************
1.1 anton 14889: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14890: @chapter Emacs and Gforth
14891: @cindex Emacs and Gforth
14892:
14893: @cindex @file{gforth.el}
14894: @cindex @file{forth.el}
14895: @cindex Rydqvist, Goran
1.107 dvdkhlng 14896: @cindex Kuehling, David
1.1 anton 14897: @cindex comment editing commands
14898: @cindex @code{\}, editing with Emacs
14899: @cindex debug tracer editing commands
14900: @cindex @code{~~}, removal with Emacs
14901: @cindex Forth mode in Emacs
1.107 dvdkhlng 14902:
1.1 anton 14903: Gforth comes with @file{gforth.el}, an improved version of
14904: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14905: improvements are:
14906:
14907: @itemize @bullet
14908: @item
1.107 dvdkhlng 14909: A better handling of indentation.
14910: @item
14911: A custom hilighting engine for Forth-code.
1.26 crook 14912: @item
14913: Comment paragraph filling (@kbd{M-q})
14914: @item
14915: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14916: @item
14917: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14918: @item
14919: Support of the @code{info-lookup} feature for looking up the
14920: documentation of a word.
1.107 dvdkhlng 14921: @item
14922: Support for reading and writing blocks files.
1.26 crook 14923: @end itemize
14924:
1.107 dvdkhlng 14925: To get a basic description of these features, enter Forth mode and
14926: type @kbd{C-h m}.
1.1 anton 14927:
14928: @cindex source location of error or debugging output in Emacs
14929: @cindex error output, finding the source location in Emacs
14930: @cindex debugging output, finding the source location in Emacs
14931: In addition, Gforth supports Emacs quite well: The source code locations
14932: given in error messages, debugging output (from @code{~~}) and failed
14933: assertion messages are in the right format for Emacs' compilation mode
14934: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14935: Manual}) so the source location corresponding to an error or other
14936: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14937: @kbd{C-c C-c} for the error under the cursor).
14938:
1.107 dvdkhlng 14939: @cindex viewing the documentation of a word in Emacs
14940: @cindex context-sensitive help
14941: Moreover, for words documented in this manual, you can look up the
14942: glossary entry quickly by using @kbd{C-h TAB}
14943: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14944: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14945: later and does not work for words containing @code{:}.
14946:
14947: @menu
14948: * Installing gforth.el:: Making Emacs aware of Forth.
14949: * Emacs Tags:: Viewing the source of a word in Emacs.
14950: * Hilighting:: Making Forth code look prettier.
14951: * Auto-Indentation:: Customizing auto-indentation.
14952: * Blocks Files:: Reading and writing blocks files.
14953: @end menu
14954:
14955: @c ----------------------------------
1.109 anton 14956: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14957: @section Installing gforth.el
14958: @cindex @file{.emacs}
14959: @cindex @file{gforth.el}, installation
14960: To make the features from @file{gforth.el} available in Emacs, add
14961: the following lines to your @file{.emacs} file:
14962:
14963: @example
14964: (autoload 'forth-mode "gforth.el")
14965: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14966: auto-mode-alist))
14967: (autoload 'forth-block-mode "gforth.el")
14968: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14969: auto-mode-alist))
14970: (add-hook 'forth-mode-hook (function (lambda ()
14971: ;; customize variables here:
14972: (setq forth-indent-level 4)
14973: (setq forth-minor-indent-level 2)
14974: (setq forth-hilight-level 3)
14975: ;;; ...
14976: )))
14977: @end example
14978:
14979: @c ----------------------------------
14980: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
14981: @section Emacs Tags
1.1 anton 14982: @cindex @file{TAGS} file
14983: @cindex @file{etags.fs}
14984: @cindex viewing the source of a word in Emacs
1.43 anton 14985: @cindex @code{require}, placement in files
14986: @cindex @code{include}, placement in files
1.107 dvdkhlng 14987: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
14988: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 14989: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 14990: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 14991: several tags files at the same time (e.g., one for the Gforth sources
14992: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
14993: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
14994: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 14995: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
14996: with @file{etags.fs}, you should avoid putting definitions both before
14997: and after @code{require} etc., otherwise you will see the same file
14998: visited several times by commands like @code{tags-search}.
1.1 anton 14999:
1.107 dvdkhlng 15000: @c ----------------------------------
15001: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15002: @section Hilighting
15003: @cindex hilighting Forth code in Emacs
15004: @cindex highlighting Forth code in Emacs
15005: @file{gforth.el} comes with a custom source hilighting engine. When
15006: you open a file in @code{forth-mode}, it will be completely parsed,
15007: assigning faces to keywords, comments, strings etc. While you edit
15008: the file, modified regions get parsed and updated on-the-fly.
15009:
15010: Use the variable `forth-hilight-level' to change the level of
15011: decoration from 0 (no hilighting at all) to 3 (the default). Even if
15012: you set the hilighting level to 0, the parser will still work in the
15013: background, collecting information about whether regions of text are
15014: ``compiled'' or ``interpreted''. Those information are required for
15015: auto-indentation to work properly. Set `forth-disable-parser' to
15016: non-nil if your computer is too slow to handle parsing. This will
15017: have an impact on the smartness of the auto-indentation engine,
15018: though.
15019:
15020: Sometimes Forth sources define new features that should be hilighted,
15021: new control structures, defining-words etc. You can use the variable
15022: `forth-custom-words' to make @code{forth-mode} hilight additional
15023: words and constructs. See the docstring of `forth-words' for details
15024: (in Emacs, type @kbd{C-h v forth-words}).
15025:
15026: `forth-custom-words' is meant to be customized in your
15027: @file{.emacs} file. To customize hilighing in a file-specific manner,
15028: set `forth-local-words' in a local-variables section at the end of
15029: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15030:
15031: Example:
15032: @example
15033: 0 [IF]
15034: Local Variables:
15035: forth-local-words:
15036: ((("t:") definition-starter (font-lock-keyword-face . 1)
15037: "[ \t\n]" t name (font-lock-function-name-face . 3))
15038: ((";t") definition-ender (font-lock-keyword-face . 1)))
15039: End:
15040: [THEN]
15041: @end example
15042:
15043: @c ----------------------------------
15044: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15045: @section Auto-Indentation
15046: @cindex auto-indentation of Forth code in Emacs
15047: @cindex indentation of Forth code in Emacs
15048: @code{forth-mode} automatically tries to indent lines in a smart way,
15049: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15050:
15051: Simple customization can be achieved by setting
15052: `forth-indent-level' and `forth-minor-indent-level' in your
15053: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15054: per default by multiples of 4 columns. To use the more traditional
15055: 3-column indentation, add the following lines to your @file{.emacs}:
15056:
15057: @example
15058: (add-hook 'forth-mode-hook (function (lambda ()
15059: ;; customize variables here:
15060: (setq forth-indent-level 3)
15061: (setq forth-minor-indent-level 1)
15062: )))
15063: @end example
15064:
15065: If you want indentation to recognize non-default words, customize it
15066: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
15067: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15068: v forth-indent-words}).
15069:
15070: To customize indentation in a file-specific manner, set
15071: `forth-local-indent-words' in a local-variables section at the end of
15072: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15073: Emacs Manual}).
15074:
15075: Example:
15076: @example
15077: 0 [IF]
15078: Local Variables:
15079: forth-local-indent-words:
15080: ((("t:") (0 . 2) (0 . 2))
15081: ((";t") (-2 . 0) (0 . -2)))
15082: End:
15083: [THEN]
15084: @end example
15085:
15086: @c ----------------------------------
1.109 anton 15087: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 15088: @section Blocks Files
15089: @cindex blocks files, use with Emacs
15090: @code{forth-mode} Autodetects blocks files by checking whether the
15091: length of the first line exceeds 1023 characters. It then tries to
15092: convert the file into normal text format. When you save the file, it
15093: will be written to disk as normal stream-source file.
15094:
15095: If you want to write blocks files, use @code{forth-blocks-mode}. It
15096: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 15097:
1.107 dvdkhlng 15098: @itemize @bullet
15099: @item
15100: Files are written to disk in blocks file format.
15101: @item
15102: Screen numbers are displayed in the mode line (enumerated beginning
15103: with the value of `forth-block-base')
15104: @item
15105: Warnings are displayed when lines exceed 64 characters.
15106: @item
15107: The beginning of the currently edited block is marked with an
15108: overlay-arrow.
15109: @end itemize
1.41 anton 15110:
1.107 dvdkhlng 15111: There are some restrictions you should be aware of. When you open a
15112: blocks file that contains tabulator or newline characters, these
15113: characters will be translated into spaces when the file is written
15114: back to disk. If tabs or newlines are encountered during blocks file
15115: reading, an error is output to the echo area. So have a look at the
15116: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 15117:
1.107 dvdkhlng 15118: Please consult the docstring of @code{forth-blocks-mode} for more
15119: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 15120:
1.26 crook 15121: @c ******************************************************************
1.1 anton 15122: @node Image Files, Engine, Emacs and Gforth, Top
15123: @chapter Image Files
1.26 crook 15124: @cindex image file
15125: @cindex @file{.fi} files
1.1 anton 15126: @cindex precompiled Forth code
15127: @cindex dictionary in persistent form
15128: @cindex persistent form of dictionary
15129:
15130: An image file is a file containing an image of the Forth dictionary,
15131: i.e., compiled Forth code and data residing in the dictionary. By
15132: convention, we use the extension @code{.fi} for image files.
15133:
15134: @menu
1.18 anton 15135: * Image Licensing Issues:: Distribution terms for images.
15136: * Image File Background:: Why have image files?
1.67 anton 15137: * Non-Relocatable Image Files:: don't always work.
1.18 anton 15138: * Data-Relocatable Image Files:: are better.
1.67 anton 15139: * Fully Relocatable Image Files:: better yet.
1.18 anton 15140: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 15141: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 15142: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 15143: @end menu
15144:
1.18 anton 15145: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15146: @section Image Licensing Issues
15147: @cindex license for images
15148: @cindex image license
15149:
15150: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15151: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15152: original image; i.e., according to copyright law it is a derived work of
15153: the original image.
15154:
15155: Since Gforth is distributed under the GNU GPL, the newly created image
15156: falls under the GNU GPL, too. In particular, this means that if you
15157: distribute the image, you have to make all of the sources for the image
1.113 anton 15158: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 15159: GNU General Public License (Section 3)}.
15160:
15161: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15162: contains only code compiled from the sources you gave it; if none of
15163: these sources is under the GPL, the terms discussed above do not apply
15164: to the image. However, if your image needs an engine (a gforth binary)
15165: that is under the GPL, you should make sure that you distribute both in
15166: a way that is at most a @emph{mere aggregation}, if you don't want the
15167: terms of the GPL to apply to the image.
15168:
15169: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 15170: @section Image File Background
15171: @cindex image file background
15172:
1.80 anton 15173: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 15174: definitions written in Forth. Since the Forth compiler itself belongs to
15175: those definitions, it is not possible to start the system with the
1.80 anton 15176: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 15177: code as an image file in nearly executable form. When Gforth starts up,
15178: a C routine loads the image file into memory, optionally relocates the
15179: addresses, then sets up the memory (stacks etc.) according to
15180: information in the image file, and (finally) starts executing Forth
15181: code.
1.1 anton 15182:
1.204 anton 15183: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15184: You can use a different image by using the @code{-i},
15185: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15186: Gforth}), e.g.:
15187:
15188: @example
15189: gforth-fast -i myimage.fi
15190: @end example
15191:
15192: There are different variants of image files, and they represent
15193: different compromises between the goals of making it easy to generate
15194: image files and making them portable.
1.1 anton 15195:
15196: @cindex relocation at run-time
1.26 crook 15197: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15198: run-time. This avoids many of the complications discussed below (image
15199: files are data relocatable without further ado), but costs performance
1.204 anton 15200: (one addition per memory access) and makes it difficult to pass
15201: addresses between Forth and library calls or other programs.
1.1 anton 15202:
15203: @cindex relocation at load-time
1.26 crook 15204: By contrast, the Gforth loader performs relocation at image load time. The
15205: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15206: appropriate code-field addresses (or code addresses in the case of
15207: direct threading).
15208:
15209: There are three kinds of image files, with different degrees of
15210: relocatability: non-relocatable, data-relocatable, and fully relocatable
15211: image files.
15212:
15213: @cindex image file loader
15214: @cindex relocating loader
15215: @cindex loader for image files
15216: These image file variants have several restrictions in common; they are
15217: caused by the design of the image file loader:
15218:
15219: @itemize @bullet
15220: @item
15221: There is only one segment; in particular, this means, that an image file
15222: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15223: them). The contents of the stacks are not represented, either.
1.1 anton 15224:
15225: @item
15226: The only kinds of relocation supported are: adding the same offset to
15227: all cells that represent data addresses; and replacing special tokens
15228: with code addresses or with pieces of machine code.
15229:
15230: If any complex computations involving addresses are performed, the
15231: results cannot be represented in the image file. Several applications that
15232: use such computations come to mind:
1.204 anton 15233:
1.1 anton 15234: @itemize @minus
15235: @item
15236: Hashing addresses (or data structures which contain addresses) for table
15237: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15238: purpose, you will have no problem, because the hash tables are
15239: recomputed automatically when the system is started. If you use your own
15240: hash tables, you will have to do something similar.
15241:
15242: @item
15243: There's a cute implementation of doubly-linked lists that uses
15244: @code{XOR}ed addresses. You could represent such lists as singly-linked
15245: in the image file, and restore the doubly-linked representation on
15246: startup.@footnote{In my opinion, though, you should think thrice before
15247: using a doubly-linked list (whatever implementation).}
15248:
15249: @item
15250: The code addresses of run-time routines like @code{docol:} cannot be
15251: represented in the image file (because their tokens would be replaced by
15252: machine code in direct threaded implementations). As a workaround,
15253: compute these addresses at run-time with @code{>code-address} from the
15254: executions tokens of appropriate words (see the definitions of
1.80 anton 15255: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15256:
15257: @item
15258: On many architectures addresses are represented in machine code in some
15259: shifted or mangled form. You cannot put @code{CODE} words that contain
15260: absolute addresses in this form in a relocatable image file. Workarounds
15261: are representing the address in some relative form (e.g., relative to
15262: the CFA, which is present in some register), or loading the address from
15263: a place where it is stored in a non-mangled form.
15264: @end itemize
15265: @end itemize
15266:
15267: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15268: @section Non-Relocatable Image Files
15269: @cindex non-relocatable image files
1.26 crook 15270: @cindex image file, non-relocatable
1.1 anton 15271:
1.204 anton 15272: These files are simple memory dumps of the dictionary. They are
15273: specific to the executable (i.e., @file{gforth} file) they were
15274: created with. What's worse, they are specific to the place on which
15275: the dictionary resided when the image was created. Now, there is no
1.1 anton 15276: guarantee that the dictionary will reside at the same place the next
15277: time you start Gforth, so there's no guarantee that a non-relocatable
1.204 anton 15278: image will work the next time (Gforth will complain instead of
15279: crashing, though). Indeed, on OSs with (enabled) address-space
15280: randomization non-relocatable images are unlikely to work.
1.1 anton 15281:
1.204 anton 15282: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1 anton 15283:
1.204 anton 15284: @example
15285: gforth app.fs -e "savesystem app.fi bye"
15286: @end example
1.44 crook 15287:
1.1 anton 15288: doc-savesystem
15289:
1.44 crook 15290:
1.1 anton 15291: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15292: @section Data-Relocatable Image Files
15293: @cindex data-relocatable image files
1.26 crook 15294: @cindex image file, data-relocatable
1.1 anton 15295:
1.204 anton 15296: These files contain relocatable data addresses, but fixed code
15297: addresses (instead of tokens). They are specific to the executable
15298: (i.e., @file{gforth} file) they were created with. Also, they disable
15299: dynamic native code generation (typically a factor of 2 in speed).
15300: You get a data-relocatable image, if you pass the engine you want to
15301: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15302: (@pxref{gforthmi}), e.g.
15303:
15304: @example
15305: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15306: @end example
15307:
15308: Note that the @code{--no-dynamic} is required here for the image to
15309: work (otherwise it will contain references to dynamically generated
15310: code that is not saved in the image).
15311:
1.1 anton 15312:
15313: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15314: @section Fully Relocatable Image Files
15315: @cindex fully relocatable image files
1.26 crook 15316: @cindex image file, fully relocatable
1.1 anton 15317:
15318: @cindex @file{kern*.fi}, relocatability
15319: @cindex @file{gforth.fi}, relocatability
15320: These image files have relocatable data addresses, and tokens for code
15321: addresses. They can be used with different binaries (e.g., with and
15322: without debugging) on the same machine, and even across machines with
1.204 anton 15323: the same data formats (byte order, cell size, floating point format),
15324: and they work with dynamic native code generation. However, they are
15325: usually specific to the version of Gforth they were created with. The
15326: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1 anton 15327:
15328: There are two ways to create a fully relocatable image file:
15329:
15330: @menu
1.29 crook 15331: * gforthmi:: The normal way
1.1 anton 15332: * cross.fs:: The hard way
15333: @end menu
15334:
15335: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15336: @subsection @file{gforthmi}
15337: @cindex @file{comp-i.fs}
15338: @cindex @file{gforthmi}
15339:
15340: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15341: image @i{file} that contains everything you would load by invoking
15342: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15343: @example
1.29 crook 15344: gforthmi @i{file} @i{options}
1.1 anton 15345: @end example
15346:
15347: E.g., if you want to create an image @file{asm.fi} that has the file
15348: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15349: like this:
15350:
15351: @example
15352: gforthmi asm.fi asm.fs
15353: @end example
15354:
1.27 crook 15355: @file{gforthmi} is implemented as a sh script and works like this: It
15356: produces two non-relocatable images for different addresses and then
15357: compares them. Its output reflects this: first you see the output (if
1.62 crook 15358: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15359: files, then you see the output of the comparing program: It displays the
15360: offset used for data addresses and the offset used for code addresses;
1.1 anton 15361: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15362: image files, it displays a line like this:
1.1 anton 15363:
15364: @example
15365: 78DC BFFFFA50 BFFFFA40
15366: @end example
15367:
15368: This means that at offset $78dc from @code{forthstart}, one input image
15369: contains $bffffa50, and the other contains $bffffa40. Since these cells
15370: cannot be represented correctly in the output image, you should examine
15371: these places in the dictionary and verify that these cells are dead
15372: (i.e., not read before they are written).
1.39 anton 15373:
15374: @cindex --application, @code{gforthmi} option
15375: If you insert the option @code{--application} in front of the image file
15376: name, you will get an image that uses the @code{--appl-image} option
15377: instead of the @code{--image-file} option (@pxref{Invoking
15378: Gforth}). When you execute such an image on Unix (by typing the image
15379: name as command), the Gforth engine will pass all options to the image
15380: instead of trying to interpret them as engine options.
1.1 anton 15381:
1.27 crook 15382: If you type @file{gforthmi} with no arguments, it prints some usage
15383: instructions.
15384:
1.1 anton 15385: @cindex @code{savesystem} during @file{gforthmi}
15386: @cindex @code{bye} during @file{gforthmi}
15387: @cindex doubly indirect threaded code
1.44 crook 15388: @cindex environment variables
15389: @cindex @code{GFORTHD} -- environment variable
15390: @cindex @code{GFORTH} -- environment variable
1.1 anton 15391: @cindex @code{gforth-ditc}
1.29 crook 15392: There are a few wrinkles: After processing the passed @i{options}, the
1.204 anton 15393: words @code{savesystem} and @code{bye} must be visible. A special
15394: doubly indirect threaded version of the @file{gforth} executable is
15395: used for creating the non-relocatable images; you can pass the exact
15396: filename of this executable through the environment variable
15397: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15398: that is not doubly indirect threaded, you will not get a fully
15399: relocatable image, but a data-relocatable image
15400: (@pxref{Data-Relocatable Image Files}), because there is no code
15401: address offset). The normal @file{gforth} executable is used for
15402: creating the relocatable image; you can pass the exact filename of
15403: this executable through the environment variable @code{GFORTH}.
1.1 anton 15404:
15405: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15406: @subsection @file{cross.fs}
15407: @cindex @file{cross.fs}
15408: @cindex cross-compiler
15409: @cindex metacompiler
1.47 crook 15410: @cindex target compiler
1.1 anton 15411:
15412: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15413: programming language (@pxref{Cross Compiler}).
1.1 anton 15414:
1.47 crook 15415: @code{cross} allows you to create image files for machines with
1.1 anton 15416: different data sizes and data formats than the one used for generating
15417: the image file. You can also use it to create an application image that
15418: does not contain a Forth compiler. These features are bought with
15419: restrictions and inconveniences in programming. E.g., addresses have to
15420: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15421: order to make the code relocatable.
15422:
15423:
15424: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15425: @section Stack and Dictionary Sizes
15426: @cindex image file, stack and dictionary sizes
15427: @cindex dictionary size default
15428: @cindex stack size default
15429:
15430: If you invoke Gforth with a command line flag for the size
15431: (@pxref{Invoking Gforth}), the size you specify is stored in the
15432: dictionary. If you save the dictionary with @code{savesystem} or create
15433: an image with @file{gforthmi}, this size will become the default
15434: for the resulting image file. E.g., the following will create a
1.21 crook 15435: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15436:
15437: @example
15438: gforthmi gforth.fi -m 1M
15439: @end example
15440:
15441: In other words, if you want to set the default size for the dictionary
15442: and the stacks of an image, just invoke @file{gforthmi} with the
15443: appropriate options when creating the image.
15444:
15445: @cindex stack size, cache-friendly
15446: Note: For cache-friendly behaviour (i.e., good performance), you should
15447: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15448: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15449: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15450:
15451: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15452: @section Running Image Files
15453: @cindex running image files
15454: @cindex invoking image files
15455: @cindex image file invocation
15456:
15457: @cindex -i, invoke image file
15458: @cindex --image file, invoke image file
1.29 crook 15459: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15460: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15461: @example
1.29 crook 15462: gforth -i @i{image}
1.1 anton 15463: @end example
15464:
15465: @cindex executable image file
1.26 crook 15466: @cindex image file, executable
1.1 anton 15467: If your operating system supports starting scripts with a line of the
15468: form @code{#! ...}, you just have to type the image file name to start
15469: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15470: just a convention). I.e., to run Gforth with the image file @i{image},
15471: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15472: This works because every @code{.fi} file starts with a line of this
15473: format:
15474:
15475: @example
15476: #! /usr/local/bin/gforth-0.4.0 -i
15477: @end example
15478:
15479: The file and pathname for the Gforth engine specified on this line is
15480: the specific Gforth executable that it was built against; i.e. the value
15481: of the environment variable @code{GFORTH} at the time that
15482: @file{gforthmi} was executed.
1.1 anton 15483:
1.27 crook 15484: You can make use of the same shell capability to make a Forth source
15485: file into an executable. For example, if you place this text in a file:
1.26 crook 15486:
15487: @example
15488: #! /usr/local/bin/gforth
15489:
15490: ." Hello, world" CR
15491: bye
15492: @end example
15493:
15494: @noindent
1.27 crook 15495: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15496: directly from the command line. The sequence @code{#!} is used in two
15497: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15498: system@footnote{The Unix kernel actually recognises two types of files:
15499: executable files and files of data, where the data is processed by an
15500: interpreter that is specified on the ``interpreter line'' -- the first
15501: line of the file, starting with the sequence #!. There may be a small
15502: limit (e.g., 32) on the number of characters that may be specified on
15503: the interpreter line.} secondly it is treated as a comment character by
15504: Gforth. Because of the second usage, a space is required between
1.80 anton 15505: @code{#!} and the path to the executable (moreover, some Unixes
15506: require the sequence @code{#! /}).
1.27 crook 15507:
15508: The disadvantage of this latter technique, compared with using
1.80 anton 15509: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15510: compiled on-the-fly, each time the program is invoked.
1.26 crook 15511:
1.1 anton 15512: doc-#!
15513:
1.44 crook 15514:
1.1 anton 15515: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15516: @section Modifying the Startup Sequence
15517: @cindex startup sequence for image file
15518: @cindex image file initialization sequence
15519: @cindex initialization sequence of image file
15520:
1.120 anton 15521: You can add your own initialization to the startup sequence of an image
15522: through the deferred word @code{'cold}. @code{'cold} is invoked just
15523: before the image-specific command line processing (i.e., loading files
15524: and evaluating (@code{-e}) strings) starts.
1.1 anton 15525:
15526: A sequence for adding your initialization usually looks like this:
15527:
15528: @example
15529: :noname
15530: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15531: ... \ your stuff
15532: ; IS 'cold
15533: @end example
15534:
1.157 anton 15535: After @code{'cold}, Gforth processes the image options
15536: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15537: another deferred word. This normally prints Gforth's startup message
15538: and does nothing else.
15539:
1.1 anton 15540: @cindex turnkey image files
1.26 crook 15541: @cindex image file, turnkey applications
1.157 anton 15542: So, if you want to make a turnkey image (i.e., an image for an
15543: application instead of an extended Forth system), you can do this in
15544: two ways:
15545:
15546: @itemize @bullet
15547:
15548: @item
15549: If you want to do your interpretation of the OS command-line
15550: arguments, hook into @code{'cold}. In that case you probably also
15551: want to build the image with @code{gforthmi --application}
15552: (@pxref{gforthmi}) to keep the engine from processing OS command line
15553: options. You can then do your own command-line processing with
15554: @code{next-arg}
15555:
15556: @item
15557: If you want to have the normal Gforth processing of OS command-line
15558: arguments, hook into @code{bootmessage}.
15559:
15560: @end itemize
15561:
15562: In either case, you probably do not want the word that you execute in
15563: these hooks to exit normally, but use @code{bye} or @code{throw}.
15564: Otherwise the Gforth startup process would continue and eventually
15565: present the Forth command line to the user.
1.26 crook 15566:
15567: doc-'cold
1.157 anton 15568: doc-bootmessage
1.44 crook 15569:
1.1 anton 15570: @c ******************************************************************
1.113 anton 15571: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15572: @chapter Engine
15573: @cindex engine
15574: @cindex virtual machine
15575:
1.26 crook 15576: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15577: may be helpful for finding your way in the Gforth sources.
15578:
1.109 anton 15579: The ideas in this section have also been published in the following
15580: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15581: Forth-Tagung '93; M. Anton Ertl,
15582: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15583: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15584: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15585: Threaded code variations and optimizations (extended version)}},
15586: Forth-Tagung '02.
1.1 anton 15587:
15588: @menu
15589: * Portability::
15590: * Threading::
15591: * Primitives::
15592: * Performance::
15593: @end menu
15594:
15595: @node Portability, Threading, Engine, Engine
15596: @section Portability
15597: @cindex engine portability
15598:
1.26 crook 15599: An important goal of the Gforth Project is availability across a wide
15600: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15601: achieved this goal by manually coding the engine in assembly language
15602: for several then-popular processors. This approach is very
15603: labor-intensive and the results are short-lived due to progress in
15604: computer architecture.
1.1 anton 15605:
15606: @cindex C, using C for the engine
15607: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15608: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15609: particularly popular for UNIX-based Forths due to the large variety of
15610: architectures of UNIX machines. Unfortunately an implementation in C
15611: does not mix well with the goals of efficiency and with using
15612: traditional techniques: Indirect or direct threading cannot be expressed
15613: in C, and switch threading, the fastest technique available in C, is
15614: significantly slower. Another problem with C is that it is very
15615: cumbersome to express double integer arithmetic.
15616:
15617: @cindex GNU C for the engine
15618: @cindex long long
15619: Fortunately, there is a portable language that does not have these
15620: limitations: GNU C, the version of C processed by the GNU C compiler
15621: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15622: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15623: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15624: threading possible, its @code{long long} type (@pxref{Long Long, ,
15625: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15626: double numbers on many systems. GNU C is freely available on all
1.1 anton 15627: important (and many unimportant) UNIX machines, VMS, 80386s running
15628: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15629: on all these machines.
15630:
15631: Writing in a portable language has the reputation of producing code that
15632: is slower than assembly. For our Forth engine we repeatedly looked at
15633: the code produced by the compiler and eliminated most compiler-induced
15634: inefficiencies by appropriate changes in the source code.
15635:
15636: @cindex explicit register declarations
15637: @cindex --enable-force-reg, configuration flag
15638: @cindex -DFORCE_REG
15639: However, register allocation cannot be portably influenced by the
15640: programmer, leading to some inefficiencies on register-starved
15641: machines. We use explicit register declarations (@pxref{Explicit Reg
15642: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15643: improve the speed on some machines. They are turned on by using the
15644: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15645: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15646: machine, but also on the compiler version: On some machines some
15647: compiler versions produce incorrect code when certain explicit register
15648: declarations are used. So by default @code{-DFORCE_REG} is not used.
15649:
15650: @node Threading, Primitives, Portability, Engine
15651: @section Threading
15652: @cindex inner interpreter implementation
15653: @cindex threaded code implementation
15654:
15655: @cindex labels as values
15656: GNU C's labels as values extension (available since @code{gcc-2.0},
15657: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15658: makes it possible to take the address of @i{label} by writing
15659: @code{&&@i{label}}. This address can then be used in a statement like
15660: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15661: @code{goto x}.
15662:
1.26 crook 15663: @cindex @code{NEXT}, indirect threaded
1.1 anton 15664: @cindex indirect threaded inner interpreter
15665: @cindex inner interpreter, indirect threaded
1.26 crook 15666: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15667: @example
15668: cfa = *ip++;
15669: ca = *cfa;
15670: goto *ca;
15671: @end example
15672: @cindex instruction pointer
15673: For those unfamiliar with the names: @code{ip} is the Forth instruction
15674: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15675: execution token and points to the code field of the next word to be
15676: executed; The @code{ca} (code address) fetched from there points to some
15677: executable code, e.g., a primitive or the colon definition handler
15678: @code{docol}.
15679:
1.26 crook 15680: @cindex @code{NEXT}, direct threaded
1.1 anton 15681: @cindex direct threaded inner interpreter
15682: @cindex inner interpreter, direct threaded
15683: Direct threading is even simpler:
15684: @example
15685: ca = *ip++;
15686: goto *ca;
15687: @end example
15688:
15689: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15690: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15691:
15692: @menu
15693: * Scheduling::
15694: * Direct or Indirect Threaded?::
1.109 anton 15695: * Dynamic Superinstructions::
1.1 anton 15696: * DOES>::
15697: @end menu
15698:
15699: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15700: @subsection Scheduling
15701: @cindex inner interpreter optimization
15702:
15703: There is a little complication: Pipelined and superscalar processors,
15704: i.e., RISC and some modern CISC machines can process independent
15705: instructions while waiting for the results of an instruction. The
15706: compiler usually reorders (schedules) the instructions in a way that
15707: achieves good usage of these delay slots. However, on our first tries
15708: the compiler did not do well on scheduling primitives. E.g., for
15709: @code{+} implemented as
15710: @example
15711: n=sp[0]+sp[1];
15712: sp++;
15713: sp[0]=n;
15714: NEXT;
15715: @end example
1.81 anton 15716: the @code{NEXT} comes strictly after the other code, i.e., there is
15717: nearly no scheduling. After a little thought the problem becomes clear:
15718: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15719: addresses (and the version of @code{gcc} we used would not know it even
15720: if it was possible), so it could not move the load of the cfa above the
15721: store to the TOS. Indeed the pointers could be the same, if code on or
15722: very near the top of stack were executed. In the interest of speed we
15723: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15724: in scheduling: @code{NEXT} is divided into several parts:
15725: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15726: like:
1.1 anton 15727: @example
1.81 anton 15728: NEXT_P0;
1.1 anton 15729: n=sp[0]+sp[1];
15730: sp++;
15731: NEXT_P1;
15732: sp[0]=n;
15733: NEXT_P2;
15734: @end example
15735:
1.81 anton 15736: There are various schemes that distribute the different operations of
15737: NEXT between these parts in several ways; in general, different schemes
15738: perform best on different processors. We use a scheme for most
15739: architectures that performs well for most processors of this
1.109 anton 15740: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15741: the scheme on installation time.
15742:
1.1 anton 15743:
1.109 anton 15744: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15745: @subsection Direct or Indirect Threaded?
15746: @cindex threading, direct or indirect?
15747:
1.109 anton 15748: Threaded forth code consists of references to primitives (simple machine
15749: code routines like @code{+}) and to non-primitives (e.g., colon
15750: definitions, variables, constants); for a specific class of
15751: non-primitives (e.g., variables) there is one code routine (e.g.,
15752: @code{dovar}), but each variable needs a separate reference to its data.
15753:
15754: Traditionally Forth has been implemented as indirect threaded code,
15755: because this allows to use only one cell to reference a non-primitive
15756: (basically you point to the data, and find the code address there).
15757:
15758: @cindex primitive-centric threaded code
15759: However, threaded code in Gforth (since 0.6.0) uses two cells for
15760: non-primitives, one for the code address, and one for the data address;
15761: the data pointer is an immediate argument for the virtual machine
15762: instruction represented by the code address. We call this
15763: @emph{primitive-centric} threaded code, because all code addresses point
15764: to simple primitives. E.g., for a variable, the code address is for
15765: @code{lit} (also used for integer literals like @code{99}).
15766:
15767: Primitive-centric threaded code allows us to use (faster) direct
15768: threading as dispatch method, completely portably (direct threaded code
15769: in Gforth before 0.6.0 required architecture-specific code). It also
15770: eliminates the performance problems related to I-cache consistency that
15771: 386 implementations have with direct threaded code, and allows
15772: additional optimizations.
15773:
15774: @cindex hybrid direct/indirect threaded code
15775: There is a catch, however: the @var{xt} parameter of @code{execute} can
15776: occupy only one cell, so how do we pass non-primitives with their code
15777: @emph{and} data addresses to them? Our answer is to use indirect
15778: threaded dispatch for @code{execute} and other words that use a
15779: single-cell xt. So, normal threaded code in colon definitions uses
15780: direct threading, and @code{execute} and similar words, which dispatch
15781: to xts on the data stack, use indirect threaded code. We call this
15782: @emph{hybrid direct/indirect} threaded code.
15783:
15784: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15785: @cindex gforth engine
15786: @cindex gforth-fast engine
15787: The engines @command{gforth} and @command{gforth-fast} use hybrid
15788: direct/indirect threaded code. This means that with these engines you
15789: cannot use @code{,} to compile an xt. Instead, you have to use
15790: @code{compile,}.
15791:
15792: @cindex gforth-itc engine
1.115 anton 15793: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15794: This engine uses plain old indirect threaded code. It still compiles in
15795: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15796: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15797: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15798: and execute @code{' , is compile,}. Your program can check if it is
15799: running on a hybrid direct/indirect threaded engine or a pure indirect
15800: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15801:
15802:
15803: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15804: @subsection Dynamic Superinstructions
15805: @cindex Dynamic superinstructions with replication
15806: @cindex Superinstructions
15807: @cindex Replication
15808:
15809: The engines @command{gforth} and @command{gforth-fast} use another
15810: optimization: Dynamic superinstructions with replication. As an
15811: example, consider the following colon definition:
15812:
15813: @example
15814: : squared ( n1 -- n2 )
15815: dup * ;
15816: @end example
15817:
15818: Gforth compiles this into the threaded code sequence
15819:
15820: @example
15821: dup
15822: *
15823: ;s
15824: @end example
15825:
15826: In normal direct threaded code there is a code address occupying one
15827: cell for each of these primitives. Each code address points to a
15828: machine code routine, and the interpreter jumps to this machine code in
15829: order to execute the primitive. The routines for these three
15830: primitives are (in @command{gforth-fast} on the 386):
15831:
15832: @example
15833: Code dup
15834: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15835: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15836: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15837: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15838: end-code
15839: Code *
15840: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15841: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15842: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15843: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15844: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15845: end-code
15846: Code ;s
15847: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15848: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15849: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15850: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15851: end-code
15852: @end example
15853:
15854: With dynamic superinstructions and replication the compiler does not
15855: just lay down the threaded code, but also copies the machine code
15856: fragments, usually without the jump at the end.
15857:
15858: @example
15859: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15860: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15861: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15862: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15863: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15864: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15865: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15866: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15867: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15868: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15869: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15870: @end example
15871:
15872: Only when a threaded-code control-flow change happens (e.g., in
15873: @code{;s}), the jump is appended. This optimization eliminates many of
15874: these jumps and makes the rest much more predictable. The speedup
15875: depends on the processor and the application; on the Athlon and Pentium
15876: III this optimization typically produces a speedup by a factor of 2.
15877:
15878: The code addresses in the direct-threaded code are set to point to the
15879: appropriate points in the copied machine code, in this example like
15880: this:
1.1 anton 15881:
1.109 anton 15882: @example
15883: primitive code address
15884: dup $4057D27D
15885: * $4057D286
15886: ;s $4057D292
15887: @end example
15888:
15889: Thus there can be threaded-code jumps to any place in this piece of
15890: code. This also simplifies decompilation quite a bit.
15891:
15892: @cindex --no-dynamic command-line option
15893: @cindex --no-super command-line option
15894: You can disable this optimization with @option{--no-dynamic}. You can
15895: use the copying without eliminating the jumps (i.e., dynamic
15896: replication, but without superinstructions) with @option{--no-super};
15897: this gives the branch prediction benefit alone; the effect on
1.110 anton 15898: performance depends on the CPU; on the Athlon and Pentium III the
15899: speedup is a little less than for dynamic superinstructions with
15900: replication.
15901:
15902: @cindex patching threaded code
15903: One use of these options is if you want to patch the threaded code.
15904: With superinstructions, many of the dispatch jumps are eliminated, so
15905: patching often has no effect. These options preserve all the dispatch
15906: jumps.
1.109 anton 15907:
15908: @cindex --dynamic command-line option
1.110 anton 15909: On some machines dynamic superinstructions are disabled by default,
15910: because it is unsafe on these machines. However, if you feel
15911: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15912:
15913: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15914: @subsection DOES>
15915: @cindex @code{DOES>} implementation
15916:
1.26 crook 15917: @cindex @code{dodoes} routine
15918: @cindex @code{DOES>}-code
1.1 anton 15919: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15920: the chunk of code executed by every word defined by a
1.109 anton 15921: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15922: this is only needed if the xt of the word is @code{execute}d. The main
15923: problem here is: How to find the Forth code to be executed, i.e. the
15924: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15925: solutions:
1.1 anton 15926:
1.21 crook 15927: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15928: @code{DOES>}-code address is stored in the cell after the code address
15929: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15930: illegal in the Forth-79 and all later standards, because in fig-Forth
15931: this address lies in the body (which is illegal in these
15932: standards). However, by making the code field larger for all words this
15933: solution becomes legal again. We use this approach. Leaving a cell
15934: unused in most words is a bit wasteful, but on the machines we are
15935: targeting this is hardly a problem.
15936:
1.1 anton 15937:
15938: @node Primitives, Performance, Threading, Engine
15939: @section Primitives
15940: @cindex primitives, implementation
15941: @cindex virtual machine instructions, implementation
15942:
15943: @menu
15944: * Automatic Generation::
15945: * TOS Optimization::
15946: * Produced code::
15947: @end menu
15948:
15949: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15950: @subsection Automatic Generation
15951: @cindex primitives, automatic generation
15952:
15953: @cindex @file{prims2x.fs}
1.109 anton 15954:
1.1 anton 15955: Since the primitives are implemented in a portable language, there is no
15956: longer any need to minimize the number of primitives. On the contrary,
15957: having many primitives has an advantage: speed. In order to reduce the
15958: number of errors in primitives and to make programming them easier, we
1.109 anton 15959: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15960: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15961: generates most (and sometimes all) of the C code for a primitive from
15962: the stack effect notation. The source for a primitive has the following
15963: form:
1.1 anton 15964:
15965: @cindex primitive source format
15966: @format
1.58 anton 15967: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15968: [@code{""}@i{glossary entry}@code{""}]
15969: @i{C code}
1.1 anton 15970: [@code{:}
1.29 crook 15971: @i{Forth code}]
1.1 anton 15972: @end format
15973:
15974: The items in brackets are optional. The category and glossary fields
15975: are there for generating the documentation, the Forth code is there
15976: for manual implementations on machines without GNU C. E.g., the source
15977: for the primitive @code{+} is:
15978: @example
1.58 anton 15979: + ( n1 n2 -- n ) core plus
1.1 anton 15980: n = n1+n2;
15981: @end example
15982:
15983: This looks like a specification, but in fact @code{n = n1+n2} is C
15984: code. Our primitive generation tool extracts a lot of information from
15985: the stack effect notations@footnote{We use a one-stack notation, even
15986: though we have separate data and floating-point stacks; The separate
15987: notation can be generated easily from the unified notation.}: The number
15988: of items popped from and pushed on the stack, their type, and by what
15989: name they are referred to in the C code. It then generates a C code
15990: prelude and postlude for each primitive. The final C code for @code{+}
15991: looks like this:
15992:
15993: @example
1.46 pazsan 15994: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 15995: /* */ /* documentation */
1.81 anton 15996: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 15997: @{
15998: DEF_CA /* definition of variable ca (indirect threading) */
15999: Cell n1; /* definitions of variables */
16000: Cell n2;
16001: Cell n;
1.81 anton 16002: NEXT_P0; /* NEXT part 0 */
1.1 anton 16003: n1 = (Cell) sp[1]; /* input */
16004: n2 = (Cell) TOS;
16005: sp += 1; /* stack adjustment */
16006: @{
16007: n = n1+n2; /* C code taken from the source */
16008: @}
16009: NEXT_P1; /* NEXT part 1 */
16010: TOS = (Cell)n; /* output */
16011: NEXT_P2; /* NEXT part 2 */
16012: @}
16013: @end example
16014:
16015: This looks long and inefficient, but the GNU C compiler optimizes quite
16016: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16017: HP RISC machines: Defining the @code{n}s does not produce any code, and
16018: using them as intermediate storage also adds no cost.
16019:
1.26 crook 16020: There are also other optimizations that are not illustrated by this
16021: example: assignments between simple variables are usually for free (copy
1.1 anton 16022: propagation). If one of the stack items is not used by the primitive
16023: (e.g. in @code{drop}), the compiler eliminates the load from the stack
16024: (dead code elimination). On the other hand, there are some things that
16025: the compiler does not do, therefore they are performed by
16026: @file{prims2x.fs}: The compiler does not optimize code away that stores
16027: a stack item to the place where it just came from (e.g., @code{over}).
16028:
16029: While programming a primitive is usually easy, there are a few cases
16030: where the programmer has to take the actions of the generator into
16031: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 16032: fall through to @code{NEXT}.
1.109 anton 16033:
16034: For more information
1.1 anton 16035:
16036: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16037: @subsection TOS Optimization
16038: @cindex TOS optimization for primitives
16039: @cindex primitives, keeping the TOS in a register
16040:
16041: An important optimization for stack machine emulators, e.g., Forth
16042: engines, is keeping one or more of the top stack items in
1.29 crook 16043: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
16044: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 16045: @itemize @bullet
16046: @item
1.29 crook 16047: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 16048: due to fewer loads from and stores to the stack.
1.29 crook 16049: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16050: @i{y<n}, due to additional moves between registers.
1.1 anton 16051: @end itemize
16052:
16053: @cindex -DUSE_TOS
16054: @cindex -DUSE_NO_TOS
16055: In particular, keeping one item in a register is never a disadvantage,
16056: if there are enough registers. Keeping two items in registers is a
16057: disadvantage for frequent words like @code{?branch}, constants,
16058: variables, literals and @code{i}. Therefore our generator only produces
16059: code that keeps zero or one items in registers. The generated C code
16060: covers both cases; the selection between these alternatives is made at
16061: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16062: code for @code{+} is just a simple variable name in the one-item case,
16063: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16064: GNU C compiler tries to keep simple variables like @code{TOS} in
16065: registers, and it usually succeeds, if there are enough registers.
16066:
16067: @cindex -DUSE_FTOS
16068: @cindex -DUSE_NO_FTOS
16069: The primitive generator performs the TOS optimization for the
16070: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16071: operations the benefit of this optimization is even larger:
16072: floating-point operations take quite long on most processors, but can be
16073: performed in parallel with other operations as long as their results are
16074: not used. If the FP-TOS is kept in a register, this works. If
16075: it is kept on the stack, i.e., in memory, the store into memory has to
16076: wait for the result of the floating-point operation, lengthening the
16077: execution time of the primitive considerably.
16078:
16079: The TOS optimization makes the automatic generation of primitives a
16080: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16081: @code{TOS} is not sufficient. There are some special cases to
16082: consider:
16083: @itemize @bullet
16084: @item In the case of @code{dup ( w -- w w )} the generator must not
16085: eliminate the store to the original location of the item on the stack,
16086: if the TOS optimization is turned on.
16087: @item Primitives with stack effects of the form @code{--}
1.29 crook 16088: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16089: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 16090: must load the TOS from the stack at the end. But for the null stack
16091: effect @code{--} no stores or loads should be generated.
16092: @end itemize
16093:
16094: @node Produced code, , TOS Optimization, Primitives
16095: @subsection Produced code
16096: @cindex primitives, assembly code listing
16097:
16098: @cindex @file{engine.s}
16099: To see what assembly code is produced for the primitives on your machine
16100: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 16101: look at the resulting file @file{engine.s}. Alternatively, you can also
16102: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 16103:
16104: @node Performance, , Primitives, Engine
16105: @section Performance
16106: @cindex performance of some Forth interpreters
16107: @cindex engine performance
16108: @cindex benchmarking Forth systems
16109: @cindex Gforth performance
16110:
16111: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 16112: impossible to write a significantly faster threaded-code engine.
1.1 anton 16113:
16114: On register-starved machines like the 386 architecture processors
16115: improvements are possible, because @code{gcc} does not utilize the
16116: registers as well as a human, even with explicit register declarations;
16117: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16118: and hand-tuned it for the 486; this system is 1.19 times faster on the
16119: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 16120: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16121: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16122: registers fit in real registers (and we can even afford to use the TOS
16123: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 16124: earlier results. And dynamic superinstructions provide another speedup
16125: (but only around a factor 1.2 on the 486).
1.1 anton 16126:
16127: @cindex Win32Forth performance
16128: @cindex NT Forth performance
16129: @cindex eforth performance
16130: @cindex ThisForth performance
16131: @cindex PFE performance
16132: @cindex TILE performance
1.81 anton 16133: The potential advantage of assembly language implementations is not
1.112 anton 16134: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 16135: (direct threaded, compiled with @code{gcc-2.95.1} and
16136: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16137: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16138: (with and without peephole (aka pinhole) optimization of the threaded
16139: code); all these systems were written in assembly language. We also
16140: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16141: with @code{gcc-2.6.3} with the default configuration for Linux:
16142: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16143: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16144: employs peephole optimization of the threaded code) and TILE (compiled
16145: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16146: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16147: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16148: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16149: then extended it to run the benchmarks, added the peephole optimizer,
16150: ran the benchmarks and reported the results.
1.40 anton 16151:
1.1 anton 16152: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16153: matrix multiplication come from the Stanford integer benchmarks and have
16154: been translated into Forth by Martin Fraeman; we used the versions
16155: included in the TILE Forth package, but with bigger data set sizes; and
16156: a recursive Fibonacci number computation for benchmarking calling
16157: performance. The following table shows the time taken for the benchmarks
16158: scaled by the time taken by Gforth (in other words, it shows the speedup
16159: factor that Gforth achieved over the other systems).
16160:
16161: @example
1.112 anton 16162: relative Win32- NT eforth This-
16163: time Gforth Forth Forth eforth +opt PFE Forth TILE
16164: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16165: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16166: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16167: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 16168: @end example
16169:
1.26 crook 16170: You may be quite surprised by the good performance of Gforth when
16171: compared with systems written in assembly language. One important reason
16172: for the disappointing performance of these other systems is probably
16173: that they are not written optimally for the 486 (e.g., they use the
16174: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16175: but costly method for relocating the Forth image: like @code{cforth}, it
16176: computes the actual addresses at run time, resulting in two address
16177: computations per @code{NEXT} (@pxref{Image File Background}).
16178:
1.1 anton 16179: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16180: explained with the self-imposed restriction of the latter systems to
16181: standard C, which makes efficient threading impossible (however, the
1.4 anton 16182: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 16183: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16184: Moreover, current C compilers have a hard time optimizing other aspects
16185: of the ThisForth and the TILE source.
16186:
1.26 crook 16187: The performance of Gforth on 386 architecture processors varies widely
16188: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16189: allocate any of the virtual machine registers into real machine
16190: registers by itself and would not work correctly with explicit register
1.112 anton 16191: declarations, giving a significantly slower engine (on a 486DX2/66
16192: running the Sieve) than the one measured above.
1.1 anton 16193:
1.26 crook 16194: Note that there have been several releases of Win32Forth since the
16195: release presented here, so the results presented above may have little
1.40 anton 16196: predictive value for the performance of Win32Forth today (results for
16197: the current release on an i486DX2/66 are welcome).
1.1 anton 16198:
16199: @cindex @file{Benchres}
1.66 anton 16200: In
16201: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16202: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 16203: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 16204: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16205: several native code systems; that version of Gforth is slower on a 486
1.112 anton 16206: than the version used here. You can find a newer version of these
16207: measurements at
1.47 crook 16208: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 16209: find numbers for Gforth on various machines in @file{Benchres}.
16210:
1.26 crook 16211: @c ******************************************************************
1.113 anton 16212: @c @node Binding to System Library, Cross Compiler, Engine, Top
16213: @c @chapter Binding to System Library
1.13 pazsan 16214:
1.113 anton 16215: @c ****************************************************************
16216: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16217: @chapter Cross Compiler
1.47 crook 16218: @cindex @file{cross.fs}
16219: @cindex cross-compiler
16220: @cindex metacompiler
16221: @cindex target compiler
1.13 pazsan 16222:
1.46 pazsan 16223: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16224: mostly written in Forth, including crucial parts like the outer
16225: interpreter and compiler, it needs compiled Forth code to get
16226: started. The cross compiler allows to create new images for other
16227: architectures, even running under another Forth system.
1.13 pazsan 16228:
16229: @menu
1.67 anton 16230: * Using the Cross Compiler::
16231: * How the Cross Compiler Works::
1.13 pazsan 16232: @end menu
16233:
1.21 crook 16234: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16235: @section Using the Cross Compiler
1.46 pazsan 16236:
16237: The cross compiler uses a language that resembles Forth, but isn't. The
16238: main difference is that you can execute Forth code after definition,
16239: while you usually can't execute the code compiled by cross, because the
16240: code you are compiling is typically for a different computer than the
16241: one you are compiling on.
16242:
1.81 anton 16243: @c anton: This chapter is somewhat different from waht I would expect: I
16244: @c would expect an explanation of the cross language and how to create an
16245: @c application image with it. The section explains some aspects of
16246: @c creating a Gforth kernel.
16247:
1.46 pazsan 16248: The Makefile is already set up to allow you to create kernels for new
16249: architectures with a simple make command. The generic kernels using the
16250: GCC compiled virtual machine are created in the normal build process
16251: with @code{make}. To create a embedded Gforth executable for e.g. the
16252: 8086 processor (running on a DOS machine), type
16253:
16254: @example
16255: make kernl-8086.fi
16256: @end example
16257:
16258: This will use the machine description from the @file{arch/8086}
16259: directory to create a new kernel. A machine file may look like that:
16260:
16261: @example
16262: \ Parameter for target systems 06oct92py
16263:
16264: 4 Constant cell \ cell size in bytes
16265: 2 Constant cell<< \ cell shift to bytes
16266: 5 Constant cell>bit \ cell shift to bits
16267: 8 Constant bits/char \ bits per character
16268: 8 Constant bits/byte \ bits per byte [default: 8]
16269: 8 Constant float \ bytes per float
16270: 8 Constant /maxalign \ maximum alignment in bytes
16271: false Constant bigendian \ byte order
16272: ( true=big, false=little )
16273:
16274: include machpc.fs \ feature list
16275: @end example
16276:
16277: This part is obligatory for the cross compiler itself, the feature list
16278: is used by the kernel to conditionally compile some features in and out,
16279: depending on whether the target supports these features.
16280:
16281: There are some optional features, if you define your own primitives,
16282: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16283: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16284: @code{prims-include} includes primitives, and @code{>boot} prepares for
16285: booting.
16286:
16287: @example
16288: : asm-include ." Include assembler" cr
16289: s" arch/8086/asm.fs" included ;
16290:
16291: : prims-include ." Include primitives" cr
16292: s" arch/8086/prim.fs" included ;
16293:
16294: : >boot ." Prepare booting" cr
16295: s" ' boot >body into-forth 1+ !" evaluate ;
16296: @end example
16297:
16298: These words are used as sort of macro during the cross compilation in
1.81 anton 16299: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16300: be possible --- but more complicated --- to write a new kernel project
16301: file, too.
16302:
16303: @file{kernel/main.fs} expects the machine description file name on the
16304: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16305: @code{mach-file} leaves a counted string on the stack, or
16306: @code{machine-file} leaves an address, count pair of the filename on the
16307: stack.
16308:
16309: The feature list is typically controlled using @code{SetValue}, generic
16310: files that are used by several projects can use @code{DefaultValue}
16311: instead. Both functions work like @code{Value}, when the value isn't
16312: defined, but @code{SetValue} works like @code{to} if the value is
16313: defined, and @code{DefaultValue} doesn't set anything, if the value is
16314: defined.
16315:
16316: @example
16317: \ generic mach file for pc gforth 03sep97jaw
16318:
16319: true DefaultValue NIL \ relocating
16320:
16321: >ENVIRON
16322:
16323: true DefaultValue file \ controls the presence of the
16324: \ file access wordset
16325: true DefaultValue OS \ flag to indicate a operating system
16326:
16327: true DefaultValue prims \ true: primitives are c-code
16328:
16329: true DefaultValue floating \ floating point wordset is present
16330:
16331: true DefaultValue glocals \ gforth locals are present
16332: \ will be loaded
16333: true DefaultValue dcomps \ double number comparisons
16334:
16335: true DefaultValue hash \ hashing primitives are loaded/present
16336:
16337: true DefaultValue xconds \ used together with glocals,
16338: \ special conditionals supporting gforths'
16339: \ local variables
16340: true DefaultValue header \ save a header information
16341:
16342: true DefaultValue backtrace \ enables backtrace code
16343:
16344: false DefaultValue ec
16345: false DefaultValue crlf
16346:
16347: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16348:
16349: &16 KB DefaultValue stack-size
16350: &15 KB &512 + DefaultValue fstack-size
16351: &15 KB DefaultValue rstack-size
16352: &14 KB &512 + DefaultValue lstack-size
16353: @end example
1.13 pazsan 16354:
1.48 anton 16355: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16356: @section How the Cross Compiler Works
1.13 pazsan 16357:
16358: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16359: @appendix Bugs
1.1 anton 16360: @cindex bug reporting
16361:
1.21 crook 16362: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16363:
1.103 anton 16364: If you find a bug, please submit a bug report through
16365: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16366:
16367: @itemize @bullet
16368: @item
1.81 anton 16369: A program (or a sequence of keyboard commands) that reproduces the bug.
16370: @item
16371: A description of what you think constitutes the buggy behaviour.
16372: @item
1.21 crook 16373: The Gforth version used (it is announced at the start of an
16374: interactive Gforth session).
16375: @item
16376: The machine and operating system (on Unix
16377: systems @code{uname -a} will report this information).
16378: @item
1.81 anton 16379: The installation options (you can find the configure options at the
16380: start of @file{config.status}) and configuration (@code{configure}
16381: output or @file{config.cache}).
1.21 crook 16382: @item
16383: A complete list of changes (if any) you (or your installer) have made to the
16384: Gforth sources.
16385: @end itemize
1.1 anton 16386:
16387: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16388: to Report Bugs, gcc.info, GNU C Manual}.
16389:
16390:
1.21 crook 16391: @node Origin, Forth-related information, Bugs, Top
16392: @appendix Authors and Ancestors of Gforth
1.1 anton 16393:
16394: @section Authors and Contributors
16395: @cindex authors of Gforth
16396: @cindex contributors to Gforth
16397:
16398: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16399: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16400: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16401: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16402: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16403: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16404: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16405: working on automatic support for calling C libraries. Helpful comments
16406: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16407: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16408: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16409: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16410: comments from many others; thank you all, sorry for not listing you
16411: here (but digging through my mailbox to extract your names is on my
16412: to-do list).
1.1 anton 16413:
16414: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16415: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16416: was developed across the Internet, and its authors did not meet
1.20 pazsan 16417: physically for the first 4 years of development.
1.1 anton 16418:
16419: @section Pedigree
1.26 crook 16420: @cindex pedigree of Gforth
1.1 anton 16421:
1.81 anton 16422: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16423: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16424:
1.20 pazsan 16425: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16426: 32 bit native code version of VolksForth for the Atari ST, written
16427: mostly by Dietrich Weineck.
16428:
1.81 anton 16429: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16430: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16431: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16432:
1.147 anton 16433: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16434: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16435:
16436: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16437: 1979. Robert Selzer and Bill Ragsdale developed the original
16438: implementation of fig-Forth for the 6502 based on microForth.
16439:
16440: The principal architect of microForth was Dean Sanderson. microForth was
16441: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16442: the 1802, and subsequently implemented on the 8080, the 6800 and the
16443: Z80.
16444:
16445: All earlier Forth systems were custom-made, usually by Charles Moore,
16446: who discovered (as he puts it) Forth during the late 60s. The first full
16447: Forth existed in 1971.
16448:
1.81 anton 16449: A part of the information in this section comes from
16450: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16451: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16452: Charles H. Moore, presented at the HOPL-II conference and preprinted
16453: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16454: genealogical information about Forth there. For a more general (and
16455: graphical) Forth family tree look see
16456: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16457: Forth Family Tree and Timeline}.
1.1 anton 16458:
1.81 anton 16459: @c ------------------------------------------------------------------
1.113 anton 16460: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16461: @appendix Other Forth-related information
16462: @cindex Forth-related information
16463:
1.81 anton 16464: @c anton: I threw most of this stuff out, because it can be found through
16465: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16466:
16467: @cindex comp.lang.forth
16468: @cindex frequently asked questions
1.81 anton 16469: There is an active news group (comp.lang.forth) discussing Forth
16470: (including Gforth) and Forth-related issues. Its
16471: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16472: (frequently asked questions and their answers) contains a lot of
16473: information on Forth. You should read it before posting to
16474: comp.lang.forth.
1.21 crook 16475:
1.81 anton 16476: The ANS Forth standard is most usable in its
16477: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16478:
1.113 anton 16479: @c ---------------------------------------------------
16480: @node Licenses, Word Index, Forth-related information, Top
16481: @appendix Licenses
16482:
16483: @menu
16484: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16485: * Copying:: GPL (for copying this software).
1.113 anton 16486: @end menu
16487:
1.192 anton 16488: @node GNU Free Documentation License, Copying, Licenses, Licenses
16489: @appendixsec GNU Free Documentation License
1.113 anton 16490: @include fdl.texi
16491:
1.192 anton 16492: @node Copying, , GNU Free Documentation License, Licenses
16493: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16494: @include gpl.texi
16495:
16496:
16497:
1.81 anton 16498: @c ------------------------------------------------------------------
1.113 anton 16499: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16500: @unnumbered Word Index
16501:
1.26 crook 16502: This index is a list of Forth words that have ``glossary'' entries
16503: within this manual. Each word is listed with its stack effect and
16504: wordset.
1.1 anton 16505:
16506: @printindex fn
16507:
1.81 anton 16508: @c anton: the name index seems superfluous given the word and concept indices.
16509:
16510: @c @node Name Index, Concept Index, Word Index, Top
16511: @c @unnumbered Name Index
1.41 anton 16512:
1.81 anton 16513: @c This index is a list of Forth words that have ``glossary'' entries
16514: @c within this manual.
1.41 anton 16515:
1.81 anton 16516: @c @printindex ky
1.41 anton 16517:
1.113 anton 16518: @c -------------------------------------------------------
1.81 anton 16519: @node Concept Index, , Word Index, Top
1.1 anton 16520: @unnumbered Concept and Word Index
16521:
1.26 crook 16522: Not all entries listed in this index are present verbatim in the
16523: text. This index also duplicates, in abbreviated form, all of the words
16524: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16525:
16526: @printindex cp
16527:
16528: @bye
1.81 anton 16529:
16530:
1.1 anton 16531:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>