Annotation of gforth/doc/gforth.ds, revision 1.212
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:
1.211 anton 2084: In Forth there are a number of combinations/abbreviations, like
2085: @code{1+}. However, @code{2/} is not one of them; it shifts its
2086: argument right by one bit (arithmetic shift right), and viewed as
2087: division that always rounds towards negative infinity (floored
2088: division). In contrast, @code{/} rounds towards zero on some systems
2089: (not on default installations of gforth (>=0.7.0), however).
1.48 anton 2090:
2091: @example
1.211 anton 2092: -5 2 / . \ -2 or -3
2093: -5 2/ . \ -3
1.48 anton 2094: @end example
2095:
2096: @code{assert(} is no standard word, but you can get it on systems other
1.198 anton 2097: than Gforth by including @file{compat/assert.fs}. You can see what it
1.48 anton 2098: does by trying
2099:
2100: @example
2101: 0 log2 .
2102: @end example
2103:
2104: Here's a loop with an exit at the end:
2105:
2106: @example
2107: : log2 ( +n1 -- n2 )
2108: \ logarithmus dualis of n1>0, rounded down to the next integer
2109: assert( dup 0 > )
2110: -1 begin
2111: 1+ swap 2/ swap
2112: over 0 <=
2113: until
2114: nip ;
2115: @end example
2116:
2117: @code{Until} consumes a flag; if it is non-zero, execution continues at
2118: the @code{begin}, otherwise after the @code{until}.
2119:
1.141 anton 2120: @quotation Assignment
1.48 anton 2121: Write a definition for computing the greatest common divisor.
1.141 anton 2122: @end quotation
1.48 anton 2123:
1.66 anton 2124: Reference: @ref{Simple Loops}.
2125:
1.48 anton 2126:
2127: @node Counted loops Tutorial, Recursion Tutorial, General Loops Tutorial, Tutorial
2128: @section Counted loops
1.66 anton 2129: @cindex loops, counted, tutorial
1.48 anton 2130:
2131: @example
2132: : ^ ( n1 u -- n )
1.171 anton 2133: \ n = the uth power of n1
1.48 anton 2134: 1 swap 0 u+do
2135: over *
2136: loop
2137: nip ;
2138: 3 2 ^ .
2139: 4 3 ^ .
2140: @end example
2141:
2142: @code{U+do} (from @file{compat/loops.fs}, if your Forth system doesn't
2143: have it) takes two numbers of the stack @code{( u3 u4 -- )}, and then
2144: performs the code between @code{u+do} and @code{loop} for @code{u3-u4}
2145: times (or not at all, if @code{u3-u4<0}).
2146:
2147: You can see the stack effect design rules at work in the stack effect of
2148: the loop start words: Since the start value of the loop is more
2149: frequently constant than the end value, the start value is passed on
2150: the top-of-stack.
2151:
2152: You can access the counter of a counted loop with @code{i}:
2153:
2154: @example
2155: : fac ( u -- u! )
2156: 1 swap 1+ 1 u+do
2157: i *
2158: loop ;
2159: 5 fac .
2160: 7 fac .
2161: @end example
2162:
2163: There is also @code{+do}, which expects signed numbers (important for
2164: deciding whether to enter the loop).
2165:
1.141 anton 2166: @quotation Assignment
1.48 anton 2167: Write a definition for computing the nth Fibonacci number.
1.141 anton 2168: @end quotation
1.48 anton 2169:
1.65 anton 2170: You can also use increments other than 1:
2171:
2172: @example
2173: : up2 ( n1 n2 -- )
2174: +do
2175: i .
2176: 2 +loop ;
2177: 10 0 up2
2178:
2179: : down2 ( n1 n2 -- )
2180: -do
2181: i .
2182: 2 -loop ;
2183: 0 10 down2
2184: @end example
1.48 anton 2185:
1.66 anton 2186: Reference: @ref{Counted Loops}.
2187:
1.48 anton 2188:
2189: @node Recursion Tutorial, Leaving definitions or loops Tutorial, Counted loops Tutorial, Tutorial
2190: @section Recursion
1.66 anton 2191: @cindex recursion tutorial
1.48 anton 2192:
2193: Usually the name of a definition is not visible in the definition; but
2194: earlier definitions are usually visible:
2195:
2196: @example
1.166 anton 2197: 1 0 / . \ "Floating-point unidentified fault" in Gforth on some platforms
1.48 anton 2198: : / ( n1 n2 -- n )
2199: dup 0= if
2200: -10 throw \ report division by zero
2201: endif
2202: / \ old version
2203: ;
2204: 1 0 /
2205: @end example
2206:
2207: For recursive definitions you can use @code{recursive} (non-standard) or
2208: @code{recurse}:
2209:
2210: @example
2211: : fac1 ( n -- n! ) recursive
2212: dup 0> if
2213: dup 1- fac1 *
2214: else
2215: drop 1
2216: endif ;
2217: 7 fac1 .
2218:
2219: : fac2 ( n -- n! )
2220: dup 0> if
2221: dup 1- recurse *
2222: else
2223: drop 1
2224: endif ;
2225: 8 fac2 .
2226: @end example
2227:
1.141 anton 2228: @quotation Assignment
1.48 anton 2229: Write a recursive definition for computing the nth Fibonacci number.
1.141 anton 2230: @end quotation
1.48 anton 2231:
1.66 anton 2232: Reference (including indirect recursion): @xref{Calls and returns}.
2233:
1.48 anton 2234:
2235: @node Leaving definitions or loops Tutorial, Return Stack Tutorial, Recursion Tutorial, Tutorial
2236: @section Leaving definitions or loops
1.66 anton 2237: @cindex leaving definitions, tutorial
2238: @cindex leaving loops, tutorial
1.48 anton 2239:
2240: @code{EXIT} exits the current definition right away. For every counted
2241: loop that is left in this way, an @code{UNLOOP} has to be performed
2242: before the @code{EXIT}:
2243:
2244: @c !! real examples
2245: @example
2246: : ...
2247: ... u+do
2248: ... if
2249: ... unloop exit
2250: endif
2251: ...
2252: loop
2253: ... ;
2254: @end example
2255:
2256: @code{LEAVE} leaves the innermost counted loop right away:
2257:
2258: @example
2259: : ...
2260: ... u+do
2261: ... if
2262: ... leave
2263: endif
2264: ...
2265: loop
2266: ... ;
2267: @end example
2268:
1.65 anton 2269: @c !! example
1.48 anton 2270:
1.66 anton 2271: Reference: @ref{Calls and returns}, @ref{Counted Loops}.
2272:
2273:
1.48 anton 2274: @node Return Stack Tutorial, Memory Tutorial, Leaving definitions or loops Tutorial, Tutorial
2275: @section Return Stack
1.66 anton 2276: @cindex return stack tutorial
1.48 anton 2277:
2278: In addition to the data stack Forth also has a second stack, the return
2279: stack; most Forth systems store the return addresses of procedure calls
2280: there (thus its name). Programmers can also use this stack:
2281:
2282: @example
2283: : foo ( n1 n2 -- )
2284: .s
2285: >r .s
1.50 anton 2286: r@@ .
1.48 anton 2287: >r .s
1.50 anton 2288: r@@ .
1.48 anton 2289: r> .
1.50 anton 2290: r@@ .
1.48 anton 2291: r> . ;
2292: 1 2 foo
2293: @end example
2294:
2295: @code{>r} takes an element from the data stack and pushes it onto the
2296: return stack; conversely, @code{r>} moves an elementm from the return to
2297: the data stack; @code{r@@} pushes a copy of the top of the return stack
1.148 anton 2298: on the data stack.
1.48 anton 2299:
2300: Forth programmers usually use the return stack for storing data
2301: temporarily, if using the data stack alone would be too complex, and
2302: factoring and locals are not an option:
2303:
2304: @example
2305: : 2swap ( x1 x2 x3 x4 -- x3 x4 x1 x2 )
2306: rot >r rot r> ;
2307: @end example
2308:
2309: The return address of the definition and the loop control parameters of
2310: counted loops usually reside on the return stack, so you have to take
2311: all items, that you have pushed on the return stack in a colon
2312: definition or counted loop, from the return stack before the definition
2313: or loop ends. You cannot access items that you pushed on the return
2314: stack outside some definition or loop within the definition of loop.
2315:
2316: If you miscount the return stack items, this usually ends in a crash:
2317:
2318: @example
2319: : crash ( n -- )
2320: >r ;
2321: 5 crash
2322: @end example
2323:
2324: You cannot mix using locals and using the return stack (according to the
2325: standard; Gforth has no problem). However, they solve the same
2326: problems, so this shouldn't be an issue.
2327:
1.141 anton 2328: @quotation Assignment
1.48 anton 2329: Can you rewrite any of the definitions you wrote until now in a better
2330: way using the return stack?
1.141 anton 2331: @end quotation
1.48 anton 2332:
1.66 anton 2333: Reference: @ref{Return stack}.
2334:
1.48 anton 2335:
2336: @node Memory Tutorial, Characters and Strings Tutorial, Return Stack Tutorial, Tutorial
2337: @section Memory
1.66 anton 2338: @cindex memory access/allocation tutorial
1.48 anton 2339:
2340: You can create a global variable @code{v} with
2341:
2342: @example
2343: variable v ( -- addr )
2344: @end example
2345:
2346: @code{v} pushes the address of a cell in memory on the stack. This cell
2347: was reserved by @code{variable}. You can use @code{!} (store) to store
2348: values into this cell and @code{@@} (fetch) to load the value from the
2349: stack into memory:
2350:
2351: @example
2352: v .
2353: 5 v ! .s
1.50 anton 2354: v @@ .
1.48 anton 2355: @end example
2356:
1.65 anton 2357: You can see a raw dump of memory with @code{dump}:
2358:
2359: @example
2360: v 1 cells .s dump
2361: @end example
2362:
2363: @code{Cells ( n1 -- n2 )} gives you the number of bytes (or, more
2364: generally, address units (aus)) that @code{n1 cells} occupy. You can
2365: also reserve more memory:
1.48 anton 2366:
2367: @example
2368: create v2 20 cells allot
1.65 anton 2369: v2 20 cells dump
1.48 anton 2370: @end example
2371:
1.212 ! anton 2372: creates a variable-like word @code{v2} and reserves 20 uninitialized
! 2373: cells; the address pushed by @code{v2} points to the start of these 20
! 2374: cells (@pxref{CREATE}). You can use address arithmetic to access
! 2375: these cells:
1.48 anton 2376:
2377: @example
2378: 3 v2 5 cells + !
1.65 anton 2379: v2 20 cells dump
1.48 anton 2380: @end example
2381:
2382: You can reserve and initialize memory with @code{,}:
2383:
2384: @example
2385: create v3
2386: 5 , 4 , 3 , 2 , 1 ,
1.50 anton 2387: v3 @@ .
2388: v3 cell+ @@ .
2389: v3 2 cells + @@ .
1.65 anton 2390: v3 5 cells dump
1.48 anton 2391: @end example
2392:
1.141 anton 2393: @quotation Assignment
1.48 anton 2394: Write a definition @code{vsum ( addr u -- n )} that computes the sum of
2395: @code{u} cells, with the first of these cells at @code{addr}, the next
2396: one at @code{addr cell+} etc.
1.141 anton 2397: @end quotation
1.48 anton 2398:
2399: You can also reserve memory without creating a new word:
2400:
2401: @example
1.60 anton 2402: here 10 cells allot .
2403: here .
1.48 anton 2404: @end example
2405:
1.211 anton 2406: The first @code{here} pushes the start address of the memory area, the
2407: second @code{here} the address after the dictionary area. You should
2408: store the start address somewhere, or you will have a hard time
2409: finding the memory area again.
1.48 anton 2410:
2411: @code{Allot} manages dictionary memory. The dictionary memory contains
2412: the system's data structures for words etc. on Gforth and most other
2413: Forth systems. It is managed like a stack: You can free the memory that
2414: you have just @code{allot}ed with
2415:
2416: @example
2417: -10 cells allot
1.60 anton 2418: here .
1.48 anton 2419: @end example
2420:
2421: Note that you cannot do this if you have created a new word in the
2422: meantime (because then your @code{allot}ed memory is no longer on the
2423: top of the dictionary ``stack'').
2424:
2425: Alternatively, you can use @code{allocate} and @code{free} which allow
2426: freeing memory in any order:
2427:
2428: @example
2429: 10 cells allocate throw .s
2430: 20 cells allocate throw .s
2431: swap
2432: free throw
2433: free throw
2434: @end example
2435:
2436: The @code{throw}s deal with errors (e.g., out of memory).
2437:
1.65 anton 2438: And there is also a
2439: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
2440: garbage collector}, which eliminates the need to @code{free} memory
2441: explicitly.
1.48 anton 2442:
1.66 anton 2443: Reference: @ref{Memory}.
2444:
1.48 anton 2445:
2446: @node Characters and Strings Tutorial, Alignment Tutorial, Memory Tutorial, Tutorial
2447: @section Characters and Strings
1.66 anton 2448: @cindex strings tutorial
2449: @cindex characters tutorial
1.48 anton 2450:
2451: On the stack characters take up a cell, like numbers. In memory they
2452: have their own size (one 8-bit byte on most systems), and therefore
2453: require their own words for memory access:
2454:
2455: @example
2456: create v4
2457: 104 c, 97 c, 108 c, 108 c, 111 c,
1.50 anton 2458: v4 4 chars + c@@ .
1.65 anton 2459: v4 5 chars dump
1.48 anton 2460: @end example
2461:
2462: The preferred representation of strings on the stack is @code{addr
2463: u-count}, where @code{addr} is the address of the first character and
2464: @code{u-count} is the number of characters in the string.
2465:
2466: @example
2467: v4 5 type
2468: @end example
2469:
2470: You get a string constant with
2471:
2472: @example
2473: s" hello, world" .s
2474: type
2475: @end example
2476:
2477: Make sure you have a space between @code{s"} and the string; @code{s"}
2478: is a normal Forth word and must be delimited with white space (try what
2479: happens when you remove the space).
2480:
2481: However, this interpretive use of @code{s"} is quite restricted: the
2482: string exists only until the next call of @code{s"} (some Forth systems
2483: keep more than one of these strings, but usually they still have a
1.62 crook 2484: limited lifetime).
1.48 anton 2485:
2486: @example
2487: s" hello," s" world" .s
2488: type
2489: type
2490: @end example
2491:
1.62 crook 2492: You can also use @code{s"} in a definition, and the resulting
2493: strings then live forever (well, for as long as the definition):
1.48 anton 2494:
2495: @example
2496: : foo s" hello," s" world" ;
2497: foo .s
2498: type
2499: type
2500: @end example
2501:
1.141 anton 2502: @quotation Assignment
1.48 anton 2503: @code{Emit ( c -- )} types @code{c} as character (not a number).
2504: Implement @code{type ( addr u -- )}.
1.141 anton 2505: @end quotation
1.48 anton 2506:
1.66 anton 2507: Reference: @ref{Memory Blocks}.
2508:
2509:
1.190 anton 2510: @node Alignment Tutorial, Floating Point Tutorial, Characters and Strings Tutorial, Tutorial
1.48 anton 2511: @section Alignment
1.66 anton 2512: @cindex alignment tutorial
2513: @cindex memory alignment tutorial
1.48 anton 2514:
2515: On many processors cells have to be aligned in memory, if you want to
2516: access them with @code{@@} and @code{!} (and even if the processor does
1.62 crook 2517: not require alignment, access to aligned cells is faster).
1.48 anton 2518:
2519: @code{Create} aligns @code{here} (i.e., the place where the next
2520: allocation will occur, and that the @code{create}d word points to).
2521: Likewise, the memory produced by @code{allocate} starts at an aligned
2522: address. Adding a number of @code{cells} to an aligned address produces
2523: another aligned address.
2524:
2525: However, address arithmetic involving @code{char+} and @code{chars} can
2526: create an address that is not cell-aligned. @code{Aligned ( addr --
2527: a-addr )} produces the next aligned address:
2528:
2529: @example
1.50 anton 2530: v3 char+ aligned .s @@ .
2531: v3 char+ .s @@ .
1.48 anton 2532: @end example
2533:
2534: Similarly, @code{align} advances @code{here} to the next aligned
2535: address:
2536:
2537: @example
2538: create v5 97 c,
2539: here .
2540: align here .
2541: 1000 ,
2542: @end example
2543:
2544: Note that you should use aligned addresses even if your processor does
2545: not require them, if you want your program to be portable.
2546:
1.66 anton 2547: Reference: @ref{Address arithmetic}.
2548:
1.190 anton 2549: @node Floating Point Tutorial, Files Tutorial, Alignment Tutorial, Tutorial
2550: @section Floating Point
2551: @cindex floating point tutorial
2552: @cindex FP tutorial
2553:
2554: Floating-point (FP) numbers and arithmetic in Forth works mostly as one
2555: might expect, but there are a few things worth noting:
2556:
2557: The first point is not specific to Forth, but so important and yet not
2558: universally known that I mention it here: FP numbers are not reals.
2559: Many properties (e.g., arithmetic laws) that reals have and that one
2560: expects of all kinds of numbers do not hold for FP numbers. If you
2561: want to use FP computations, you should learn about their problems and
2562: how to avoid them; a good starting point is @cite{David Goldberg,
2563: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
2564: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
2565: Computing Surveys 23(1):5@minus{}48, March 1991}.
2566:
2567: In Forth source code literal FP numbers need an exponent, e.g.,
1.210 anton 2568: @code{1e0}; this can also be written shorter as @code{1e}, longer as
2569: @code{+1.0e+0}, and many variations in between. The reason for this is
2570: that, for historical reasons, Forth interprets a decimal point alone
2571: (e.g., @code{1.}) as indicating a double-cell integer. Examples:
2572:
2573: @example
2574: 2e 2e f+ f.
2575: @end example
2576:
2577: Another requirement for literal FP numbers is that the current base is
1.190 anton 2578: decimal; with a hex base @code{1e} is interpreted as an integer.
2579:
2580: Forth has a separate stack for FP numbers.@footnote{Theoretically, an
2581: ANS Forth system may implement the FP stack on the data stack, but
2582: virtually all systems implement a separate FP stack; and programming
2583: in a way that accommodates all models is so cumbersome that nobody
2584: does it.} One advantage of this model is that cells are not in the
2585: way when accessing FP values, and vice versa. Forth has a set of
2586: words for manipulating the FP stack: @code{fdup fswap fdrop fover
2587: frot} and (non-standard) @code{fnip ftuck fpick}.
2588:
2589: FP arithmetic words are prefixed with @code{F}. There is the usual
2590: set @code{f+ f- f* f/ f** fnegate} as well as a number of words for
2591: other functions, e.g., @code{fsqrt fsin fln fmin}. One word that you
2592: might expect is @code{f=}; but @code{f=} is non-standard, because FP
2593: computation results are usually inaccurate, so exact comparison is
2594: usually a mistake, and one should use approximate comparison.
2595: Unfortunately, @code{f~}, the standard word for that purpose, is not
2596: well designed, so Gforth provides @code{f~abs} and @code{f~rel} as
2597: well.
2598:
2599: And of course there are words for accessing FP numbers in memory
2600: (@code{f@@ f!}), and for address arithmetic (@code{floats float+
2601: faligned}). There are also variants of these words with an @code{sf}
2602: and @code{df} prefix for accessing IEEE format single-precision and
2603: double-precision numbers in memory; their main purpose is for
2604: accessing external FP data (e.g., that has been read from or will be
2605: written to a file).
2606:
2607: Here is an example of a dot-product word and its use:
2608:
2609: @example
2610: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
2611: >r swap 2swap swap 0e r> 0 ?DO
2612: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
2613: LOOP
2614: 2drop 2drop ;
1.48 anton 2615:
1.190 anton 2616: create v 1.23e f, 4.56e f, 7.89e f,
2617:
2618: v 1 floats v 1 floats 3 v* f.
2619: @end example
2620:
2621: @quotation Assignment
2622: Write a program to solve a quadratic equation. Then read @cite{Henry
2623: G. Baker,
2624: @uref{http://home.pipeline.com/~hbaker1/sigplannotices/sigcol05.ps.gz,You
2625: Could Learn a Lot from a Quadratic}, ACM SIGPLAN Notices,
2626: 33(1):30@minus{}39, January 1998}, and see if you can improve your
2627: program. Finally, find a test case where the original and the
2628: improved version produce different results.
2629: @end quotation
2630:
2631: Reference: @ref{Floating Point}; @ref{Floating point stack};
2632: @ref{Number Conversion}; @ref{Memory Access}; @ref{Address
2633: arithmetic}.
2634:
2635: @node Files Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Floating Point Tutorial, Tutorial
1.84 pazsan 2636: @section Files
2637: @cindex files tutorial
2638:
2639: This section gives a short introduction into how to use files inside
2640: Forth. It's broken up into five easy steps:
2641:
2642: @enumerate 1
2643: @item Opened an ASCII text file for input
2644: @item Opened a file for output
2645: @item Read input file until string matched (or some other condition matched)
2646: @item Wrote some lines from input ( modified or not) to output
2647: @item Closed the files.
2648: @end enumerate
2649:
1.153 anton 2650: Reference: @ref{General files}.
2651:
1.84 pazsan 2652: @subsection Open file for input
2653:
2654: @example
2655: s" foo.in" r/o open-file throw Value fd-in
2656: @end example
2657:
2658: @subsection Create file for output
2659:
2660: @example
2661: s" foo.out" w/o create-file throw Value fd-out
2662: @end example
2663:
2664: The available file modes are r/o for read-only access, r/w for
2665: read-write access, and w/o for write-only access. You could open both
2666: files with r/w, too, if you like. All file words return error codes; for
2667: most applications, it's best to pass there error codes with @code{throw}
2668: to the outer error handler.
2669:
2670: If you want words for opening and assigning, define them as follows:
2671:
2672: @example
2673: 0 Value fd-in
2674: 0 Value fd-out
2675: : open-input ( addr u -- ) r/o open-file throw to fd-in ;
2676: : open-output ( addr u -- ) w/o create-file throw to fd-out ;
2677: @end example
2678:
2679: Usage example:
2680:
2681: @example
2682: s" foo.in" open-input
2683: s" foo.out" open-output
2684: @end example
2685:
2686: @subsection Scan file for a particular line
2687:
2688: @example
2689: 256 Constant max-line
2690: Create line-buffer max-line 2 + allot
2691:
2692: : scan-file ( addr u -- )
2693: begin
2694: line-buffer max-line fd-in read-line throw
2695: while
2696: >r 2dup line-buffer r> compare 0=
2697: until
2698: else
2699: drop
2700: then
2701: 2drop ;
2702: @end example
2703:
2704: @code{read-line ( addr u1 fd -- u2 flag ior )} reads up to u1 bytes into
1.94 anton 2705: the buffer at addr, and returns the number of bytes read, a flag that is
2706: false when the end of file is reached, and an error code.
1.84 pazsan 2707:
2708: @code{compare ( addr1 u1 addr2 u2 -- n )} compares two strings and
2709: returns zero if both strings are equal. It returns a positive number if
2710: the first string is lexically greater, a negative if the second string
2711: is lexically greater.
2712:
2713: We haven't seen this loop here; it has two exits. Since the @code{while}
2714: exits with the number of bytes read on the stack, we have to clean up
2715: that separately; that's after the @code{else}.
2716:
2717: Usage example:
2718:
2719: @example
2720: s" The text I search is here" scan-file
2721: @end example
2722:
2723: @subsection Copy input to output
2724:
2725: @example
2726: : copy-file ( -- )
2727: begin
2728: line-buffer max-line fd-in read-line throw
2729: while
1.194 anton 2730: line-buffer swap fd-out write-line throw
1.84 pazsan 2731: repeat ;
2732: @end example
1.194 anton 2733: @c !! does not handle long lines, no newline at end of file
1.84 pazsan 2734:
2735: @subsection Close files
2736:
2737: @example
2738: fd-in close-file throw
2739: fd-out close-file throw
2740: @end example
2741:
2742: Likewise, you can put that into definitions, too:
2743:
2744: @example
2745: : close-input ( -- ) fd-in close-file throw ;
2746: : close-output ( -- ) fd-out close-file throw ;
2747: @end example
2748:
1.141 anton 2749: @quotation Assignment
1.84 pazsan 2750: How could you modify @code{copy-file} so that it copies until a second line is
2751: matched? Can you write a program that extracts a section of a text file,
2752: given the line that starts and the line that terminates that section?
1.141 anton 2753: @end quotation
1.84 pazsan 2754:
2755: @node Interpretation and Compilation Semantics and Immediacy Tutorial, Execution Tokens Tutorial, Files Tutorial, Tutorial
1.48 anton 2756: @section Interpretation and Compilation Semantics and Immediacy
1.66 anton 2757: @cindex semantics tutorial
2758: @cindex interpretation semantics tutorial
2759: @cindex compilation semantics tutorial
2760: @cindex immediate, tutorial
1.48 anton 2761:
2762: When a word is compiled, it behaves differently from being interpreted.
2763: E.g., consider @code{+}:
2764:
2765: @example
2766: 1 2 + .
2767: : foo + ;
2768: @end example
2769:
2770: These two behaviours are known as compilation and interpretation
2771: semantics. For normal words (e.g., @code{+}), the compilation semantics
2772: is to append the interpretation semantics to the currently defined word
2773: (@code{foo} in the example above). I.e., when @code{foo} is executed
2774: later, the interpretation semantics of @code{+} (i.e., adding two
2775: numbers) will be performed.
2776:
2777: However, there are words with non-default compilation semantics, e.g.,
2778: the control-flow words like @code{if}. You can use @code{immediate} to
2779: change the compilation semantics of the last defined word to be equal to
2780: the interpretation semantics:
2781:
2782: @example
2783: : [FOO] ( -- )
2784: 5 . ; immediate
2785:
2786: [FOO]
2787: : bar ( -- )
2788: [FOO] ;
2789: bar
2790: see bar
2791: @end example
2792:
1.198 anton 2793: Two conventions to mark words with non-default compilation semantics are
1.48 anton 2794: names with brackets (more frequently used) and to write them all in
2795: upper case (less frequently used).
2796:
2797: In Gforth (and many other systems) you can also remove the
2798: interpretation semantics with @code{compile-only} (the compilation
2799: semantics is derived from the original interpretation semantics):
2800:
2801: @example
2802: : flip ( -- )
2803: 6 . ; compile-only \ but not immediate
2804: flip
2805:
2806: : flop ( -- )
2807: flip ;
2808: flop
2809: @end example
2810:
2811: In this example the interpretation semantics of @code{flop} is equal to
2812: the original interpretation semantics of @code{flip}.
2813:
2814: The text interpreter has two states: in interpret state, it performs the
2815: interpretation semantics of words it encounters; in compile state, it
2816: performs the compilation semantics of these words.
2817:
2818: Among other things, @code{:} switches into compile state, and @code{;}
2819: switches back to interpret state. They contain the factors @code{]}
2820: (switch to compile state) and @code{[} (switch to interpret state), that
2821: do nothing but switch the state.
2822:
2823: @example
2824: : xxx ( -- )
2825: [ 5 . ]
2826: ;
2827:
2828: xxx
2829: see xxx
2830: @end example
2831:
2832: These brackets are also the source of the naming convention mentioned
2833: above.
2834:
1.66 anton 2835: Reference: @ref{Interpretation and Compilation Semantics}.
2836:
1.48 anton 2837:
2838: @node Execution Tokens Tutorial, Exceptions Tutorial, Interpretation and Compilation Semantics and Immediacy Tutorial, Tutorial
2839: @section Execution Tokens
1.66 anton 2840: @cindex execution tokens tutorial
2841: @cindex XT tutorial
1.48 anton 2842:
2843: @code{' word} gives you the execution token (XT) of a word. The XT is a
2844: cell representing the interpretation semantics of a word. You can
2845: execute this semantics with @code{execute}:
2846:
2847: @example
2848: ' + .s
2849: 1 2 rot execute .
2850: @end example
2851:
2852: The XT is similar to a function pointer in C. However, parameter
2853: passing through the stack makes it a little more flexible:
2854:
2855: @example
2856: : map-array ( ... addr u xt -- ... )
1.50 anton 2857: \ executes xt ( ... x -- ... ) for every element of the array starting
2858: \ at addr and containing u elements
1.48 anton 2859: @{ xt @}
2860: cells over + swap ?do
1.50 anton 2861: i @@ xt execute
1.48 anton 2862: 1 cells +loop ;
2863:
2864: create a 3 , 4 , 2 , -1 , 4 ,
2865: a 5 ' . map-array .s
2866: 0 a 5 ' + map-array .
2867: s" max-n" environment? drop .s
2868: a 5 ' min map-array .
2869: @end example
2870:
2871: You can use map-array with the XTs of words that consume one element
2872: more than they produce. In theory you can also use it with other XTs,
2873: but the stack effect then depends on the size of the array, which is
2874: hard to understand.
2875:
1.51 pazsan 2876: Since XTs are cell-sized, you can store them in memory and manipulate
2877: them on the stack like other cells. You can also compile the XT into a
1.48 anton 2878: word with @code{compile,}:
2879:
2880: @example
2881: : foo1 ( n1 n2 -- n )
2882: [ ' + compile, ] ;
2883: see foo
2884: @end example
2885:
2886: This is non-standard, because @code{compile,} has no compilation
2887: semantics in the standard, but it works in good Forth systems. For the
2888: broken ones, use
2889:
2890: @example
2891: : [compile,] compile, ; immediate
2892:
2893: : foo1 ( n1 n2 -- n )
2894: [ ' + ] [compile,] ;
2895: see foo
2896: @end example
2897:
2898: @code{'} is a word with default compilation semantics; it parses the
2899: next word when its interpretation semantics are executed, not during
2900: compilation:
2901:
2902: @example
2903: : foo ( -- xt )
2904: ' ;
2905: see foo
2906: : bar ( ... "word" -- ... )
2907: ' execute ;
2908: see bar
1.60 anton 2909: 1 2 bar + .
1.48 anton 2910: @end example
2911:
2912: You often want to parse a word during compilation and compile its XT so
2913: it will be pushed on the stack at run-time. @code{[']} does this:
2914:
2915: @example
2916: : xt-+ ( -- xt )
2917: ['] + ;
2918: see xt-+
2919: 1 2 xt-+ execute .
2920: @end example
2921:
2922: Many programmers tend to see @code{'} and the word it parses as one
2923: unit, and expect it to behave like @code{[']} when compiled, and are
2924: confused by the actual behaviour. If you are, just remember that the
2925: Forth system just takes @code{'} as one unit and has no idea that it is
2926: a parsing word (attempts to convenience programmers in this issue have
2927: usually resulted in even worse pitfalls, see
1.66 anton 2928: @uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,
2929: @code{State}-smartness---Why it is evil and How to Exorcise it}).
1.48 anton 2930:
2931: Note that the state of the interpreter does not come into play when
1.51 pazsan 2932: creating and executing XTs. I.e., even when you execute @code{'} in
1.48 anton 2933: compile state, it still gives you the interpretation semantics. And
2934: whatever that state is, @code{execute} performs the semantics
1.66 anton 2935: represented by the XT (i.e., for XTs produced with @code{'} the
2936: interpretation semantics).
2937:
2938: Reference: @ref{Tokens for Words}.
1.48 anton 2939:
2940:
2941: @node Exceptions Tutorial, Defining Words Tutorial, Execution Tokens Tutorial, Tutorial
2942: @section Exceptions
1.66 anton 2943: @cindex exceptions tutorial
1.48 anton 2944:
2945: @code{throw ( n -- )} causes an exception unless n is zero.
2946:
2947: @example
2948: 100 throw .s
2949: 0 throw .s
2950: @end example
2951:
2952: @code{catch ( ... xt -- ... n )} behaves similar to @code{execute}, but
2953: it catches exceptions and pushes the number of the exception on the
2954: stack (or 0, if the xt executed without exception). If there was an
2955: exception, the stacks have the same depth as when entering @code{catch}:
2956:
2957: @example
2958: .s
2959: 3 0 ' / catch .s
2960: 3 2 ' / catch .s
2961: @end example
2962:
1.141 anton 2963: @quotation Assignment
1.48 anton 2964: Try the same with @code{execute} instead of @code{catch}.
1.141 anton 2965: @end quotation
1.48 anton 2966:
2967: @code{Throw} always jumps to the dynamically next enclosing
2968: @code{catch}, even if it has to leave several call levels to achieve
2969: this:
2970:
2971: @example
2972: : foo 100 throw ;
2973: : foo1 foo ." after foo" ;
1.51 pazsan 2974: : bar ['] foo1 catch ;
1.60 anton 2975: bar .
1.48 anton 2976: @end example
2977:
2978: It is often important to restore a value upon leaving a definition, even
2979: if the definition is left through an exception. You can ensure this
2980: like this:
2981:
2982: @example
2983: : ...
2984: save-x
1.51 pazsan 2985: ['] word-changing-x catch ( ... n )
1.48 anton 2986: restore-x
2987: ( ... n ) throw ;
2988: @end example
2989:
1.172 anton 2990: However, this is still not safe against, e.g., the user pressing
2991: @kbd{Ctrl-C} when execution is between the @code{catch} and
2992: @code{restore-x}.
2993:
2994: Gforth provides an alternative exception handling syntax that is safe
2995: against such cases: @code{try ... restore ... endtry}. If the code
2996: between @code{try} and @code{endtry} has an exception, the stack
2997: depths are restored, the exception number is pushed on the stack, and
2998: the execution continues right after @code{restore}.
1.48 anton 2999:
1.172 anton 3000: The safer equivalent to the restoration code above is
1.48 anton 3001:
3002: @example
3003: : ...
3004: save-x
3005: try
1.92 anton 3006: word-changing-x 0
1.172 anton 3007: restore
3008: restore-x
3009: endtry
1.48 anton 3010: throw ;
3011: @end example
3012:
1.66 anton 3013: Reference: @ref{Exception Handling}.
3014:
1.48 anton 3015:
3016: @node Defining Words Tutorial, Arrays and Records Tutorial, Exceptions Tutorial, Tutorial
3017: @section Defining Words
1.66 anton 3018: @cindex defining words tutorial
3019: @cindex does> tutorial
3020: @cindex create...does> tutorial
3021:
3022: @c before semantics?
1.48 anton 3023:
3024: @code{:}, @code{create}, and @code{variable} are definition words: They
3025: define other words. @code{Constant} is another definition word:
3026:
3027: @example
3028: 5 constant foo
3029: foo .
3030: @end example
3031:
3032: You can also use the prefixes @code{2} (double-cell) and @code{f}
3033: (floating point) with @code{variable} and @code{constant}.
3034:
3035: You can also define your own defining words. E.g.:
3036:
3037: @example
3038: : variable ( "name" -- )
3039: create 0 , ;
3040: @end example
3041:
3042: You can also define defining words that create words that do something
3043: other than just producing their address:
3044:
3045: @example
3046: : constant ( n "name" -- )
3047: create ,
3048: does> ( -- n )
1.50 anton 3049: ( addr ) @@ ;
1.48 anton 3050:
3051: 5 constant foo
3052: foo .
3053: @end example
3054:
3055: The definition of @code{constant} above ends at the @code{does>}; i.e.,
3056: @code{does>} replaces @code{;}, but it also does something else: It
3057: changes the last defined word such that it pushes the address of the
3058: body of the word and then performs the code after the @code{does>}
3059: whenever it is called.
3060:
3061: In the example above, @code{constant} uses @code{,} to store 5 into the
3062: body of @code{foo}. When @code{foo} executes, it pushes the address of
3063: the body onto the stack, then (in the code after the @code{does>})
3064: fetches the 5 from there.
3065:
3066: The stack comment near the @code{does>} reflects the stack effect of the
3067: defined word, not the stack effect of the code after the @code{does>}
3068: (the difference is that the code expects the address of the body that
3069: the stack comment does not show).
3070:
3071: You can use these definition words to do factoring in cases that involve
3072: (other) definition words. E.g., a field offset is always added to an
3073: address. Instead of defining
3074:
3075: @example
3076: 2 cells constant offset-field1
3077: @end example
3078:
3079: and using this like
3080:
3081: @example
3082: ( addr ) offset-field1 +
3083: @end example
3084:
3085: you can define a definition word
3086:
3087: @example
3088: : simple-field ( n "name" -- )
3089: create ,
3090: does> ( n1 -- n1+n )
1.50 anton 3091: ( addr ) @@ + ;
1.48 anton 3092: @end example
1.21 crook 3093:
1.48 anton 3094: Definition and use of field offsets now look like this:
1.21 crook 3095:
1.48 anton 3096: @example
3097: 2 cells simple-field field1
1.60 anton 3098: create mystruct 4 cells allot
3099: mystruct .s field1 .s drop
1.48 anton 3100: @end example
1.21 crook 3101:
1.48 anton 3102: If you want to do something with the word without performing the code
3103: after the @code{does>}, you can access the body of a @code{create}d word
3104: with @code{>body ( xt -- addr )}:
1.21 crook 3105:
1.48 anton 3106: @example
3107: : value ( n "name" -- )
3108: create ,
3109: does> ( -- n1 )
1.50 anton 3110: @@ ;
1.48 anton 3111: : to ( n "name" -- )
3112: ' >body ! ;
1.21 crook 3113:
1.48 anton 3114: 5 value foo
3115: foo .
3116: 7 to foo
3117: foo .
3118: @end example
1.21 crook 3119:
1.141 anton 3120: @quotation Assignment
1.48 anton 3121: Define @code{defer ( "name" -- )}, which creates a word that stores an
3122: XT (at the start the XT of @code{abort}), and upon execution
3123: @code{execute}s the XT. Define @code{is ( xt "name" -- )} that stores
3124: @code{xt} into @code{name}, a word defined with @code{defer}. Indirect
3125: recursion is one application of @code{defer}.
1.141 anton 3126: @end quotation
1.29 crook 3127:
1.66 anton 3128: Reference: @ref{User-defined Defining Words}.
3129:
3130:
1.48 anton 3131: @node Arrays and Records Tutorial, POSTPONE Tutorial, Defining Words Tutorial, Tutorial
3132: @section Arrays and Records
1.66 anton 3133: @cindex arrays tutorial
3134: @cindex records tutorial
3135: @cindex structs tutorial
1.29 crook 3136:
1.48 anton 3137: Forth has no standard words for defining data structures such as arrays
3138: and records (structs in C terminology), but you can build them yourself
3139: based on address arithmetic. You can also define words for defining
3140: arrays and records (@pxref{Defining Words Tutorial,, Defining Words}).
1.29 crook 3141:
1.48 anton 3142: One of the first projects a Forth newcomer sets out upon when learning
3143: about defining words is an array defining word (possibly for
3144: n-dimensional arrays). Go ahead and do it, I did it, too; you will
3145: learn something from it. However, don't be disappointed when you later
3146: learn that you have little use for these words (inappropriate use would
1.198 anton 3147: be even worse). I have not found a set of useful array words yet;
1.48 anton 3148: the needs are just too diverse, and named, global arrays (the result of
3149: naive use of defining words) are often not flexible enough (e.g.,
1.66 anton 3150: consider how to pass them as parameters). Another such project is a set
3151: of words to help dealing with strings.
1.29 crook 3152:
1.48 anton 3153: On the other hand, there is a useful set of record words, and it has
3154: been defined in @file{compat/struct.fs}; these words are predefined in
3155: Gforth. They are explained in depth elsewhere in this manual (see
3156: @pxref{Structures}). The @code{simple-field} example above is
3157: simplified variant of fields in this package.
1.21 crook 3158:
3159:
1.48 anton 3160: @node POSTPONE Tutorial, Literal Tutorial, Arrays and Records Tutorial, Tutorial
3161: @section @code{POSTPONE}
1.66 anton 3162: @cindex postpone tutorial
1.21 crook 3163:
1.48 anton 3164: You can compile the compilation semantics (instead of compiling the
3165: interpretation semantics) of a word with @code{POSTPONE}:
1.21 crook 3166:
1.48 anton 3167: @example
3168: : MY-+ ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
1.51 pazsan 3169: POSTPONE + ; immediate
1.48 anton 3170: : foo ( n1 n2 -- n )
3171: MY-+ ;
3172: 1 2 foo .
3173: see foo
3174: @end example
1.21 crook 3175:
1.48 anton 3176: During the definition of @code{foo} the text interpreter performs the
3177: compilation semantics of @code{MY-+}, which performs the compilation
3178: semantics of @code{+}, i.e., it compiles @code{+} into @code{foo}.
3179:
3180: This example also displays separate stack comments for the compilation
3181: semantics and for the stack effect of the compiled code. For words with
3182: default compilation semantics these stack effects are usually not
3183: displayed; the stack effect of the compilation semantics is always
3184: @code{( -- )} for these words, the stack effect for the compiled code is
3185: the stack effect of the interpretation semantics.
3186:
3187: Note that the state of the interpreter does not come into play when
3188: performing the compilation semantics in this way. You can also perform
3189: it interpretively, e.g.:
3190:
3191: @example
3192: : foo2 ( n1 n2 -- n )
3193: [ MY-+ ] ;
3194: 1 2 foo .
3195: see foo
3196: @end example
1.21 crook 3197:
1.48 anton 3198: However, there are some broken Forth systems where this does not always
1.62 crook 3199: work, and therefore this practice was been declared non-standard in
1.48 anton 3200: 1999.
3201: @c !! repair.fs
3202:
3203: Here is another example for using @code{POSTPONE}:
1.44 crook 3204:
1.48 anton 3205: @example
3206: : MY-- ( Compilation: -- ; Run-time of compiled code: n1 n2 -- n )
3207: POSTPONE negate POSTPONE + ; immediate compile-only
3208: : bar ( n1 n2 -- n )
3209: MY-- ;
3210: 2 1 bar .
3211: see bar
3212: @end example
1.21 crook 3213:
1.48 anton 3214: You can define @code{ENDIF} in this way:
1.21 crook 3215:
1.48 anton 3216: @example
3217: : ENDIF ( Compilation: orig -- )
3218: POSTPONE then ; immediate
3219: @end example
1.21 crook 3220:
1.141 anton 3221: @quotation Assignment
1.48 anton 3222: Write @code{MY-2DUP} that has compilation semantics equivalent to
3223: @code{2dup}, but compiles @code{over over}.
1.141 anton 3224: @end quotation
1.29 crook 3225:
1.66 anton 3226: @c !! @xref{Macros} for reference
3227:
3228:
1.48 anton 3229: @node Literal Tutorial, Advanced macros Tutorial, POSTPONE Tutorial, Tutorial
3230: @section @code{Literal}
1.66 anton 3231: @cindex literal tutorial
1.29 crook 3232:
1.48 anton 3233: You cannot @code{POSTPONE} numbers:
1.21 crook 3234:
1.48 anton 3235: @example
3236: : [FOO] POSTPONE 500 ; immediate
1.21 crook 3237: @end example
3238:
1.48 anton 3239: Instead, you can use @code{LITERAL (compilation: n --; run-time: -- n )}:
1.29 crook 3240:
1.48 anton 3241: @example
3242: : [FOO] ( compilation: --; run-time: -- n )
3243: 500 POSTPONE literal ; immediate
1.29 crook 3244:
1.60 anton 3245: : flip [FOO] ;
1.48 anton 3246: flip .
3247: see flip
3248: @end example
1.29 crook 3249:
1.48 anton 3250: @code{LITERAL} consumes a number at compile-time (when it's compilation
3251: semantics are executed) and pushes it at run-time (when the code it
3252: compiled is executed). A frequent use of @code{LITERAL} is to compile a
3253: number computed at compile time into the current word:
1.29 crook 3254:
1.48 anton 3255: @example
3256: : bar ( -- n )
3257: [ 2 2 + ] literal ;
3258: see bar
3259: @end example
1.29 crook 3260:
1.141 anton 3261: @quotation Assignment
1.48 anton 3262: Write @code{]L} which allows writing the example above as @code{: bar (
3263: -- n ) [ 2 2 + ]L ;}
1.141 anton 3264: @end quotation
1.48 anton 3265:
1.66 anton 3266: @c !! @xref{Macros} for reference
3267:
1.48 anton 3268:
3269: @node Advanced macros Tutorial, Compilation Tokens Tutorial, Literal Tutorial, Tutorial
3270: @section Advanced macros
1.66 anton 3271: @cindex macros, advanced tutorial
3272: @cindex run-time code generation, tutorial
1.48 anton 3273:
1.66 anton 3274: Reconsider @code{map-array} from @ref{Execution Tokens Tutorial,,
3275: Execution Tokens}. It frequently performs @code{execute}, a relatively
3276: expensive operation in some Forth implementations. You can use
1.48 anton 3277: @code{compile,} and @code{POSTPONE} to eliminate these @code{execute}s
3278: and produce a word that contains the word to be performed directly:
3279:
3280: @c use ]] ... [[
3281: @example
3282: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
3283: \ at run-time, execute xt ( ... x -- ... ) for each element of the
3284: \ array beginning at addr and containing u elements
3285: @{ xt @}
3286: POSTPONE cells POSTPONE over POSTPONE + POSTPONE swap POSTPONE ?do
1.50 anton 3287: POSTPONE i POSTPONE @@ xt compile,
1.48 anton 3288: 1 cells POSTPONE literal POSTPONE +loop ;
3289:
3290: : sum-array ( addr u -- n )
3291: 0 rot rot [ ' + compile-map-array ] ;
3292: see sum-array
3293: a 5 sum-array .
3294: @end example
3295:
3296: You can use the full power of Forth for generating the code; here's an
3297: example where the code is generated in a loop:
3298:
3299: @example
3300: : compile-vmul-step ( compilation: n --; run-time: n1 addr1 -- n2 addr2 )
3301: \ n2=n1+(addr1)*n, addr2=addr1+cell
1.50 anton 3302: POSTPONE tuck POSTPONE @@
1.48 anton 3303: POSTPONE literal POSTPONE * POSTPONE +
3304: POSTPONE swap POSTPONE cell+ ;
3305:
3306: : compile-vmul ( compilation: addr1 u -- ; run-time: addr2 -- n )
1.51 pazsan 3307: \ n=v1*v2 (inner product), where the v_i are represented as addr_i u
1.48 anton 3308: 0 postpone literal postpone swap
3309: [ ' compile-vmul-step compile-map-array ]
3310: postpone drop ;
3311: see compile-vmul
3312:
3313: : a-vmul ( addr -- n )
1.51 pazsan 3314: \ n=a*v, where v is a vector that's as long as a and starts at addr
1.48 anton 3315: [ a 5 compile-vmul ] ;
3316: see a-vmul
3317: a a-vmul .
3318: @end example
3319:
3320: This example uses @code{compile-map-array} to show off, but you could
1.66 anton 3321: also use @code{map-array} instead (try it now!).
1.48 anton 3322:
3323: You can use this technique for efficient multiplication of large
3324: matrices. In matrix multiplication, you multiply every line of one
3325: matrix with every column of the other matrix. You can generate the code
3326: for one line once, and use it for every column. The only downside of
3327: this technique is that it is cumbersome to recover the memory consumed
3328: by the generated code when you are done (and in more complicated cases
3329: it is not possible portably).
3330:
1.66 anton 3331: @c !! @xref{Macros} for reference
3332:
3333:
1.48 anton 3334: @node Compilation Tokens Tutorial, Wordlists and Search Order Tutorial, Advanced macros Tutorial, Tutorial
3335: @section Compilation Tokens
1.66 anton 3336: @cindex compilation tokens, tutorial
3337: @cindex CT, tutorial
1.48 anton 3338:
3339: This section is Gforth-specific. You can skip it.
3340:
3341: @code{' word compile,} compiles the interpretation semantics. For words
3342: with default compilation semantics this is the same as performing the
3343: compilation semantics. To represent the compilation semantics of other
3344: words (e.g., words like @code{if} that have no interpretation
3345: semantics), Gforth has the concept of a compilation token (CT,
3346: consisting of two cells), and words @code{comp'} and @code{[comp']}.
3347: You can perform the compilation semantics represented by a CT with
3348: @code{execute}:
1.29 crook 3349:
1.48 anton 3350: @example
3351: : foo2 ( n1 n2 -- n )
3352: [ comp' + execute ] ;
3353: see foo
3354: @end example
1.29 crook 3355:
1.48 anton 3356: You can compile the compilation semantics represented by a CT with
3357: @code{postpone,}:
1.30 anton 3358:
1.48 anton 3359: @example
3360: : foo3 ( -- )
3361: [ comp' + postpone, ] ;
3362: see foo3
3363: @end example
1.30 anton 3364:
1.51 pazsan 3365: @code{[ comp' word postpone, ]} is equivalent to @code{POSTPONE word}.
1.48 anton 3366: @code{comp'} is particularly useful for words that have no
3367: interpretation semantics:
1.29 crook 3368:
1.30 anton 3369: @example
1.48 anton 3370: ' if
1.60 anton 3371: comp' if .s 2drop
1.30 anton 3372: @end example
3373:
1.66 anton 3374: Reference: @ref{Tokens for Words}.
3375:
1.29 crook 3376:
1.48 anton 3377: @node Wordlists and Search Order Tutorial, , Compilation Tokens Tutorial, Tutorial
3378: @section Wordlists and Search Order
1.66 anton 3379: @cindex wordlists tutorial
3380: @cindex search order, tutorial
1.48 anton 3381:
3382: The dictionary is not just a memory area that allows you to allocate
3383: memory with @code{allot}, it also contains the Forth words, arranged in
3384: several wordlists. When searching for a word in a wordlist,
3385: conceptually you start searching at the youngest and proceed towards
3386: older words (in reality most systems nowadays use hash-tables); i.e., if
3387: you define a word with the same name as an older word, the new word
3388: shadows the older word.
3389:
3390: Which wordlists are searched in which order is determined by the search
3391: order. You can display the search order with @code{order}. It displays
3392: first the search order, starting with the wordlist searched first, then
3393: it displays the wordlist that will contain newly defined words.
1.21 crook 3394:
1.48 anton 3395: You can create a new, empty wordlist with @code{wordlist ( -- wid )}:
1.21 crook 3396:
1.48 anton 3397: @example
3398: wordlist constant mywords
3399: @end example
1.21 crook 3400:
1.48 anton 3401: @code{Set-current ( wid -- )} sets the wordlist that will contain newly
3402: defined words (the @emph{current} wordlist):
1.21 crook 3403:
1.48 anton 3404: @example
3405: mywords set-current
3406: order
3407: @end example
1.26 crook 3408:
1.48 anton 3409: Gforth does not display a name for the wordlist in @code{mywords}
3410: because this wordlist was created anonymously with @code{wordlist}.
1.21 crook 3411:
1.48 anton 3412: You can get the current wordlist with @code{get-current ( -- wid)}. If
3413: you want to put something into a specific wordlist without overall
3414: effect on the current wordlist, this typically looks like this:
1.21 crook 3415:
1.48 anton 3416: @example
3417: get-current mywords set-current ( wid )
3418: create someword
3419: ( wid ) set-current
3420: @end example
1.21 crook 3421:
1.48 anton 3422: You can write the search order with @code{set-order ( wid1 .. widn n --
3423: )} and read it with @code{get-order ( -- wid1 .. widn n )}. The first
3424: searched wordlist is topmost.
1.21 crook 3425:
1.48 anton 3426: @example
3427: get-order mywords swap 1+ set-order
3428: order
3429: @end example
1.21 crook 3430:
1.48 anton 3431: Yes, the order of wordlists in the output of @code{order} is reversed
3432: from stack comments and the output of @code{.s} and thus unintuitive.
1.21 crook 3433:
1.141 anton 3434: @quotation Assignment
1.48 anton 3435: Define @code{>order ( wid -- )} with adds @code{wid} as first searched
3436: wordlist to the search order. Define @code{previous ( -- )}, which
3437: removes the first searched wordlist from the search order. Experiment
3438: with boundary conditions (you will see some crashes or situations that
3439: are hard or impossible to leave).
1.141 anton 3440: @end quotation
1.21 crook 3441:
1.48 anton 3442: The search order is a powerful foundation for providing features similar
3443: to Modula-2 modules and C++ namespaces. However, trying to modularize
3444: programs in this way has disadvantages for debugging and reuse/factoring
3445: that overcome the advantages in my experience (I don't do huge projects,
1.55 anton 3446: though). These disadvantages are not so clear in other
1.82 anton 3447: languages/programming environments, because these languages are not so
1.48 anton 3448: strong in debugging and reuse.
1.21 crook 3449:
1.66 anton 3450: @c !! example
3451:
3452: Reference: @ref{Word Lists}.
1.21 crook 3453:
1.29 crook 3454: @c ******************************************************************
1.48 anton 3455: @node Introduction, Words, Tutorial, Top
1.29 crook 3456: @comment node-name, next, previous, up
3457: @chapter An Introduction to ANS Forth
3458: @cindex Forth - an introduction
1.21 crook 3459:
1.83 anton 3460: The difference of this chapter from the Tutorial (@pxref{Tutorial}) is
3461: that it is slower-paced in its examples, but uses them to dive deep into
3462: explaining Forth internals (not covered by the Tutorial). Apart from
3463: that, this chapter covers far less material. It is suitable for reading
3464: without using a computer.
3465:
1.29 crook 3466: The primary purpose of this manual is to document Gforth. However, since
3467: Forth is not a widely-known language and there is a lack of up-to-date
3468: teaching material, it seems worthwhile to provide some introductory
1.49 anton 3469: material. For other sources of Forth-related
3470: information, see @ref{Forth-related information}.
1.21 crook 3471:
1.29 crook 3472: The examples in this section should work on any ANS Forth; the
3473: output shown was produced using Gforth. Each example attempts to
3474: reproduce the exact output that Gforth produces. If you try out the
3475: examples (and you should), what you should type is shown @kbd{like this}
3476: and Gforth's response is shown @code{like this}. The single exception is
1.30 anton 3477: that, where the example shows @key{RET} it means that you should
1.29 crook 3478: press the ``carriage return'' key. Unfortunately, some output formats for
3479: this manual cannot show the difference between @kbd{this} and
3480: @code{this} which will make trying out the examples harder (but not
3481: impossible).
1.21 crook 3482:
1.29 crook 3483: Forth is an unusual language. It provides an interactive development
3484: environment which includes both an interpreter and compiler. Forth
3485: programming style encourages you to break a problem down into many
3486: @cindex factoring
3487: small fragments (@dfn{factoring}), and then to develop and test each
3488: fragment interactively. Forth advocates assert that breaking the
3489: edit-compile-test cycle used by conventional programming languages can
3490: lead to great productivity improvements.
1.21 crook 3491:
1.29 crook 3492: @menu
1.67 anton 3493: * Introducing the Text Interpreter::
3494: * Stacks and Postfix notation::
3495: * Your first definition::
3496: * How does that work?::
3497: * Forth is written in Forth::
3498: * Review - elements of a Forth system::
3499: * Where to go next::
3500: * Exercises::
1.29 crook 3501: @end menu
1.21 crook 3502:
1.29 crook 3503: @comment ----------------------------------------------
3504: @node Introducing the Text Interpreter, Stacks and Postfix notation, Introduction, Introduction
3505: @section Introducing the Text Interpreter
3506: @cindex text interpreter
3507: @cindex outer interpreter
1.21 crook 3508:
1.30 anton 3509: @c IMO this is too detailed and the pace is too slow for
3510: @c an introduction. If you know German, take a look at
3511: @c http://www.complang.tuwien.ac.at/anton/lvas/skriptum-stack.html
3512: @c to see how I do it - anton
3513:
1.44 crook 3514: @c nac-> Where I have accepted your comments 100% and modified the text
3515: @c accordingly, I have deleted your comments. Elsewhere I have added a
3516: @c response like this to attempt to rationalise what I have done. Of
3517: @c course, this is a very clumsy mechanism for something that would be
3518: @c done far more efficiently over a beer. Please delete any dialogue
3519: @c you consider closed.
3520:
1.29 crook 3521: When you invoke the Forth image, you will see a startup banner printed
3522: and nothing else (if you have Gforth installed on your system, try
1.30 anton 3523: invoking it now, by typing @kbd{gforth@key{RET}}). Forth is now running
1.29 crook 3524: its command line interpreter, which is called the @dfn{Text Interpreter}
3525: (also known as the @dfn{Outer Interpreter}). (You will learn a lot
1.49 anton 3526: about the text interpreter as you read through this chapter, for more
3527: detail @pxref{The Text Interpreter}).
1.21 crook 3528:
1.29 crook 3529: Although it's not obvious, Forth is actually waiting for your
1.30 anton 3530: input. Type a number and press the @key{RET} key:
1.21 crook 3531:
1.26 crook 3532: @example
1.30 anton 3533: @kbd{45@key{RET}} ok
1.26 crook 3534: @end example
1.21 crook 3535:
1.29 crook 3536: Rather than give you a prompt to invite you to input something, the text
3537: interpreter prints a status message @i{after} it has processed a line
3538: of input. The status message in this case (``@code{ ok}'' followed by
3539: carriage-return) indicates that the text interpreter was able to process
3540: all of your input successfully. Now type something illegal:
3541:
3542: @example
1.30 anton 3543: @kbd{qwer341@key{RET}}
1.134 anton 3544: *the terminal*:2: Undefined word
3545: >>>qwer341<<<
3546: Backtrace:
3547: $2A95B42A20 throw
3548: $2A95B57FB8 no.extensions
1.29 crook 3549: @end example
1.23 crook 3550:
1.134 anton 3551: The exact text, other than the ``Undefined word'' may differ slightly
3552: on your system, but the effect is the same; when the text interpreter
1.29 crook 3553: detects an error, it discards any remaining text on a line, resets
1.134 anton 3554: certain internal state and prints an error message. For a detailed
3555: description of error messages see @ref{Error messages}.
1.23 crook 3556:
1.29 crook 3557: The text interpreter waits for you to press carriage-return, and then
3558: processes your input line. Starting at the beginning of the line, it
3559: breaks the line into groups of characters separated by spaces. For each
3560: group of characters in turn, it makes two attempts to do something:
1.23 crook 3561:
1.29 crook 3562: @itemize @bullet
3563: @item
1.44 crook 3564: @cindex name dictionary
1.29 crook 3565: It tries to treat it as a command. It does this by searching a @dfn{name
3566: dictionary}. If the group of characters matches an entry in the name
3567: dictionary, the name dictionary provides the text interpreter with
3568: information that allows the text interpreter perform some actions. In
3569: Forth jargon, we say that the group
3570: @cindex word
3571: @cindex definition
3572: @cindex execution token
3573: @cindex xt
3574: of characters names a @dfn{word}, that the dictionary search returns an
3575: @dfn{execution token (xt)} corresponding to the @dfn{definition} of the
3576: word, and that the text interpreter executes the xt. Often, the terms
3577: @dfn{word} and @dfn{definition} are used interchangeably.
3578: @item
3579: If the text interpreter fails to find a match in the name dictionary, it
3580: tries to treat the group of characters as a number in the current number
3581: base (when you start up Forth, the current number base is base 10). If
3582: the group of characters legitimately represents a number, the text
3583: interpreter pushes the number onto a stack (we'll learn more about that
3584: in the next section).
3585: @end itemize
1.23 crook 3586:
1.29 crook 3587: If the text interpreter is unable to do either of these things with any
3588: group of characters, it discards the group of characters and the rest of
3589: the line, then prints an error message. If the text interpreter reaches
3590: the end of the line without error, it prints the status message ``@code{ ok}''
3591: followed by carriage-return.
1.21 crook 3592:
1.29 crook 3593: This is the simplest command we can give to the text interpreter:
1.23 crook 3594:
3595: @example
1.30 anton 3596: @key{RET} ok
1.23 crook 3597: @end example
1.21 crook 3598:
1.29 crook 3599: The text interpreter did everything we asked it to do (nothing) without
3600: an error, so it said that everything is ``@code{ ok}''. Try a slightly longer
3601: command:
1.21 crook 3602:
1.23 crook 3603: @example
1.30 anton 3604: @kbd{12 dup fred dup@key{RET}}
1.134 anton 3605: *the terminal*:3: Undefined word
3606: 12 dup >>>fred<<< dup
3607: Backtrace:
3608: $2A95B42A20 throw
3609: $2A95B57FB8 no.extensions
1.23 crook 3610: @end example
1.21 crook 3611:
1.29 crook 3612: When you press the carriage-return key, the text interpreter starts to
3613: work its way along the line:
1.21 crook 3614:
1.29 crook 3615: @itemize @bullet
3616: @item
3617: When it gets to the space after the @code{2}, it takes the group of
3618: characters @code{12} and looks them up in the name
3619: dictionary@footnote{We can't tell if it found them or not, but assume
3620: for now that it did not}. There is no match for this group of characters
3621: in the name dictionary, so it tries to treat them as a number. It is
3622: able to do this successfully, so it puts the number, 12, ``on the stack''
3623: (whatever that means).
3624: @item
3625: The text interpreter resumes scanning the line and gets the next group
3626: of characters, @code{dup}. It looks it up in the name dictionary and
3627: (you'll have to take my word for this) finds it, and executes the word
3628: @code{dup} (whatever that means).
3629: @item
3630: Once again, the text interpreter resumes scanning the line and gets the
3631: group of characters @code{fred}. It looks them up in the name
3632: dictionary, but can't find them. It tries to treat them as a number, but
3633: they don't represent any legal number.
3634: @end itemize
1.21 crook 3635:
1.29 crook 3636: At this point, the text interpreter gives up and prints an error
3637: message. The error message shows exactly how far the text interpreter
3638: got in processing the line. In particular, it shows that the text
3639: interpreter made no attempt to do anything with the final character
3640: group, @code{dup}, even though we have good reason to believe that the
3641: text interpreter would have no problem looking that word up and
3642: executing it a second time.
1.21 crook 3643:
3644:
1.29 crook 3645: @comment ----------------------------------------------
3646: @node Stacks and Postfix notation, Your first definition, Introducing the Text Interpreter, Introduction
3647: @section Stacks, postfix notation and parameter passing
3648: @cindex text interpreter
3649: @cindex outer interpreter
1.21 crook 3650:
1.29 crook 3651: In procedural programming languages (like C and Pascal), the
3652: building-block of programs is the @dfn{function} or @dfn{procedure}. These
3653: functions or procedures are called with @dfn{explicit parameters}. For
3654: example, in C we might write:
1.21 crook 3655:
1.23 crook 3656: @example
1.29 crook 3657: total = total + new_volume(length,height,depth);
1.23 crook 3658: @end example
1.21 crook 3659:
1.23 crook 3660: @noindent
1.29 crook 3661: where new_volume is a function-call to another piece of code, and total,
3662: length, height and depth are all variables. length, height and depth are
3663: parameters to the function-call.
1.21 crook 3664:
1.29 crook 3665: In Forth, the equivalent of the function or procedure is the
3666: @dfn{definition} and parameters are implicitly passed between
3667: definitions using a shared stack that is visible to the
3668: programmer. Although Forth does support variables, the existence of the
3669: stack means that they are used far less often than in most other
3670: programming languages. When the text interpreter encounters a number, it
3671: will place (@dfn{push}) it on the stack. There are several stacks (the
1.30 anton 3672: actual number is implementation-dependent ...) and the particular stack
1.29 crook 3673: used for any operation is implied unambiguously by the operation being
3674: performed. The stack used for all integer operations is called the @dfn{data
3675: stack} and, since this is the stack used most commonly, references to
3676: ``the data stack'' are often abbreviated to ``the stack''.
1.21 crook 3677:
1.29 crook 3678: The stacks have a last-in, first-out (LIFO) organisation. If you type:
1.21 crook 3679:
1.23 crook 3680: @example
1.30 anton 3681: @kbd{1 2 3@key{RET}} ok
1.23 crook 3682: @end example
1.21 crook 3683:
1.29 crook 3684: Then this instructs the text interpreter to placed three numbers on the
3685: (data) stack. An analogy for the behaviour of the stack is to take a
3686: pack of playing cards and deal out the ace (1), 2 and 3 into a pile on
3687: the table. The 3 was the last card onto the pile (``last-in'') and if
3688: you take a card off the pile then, unless you're prepared to fiddle a
3689: bit, the card that you take off will be the 3 (``first-out''). The
3690: number that will be first-out of the stack is called the @dfn{top of
3691: stack}, which
3692: @cindex TOS definition
3693: is often abbreviated to @dfn{TOS}.
1.21 crook 3694:
1.29 crook 3695: To understand how parameters are passed in Forth, consider the
3696: behaviour of the definition @code{+} (pronounced ``plus''). You will not
3697: be surprised to learn that this definition performs addition. More
3698: precisely, it adds two number together and produces a result. Where does
3699: it get the two numbers from? It takes the top two numbers off the
3700: stack. Where does it place the result? On the stack. You can act-out the
3701: behaviour of @code{+} with your playing cards like this:
1.21 crook 3702:
3703: @itemize @bullet
3704: @item
1.29 crook 3705: Pick up two cards from the stack on the table
1.21 crook 3706: @item
1.29 crook 3707: Stare at them intently and ask yourself ``what @i{is} the sum of these two
3708: numbers''
1.21 crook 3709: @item
1.29 crook 3710: Decide that the answer is 5
1.21 crook 3711: @item
1.29 crook 3712: Shuffle the two cards back into the pack and find a 5
1.21 crook 3713: @item
1.29 crook 3714: Put a 5 on the remaining ace that's on the table.
1.21 crook 3715: @end itemize
3716:
1.29 crook 3717: If you don't have a pack of cards handy but you do have Forth running,
3718: you can use the definition @code{.s} to show the current state of the stack,
3719: without affecting the stack. Type:
1.21 crook 3720:
3721: @example
1.124 anton 3722: @kbd{clearstacks 1 2 3@key{RET}} ok
1.30 anton 3723: @kbd{.s@key{RET}} <3> 1 2 3 ok
1.23 crook 3724: @end example
3725:
1.124 anton 3726: The text interpreter looks up the word @code{clearstacks} and executes
3727: it; it tidies up the stacks and removes any entries that may have been
1.29 crook 3728: left on it by earlier examples. The text interpreter pushes each of the
3729: three numbers in turn onto the stack. Finally, the text interpreter
3730: looks up the word @code{.s} and executes it. The effect of executing
3731: @code{.s} is to print the ``<3>'' (the total number of items on the stack)
3732: followed by a list of all the items on the stack; the item on the far
3733: right-hand side is the TOS.
1.21 crook 3734:
1.29 crook 3735: You can now type:
1.21 crook 3736:
1.29 crook 3737: @example
1.30 anton 3738: @kbd{+ .s@key{RET}} <2> 1 5 ok
1.29 crook 3739: @end example
1.21 crook 3740:
1.29 crook 3741: @noindent
3742: which is correct; there are now 2 items on the stack and the result of
3743: the addition is 5.
1.23 crook 3744:
1.29 crook 3745: If you're playing with cards, try doing a second addition: pick up the
3746: two cards, work out that their sum is 6, shuffle them into the pack,
3747: look for a 6 and place that on the table. You now have just one item on
3748: the stack. What happens if you try to do a third addition? Pick up the
3749: first card, pick up the second card -- ah! There is no second card. This
3750: is called a @dfn{stack underflow} and consitutes an error. If you try to
1.95 anton 3751: do the same thing with Forth it often reports an error (probably a Stack
1.29 crook 3752: Underflow or an Invalid Memory Address error).
1.23 crook 3753:
1.29 crook 3754: The opposite situation to a stack underflow is a @dfn{stack overflow},
3755: which simply accepts that there is a finite amount of storage space
3756: reserved for the stack. To stretch the playing card analogy, if you had
3757: enough packs of cards and you piled the cards up on the table, you would
3758: eventually be unable to add another card; you'd hit the ceiling. Gforth
3759: allows you to set the maximum size of the stacks. In general, the only
3760: time that you will get a stack overflow is because a definition has a
3761: bug in it and is generating data on the stack uncontrollably.
1.23 crook 3762:
1.29 crook 3763: There's one final use for the playing card analogy. If you model your
3764: stack using a pack of playing cards, the maximum number of items on
3765: your stack will be 52 (I assume you didn't use the Joker). The maximum
3766: @i{value} of any item on the stack is 13 (the King). In fact, the only
3767: possible numbers are positive integer numbers 1 through 13; you can't
3768: have (for example) 0 or 27 or 3.52 or -2. If you change the way you
3769: think about some of the cards, you can accommodate different
3770: numbers. For example, you could think of the Jack as representing 0,
3771: the Queen as representing -1 and the King as representing -2. Your
1.45 crook 3772: @i{range} remains unchanged (you can still only represent a total of 13
1.29 crook 3773: numbers) but the numbers that you can represent are -2 through 10.
1.28 crook 3774:
1.29 crook 3775: In that analogy, the limit was the amount of information that a single
3776: stack entry could hold, and Forth has a similar limit. In Forth, the
3777: size of a stack entry is called a @dfn{cell}. The actual size of a cell is
3778: implementation dependent and affects the maximum value that a stack
3779: entry can hold. A Standard Forth provides a cell size of at least
3780: 16-bits, and most desktop systems use a cell size of 32-bits.
1.21 crook 3781:
1.29 crook 3782: Forth does not do any type checking for you, so you are free to
3783: manipulate and combine stack items in any way you wish. A convenient way
3784: of treating stack items is as 2's complement signed integers, and that
3785: is what Standard words like @code{+} do. Therefore you can type:
1.21 crook 3786:
1.29 crook 3787: @example
1.30 anton 3788: @kbd{-5 12 + .s@key{RET}} <1> 7 ok
1.29 crook 3789: @end example
1.21 crook 3790:
1.29 crook 3791: If you use numbers and definitions like @code{+} in order to turn Forth
3792: into a great big pocket calculator, you will realise that it's rather
3793: different from a normal calculator. Rather than typing 2 + 3 = you had
3794: to type 2 3 + (ignore the fact that you had to use @code{.s} to see the
3795: result). The terminology used to describe this difference is to say that
3796: your calculator uses @dfn{Infix Notation} (parameters and operators are
3797: mixed) whilst Forth uses @dfn{Postfix Notation} (parameters and
3798: operators are separate), also called @dfn{Reverse Polish Notation}.
1.21 crook 3799:
1.29 crook 3800: Whilst postfix notation might look confusing to begin with, it has
3801: several important advantages:
1.21 crook 3802:
1.23 crook 3803: @itemize @bullet
3804: @item
1.29 crook 3805: it is unambiguous
1.23 crook 3806: @item
1.29 crook 3807: it is more concise
1.23 crook 3808: @item
1.29 crook 3809: it fits naturally with a stack-based system
1.23 crook 3810: @end itemize
1.21 crook 3811:
1.29 crook 3812: To examine these claims in more detail, consider these sums:
1.21 crook 3813:
1.29 crook 3814: @example
3815: 6 + 5 * 4 =
3816: 4 * 5 + 6 =
3817: @end example
1.21 crook 3818:
1.29 crook 3819: If you're just learning maths or your maths is very rusty, you will
3820: probably come up with the answer 44 for the first and 26 for the
3821: second. If you are a bit of a whizz at maths you will remember the
3822: @i{convention} that multiplication takes precendence over addition, and
3823: you'd come up with the answer 26 both times. To explain the answer 26
3824: to someone who got the answer 44, you'd probably rewrite the first sum
3825: like this:
1.21 crook 3826:
1.29 crook 3827: @example
3828: 6 + (5 * 4) =
3829: @end example
1.21 crook 3830:
1.29 crook 3831: If what you really wanted was to perform the addition before the
3832: multiplication, you would have to use parentheses to force it.
1.21 crook 3833:
1.29 crook 3834: If you did the first two sums on a pocket calculator you would probably
3835: get the right answers, unless you were very cautious and entered them using
3836: these keystroke sequences:
1.21 crook 3837:
1.29 crook 3838: 6 + 5 = * 4 =
3839: 4 * 5 = + 6 =
1.21 crook 3840:
1.29 crook 3841: Postfix notation is unambiguous because the order that the operators
3842: are applied is always explicit; that also means that parentheses are
3843: never required. The operators are @i{active} (the act of quoting the
3844: operator makes the operation occur) which removes the need for ``=''.
1.28 crook 3845:
1.29 crook 3846: The sum 6 + 5 * 4 can be written (in postfix notation) in two
3847: equivalent ways:
1.26 crook 3848:
3849: @example
1.29 crook 3850: 6 5 4 * + or:
3851: 5 4 * 6 +
1.26 crook 3852: @end example
1.23 crook 3853:
1.29 crook 3854: An important thing that you should notice about this notation is that
3855: the @i{order} of the numbers does not change; if you want to subtract
3856: 2 from 10 you type @code{10 2 -}.
1.1 anton 3857:
1.29 crook 3858: The reason that Forth uses postfix notation is very simple to explain: it
3859: makes the implementation extremely simple, and it follows naturally from
3860: using the stack as a mechanism for passing parameters. Another way of
3861: thinking about this is to realise that all Forth definitions are
3862: @i{active}; they execute as they are encountered by the text
3863: interpreter. The result of this is that the syntax of Forth is trivially
3864: simple.
1.1 anton 3865:
3866:
3867:
1.29 crook 3868: @comment ----------------------------------------------
3869: @node Your first definition, How does that work?, Stacks and Postfix notation, Introduction
3870: @section Your first Forth definition
3871: @cindex first definition
1.1 anton 3872:
1.29 crook 3873: Until now, the examples we've seen have been trivial; we've just been
3874: using Forth as a bigger-than-pocket calculator. Also, each calculation
3875: we've shown has been a ``one-off'' -- to repeat it we'd need to type it in
3876: again@footnote{That's not quite true. If you press the up-arrow key on
3877: your keyboard you should be able to scroll back to any earlier command,
3878: edit it and re-enter it.} In this section we'll see how to add new
3879: words to Forth's vocabulary.
1.1 anton 3880:
1.29 crook 3881: The easiest way to create a new word is to use a @dfn{colon
3882: definition}. We'll define a few and try them out before worrying too
3883: much about how they work. Try typing in these examples; be careful to
3884: copy the spaces accurately:
1.1 anton 3885:
1.29 crook 3886: @example
3887: : add-two 2 + . ;
3888: : greet ." Hello and welcome" ;
3889: : demo 5 add-two ;
3890: @end example
1.1 anton 3891:
1.29 crook 3892: @noindent
3893: Now try them out:
1.1 anton 3894:
1.29 crook 3895: @example
1.30 anton 3896: @kbd{greet@key{RET}} Hello and welcome ok
3897: @kbd{greet greet@key{RET}} Hello and welcomeHello and welcome ok
3898: @kbd{4 add-two@key{RET}} 6 ok
3899: @kbd{demo@key{RET}} 7 ok
3900: @kbd{9 greet demo add-two@key{RET}} Hello and welcome7 11 ok
1.29 crook 3901: @end example
1.1 anton 3902:
1.29 crook 3903: The first new thing that we've introduced here is the pair of words
3904: @code{:} and @code{;}. These are used to start and terminate a new
3905: definition, respectively. The first word after the @code{:} is the name
3906: for the new definition.
1.1 anton 3907:
1.29 crook 3908: As you can see from the examples, a definition is built up of words that
3909: have already been defined; Forth makes no distinction between
3910: definitions that existed when you started the system up, and those that
3911: you define yourself.
1.1 anton 3912:
1.29 crook 3913: The examples also introduce the words @code{.} (dot), @code{."}
3914: (dot-quote) and @code{dup} (dewp). Dot takes the value from the top of
3915: the stack and displays it. It's like @code{.s} except that it only
3916: displays the top item of the stack and it is destructive; after it has
3917: executed, the number is no longer on the stack. There is always one
3918: space printed after the number, and no spaces before it. Dot-quote
3919: defines a string (a sequence of characters) that will be printed when
3920: the word is executed. The string can contain any printable characters
3921: except @code{"}. A @code{"} has a special function; it is not a Forth
3922: word but it acts as a delimiter (the way that delimiters work is
3923: described in the next section). Finally, @code{dup} duplicates the value
3924: at the top of the stack. Try typing @code{5 dup .s} to see what it does.
1.1 anton 3925:
1.29 crook 3926: We already know that the text interpreter searches through the
3927: dictionary to locate names. If you've followed the examples earlier, you
3928: will already have a definition called @code{add-two}. Lets try modifying
3929: it by typing in a new definition:
1.1 anton 3930:
1.29 crook 3931: @example
1.30 anton 3932: @kbd{: add-two dup . ." + 2 =" 2 + . ;@key{RET}} redefined add-two ok
1.29 crook 3933: @end example
1.5 anton 3934:
1.29 crook 3935: Forth recognised that we were defining a word that already exists, and
3936: printed a message to warn us of that fact. Let's try out the new
3937: definition:
1.5 anton 3938:
1.29 crook 3939: @example
1.30 anton 3940: @kbd{9 add-two@key{RET}} 9 + 2 =11 ok
1.29 crook 3941: @end example
1.1 anton 3942:
1.29 crook 3943: @noindent
3944: All that we've actually done here, though, is to create a new
3945: definition, with a particular name. The fact that there was already a
3946: definition with the same name did not make any difference to the way
3947: that the new definition was created (except that Forth printed a warning
3948: message). The old definition of add-two still exists (try @code{demo}
3949: again to see that this is true). Any new definition will use the new
3950: definition of @code{add-two}, but old definitions continue to use the
3951: version that already existed at the time that they were @code{compiled}.
1.1 anton 3952:
1.29 crook 3953: Before you go on to the next section, try defining and redefining some
3954: words of your own.
1.1 anton 3955:
1.29 crook 3956: @comment ----------------------------------------------
3957: @node How does that work?, Forth is written in Forth, Your first definition, Introduction
3958: @section How does that work?
3959: @cindex parsing words
1.1 anton 3960:
1.30 anton 3961: @c That's pretty deep (IMO way too deep) for an introduction. - anton
3962:
3963: @c Is it a good idea to talk about the interpretation semantics of a
3964: @c number? We don't have an xt to go along with it. - anton
3965:
3966: @c Now that I have eliminated execution semantics, I wonder if it would not
3967: @c be better to keep them (or add run-time semantics), to make it easier to
3968: @c explain what compilation semantics usually does. - anton
3969:
1.44 crook 3970: @c nac-> I removed the term ``default compilation sematics'' from the
3971: @c introductory chapter. Removing ``execution semantics'' was making
3972: @c everything simpler to explain, then I think the use of this term made
3973: @c everything more complex again. I replaced it with ``default
3974: @c semantics'' (which is used elsewhere in the manual) by which I mean
3975: @c ``a definition that has neither the immediate nor the compile-only
1.83 anton 3976: @c flag set''.
3977:
3978: @c anton: I have eliminated default semantics (except in one place where it
3979: @c means "default interpretation and compilation semantics"), because it
3980: @c makes no sense in the presence of combined words. I reverted to
3981: @c "execution semantics" where necessary.
3982:
3983: @c nac-> I reworded big chunks of the ``how does that work''
1.44 crook 3984: @c section (and, unusually for me, I think I even made it shorter!). See
3985: @c what you think -- I know I have not addressed your primary concern
3986: @c that it is too heavy-going for an introduction. From what I understood
3987: @c of your course notes it looks as though they might be a good framework.
3988: @c Things that I've tried to capture here are some things that came as a
3989: @c great revelation here when I first understood them. Also, I like the
3990: @c fact that a very simple code example shows up almost all of the issues
3991: @c that you need to understand to see how Forth works. That's unique and
3992: @c worthwhile to emphasise.
3993:
1.83 anton 3994: @c anton: I think it's a good idea to present the details, especially those
3995: @c that you found to be a revelation, and probably the tutorial tries to be
3996: @c too superficial and does not get some of the things across that make
3997: @c Forth special. I do believe that most of the time these things should
3998: @c be discussed at the end of a section or in separate sections instead of
3999: @c in the middle of a section (e.g., the stuff you added in "User-defined
4000: @c defining words" leads in a completely different direction from the rest
4001: @c of the section).
4002:
1.29 crook 4003: Now we're going to take another look at the definition of @code{add-two}
4004: from the previous section. From our knowledge of the way that the text
4005: interpreter works, we would have expected this result when we tried to
4006: define @code{add-two}:
1.21 crook 4007:
1.29 crook 4008: @example
1.44 crook 4009: @kbd{: add-two 2 + . ;@key{RET}}
1.134 anton 4010: *the terminal*:4: Undefined word
4011: : >>>add-two<<< 2 + . ;
1.29 crook 4012: @end example
1.28 crook 4013:
1.29 crook 4014: The reason that this didn't happen is bound up in the way that @code{:}
4015: works. The word @code{:} does two special things. The first special
4016: thing that it does prevents the text interpreter from ever seeing the
4017: characters @code{add-two}. The text interpreter uses a variable called
4018: @cindex modifying >IN
1.44 crook 4019: @code{>IN} (pronounced ``to-in'') to keep track of where it is in the
1.29 crook 4020: input line. When it encounters the word @code{:} it behaves in exactly
4021: the same way as it does for any other word; it looks it up in the name
4022: dictionary, finds its xt and executes it. When @code{:} executes, it
4023: looks at the input buffer, finds the word @code{add-two} and advances the
4024: value of @code{>IN} to point past it. It then does some other stuff
4025: associated with creating the new definition (including creating an entry
4026: for @code{add-two} in the name dictionary). When the execution of @code{:}
4027: completes, control returns to the text interpreter, which is oblivious
4028: to the fact that it has been tricked into ignoring part of the input
4029: line.
1.21 crook 4030:
1.29 crook 4031: @cindex parsing words
4032: Words like @code{:} -- words that advance the value of @code{>IN} and so
4033: prevent the text interpreter from acting on the whole of the input line
4034: -- are called @dfn{parsing words}.
1.21 crook 4035:
1.29 crook 4036: @cindex @code{state} - effect on the text interpreter
4037: @cindex text interpreter - effect of state
4038: The second special thing that @code{:} does is change the value of a
4039: variable called @code{state}, which affects the way that the text
4040: interpreter behaves. When Gforth starts up, @code{state} has the value
4041: 0, and the text interpreter is said to be @dfn{interpreting}. During a
4042: colon definition (started with @code{:}), @code{state} is set to -1 and
1.44 crook 4043: the text interpreter is said to be @dfn{compiling}.
4044:
4045: In this example, the text interpreter is compiling when it processes the
4046: string ``@code{2 + . ;}''. It still breaks the string down into
4047: character sequences in the same way. However, instead of pushing the
4048: number @code{2} onto the stack, it lays down (@dfn{compiles}) some magic
4049: into the definition of @code{add-two} that will make the number @code{2} get
4050: pushed onto the stack when @code{add-two} is @dfn{executed}. Similarly,
4051: the behaviours of @code{+} and @code{.} are also compiled into the
4052: definition.
4053:
4054: One category of words don't get compiled. These so-called @dfn{immediate
4055: words} get executed (performed @i{now}) regardless of whether the text
4056: interpreter is interpreting or compiling. The word @code{;} is an
4057: immediate word. Rather than being compiled into the definition, it
4058: executes. Its effect is to terminate the current definition, which
4059: includes changing the value of @code{state} back to 0.
4060:
4061: When you execute @code{add-two}, it has a @dfn{run-time effect} that is
4062: exactly the same as if you had typed @code{2 + . @key{RET}} outside of a
4063: definition.
1.28 crook 4064:
1.30 anton 4065: In Forth, every word or number can be described in terms of two
1.29 crook 4066: properties:
1.28 crook 4067:
4068: @itemize @bullet
4069: @item
1.29 crook 4070: @cindex interpretation semantics
1.44 crook 4071: Its @dfn{interpretation semantics} describe how it will behave when the
4072: text interpreter encounters it in @dfn{interpret} state. The
4073: interpretation semantics of a word are represented by an @dfn{execution
4074: token}.
1.28 crook 4075: @item
1.29 crook 4076: @cindex compilation semantics
1.44 crook 4077: Its @dfn{compilation semantics} describe how it will behave when the
4078: text interpreter encounters it in @dfn{compile} state. The compilation
4079: semantics of a word are represented in an implementation-dependent way;
4080: Gforth uses a @dfn{compilation token}.
1.29 crook 4081: @end itemize
4082:
4083: @noindent
4084: Numbers are always treated in a fixed way:
4085:
4086: @itemize @bullet
1.28 crook 4087: @item
1.44 crook 4088: When the number is @dfn{interpreted}, its behaviour is to push the
4089: number onto the stack.
1.28 crook 4090: @item
1.30 anton 4091: When the number is @dfn{compiled}, a piece of code is appended to the
4092: current definition that pushes the number when it runs. (In other words,
4093: the compilation semantics of a number are to postpone its interpretation
4094: semantics until the run-time of the definition that it is being compiled
4095: into.)
1.29 crook 4096: @end itemize
4097:
1.44 crook 4098: Words don't behave in such a regular way, but most have @i{default
4099: semantics} which means that they behave like this:
1.29 crook 4100:
4101: @itemize @bullet
1.28 crook 4102: @item
1.30 anton 4103: The @dfn{interpretation semantics} of the word are to do something useful.
4104: @item
1.29 crook 4105: The @dfn{compilation semantics} of the word are to append its
1.30 anton 4106: @dfn{interpretation semantics} to the current definition (so that its
4107: run-time behaviour is to do something useful).
1.28 crook 4108: @end itemize
4109:
1.30 anton 4110: @cindex immediate words
1.44 crook 4111: The actual behaviour of any particular word can be controlled by using
4112: the words @code{immediate} and @code{compile-only} when the word is
4113: defined. These words set flags in the name dictionary entry of the most
4114: recently defined word, and these flags are retrieved by the text
4115: interpreter when it finds the word in the name dictionary.
4116:
4117: A word that is marked as @dfn{immediate} has compilation semantics that
4118: are identical to its interpretation semantics. In other words, it
4119: behaves like this:
1.29 crook 4120:
4121: @itemize @bullet
4122: @item
1.30 anton 4123: The @dfn{interpretation semantics} of the word are to do something useful.
1.29 crook 4124: @item
1.30 anton 4125: The @dfn{compilation semantics} of the word are to do something useful
4126: (and actually the same thing); i.e., it is executed during compilation.
1.29 crook 4127: @end itemize
1.28 crook 4128:
1.44 crook 4129: Marking a word as @dfn{compile-only} prohibits the text interpreter from
4130: performing the interpretation semantics of the word directly; an attempt
4131: to do so will generate an error. It is never necessary to use
4132: @code{compile-only} (and it is not even part of ANS Forth, though it is
4133: provided by many implementations) but it is good etiquette to apply it
4134: to a word that will not behave correctly (and might have unexpected
4135: side-effects) in interpret state. For example, it is only legal to use
4136: the conditional word @code{IF} within a definition. If you forget this
4137: and try to use it elsewhere, the fact that (in Gforth) it is marked as
4138: @code{compile-only} allows the text interpreter to generate a helpful
4139: error message rather than subjecting you to the consequences of your
4140: folly.
4141:
1.29 crook 4142: This example shows the difference between an immediate and a
4143: non-immediate word:
1.28 crook 4144:
1.29 crook 4145: @example
4146: : show-state state @@ . ;
4147: : show-state-now show-state ; immediate
4148: : word1 show-state ;
4149: : word2 show-state-now ;
1.28 crook 4150: @end example
1.23 crook 4151:
1.29 crook 4152: The word @code{immediate} after the definition of @code{show-state-now}
4153: makes that word an immediate word. These definitions introduce a new
4154: word: @code{@@} (pronounced ``fetch''). This word fetches the value of a
4155: variable, and leaves it on the stack. Therefore, the behaviour of
4156: @code{show-state} is to print a number that represents the current value
4157: of @code{state}.
1.28 crook 4158:
1.29 crook 4159: When you execute @code{word1}, it prints the number 0, indicating that
4160: the system is interpreting. When the text interpreter compiled the
4161: definition of @code{word1}, it encountered @code{show-state} whose
1.30 anton 4162: compilation semantics are to append its interpretation semantics to the
1.29 crook 4163: current definition. When you execute @code{word1}, it performs the
1.30 anton 4164: interpretation semantics of @code{show-state}. At the time that @code{word1}
1.29 crook 4165: (and therefore @code{show-state}) are executed, the system is
4166: interpreting.
1.28 crook 4167:
1.30 anton 4168: When you pressed @key{RET} after entering the definition of @code{word2},
1.29 crook 4169: you should have seen the number -1 printed, followed by ``@code{
4170: ok}''. When the text interpreter compiled the definition of
4171: @code{word2}, it encountered @code{show-state-now}, an immediate word,
1.30 anton 4172: whose compilation semantics are therefore to perform its interpretation
1.29 crook 4173: semantics. It is executed straight away (even before the text
4174: interpreter has moved on to process another group of characters; the
4175: @code{;} in this example). The effect of executing it are to display the
4176: value of @code{state} @i{at the time that the definition of}
4177: @code{word2} @i{is being defined}. Printing -1 demonstrates that the
4178: system is compiling at this time. If you execute @code{word2} it does
4179: nothing at all.
1.28 crook 4180:
1.29 crook 4181: @cindex @code{."}, how it works
4182: Before leaving the subject of immediate words, consider the behaviour of
4183: @code{."} in the definition of @code{greet}, in the previous
4184: section. This word is both a parsing word and an immediate word. Notice
4185: that there is a space between @code{."} and the start of the text
4186: @code{Hello and welcome}, but that there is no space between the last
4187: letter of @code{welcome} and the @code{"} character. The reason for this
4188: is that @code{."} is a Forth word; it must have a space after it so that
4189: the text interpreter can identify it. The @code{"} is not a Forth word;
4190: it is a @dfn{delimiter}. The examples earlier show that, when the string
4191: is displayed, there is neither a space before the @code{H} nor after the
4192: @code{e}. Since @code{."} is an immediate word, it executes at the time
4193: that @code{greet} is defined. When it executes, its behaviour is to
4194: search forward in the input line looking for the delimiter. When it
4195: finds the delimiter, it updates @code{>IN} to point past the
4196: delimiter. It also compiles some magic code into the definition of
4197: @code{greet}; the xt of a run-time routine that prints a text string. It
4198: compiles the string @code{Hello and welcome} into memory so that it is
4199: available to be printed later. When the text interpreter gains control,
4200: the next word it finds in the input stream is @code{;} and so it
4201: terminates the definition of @code{greet}.
1.28 crook 4202:
4203:
4204: @comment ----------------------------------------------
1.29 crook 4205: @node Forth is written in Forth, Review - elements of a Forth system, How does that work?, Introduction
4206: @section Forth is written in Forth
4207: @cindex structure of Forth programs
4208:
4209: When you start up a Forth compiler, a large number of definitions
4210: already exist. In Forth, you develop a new application using bottom-up
4211: programming techniques to create new definitions that are defined in
4212: terms of existing definitions. As you create each definition you can
4213: test and debug it interactively.
4214:
4215: If you have tried out the examples in this section, you will probably
4216: have typed them in by hand; when you leave Gforth, your definitions will
4217: be lost. You can avoid this by using a text editor to enter Forth source
4218: code into a file, and then loading code from the file using
1.49 anton 4219: @code{include} (@pxref{Forth source files}). A Forth source file is
1.29 crook 4220: processed by the text interpreter, just as though you had typed it in by
4221: hand@footnote{Actually, there are some subtle differences -- see
4222: @ref{The Text Interpreter}.}.
4223:
4224: Gforth also supports the traditional Forth alternative to using text
1.49 anton 4225: files for program entry (@pxref{Blocks}).
1.28 crook 4226:
1.29 crook 4227: In common with many, if not most, Forth compilers, most of Gforth is
4228: actually written in Forth. All of the @file{.fs} files in the
4229: installation directory@footnote{For example,
1.30 anton 4230: @file{/usr/local/share/gforth...}} are Forth source files, which you can
1.29 crook 4231: study to see examples of Forth programming.
1.28 crook 4232:
1.29 crook 4233: Gforth maintains a history file that records every line that you type to
4234: the text interpreter. This file is preserved between sessions, and is
4235: used to provide a command-line recall facility. If you enter long
4236: definitions by hand, you can use a text editor to paste them out of the
4237: history file into a Forth source file for reuse at a later time
1.49 anton 4238: (for more information @pxref{Command-line editing}).
1.28 crook 4239:
4240:
4241: @comment ----------------------------------------------
1.29 crook 4242: @node Review - elements of a Forth system, Where to go next, Forth is written in Forth, Introduction
4243: @section Review - elements of a Forth system
4244: @cindex elements of a Forth system
1.28 crook 4245:
1.29 crook 4246: To summarise this chapter:
1.28 crook 4247:
4248: @itemize @bullet
4249: @item
1.29 crook 4250: Forth programs use @dfn{factoring} to break a problem down into small
4251: fragments called @dfn{words} or @dfn{definitions}.
4252: @item
4253: Forth program development is an interactive process.
4254: @item
4255: The main command loop that accepts input, and controls both
4256: interpretation and compilation, is called the @dfn{text interpreter}
4257: (also known as the @dfn{outer interpreter}).
4258: @item
4259: Forth has a very simple syntax, consisting of words and numbers
4260: separated by spaces or carriage-return characters. Any additional syntax
4261: is imposed by @dfn{parsing words}.
4262: @item
4263: Forth uses a stack to pass parameters between words. As a result, it
4264: uses postfix notation.
4265: @item
4266: To use a word that has previously been defined, the text interpreter
4267: searches for the word in the @dfn{name dictionary}.
4268: @item
1.30 anton 4269: Words have @dfn{interpretation semantics} and @dfn{compilation semantics}.
1.28 crook 4270: @item
1.29 crook 4271: The text interpreter uses the value of @code{state} to select between
4272: the use of the @dfn{interpretation semantics} and the @dfn{compilation
4273: semantics} of a word that it encounters.
1.28 crook 4274: @item
1.30 anton 4275: The relationship between the @dfn{interpretation semantics} and
4276: @dfn{compilation semantics} for a word
1.29 crook 4277: depend upon the way in which the word was defined (for example, whether
4278: it is an @dfn{immediate} word).
1.28 crook 4279: @item
1.29 crook 4280: Forth definitions can be implemented in Forth (called @dfn{high-level
4281: definitions}) or in some other way (usually a lower-level language and
4282: as a result often called @dfn{low-level definitions}, @dfn{code
4283: definitions} or @dfn{primitives}).
1.28 crook 4284: @item
1.29 crook 4285: Many Forth systems are implemented mainly in Forth.
1.28 crook 4286: @end itemize
4287:
4288:
1.29 crook 4289: @comment ----------------------------------------------
1.48 anton 4290: @node Where to go next, Exercises, Review - elements of a Forth system, Introduction
1.29 crook 4291: @section Where To Go Next
4292: @cindex where to go next
1.28 crook 4293:
1.29 crook 4294: Amazing as it may seem, if you have read (and understood) this far, you
4295: know almost all the fundamentals about the inner workings of a Forth
4296: system. You certainly know enough to be able to read and understand the
4297: rest of this manual and the ANS Forth document, to learn more about the
4298: facilities that Forth in general and Gforth in particular provide. Even
4299: scarier, you know almost enough to implement your own Forth system.
1.30 anton 4300: However, that's not a good idea just yet... better to try writing some
1.29 crook 4301: programs in Gforth.
1.28 crook 4302:
1.29 crook 4303: Forth has such a rich vocabulary that it can be hard to know where to
4304: start in learning it. This section suggests a few sets of words that are
4305: enough to write small but useful programs. Use the word index in this
4306: document to learn more about each word, then try it out and try to write
4307: small definitions using it. Start by experimenting with these words:
1.28 crook 4308:
4309: @itemize @bullet
4310: @item
1.29 crook 4311: Arithmetic: @code{+ - * / /MOD */ ABS INVERT}
4312: @item
4313: Comparison: @code{MIN MAX =}
4314: @item
4315: Logic: @code{AND OR XOR NOT}
4316: @item
4317: Stack manipulation: @code{DUP DROP SWAP OVER}
1.28 crook 4318: @item
1.29 crook 4319: Loops and decisions: @code{IF ELSE ENDIF ?DO I LOOP}
1.28 crook 4320: @item
1.29 crook 4321: Input/Output: @code{. ." EMIT CR KEY}
1.28 crook 4322: @item
1.29 crook 4323: Defining words: @code{: ; CREATE}
1.28 crook 4324: @item
1.29 crook 4325: Memory allocation words: @code{ALLOT ,}
1.28 crook 4326: @item
1.29 crook 4327: Tools: @code{SEE WORDS .S MARKER}
4328: @end itemize
4329:
4330: When you have mastered those, go on to:
4331:
4332: @itemize @bullet
1.28 crook 4333: @item
1.29 crook 4334: More defining words: @code{VARIABLE CONSTANT VALUE TO CREATE DOES>}
1.28 crook 4335: @item
1.29 crook 4336: Memory access: @code{@@ !}
1.28 crook 4337: @end itemize
1.23 crook 4338:
1.29 crook 4339: When you have mastered these, there's nothing for it but to read through
4340: the whole of this manual and find out what you've missed.
4341:
4342: @comment ----------------------------------------------
1.48 anton 4343: @node Exercises, , Where to go next, Introduction
1.29 crook 4344: @section Exercises
4345: @cindex exercises
4346:
4347: TODO: provide a set of programming excercises linked into the stuff done
4348: already and into other sections of the manual. Provide solutions to all
4349: the exercises in a .fs file in the distribution.
4350:
4351: @c Get some inspiration from Starting Forth and Kelly&Spies.
4352:
4353: @c excercises:
4354: @c 1. take inches and convert to feet and inches.
4355: @c 2. take temperature and convert from fahrenheight to celcius;
4356: @c may need to care about symmetric vs floored??
4357: @c 3. take input line and do character substitution
4358: @c to encipher or decipher
4359: @c 4. as above but work on a file for in and out
4360: @c 5. take input line and convert to pig-latin
4361: @c
4362: @c thing of sets of things to exercise then come up with
4363: @c problems that need those things.
4364:
4365:
1.26 crook 4366: @c ******************************************************************
1.29 crook 4367: @node Words, Error messages, Introduction, Top
1.1 anton 4368: @chapter Forth Words
1.26 crook 4369: @cindex words
1.1 anton 4370:
4371: @menu
4372: * Notation::
1.65 anton 4373: * Case insensitivity::
4374: * Comments::
4375: * Boolean Flags::
1.1 anton 4376: * Arithmetic::
4377: * Stack Manipulation::
1.5 anton 4378: * Memory::
1.1 anton 4379: * Control Structures::
4380: * Defining Words::
1.65 anton 4381: * Interpretation and Compilation Semantics::
1.47 crook 4382: * Tokens for Words::
1.81 anton 4383: * Compiling words::
1.65 anton 4384: * The Text Interpreter::
1.111 anton 4385: * The Input Stream::
1.65 anton 4386: * Word Lists::
4387: * Environmental Queries::
1.12 anton 4388: * Files::
4389: * Blocks::
4390: * Other I/O::
1.121 anton 4391: * OS command line arguments::
1.78 anton 4392: * Locals::
4393: * Structures::
4394: * Object-oriented Forth::
1.12 anton 4395: * Programming Tools::
1.150 anton 4396: * C Interface::
1.12 anton 4397: * Assembler and Code Words::
4398: * Threading Words::
1.65 anton 4399: * Passing Commands to the OS::
4400: * Keeping track of Time::
4401: * Miscellaneous Words::
1.1 anton 4402: @end menu
4403:
1.65 anton 4404: @node Notation, Case insensitivity, Words, Words
1.1 anton 4405: @section Notation
4406: @cindex notation of glossary entries
4407: @cindex format of glossary entries
4408: @cindex glossary notation format
4409: @cindex word glossary entry format
4410:
4411: The Forth words are described in this section in the glossary notation
1.67 anton 4412: that has become a de-facto standard for Forth texts:
1.1 anton 4413:
4414: @format
1.29 crook 4415: @i{word} @i{Stack effect} @i{wordset} @i{pronunciation}
1.1 anton 4416: @end format
1.29 crook 4417: @i{Description}
1.1 anton 4418:
4419: @table @var
4420: @item word
1.28 crook 4421: The name of the word.
1.1 anton 4422:
4423: @item Stack effect
4424: @cindex stack effect
1.29 crook 4425: The stack effect is written in the notation @code{@i{before} --
4426: @i{after}}, where @i{before} and @i{after} describe the top of
1.1 anton 4427: stack entries before and after the execution of the word. The rest of
4428: the stack is not touched by the word. The top of stack is rightmost,
4429: i.e., a stack sequence is written as it is typed in. Note that Gforth
4430: uses a separate floating point stack, but a unified stack
1.29 crook 4431: notation. Also, return stack effects are not shown in @i{stack
4432: effect}, but in @i{Description}. The name of a stack item describes
1.1 anton 4433: the type and/or the function of the item. See below for a discussion of
4434: the types.
4435:
4436: All words have two stack effects: A compile-time stack effect and a
4437: run-time stack effect. The compile-time stack-effect of most words is
1.29 crook 4438: @i{ -- }. If the compile-time stack-effect of a word deviates from
1.1 anton 4439: this standard behaviour, or the word does other unusual things at
4440: compile time, both stack effects are shown; otherwise only the run-time
4441: stack effect is shown.
4442:
1.211 anton 4443: Also note that in code templates or examples there can be comments in
4444: parentheses that display the stack picture at this point; there is no
4445: @code{--} in these places, because there is no before-after situation.
4446:
1.1 anton 4447: @cindex pronounciation of words
4448: @item pronunciation
4449: How the word is pronounced.
4450:
4451: @cindex wordset
1.67 anton 4452: @cindex environment wordset
1.1 anton 4453: @item wordset
1.21 crook 4454: The ANS Forth standard is divided into several word sets. A standard
4455: system need not support all of them. Therefore, in theory, the fewer
4456: word sets your program uses the more portable it will be. However, we
4457: suspect that most ANS Forth systems on personal machines will feature
1.26 crook 4458: all word sets. Words that are not defined in ANS Forth have
1.21 crook 4459: @code{gforth} or @code{gforth-internal} as word set. @code{gforth}
1.1 anton 4460: describes words that will work in future releases of Gforth;
4461: @code{gforth-internal} words are more volatile. Environmental query
4462: strings are also displayed like words; you can recognize them by the
1.21 crook 4463: @code{environment} in the word set field.
1.1 anton 4464:
4465: @item Description
4466: A description of the behaviour of the word.
4467: @end table
4468:
4469: @cindex types of stack items
4470: @cindex stack item types
4471: The type of a stack item is specified by the character(s) the name
4472: starts with:
4473:
4474: @table @code
4475: @item f
4476: @cindex @code{f}, stack item type
4477: Boolean flags, i.e. @code{false} or @code{true}.
4478: @item c
4479: @cindex @code{c}, stack item type
4480: Char
4481: @item w
4482: @cindex @code{w}, stack item type
4483: Cell, can contain an integer or an address
4484: @item n
4485: @cindex @code{n}, stack item type
4486: signed integer
4487: @item u
4488: @cindex @code{u}, stack item type
4489: unsigned integer
4490: @item d
4491: @cindex @code{d}, stack item type
4492: double sized signed integer
4493: @item ud
4494: @cindex @code{ud}, stack item type
4495: double sized unsigned integer
4496: @item r
4497: @cindex @code{r}, stack item type
4498: Float (on the FP stack)
1.21 crook 4499: @item a-
1.1 anton 4500: @cindex @code{a_}, stack item type
4501: Cell-aligned address
1.21 crook 4502: @item c-
1.1 anton 4503: @cindex @code{c_}, stack item type
4504: Char-aligned address (note that a Char may have two bytes in Windows NT)
1.21 crook 4505: @item f-
1.1 anton 4506: @cindex @code{f_}, stack item type
4507: Float-aligned address
1.21 crook 4508: @item df-
1.1 anton 4509: @cindex @code{df_}, stack item type
4510: Address aligned for IEEE double precision float
1.21 crook 4511: @item sf-
1.1 anton 4512: @cindex @code{sf_}, stack item type
4513: Address aligned for IEEE single precision float
4514: @item xt
4515: @cindex @code{xt}, stack item type
4516: Execution token, same size as Cell
4517: @item wid
4518: @cindex @code{wid}, stack item type
1.21 crook 4519: Word list ID, same size as Cell
1.68 anton 4520: @item ior, wior
4521: @cindex ior type description
4522: @cindex wior type description
4523: I/O result code, cell-sized. In Gforth, you can @code{throw} iors.
1.1 anton 4524: @item f83name
4525: @cindex @code{f83name}, stack item type
4526: Pointer to a name structure
4527: @item "
4528: @cindex @code{"}, stack item type
1.12 anton 4529: string in the input stream (not on the stack). The terminating character
4530: is a blank by default. If it is not a blank, it is shown in @code{<>}
1.1 anton 4531: quotes.
4532: @end table
4533:
1.65 anton 4534: @comment ----------------------------------------------
4535: @node Case insensitivity, Comments, Notation, Words
4536: @section Case insensitivity
4537: @cindex case sensitivity
4538: @cindex upper and lower case
4539:
4540: Gforth is case-insensitive; you can enter definitions and invoke
4541: Standard words using upper, lower or mixed case (however,
4542: @pxref{core-idef, Implementation-defined options, Implementation-defined
4543: options}).
4544:
4545: ANS Forth only @i{requires} implementations to recognise Standard words
4546: when they are typed entirely in upper case. Therefore, a Standard
4547: program must use upper case for all Standard words. You can use whatever
4548: case you like for words that you define, but in a Standard program you
4549: have to use the words in the same case that you defined them.
4550:
4551: Gforth supports case sensitivity through @code{table}s (case-sensitive
4552: wordlists, @pxref{Word Lists}).
4553:
4554: Two people have asked how to convert Gforth to be case-sensitive; while
4555: we think this is a bad idea, you can change all wordlists into tables
4556: like this:
4557:
4558: @example
4559: ' table-find forth-wordlist wordlist-map @ !
4560: @end example
4561:
4562: Note that you now have to type the predefined words in the same case
4563: that we defined them, which are varying. You may want to convert them
4564: to your favourite case before doing this operation (I won't explain how,
4565: because if you are even contemplating doing this, you'd better have
4566: enough knowledge of Forth systems to know this already).
4567:
4568: @node Comments, Boolean Flags, Case insensitivity, Words
1.21 crook 4569: @section Comments
1.26 crook 4570: @cindex comments
1.21 crook 4571:
1.29 crook 4572: Forth supports two styles of comment; the traditional @i{in-line} comment,
4573: @code{(} and its modern cousin, the @i{comment to end of line}; @code{\}.
1.21 crook 4574:
1.44 crook 4575:
1.23 crook 4576: doc-(
1.21 crook 4577: doc-\
1.23 crook 4578: doc-\G
1.21 crook 4579:
1.44 crook 4580:
1.21 crook 4581: @node Boolean Flags, Arithmetic, Comments, Words
4582: @section Boolean Flags
1.26 crook 4583: @cindex Boolean flags
1.21 crook 4584:
4585: A Boolean flag is cell-sized. A cell with all bits clear represents the
4586: flag @code{false} and a flag with all bits set represents the flag
1.26 crook 4587: @code{true}. Words that check a flag (for example, @code{IF}) will treat
1.29 crook 4588: a cell that has @i{any} bit set as @code{true}.
1.67 anton 4589: @c on and off to Memory?
4590: @c true and false to "Bitwise operations" or "Numeric comparison"?
1.44 crook 4591:
1.21 crook 4592: doc-true
4593: doc-false
1.29 crook 4594: doc-on
4595: doc-off
1.21 crook 4596:
1.44 crook 4597:
1.21 crook 4598: @node Arithmetic, Stack Manipulation, Boolean Flags, Words
1.1 anton 4599: @section Arithmetic
4600: @cindex arithmetic words
4601:
4602: @cindex division with potentially negative operands
4603: Forth arithmetic is not checked, i.e., you will not hear about integer
4604: overflow on addition or multiplication, you may hear about division by
4605: zero if you are lucky. The operator is written after the operands, but
4606: the operands are still in the original order. I.e., the infix @code{2-1}
4607: corresponds to @code{2 1 -}. Forth offers a variety of division
4608: operators. If you perform division with potentially negative operands,
4609: you do not want to use @code{/} or @code{/mod} with its undefined
4610: behaviour, but rather @code{fm/mod} or @code{sm/mod} (probably the
4611: former, @pxref{Mixed precision}).
1.26 crook 4612: @comment TODO discuss the different division forms and the std approach
1.1 anton 4613:
4614: @menu
4615: * Single precision::
1.67 anton 4616: * Double precision:: Double-cell integer arithmetic
1.1 anton 4617: * Bitwise operations::
1.67 anton 4618: * Numeric comparison::
1.29 crook 4619: * Mixed precision:: Operations with single and double-cell integers
1.1 anton 4620: * Floating Point::
4621: @end menu
4622:
1.67 anton 4623: @node Single precision, Double precision, Arithmetic, Arithmetic
1.1 anton 4624: @subsection Single precision
4625: @cindex single precision arithmetic words
4626:
1.67 anton 4627: @c !! cell undefined
4628:
4629: By default, numbers in Forth are single-precision integers that are one
1.26 crook 4630: cell in size. They can be signed or unsigned, depending upon how you
1.49 anton 4631: treat them. For the rules used by the text interpreter for recognising
4632: single-precision integers see @ref{Number Conversion}.
1.21 crook 4633:
1.67 anton 4634: These words are all defined for signed operands, but some of them also
4635: work for unsigned numbers: @code{+}, @code{1+}, @code{-}, @code{1-},
4636: @code{*}.
1.44 crook 4637:
1.1 anton 4638: doc-+
1.21 crook 4639: doc-1+
1.128 anton 4640: doc-under+
1.1 anton 4641: doc--
1.21 crook 4642: doc-1-
1.1 anton 4643: doc-*
4644: doc-/
4645: doc-mod
4646: doc-/mod
4647: doc-negate
4648: doc-abs
4649: doc-min
4650: doc-max
1.27 crook 4651: doc-floored
1.1 anton 4652:
1.44 crook 4653:
1.67 anton 4654: @node Double precision, Bitwise operations, Single precision, Arithmetic
1.21 crook 4655: @subsection Double precision
4656: @cindex double precision arithmetic words
4657:
1.49 anton 4658: For the rules used by the text interpreter for
4659: recognising double-precision integers, see @ref{Number Conversion}.
1.21 crook 4660:
4661: A double precision number is represented by a cell pair, with the most
1.67 anton 4662: significant cell at the TOS. It is trivial to convert an unsigned single
4663: to a double: simply push a @code{0} onto the TOS. Since numbers are
4664: represented by Gforth using 2's complement arithmetic, converting a
4665: signed single to a (signed) double requires sign-extension across the
4666: most significant cell. This can be achieved using @code{s>d}. The moral
4667: of the story is that you cannot convert a number without knowing whether
4668: it represents an unsigned or a signed number.
1.21 crook 4669:
1.67 anton 4670: These words are all defined for signed operands, but some of them also
4671: work for unsigned numbers: @code{d+}, @code{d-}.
1.44 crook 4672:
1.21 crook 4673: doc-s>d
1.67 anton 4674: doc-d>s
1.21 crook 4675: doc-d+
4676: doc-d-
4677: doc-dnegate
4678: doc-dabs
4679: doc-dmin
4680: doc-dmax
4681:
1.44 crook 4682:
1.67 anton 4683: @node Bitwise operations, Numeric comparison, Double precision, Arithmetic
4684: @subsection Bitwise operations
4685: @cindex bitwise operation words
4686:
4687:
4688: doc-and
4689: doc-or
4690: doc-xor
4691: doc-invert
4692: doc-lshift
4693: doc-rshift
4694: doc-2*
4695: doc-d2*
4696: doc-2/
4697: doc-d2/
4698:
4699:
4700: @node Numeric comparison, Mixed precision, Bitwise operations, Arithmetic
1.21 crook 4701: @subsection Numeric comparison
4702: @cindex numeric comparison words
4703:
1.67 anton 4704: Note that the words that compare for equality (@code{= <> 0= 0<> d= d<>
4705: d0= d0<>}) work for for both signed and unsigned numbers.
1.44 crook 4706:
1.28 crook 4707: doc-<
4708: doc-<=
4709: doc-<>
4710: doc-=
4711: doc->
4712: doc->=
4713:
1.21 crook 4714: doc-0<
1.23 crook 4715: doc-0<=
1.21 crook 4716: doc-0<>
4717: doc-0=
1.23 crook 4718: doc-0>
4719: doc-0>=
1.28 crook 4720:
4721: doc-u<
4722: doc-u<=
1.44 crook 4723: @c u<> and u= exist but are the same as <> and =
1.31 anton 4724: @c doc-u<>
4725: @c doc-u=
1.28 crook 4726: doc-u>
4727: doc-u>=
4728:
4729: doc-within
4730:
4731: doc-d<
4732: doc-d<=
4733: doc-d<>
4734: doc-d=
4735: doc-d>
4736: doc-d>=
1.23 crook 4737:
1.21 crook 4738: doc-d0<
1.23 crook 4739: doc-d0<=
4740: doc-d0<>
1.21 crook 4741: doc-d0=
1.23 crook 4742: doc-d0>
4743: doc-d0>=
4744:
1.21 crook 4745: doc-du<
1.28 crook 4746: doc-du<=
1.44 crook 4747: @c du<> and du= exist but are the same as d<> and d=
1.31 anton 4748: @c doc-du<>
4749: @c doc-du=
1.28 crook 4750: doc-du>
4751: doc-du>=
1.1 anton 4752:
1.44 crook 4753:
1.21 crook 4754: @node Mixed precision, Floating Point, Numeric comparison, Arithmetic
1.1 anton 4755: @subsection Mixed precision
4756: @cindex mixed precision arithmetic words
4757:
1.44 crook 4758:
1.1 anton 4759: doc-m+
4760: doc-*/
4761: doc-*/mod
4762: doc-m*
4763: doc-um*
4764: doc-m*/
4765: doc-um/mod
4766: doc-fm/mod
4767: doc-sm/rem
4768:
1.44 crook 4769:
1.21 crook 4770: @node Floating Point, , Mixed precision, Arithmetic
1.1 anton 4771: @subsection Floating Point
4772: @cindex floating point arithmetic words
4773:
1.49 anton 4774: For the rules used by the text interpreter for
4775: recognising floating-point numbers see @ref{Number Conversion}.
1.1 anton 4776:
1.67 anton 4777: Gforth has a separate floating point stack, but the documentation uses
4778: the unified notation.@footnote{It's easy to generate the separate
4779: notation from that by just separating the floating-point numbers out:
4780: e.g. @code{( n r1 u r2 -- r3 )} becomes @code{( n u -- ) ( F: r1 r2 --
4781: r3 )}.}
1.1 anton 4782:
4783: @cindex floating-point arithmetic, pitfalls
4784: Floating point numbers have a number of unpleasant surprises for the
1.190 anton 4785: unwary (e.g., floating point addition is not associative) and even a
4786: few for the wary. You should not use them unless you know what you are
4787: doing or you don't care that the results you get are totally bogus. If
4788: you want to learn about the problems of floating point numbers (and
4789: how to avoid them), you might start with @cite{David Goldberg,
4790: @uref{http://docs.sun.com/source/806-3568/ncg_goldberg.html,What Every
4791: Computer Scientist Should Know About Floating-Point Arithmetic}, ACM
4792: Computing Surveys 23(1):5@minus{}48, March 1991}.
1.1 anton 4793:
1.44 crook 4794:
1.21 crook 4795: doc-d>f
4796: doc-f>d
1.1 anton 4797: doc-f+
4798: doc-f-
4799: doc-f*
4800: doc-f/
4801: doc-fnegate
4802: doc-fabs
4803: doc-fmax
4804: doc-fmin
4805: doc-floor
4806: doc-fround
4807: doc-f**
4808: doc-fsqrt
4809: doc-fexp
4810: doc-fexpm1
4811: doc-fln
4812: doc-flnp1
4813: doc-flog
4814: doc-falog
1.32 anton 4815: doc-f2*
4816: doc-f2/
4817: doc-1/f
4818: doc-precision
4819: doc-set-precision
4820:
4821: @cindex angles in trigonometric operations
4822: @cindex trigonometric operations
4823: Angles in floating point operations are given in radians (a full circle
4824: has 2 pi radians).
4825:
1.1 anton 4826: doc-fsin
4827: doc-fcos
4828: doc-fsincos
4829: doc-ftan
4830: doc-fasin
4831: doc-facos
4832: doc-fatan
4833: doc-fatan2
4834: doc-fsinh
4835: doc-fcosh
4836: doc-ftanh
4837: doc-fasinh
4838: doc-facosh
4839: doc-fatanh
1.21 crook 4840: doc-pi
1.28 crook 4841:
1.32 anton 4842: @cindex equality of floats
4843: @cindex floating-point comparisons
1.31 anton 4844: One particular problem with floating-point arithmetic is that comparison
4845: for equality often fails when you would expect it to succeed. For this
4846: reason approximate equality is often preferred (but you still have to
1.67 anton 4847: know what you are doing). Also note that IEEE NaNs may compare
1.68 anton 4848: differently from what you might expect. The comparison words are:
1.31 anton 4849:
4850: doc-f~rel
4851: doc-f~abs
1.68 anton 4852: doc-f~
1.31 anton 4853: doc-f=
4854: doc-f<>
4855:
4856: doc-f<
4857: doc-f<=
4858: doc-f>
4859: doc-f>=
4860:
1.21 crook 4861: doc-f0<
1.28 crook 4862: doc-f0<=
4863: doc-f0<>
1.21 crook 4864: doc-f0=
1.28 crook 4865: doc-f0>
4866: doc-f0>=
4867:
1.1 anton 4868:
4869: @node Stack Manipulation, Memory, Arithmetic, Words
4870: @section Stack Manipulation
4871: @cindex stack manipulation words
4872:
4873: @cindex floating-point stack in the standard
1.21 crook 4874: Gforth maintains a number of separate stacks:
4875:
1.29 crook 4876: @cindex data stack
4877: @cindex parameter stack
1.21 crook 4878: @itemize @bullet
4879: @item
1.29 crook 4880: A data stack (also known as the @dfn{parameter stack}) -- for
4881: characters, cells, addresses, and double cells.
1.21 crook 4882:
1.29 crook 4883: @cindex floating-point stack
1.21 crook 4884: @item
1.44 crook 4885: A floating point stack -- for holding floating point (FP) numbers.
1.21 crook 4886:
1.29 crook 4887: @cindex return stack
1.21 crook 4888: @item
1.44 crook 4889: A return stack -- for holding the return addresses of colon
1.32 anton 4890: definitions and other (non-FP) data.
1.21 crook 4891:
1.29 crook 4892: @cindex locals stack
1.21 crook 4893: @item
1.44 crook 4894: A locals stack -- for holding local variables.
1.21 crook 4895: @end itemize
4896:
1.1 anton 4897: @menu
4898: * Data stack::
4899: * Floating point stack::
4900: * Return stack::
4901: * Locals stack::
4902: * Stack pointer manipulation::
4903: @end menu
4904:
4905: @node Data stack, Floating point stack, Stack Manipulation, Stack Manipulation
4906: @subsection Data stack
4907: @cindex data stack manipulation words
4908: @cindex stack manipulations words, data stack
4909:
1.44 crook 4910:
1.1 anton 4911: doc-drop
4912: doc-nip
4913: doc-dup
4914: doc-over
4915: doc-tuck
4916: doc-swap
1.21 crook 4917: doc-pick
1.1 anton 4918: doc-rot
4919: doc--rot
4920: doc-?dup
4921: doc-roll
4922: doc-2drop
4923: doc-2nip
4924: doc-2dup
4925: doc-2over
4926: doc-2tuck
4927: doc-2swap
4928: doc-2rot
4929:
1.44 crook 4930:
1.1 anton 4931: @node Floating point stack, Return stack, Data stack, Stack Manipulation
4932: @subsection Floating point stack
4933: @cindex floating-point stack manipulation words
4934: @cindex stack manipulation words, floating-point stack
4935:
1.32 anton 4936: Whilst every sane Forth has a separate floating-point stack, it is not
4937: strictly required; an ANS Forth system could theoretically keep
4938: floating-point numbers on the data stack. As an additional difficulty,
4939: you don't know how many cells a floating-point number takes. It is
4940: reportedly possible to write words in a way that they work also for a
4941: unified stack model, but we do not recommend trying it. Instead, just
4942: say that your program has an environmental dependency on a separate
4943: floating-point stack.
4944:
4945: doc-floating-stack
4946:
1.1 anton 4947: doc-fdrop
4948: doc-fnip
4949: doc-fdup
4950: doc-fover
4951: doc-ftuck
4952: doc-fswap
1.21 crook 4953: doc-fpick
1.1 anton 4954: doc-frot
4955:
1.44 crook 4956:
1.1 anton 4957: @node Return stack, Locals stack, Floating point stack, Stack Manipulation
4958: @subsection Return stack
4959: @cindex return stack manipulation words
4960: @cindex stack manipulation words, return stack
4961:
1.32 anton 4962: @cindex return stack and locals
4963: @cindex locals and return stack
4964: A Forth system is allowed to keep local variables on the
4965: return stack. This is reasonable, as local variables usually eliminate
4966: the need to use the return stack explicitly. So, if you want to produce
4967: a standard compliant program and you are using local variables in a
4968: word, forget about return stack manipulations in that word (refer to the
4969: standard document for the exact rules).
4970:
1.1 anton 4971: doc->r
4972: doc-r>
4973: doc-r@
4974: doc-rdrop
4975: doc-2>r
4976: doc-2r>
4977: doc-2r@
4978: doc-2rdrop
4979:
1.44 crook 4980:
1.1 anton 4981: @node Locals stack, Stack pointer manipulation, Return stack, Stack Manipulation
4982: @subsection Locals stack
4983:
1.78 anton 4984: Gforth uses an extra locals stack. It is described, along with the
4985: reasons for its existence, in @ref{Locals implementation}.
1.21 crook 4986:
1.1 anton 4987: @node Stack pointer manipulation, , Locals stack, Stack Manipulation
4988: @subsection Stack pointer manipulation
4989: @cindex stack pointer manipulation words
4990:
1.44 crook 4991: @c removed s0 r0 l0 -- they are obsolete aliases for sp0 rp0 lp0
1.21 crook 4992: doc-sp0
1.1 anton 4993: doc-sp@
4994: doc-sp!
1.21 crook 4995: doc-fp0
1.1 anton 4996: doc-fp@
4997: doc-fp!
1.21 crook 4998: doc-rp0
1.1 anton 4999: doc-rp@
5000: doc-rp!
1.21 crook 5001: doc-lp0
1.1 anton 5002: doc-lp@
5003: doc-lp!
5004:
1.44 crook 5005:
1.1 anton 5006: @node Memory, Control Structures, Stack Manipulation, Words
5007: @section Memory
1.26 crook 5008: @cindex memory words
1.1 anton 5009:
1.32 anton 5010: @menu
5011: * Memory model::
5012: * Dictionary allocation::
5013: * Heap Allocation::
5014: * Memory Access::
5015: * Address arithmetic::
5016: * Memory Blocks::
5017: @end menu
5018:
1.67 anton 5019: In addition to the standard Forth memory allocation words, there is also
5020: a @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
5021: garbage collector}.
5022:
1.32 anton 5023: @node Memory model, Dictionary allocation, Memory, Memory
5024: @subsection ANS Forth and Gforth memory models
5025:
5026: @c The ANS Forth description is a mess (e.g., is the heap part of
5027: @c the dictionary?), so let's not stick to closely with it.
5028:
1.67 anton 5029: ANS Forth considers a Forth system as consisting of several address
5030: spaces, of which only @dfn{data space} is managed and accessible with
5031: the memory words. Memory not necessarily in data space includes the
5032: stacks, the code (called code space) and the headers (called name
5033: space). In Gforth everything is in data space, but the code for the
5034: primitives is usually read-only.
1.32 anton 5035:
5036: Data space is divided into a number of areas: The (data space portion of
5037: the) dictionary@footnote{Sometimes, the term @dfn{dictionary} is used to
5038: refer to the search data structure embodied in word lists and headers,
5039: because it is used for looking up names, just as you would in a
5040: conventional dictionary.}, the heap, and a number of system-allocated
5041: buffers.
5042:
1.68 anton 5043: @cindex address arithmetic restrictions, ANS vs. Gforth
5044: @cindex contiguous regions, ANS vs. Gforth
1.32 anton 5045: In ANS Forth data space is also divided into contiguous regions. You
5046: can only use address arithmetic within a contiguous region, not between
5047: them. Usually each allocation gives you one contiguous region, but the
1.33 anton 5048: dictionary allocation words have additional rules (@pxref{Dictionary
1.32 anton 5049: allocation}).
5050:
5051: Gforth provides one big address space, and address arithmetic can be
5052: performed between any addresses. However, in the dictionary headers or
5053: code are interleaved with data, so almost the only contiguous data space
5054: regions there are those described by ANS Forth as contiguous; but you
5055: can be sure that the dictionary is allocated towards increasing
5056: addresses even between contiguous regions. The memory order of
5057: allocations in the heap is platform-dependent (and possibly different
5058: from one run to the next).
5059:
1.27 crook 5060:
1.32 anton 5061: @node Dictionary allocation, Heap Allocation, Memory model, Memory
5062: @subsection Dictionary allocation
1.27 crook 5063: @cindex reserving data space
5064: @cindex data space - reserving some
5065:
1.32 anton 5066: Dictionary allocation is a stack-oriented allocation scheme, i.e., if
5067: you want to deallocate X, you also deallocate everything
5068: allocated after X.
5069:
1.68 anton 5070: @cindex contiguous regions in dictionary allocation
1.32 anton 5071: The allocations using the words below are contiguous and grow the region
5072: towards increasing addresses. Other words that allocate dictionary
5073: memory of any kind (i.e., defining words including @code{:noname}) end
5074: the contiguous region and start a new one.
5075:
5076: In ANS Forth only @code{create}d words are guaranteed to produce an
5077: address that is the start of the following contiguous region. In
5078: particular, the cell allocated by @code{variable} is not guaranteed to
5079: be contiguous with following @code{allot}ed memory.
5080:
5081: You can deallocate memory by using @code{allot} with a negative argument
5082: (with some restrictions, see @code{allot}). For larger deallocations use
5083: @code{marker}.
1.27 crook 5084:
1.29 crook 5085:
1.27 crook 5086: doc-here
5087: doc-unused
5088: doc-allot
5089: doc-c,
1.29 crook 5090: doc-f,
1.27 crook 5091: doc-,
5092: doc-2,
5093:
1.32 anton 5094: Memory accesses have to be aligned (@pxref{Address arithmetic}). So of
5095: course you should allocate memory in an aligned way, too. I.e., before
5096: allocating allocating a cell, @code{here} must be cell-aligned, etc.
5097: The words below align @code{here} if it is not already. Basically it is
5098: only already aligned for a type, if the last allocation was a multiple
5099: of the size of this type and if @code{here} was aligned for this type
5100: before.
5101:
5102: After freshly @code{create}ing a word, @code{here} is @code{align}ed in
5103: ANS Forth (@code{maxalign}ed in Gforth).
5104:
5105: doc-align
5106: doc-falign
5107: doc-sfalign
5108: doc-dfalign
5109: doc-maxalign
5110: doc-cfalign
5111:
5112:
5113: @node Heap Allocation, Memory Access, Dictionary allocation, Memory
5114: @subsection Heap allocation
5115: @cindex heap allocation
5116: @cindex dynamic allocation of memory
5117: @cindex memory-allocation word set
5118:
1.68 anton 5119: @cindex contiguous regions and heap allocation
1.32 anton 5120: Heap allocation supports deallocation of allocated memory in any
5121: order. Dictionary allocation is not affected by it (i.e., it does not
5122: end a contiguous region). In Gforth, these words are implemented using
5123: the standard C library calls malloc(), free() and resize().
5124:
1.68 anton 5125: The memory region produced by one invocation of @code{allocate} or
5126: @code{resize} is internally contiguous. There is no contiguity between
5127: such a region and any other region (including others allocated from the
5128: heap).
5129:
1.32 anton 5130: doc-allocate
5131: doc-free
5132: doc-resize
5133:
1.27 crook 5134:
1.32 anton 5135: @node Memory Access, Address arithmetic, Heap Allocation, Memory
1.1 anton 5136: @subsection Memory Access
5137: @cindex memory access words
5138:
5139: doc-@
5140: doc-!
5141: doc-+!
5142: doc-c@
5143: doc-c!
5144: doc-2@
5145: doc-2!
5146: doc-f@
5147: doc-f!
5148: doc-sf@
5149: doc-sf!
5150: doc-df@
5151: doc-df!
1.144 anton 5152: doc-sw@
5153: doc-uw@
5154: doc-w!
5155: doc-sl@
5156: doc-ul@
5157: doc-l!
1.68 anton 5158:
1.32 anton 5159: @node Address arithmetic, Memory Blocks, Memory Access, Memory
5160: @subsection Address arithmetic
1.1 anton 5161: @cindex address arithmetic words
5162:
1.67 anton 5163: Address arithmetic is the foundation on which you can build data
5164: structures like arrays, records (@pxref{Structures}) and objects
5165: (@pxref{Object-oriented Forth}).
1.32 anton 5166:
1.68 anton 5167: @cindex address unit
5168: @cindex au (address unit)
1.1 anton 5169: ANS Forth does not specify the sizes of the data types. Instead, it
5170: offers a number of words for computing sizes and doing address
1.29 crook 5171: arithmetic. Address arithmetic is performed in terms of address units
5172: (aus); on most systems the address unit is one byte. Note that a
5173: character may have more than one au, so @code{chars} is no noop (on
1.68 anton 5174: platforms where it is a noop, it compiles to nothing).
1.1 anton 5175:
1.67 anton 5176: The basic address arithmetic words are @code{+} and @code{-}. E.g., if
5177: you have the address of a cell, perform @code{1 cells +}, and you will
5178: have the address of the next cell.
5179:
1.68 anton 5180: @cindex contiguous regions and address arithmetic
1.67 anton 5181: In ANS Forth you can perform address arithmetic only within a contiguous
5182: region, i.e., if you have an address into one region, you can only add
5183: and subtract such that the result is still within the region; you can
5184: only subtract or compare addresses from within the same contiguous
5185: region. Reasons: several contiguous regions can be arranged in memory
5186: in any way; on segmented systems addresses may have unusual
5187: representations, such that address arithmetic only works within a
5188: region. Gforth provides a few more guarantees (linear address space,
5189: dictionary grows upwards), but in general I have found it easy to stay
5190: within contiguous regions (exception: computing and comparing to the
5191: address just beyond the end of an array).
5192:
1.1 anton 5193: @cindex alignment of addresses for types
5194: ANS Forth also defines words for aligning addresses for specific
5195: types. Many computers require that accesses to specific data types
5196: must only occur at specific addresses; e.g., that cells may only be
5197: accessed at addresses divisible by 4. Even if a machine allows unaligned
5198: accesses, it can usually perform aligned accesses faster.
5199:
5200: For the performance-conscious: alignment operations are usually only
5201: necessary during the definition of a data structure, not during the
5202: (more frequent) accesses to it.
5203:
5204: ANS Forth defines no words for character-aligning addresses. This is not
5205: an oversight, but reflects the fact that addresses that are not
5206: char-aligned have no use in the standard and therefore will not be
5207: created.
5208:
5209: @cindex @code{CREATE} and alignment
1.29 crook 5210: ANS Forth guarantees that addresses returned by @code{CREATE}d words
1.1 anton 5211: are cell-aligned; in addition, Gforth guarantees that these addresses
5212: are aligned for all purposes.
5213:
1.26 crook 5214: Note that the ANS Forth word @code{char} has nothing to do with address
5215: arithmetic.
1.1 anton 5216:
1.44 crook 5217:
1.1 anton 5218: doc-chars
5219: doc-char+
5220: doc-cells
5221: doc-cell+
5222: doc-cell
5223: doc-aligned
5224: doc-floats
5225: doc-float+
5226: doc-float
5227: doc-faligned
5228: doc-sfloats
5229: doc-sfloat+
5230: doc-sfaligned
5231: doc-dfloats
5232: doc-dfloat+
5233: doc-dfaligned
5234: doc-maxaligned
5235: doc-cfaligned
5236: doc-address-unit-bits
1.145 anton 5237: doc-/w
5238: doc-/l
1.44 crook 5239:
1.32 anton 5240: @node Memory Blocks, , Address arithmetic, Memory
1.1 anton 5241: @subsection Memory Blocks
5242: @cindex memory block words
1.27 crook 5243: @cindex character strings - moving and copying
5244:
1.49 anton 5245: Memory blocks often represent character strings; For ways of storing
5246: character strings in memory see @ref{String Formats}. For other
5247: string-processing words see @ref{Displaying characters and strings}.
1.1 anton 5248:
1.67 anton 5249: A few of these words work on address unit blocks. In that case, you
5250: usually have to insert @code{CHARS} before the word when working on
5251: character strings. Most words work on character blocks, and expect a
5252: char-aligned address.
5253:
5254: When copying characters between overlapping memory regions, use
5255: @code{chars move} or choose carefully between @code{cmove} and
5256: @code{cmove>}.
1.44 crook 5257:
1.1 anton 5258: doc-move
5259: doc-erase
5260: doc-cmove
5261: doc-cmove>
5262: doc-fill
5263: doc-blank
1.21 crook 5264: doc-compare
1.111 anton 5265: doc-str=
5266: doc-str<
5267: doc-string-prefix?
1.21 crook 5268: doc-search
1.27 crook 5269: doc--trailing
5270: doc-/string
1.82 anton 5271: doc-bounds
1.141 anton 5272: doc-pad
1.111 anton 5273:
1.27 crook 5274: @comment TODO examples
5275:
1.1 anton 5276:
1.26 crook 5277: @node Control Structures, Defining Words, Memory, Words
1.1 anton 5278: @section Control Structures
5279: @cindex control structures
5280:
1.33 anton 5281: Control structures in Forth cannot be used interpretively, only in a
5282: colon definition@footnote{To be precise, they have no interpretation
5283: semantics (@pxref{Interpretation and Compilation Semantics}).}. We do
5284: not like this limitation, but have not seen a satisfying way around it
5285: yet, although many schemes have been proposed.
1.1 anton 5286:
5287: @menu
1.33 anton 5288: * Selection:: IF ... ELSE ... ENDIF
5289: * Simple Loops:: BEGIN ...
1.29 crook 5290: * Counted Loops:: DO
1.67 anton 5291: * Arbitrary control structures::
5292: * Calls and returns::
1.1 anton 5293: * Exception Handling::
5294: @end menu
5295:
5296: @node Selection, Simple Loops, Control Structures, Control Structures
5297: @subsection Selection
5298: @cindex selection control structures
5299: @cindex control structures for selection
5300:
5301: @cindex @code{IF} control structure
5302: @example
1.29 crook 5303: @i{flag}
1.1 anton 5304: IF
1.29 crook 5305: @i{code}
1.1 anton 5306: ENDIF
5307: @end example
1.21 crook 5308: @noindent
1.33 anton 5309:
1.44 crook 5310: If @i{flag} is non-zero (as far as @code{IF} etc. are concerned, a cell
5311: with any bit set represents truth) @i{code} is executed.
1.33 anton 5312:
1.1 anton 5313: @example
1.29 crook 5314: @i{flag}
1.1 anton 5315: IF
1.29 crook 5316: @i{code1}
1.1 anton 5317: ELSE
1.29 crook 5318: @i{code2}
1.1 anton 5319: ENDIF
5320: @end example
5321:
1.44 crook 5322: If @var{flag} is true, @i{code1} is executed, otherwise @i{code2} is
5323: executed.
1.33 anton 5324:
1.1 anton 5325: You can use @code{THEN} instead of @code{ENDIF}. Indeed, @code{THEN} is
5326: standard, and @code{ENDIF} is not, although it is quite popular. We
5327: recommend using @code{ENDIF}, because it is less confusing for people
5328: who also know other languages (and is not prone to reinforcing negative
5329: prejudices against Forth in these people). Adding @code{ENDIF} to a
5330: system that only supplies @code{THEN} is simple:
5331: @example
1.82 anton 5332: : ENDIF POSTPONE then ; immediate
1.1 anton 5333: @end example
5334:
5335: [According to @cite{Webster's New Encyclopedic Dictionary}, @dfn{then
5336: (adv.)} has the following meanings:
5337: @quotation
5338: ... 2b: following next after in order ... 3d: as a necessary consequence
5339: (if you were there, then you saw them).
5340: @end quotation
5341: Forth's @code{THEN} has the meaning 2b, whereas @code{THEN} in Pascal
5342: and many other programming languages has the meaning 3d.]
5343:
1.21 crook 5344: Gforth also provides the words @code{?DUP-IF} and @code{?DUP-0=-IF}, so
1.1 anton 5345: you can avoid using @code{?dup}. Using these alternatives is also more
1.26 crook 5346: efficient than using @code{?dup}. Definitions in ANS Forth
1.1 anton 5347: for @code{ENDIF}, @code{?DUP-IF} and @code{?DUP-0=-IF} are provided in
5348: @file{compat/control.fs}.
5349:
5350: @cindex @code{CASE} control structure
5351: @example
1.29 crook 5352: @i{n}
1.1 anton 5353: CASE
1.29 crook 5354: @i{n1} OF @i{code1} ENDOF
5355: @i{n2} OF @i{code2} ENDOF
1.1 anton 5356: @dots{}
1.68 anton 5357: ( n ) @i{default-code} ( n )
1.131 anton 5358: ENDCASE ( )
1.1 anton 5359: @end example
5360:
1.211 anton 5361: Executes the first @i{codei}, where the @i{ni} is equal to @i{n}. If no
5362: @i{ni} matches, the optional @i{default-code} is executed. The optional
5363: default case can be added by simply writing the code after the last
5364: @code{ENDOF}. It may use @i{n}, which is on top of the stack, but must
5365: not consume it. The value @i{n} is consumed by this construction
5366: (either by an @code{OF} that matches, or by the @code{ENDCASE}, if no OF
5367: matches). Example:
5368:
5369: @example
5370: : .spell ( n -- )
5371: case
5372: 0 of ." zero " endof
5373: 1 of ." one " endof
5374: 2 of ." two " endof
5375: dup .
5376: endcase ;
5377: @end example
1.1 anton 5378:
1.69 anton 5379: @progstyle
1.131 anton 5380: To keep the code understandable, you should ensure that you change the
5381: stack in the same way (wrt. number and types of stack items consumed
5382: and pushed) on all paths through a selection construct.
1.69 anton 5383:
1.1 anton 5384: @node Simple Loops, Counted Loops, Selection, Control Structures
5385: @subsection Simple Loops
5386: @cindex simple loops
5387: @cindex loops without count
5388:
5389: @cindex @code{WHILE} loop
5390: @example
5391: BEGIN
1.29 crook 5392: @i{code1}
5393: @i{flag}
1.1 anton 5394: WHILE
1.29 crook 5395: @i{code2}
1.1 anton 5396: REPEAT
5397: @end example
5398:
1.29 crook 5399: @i{code1} is executed and @i{flag} is computed. If it is true,
5400: @i{code2} is executed and the loop is restarted; If @i{flag} is
1.1 anton 5401: false, execution continues after the @code{REPEAT}.
5402:
5403: @cindex @code{UNTIL} loop
5404: @example
5405: BEGIN
1.29 crook 5406: @i{code}
5407: @i{flag}
1.1 anton 5408: UNTIL
5409: @end example
5410:
1.29 crook 5411: @i{code} is executed. The loop is restarted if @code{flag} is false.
1.1 anton 5412:
1.69 anton 5413: @progstyle
5414: To keep the code understandable, a complete iteration of the loop should
5415: not change the number and types of the items on the stacks.
5416:
1.1 anton 5417: @cindex endless loop
5418: @cindex loops, endless
5419: @example
5420: BEGIN
1.29 crook 5421: @i{code}
1.1 anton 5422: AGAIN
5423: @end example
5424:
5425: This is an endless loop.
5426:
5427: @node Counted Loops, Arbitrary control structures, Simple Loops, Control Structures
5428: @subsection Counted Loops
5429: @cindex counted loops
5430: @cindex loops, counted
5431: @cindex @code{DO} loops
5432:
5433: The basic counted loop is:
5434: @example
1.29 crook 5435: @i{limit} @i{start}
1.1 anton 5436: ?DO
1.29 crook 5437: @i{body}
1.1 anton 5438: LOOP
5439: @end example
5440:
1.29 crook 5441: This performs one iteration for every integer, starting from @i{start}
5442: and up to, but excluding @i{limit}. The counter, or @i{index}, can be
1.21 crook 5443: accessed with @code{i}. For example, the loop:
1.1 anton 5444: @example
5445: 10 0 ?DO
5446: i .
5447: LOOP
5448: @end example
1.21 crook 5449: @noindent
5450: prints @code{0 1 2 3 4 5 6 7 8 9}
5451:
1.1 anton 5452: The index of the innermost loop can be accessed with @code{i}, the index
5453: of the next loop with @code{j}, and the index of the third loop with
5454: @code{k}.
5455:
1.44 crook 5456:
1.1 anton 5457: doc-i
5458: doc-j
5459: doc-k
5460:
1.44 crook 5461:
1.1 anton 5462: The loop control data are kept on the return stack, so there are some
1.21 crook 5463: restrictions on mixing return stack accesses and counted loop words. In
5464: particuler, if you put values on the return stack outside the loop, you
5465: cannot read them inside the loop@footnote{well, not in a way that is
5466: portable.}. If you put values on the return stack within a loop, you
5467: have to remove them before the end of the loop and before accessing the
5468: index of the loop.
1.1 anton 5469:
5470: There are several variations on the counted loop:
5471:
1.21 crook 5472: @itemize @bullet
5473: @item
5474: @code{LEAVE} leaves the innermost counted loop immediately; execution
5475: continues after the associated @code{LOOP} or @code{NEXT}. For example:
5476:
5477: @example
5478: 10 0 ?DO i DUP . 3 = IF LEAVE THEN LOOP
5479: @end example
5480: prints @code{0 1 2 3}
5481:
1.1 anton 5482:
1.21 crook 5483: @item
5484: @code{UNLOOP} prepares for an abnormal loop exit, e.g., via
5485: @code{EXIT}. @code{UNLOOP} removes the loop control parameters from the
5486: return stack so @code{EXIT} can get to its return address. For example:
5487:
5488: @example
5489: : demo 10 0 ?DO i DUP . 3 = IF UNLOOP EXIT THEN LOOP ." Done" ;
5490: @end example
5491: prints @code{0 1 2 3}
5492:
5493:
5494: @item
1.29 crook 5495: If @i{start} is greater than @i{limit}, a @code{?DO} loop is entered
1.1 anton 5496: (and @code{LOOP} iterates until they become equal by wrap-around
5497: arithmetic). This behaviour is usually not what you want. Therefore,
5498: Gforth offers @code{+DO} and @code{U+DO} (as replacements for
1.29 crook 5499: @code{?DO}), which do not enter the loop if @i{start} is greater than
5500: @i{limit}; @code{+DO} is for signed loop parameters, @code{U+DO} for
1.1 anton 5501: unsigned loop parameters.
5502:
1.21 crook 5503: @item
5504: @code{?DO} can be replaced by @code{DO}. @code{DO} always enters
5505: the loop, independent of the loop parameters. Do not use @code{DO}, even
5506: if you know that the loop is entered in any case. Such knowledge tends
5507: to become invalid during maintenance of a program, and then the
5508: @code{DO} will make trouble.
5509:
5510: @item
1.29 crook 5511: @code{LOOP} can be replaced with @code{@i{n} +LOOP}; this updates the
5512: index by @i{n} instead of by 1. The loop is terminated when the border
5513: between @i{limit-1} and @i{limit} is crossed. E.g.:
1.1 anton 5514:
1.21 crook 5515: @example
5516: 4 0 +DO i . 2 +LOOP
5517: @end example
5518: @noindent
5519: prints @code{0 2}
5520:
5521: @example
5522: 4 1 +DO i . 2 +LOOP
5523: @end example
5524: @noindent
5525: prints @code{1 3}
1.1 anton 5526:
1.68 anton 5527: @item
1.1 anton 5528: @cindex negative increment for counted loops
5529: @cindex counted loops with negative increment
1.29 crook 5530: The behaviour of @code{@i{n} +LOOP} is peculiar when @i{n} is negative:
1.1 anton 5531:
1.21 crook 5532: @example
5533: -1 0 ?DO i . -1 +LOOP
5534: @end example
5535: @noindent
5536: prints @code{0 -1}
1.1 anton 5537:
1.21 crook 5538: @example
5539: 0 0 ?DO i . -1 +LOOP
5540: @end example
5541: prints nothing.
1.1 anton 5542:
1.29 crook 5543: Therefore we recommend avoiding @code{@i{n} +LOOP} with negative
5544: @i{n}. One alternative is @code{@i{u} -LOOP}, which reduces the
5545: index by @i{u} each iteration. The loop is terminated when the border
5546: between @i{limit+1} and @i{limit} is crossed. Gforth also provides
1.1 anton 5547: @code{-DO} and @code{U-DO} for down-counting loops. E.g.:
5548:
1.21 crook 5549: @example
5550: -2 0 -DO i . 1 -LOOP
5551: @end example
5552: @noindent
5553: prints @code{0 -1}
1.1 anton 5554:
1.21 crook 5555: @example
5556: -1 0 -DO i . 1 -LOOP
5557: @end example
5558: @noindent
5559: prints @code{0}
5560:
5561: @example
5562: 0 0 -DO i . 1 -LOOP
5563: @end example
5564: @noindent
5565: prints nothing.
1.1 anton 5566:
1.21 crook 5567: @end itemize
1.1 anton 5568:
5569: Unfortunately, @code{+DO}, @code{U+DO}, @code{-DO}, @code{U-DO} and
1.26 crook 5570: @code{-LOOP} are not defined in ANS Forth. However, an implementation
5571: for these words that uses only standard words is provided in
5572: @file{compat/loops.fs}.
1.1 anton 5573:
5574:
5575: @cindex @code{FOR} loops
1.26 crook 5576: Another counted loop is:
1.1 anton 5577: @example
1.29 crook 5578: @i{n}
1.1 anton 5579: FOR
1.29 crook 5580: @i{body}
1.1 anton 5581: NEXT
5582: @end example
5583: This is the preferred loop of native code compiler writers who are too
1.26 crook 5584: lazy to optimize @code{?DO} loops properly. This loop structure is not
1.29 crook 5585: defined in ANS Forth. In Gforth, this loop iterates @i{n+1} times;
5586: @code{i} produces values starting with @i{n} and ending with 0. Other
1.26 crook 5587: Forth systems may behave differently, even if they support @code{FOR}
5588: loops. To avoid problems, don't use @code{FOR} loops.
1.1 anton 5589:
5590: @node Arbitrary control structures, Calls and returns, Counted Loops, Control Structures
5591: @subsection Arbitrary control structures
5592: @cindex control structures, user-defined
5593:
5594: @cindex control-flow stack
5595: ANS Forth permits and supports using control structures in a non-nested
5596: way. Information about incomplete control structures is stored on the
5597: control-flow stack. This stack may be implemented on the Forth data
5598: stack, and this is what we have done in Gforth.
5599:
5600: @cindex @code{orig}, control-flow stack item
5601: @cindex @code{dest}, control-flow stack item
5602: An @i{orig} entry represents an unresolved forward branch, a @i{dest}
5603: entry represents a backward branch target. A few words are the basis for
5604: building any control structure possible (except control structures that
5605: need storage, like calls, coroutines, and backtracking).
5606:
1.44 crook 5607:
1.1 anton 5608: doc-if
5609: doc-ahead
5610: doc-then
5611: doc-begin
5612: doc-until
5613: doc-again
5614: doc-cs-pick
5615: doc-cs-roll
5616:
1.44 crook 5617:
1.21 crook 5618: The Standard words @code{CS-PICK} and @code{CS-ROLL} allow you to
5619: manipulate the control-flow stack in a portable way. Without them, you
5620: would need to know how many stack items are occupied by a control-flow
5621: entry (many systems use one cell. In Gforth they currently take three,
5622: but this may change in the future).
5623:
1.1 anton 5624: Some standard control structure words are built from these words:
5625:
1.44 crook 5626:
1.1 anton 5627: doc-else
5628: doc-while
5629: doc-repeat
5630:
1.44 crook 5631:
5632: @noindent
1.1 anton 5633: Gforth adds some more control-structure words:
5634:
1.44 crook 5635:
1.1 anton 5636: doc-endif
5637: doc-?dup-if
5638: doc-?dup-0=-if
5639:
1.44 crook 5640:
5641: @noindent
1.1 anton 5642: Counted loop words constitute a separate group of words:
5643:
1.44 crook 5644:
1.1 anton 5645: doc-?do
5646: doc-+do
5647: doc-u+do
5648: doc--do
5649: doc-u-do
5650: doc-do
5651: doc-for
5652: doc-loop
5653: doc-+loop
5654: doc--loop
5655: doc-next
5656: doc-leave
5657: doc-?leave
5658: doc-unloop
5659: doc-done
5660:
1.44 crook 5661:
1.21 crook 5662: The standard does not allow using @code{CS-PICK} and @code{CS-ROLL} on
5663: @i{do-sys}. Gforth allows it, but it's your job to ensure that for
1.1 anton 5664: every @code{?DO} etc. there is exactly one @code{UNLOOP} on any path
5665: through the definition (@code{LOOP} etc. compile an @code{UNLOOP} on the
5666: fall-through path). Also, you have to ensure that all @code{LEAVE}s are
5667: resolved (by using one of the loop-ending words or @code{DONE}).
5668:
1.44 crook 5669: @noindent
1.26 crook 5670: Another group of control structure words are:
1.1 anton 5671:
1.44 crook 5672:
1.1 anton 5673: doc-case
5674: doc-endcase
5675: doc-of
5676: doc-endof
5677:
1.44 crook 5678:
1.21 crook 5679: @i{case-sys} and @i{of-sys} cannot be processed using @code{CS-PICK} and
5680: @code{CS-ROLL}.
1.1 anton 5681:
5682: @subsubsection Programming Style
1.47 crook 5683: @cindex control structures programming style
5684: @cindex programming style, arbitrary control structures
1.1 anton 5685:
5686: In order to ensure readability we recommend that you do not create
5687: arbitrary control structures directly, but define new control structure
5688: words for the control structure you want and use these words in your
1.26 crook 5689: program. For example, instead of writing:
1.1 anton 5690:
5691: @example
1.26 crook 5692: BEGIN
1.1 anton 5693: ...
1.26 crook 5694: IF [ 1 CS-ROLL ]
1.1 anton 5695: ...
1.26 crook 5696: AGAIN THEN
1.1 anton 5697: @end example
5698:
1.21 crook 5699: @noindent
1.1 anton 5700: we recommend defining control structure words, e.g.,
5701:
5702: @example
1.26 crook 5703: : WHILE ( DEST -- ORIG DEST )
5704: POSTPONE IF
5705: 1 CS-ROLL ; immediate
5706:
5707: : REPEAT ( orig dest -- )
5708: POSTPONE AGAIN
5709: POSTPONE THEN ; immediate
1.1 anton 5710: @end example
5711:
1.21 crook 5712: @noindent
1.1 anton 5713: and then using these to create the control structure:
5714:
5715: @example
1.26 crook 5716: BEGIN
1.1 anton 5717: ...
1.26 crook 5718: WHILE
1.1 anton 5719: ...
1.26 crook 5720: REPEAT
1.1 anton 5721: @end example
5722:
5723: That's much easier to read, isn't it? Of course, @code{REPEAT} and
5724: @code{WHILE} are predefined, so in this example it would not be
5725: necessary to define them.
5726:
5727: @node Calls and returns, Exception Handling, Arbitrary control structures, Control Structures
5728: @subsection Calls and returns
5729: @cindex calling a definition
5730: @cindex returning from a definition
5731:
1.3 anton 5732: @cindex recursive definitions
5733: A definition can be called simply be writing the name of the definition
1.26 crook 5734: to be called. Normally a definition is invisible during its own
1.3 anton 5735: definition. If you want to write a directly recursive definition, you
1.26 crook 5736: can use @code{recursive} to make the current definition visible, or
5737: @code{recurse} to call the current definition directly.
1.3 anton 5738:
1.44 crook 5739:
1.3 anton 5740: doc-recursive
5741: doc-recurse
5742:
1.44 crook 5743:
1.21 crook 5744: @comment TODO add example of the two recursion methods
1.12 anton 5745: @quotation
5746: @progstyle
5747: I prefer using @code{recursive} to @code{recurse}, because calling the
5748: definition by name is more descriptive (if the name is well-chosen) than
5749: the somewhat cryptic @code{recurse}. E.g., in a quicksort
5750: implementation, it is much better to read (and think) ``now sort the
5751: partitions'' than to read ``now do a recursive call''.
5752: @end quotation
1.3 anton 5753:
1.29 crook 5754: For mutual recursion, use @code{Defer}red words, like this:
1.3 anton 5755:
5756: @example
1.28 crook 5757: Defer foo
1.3 anton 5758:
5759: : bar ( ... -- ... )
5760: ... foo ... ;
5761:
5762: :noname ( ... -- ... )
5763: ... bar ... ;
5764: IS foo
5765: @end example
5766:
1.170 pazsan 5767: Deferred words are discussed in more detail in @ref{Deferred Words}.
1.33 anton 5768:
1.26 crook 5769: The current definition returns control to the calling definition when
1.33 anton 5770: the end of the definition is reached or @code{EXIT} is encountered.
1.1 anton 5771:
5772: doc-exit
5773: doc-;s
5774:
1.44 crook 5775:
1.1 anton 5776: @node Exception Handling, , Calls and returns, Control Structures
5777: @subsection Exception Handling
1.26 crook 5778: @cindex exceptions
1.1 anton 5779:
1.68 anton 5780: @c quit is a very bad idea for error handling,
5781: @c because it does not translate into a THROW
5782: @c it also does not belong into this chapter
5783:
5784: If a word detects an error condition that it cannot handle, it can
5785: @code{throw} an exception. In the simplest case, this will terminate
5786: your program, and report an appropriate error.
1.21 crook 5787:
1.68 anton 5788: doc-throw
1.1 anton 5789:
1.69 anton 5790: @code{Throw} consumes a cell-sized error number on the stack. There are
5791: some predefined error numbers in ANS Forth (see @file{errors.fs}). In
5792: Gforth (and most other systems) you can use the iors produced by various
5793: words as error numbers (e.g., a typical use of @code{allocate} is
5794: @code{allocate throw}). Gforth also provides the word @code{exception}
5795: to define your own error numbers (with decent error reporting); an ANS
5796: Forth version of this word (but without the error messages) is available
5797: in @code{compat/except.fs}. And finally, you can use your own error
1.68 anton 5798: numbers (anything outside the range -4095..0), but won't get nice error
5799: messages, only numbers. For example, try:
5800:
5801: @example
1.69 anton 5802: -10 throw \ ANS defined
5803: -267 throw \ system defined
5804: s" my error" exception throw \ user defined
5805: 7 throw \ arbitrary number
1.68 anton 5806: @end example
5807:
5808: doc---exception-exception
1.1 anton 5809:
1.69 anton 5810: A common idiom to @code{THROW} a specific error if a flag is true is
5811: this:
5812:
5813: @example
5814: @code{( flag ) 0<> @i{errno} and throw}
5815: @end example
5816:
5817: Your program can provide exception handlers to catch exceptions. An
5818: exception handler can be used to correct the problem, or to clean up
5819: some data structures and just throw the exception to the next exception
5820: handler. Note that @code{throw} jumps to the dynamically innermost
5821: exception handler. The system's exception handler is outermost, and just
5822: prints an error and restarts command-line interpretation (or, in batch
5823: mode (i.e., while processing the shell command line), leaves Gforth).
1.1 anton 5824:
1.68 anton 5825: The ANS Forth way to catch exceptions is @code{catch}:
1.1 anton 5826:
1.68 anton 5827: doc-catch
1.160 anton 5828: doc-nothrow
1.68 anton 5829:
5830: The most common use of exception handlers is to clean up the state when
5831: an error happens. E.g.,
1.1 anton 5832:
1.26 crook 5833: @example
1.68 anton 5834: base @ >r hex \ actually the hex should be inside foo, or we h
5835: ['] foo catch ( nerror|0 )
5836: r> base !
1.69 anton 5837: ( nerror|0 ) throw \ pass it on
1.26 crook 5838: @end example
1.1 anton 5839:
1.69 anton 5840: A use of @code{catch} for handling the error @code{myerror} might look
5841: like this:
1.44 crook 5842:
1.68 anton 5843: @example
1.69 anton 5844: ['] foo catch
5845: CASE
1.160 anton 5846: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5847: dup throw \ default: pass other errors on, do nothing on non-errors
5848: ENDCASE
1.68 anton 5849: @end example
1.44 crook 5850:
1.68 anton 5851: Having to wrap the code into a separate word is often cumbersome,
5852: therefore Gforth provides an alternative syntax:
1.1 anton 5853:
5854: @example
1.69 anton 5855: TRY
1.68 anton 5856: @i{code1}
1.172 anton 5857: IFERROR
5858: @i{code2}
5859: THEN
5860: @i{code3}
1.69 anton 5861: ENDTRY
1.1 anton 5862: @end example
5863:
1.172 anton 5864: This performs @i{code1}. If @i{code1} completes normally, execution
1.201 anton 5865: continues with @i{code3}. If there is an exception in @i{code1} or
5866: before @code{endtry}, the stacks are reset to the depth during
1.172 anton 5867: @code{try}, the throw value is pushed on the data stack, and execution
1.201 anton 5868: constinues at @i{code2}, and finally falls through to @i{code3}.
1.26 crook 5869:
1.68 anton 5870: doc-try
5871: doc-endtry
1.172 anton 5872: doc-iferror
5873:
5874: If you don't need @i{code2}, you can write @code{restore} instead of
5875: @code{iferror then}:
5876:
5877: @example
5878: TRY
5879: @i{code1}
5880: RESTORE
5881: @i{code3}
5882: ENDTRY
5883: @end example
1.26 crook 5884:
1.172 anton 5885: @cindex unwind-protect
1.69 anton 5886: The cleanup example from above in this syntax:
1.26 crook 5887:
1.68 anton 5888: @example
1.174 anton 5889: base @@ @{ oldbase @}
1.172 anton 5890: TRY
1.68 anton 5891: hex foo \ now the hex is placed correctly
1.69 anton 5892: 0 \ value for throw
1.172 anton 5893: RESTORE
5894: oldbase base !
5895: ENDTRY
5896: throw
1.1 anton 5897: @end example
5898:
1.172 anton 5899: An additional advantage of this variant is that an exception between
5900: @code{restore} and @code{endtry} (e.g., from the user pressing
5901: @kbd{Ctrl-C}) restarts the execution of the code after @code{restore},
5902: so the base will be restored under all circumstances.
5903:
5904: However, you have to ensure that this code does not cause an exception
5905: itself, otherwise the @code{iferror}/@code{restore} code will loop.
5906: Moreover, you should also make sure that the stack contents needed by
5907: the @code{iferror}/@code{restore} code exist everywhere between
5908: @code{try} and @code{endtry}; in our example this is achived by
5909: putting the data in a local before the @code{try} (you cannot use the
5910: return stack because the exception frame (@i{sys1}) is in the way
5911: there).
5912:
5913: This kind of usage corresponds to Lisp's @code{unwind-protect}.
5914:
5915: @cindex @code{recover} (old Gforth versions)
5916: If you do not want this exception-restarting behaviour, you achieve
5917: this as follows:
5918:
5919: @example
5920: TRY
5921: @i{code1}
5922: ENDTRY-IFERROR
5923: @i{code2}
5924: THEN
5925: @end example
5926:
5927: If there is an exception in @i{code1}, then @i{code2} is executed,
5928: otherwise execution continues behind the @code{then} (or in a possible
5929: @code{else} branch). This corresponds to the construct
5930:
5931: @example
5932: TRY
5933: @i{code1}
5934: RECOVER
5935: @i{code2}
5936: ENDTRY
5937: @end example
5938:
5939: in Gforth before version 0.7. So you can directly replace
5940: @code{recover}-using code; however, we recommend that you check if it
5941: would not be better to use one of the other @code{try} variants while
5942: you are at it.
5943:
1.173 anton 5944: To ease the transition, Gforth provides two compatibility files:
5945: @file{endtry-iferror.fs} provides the @code{try ... endtry-iferror
5946: ... then} syntax (but not @code{iferror} or @code{restore}) for old
5947: systems; @file{recover-endtry.fs} provides the @code{try ... recover
5948: ... endtry} syntax on new systems, so you can use that file as a
5949: stopgap to run old programs. Both files work on any system (they just
5950: do nothing if the system already has the syntax it implements), so you
5951: can unconditionally @code{require} one of these files, even if you use
5952: a mix old and new systems.
5953:
1.172 anton 5954: doc-restore
5955: doc-endtry-iferror
5956:
5957: Here's the error handling example:
1.1 anton 5958:
1.68 anton 5959: @example
1.69 anton 5960: TRY
1.68 anton 5961: foo
1.172 anton 5962: ENDTRY-IFERROR
1.69 anton 5963: CASE
1.160 anton 5964: myerror OF ... ( do something about it ) nothrow ENDOF
1.69 anton 5965: throw \ pass other errors on
5966: ENDCASE
1.172 anton 5967: THEN
1.68 anton 5968: @end example
1.1 anton 5969:
1.69 anton 5970: @progstyle
5971: As usual, you should ensure that the stack depth is statically known at
5972: the end: either after the @code{throw} for passing on errors, or after
5973: the @code{ENDTRY} (or, if you use @code{catch}, after the end of the
5974: selection construct for handling the error).
5975:
1.68 anton 5976: There are two alternatives to @code{throw}: @code{Abort"} is conditional
5977: and you can provide an error message. @code{Abort} just produces an
5978: ``Aborted'' error.
1.1 anton 5979:
1.68 anton 5980: The problem with these words is that exception handlers cannot
5981: differentiate between different @code{abort"}s; they just look like
5982: @code{-2 throw} to them (the error message cannot be accessed by
5983: standard programs). Similar @code{abort} looks like @code{-1 throw} to
5984: exception handlers.
1.44 crook 5985:
1.68 anton 5986: doc-abort"
1.26 crook 5987: doc-abort
1.29 crook 5988:
5989:
1.44 crook 5990:
1.29 crook 5991: @c -------------------------------------------------------------
1.47 crook 5992: @node Defining Words, Interpretation and Compilation Semantics, Control Structures, Words
1.29 crook 5993: @section Defining Words
5994: @cindex defining words
5995:
1.47 crook 5996: Defining words are used to extend Forth by creating new entries in the dictionary.
5997:
1.29 crook 5998: @menu
1.67 anton 5999: * CREATE::
1.44 crook 6000: * Variables:: Variables and user variables
1.67 anton 6001: * Constants::
1.44 crook 6002: * Values:: Initialised variables
1.67 anton 6003: * Colon Definitions::
1.44 crook 6004: * Anonymous Definitions:: Definitions without names
1.69 anton 6005: * Supplying names:: Passing definition names as strings
1.67 anton 6006: * User-defined Defining Words::
1.170 pazsan 6007: * Deferred Words:: Allow forward references
1.67 anton 6008: * Aliases::
1.29 crook 6009: @end menu
6010:
1.44 crook 6011: @node CREATE, Variables, Defining Words, Defining Words
6012: @subsection @code{CREATE}
1.29 crook 6013: @cindex simple defining words
6014: @cindex defining words, simple
6015:
6016: Defining words are used to create new entries in the dictionary. The
6017: simplest defining word is @code{CREATE}. @code{CREATE} is used like
6018: this:
6019:
6020: @example
6021: CREATE new-word1
6022: @end example
6023:
1.69 anton 6024: @code{CREATE} is a parsing word, i.e., it takes an argument from the
6025: input stream (@code{new-word1} in our example). It generates a
6026: dictionary entry for @code{new-word1}. When @code{new-word1} is
6027: executed, all that it does is leave an address on the stack. The address
6028: represents the value of the data space pointer (@code{HERE}) at the time
6029: that @code{new-word1} was defined. Therefore, @code{CREATE} is a way of
6030: associating a name with the address of a region of memory.
1.29 crook 6031:
1.34 anton 6032: doc-create
6033:
1.69 anton 6034: Note that in ANS Forth guarantees only for @code{create} that its body
6035: is in dictionary data space (i.e., where @code{here}, @code{allot}
6036: etc. work, @pxref{Dictionary allocation}). Also, in ANS Forth only
6037: @code{create}d words can be modified with @code{does>}
6038: (@pxref{User-defined Defining Words}). And in ANS Forth @code{>body}
6039: can only be applied to @code{create}d words.
6040:
1.29 crook 6041: By extending this example to reserve some memory in data space, we end
1.69 anton 6042: up with something like a @i{variable}. Here are two different ways to do
6043: it:
1.29 crook 6044:
6045: @example
6046: CREATE new-word2 1 cells allot \ reserve 1 cell - initial value undefined
6047: CREATE new-word3 4 , \ reserve 1 cell and initialise it (to 4)
6048: @end example
6049:
6050: The variable can be examined and modified using @code{@@} (``fetch'') and
6051: @code{!} (``store'') like this:
6052:
6053: @example
6054: new-word2 @@ . \ get address, fetch from it and display
6055: 1234 new-word2 ! \ new value, get address, store to it
6056: @end example
6057:
1.44 crook 6058: @cindex arrays
6059: A similar mechanism can be used to create arrays. For example, an
6060: 80-character text input buffer:
1.29 crook 6061:
6062: @example
1.44 crook 6063: CREATE text-buf 80 chars allot
6064:
1.168 anton 6065: text-buf 0 chars + c@@ \ the 1st character (offset 0)
6066: text-buf 3 chars + c@@ \ the 4th character (offset 3)
1.44 crook 6067: @end example
1.29 crook 6068:
1.44 crook 6069: You can build arbitrarily complex data structures by allocating
1.49 anton 6070: appropriate areas of memory. For further discussions of this, and to
1.66 anton 6071: learn about some Gforth tools that make it easier,
1.49 anton 6072: @xref{Structures}.
1.44 crook 6073:
6074:
6075: @node Variables, Constants, CREATE, Defining Words
6076: @subsection Variables
6077: @cindex variables
6078:
6079: The previous section showed how a sequence of commands could be used to
6080: generate a variable. As a final refinement, the whole code sequence can
6081: be wrapped up in a defining word (pre-empting the subject of the next
6082: section), making it easier to create new variables:
6083:
6084: @example
6085: : myvariableX ( "name" -- a-addr ) CREATE 1 cells allot ;
6086: : myvariable0 ( "name" -- a-addr ) CREATE 0 , ;
6087:
6088: myvariableX foo \ variable foo starts off with an unknown value
6089: myvariable0 joe \ whilst joe is initialised to 0
1.29 crook 6090:
6091: 45 3 * foo ! \ set foo to 135
6092: 1234 joe ! \ set joe to 1234
6093: 3 joe +! \ increment joe by 3.. to 1237
6094: @end example
6095:
6096: Not surprisingly, there is no need to define @code{myvariable}, since
1.44 crook 6097: Forth already has a definition @code{Variable}. ANS Forth does not
1.69 anton 6098: guarantee that a @code{Variable} is initialised when it is created
6099: (i.e., it may behave like @code{myvariableX}). In contrast, Gforth's
6100: @code{Variable} initialises the variable to 0 (i.e., it behaves exactly
6101: like @code{myvariable0}). Forth also provides @code{2Variable} and
1.47 crook 6102: @code{fvariable} for double and floating-point variables, respectively
1.69 anton 6103: -- they are initialised to 0. and 0e in Gforth. If you use a @code{Variable} to
1.47 crook 6104: store a boolean, you can use @code{on} and @code{off} to toggle its
6105: state.
1.29 crook 6106:
1.34 anton 6107: doc-variable
6108: doc-2variable
6109: doc-fvariable
6110:
1.29 crook 6111: @cindex user variables
6112: @cindex user space
6113: The defining word @code{User} behaves in the same way as @code{Variable}.
6114: The difference is that it reserves space in @i{user (data) space} rather
6115: than normal data space. In a Forth system that has a multi-tasker, each
6116: task has its own set of user variables.
6117:
1.34 anton 6118: doc-user
1.67 anton 6119: @c doc-udp
6120: @c doc-uallot
1.34 anton 6121:
1.29 crook 6122: @comment TODO is that stuff about user variables strictly correct? Is it
6123: @comment just terminal tasks that have user variables?
6124: @comment should document tasker.fs (with some examples) elsewhere
6125: @comment in this manual, then expand on user space and user variables.
6126:
1.44 crook 6127: @node Constants, Values, Variables, Defining Words
6128: @subsection Constants
6129: @cindex constants
6130:
6131: @code{Constant} allows you to declare a fixed value and refer to it by
6132: name. For example:
1.29 crook 6133:
6134: @example
6135: 12 Constant INCHES-PER-FOOT
6136: 3E+08 fconstant SPEED-O-LIGHT
6137: @end example
6138:
6139: A @code{Variable} can be both read and written, so its run-time
6140: behaviour is to supply an address through which its current value can be
6141: manipulated. In contrast, the value of a @code{Constant} cannot be
6142: changed once it has been declared@footnote{Well, often it can be -- but
6143: not in a Standard, portable way. It's safer to use a @code{Value} (read
6144: on).} so it's not necessary to supply the address -- it is more
6145: efficient to return the value of the constant directly. That's exactly
6146: what happens; the run-time effect of a constant is to put its value on
1.49 anton 6147: the top of the stack (You can find one
6148: way of implementing @code{Constant} in @ref{User-defined Defining Words}).
1.29 crook 6149:
1.69 anton 6150: Forth also provides @code{2Constant} and @code{fconstant} for defining
1.29 crook 6151: double and floating-point constants, respectively.
6152:
1.34 anton 6153: doc-constant
6154: doc-2constant
6155: doc-fconstant
6156:
6157: @c that's too deep, and it's not necessarily true for all ANS Forths. - anton
1.44 crook 6158: @c nac-> How could that not be true in an ANS Forth? You can't define a
6159: @c constant, use it and then delete the definition of the constant..
1.69 anton 6160:
6161: @c anton->An ANS Forth system can compile a constant to a literal; On
6162: @c decompilation you would see only the number, just as if it had been used
6163: @c in the first place. The word will stay, of course, but it will only be
6164: @c used by the text interpreter (no run-time duties, except when it is
6165: @c POSTPONEd or somesuch).
6166:
6167: @c nac:
1.44 crook 6168: @c I agree that it's rather deep, but IMO it is an important difference
6169: @c relative to other programming languages.. often it's annoying: it
6170: @c certainly changes my programming style relative to C.
6171:
1.69 anton 6172: @c anton: In what way?
6173:
1.29 crook 6174: Constants in Forth behave differently from their equivalents in other
6175: programming languages. In other languages, a constant (such as an EQU in
6176: assembler or a #define in C) only exists at compile-time; in the
6177: executable program the constant has been translated into an absolute
6178: number and, unless you are using a symbolic debugger, it's impossible to
6179: know what abstract thing that number represents. In Forth a constant has
1.44 crook 6180: an entry in the header space and remains there after the code that uses
6181: it has been defined. In fact, it must remain in the dictionary since it
6182: has run-time duties to perform. For example:
1.29 crook 6183:
6184: @example
6185: 12 Constant INCHES-PER-FOOT
6186: : FEET-TO-INCHES ( n1 -- n2 ) INCHES-PER-FOOT * ;
6187: @end example
6188:
6189: @cindex in-lining of constants
6190: When @code{FEET-TO-INCHES} is executed, it will in turn execute the xt
6191: associated with the constant @code{INCHES-PER-FOOT}. If you use
6192: @code{see} to decompile the definition of @code{FEET-TO-INCHES}, you can
6193: see that it makes a call to @code{INCHES-PER-FOOT}. Some Forth compilers
6194: attempt to optimise constants by in-lining them where they are used. You
6195: can force Gforth to in-line a constant like this:
6196:
6197: @example
6198: : FEET-TO-INCHES ( n1 -- n2 ) [ INCHES-PER-FOOT ] LITERAL * ;
6199: @end example
6200:
6201: If you use @code{see} to decompile @i{this} version of
6202: @code{FEET-TO-INCHES}, you can see that @code{INCHES-PER-FOOT} is no
1.49 anton 6203: longer present. To understand how this works, read
6204: @ref{Interpret/Compile states}, and @ref{Literals}.
1.29 crook 6205:
6206: In-lining constants in this way might improve execution time
6207: fractionally, and can ensure that a constant is now only referenced at
6208: compile-time. However, the definition of the constant still remains in
6209: the dictionary. Some Forth compilers provide a mechanism for controlling
6210: a second dictionary for holding transient words such that this second
6211: dictionary can be deleted later in order to recover memory
6212: space. However, there is no standard way of doing this.
6213:
6214:
1.44 crook 6215: @node Values, Colon Definitions, Constants, Defining Words
6216: @subsection Values
6217: @cindex values
1.34 anton 6218:
1.69 anton 6219: A @code{Value} behaves like a @code{Constant}, but it can be changed.
6220: @code{TO} is a parsing word that changes a @code{Values}. In Gforth
6221: (not in ANS Forth) you can access (and change) a @code{value} also with
6222: @code{>body}.
6223:
6224: Here are some
6225: examples:
1.29 crook 6226:
6227: @example
1.69 anton 6228: 12 Value APPLES \ Define APPLES with an initial value of 12
6229: 34 TO APPLES \ Change the value of APPLES. TO is a parsing word
6230: 1 ' APPLES >body +! \ Increment APPLES. Non-standard usage.
6231: APPLES \ puts 35 on the top of the stack.
1.29 crook 6232: @end example
6233:
1.44 crook 6234: doc-value
6235: doc-to
1.29 crook 6236:
1.35 anton 6237:
1.69 anton 6238:
1.44 crook 6239: @node Colon Definitions, Anonymous Definitions, Values, Defining Words
6240: @subsection Colon Definitions
6241: @cindex colon definitions
1.35 anton 6242:
6243: @example
1.44 crook 6244: : name ( ... -- ... )
6245: word1 word2 word3 ;
1.29 crook 6246: @end example
6247:
1.44 crook 6248: @noindent
6249: Creates a word called @code{name} that, upon execution, executes
6250: @code{word1 word2 word3}. @code{name} is a @dfn{(colon) definition}.
1.29 crook 6251:
1.49 anton 6252: The explanation above is somewhat superficial. For simple examples of
6253: colon definitions see @ref{Your first definition}. For an in-depth
1.66 anton 6254: discussion of some of the issues involved, @xref{Interpretation and
1.49 anton 6255: Compilation Semantics}.
1.29 crook 6256:
1.44 crook 6257: doc-:
6258: doc-;
1.1 anton 6259:
1.34 anton 6260:
1.69 anton 6261: @node Anonymous Definitions, Supplying names, Colon Definitions, Defining Words
1.44 crook 6262: @subsection Anonymous Definitions
6263: @cindex colon definitions
6264: @cindex defining words without name
1.34 anton 6265:
1.44 crook 6266: Sometimes you want to define an @dfn{anonymous word}; a word without a
6267: name. You can do this with:
1.1 anton 6268:
1.44 crook 6269: doc-:noname
1.1 anton 6270:
1.44 crook 6271: This leaves the execution token for the word on the stack after the
6272: closing @code{;}. Here's an example in which a deferred word is
6273: initialised with an @code{xt} from an anonymous colon definition:
1.1 anton 6274:
1.29 crook 6275: @example
1.44 crook 6276: Defer deferred
6277: :noname ( ... -- ... )
6278: ... ;
6279: IS deferred
1.29 crook 6280: @end example
1.26 crook 6281:
1.44 crook 6282: @noindent
6283: Gforth provides an alternative way of doing this, using two separate
6284: words:
1.27 crook 6285:
1.44 crook 6286: doc-noname
6287: @cindex execution token of last defined word
1.116 anton 6288: doc-latestxt
1.1 anton 6289:
1.44 crook 6290: @noindent
6291: The previous example can be rewritten using @code{noname} and
1.116 anton 6292: @code{latestxt}:
1.1 anton 6293:
1.26 crook 6294: @example
1.44 crook 6295: Defer deferred
6296: noname : ( ... -- ... )
6297: ... ;
1.116 anton 6298: latestxt IS deferred
1.26 crook 6299: @end example
1.1 anton 6300:
1.29 crook 6301: @noindent
1.44 crook 6302: @code{noname} works with any defining word, not just @code{:}.
6303:
1.116 anton 6304: @code{latestxt} also works when the last word was not defined as
1.71 anton 6305: @code{noname}. It does not work for combined words, though. It also has
6306: the useful property that is is valid as soon as the header for a
6307: definition has been built. Thus:
1.44 crook 6308:
6309: @example
1.116 anton 6310: latestxt . : foo [ latestxt . ] ; ' foo .
1.44 crook 6311: @end example
1.1 anton 6312:
1.44 crook 6313: @noindent
6314: prints 3 numbers; the last two are the same.
1.26 crook 6315:
1.69 anton 6316: @node Supplying names, User-defined Defining Words, Anonymous Definitions, Defining Words
6317: @subsection Supplying the name of a defined word
6318: @cindex names for defined words
6319: @cindex defining words, name given in a string
6320:
6321: By default, a defining word takes the name for the defined word from the
6322: input stream. Sometimes you want to supply the name from a string. You
6323: can do this with:
6324:
6325: doc-nextname
6326:
6327: For example:
6328:
6329: @example
6330: s" foo" nextname create
6331: @end example
6332:
6333: @noindent
6334: is equivalent to:
6335:
6336: @example
6337: create foo
6338: @end example
6339:
6340: @noindent
6341: @code{nextname} works with any defining word.
6342:
1.1 anton 6343:
1.170 pazsan 6344: @node User-defined Defining Words, Deferred Words, Supplying names, Defining Words
1.26 crook 6345: @subsection User-defined Defining Words
6346: @cindex user-defined defining words
6347: @cindex defining words, user-defined
1.1 anton 6348:
1.29 crook 6349: You can create a new defining word by wrapping defining-time code around
6350: an existing defining word and putting the sequence in a colon
1.69 anton 6351: definition.
6352:
6353: @c anton: This example is very complex and leads in a quite different
6354: @c direction from the CREATE-DOES> stuff that follows. It should probably
6355: @c be done elsewhere, or as a subsubsection of this subsection (or as a
6356: @c subsection of Defining Words)
6357:
6358: For example, suppose that you have a word @code{stats} that
1.29 crook 6359: gathers statistics about colon definitions given the @i{xt} of the
6360: definition, and you want every colon definition in your application to
6361: make a call to @code{stats}. You can define and use a new version of
6362: @code{:} like this:
6363:
6364: @example
6365: : stats ( xt -- ) DUP ." (Gathering statistics for " . ." )"
6366: ... ; \ other code
6367:
1.116 anton 6368: : my: : latestxt postpone literal ['] stats compile, ;
1.29 crook 6369:
6370: my: foo + - ;
6371: @end example
6372:
6373: When @code{foo} is defined using @code{my:} these steps occur:
6374:
6375: @itemize @bullet
6376: @item
6377: @code{my:} is executed.
6378: @item
6379: The @code{:} within the definition (the one between @code{my:} and
1.116 anton 6380: @code{latestxt}) is executed, and does just what it always does; it parses
1.29 crook 6381: the input stream for a name, builds a dictionary header for the name
6382: @code{foo} and switches @code{state} from interpret to compile.
6383: @item
1.116 anton 6384: The word @code{latestxt} is executed. It puts the @i{xt} for the word that is
1.29 crook 6385: being defined -- @code{foo} -- onto the stack.
6386: @item
6387: The code that was produced by @code{postpone literal} is executed; this
6388: causes the value on the stack to be compiled as a literal in the code
6389: area of @code{foo}.
6390: @item
6391: The code @code{['] stats} compiles a literal into the definition of
6392: @code{my:}. When @code{compile,} is executed, that literal -- the
6393: execution token for @code{stats} -- is layed down in the code area of
6394: @code{foo} , following the literal@footnote{Strictly speaking, the
6395: mechanism that @code{compile,} uses to convert an @i{xt} into something
6396: in the code area is implementation-dependent. A threaded implementation
6397: might spit out the execution token directly whilst another
6398: implementation might spit out a native code sequence.}.
6399: @item
6400: At this point, the execution of @code{my:} is complete, and control
6401: returns to the text interpreter. The text interpreter is in compile
6402: state, so subsequent text @code{+ -} is compiled into the definition of
6403: @code{foo} and the @code{;} terminates the definition as always.
6404: @end itemize
6405:
6406: You can use @code{see} to decompile a word that was defined using
6407: @code{my:} and see how it is different from a normal @code{:}
6408: definition. For example:
6409:
6410: @example
6411: : bar + - ; \ like foo but using : rather than my:
6412: see bar
6413: : bar
6414: + - ;
6415: see foo
6416: : foo
6417: 107645672 stats + - ;
6418:
1.140 anton 6419: \ use ' foo . to show that 107645672 is the xt for foo
1.29 crook 6420: @end example
6421:
6422: You can use techniques like this to make new defining words in terms of
6423: @i{any} existing defining word.
1.1 anton 6424:
6425:
1.29 crook 6426: @cindex defining defining words
1.26 crook 6427: @cindex @code{CREATE} ... @code{DOES>}
6428: If you want the words defined with your defining words to behave
6429: differently from words defined with standard defining words, you can
6430: write your defining word like this:
1.1 anton 6431:
6432: @example
1.26 crook 6433: : def-word ( "name" -- )
1.29 crook 6434: CREATE @i{code1}
1.26 crook 6435: DOES> ( ... -- ... )
1.29 crook 6436: @i{code2} ;
1.26 crook 6437:
6438: def-word name
1.1 anton 6439: @end example
6440:
1.29 crook 6441: @cindex child words
6442: This fragment defines a @dfn{defining word} @code{def-word} and then
6443: executes it. When @code{def-word} executes, it @code{CREATE}s a new
6444: word, @code{name}, and executes the code @i{code1}. The code @i{code2}
6445: is not executed at this time. The word @code{name} is sometimes called a
6446: @dfn{child} of @code{def-word}.
6447:
6448: When you execute @code{name}, the address of the body of @code{name} is
6449: put on the data stack and @i{code2} is executed (the address of the body
6450: of @code{name} is the address @code{HERE} returns immediately after the
1.69 anton 6451: @code{CREATE}, i.e., the address a @code{create}d word returns by
6452: default).
6453:
6454: @c anton:
6455: @c www.dictionary.com says:
6456: @c at·a·vism: 1.The reappearance of a characteristic in an organism after
6457: @c several generations of absence, usually caused by the chance
6458: @c recombination of genes. 2.An individual or a part that exhibits
6459: @c atavism. Also called throwback. 3.The return of a trait or recurrence
6460: @c of previous behavior after a period of absence.
6461: @c
6462: @c Doesn't seem to fit.
1.29 crook 6463:
1.69 anton 6464: @c @cindex atavism in child words
1.33 anton 6465: You can use @code{def-word} to define a set of child words that behave
1.69 anton 6466: similarly; they all have a common run-time behaviour determined by
6467: @i{code2}. Typically, the @i{code1} sequence builds a data area in the
6468: body of the child word. The structure of the data is common to all
6469: children of @code{def-word}, but the data values are specific -- and
6470: private -- to each child word. When a child word is executed, the
6471: address of its private data area is passed as a parameter on TOS to be
6472: used and manipulated@footnote{It is legitimate both to read and write to
6473: this data area.} by @i{code2}.
1.29 crook 6474:
6475: The two fragments of code that make up the defining words act (are
6476: executed) at two completely separate times:
1.1 anton 6477:
1.29 crook 6478: @itemize @bullet
6479: @item
6480: At @i{define time}, the defining word executes @i{code1} to generate a
6481: child word
6482: @item
6483: At @i{child execution time}, when a child word is invoked, @i{code2}
6484: is executed, using parameters (data) that are private and specific to
6485: the child word.
6486: @end itemize
6487:
1.44 crook 6488: Another way of understanding the behaviour of @code{def-word} and
6489: @code{name} is to say that, if you make the following definitions:
1.33 anton 6490: @example
6491: : def-word1 ( "name" -- )
6492: CREATE @i{code1} ;
6493:
6494: : action1 ( ... -- ... )
6495: @i{code2} ;
6496:
6497: def-word1 name1
6498: @end example
6499:
1.44 crook 6500: @noindent
6501: Then using @code{name1 action1} is equivalent to using @code{name}.
1.1 anton 6502:
1.29 crook 6503: The classic example is that you can define @code{CONSTANT} in this way:
1.26 crook 6504:
1.1 anton 6505: @example
1.29 crook 6506: : CONSTANT ( w "name" -- )
6507: CREATE ,
1.26 crook 6508: DOES> ( -- w )
6509: @@ ;
1.1 anton 6510: @end example
6511:
1.29 crook 6512: @comment There is a beautiful description of how this works and what
6513: @comment it does in the Forthwrite 100th edition.. as well as an elegant
6514: @comment commentary on the Counting Fruits problem.
6515:
6516: When you create a constant with @code{5 CONSTANT five}, a set of
6517: define-time actions take place; first a new word @code{five} is created,
6518: then the value 5 is laid down in the body of @code{five} with
1.44 crook 6519: @code{,}. When @code{five} is executed, the address of the body is put on
1.29 crook 6520: the stack, and @code{@@} retrieves the value 5. The word @code{five} has
6521: no code of its own; it simply contains a data field and a pointer to the
6522: code that follows @code{DOES>} in its defining word. That makes words
6523: created in this way very compact.
6524:
6525: The final example in this section is intended to remind you that space
6526: reserved in @code{CREATE}d words is @i{data} space and therefore can be
6527: both read and written by a Standard program@footnote{Exercise: use this
6528: example as a starting point for your own implementation of @code{Value}
6529: and @code{TO} -- if you get stuck, investigate the behaviour of @code{'} and
6530: @code{[']}.}:
6531:
6532: @example
6533: : foo ( "name" -- )
6534: CREATE -1 ,
6535: DOES> ( -- )
1.33 anton 6536: @@ . ;
1.29 crook 6537:
6538: foo first-word
6539: foo second-word
6540:
6541: 123 ' first-word >BODY !
6542: @end example
6543:
6544: If @code{first-word} had been a @code{CREATE}d word, we could simply
6545: have executed it to get the address of its data field. However, since it
6546: was defined to have @code{DOES>} actions, its execution semantics are to
6547: perform those @code{DOES>} actions. To get the address of its data field
6548: it's necessary to use @code{'} to get its xt, then @code{>BODY} to
6549: translate the xt into the address of the data field. When you execute
6550: @code{first-word}, it will display @code{123}. When you execute
6551: @code{second-word} it will display @code{-1}.
1.26 crook 6552:
6553: @cindex stack effect of @code{DOES>}-parts
6554: @cindex @code{DOES>}-parts, stack effect
1.29 crook 6555: In the examples above the stack comment after the @code{DOES>} specifies
1.26 crook 6556: the stack effect of the defined words, not the stack effect of the
6557: following code (the following code expects the address of the body on
6558: the top of stack, which is not reflected in the stack comment). This is
6559: the convention that I use and recommend (it clashes a bit with using
6560: locals declarations for stack effect specification, though).
1.1 anton 6561:
1.53 anton 6562: @menu
6563: * CREATE..DOES> applications::
6564: * CREATE..DOES> details::
1.63 anton 6565: * Advanced does> usage example::
1.155 anton 6566: * Const-does>::
1.53 anton 6567: @end menu
6568:
6569: @node CREATE..DOES> applications, CREATE..DOES> details, User-defined Defining Words, User-defined Defining Words
1.26 crook 6570: @subsubsection Applications of @code{CREATE..DOES>}
6571: @cindex @code{CREATE} ... @code{DOES>}, applications
1.1 anton 6572:
1.26 crook 6573: You may wonder how to use this feature. Here are some usage patterns:
1.1 anton 6574:
1.26 crook 6575: @cindex factoring similar colon definitions
6576: When you see a sequence of code occurring several times, and you can
6577: identify a meaning, you will factor it out as a colon definition. When
6578: you see similar colon definitions, you can factor them using
6579: @code{CREATE..DOES>}. E.g., an assembler usually defines several words
6580: that look very similar:
1.1 anton 6581: @example
1.26 crook 6582: : ori, ( reg-target reg-source n -- )
6583: 0 asm-reg-reg-imm ;
6584: : andi, ( reg-target reg-source n -- )
6585: 1 asm-reg-reg-imm ;
1.1 anton 6586: @end example
6587:
1.26 crook 6588: @noindent
6589: This could be factored with:
6590: @example
6591: : reg-reg-imm ( op-code -- )
6592: CREATE ,
6593: DOES> ( reg-target reg-source n -- )
6594: @@ asm-reg-reg-imm ;
6595:
6596: 0 reg-reg-imm ori,
6597: 1 reg-reg-imm andi,
6598: @end example
1.1 anton 6599:
1.26 crook 6600: @cindex currying
6601: Another view of @code{CREATE..DOES>} is to consider it as a crude way to
6602: supply a part of the parameters for a word (known as @dfn{currying} in
6603: the functional language community). E.g., @code{+} needs two
6604: parameters. Creating versions of @code{+} with one parameter fixed can
6605: be done like this:
1.82 anton 6606:
1.1 anton 6607: @example
1.82 anton 6608: : curry+ ( n1 "name" -- )
1.26 crook 6609: CREATE ,
6610: DOES> ( n2 -- n1+n2 )
6611: @@ + ;
6612:
6613: 3 curry+ 3+
6614: -2 curry+ 2-
1.1 anton 6615: @end example
6616:
1.91 anton 6617:
1.63 anton 6618: @node CREATE..DOES> details, Advanced does> usage example, CREATE..DOES> applications, User-defined Defining Words
1.26 crook 6619: @subsubsection The gory details of @code{CREATE..DOES>}
6620: @cindex @code{CREATE} ... @code{DOES>}, details
1.1 anton 6621:
1.26 crook 6622: doc-does>
1.1 anton 6623:
1.26 crook 6624: @cindex @code{DOES>} in a separate definition
6625: This means that you need not use @code{CREATE} and @code{DOES>} in the
6626: same definition; you can put the @code{DOES>}-part in a separate
1.29 crook 6627: definition. This allows us to, e.g., select among different @code{DOES>}-parts:
1.26 crook 6628: @example
6629: : does1
6630: DOES> ( ... -- ... )
1.44 crook 6631: ... ;
6632:
6633: : does2
6634: DOES> ( ... -- ... )
6635: ... ;
6636:
6637: : def-word ( ... -- ... )
6638: create ...
6639: IF
6640: does1
6641: ELSE
6642: does2
6643: ENDIF ;
6644: @end example
6645:
6646: In this example, the selection of whether to use @code{does1} or
1.69 anton 6647: @code{does2} is made at definition-time; at the time that the child word is
1.44 crook 6648: @code{CREATE}d.
6649:
6650: @cindex @code{DOES>} in interpretation state
6651: In a standard program you can apply a @code{DOES>}-part only if the last
6652: word was defined with @code{CREATE}. In Gforth, the @code{DOES>}-part
6653: will override the behaviour of the last word defined in any case. In a
6654: standard program, you can use @code{DOES>} only in a colon
6655: definition. In Gforth, you can also use it in interpretation state, in a
6656: kind of one-shot mode; for example:
6657: @example
6658: CREATE name ( ... -- ... )
6659: @i{initialization}
6660: DOES>
6661: @i{code} ;
6662: @end example
6663:
6664: @noindent
6665: is equivalent to the standard:
6666: @example
6667: :noname
6668: DOES>
6669: @i{code} ;
6670: CREATE name EXECUTE ( ... -- ... )
6671: @i{initialization}
6672: @end example
6673:
1.53 anton 6674: doc->body
6675:
1.152 pazsan 6676: @node Advanced does> usage example, Const-does>, CREATE..DOES> details, User-defined Defining Words
1.63 anton 6677: @subsubsection Advanced does> usage example
6678:
6679: The MIPS disassembler (@file{arch/mips/disasm.fs}) contains many words
6680: for disassembling instructions, that follow a very repetetive scheme:
6681:
6682: @example
6683: :noname @var{disasm-operands} s" @var{inst-name}" type ;
6684: @var{entry-num} cells @var{table} + !
6685: @end example
6686:
6687: Of course, this inspires the idea to factor out the commonalities to
6688: allow a definition like
6689:
6690: @example
6691: @var{disasm-operands} @var{entry-num} @var{table} define-inst @var{inst-name}
6692: @end example
6693:
6694: The parameters @var{disasm-operands} and @var{table} are usually
1.69 anton 6695: correlated. Moreover, before I wrote the disassembler, there already
6696: existed code that defines instructions like this:
1.63 anton 6697:
6698: @example
6699: @var{entry-num} @var{inst-format} @var{inst-name}
6700: @end example
6701:
6702: This code comes from the assembler and resides in
6703: @file{arch/mips/insts.fs}.
6704:
6705: So I had to define the @var{inst-format} words that performed the scheme
6706: above when executed. At first I chose to use run-time code-generation:
6707:
6708: @example
6709: : @var{inst-format} ( entry-num "name" -- ; compiled code: addr w -- )
6710: :noname Postpone @var{disasm-operands}
6711: name Postpone sliteral Postpone type Postpone ;
6712: swap cells @var{table} + ! ;
6713: @end example
6714:
6715: Note that this supplies the other two parameters of the scheme above.
1.44 crook 6716:
1.63 anton 6717: An alternative would have been to write this using
6718: @code{create}/@code{does>}:
6719:
6720: @example
6721: : @var{inst-format} ( entry-num "name" -- )
6722: here name string, ( entry-num c-addr ) \ parse and save "name"
6723: noname create , ( entry-num )
1.116 anton 6724: latestxt swap cells @var{table} + !
1.63 anton 6725: does> ( addr w -- )
6726: \ disassemble instruction w at addr
6727: @@ >r
6728: @var{disasm-operands}
6729: r> count type ;
6730: @end example
6731:
6732: Somehow the first solution is simpler, mainly because it's simpler to
6733: shift a string from definition-time to use-time with @code{sliteral}
6734: than with @code{string,} and friends.
6735:
6736: I wrote a lot of words following this scheme and soon thought about
6737: factoring out the commonalities among them. Note that this uses a
6738: two-level defining word, i.e., a word that defines ordinary defining
6739: words.
6740:
6741: This time a solution involving @code{postpone} and friends seemed more
6742: difficult (try it as an exercise), so I decided to use a
6743: @code{create}/@code{does>} word; since I was already at it, I also used
6744: @code{create}/@code{does>} for the lower level (try using
6745: @code{postpone} etc. as an exercise), resulting in the following
6746: definition:
6747:
6748: @example
6749: : define-format ( disasm-xt table-xt -- )
6750: \ define an instruction format that uses disasm-xt for
6751: \ disassembling and enters the defined instructions into table
6752: \ table-xt
6753: create 2,
6754: does> ( u "inst" -- )
6755: \ defines an anonymous word for disassembling instruction inst,
6756: \ and enters it as u-th entry into table-xt
6757: 2@@ swap here name string, ( u table-xt disasm-xt c-addr ) \ remember string
6758: noname create 2, \ define anonymous word
1.116 anton 6759: execute latestxt swap ! \ enter xt of defined word into table-xt
1.63 anton 6760: does> ( addr w -- )
6761: \ disassemble instruction w at addr
6762: 2@@ >r ( addr w disasm-xt R: c-addr )
6763: execute ( R: c-addr ) \ disassemble operands
6764: r> count type ; \ print name
6765: @end example
6766:
6767: Note that the tables here (in contrast to above) do the @code{cells +}
6768: by themselves (that's why you have to pass an xt). This word is used in
6769: the following way:
6770:
6771: @example
6772: ' @var{disasm-operands} ' @var{table} define-format @var{inst-format}
6773: @end example
6774:
1.71 anton 6775: As shown above, the defined instruction format is then used like this:
6776:
6777: @example
6778: @var{entry-num} @var{inst-format} @var{inst-name}
6779: @end example
6780:
1.63 anton 6781: In terms of currying, this kind of two-level defining word provides the
6782: parameters in three stages: first @var{disasm-operands} and @var{table},
6783: then @var{entry-num} and @var{inst-name}, finally @code{addr w}, i.e.,
6784: the instruction to be disassembled.
6785:
6786: Of course this did not quite fit all the instruction format names used
6787: in @file{insts.fs}, so I had to define a few wrappers that conditioned
6788: the parameters into the right form.
6789:
6790: If you have trouble following this section, don't worry. First, this is
6791: involved and takes time (and probably some playing around) to
6792: understand; second, this is the first two-level
6793: @code{create}/@code{does>} word I have written in seventeen years of
6794: Forth; and if I did not have @file{insts.fs} to start with, I may well
6795: have elected to use just a one-level defining word (with some repeating
6796: of parameters when using the defining word). So it is not necessary to
6797: understand this, but it may improve your understanding of Forth.
1.44 crook 6798:
6799:
1.152 pazsan 6800: @node Const-does>, , Advanced does> usage example, User-defined Defining Words
1.91 anton 6801: @subsubsection @code{Const-does>}
6802:
6803: A frequent use of @code{create}...@code{does>} is for transferring some
6804: values from definition-time to run-time. Gforth supports this use with
6805:
6806: doc-const-does>
6807:
6808: A typical use of this word is:
6809:
6810: @example
6811: : curry+ ( n1 "name" -- )
6812: 1 0 CONST-DOES> ( n2 -- n1+n2 )
6813: + ;
6814:
6815: 3 curry+ 3+
6816: @end example
6817:
6818: Here the @code{1 0} means that 1 cell and 0 floats are transferred from
6819: definition to run-time.
6820:
6821: The advantages of using @code{const-does>} are:
6822:
6823: @itemize
6824:
6825: @item
6826: You don't have to deal with storing and retrieving the values, i.e.,
6827: your program becomes more writable and readable.
6828:
6829: @item
6830: When using @code{does>}, you have to introduce a @code{@@} that cannot
6831: be optimized away (because you could change the data using
6832: @code{>body}...@code{!}); @code{const-does>} avoids this problem.
6833:
6834: @end itemize
6835:
6836: An ANS Forth implementation of @code{const-does>} is available in
6837: @file{compat/const-does.fs}.
6838:
6839:
1.170 pazsan 6840: @node Deferred Words, Aliases, User-defined Defining Words, Defining Words
6841: @subsection Deferred Words
1.44 crook 6842: @cindex deferred words
6843:
6844: The defining word @code{Defer} allows you to define a word by name
6845: without defining its behaviour; the definition of its behaviour is
6846: deferred. Here are two situation where this can be useful:
6847:
6848: @itemize @bullet
6849: @item
6850: Where you want to allow the behaviour of a word to be altered later, and
6851: for all precompiled references to the word to change when its behaviour
6852: is changed.
6853: @item
6854: For mutual recursion; @xref{Calls and returns}.
6855: @end itemize
6856:
6857: In the following example, @code{foo} always invokes the version of
6858: @code{greet} that prints ``@code{Good morning}'' whilst @code{bar}
6859: always invokes the version that prints ``@code{Hello}''. There is no way
6860: of getting @code{foo} to use the later version without re-ordering the
6861: source code and recompiling it.
6862:
6863: @example
6864: : greet ." Good morning" ;
6865: : foo ... greet ... ;
6866: : greet ." Hello" ;
6867: : bar ... greet ... ;
6868: @end example
6869:
6870: This problem can be solved by defining @code{greet} as a @code{Defer}red
6871: word. The behaviour of a @code{Defer}red word can be defined and
6872: redefined at any time by using @code{IS} to associate the xt of a
6873: previously-defined word with it. The previous example becomes:
6874:
6875: @example
1.69 anton 6876: Defer greet ( -- )
1.44 crook 6877: : foo ... greet ... ;
6878: : bar ... greet ... ;
1.69 anton 6879: : greet1 ( -- ) ." Good morning" ;
6880: : greet2 ( -- ) ." Hello" ;
1.132 anton 6881: ' greet2 IS greet \ make greet behave like greet2
1.44 crook 6882: @end example
6883:
1.69 anton 6884: @progstyle
6885: You should write a stack comment for every deferred word, and put only
6886: XTs into deferred words that conform to this stack effect. Otherwise
6887: it's too difficult to use the deferred word.
6888:
1.44 crook 6889: A deferred word can be used to improve the statistics-gathering example
6890: from @ref{User-defined Defining Words}; rather than edit the
6891: application's source code to change every @code{:} to a @code{my:}, do
6892: this:
6893:
6894: @example
6895: : real: : ; \ retain access to the original
6896: defer : \ redefine as a deferred word
1.132 anton 6897: ' my: IS : \ use special version of :
1.44 crook 6898: \
6899: \ load application here
6900: \
1.132 anton 6901: ' real: IS : \ go back to the original
1.44 crook 6902: @end example
6903:
6904:
1.132 anton 6905: One thing to note is that @code{IS} has special compilation semantics,
6906: such that it parses the name at compile time (like @code{TO}):
1.44 crook 6907:
6908: @example
6909: : set-greet ( xt -- )
1.132 anton 6910: IS greet ;
1.44 crook 6911:
6912: ' greet1 set-greet
6913: @end example
6914:
1.132 anton 6915: In situations where @code{IS} does not fit, use @code{defer!} instead.
6916:
1.69 anton 6917: A deferred word can only inherit execution semantics from the xt
6918: (because that is all that an xt can represent -- for more discussion of
6919: this @pxref{Tokens for Words}); by default it will have default
6920: interpretation and compilation semantics deriving from this execution
6921: semantics. However, you can change the interpretation and compilation
6922: semantics of the deferred word in the usual ways:
1.44 crook 6923:
6924: @example
1.132 anton 6925: : bar .... ; immediate
1.44 crook 6926: Defer fred immediate
6927: Defer jim
6928:
1.132 anton 6929: ' bar IS jim \ jim has default semantics
6930: ' bar IS fred \ fred is immediate
1.44 crook 6931: @end example
6932:
6933: doc-defer
1.132 anton 6934: doc-defer!
1.44 crook 6935: doc-is
1.132 anton 6936: doc-defer@
6937: doc-action-of
1.44 crook 6938: @comment TODO document these: what's defers [is]
6939: doc-defers
6940:
6941: @c Use @code{words-deferred} to see a list of deferred words.
6942:
1.132 anton 6943: Definitions of these words (except @code{defers}) in ANS Forth are
6944: provided in @file{compat/defer.fs}.
1.44 crook 6945:
6946:
1.170 pazsan 6947: @node Aliases, , Deferred Words, Defining Words
1.44 crook 6948: @subsection Aliases
6949: @cindex aliases
1.1 anton 6950:
1.44 crook 6951: The defining word @code{Alias} allows you to define a word by name that
6952: has the same behaviour as some other word. Here are two situation where
6953: this can be useful:
1.1 anton 6954:
1.44 crook 6955: @itemize @bullet
6956: @item
6957: When you want access to a word's definition from a different word list
6958: (for an example of this, see the definition of the @code{Root} word list
6959: in the Gforth source).
6960: @item
6961: When you want to create a synonym; a definition that can be known by
6962: either of two names (for example, @code{THEN} and @code{ENDIF} are
6963: aliases).
6964: @end itemize
1.1 anton 6965:
1.69 anton 6966: Like deferred words, an alias has default compilation and interpretation
6967: semantics at the beginning (not the modifications of the other word),
6968: but you can change them in the usual ways (@code{immediate},
6969: @code{compile-only}). For example:
1.1 anton 6970:
6971: @example
1.44 crook 6972: : foo ... ; immediate
6973:
6974: ' foo Alias bar \ bar is not an immediate word
6975: ' foo Alias fooby immediate \ fooby is an immediate word
1.1 anton 6976: @end example
6977:
1.44 crook 6978: Words that are aliases have the same xt, different headers in the
6979: dictionary, and consequently different name tokens (@pxref{Tokens for
6980: Words}) and possibly different immediate flags. An alias can only have
6981: default or immediate compilation semantics; you can define aliases for
6982: combined words with @code{interpret/compile:} -- see @ref{Combined words}.
1.1 anton 6983:
1.44 crook 6984: doc-alias
1.1 anton 6985:
6986:
1.47 crook 6987: @node Interpretation and Compilation Semantics, Tokens for Words, Defining Words, Words
6988: @section Interpretation and Compilation Semantics
1.26 crook 6989: @cindex semantics, interpretation and compilation
1.1 anton 6990:
1.71 anton 6991: @c !! state and ' are used without explanation
6992: @c example for immediate/compile-only? or is the tutorial enough
6993:
1.26 crook 6994: @cindex interpretation semantics
1.71 anton 6995: The @dfn{interpretation semantics} of a (named) word are what the text
1.26 crook 6996: interpreter does when it encounters the word in interpret state. It also
6997: appears in some other contexts, e.g., the execution token returned by
1.71 anton 6998: @code{' @i{word}} identifies the interpretation semantics of @i{word}
6999: (in other words, @code{' @i{word} execute} is equivalent to
1.29 crook 7000: interpret-state text interpretation of @code{@i{word}}).
1.1 anton 7001:
1.26 crook 7002: @cindex compilation semantics
1.71 anton 7003: The @dfn{compilation semantics} of a (named) word are what the text
7004: interpreter does when it encounters the word in compile state. It also
7005: appears in other contexts, e.g, @code{POSTPONE @i{word}}
7006: compiles@footnote{In standard terminology, ``appends to the current
7007: definition''.} the compilation semantics of @i{word}.
1.1 anton 7008:
1.26 crook 7009: @cindex execution semantics
7010: The standard also talks about @dfn{execution semantics}. They are used
7011: only for defining the interpretation and compilation semantics of many
7012: words. By default, the interpretation semantics of a word are to
7013: @code{execute} its execution semantics, and the compilation semantics of
7014: a word are to @code{compile,} its execution semantics.@footnote{In
7015: standard terminology: The default interpretation semantics are its
7016: execution semantics; the default compilation semantics are to append its
7017: execution semantics to the execution semantics of the current
7018: definition.}
7019:
1.71 anton 7020: Unnamed words (@pxref{Anonymous Definitions}) cannot be encountered by
7021: the text interpreter, ticked, or @code{postpone}d, so they have no
7022: interpretation or compilation semantics. Their behaviour is represented
7023: by their XT (@pxref{Tokens for Words}), and we call it execution
7024: semantics, too.
7025:
1.26 crook 7026: @comment TODO expand, make it co-operate with new sections on text interpreter.
7027:
7028: @cindex immediate words
7029: @cindex compile-only words
7030: You can change the semantics of the most-recently defined word:
7031:
1.44 crook 7032:
1.26 crook 7033: doc-immediate
7034: doc-compile-only
7035: doc-restrict
7036:
1.82 anton 7037: By convention, words with non-default compilation semantics (e.g.,
7038: immediate words) often have names surrounded with brackets (e.g.,
7039: @code{[']}, @pxref{Execution token}).
1.44 crook 7040:
1.26 crook 7041: Note that ticking (@code{'}) a compile-only word gives an error
7042: (``Interpreting a compile-only word'').
1.1 anton 7043:
1.47 crook 7044: @menu
1.67 anton 7045: * Combined words::
1.47 crook 7046: @end menu
1.44 crook 7047:
1.71 anton 7048:
1.48 anton 7049: @node Combined words, , Interpretation and Compilation Semantics, Interpretation and Compilation Semantics
1.44 crook 7050: @subsection Combined Words
7051: @cindex combined words
7052:
7053: Gforth allows you to define @dfn{combined words} -- words that have an
7054: arbitrary combination of interpretation and compilation semantics.
7055:
1.26 crook 7056: doc-interpret/compile:
1.1 anton 7057:
1.26 crook 7058: This feature was introduced for implementing @code{TO} and @code{S"}. I
7059: recommend that you do not define such words, as cute as they may be:
7060: they make it hard to get at both parts of the word in some contexts.
7061: E.g., assume you want to get an execution token for the compilation
7062: part. Instead, define two words, one that embodies the interpretation
7063: part, and one that embodies the compilation part. Once you have done
7064: that, you can define a combined word with @code{interpret/compile:} for
7065: the convenience of your users.
1.1 anton 7066:
1.26 crook 7067: You might try to use this feature to provide an optimizing
7068: implementation of the default compilation semantics of a word. For
7069: example, by defining:
1.1 anton 7070: @example
1.26 crook 7071: :noname
7072: foo bar ;
7073: :noname
7074: POSTPONE foo POSTPONE bar ;
1.29 crook 7075: interpret/compile: opti-foobar
1.1 anton 7076: @end example
1.26 crook 7077:
1.23 crook 7078: @noindent
1.26 crook 7079: as an optimizing version of:
7080:
1.1 anton 7081: @example
1.26 crook 7082: : foobar
7083: foo bar ;
1.1 anton 7084: @end example
7085:
1.26 crook 7086: Unfortunately, this does not work correctly with @code{[compile]},
7087: because @code{[compile]} assumes that the compilation semantics of all
7088: @code{interpret/compile:} words are non-default. I.e., @code{[compile]
1.29 crook 7089: opti-foobar} would compile compilation semantics, whereas
7090: @code{[compile] foobar} would compile interpretation semantics.
1.1 anton 7091:
1.26 crook 7092: @cindex state-smart words (are a bad idea)
1.82 anton 7093: @anchor{state-smartness}
1.29 crook 7094: Some people try to use @dfn{state-smart} words to emulate the feature provided
1.26 crook 7095: by @code{interpret/compile:} (words are state-smart if they check
7096: @code{STATE} during execution). E.g., they would try to code
7097: @code{foobar} like this:
1.1 anton 7098:
1.26 crook 7099: @example
7100: : foobar
7101: STATE @@
7102: IF ( compilation state )
7103: POSTPONE foo POSTPONE bar
7104: ELSE
7105: foo bar
7106: ENDIF ; immediate
7107: @end example
1.1 anton 7108:
1.26 crook 7109: Although this works if @code{foobar} is only processed by the text
7110: interpreter, it does not work in other contexts (like @code{'} or
7111: @code{POSTPONE}). E.g., @code{' foobar} will produce an execution token
7112: for a state-smart word, not for the interpretation semantics of the
7113: original @code{foobar}; when you execute this execution token (directly
7114: with @code{EXECUTE} or indirectly through @code{COMPILE,}) in compile
7115: state, the result will not be what you expected (i.e., it will not
7116: perform @code{foo bar}). State-smart words are a bad idea. Simply don't
7117: write them@footnote{For a more detailed discussion of this topic, see
1.66 anton 7118: M. Anton Ertl,
7119: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl98.ps.gz,@code{State}-smartness---Why
7120: it is Evil and How to Exorcise it}}, EuroForth '98.}!
1.1 anton 7121:
1.26 crook 7122: @cindex defining words with arbitrary semantics combinations
7123: It is also possible to write defining words that define words with
7124: arbitrary combinations of interpretation and compilation semantics. In
7125: general, they look like this:
1.1 anton 7126:
1.26 crook 7127: @example
7128: : def-word
7129: create-interpret/compile
1.29 crook 7130: @i{code1}
1.26 crook 7131: interpretation>
1.29 crook 7132: @i{code2}
1.26 crook 7133: <interpretation
7134: compilation>
1.29 crook 7135: @i{code3}
1.26 crook 7136: <compilation ;
7137: @end example
1.1 anton 7138:
1.29 crook 7139: For a @i{word} defined with @code{def-word}, the interpretation
7140: semantics are to push the address of the body of @i{word} and perform
7141: @i{code2}, and the compilation semantics are to push the address of
7142: the body of @i{word} and perform @i{code3}. E.g., @code{constant}
1.26 crook 7143: can also be defined like this (except that the defined constants don't
7144: behave correctly when @code{[compile]}d):
1.1 anton 7145:
1.26 crook 7146: @example
7147: : constant ( n "name" -- )
7148: create-interpret/compile
7149: ,
7150: interpretation> ( -- n )
7151: @@
7152: <interpretation
7153: compilation> ( compilation. -- ; run-time. -- n )
7154: @@ postpone literal
7155: <compilation ;
7156: @end example
1.1 anton 7157:
1.44 crook 7158:
1.26 crook 7159: doc-create-interpret/compile
7160: doc-interpretation>
7161: doc-<interpretation
7162: doc-compilation>
7163: doc-<compilation
1.1 anton 7164:
1.44 crook 7165:
1.29 crook 7166: Words defined with @code{interpret/compile:} and
1.26 crook 7167: @code{create-interpret/compile} have an extended header structure that
7168: differs from other words; however, unless you try to access them with
7169: plain address arithmetic, you should not notice this. Words for
7170: accessing the header structure usually know how to deal with this; e.g.,
1.29 crook 7171: @code{'} @i{word} @code{>body} also gives you the body of a word created
7172: with @code{create-interpret/compile}.
1.1 anton 7173:
1.44 crook 7174:
1.47 crook 7175: @c -------------------------------------------------------------
1.81 anton 7176: @node Tokens for Words, Compiling words, Interpretation and Compilation Semantics, Words
1.47 crook 7177: @section Tokens for Words
7178: @cindex tokens for words
7179:
7180: This section describes the creation and use of tokens that represent
7181: words.
7182:
1.71 anton 7183: @menu
7184: * Execution token:: represents execution/interpretation semantics
7185: * Compilation token:: represents compilation semantics
7186: * Name token:: represents named words
7187: @end menu
1.47 crook 7188:
1.71 anton 7189: @node Execution token, Compilation token, Tokens for Words, Tokens for Words
7190: @subsection Execution token
1.47 crook 7191:
7192: @cindex xt
7193: @cindex execution token
1.71 anton 7194: An @dfn{execution token} (@i{XT}) represents some behaviour of a word.
7195: You can use @code{execute} to invoke this behaviour.
1.47 crook 7196:
1.71 anton 7197: @cindex tick (')
7198: You can use @code{'} to get an execution token that represents the
7199: interpretation semantics of a named word:
1.47 crook 7200:
7201: @example
1.97 anton 7202: 5 ' . ( n xt )
7203: execute ( ) \ execute the xt (i.e., ".")
1.71 anton 7204: @end example
1.47 crook 7205:
1.71 anton 7206: doc-'
7207:
7208: @code{'} parses at run-time; there is also a word @code{[']} that parses
7209: when it is compiled, and compiles the resulting XT:
7210:
7211: @example
7212: : foo ['] . execute ;
7213: 5 foo
7214: : bar ' execute ; \ by contrast,
7215: 5 bar . \ ' parses "." when bar executes
7216: @end example
7217:
7218: doc-[']
7219:
7220: If you want the execution token of @i{word}, write @code{['] @i{word}}
7221: in compiled code and @code{' @i{word}} in interpreted code. Gforth's
7222: @code{'} and @code{[']} behave somewhat unusually by complaining about
7223: compile-only words (because these words have no interpretation
7224: semantics). You might get what you want by using @code{COMP' @i{word}
7225: DROP} or @code{[COMP'] @i{word} DROP} (for details @pxref{Compilation
7226: token}).
7227:
1.116 anton 7228: Another way to get an XT is @code{:noname} or @code{latestxt}
1.71 anton 7229: (@pxref{Anonymous Definitions}). For anonymous words this gives an xt
7230: for the only behaviour the word has (the execution semantics). For
1.116 anton 7231: named words, @code{latestxt} produces an XT for the same behaviour it
1.71 anton 7232: would produce if the word was defined anonymously.
7233:
7234: @example
7235: :noname ." hello" ;
7236: execute
1.47 crook 7237: @end example
7238:
1.71 anton 7239: An XT occupies one cell and can be manipulated like any other cell.
7240:
1.47 crook 7241: @cindex code field address
7242: @cindex CFA
1.71 anton 7243: In ANS Forth the XT is just an abstract data type (i.e., defined by the
7244: operations that produce or consume it). For old hands: In Gforth, the
7245: XT is implemented as a code field address (CFA).
7246:
7247: doc-execute
7248: doc-perform
7249:
7250: @node Compilation token, Name token, Execution token, Tokens for Words
7251: @subsection Compilation token
1.47 crook 7252:
7253: @cindex compilation token
1.71 anton 7254: @cindex CT (compilation token)
7255: Gforth represents the compilation semantics of a named word by a
1.47 crook 7256: @dfn{compilation token} consisting of two cells: @i{w xt}. The top cell
7257: @i{xt} is an execution token. The compilation semantics represented by
7258: the compilation token can be performed with @code{execute}, which
7259: consumes the whole compilation token, with an additional stack effect
7260: determined by the represented compilation semantics.
7261:
7262: At present, the @i{w} part of a compilation token is an execution token,
7263: and the @i{xt} part represents either @code{execute} or
7264: @code{compile,}@footnote{Depending upon the compilation semantics of the
7265: word. If the word has default compilation semantics, the @i{xt} will
7266: represent @code{compile,}. Otherwise (e.g., for immediate words), the
7267: @i{xt} will represent @code{execute}.}. However, don't rely on that
7268: knowledge, unless necessary; future versions of Gforth may introduce
7269: unusual compilation tokens (e.g., a compilation token that represents
7270: the compilation semantics of a literal).
7271:
1.71 anton 7272: You can perform the compilation semantics represented by the compilation
7273: token with @code{execute}. You can compile the compilation semantics
7274: with @code{postpone,}. I.e., @code{COMP' @i{word} postpone,} is
7275: equivalent to @code{postpone @i{word}}.
7276:
7277: doc-[comp']
7278: doc-comp'
7279: doc-postpone,
7280:
7281: @node Name token, , Compilation token, Tokens for Words
7282: @subsection Name token
1.47 crook 7283:
7284: @cindex name token
1.116 anton 7285: Gforth represents named words by the @dfn{name token}, (@i{nt}). Name
7286: token is an abstract data type that occurs as argument or result of the
7287: words below.
7288:
7289: @c !! put this elswhere?
1.47 crook 7290: @cindex name field address
7291: @cindex NFA
1.116 anton 7292: The closest thing to the nt in older Forth systems is the name field
7293: address (NFA), but there are significant differences: in older Forth
7294: systems each word had a unique NFA, LFA, CFA and PFA (in this order, or
7295: LFA, NFA, CFA, PFA) and there were words for getting from one to the
7296: next. In contrast, in Gforth 0@dots{}n nts correspond to one xt; there
7297: is a link field in the structure identified by the name token, but
7298: searching usually uses a hash table external to these structures; the
7299: name in Gforth has a cell-wide count-and-flags field, and the nt is not
7300: implemented as the address of that count field.
1.47 crook 7301:
7302: doc-find-name
1.116 anton 7303: doc-latest
7304: doc->name
1.47 crook 7305: doc-name>int
7306: doc-name?int
7307: doc-name>comp
7308: doc-name>string
1.109 anton 7309: doc-id.
7310: doc-.name
7311: doc-.id
1.47 crook 7312:
1.81 anton 7313: @c ----------------------------------------------------------
7314: @node Compiling words, The Text Interpreter, Tokens for Words, Words
7315: @section Compiling words
7316: @cindex compiling words
7317: @cindex macros
7318:
7319: In contrast to most other languages, Forth has no strict boundary
1.82 anton 7320: between compilation and run-time. E.g., you can run arbitrary code
7321: between defining words (or for computing data used by defining words
7322: like @code{constant}). Moreover, @code{Immediate} (@pxref{Interpretation
7323: and Compilation Semantics} and @code{[}...@code{]} (see below) allow
7324: running arbitrary code while compiling a colon definition (exception:
7325: you must not allot dictionary space).
7326:
7327: @menu
7328: * Literals:: Compiling data values
7329: * Macros:: Compiling words
7330: @end menu
7331:
7332: @node Literals, Macros, Compiling words, Compiling words
7333: @subsection Literals
7334: @cindex Literals
7335:
7336: The simplest and most frequent example is to compute a literal during
7337: compilation. E.g., the following definition prints an array of strings,
7338: one string per line:
7339:
7340: @example
7341: : .strings ( addr u -- ) \ gforth
7342: 2* cells bounds U+DO
7343: cr i 2@@ type
7344: 2 cells +LOOP ;
7345: @end example
1.81 anton 7346:
1.82 anton 7347: With a simple-minded compiler like Gforth's, this computes @code{2
7348: cells} on every loop iteration. You can compute this value once and for
7349: all at compile time and compile it into the definition like this:
7350:
7351: @example
7352: : .strings ( addr u -- ) \ gforth
7353: 2* cells bounds U+DO
7354: cr i 2@@ type
7355: [ 2 cells ] literal +LOOP ;
7356: @end example
7357:
7358: @code{[} switches the text interpreter to interpret state (you will get
7359: an @code{ok} prompt if you type this example interactively and insert a
7360: newline between @code{[} and @code{]}), so it performs the
7361: interpretation semantics of @code{2 cells}; this computes a number.
7362: @code{]} switches the text interpreter back into compile state. It then
7363: performs @code{Literal}'s compilation semantics, which are to compile
7364: this number into the current word. You can decompile the word with
7365: @code{see .strings} to see the effect on the compiled code.
1.81 anton 7366:
1.82 anton 7367: You can also optimize the @code{2* cells} into @code{[ 2 cells ] literal
7368: *} in this way.
1.81 anton 7369:
1.82 anton 7370: doc-[
7371: doc-]
1.81 anton 7372: doc-literal
7373: doc-]L
1.82 anton 7374:
7375: There are also words for compiling other data types than single cells as
7376: literals:
7377:
1.81 anton 7378: doc-2literal
7379: doc-fliteral
1.82 anton 7380: doc-sliteral
7381:
7382: @cindex colon-sys, passing data across @code{:}
7383: @cindex @code{:}, passing data across
7384: You might be tempted to pass data from outside a colon definition to the
7385: inside on the data stack. This does not work, because @code{:} puhes a
7386: colon-sys, making stuff below unaccessible. E.g., this does not work:
7387:
7388: @example
7389: 5 : foo literal ; \ error: "unstructured"
7390: @end example
7391:
7392: Instead, you have to pass the value in some other way, e.g., through a
7393: variable:
7394:
7395: @example
7396: variable temp
7397: 5 temp !
7398: : foo [ temp @@ ] literal ;
7399: @end example
7400:
7401:
7402: @node Macros, , Literals, Compiling words
7403: @subsection Macros
7404: @cindex Macros
7405: @cindex compiling compilation semantics
7406:
7407: @code{Literal} and friends compile data values into the current
7408: definition. You can also write words that compile other words into the
7409: current definition. E.g.,
7410:
7411: @example
7412: : compile-+ ( -- ) \ compiled code: ( n1 n2 -- n )
7413: POSTPONE + ;
7414:
7415: : foo ( n1 n2 -- n )
7416: [ compile-+ ] ;
7417: 1 2 foo .
7418: @end example
7419:
7420: This is equivalent to @code{: foo + ;} (@code{see foo} to check this).
7421: What happens in this example? @code{Postpone} compiles the compilation
7422: semantics of @code{+} into @code{compile-+}; later the text interpreter
7423: executes @code{compile-+} and thus the compilation semantics of +, which
7424: compile (the execution semantics of) @code{+} into
7425: @code{foo}.@footnote{A recent RFI answer requires that compiling words
7426: should only be executed in compile state, so this example is not
7427: guaranteed to work on all standard systems, but on any decent system it
7428: will work.}
7429:
7430: doc-postpone
7431:
7432: Compiling words like @code{compile-+} are usually immediate (or similar)
7433: so you do not have to switch to interpret state to execute them;
1.206 anton 7434: modifying the last example accordingly produces:
1.82 anton 7435:
7436: @example
7437: : [compile-+] ( compilation: --; interpretation: -- )
7438: \ compiled code: ( n1 n2 -- n )
7439: POSTPONE + ; immediate
7440:
7441: : foo ( n1 n2 -- n )
7442: [compile-+] ;
7443: 1 2 foo .
7444: @end example
7445:
1.206 anton 7446: You will occassionally find the need to POSTPONE several words;
7447: putting POSTPONE before each such word is cumbersome, so Gforth
7448: provides a more convenient syntax: @code{]] ... [[}. This
7449: allows us to write @code{[compile-+]} as:
7450:
7451: @example
7452: : [compile-+] ( compilation: --; interpretation: -- )
7453: ]] + [[ ; immediate
7454: @end example
7455:
7456: doc-]]
7457: doc-[[
7458:
7459: The unusual direction of the brackets indicates their function:
7460: @code{]]} switches from compilation to postponing (i.e., compilation
7461: of compilation), just like @code{]} switches from immediate execution
7462: (interpretation) to compilation. Conversely, @code{[[} switches from
7463: postponing to compilation, ananlogous to @code{[} which switches from
7464: compilation to immediate execution.
7465:
7466: The real advantage of @code{]] }...@code{ [[} becomes apparent when
7467: there are many words to POSTPONE. E.g., the word
7468: @code{compile-map-array} (@pxref{Advanced macros Tutorial}) can be
7469: written much shorter as follows:
7470:
7471: @example
7472: : compile-map-array ( compilation: xt -- ; run-time: ... addr u -- ... )
7473: \ at run-time, execute xt ( ... x -- ... ) for each element of the
7474: \ array beginning at addr and containing u elements
7475: @{ xt @}
7476: ]] cells over + swap ?do
7477: i @@ [[ xt compile,
7478: 1 cells ]]L +loop [[ ;
7479: @end example
7480:
7481: This example also uses @code{]]L} as a shortcut for @code{]] literal}.
7482: There are also other shortcuts
7483:
7484: doc-]]L
7485: doc-]]2L
7486: doc-]]FL
7487: doc-]]SL
7488:
7489: Note that parsing words don't parse at postpone time; if you want to
7490: provide the parsed string right away, you have to switch back to
7491: compilation:
7492:
7493: @example
7494: ]] ... [[ s" some string" ]]2L ... [[
7495: ]] ... [[ ['] + ]]L ... [[
7496: @end example
7497:
7498: Definitions of @code{]]} and friends in ANS Forth are provided in
7499: @file{compat/macros.fs}.
7500:
1.82 anton 7501: Immediate compiling words are similar to macros in other languages (in
7502: particular, Lisp). The important differences to macros in, e.g., C are:
7503:
7504: @itemize @bullet
7505:
7506: @item
7507: You use the same language for defining and processing macros, not a
7508: separate preprocessing language and processor.
7509:
7510: @item
7511: Consequently, the full power of Forth is available in macro definitions.
7512: E.g., you can perform arbitrarily complex computations, or generate
7513: different code conditionally or in a loop (e.g., @pxref{Advanced macros
7514: Tutorial}). This power is very useful when writing a parser generators
7515: or other code-generating software.
7516:
7517: @item
7518: Macros defined using @code{postpone} etc. deal with the language at a
7519: higher level than strings; name binding happens at macro definition
7520: time, so you can avoid the pitfalls of name collisions that can happen
7521: in C macros. Of course, Forth is a liberal language and also allows to
7522: shoot yourself in the foot with text-interpreted macros like
7523:
7524: @example
7525: : [compile-+] s" +" evaluate ; immediate
7526: @end example
7527:
7528: Apart from binding the name at macro use time, using @code{evaluate}
7529: also makes your definition @code{state}-smart (@pxref{state-smartness}).
7530: @end itemize
7531:
7532: You may want the macro to compile a number into a word. The word to do
7533: it is @code{literal}, but you have to @code{postpone} it, so its
7534: compilation semantics take effect when the macro is executed, not when
7535: it is compiled:
7536:
7537: @example
7538: : [compile-5] ( -- ) \ compiled code: ( -- n )
7539: 5 POSTPONE literal ; immediate
7540:
7541: : foo [compile-5] ;
7542: foo .
7543: @end example
7544:
7545: You may want to pass parameters to a macro, that the macro should
7546: compile into the current definition. If the parameter is a number, then
7547: you can use @code{postpone literal} (similar for other values).
7548:
7549: If you want to pass a word that is to be compiled, the usual way is to
7550: pass an execution token and @code{compile,} it:
7551:
7552: @example
7553: : twice1 ( xt -- ) \ compiled code: ... -- ...
7554: dup compile, compile, ;
7555:
7556: : 2+ ( n1 -- n2 )
7557: [ ' 1+ twice1 ] ;
7558: @end example
7559:
7560: doc-compile,
7561:
7562: An alternative available in Gforth, that allows you to pass compile-only
7563: words as parameters is to use the compilation token (@pxref{Compilation
7564: token}). The same example in this technique:
7565:
7566: @example
7567: : twice ( ... ct -- ... ) \ compiled code: ... -- ...
7568: 2dup 2>r execute 2r> execute ;
7569:
7570: : 2+ ( n1 -- n2 )
7571: [ comp' 1+ twice ] ;
7572: @end example
7573:
7574: In the example above @code{2>r} and @code{2r>} ensure that @code{twice}
7575: works even if the executed compilation semantics has an effect on the
7576: data stack.
7577:
7578: You can also define complete definitions with these words; this provides
7579: an alternative to using @code{does>} (@pxref{User-defined Defining
7580: Words}). E.g., instead of
7581:
7582: @example
7583: : curry+ ( n1 "name" -- )
7584: CREATE ,
7585: DOES> ( n2 -- n1+n2 )
7586: @@ + ;
7587: @end example
7588:
7589: you could define
7590:
7591: @example
7592: : curry+ ( n1 "name" -- )
7593: \ name execution: ( n2 -- n1+n2 )
7594: >r : r> POSTPONE literal POSTPONE + POSTPONE ; ;
1.81 anton 7595:
1.82 anton 7596: -3 curry+ 3-
7597: see 3-
7598: @end example
1.81 anton 7599:
1.82 anton 7600: The sequence @code{>r : r>} is necessary, because @code{:} puts a
7601: colon-sys on the data stack that makes everything below it unaccessible.
1.81 anton 7602:
1.82 anton 7603: This way of writing defining words is sometimes more, sometimes less
7604: convenient than using @code{does>} (@pxref{Advanced does> usage
7605: example}). One advantage of this method is that it can be optimized
7606: better, because the compiler knows that the value compiled with
7607: @code{literal} is fixed, whereas the data associated with a
7608: @code{create}d word can be changed.
1.47 crook 7609:
1.206 anton 7610: @c doc-[compile] !! not properly documented
7611:
1.26 crook 7612: @c ----------------------------------------------------------
1.111 anton 7613: @node The Text Interpreter, The Input Stream, Compiling words, Words
1.26 crook 7614: @section The Text Interpreter
7615: @cindex interpreter - outer
7616: @cindex text interpreter
7617: @cindex outer interpreter
1.1 anton 7618:
1.34 anton 7619: @c Should we really describe all these ugly details? IMO the text
7620: @c interpreter should be much cleaner, but that may not be possible within
7621: @c ANS Forth. - anton
1.44 crook 7622: @c nac-> I wanted to explain how it works to show how you can exploit
7623: @c it in your own programs. When I was writing a cross-compiler, figuring out
7624: @c some of these gory details was very helpful to me. None of the textbooks
7625: @c I've seen cover it, and the most modern Forth textbook -- Forth Inc's,
7626: @c seems to positively avoid going into too much detail for some of
7627: @c the internals.
1.34 anton 7628:
1.71 anton 7629: @c anton: ok. I wonder, though, if this is the right place; for some stuff
7630: @c it is; for the ugly details, I would prefer another place. I wonder
7631: @c whether we should have a chapter before "Words" that describes some
7632: @c basic concepts referred to in words, and a chapter after "Words" that
7633: @c describes implementation details.
7634:
1.29 crook 7635: The text interpreter@footnote{This is an expanded version of the
7636: material in @ref{Introducing the Text Interpreter}.} is an endless loop
1.34 anton 7637: that processes input from the current input device. It is also called
7638: the outer interpreter, in contrast to the inner interpreter
7639: (@pxref{Engine}) which executes the compiled Forth code on interpretive
7640: implementations.
1.27 crook 7641:
1.29 crook 7642: @cindex interpret state
7643: @cindex compile state
7644: The text interpreter operates in one of two states: @dfn{interpret
7645: state} and @dfn{compile state}. The current state is defined by the
1.71 anton 7646: aptly-named variable @code{state}.
1.29 crook 7647:
7648: This section starts by describing how the text interpreter behaves when
7649: it is in interpret state, processing input from the user input device --
7650: the keyboard. This is the mode that a Forth system is in after it starts
7651: up.
7652:
7653: @cindex input buffer
7654: @cindex terminal input buffer
7655: The text interpreter works from an area of memory called the @dfn{input
7656: buffer}@footnote{When the text interpreter is processing input from the
7657: keyboard, this area of memory is called the @dfn{terminal input buffer}
7658: (TIB) and is addressed by the (obsolescent) words @code{TIB} and
7659: @code{#TIB}.}, which stores your keyboard input when you press the
1.30 anton 7660: @key{RET} key. Starting at the beginning of the input buffer, it skips
1.29 crook 7661: leading spaces (called @dfn{delimiters}) then parses a string (a
7662: sequence of non-space characters) until it reaches either a space
7663: character or the end of the buffer. Having parsed a string, it makes two
7664: attempts to process it:
1.27 crook 7665:
1.29 crook 7666: @cindex dictionary
1.27 crook 7667: @itemize @bullet
7668: @item
1.29 crook 7669: It looks for the string in a @dfn{dictionary} of definitions. If the
7670: string is found, the string names a @dfn{definition} (also known as a
7671: @dfn{word}) and the dictionary search returns information that allows
7672: the text interpreter to perform the word's @dfn{interpretation
7673: semantics}. In most cases, this simply means that the word will be
7674: executed.
1.27 crook 7675: @item
7676: If the string is not found in the dictionary, the text interpreter
1.29 crook 7677: attempts to treat it as a number, using the rules described in
7678: @ref{Number Conversion}. If the string represents a legal number in the
7679: current radix, the number is pushed onto a parameter stack (the data
7680: stack for integers, the floating-point stack for floating-point
7681: numbers).
7682: @end itemize
7683:
7684: If both attempts fail, or if the word is found in the dictionary but has
7685: no interpretation semantics@footnote{This happens if the word was
7686: defined as @code{COMPILE-ONLY}.} the text interpreter discards the
7687: remainder of the input buffer, issues an error message and waits for
7688: more input. If one of the attempts succeeds, the text interpreter
7689: repeats the parsing process until the whole of the input buffer has been
7690: processed, at which point it prints the status message ``@code{ ok}''
7691: and waits for more input.
7692:
1.71 anton 7693: @c anton: this should be in the input stream subsection (or below it)
7694:
1.29 crook 7695: @cindex parse area
7696: The text interpreter keeps track of its position in the input buffer by
7697: updating a variable called @code{>IN} (pronounced ``to-in''). The value
7698: of @code{>IN} starts out as 0, indicating an offset of 0 from the start
7699: of the input buffer. The region from offset @code{>IN @@} to the end of
7700: the input buffer is called the @dfn{parse area}@footnote{In other words,
7701: the text interpreter processes the contents of the input buffer by
7702: parsing strings from the parse area until the parse area is empty.}.
7703: This example shows how @code{>IN} changes as the text interpreter parses
7704: the input buffer:
7705:
7706: @example
7707: : remaining >IN @@ SOURCE 2 PICK - -ROT + SWAP
7708: CR ." ->" TYPE ." <-" ; IMMEDIATE
7709:
7710: 1 2 3 remaining + remaining .
7711:
7712: : foo 1 2 3 remaining SWAP remaining ;
7713: @end example
7714:
7715: @noindent
7716: The result is:
7717:
7718: @example
7719: ->+ remaining .<-
7720: ->.<-5 ok
7721:
7722: ->SWAP remaining ;-<
7723: ->;<- ok
7724: @end example
7725:
7726: @cindex parsing words
7727: The value of @code{>IN} can also be modified by a word in the input
7728: buffer that is executed by the text interpreter. This means that a word
7729: can ``trick'' the text interpreter into either skipping a section of the
7730: input buffer@footnote{This is how parsing words work.} or into parsing a
7731: section twice. For example:
1.27 crook 7732:
1.29 crook 7733: @example
1.71 anton 7734: : lat ." <<foo>>" ;
7735: : flat ." <<bar>>" >IN DUP @@ 3 - SWAP ! ;
1.29 crook 7736: @end example
7737:
7738: @noindent
7739: When @code{flat} is executed, this output is produced@footnote{Exercise
7740: for the reader: what would happen if the @code{3} were replaced with
7741: @code{4}?}:
7742:
7743: @example
1.71 anton 7744: <<bar>><<foo>>
1.29 crook 7745: @end example
7746:
1.71 anton 7747: This technique can be used to work around some of the interoperability
7748: problems of parsing words. Of course, it's better to avoid parsing
7749: words where possible.
7750:
1.29 crook 7751: @noindent
7752: Two important notes about the behaviour of the text interpreter:
1.27 crook 7753:
7754: @itemize @bullet
7755: @item
7756: It processes each input string to completion before parsing additional
1.29 crook 7757: characters from the input buffer.
7758: @item
7759: It treats the input buffer as a read-only region (and so must your code).
7760: @end itemize
7761:
7762: @noindent
7763: When the text interpreter is in compile state, its behaviour changes in
7764: these ways:
7765:
7766: @itemize @bullet
7767: @item
7768: If a parsed string is found in the dictionary, the text interpreter will
7769: perform the word's @dfn{compilation semantics}. In most cases, this
7770: simply means that the execution semantics of the word will be appended
7771: to the current definition.
1.27 crook 7772: @item
1.29 crook 7773: When a number is encountered, it is compiled into the current definition
7774: (as a literal) rather than being pushed onto a parameter stack.
7775: @item
7776: If an error occurs, @code{state} is modified to put the text interpreter
7777: back into interpret state.
7778: @item
7779: Each time a line is entered from the keyboard, Gforth prints
7780: ``@code{ compiled}'' rather than `` @code{ok}''.
7781: @end itemize
7782:
7783: @cindex text interpreter - input sources
7784: When the text interpreter is using an input device other than the
7785: keyboard, its behaviour changes in these ways:
7786:
7787: @itemize @bullet
7788: @item
7789: When the parse area is empty, the text interpreter attempts to refill
7790: the input buffer from the input source. When the input source is
1.71 anton 7791: exhausted, the input source is set back to the previous input source.
1.29 crook 7792: @item
7793: It doesn't print out ``@code{ ok}'' or ``@code{ compiled}'' messages each
7794: time the parse area is emptied.
7795: @item
7796: If an error occurs, the input source is set back to the user input
7797: device.
1.27 crook 7798: @end itemize
1.21 crook 7799:
1.49 anton 7800: You can read about this in more detail in @ref{Input Sources}.
1.44 crook 7801:
1.26 crook 7802: doc->in
1.27 crook 7803: doc-source
7804:
1.26 crook 7805: doc-tib
7806: doc-#tib
1.1 anton 7807:
1.44 crook 7808:
1.26 crook 7809: @menu
1.67 anton 7810: * Input Sources::
7811: * Number Conversion::
7812: * Interpret/Compile states::
7813: * Interpreter Directives::
1.26 crook 7814: @end menu
1.1 anton 7815:
1.29 crook 7816: @node Input Sources, Number Conversion, The Text Interpreter, The Text Interpreter
7817: @subsection Input Sources
7818: @cindex input sources
7819: @cindex text interpreter - input sources
7820:
1.44 crook 7821: By default, the text interpreter processes input from the user input
1.29 crook 7822: device (the keyboard) when Forth starts up. The text interpreter can
7823: process input from any of these sources:
7824:
7825: @itemize @bullet
7826: @item
7827: The user input device -- the keyboard.
7828: @item
7829: A file, using the words described in @ref{Forth source files}.
7830: @item
7831: A block, using the words described in @ref{Blocks}.
7832: @item
7833: A text string, using @code{evaluate}.
7834: @end itemize
7835:
7836: A program can identify the current input device from the values of
7837: @code{source-id} and @code{blk}.
7838:
1.44 crook 7839:
1.29 crook 7840: doc-source-id
7841: doc-blk
7842:
7843: doc-save-input
7844: doc-restore-input
7845:
7846: doc-evaluate
1.111 anton 7847: doc-query
1.1 anton 7848:
1.29 crook 7849:
1.44 crook 7850:
1.29 crook 7851: @node Number Conversion, Interpret/Compile states, Input Sources, The Text Interpreter
1.26 crook 7852: @subsection Number Conversion
7853: @cindex number conversion
7854: @cindex double-cell numbers, input format
7855: @cindex input format for double-cell numbers
7856: @cindex single-cell numbers, input format
7857: @cindex input format for single-cell numbers
7858: @cindex floating-point numbers, input format
7859: @cindex input format for floating-point numbers
1.1 anton 7860:
1.29 crook 7861: This section describes the rules that the text interpreter uses when it
7862: tries to convert a string into a number.
1.1 anton 7863:
1.26 crook 7864: Let <digit> represent any character that is a legal digit in the current
1.29 crook 7865: number base@footnote{For example, 0-9 when the number base is decimal or
7866: 0-9, A-F when the number base is hexadecimal.}.
1.1 anton 7867:
1.26 crook 7868: Let <decimal digit> represent any character in the range 0-9.
1.1 anton 7869:
1.29 crook 7870: Let @{@i{a b}@} represent the @i{optional} presence of any of the characters
7871: in the braces (@i{a} or @i{b} or neither).
1.1 anton 7872:
1.26 crook 7873: Let * represent any number of instances of the previous character
7874: (including none).
1.1 anton 7875:
1.26 crook 7876: Let any other character represent itself.
1.1 anton 7877:
1.29 crook 7878: @noindent
1.26 crook 7879: Now, the conversion rules are:
1.21 crook 7880:
1.26 crook 7881: @itemize @bullet
7882: @item
7883: A string of the form <digit><digit>* is treated as a single-precision
1.29 crook 7884: (cell-sized) positive integer. Examples are 0 123 6784532 32343212343456 42
1.26 crook 7885: @item
7886: A string of the form -<digit><digit>* is treated as a single-precision
1.29 crook 7887: (cell-sized) negative integer, and is represented using 2's-complement
1.26 crook 7888: arithmetic. Examples are -45 -5681 -0
7889: @item
7890: A string of the form <digit><digit>*.<digit>* is treated as a double-precision
1.29 crook 7891: (double-cell-sized) positive integer. Examples are 3465. 3.465 34.65
7892: (all three of these represent the same number).
1.26 crook 7893: @item
7894: A string of the form -<digit><digit>*.<digit>* is treated as a
1.29 crook 7895: double-precision (double-cell-sized) negative integer, and is
1.26 crook 7896: represented using 2's-complement arithmetic. Examples are -3465. -3.465
1.29 crook 7897: -34.65 (all three of these represent the same number).
1.26 crook 7898: @item
1.29 crook 7899: A string of the form @{+ -@}<decimal digit>@{.@}<decimal digit>*@{e
7900: E@}@{+ -@}<decimal digit><decimal digit>* is treated as a floating-point
1.35 anton 7901: number. Examples are 1e 1e0 1.e 1.e0 +1e+0 (which all represent the same
1.29 crook 7902: number) +12.E-4
1.26 crook 7903: @end itemize
1.1 anton 7904:
1.174 anton 7905: By default, the number base used for integer number conversion is
7906: given by the contents of the variable @code{base}. Note that a lot of
1.35 anton 7907: confusion can result from unexpected values of @code{base}. If you
1.174 anton 7908: change @code{base} anywhere, make sure to save the old value and
7909: restore it afterwards; better yet, use @code{base-execute}, which does
7910: this for you. In general I recommend keeping @code{base} decimal, and
1.35 anton 7911: using the prefixes described below for the popular non-decimal bases.
1.1 anton 7912:
1.29 crook 7913: doc-dpl
1.174 anton 7914: doc-base-execute
1.26 crook 7915: doc-base
7916: doc-hex
7917: doc-decimal
1.1 anton 7918:
1.26 crook 7919: @cindex '-prefix for character strings
7920: @cindex &-prefix for decimal numbers
1.133 anton 7921: @cindex #-prefix for decimal numbers
1.26 crook 7922: @cindex %-prefix for binary numbers
7923: @cindex $-prefix for hexadecimal numbers
1.133 anton 7924: @cindex 0x-prefix for hexadecimal numbers
1.35 anton 7925: Gforth allows you to override the value of @code{base} by using a
1.29 crook 7926: prefix@footnote{Some Forth implementations provide a similar scheme by
7927: implementing @code{$} etc. as parsing words that process the subsequent
7928: number in the input stream and push it onto the stack. For example, see
7929: @cite{Number Conversion and Literals}, by Wil Baden; Forth Dimensions
7930: 20(3) pages 26--27. In such implementations, unlike in Gforth, a space
7931: is required between the prefix and the number.} before the first digit
1.133 anton 7932: of an (integer) number. The following prefixes are supported:
1.1 anton 7933:
1.26 crook 7934: @itemize @bullet
7935: @item
1.35 anton 7936: @code{&} -- decimal
1.26 crook 7937: @item
1.133 anton 7938: @code{#} -- decimal
7939: @item
1.35 anton 7940: @code{%} -- binary
1.26 crook 7941: @item
1.35 anton 7942: @code{$} -- hexadecimal
1.26 crook 7943: @item
1.133 anton 7944: @code{0x} -- hexadecimal, if base<33.
7945: @item
7946: @code{'} -- numeric value (e.g., ASCII code) of next character; an
7947: optional @code{'} may be present after the character.
1.26 crook 7948: @end itemize
1.1 anton 7949:
1.26 crook 7950: Here are some examples, with the equivalent decimal number shown after
7951: in braces:
1.1 anton 7952:
1.26 crook 7953: -$41 (-65), %1001101 (205), %1001.0001 (145 - a double-precision number),
1.133 anton 7954: 'A (65),
7955: -'a' (-97),
1.26 crook 7956: &905 (905), $abc (2478), $ABC (2478).
1.1 anton 7957:
1.26 crook 7958: @cindex number conversion - traps for the unwary
1.29 crook 7959: @noindent
1.26 crook 7960: Number conversion has a number of traps for the unwary:
1.1 anton 7961:
1.26 crook 7962: @itemize @bullet
7963: @item
7964: You cannot determine the current number base using the code sequence
1.35 anton 7965: @code{base @@ .} -- the number base is always 10 in the current number
7966: base. Instead, use something like @code{base @@ dec.}
1.26 crook 7967: @item
7968: If the number base is set to a value greater than 14 (for example,
7969: hexadecimal), the number 123E4 is ambiguous; the conversion rules allow
7970: it to be intepreted as either a single-precision integer or a
7971: floating-point number (Gforth treats it as an integer). The ambiguity
7972: can be resolved by explicitly stating the sign of the mantissa and/or
7973: exponent: 123E+4 or +123E4 -- if the number base is decimal, no
7974: ambiguity arises; either representation will be treated as a
7975: floating-point number.
7976: @item
1.29 crook 7977: There is a word @code{bin} but it does @i{not} set the number base!
1.26 crook 7978: It is used to specify file types.
7979: @item
1.72 anton 7980: ANS Forth requires the @code{.} of a double-precision number to be the
7981: final character in the string. Gforth allows the @code{.} to be
7982: anywhere after the first digit.
1.26 crook 7983: @item
7984: The number conversion process does not check for overflow.
7985: @item
1.72 anton 7986: In an ANS Forth program @code{base} is required to be decimal when
7987: converting floating-point numbers. In Gforth, number conversion to
7988: floating-point numbers always uses base &10, irrespective of the value
7989: of @code{base}.
1.26 crook 7990: @end itemize
1.1 anton 7991:
1.49 anton 7992: You can read numbers into your programs with the words described in
1.181 anton 7993: @ref{Line input and conversion}.
1.1 anton 7994:
1.82 anton 7995: @node Interpret/Compile states, Interpreter Directives, Number Conversion, The Text Interpreter
1.26 crook 7996: @subsection Interpret/Compile states
7997: @cindex Interpret/Compile states
1.1 anton 7998:
1.29 crook 7999: A standard program is not permitted to change @code{state}
8000: explicitly. However, it can change @code{state} implicitly, using the
8001: words @code{[} and @code{]}. When @code{[} is executed it switches
8002: @code{state} to interpret state, and therefore the text interpreter
8003: starts interpreting. When @code{]} is executed it switches @code{state}
8004: to compile state and therefore the text interpreter starts
1.44 crook 8005: compiling. The most common usage for these words is for switching into
8006: interpret state and back from within a colon definition; this technique
1.49 anton 8007: can be used to compile a literal (for an example, @pxref{Literals}) or
8008: for conditional compilation (for an example, @pxref{Interpreter
8009: Directives}).
1.44 crook 8010:
1.35 anton 8011:
8012: @c This is a bad example: It's non-standard, and it's not necessary.
8013: @c However, I can't think of a good example for switching into compile
8014: @c state when there is no current word (@code{state}-smart words are not a
8015: @c good reason). So maybe we should use an example for switching into
8016: @c interpret @code{state} in a colon def. - anton
1.44 crook 8017: @c nac-> I agree. I started out by putting in the example, then realised
8018: @c that it was non-ANS, so wrote more words around it. I hope this
8019: @c re-written version is acceptable to you. I do want to keep the example
8020: @c as it is helpful for showing what is and what is not portable, particularly
8021: @c where it outlaws a style in common use.
8022:
1.72 anton 8023: @c anton: it's more important to show what's portable. After we have done
1.83 anton 8024: @c that, we can also show what's not. In any case, I have written a
8025: @c section Compiling Words which also deals with [ ].
1.35 anton 8026:
1.95 anton 8027: @c !! The following example does not work in Gforth 0.5.9 or later.
1.29 crook 8028:
1.95 anton 8029: @c @code{[} and @code{]} also give you the ability to switch into compile
8030: @c state and back, but we cannot think of any useful Standard application
8031: @c for this ability. Pre-ANS Forth textbooks have examples like this:
8032:
8033: @c @example
8034: @c : AA ." this is A" ;
8035: @c : BB ." this is B" ;
8036: @c : CC ." this is C" ;
8037:
8038: @c create table ] aa bb cc [
8039:
8040: @c : go ( n -- ) \ n is offset into table.. 0 for 1st entry
8041: @c cells table + @@ execute ;
8042: @c @end example
8043:
8044: @c This example builds a jump table; @code{0 go} will display ``@code{this
8045: @c is A}''. Using @code{[} and @code{]} in this example is equivalent to
8046: @c defining @code{table} like this:
8047:
8048: @c @example
8049: @c create table ' aa COMPILE, ' bb COMPILE, ' cc COMPILE,
8050: @c @end example
8051:
8052: @c The problem with this code is that the definition of @code{table} is not
8053: @c portable -- it @i{compile}s execution tokens into code space. Whilst it
8054: @c @i{may} work on systems where code space and data space co-incide, the
8055: @c Standard only allows data space to be assigned for a @code{CREATE}d
8056: @c word. In addition, the Standard only allows @code{@@} to access data
8057: @c space, whilst this example is using it to access code space. The only
8058: @c portable, Standard way to build this table is to build it in data space,
8059: @c like this:
8060:
8061: @c @example
8062: @c create table ' aa , ' bb , ' cc ,
8063: @c @end example
1.29 crook 8064:
1.95 anton 8065: @c doc-state
1.44 crook 8066:
1.29 crook 8067:
1.82 anton 8068: @node Interpreter Directives, , Interpret/Compile states, The Text Interpreter
1.26 crook 8069: @subsection Interpreter Directives
8070: @cindex interpreter directives
1.72 anton 8071: @cindex conditional compilation
1.1 anton 8072:
1.29 crook 8073: These words are usually used in interpret state; typically to control
8074: which parts of a source file are processed by the text
1.26 crook 8075: interpreter. There are only a few ANS Forth Standard words, but Gforth
8076: supplements these with a rich set of immediate control structure words
8077: to compensate for the fact that the non-immediate versions can only be
1.29 crook 8078: used in compile state (@pxref{Control Structures}). Typical usages:
8079:
8080: @example
1.72 anton 8081: FALSE Constant HAVE-ASSEMBLER
1.29 crook 8082: .
8083: .
1.72 anton 8084: HAVE-ASSEMBLER [IF]
1.29 crook 8085: : ASSEMBLER-FEATURE
8086: ...
8087: ;
8088: [ENDIF]
8089: .
8090: .
8091: : SEE
8092: ... \ general-purpose SEE code
1.72 anton 8093: [ HAVE-ASSEMBLER [IF] ]
1.29 crook 8094: ... \ assembler-specific SEE code
8095: [ [ENDIF] ]
8096: ;
8097: @end example
1.1 anton 8098:
1.44 crook 8099:
1.26 crook 8100: doc-[IF]
8101: doc-[ELSE]
8102: doc-[THEN]
8103: doc-[ENDIF]
1.1 anton 8104:
1.26 crook 8105: doc-[IFDEF]
8106: doc-[IFUNDEF]
1.1 anton 8107:
1.26 crook 8108: doc-[?DO]
8109: doc-[DO]
8110: doc-[FOR]
8111: doc-[LOOP]
8112: doc-[+LOOP]
8113: doc-[NEXT]
1.1 anton 8114:
1.26 crook 8115: doc-[BEGIN]
8116: doc-[UNTIL]
8117: doc-[AGAIN]
8118: doc-[WHILE]
8119: doc-[REPEAT]
1.1 anton 8120:
1.27 crook 8121:
1.26 crook 8122: @c -------------------------------------------------------------
1.111 anton 8123: @node The Input Stream, Word Lists, The Text Interpreter, Words
8124: @section The Input Stream
8125: @cindex input stream
8126:
8127: @c !! integrate this better with the "Text Interpreter" section
8128: The text interpreter reads from the input stream, which can come from
8129: several sources (@pxref{Input Sources}). Some words, in particular
8130: defining words, but also words like @code{'}, read parameters from the
8131: input stream instead of from the stack.
8132:
8133: Such words are called parsing words, because they parse the input
8134: stream. Parsing words are hard to use in other words, because it is
8135: hard to pass program-generated parameters through the input stream.
8136: They also usually have an unintuitive combination of interpretation and
8137: compilation semantics when implemented naively, leading to various
8138: approaches that try to produce a more intuitive behaviour
8139: (@pxref{Combined words}).
8140:
8141: It should be obvious by now that parsing words are a bad idea. If you
8142: want to implement a parsing word for convenience, also provide a factor
8143: of the word that does not parse, but takes the parameters on the stack.
8144: To implement the parsing word on top if it, you can use the following
8145: words:
8146:
8147: @c anton: these belong in the input stream section
8148: doc-parse
1.138 anton 8149: doc-parse-name
1.111 anton 8150: doc-parse-word
8151: doc-name
8152: doc-word
8153: doc-refill
8154:
8155: Conversely, if you have the bad luck (or lack of foresight) to have to
8156: deal with parsing words without having such factors, how do you pass a
8157: string that is not in the input stream to it?
8158:
8159: doc-execute-parsing
8160:
1.146 anton 8161: A definition of this word in ANS Forth is provided in
8162: @file{compat/execute-parsing.fs}.
8163:
1.111 anton 8164: If you want to run a parsing word on a file, the following word should
8165: help:
8166:
8167: doc-execute-parsing-file
8168:
8169: @c -------------------------------------------------------------
8170: @node Word Lists, Environmental Queries, The Input Stream, Words
1.26 crook 8171: @section Word Lists
8172: @cindex word lists
1.32 anton 8173: @cindex header space
1.1 anton 8174:
1.36 anton 8175: A wordlist is a list of named words; you can add new words and look up
8176: words by name (and you can remove words in a restricted way with
8177: markers). Every named (and @code{reveal}ed) word is in one wordlist.
8178:
8179: @cindex search order stack
8180: The text interpreter searches the wordlists present in the search order
8181: (a stack of wordlists), from the top to the bottom. Within each
8182: wordlist, the search starts conceptually at the newest word; i.e., if
8183: two words in a wordlist have the same name, the newer word is found.
1.1 anton 8184:
1.26 crook 8185: @cindex compilation word list
1.36 anton 8186: New words are added to the @dfn{compilation wordlist} (aka current
8187: wordlist).
1.1 anton 8188:
1.36 anton 8189: @cindex wid
8190: A word list is identified by a cell-sized word list identifier (@i{wid})
8191: in much the same way as a file is identified by a file handle. The
8192: numerical value of the wid has no (portable) meaning, and might change
8193: from session to session.
1.1 anton 8194:
1.29 crook 8195: The ANS Forth ``Search order'' word set is intended to provide a set of
8196: low-level tools that allow various different schemes to be
1.74 anton 8197: implemented. Gforth also provides @code{vocabulary}, a traditional Forth
1.26 crook 8198: word. @file{compat/vocabulary.fs} provides an implementation in ANS
1.45 crook 8199: Forth.
1.1 anton 8200:
1.27 crook 8201: @comment TODO: locals section refers to here, saying that every word list (aka
8202: @comment vocabulary) has its own methods for searching etc. Need to document that.
1.78 anton 8203: @c anton: but better in a separate subsection on wordlist internals
1.1 anton 8204:
1.45 crook 8205: @comment TODO: document markers, reveal, tables, mappedwordlist
8206:
8207: @comment the gforthman- prefix is used to pick out the true definition of a
1.27 crook 8208: @comment word from the source files, rather than some alias.
1.44 crook 8209:
1.26 crook 8210: doc-forth-wordlist
8211: doc-definitions
8212: doc-get-current
8213: doc-set-current
8214: doc-get-order
1.185 anton 8215: doc-set-order
1.26 crook 8216: doc-wordlist
1.30 anton 8217: doc-table
1.79 anton 8218: doc->order
1.36 anton 8219: doc-previous
1.26 crook 8220: doc-also
1.185 anton 8221: doc-forth
1.26 crook 8222: doc-only
1.185 anton 8223: doc-order
1.15 anton 8224:
1.26 crook 8225: doc-find
8226: doc-search-wordlist
1.15 anton 8227:
1.26 crook 8228: doc-words
8229: doc-vlist
1.44 crook 8230: @c doc-words-deferred
1.1 anton 8231:
1.74 anton 8232: @c doc-mappedwordlist @c map-structure undefined, implemantation-specific
1.26 crook 8233: doc-root
8234: doc-vocabulary
8235: doc-seal
8236: doc-vocs
8237: doc-current
8238: doc-context
1.1 anton 8239:
1.44 crook 8240:
1.26 crook 8241: @menu
1.75 anton 8242: * Vocabularies::
1.67 anton 8243: * Why use word lists?::
1.75 anton 8244: * Word list example::
1.26 crook 8245: @end menu
8246:
1.75 anton 8247: @node Vocabularies, Why use word lists?, Word Lists, Word Lists
8248: @subsection Vocabularies
8249: @cindex Vocabularies, detailed explanation
8250:
8251: Here is an example of creating and using a new wordlist using ANS
8252: Forth words:
8253:
8254: @example
8255: wordlist constant my-new-words-wordlist
8256: : my-new-words get-order nip my-new-words-wordlist swap set-order ;
8257:
8258: \ add it to the search order
8259: also my-new-words
8260:
8261: \ alternatively, add it to the search order and make it
8262: \ the compilation word list
8263: also my-new-words definitions
8264: \ type "order" to see the problem
8265: @end example
8266:
8267: The problem with this example is that @code{order} has no way to
8268: associate the name @code{my-new-words} with the wid of the word list (in
8269: Gforth, @code{order} and @code{vocs} will display @code{???} for a wid
8270: that has no associated name). There is no Standard way of associating a
8271: name with a wid.
8272:
8273: In Gforth, this example can be re-coded using @code{vocabulary}, which
8274: associates a name with a wid:
8275:
8276: @example
8277: vocabulary my-new-words
8278:
8279: \ add it to the search order
8280: also my-new-words
8281:
8282: \ alternatively, add it to the search order and make it
8283: \ the compilation word list
8284: my-new-words definitions
8285: \ type "order" to see that the problem is solved
8286: @end example
8287:
8288:
8289: @node Why use word lists?, Word list example, Vocabularies, Word Lists
1.26 crook 8290: @subsection Why use word lists?
8291: @cindex word lists - why use them?
8292:
1.74 anton 8293: Here are some reasons why people use wordlists:
1.26 crook 8294:
8295: @itemize @bullet
1.74 anton 8296:
8297: @c anton: Gforth's hashing implementation makes the search speed
8298: @c independent from the number of words. But it is linear with the number
8299: @c of wordlists that have to be searched, so in effect using more wordlists
8300: @c actually slows down compilation.
8301:
8302: @c @item
8303: @c To improve compilation speed by reducing the number of header space
8304: @c entries that must be searched. This is achieved by creating a new
8305: @c word list that contains all of the definitions that are used in the
8306: @c definition of a Forth system but which would not usually be used by
8307: @c programs running on that system. That word list would be on the search
8308: @c list when the Forth system was compiled but would be removed from the
8309: @c search list for normal operation. This can be a useful technique for
8310: @c low-performance systems (for example, 8-bit processors in embedded
8311: @c systems) but is unlikely to be necessary in high-performance desktop
8312: @c systems.
8313:
1.26 crook 8314: @item
8315: To prevent a set of words from being used outside the context in which
8316: they are valid. Two classic examples of this are an integrated editor
8317: (all of the edit commands are defined in a separate word list; the
8318: search order is set to the editor word list when the editor is invoked;
8319: the old search order is restored when the editor is terminated) and an
8320: integrated assembler (the op-codes for the machine are defined in a
8321: separate word list which is used when a @code{CODE} word is defined).
1.74 anton 8322:
8323: @item
8324: To organize the words of an application or library into a user-visible
8325: set (in @code{forth-wordlist} or some other common wordlist) and a set
8326: of helper words used just for the implementation (hidden in a separate
1.75 anton 8327: wordlist). This keeps @code{words}' output smaller, separates
8328: implementation and interface, and reduces the chance of name conflicts
8329: within the common wordlist.
1.74 anton 8330:
1.26 crook 8331: @item
8332: To prevent a name-space clash between multiple definitions with the same
8333: name. For example, when building a cross-compiler you might have a word
8334: @code{IF} that generates conditional code for your target system. By
8335: placing this definition in a different word list you can control whether
8336: the host system's @code{IF} or the target system's @code{IF} get used in
8337: any particular context by controlling the order of the word lists on the
8338: search order stack.
1.74 anton 8339:
1.26 crook 8340: @end itemize
1.1 anton 8341:
1.74 anton 8342: The downsides of using wordlists are:
8343:
8344: @itemize
8345:
8346: @item
8347: Debugging becomes more cumbersome.
8348:
8349: @item
8350: Name conflicts worked around with wordlists are still there, and you
8351: have to arrange the search order carefully to get the desired results;
8352: if you forget to do that, you get hard-to-find errors (as in any case
8353: where you read the code differently from the compiler; @code{see} can
1.75 anton 8354: help seeing which of several possible words the name resolves to in such
8355: cases). @code{See} displays just the name of the words, not what
8356: wordlist they belong to, so it might be misleading. Using unique names
8357: is a better approach to avoid name conflicts.
1.74 anton 8358:
8359: @item
8360: You have to explicitly undo any changes to the search order. In many
8361: cases it would be more convenient if this happened implicitly. Gforth
8362: currently does not provide such a feature, but it may do so in the
8363: future.
8364: @end itemize
8365:
8366:
1.75 anton 8367: @node Word list example, , Why use word lists?, Word Lists
8368: @subsection Word list example
8369: @cindex word lists - example
1.1 anton 8370:
1.74 anton 8371: The following example is from the
8372: @uref{http://www.complang.tuwien.ac.at/forth/garbage-collection.zip,
8373: garbage collector} and uses wordlists to separate public words from
8374: helper words:
8375:
8376: @example
8377: get-current ( wid )
8378: vocabulary garbage-collector also garbage-collector definitions
8379: ... \ define helper words
8380: ( wid ) set-current \ restore original (i.e., public) compilation wordlist
8381: ... \ define the public (i.e., API) words
8382: \ they can refer to the helper words
8383: previous \ restore original search order (helper words become invisible)
8384: @end example
8385:
1.26 crook 8386: @c -------------------------------------------------------------
8387: @node Environmental Queries, Files, Word Lists, Words
8388: @section Environmental Queries
8389: @cindex environmental queries
1.21 crook 8390:
1.26 crook 8391: ANS Forth introduced the idea of ``environmental queries'' as a way
8392: for a program running on a system to determine certain characteristics of the system.
8393: The Standard specifies a number of strings that might be recognised by a system.
1.21 crook 8394:
1.32 anton 8395: The Standard requires that the header space used for environmental queries
8396: be distinct from the header space used for definitions.
1.21 crook 8397:
1.26 crook 8398: Typically, environmental queries are supported by creating a set of
1.29 crook 8399: definitions in a word list that is @i{only} used during environmental
1.26 crook 8400: queries; that is what Gforth does. There is no Standard way of adding
8401: definitions to the set of recognised environmental queries, but any
8402: implementation that supports the loading of optional word sets must have
8403: some mechanism for doing this (after loading the word set, the
8404: associated environmental query string must return @code{true}). In
8405: Gforth, the word list used to honour environmental queries can be
8406: manipulated just like any other word list.
1.21 crook 8407:
1.44 crook 8408:
1.26 crook 8409: doc-environment?
8410: doc-environment-wordlist
1.21 crook 8411:
1.26 crook 8412: doc-gforth
8413: doc-os-class
1.21 crook 8414:
1.44 crook 8415:
1.26 crook 8416: Note that, whilst the documentation for (e.g.) @code{gforth} shows it
8417: returning two items on the stack, querying it using @code{environment?}
8418: will return an additional item; the @code{true} flag that shows that the
8419: string was recognised.
1.21 crook 8420:
1.26 crook 8421: @comment TODO Document the standard strings or note where they are documented herein
1.21 crook 8422:
1.26 crook 8423: Here are some examples of using environmental queries:
1.21 crook 8424:
1.26 crook 8425: @example
8426: s" address-unit-bits" environment? 0=
8427: [IF]
8428: cr .( environmental attribute address-units-bits unknown... ) cr
1.75 anton 8429: [ELSE]
8430: drop \ ensure balanced stack effect
1.26 crook 8431: [THEN]
1.21 crook 8432:
1.75 anton 8433: \ this might occur in the prelude of a standard program that uses THROW
8434: s" exception" environment? [IF]
8435: 0= [IF]
8436: : throw abort" exception thrown" ;
8437: [THEN]
8438: [ELSE] \ we don't know, so make sure
8439: : throw abort" exception thrown" ;
8440: [THEN]
1.21 crook 8441:
1.26 crook 8442: s" gforth" environment? [IF] .( Gforth version ) TYPE
8443: [ELSE] .( Not Gforth..) [THEN]
1.75 anton 8444:
8445: \ a program using v*
8446: s" gforth" environment? [IF]
8447: s" 0.5.0" compare 0< [IF] \ v* is a primitive since 0.5.0
8448: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8449: >r swap 2swap swap 0e r> 0 ?DO
1.190 anton 8450: dup f@@ over + 2swap dup f@@ f* f+ over + 2swap
1.75 anton 8451: LOOP
8452: 2drop 2drop ;
8453: [THEN]
8454: [ELSE] \
8455: : v* ( f_addr1 nstride1 f_addr2 nstride2 ucount -- r )
8456: ...
8457: [THEN]
1.26 crook 8458: @end example
1.21 crook 8459:
1.26 crook 8460: Here is an example of adding a definition to the environment word list:
1.21 crook 8461:
1.26 crook 8462: @example
8463: get-current environment-wordlist set-current
8464: true constant block
8465: true constant block-ext
8466: set-current
8467: @end example
1.21 crook 8468:
1.26 crook 8469: You can see what definitions are in the environment word list like this:
1.21 crook 8470:
1.26 crook 8471: @example
1.79 anton 8472: environment-wordlist >order words previous
1.26 crook 8473: @end example
1.21 crook 8474:
8475:
1.26 crook 8476: @c -------------------------------------------------------------
8477: @node Files, Blocks, Environmental Queries, Words
8478: @section Files
1.28 crook 8479: @cindex files
8480: @cindex I/O - file-handling
1.21 crook 8481:
1.26 crook 8482: Gforth provides facilities for accessing files that are stored in the
8483: host operating system's file-system. Files that are processed by Gforth
8484: can be divided into two categories:
1.21 crook 8485:
1.23 crook 8486: @itemize @bullet
8487: @item
1.29 crook 8488: Files that are processed by the Text Interpreter (@dfn{Forth source files}).
1.23 crook 8489: @item
1.29 crook 8490: Files that are processed by some other program (@dfn{general files}).
1.26 crook 8491: @end itemize
8492:
8493: @menu
1.48 anton 8494: * Forth source files::
8495: * General files::
1.167 anton 8496: * Redirection::
1.48 anton 8497: * Search Paths::
1.26 crook 8498: @end menu
8499:
8500: @c -------------------------------------------------------------
8501: @node Forth source files, General files, Files, Files
8502: @subsection Forth source files
8503: @cindex including files
8504: @cindex Forth source files
1.21 crook 8505:
1.26 crook 8506: The simplest way to interpret the contents of a file is to use one of
8507: these two formats:
1.21 crook 8508:
1.26 crook 8509: @example
8510: include mysource.fs
8511: s" mysource.fs" included
8512: @end example
1.21 crook 8513:
1.75 anton 8514: You usually want to include a file only if it is not included already
1.26 crook 8515: (by, say, another source file). In that case, you can use one of these
1.45 crook 8516: three formats:
1.21 crook 8517:
1.26 crook 8518: @example
8519: require mysource.fs
8520: needs mysource.fs
8521: s" mysource.fs" required
8522: @end example
1.21 crook 8523:
1.26 crook 8524: @cindex stack effect of included files
8525: @cindex including files, stack effect
1.45 crook 8526: It is good practice to write your source files such that interpreting them
8527: does not change the stack. Source files designed in this way can be used with
1.26 crook 8528: @code{required} and friends without complications. For example:
1.21 crook 8529:
1.26 crook 8530: @example
1.75 anton 8531: 1024 require foo.fs drop
1.26 crook 8532: @end example
1.21 crook 8533:
1.75 anton 8534: Here you want to pass the argument 1024 (e.g., a buffer size) to
8535: @file{foo.fs}. Interpreting @file{foo.fs} has the stack effect ( n -- n
8536: ), which allows its use with @code{require}. Of course with such
8537: parameters to required files, you have to ensure that the first
8538: @code{require} fits for all uses (i.e., @code{require} it early in the
8539: master load file).
1.44 crook 8540:
1.26 crook 8541: doc-include-file
8542: doc-included
1.28 crook 8543: doc-included?
1.26 crook 8544: doc-include
8545: doc-required
8546: doc-require
8547: doc-needs
1.75 anton 8548: @c doc-init-included-files @c internal
8549: doc-sourcefilename
8550: doc-sourceline#
1.44 crook 8551:
1.26 crook 8552: A definition in ANS Forth for @code{required} is provided in
8553: @file{compat/required.fs}.
1.21 crook 8554:
1.26 crook 8555: @c -------------------------------------------------------------
1.167 anton 8556: @node General files, Redirection, Forth source files, Files
1.26 crook 8557: @subsection General files
8558: @cindex general files
8559: @cindex file-handling
1.21 crook 8560:
1.75 anton 8561: Files are opened/created by name and type. The following file access
8562: methods (FAMs) are recognised:
1.44 crook 8563:
1.75 anton 8564: @cindex fam (file access method)
1.26 crook 8565: doc-r/o
8566: doc-r/w
8567: doc-w/o
8568: doc-bin
1.1 anton 8569:
1.44 crook 8570:
1.26 crook 8571: When a file is opened/created, it returns a file identifier,
1.29 crook 8572: @i{wfileid} that is used for all other file commands. All file
8573: commands also return a status value, @i{wior}, that is 0 for a
1.26 crook 8574: successful operation and an implementation-defined non-zero value in the
8575: case of an error.
1.21 crook 8576:
1.44 crook 8577:
1.26 crook 8578: doc-open-file
8579: doc-create-file
1.21 crook 8580:
1.26 crook 8581: doc-close-file
8582: doc-delete-file
8583: doc-rename-file
8584: doc-read-file
8585: doc-read-line
1.154 anton 8586: doc-key-file
8587: doc-key?-file
1.26 crook 8588: doc-write-file
8589: doc-write-line
8590: doc-emit-file
8591: doc-flush-file
1.21 crook 8592:
1.26 crook 8593: doc-file-status
8594: doc-file-position
8595: doc-reposition-file
8596: doc-file-size
8597: doc-resize-file
1.21 crook 8598:
1.93 anton 8599: doc-slurp-file
8600: doc-slurp-fid
1.112 anton 8601: doc-stdin
8602: doc-stdout
8603: doc-stderr
1.44 crook 8604:
1.26 crook 8605: @c ---------------------------------------------------------
1.167 anton 8606: @node Redirection, Search Paths, General files, Files
8607: @subsection Redirection
8608: @cindex Redirection
8609: @cindex Input Redirection
8610: @cindex Output Redirection
8611:
8612: You can redirect the output of @code{type} and @code{emit} and all the
8613: words that use them (all output words that don't have an explicit
1.174 anton 8614: target file) to an arbitrary file with the @code{outfile-execute},
8615: used like this:
1.167 anton 8616:
8617: @example
1.174 anton 8618: : some-warning ( n -- )
8619: cr ." warning# " . ;
8620:
1.167 anton 8621: : print-some-warning ( n -- )
1.174 anton 8622: ['] some-warning stderr outfile-execute ;
1.167 anton 8623: @end example
8624:
1.174 anton 8625: After @code{some-warning} is executed, the original output direction
8626: is restored; this construct is safe against exceptions. Similarly,
8627: there is @code{infile-execute} for redirecting the input of @code{key}
8628: and its users (any input word that does not take a file explicitly).
8629:
8630: doc-outfile-execute
8631: doc-infile-execute
1.167 anton 8632:
8633: If you do not want to redirect the input or output to a file, you can
8634: also make use of the fact that @code{key}, @code{emit} and @code{type}
8635: are deferred words (@pxref{Deferred Words}). However, in that case
8636: you have to worry about the restoration and the protection against
8637: exceptions yourself; also, note that for redirecting the output in
8638: this way, you have to redirect both @code{emit} and @code{type}.
8639:
8640: @c ---------------------------------------------------------
8641: @node Search Paths, , Redirection, Files
1.26 crook 8642: @subsection Search Paths
8643: @cindex path for @code{included}
8644: @cindex file search path
8645: @cindex @code{include} search path
8646: @cindex search path for files
1.21 crook 8647:
1.26 crook 8648: If you specify an absolute filename (i.e., a filename starting with
8649: @file{/} or @file{~}, or with @file{:} in the second position (as in
8650: @samp{C:...})) for @code{included} and friends, that file is included
8651: just as you would expect.
1.21 crook 8652:
1.75 anton 8653: If the filename starts with @file{./}, this refers to the directory that
8654: the present file was @code{included} from. This allows files to include
8655: other files relative to their own position (irrespective of the current
8656: working directory or the absolute position). This feature is essential
8657: for libraries consisting of several files, where a file may include
8658: other files from the library. It corresponds to @code{#include "..."}
8659: in C. If the current input source is not a file, @file{.} refers to the
8660: directory of the innermost file being included, or, if there is no file
8661: being included, to the current working directory.
8662:
8663: For relative filenames (not starting with @file{./}), Gforth uses a
8664: search path similar to Forth's search order (@pxref{Word Lists}). It
8665: tries to find the given filename in the directories present in the path,
8666: and includes the first one it finds. There are separate search paths for
8667: Forth source files and general files. If the search path contains the
8668: directory @file{.}, this refers to the directory of the current file, or
8669: the working directory, as if the file had been specified with @file{./}.
1.21 crook 8670:
1.26 crook 8671: Use @file{~+} to refer to the current working directory (as in the
8672: @code{bash}).
1.1 anton 8673:
1.75 anton 8674: @c anton: fold the following subsubsections into this subsection?
1.1 anton 8675:
1.48 anton 8676: @menu
1.75 anton 8677: * Source Search Paths::
1.48 anton 8678: * General Search Paths::
8679: @end menu
8680:
1.26 crook 8681: @c ---------------------------------------------------------
1.75 anton 8682: @node Source Search Paths, General Search Paths, Search Paths, Search Paths
8683: @subsubsection Source Search Paths
8684: @cindex search path control, source files
1.5 anton 8685:
1.26 crook 8686: The search path is initialized when you start Gforth (@pxref{Invoking
1.75 anton 8687: Gforth}). You can display it and change it using @code{fpath} in
8688: combination with the general path handling words.
1.5 anton 8689:
1.75 anton 8690: doc-fpath
8691: @c the functionality of the following words is easily available through
8692: @c fpath and the general path words. The may go away.
8693: @c doc-.fpath
8694: @c doc-fpath+
8695: @c doc-fpath=
8696: @c doc-open-fpath-file
1.44 crook 8697:
8698: @noindent
1.26 crook 8699: Here is an example of using @code{fpath} and @code{require}:
1.5 anton 8700:
1.26 crook 8701: @example
1.75 anton 8702: fpath path= /usr/lib/forth/|./
1.26 crook 8703: require timer.fs
8704: @end example
1.5 anton 8705:
1.75 anton 8706:
1.26 crook 8707: @c ---------------------------------------------------------
1.75 anton 8708: @node General Search Paths, , Source Search Paths, Search Paths
1.26 crook 8709: @subsubsection General Search Paths
1.75 anton 8710: @cindex search path control, source files
1.5 anton 8711:
1.26 crook 8712: Your application may need to search files in several directories, like
8713: @code{included} does. To facilitate this, Gforth allows you to define
8714: and use your own search paths, by providing generic equivalents of the
8715: Forth search path words:
1.5 anton 8716:
1.75 anton 8717: doc-open-path-file
8718: doc-path-allot
8719: doc-clear-path
8720: doc-also-path
1.26 crook 8721: doc-.path
8722: doc-path+
8723: doc-path=
1.5 anton 8724:
1.75 anton 8725: @c anton: better define a word for it, say "path-allot ( ucount -- path-addr )
1.44 crook 8726:
1.75 anton 8727: Here's an example of creating an empty search path:
8728: @c
1.26 crook 8729: @example
1.75 anton 8730: create mypath 500 path-allot \ maximum length 500 chars (is checked)
1.26 crook 8731: @end example
1.5 anton 8732:
1.26 crook 8733: @c -------------------------------------------------------------
8734: @node Blocks, Other I/O, Files, Words
8735: @section Blocks
1.28 crook 8736: @cindex I/O - blocks
8737: @cindex blocks
8738:
8739: When you run Gforth on a modern desk-top computer, it runs under the
8740: control of an operating system which provides certain services. One of
8741: these services is @var{file services}, which allows Forth source code
8742: and data to be stored in files and read into Gforth (@pxref{Files}).
8743:
8744: Traditionally, Forth has been an important programming language on
8745: systems where it has interfaced directly to the underlying hardware with
8746: no intervening operating system. Forth provides a mechanism, called
1.29 crook 8747: @dfn{blocks}, for accessing mass storage on such systems.
1.28 crook 8748:
8749: A block is a 1024-byte data area, which can be used to hold data or
8750: Forth source code. No structure is imposed on the contents of the
8751: block. A block is identified by its number; blocks are numbered
8752: contiguously from 1 to an implementation-defined maximum.
8753:
8754: A typical system that used blocks but no operating system might use a
8755: single floppy-disk drive for mass storage, with the disks formatted to
8756: provide 256-byte sectors. Blocks would be implemented by assigning the
8757: first four sectors of the disk to block 1, the second four sectors to
8758: block 2 and so on, up to the limit of the capacity of the disk. The disk
8759: would not contain any file system information, just the set of blocks.
8760:
1.29 crook 8761: @cindex blocks file
1.28 crook 8762: On systems that do provide file services, blocks are typically
1.29 crook 8763: implemented by storing a sequence of blocks within a single @dfn{blocks
1.28 crook 8764: file}. The size of the blocks file will be an exact multiple of 1024
8765: bytes, corresponding to the number of blocks it contains. This is the
8766: mechanism that Gforth uses.
8767:
1.29 crook 8768: @cindex @file{blocks.fb}
1.75 anton 8769: Only one blocks file can be open at a time. If you use block words without
1.28 crook 8770: having specified a blocks file, Gforth defaults to the blocks file
8771: @file{blocks.fb}. Gforth uses the Forth search path when attempting to
1.75 anton 8772: locate a blocks file (@pxref{Source Search Paths}).
1.28 crook 8773:
1.29 crook 8774: @cindex block buffers
1.28 crook 8775: When you read and write blocks under program control, Gforth uses a
1.29 crook 8776: number of @dfn{block buffers} as intermediate storage. These buffers are
1.28 crook 8777: not used when you use @code{load} to interpret the contents of a block.
8778:
1.75 anton 8779: The behaviour of the block buffers is analagous to that of a cache.
8780: Each block buffer has three states:
1.28 crook 8781:
8782: @itemize @bullet
8783: @item
8784: Unassigned
8785: @item
8786: Assigned-clean
8787: @item
8788: Assigned-dirty
8789: @end itemize
8790:
1.29 crook 8791: Initially, all block buffers are @i{unassigned}. In order to access a
1.28 crook 8792: block, the block (specified by its block number) must be assigned to a
8793: block buffer.
8794:
8795: The assignment of a block to a block buffer is performed by @code{block}
8796: or @code{buffer}. Use @code{block} when you wish to modify the existing
8797: contents of a block. Use @code{buffer} when you don't care about the
8798: existing contents of the block@footnote{The ANS Forth definition of
1.35 anton 8799: @code{buffer} is intended not to cause disk I/O; if the data associated
1.28 crook 8800: with the particular block is already stored in a block buffer due to an
8801: earlier @code{block} command, @code{buffer} will return that block
8802: buffer and the existing contents of the block will be
8803: available. Otherwise, @code{buffer} will simply assign a new, empty
1.29 crook 8804: block buffer for the block.}.
1.28 crook 8805:
1.47 crook 8806: Once a block has been assigned to a block buffer using @code{block} or
1.75 anton 8807: @code{buffer}, that block buffer becomes the @i{current block
8808: buffer}. Data may only be manipulated (read or written) within the
8809: current block buffer.
1.47 crook 8810:
8811: When the contents of the current block buffer has been modified it is
1.48 anton 8812: necessary, @emph{before calling @code{block} or @code{buffer} again}, to
1.75 anton 8813: either abandon the changes (by doing nothing) or mark the block as
8814: changed (assigned-dirty), using @code{update}. Using @code{update} does
8815: not change the blocks file; it simply changes a block buffer's state to
8816: @i{assigned-dirty}. The block will be written implicitly when it's
8817: buffer is needed for another block, or explicitly by @code{flush} or
8818: @code{save-buffers}.
8819:
8820: word @code{Flush} writes all @i{assigned-dirty} blocks back to the
8821: blocks file on disk. Leaving Gforth with @code{bye} also performs a
8822: @code{flush}.
1.28 crook 8823:
1.29 crook 8824: In Gforth, @code{block} and @code{buffer} use a @i{direct-mapped}
1.28 crook 8825: algorithm to assign a block buffer to a block. That means that any
8826: particular block can only be assigned to one specific block buffer,
1.29 crook 8827: called (for the particular operation) the @i{victim buffer}. If the
1.47 crook 8828: victim buffer is @i{unassigned} or @i{assigned-clean} it is allocated to
8829: the new block immediately. If it is @i{assigned-dirty} its current
8830: contents are written back to the blocks file on disk before it is
1.28 crook 8831: allocated to the new block.
8832:
8833: Although no structure is imposed on the contents of a block, it is
8834: traditional to display the contents as 16 lines each of 64 characters. A
8835: block provides a single, continuous stream of input (for example, it
8836: acts as a single parse area) -- there are no end-of-line characters
8837: within a block, and no end-of-file character at the end of a
8838: block. There are two consequences of this:
1.26 crook 8839:
1.28 crook 8840: @itemize @bullet
8841: @item
8842: The last character of one line wraps straight into the first character
8843: of the following line
8844: @item
8845: The word @code{\} -- comment to end of line -- requires special
8846: treatment; in the context of a block it causes all characters until the
8847: end of the current 64-character ``line'' to be ignored.
8848: @end itemize
8849:
8850: In Gforth, when you use @code{block} with a non-existent block number,
1.45 crook 8851: the current blocks file will be extended to the appropriate size and the
1.28 crook 8852: block buffer will be initialised with spaces.
8853:
1.47 crook 8854: Gforth includes a simple block editor (type @code{use blocked.fb 0 list}
8855: for details) but doesn't encourage the use of blocks; the mechanism is
8856: only provided for backward compatibility -- ANS Forth requires blocks to
8857: be available when files are.
1.28 crook 8858:
8859: Common techniques that are used when working with blocks include:
8860:
8861: @itemize @bullet
8862: @item
8863: A screen editor that allows you to edit blocks without leaving the Forth
8864: environment.
8865: @item
8866: Shadow screens; where every code block has an associated block
8867: containing comments (for example: code in odd block numbers, comments in
8868: even block numbers). Typically, the block editor provides a convenient
8869: mechanism to toggle between code and comments.
8870: @item
8871: Load blocks; a single block (typically block 1) contains a number of
8872: @code{thru} commands which @code{load} the whole of the application.
8873: @end itemize
1.26 crook 8874:
1.29 crook 8875: See Frank Sergeant's Pygmy Forth to see just how well blocks can be
8876: integrated into a Forth programming environment.
1.26 crook 8877:
8878: @comment TODO what about errors on open-blocks?
1.44 crook 8879:
1.26 crook 8880: doc-open-blocks
8881: doc-use
1.75 anton 8882: doc-block-offset
1.26 crook 8883: doc-get-block-fid
8884: doc-block-position
1.28 crook 8885:
1.75 anton 8886: doc-list
1.28 crook 8887: doc-scr
8888:
1.184 anton 8889: doc-block
1.28 crook 8890: doc-buffer
8891:
1.75 anton 8892: doc-empty-buffers
8893: doc-empty-buffer
1.26 crook 8894: doc-update
1.28 crook 8895: doc-updated?
1.26 crook 8896: doc-save-buffers
1.75 anton 8897: doc-save-buffer
1.26 crook 8898: doc-flush
1.28 crook 8899:
1.26 crook 8900: doc-load
8901: doc-thru
8902: doc-+load
8903: doc-+thru
1.45 crook 8904: doc---gforthman--->
1.26 crook 8905: doc-block-included
8906:
1.44 crook 8907:
1.26 crook 8908: @c -------------------------------------------------------------
1.126 pazsan 8909: @node Other I/O, OS command line arguments, Blocks, Words
1.26 crook 8910: @section Other I/O
1.28 crook 8911: @cindex I/O - keyboard and display
1.26 crook 8912:
8913: @menu
8914: * Simple numeric output:: Predefined formats
8915: * Formatted numeric output:: Formatted (pictured) output
8916: * String Formats:: How Forth stores strings in memory
1.67 anton 8917: * Displaying characters and strings:: Other stuff
1.175 anton 8918: * Terminal output:: Cursor positioning etc.
1.181 anton 8919: * Single-key input::
8920: * Line input and conversion::
1.112 anton 8921: * Pipes:: How to create your own pipes
1.149 pazsan 8922: * Xchars and Unicode:: Non-ASCII characters
1.26 crook 8923: @end menu
8924:
8925: @node Simple numeric output, Formatted numeric output, Other I/O, Other I/O
8926: @subsection Simple numeric output
1.28 crook 8927: @cindex numeric output - simple/free-format
1.5 anton 8928:
1.26 crook 8929: The simplest output functions are those that display numbers from the
8930: data or floating-point stacks. Floating-point output is always displayed
8931: using base 10. Numbers displayed from the data stack use the value stored
8932: in @code{base}.
1.5 anton 8933:
1.44 crook 8934:
1.26 crook 8935: doc-.
8936: doc-dec.
8937: doc-hex.
8938: doc-u.
8939: doc-.r
8940: doc-u.r
8941: doc-d.
8942: doc-ud.
8943: doc-d.r
8944: doc-ud.r
8945: doc-f.
8946: doc-fe.
8947: doc-fs.
1.111 anton 8948: doc-f.rdp
1.44 crook 8949:
1.26 crook 8950: Examples of printing the number 1234.5678E23 in the different floating-point output
8951: formats are shown below:
1.5 anton 8952:
8953: @example
1.26 crook 8954: f. 123456779999999000000000000.
8955: fe. 123.456779999999E24
8956: fs. 1.23456779999999E26
1.5 anton 8957: @end example
8958:
8959:
1.26 crook 8960: @node Formatted numeric output, String Formats, Simple numeric output, Other I/O
8961: @subsection Formatted numeric output
1.28 crook 8962: @cindex formatted numeric output
1.26 crook 8963: @cindex pictured numeric output
1.28 crook 8964: @cindex numeric output - formatted
1.26 crook 8965:
1.29 crook 8966: Forth traditionally uses a technique called @dfn{pictured numeric
1.26 crook 8967: output} for formatted printing of integers. In this technique, digits
8968: are extracted from the number (using the current output radix defined by
8969: @code{base}), converted to ASCII codes and appended to a string that is
8970: built in a scratch-pad area of memory (@pxref{core-idef,
8971: Implementation-defined options, Implementation-defined
8972: options}). Arbitrary characters can be appended to the string during the
8973: extraction process. The completed string is specified by an address
8974: and length and can be manipulated (@code{TYPE}ed, copied, modified)
8975: under program control.
1.5 anton 8976:
1.75 anton 8977: All of the integer output words described in the previous section
8978: (@pxref{Simple numeric output}) are implemented in Gforth using pictured
8979: numeric output.
1.5 anton 8980:
1.47 crook 8981: Three important things to remember about pictured numeric output:
1.5 anton 8982:
1.26 crook 8983: @itemize @bullet
8984: @item
1.28 crook 8985: It always operates on double-precision numbers; to display a
1.49 anton 8986: single-precision number, convert it first (for ways of doing this
8987: @pxref{Double precision}).
1.26 crook 8988: @item
1.28 crook 8989: It always treats the double-precision number as though it were
8990: unsigned. The examples below show ways of printing signed numbers.
1.26 crook 8991: @item
8992: The string is built up from right to left; least significant digit first.
8993: @end itemize
1.5 anton 8994:
1.44 crook 8995:
1.26 crook 8996: doc-<#
1.47 crook 8997: doc-<<#
1.26 crook 8998: doc-#
8999: doc-#s
9000: doc-hold
9001: doc-sign
9002: doc-#>
1.47 crook 9003: doc-#>>
1.5 anton 9004:
1.26 crook 9005: doc-represent
1.111 anton 9006: doc-f>str-rdp
9007: doc-f>buf-rdp
1.5 anton 9008:
1.44 crook 9009:
9010: @noindent
1.26 crook 9011: Here are some examples of using pictured numeric output:
1.5 anton 9012:
9013: @example
1.26 crook 9014: : my-u. ( u -- )
9015: \ Simplest use of pns.. behaves like Standard u.
9016: 0 \ convert to unsigned double
1.75 anton 9017: <<# \ start conversion
1.26 crook 9018: #s \ convert all digits
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: : cents-only ( u -- )
9024: 0 \ convert to unsigned double
1.75 anton 9025: <<# \ start conversion
1.26 crook 9026: # # \ convert two least-significant digits
9027: #> \ complete conversion, discard other digits
1.75 anton 9028: TYPE SPACE \ display, with trailing space
9029: #>> ; \ release hold area
1.5 anton 9030:
1.26 crook 9031: : dollars-and-cents ( u -- )
9032: 0 \ convert to unsigned double
1.75 anton 9033: <<# \ start conversion
1.26 crook 9034: # # \ convert two least-significant digits
9035: [char] . hold \ insert decimal point
9036: #s \ convert remaining digits
9037: [char] $ hold \ append currency symbol
9038: #> \ complete conversion
1.75 anton 9039: TYPE SPACE \ display, with trailing space
9040: #>> ; \ release hold area
1.5 anton 9041:
1.26 crook 9042: : my-. ( n -- )
9043: \ handling negatives.. behaves like Standard .
9044: s>d \ convert to signed double
9045: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9046: <<# \ start conversion
1.26 crook 9047: #s \ convert all digits
9048: rot sign \ get at sign byte, append "-" if needed
9049: #> \ complete conversion
1.75 anton 9050: TYPE SPACE \ display, with trailing space
9051: #>> ; \ release hold area
1.5 anton 9052:
1.26 crook 9053: : account. ( n -- )
1.75 anton 9054: \ accountants don't like minus signs, they use parentheses
1.26 crook 9055: \ for negative numbers
9056: s>d \ convert to signed double
9057: swap over dabs \ leave sign byte followed by unsigned double
1.75 anton 9058: <<# \ start conversion
1.26 crook 9059: 2 pick \ get copy of sign byte
9060: 0< IF [char] ) hold THEN \ right-most character of output
9061: #s \ convert all digits
9062: rot \ get at sign byte
9063: 0< IF [char] ( hold THEN
9064: #> \ complete conversion
1.75 anton 9065: TYPE SPACE \ display, with trailing space
9066: #>> ; \ release hold area
9067:
1.5 anton 9068: @end example
9069:
1.26 crook 9070: Here are some examples of using these words:
1.5 anton 9071:
9072: @example
1.26 crook 9073: 1 my-u. 1
9074: hex -1 my-u. decimal FFFFFFFF
9075: 1 cents-only 01
9076: 1234 cents-only 34
9077: 2 dollars-and-cents $0.02
9078: 1234 dollars-and-cents $12.34
9079: 123 my-. 123
9080: -123 my. -123
9081: 123 account. 123
9082: -456 account. (456)
1.5 anton 9083: @end example
9084:
9085:
1.26 crook 9086: @node String Formats, Displaying characters and strings, Formatted numeric output, Other I/O
9087: @subsection String Formats
1.27 crook 9088: @cindex strings - see character strings
9089: @cindex character strings - formats
1.28 crook 9090: @cindex I/O - see character strings
1.75 anton 9091: @cindex counted strings
9092:
9093: @c anton: this does not really belong here; maybe the memory section,
9094: @c or the principles chapter
1.26 crook 9095:
1.27 crook 9096: Forth commonly uses two different methods for representing character
9097: strings:
1.26 crook 9098:
9099: @itemize @bullet
9100: @item
9101: @cindex address of counted string
1.45 crook 9102: @cindex counted string
1.29 crook 9103: As a @dfn{counted string}, represented by a @i{c-addr}. The char
9104: addressed by @i{c-addr} contains a character-count, @i{n}, of the
9105: string and the string occupies the subsequent @i{n} char addresses in
1.26 crook 9106: memory.
9107: @item
1.29 crook 9108: As cell pair on the stack; @i{c-addr u}, where @i{u} is the length
9109: of the string in characters, and @i{c-addr} is the address of the
1.26 crook 9110: first byte of the string.
9111: @end itemize
9112:
9113: ANS Forth encourages the use of the second format when representing
1.75 anton 9114: strings.
1.26 crook 9115:
1.44 crook 9116:
1.26 crook 9117: doc-count
9118:
1.44 crook 9119:
1.49 anton 9120: For words that move, copy and search for strings see @ref{Memory
9121: Blocks}. For words that display characters and strings see
9122: @ref{Displaying characters and strings}.
1.26 crook 9123:
1.175 anton 9124: @node Displaying characters and strings, Terminal output, String Formats, Other I/O
1.26 crook 9125: @subsection Displaying characters and strings
1.27 crook 9126: @cindex characters - compiling and displaying
9127: @cindex character strings - compiling and displaying
1.26 crook 9128:
9129: This section starts with a glossary of Forth words and ends with a set
9130: of examples.
9131:
9132: doc-bl
9133: doc-space
9134: doc-spaces
9135: doc-emit
9136: doc-toupper
9137: doc-."
9138: doc-.(
1.98 anton 9139: doc-.\"
1.26 crook 9140: doc-type
1.44 crook 9141: doc-typewhite
1.26 crook 9142: doc-cr
1.27 crook 9143: @cindex cursor control
1.26 crook 9144: doc-s"
1.98 anton 9145: doc-s\"
1.26 crook 9146: doc-c"
9147: doc-char
9148: doc-[char]
9149:
1.44 crook 9150:
9151: @noindent
1.26 crook 9152: As an example, consider the following text, stored in a file @file{test.fs}:
1.5 anton 9153:
9154: @example
1.26 crook 9155: .( text-1)
9156: : my-word
9157: ." text-2" cr
9158: .( text-3)
9159: ;
9160:
9161: ." text-4"
9162:
9163: : my-char
9164: [char] ALPHABET emit
9165: char emit
9166: ;
1.5 anton 9167: @end example
9168:
1.26 crook 9169: When you load this code into Gforth, the following output is generated:
1.5 anton 9170:
1.26 crook 9171: @example
1.30 anton 9172: @kbd{include test.fs @key{RET}} text-1text-3text-4 ok
1.26 crook 9173: @end example
1.5 anton 9174:
1.26 crook 9175: @itemize @bullet
9176: @item
9177: Messages @code{text-1} and @code{text-3} are displayed because @code{.(}
9178: is an immediate word; it behaves in the same way whether it is used inside
9179: or outside a colon definition.
9180: @item
9181: Message @code{text-4} is displayed because of Gforth's added interpretation
9182: semantics for @code{."}.
9183: @item
1.29 crook 9184: Message @code{text-2} is @i{not} displayed, because the text interpreter
1.26 crook 9185: performs the compilation semantics for @code{."} within the definition of
9186: @code{my-word}.
9187: @end itemize
1.5 anton 9188:
1.26 crook 9189: Here are some examples of executing @code{my-word} and @code{my-char}:
1.5 anton 9190:
1.26 crook 9191: @example
1.30 anton 9192: @kbd{my-word @key{RET}} text-2
1.26 crook 9193: ok
1.30 anton 9194: @kbd{my-char fred @key{RET}} Af ok
9195: @kbd{my-char jim @key{RET}} Aj ok
1.26 crook 9196: @end example
1.5 anton 9197:
9198: @itemize @bullet
9199: @item
1.26 crook 9200: Message @code{text-2} is displayed because of the run-time behaviour of
9201: @code{."}.
9202: @item
9203: @code{[char]} compiles the ``A'' from ``ALPHABET'' and puts its display code
9204: on the stack at run-time. @code{emit} always displays the character
9205: when @code{my-char} is executed.
9206: @item
9207: @code{char} parses a string at run-time and the second @code{emit} displays
9208: the first character of the string.
1.5 anton 9209: @item
1.26 crook 9210: If you type @code{see my-char} you can see that @code{[char]} discarded
9211: the text ``LPHABET'' and only compiled the display code for ``A'' into the
9212: definition of @code{my-char}.
1.5 anton 9213: @end itemize
9214:
9215:
1.181 anton 9216: @node Terminal output, Single-key input, Displaying characters and strings, Other I/O
1.175 anton 9217: @subsection Terminal output
9218: @cindex output to terminal
9219: @cindex terminal output
9220:
9221: If you are outputting to a terminal, you may want to control the
9222: positioning of the cursor:
9223: @cindex cursor positioning
9224:
9225: doc-at-xy
9226:
9227: In order to know where to position the cursor, it is often helpful to
9228: know the size of the screen:
9229: @cindex terminal size
9230:
9231: doc-form
9232:
9233: And sometimes you want to use:
9234: @cindex clear screen
9235:
9236: doc-page
9237:
9238: Note that on non-terminals you should use @code{12 emit}, not
9239: @code{page}, to get a form feed.
9240:
1.5 anton 9241:
1.181 anton 9242: @node Single-key input, Line input and conversion, Terminal output, Other I/O
9243: @subsection Single-key input
9244: @cindex single-key input
9245: @cindex input, single-key
9246:
9247: If you want to get a single printable character, you can use
9248: @code{key}; to check whether a character is available for @code{key},
9249: you can use @code{key?}.
1.5 anton 9250:
1.181 anton 9251: doc-key
9252: doc-key?
1.27 crook 9253:
1.181 anton 9254: If you want to process a mix of printable and non-printable
9255: characters, you can do that with @code{ekey} and friends. @code{Ekey}
9256: produces a keyboard event that you have to convert into a character
9257: with @code{ekey>char} or into a key identifier with @code{ekey>fkey}.
9258:
9259: Typical code for using EKEY looks like this:
9260:
9261: @example
9262: ekey ekey>char if ( c )
9263: ... \ do something with the character
9264: else ekey>fkey if ( key-id )
9265: case
9266: k-up of ... endof
9267: k-f1 of ... endof
9268: k-left k-shift-mask or k-ctrl-mask or of ... endof
9269: ...
9270: endcase
9271: else ( keyboard-event )
9272: drop \ just ignore an unknown keyboard event type
9273: then then
9274: @end example
1.44 crook 9275:
1.45 crook 9276: doc-ekey
1.141 anton 9277: doc-ekey>char
1.181 anton 9278: doc-ekey>fkey
1.45 crook 9279: doc-ekey?
1.141 anton 9280:
1.181 anton 9281: The key identifiers for cursor keys are:
1.141 anton 9282:
9283: doc-k-left
9284: doc-k-right
1.185 anton 9285: doc-k-up
9286: doc-k-down
9287: doc-k-home
9288: doc-k-end
1.141 anton 9289: doc-k-prior
9290: doc-k-next
9291: doc-k-insert
9292: doc-k-delete
9293:
1.181 anton 9294: The key identifiers for function keys (aka keypad keys) are:
1.141 anton 9295:
1.181 anton 9296: doc-k-f1
9297: doc-k-f2
9298: doc-k-f3
9299: doc-k-f4
9300: doc-k-f5
9301: doc-k-f6
9302: doc-k-f7
9303: doc-k-f8
9304: doc-k-f9
9305: doc-k-f10
9306: doc-k-f11
9307: doc-k-f12
9308:
9309: Note that @code{k-f11} and @code{k-f12} are not as widely available.
9310:
9311: You can combine these key identifiers with masks for various shift keys:
9312:
9313: doc-k-shift-mask
9314: doc-k-ctrl-mask
9315: doc-k-alt-mask
9316:
9317: Note that, even if a Forth system has @code{ekey>fkey} and the key
9318: identifier words, the keys are not necessarily available or it may not
9319: necessarily be able to report all the keys and all the possible
9320: combinations with shift masks. Therefore, write your programs in such
9321: a way that they are still useful even if the keys and key combinations
9322: cannot be pressed or are not recognized.
9323:
9324: Examples: Older keyboards often do not have an F11 and F12 key. If
9325: you run Gforth in an xterm, the xterm catches a number of combinations
9326: (e.g., @key{Shift-Up}), and never passes it to Gforth. Finally,
9327: Gforth currently does not recognize and report combinations with
9328: multiple shift keys (so the @key{shift-ctrl-left} case in the example
9329: above would never be entered).
9330:
9331: Gforth recognizes various keys available on ANSI terminals (in MS-DOS
9332: you need the ANSI.SYS driver to get that behaviour); it works by
9333: recognizing the escape sequences that ANSI terminals send when such a
9334: key is pressed. If you have a terminal that sends other escape
9335: sequences, you will not get useful results on Gforth. Other Forth
9336: systems may work in a different way.
9337:
1.200 anton 9338: Gforth also provides a few words for outputting names of function
9339: keys:
9340:
9341: doc-fkey.
9342: doc-simple-fkey-string
9343:
1.181 anton 9344:
9345: @node Line input and conversion, Pipes, Single-key input, Other I/O
9346: @subsection Line input and conversion
9347: @cindex line input from terminal
9348: @cindex input, linewise from terminal
9349: @cindex convertin strings to numbers
9350: @cindex I/O - see input
9351:
9352: For ways of storing character strings in memory see @ref{String Formats}.
9353:
9354: @comment TODO examples for >number >float accept key key? pad parse word refill
9355: @comment then index them
1.141 anton 9356:
9357: Words for inputting one line from the keyboard:
9358:
9359: doc-accept
9360: doc-edit-line
9361:
9362: Conversion words:
9363:
1.143 anton 9364: doc-s>number?
9365: doc-s>unumber?
1.26 crook 9366: doc->number
9367: doc->float
1.143 anton 9368:
1.141 anton 9369:
1.27 crook 9370: @comment obsolescent words..
1.141 anton 9371: Obsolescent input and conversion words:
9372:
1.27 crook 9373: doc-convert
1.26 crook 9374: doc-expect
1.27 crook 9375: doc-span
1.5 anton 9376:
9377:
1.181 anton 9378: @node Pipes, Xchars and Unicode, Line input and conversion, Other I/O
1.112 anton 9379: @subsection Pipes
9380: @cindex pipes, creating your own
9381:
9382: In addition to using Gforth in pipes created by other processes
9383: (@pxref{Gforth in pipes}), you can create your own pipe with
9384: @code{open-pipe}, and read from or write to it.
9385:
9386: doc-open-pipe
9387: doc-close-pipe
9388:
9389: If you write to a pipe, Gforth can throw a @code{broken-pipe-error}; if
9390: you don't catch this exception, Gforth will catch it and exit, usually
9391: silently (@pxref{Gforth in pipes}). Since you probably do not want
9392: this, you should wrap a @code{catch} or @code{try} block around the code
9393: from @code{open-pipe} to @code{close-pipe}, so you can deal with the
9394: problem yourself, and then return to regular processing.
9395:
9396: doc-broken-pipe-error
9397:
1.155 anton 9398: @node Xchars and Unicode, , Pipes, Other I/O
9399: @subsection Xchars and Unicode
1.149 pazsan 9400:
1.188 pazsan 9401: ASCII is only appropriate for the English language. Most western
9402: languages however fit somewhat into the Forth frame, since a byte is
9403: sufficient to encode the few special characters in each (though not
9404: always the same encoding can be used; latin-1 is most widely used,
9405: though). For other languages, different char-sets have to be used,
9406: several of them variable-width. Most prominent representant is
9407: UTF-8. Let's call these extended characters xchars. The primitive
9408: fixed-size characters stored as bytes are called pchars in this
9409: section.
9410:
9411: The xchar words add a few data types:
9412:
9413: @itemize
9414:
9415: @item
9416: @var{xc} is an extended char (xchar) on the stack. It occupies one cell,
9417: and is a subset of unsigned cell. Note: UTF-8 can not store more that
9418: 31 bits; on 16 bit systems, only the UCS16 subset of the UTF-8
9419: character set can be used.
9420:
9421: @item
9422: @var{xc-addr} is the address of an xchar in memory. Alignment
9423: requirements are the same as @var{c-addr}. The memory representation of an
9424: xchar differs from the stack representation, and depends on the
9425: encoding used. An xchar may use a variable number of pchars in memory.
9426:
9427: @item
9428: @var{xc-addr} @var{u} is a buffer of xchars in memory, starting at
9429: @var{xc-addr}, @var{u} pchars long.
9430:
9431: @end itemize
9432:
9433: doc-xc-size
9434: doc-x-size
9435: doc-xc@+
9436: doc-xc!+?
9437: doc-xchar+
9438: doc-xchar-
9439: doc-+x/string
9440: doc-x\string-
9441: doc--trailing-garbage
9442: doc-x-width
9443: doc-xkey
9444: doc-xemit
9445:
9446: There's a new environment query
9447:
9448: doc-xchar-encoding
1.112 anton 9449:
1.121 anton 9450: @node OS command line arguments, Locals, Other I/O, Words
9451: @section OS command line arguments
9452: @cindex OS command line arguments
9453: @cindex command line arguments, OS
9454: @cindex arguments, OS command line
9455:
9456: The usual way to pass arguments to Gforth programs on the command line
9457: is via the @option{-e} option, e.g.
9458:
9459: @example
9460: gforth -e "123 456" foo.fs -e bye
9461: @end example
9462:
9463: However, you may want to interpret the command-line arguments directly.
9464: In that case, you can access the (image-specific) command-line arguments
1.123 anton 9465: through @code{next-arg}:
1.121 anton 9466:
1.123 anton 9467: doc-next-arg
1.121 anton 9468:
1.123 anton 9469: Here's an example program @file{echo.fs} for @code{next-arg}:
1.121 anton 9470:
9471: @example
9472: : echo ( -- )
1.122 anton 9473: begin
1.123 anton 9474: next-arg 2dup 0 0 d<> while
9475: type space
9476: repeat
9477: 2drop ;
1.121 anton 9478:
9479: echo cr bye
9480: @end example
9481:
9482: This can be invoked with
9483:
9484: @example
9485: gforth echo.fs hello world
9486: @end example
1.123 anton 9487:
9488: and it will print
9489:
9490: @example
9491: hello world
9492: @end example
9493:
9494: The next lower level of dealing with the OS command line are the
9495: following words:
9496:
9497: doc-arg
9498: doc-shift-args
9499:
9500: Finally, at the lowest level Gforth provides the following words:
9501:
9502: doc-argc
9503: doc-argv
1.121 anton 9504:
1.78 anton 9505: @c -------------------------------------------------------------
1.126 pazsan 9506: @node Locals, Structures, OS command line arguments, Words
1.78 anton 9507: @section Locals
9508: @cindex locals
9509:
9510: Local variables can make Forth programming more enjoyable and Forth
9511: programs easier to read. Unfortunately, the locals of ANS Forth are
9512: laden with restrictions. Therefore, we provide not only the ANS Forth
9513: locals wordset, but also our own, more powerful locals wordset (we
9514: implemented the ANS Forth locals wordset through our locals wordset).
1.44 crook 9515:
1.78 anton 9516: The ideas in this section have also been published in M. Anton Ertl,
9517: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl94l.ps.gz,
9518: Automatic Scoping of Local Variables}}, EuroForth '94.
1.12 anton 9519:
9520: @menu
1.78 anton 9521: * Gforth locals::
9522: * ANS Forth locals::
1.5 anton 9523: @end menu
9524:
1.78 anton 9525: @node Gforth locals, ANS Forth locals, Locals, Locals
9526: @subsection Gforth locals
9527: @cindex Gforth locals
9528: @cindex locals, Gforth style
1.5 anton 9529:
1.78 anton 9530: Locals can be defined with
1.44 crook 9531:
1.78 anton 9532: @example
9533: @{ local1 local2 ... -- comment @}
9534: @end example
9535: or
9536: @example
9537: @{ local1 local2 ... @}
9538: @end example
1.5 anton 9539:
1.78 anton 9540: E.g.,
9541: @example
9542: : max @{ n1 n2 -- n3 @}
9543: n1 n2 > if
9544: n1
9545: else
9546: n2
9547: endif ;
9548: @end example
1.44 crook 9549:
1.78 anton 9550: The similarity of locals definitions with stack comments is intended. A
9551: locals definition often replaces the stack comment of a word. The order
9552: of the locals corresponds to the order in a stack comment and everything
9553: after the @code{--} is really a comment.
1.77 anton 9554:
1.78 anton 9555: This similarity has one disadvantage: It is too easy to confuse locals
9556: declarations with stack comments, causing bugs and making them hard to
9557: find. However, this problem can be avoided by appropriate coding
9558: conventions: Do not use both notations in the same program. If you do,
9559: they should be distinguished using additional means, e.g. by position.
1.77 anton 9560:
1.78 anton 9561: @cindex types of locals
9562: @cindex locals types
9563: The name of the local may be preceded by a type specifier, e.g.,
9564: @code{F:} for a floating point value:
1.5 anton 9565:
1.78 anton 9566: @example
9567: : CX* @{ F: Ar F: Ai F: Br F: Bi -- Cr Ci @}
9568: \ complex multiplication
9569: Ar Br f* Ai Bi f* f-
9570: Ar Bi f* Ai Br f* f+ ;
9571: @end example
1.44 crook 9572:
1.78 anton 9573: @cindex flavours of locals
9574: @cindex locals flavours
9575: @cindex value-flavoured locals
9576: @cindex variable-flavoured locals
9577: Gforth currently supports cells (@code{W:}, @code{W^}), doubles
9578: (@code{D:}, @code{D^}), floats (@code{F:}, @code{F^}) and characters
9579: (@code{C:}, @code{C^}) in two flavours: a value-flavoured local (defined
9580: with @code{W:}, @code{D:} etc.) produces its value and can be changed
9581: with @code{TO}. A variable-flavoured local (defined with @code{W^} etc.)
9582: produces its address (which becomes invalid when the variable's scope is
9583: left). E.g., the standard word @code{emit} can be defined in terms of
9584: @code{type} like this:
1.5 anton 9585:
1.78 anton 9586: @example
9587: : emit @{ C^ char* -- @}
9588: char* 1 type ;
9589: @end example
1.5 anton 9590:
1.78 anton 9591: @cindex default type of locals
9592: @cindex locals, default type
9593: A local without type specifier is a @code{W:} local. Both flavours of
9594: locals are initialized with values from the data or FP stack.
1.44 crook 9595:
1.78 anton 9596: Currently there is no way to define locals with user-defined data
9597: structures, but we are working on it.
1.5 anton 9598:
1.78 anton 9599: Gforth allows defining locals everywhere in a colon definition. This
9600: poses the following questions:
1.5 anton 9601:
1.78 anton 9602: @menu
9603: * Where are locals visible by name?::
9604: * How long do locals live?::
9605: * Locals programming style::
9606: * Locals implementation::
9607: @end menu
1.44 crook 9608:
1.78 anton 9609: @node Where are locals visible by name?, How long do locals live?, Gforth locals, Gforth locals
9610: @subsubsection Where are locals visible by name?
9611: @cindex locals visibility
9612: @cindex visibility of locals
9613: @cindex scope of locals
1.5 anton 9614:
1.78 anton 9615: Basically, the answer is that locals are visible where you would expect
9616: it in block-structured languages, and sometimes a little longer. If you
9617: want to restrict the scope of a local, enclose its definition in
9618: @code{SCOPE}...@code{ENDSCOPE}.
1.5 anton 9619:
9620:
1.78 anton 9621: doc-scope
9622: doc-endscope
1.5 anton 9623:
9624:
1.78 anton 9625: These words behave like control structure words, so you can use them
9626: with @code{CS-PICK} and @code{CS-ROLL} to restrict the scope in
9627: arbitrary ways.
1.77 anton 9628:
1.78 anton 9629: If you want a more exact answer to the visibility question, here's the
9630: basic principle: A local is visible in all places that can only be
9631: reached through the definition of the local@footnote{In compiler
9632: construction terminology, all places dominated by the definition of the
9633: local.}. In other words, it is not visible in places that can be reached
9634: without going through the definition of the local. E.g., locals defined
9635: in @code{IF}...@code{ENDIF} are visible until the @code{ENDIF}, locals
9636: defined in @code{BEGIN}...@code{UNTIL} are visible after the
9637: @code{UNTIL} (until, e.g., a subsequent @code{ENDSCOPE}).
1.77 anton 9638:
1.78 anton 9639: The reasoning behind this solution is: We want to have the locals
9640: visible as long as it is meaningful. The user can always make the
9641: visibility shorter by using explicit scoping. In a place that can
9642: only be reached through the definition of a local, the meaning of a
9643: local name is clear. In other places it is not: How is the local
9644: initialized at the control flow path that does not contain the
9645: definition? Which local is meant, if the same name is defined twice in
9646: two independent control flow paths?
1.77 anton 9647:
1.78 anton 9648: This should be enough detail for nearly all users, so you can skip the
9649: rest of this section. If you really must know all the gory details and
9650: options, read on.
1.77 anton 9651:
1.78 anton 9652: In order to implement this rule, the compiler has to know which places
9653: are unreachable. It knows this automatically after @code{AHEAD},
9654: @code{AGAIN}, @code{EXIT} and @code{LEAVE}; in other cases (e.g., after
9655: most @code{THROW}s), you can use the word @code{UNREACHABLE} to tell the
9656: compiler that the control flow never reaches that place. If
9657: @code{UNREACHABLE} is not used where it could, the only consequence is
9658: that the visibility of some locals is more limited than the rule above
9659: says. If @code{UNREACHABLE} is used where it should not (i.e., if you
9660: lie to the compiler), buggy code will be produced.
1.77 anton 9661:
1.5 anton 9662:
1.78 anton 9663: doc-unreachable
1.5 anton 9664:
1.23 crook 9665:
1.78 anton 9666: Another problem with this rule is that at @code{BEGIN}, the compiler
9667: does not know which locals will be visible on the incoming
9668: back-edge. All problems discussed in the following are due to this
9669: ignorance of the compiler (we discuss the problems using @code{BEGIN}
9670: loops as examples; the discussion also applies to @code{?DO} and other
9671: loops). Perhaps the most insidious example is:
1.26 crook 9672: @example
1.78 anton 9673: AHEAD
9674: BEGIN
9675: x
9676: [ 1 CS-ROLL ] THEN
9677: @{ x @}
9678: ...
9679: UNTIL
1.26 crook 9680: @end example
1.23 crook 9681:
1.78 anton 9682: This should be legal according to the visibility rule. The use of
9683: @code{x} can only be reached through the definition; but that appears
9684: textually below the use.
9685:
9686: From this example it is clear that the visibility rules cannot be fully
9687: implemented without major headaches. Our implementation treats common
9688: cases as advertised and the exceptions are treated in a safe way: The
9689: compiler makes a reasonable guess about the locals visible after a
9690: @code{BEGIN}; if it is too pessimistic, the
9691: user will get a spurious error about the local not being defined; if the
9692: compiler is too optimistic, it will notice this later and issue a
9693: warning. In the case above the compiler would complain about @code{x}
9694: being undefined at its use. You can see from the obscure examples in
9695: this section that it takes quite unusual control structures to get the
9696: compiler into trouble, and even then it will often do fine.
1.23 crook 9697:
1.78 anton 9698: If the @code{BEGIN} is reachable from above, the most optimistic guess
9699: is that all locals visible before the @code{BEGIN} will also be
9700: visible after the @code{BEGIN}. This guess is valid for all loops that
9701: are entered only through the @code{BEGIN}, in particular, for normal
9702: @code{BEGIN}...@code{WHILE}...@code{REPEAT} and
9703: @code{BEGIN}...@code{UNTIL} loops and it is implemented in our
9704: compiler. When the branch to the @code{BEGIN} is finally generated by
9705: @code{AGAIN} or @code{UNTIL}, the compiler checks the guess and
9706: warns the user if it was too optimistic:
1.26 crook 9707: @example
1.78 anton 9708: IF
9709: @{ x @}
9710: BEGIN
9711: \ x ?
9712: [ 1 cs-roll ] THEN
9713: ...
9714: UNTIL
1.26 crook 9715: @end example
1.23 crook 9716:
1.78 anton 9717: Here, @code{x} lives only until the @code{BEGIN}, but the compiler
9718: optimistically assumes that it lives until the @code{THEN}. It notices
9719: this difference when it compiles the @code{UNTIL} and issues a
9720: warning. The user can avoid the warning, and make sure that @code{x}
9721: is not used in the wrong area by using explicit scoping:
9722: @example
9723: IF
9724: SCOPE
9725: @{ x @}
9726: ENDSCOPE
9727: BEGIN
9728: [ 1 cs-roll ] THEN
9729: ...
9730: UNTIL
9731: @end example
1.23 crook 9732:
1.78 anton 9733: Since the guess is optimistic, there will be no spurious error messages
9734: about undefined locals.
1.44 crook 9735:
1.78 anton 9736: If the @code{BEGIN} is not reachable from above (e.g., after
9737: @code{AHEAD} or @code{EXIT}), the compiler cannot even make an
9738: optimistic guess, as the locals visible after the @code{BEGIN} may be
9739: defined later. Therefore, the compiler assumes that no locals are
9740: visible after the @code{BEGIN}. However, the user can use
9741: @code{ASSUME-LIVE} to make the compiler assume that the same locals are
9742: visible at the BEGIN as at the point where the top control-flow stack
9743: item was created.
1.23 crook 9744:
1.44 crook 9745:
1.78 anton 9746: doc-assume-live
1.26 crook 9747:
1.23 crook 9748:
1.78 anton 9749: @noindent
9750: E.g.,
9751: @example
9752: @{ x @}
9753: AHEAD
9754: ASSUME-LIVE
9755: BEGIN
9756: x
9757: [ 1 CS-ROLL ] THEN
9758: ...
9759: UNTIL
9760: @end example
1.44 crook 9761:
1.78 anton 9762: Other cases where the locals are defined before the @code{BEGIN} can be
9763: handled by inserting an appropriate @code{CS-ROLL} before the
9764: @code{ASSUME-LIVE} (and changing the control-flow stack manipulation
9765: behind the @code{ASSUME-LIVE}).
1.23 crook 9766:
1.78 anton 9767: Cases where locals are defined after the @code{BEGIN} (but should be
9768: visible immediately after the @code{BEGIN}) can only be handled by
9769: rearranging the loop. E.g., the ``most insidious'' example above can be
9770: arranged into:
9771: @example
9772: BEGIN
9773: @{ x @}
9774: ... 0=
9775: WHILE
9776: x
9777: REPEAT
9778: @end example
1.44 crook 9779:
1.78 anton 9780: @node How long do locals live?, Locals programming style, Where are locals visible by name?, Gforth locals
9781: @subsubsection How long do locals live?
9782: @cindex locals lifetime
9783: @cindex lifetime of locals
1.23 crook 9784:
1.78 anton 9785: The right answer for the lifetime question would be: A local lives at
9786: least as long as it can be accessed. For a value-flavoured local this
9787: means: until the end of its visibility. However, a variable-flavoured
9788: local could be accessed through its address far beyond its visibility
9789: scope. Ultimately, this would mean that such locals would have to be
9790: garbage collected. Since this entails un-Forth-like implementation
9791: complexities, I adopted the same cowardly solution as some other
9792: languages (e.g., C): The local lives only as long as it is visible;
9793: afterwards its address is invalid (and programs that access it
9794: afterwards are erroneous).
1.23 crook 9795:
1.78 anton 9796: @node Locals programming style, Locals implementation, How long do locals live?, Gforth locals
9797: @subsubsection Locals programming style
9798: @cindex locals programming style
9799: @cindex programming style, locals
1.23 crook 9800:
1.78 anton 9801: The freedom to define locals anywhere has the potential to change
9802: programming styles dramatically. In particular, the need to use the
9803: return stack for intermediate storage vanishes. Moreover, all stack
9804: manipulations (except @code{PICK}s and @code{ROLL}s with run-time
9805: determined arguments) can be eliminated: If the stack items are in the
9806: wrong order, just write a locals definition for all of them; then
9807: write the items in the order you want.
1.23 crook 9808:
1.78 anton 9809: This seems a little far-fetched and eliminating stack manipulations is
9810: unlikely to become a conscious programming objective. Still, the number
9811: of stack manipulations will be reduced dramatically if local variables
9812: are used liberally (e.g., compare @code{max} (@pxref{Gforth locals}) with
9813: a traditional implementation of @code{max}).
1.23 crook 9814:
1.78 anton 9815: This shows one potential benefit of locals: making Forth programs more
9816: readable. Of course, this benefit will only be realized if the
9817: programmers continue to honour the principle of factoring instead of
9818: using the added latitude to make the words longer.
1.23 crook 9819:
1.78 anton 9820: @cindex single-assignment style for locals
9821: Using @code{TO} can and should be avoided. Without @code{TO},
9822: every value-flavoured local has only a single assignment and many
9823: advantages of functional languages apply to Forth. I.e., programs are
9824: easier to analyse, to optimize and to read: It is clear from the
9825: definition what the local stands for, it does not turn into something
9826: different later.
1.23 crook 9827:
1.78 anton 9828: E.g., a definition using @code{TO} might look like this:
9829: @example
9830: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9831: u1 u2 min 0
9832: ?do
9833: addr1 c@@ addr2 c@@ -
9834: ?dup-if
9835: unloop exit
9836: then
9837: addr1 char+ TO addr1
9838: addr2 char+ TO addr2
9839: loop
9840: u1 u2 - ;
1.26 crook 9841: @end example
1.78 anton 9842: Here, @code{TO} is used to update @code{addr1} and @code{addr2} at
9843: every loop iteration. @code{strcmp} is a typical example of the
9844: readability problems of using @code{TO}. When you start reading
9845: @code{strcmp}, you think that @code{addr1} refers to the start of the
9846: string. Only near the end of the loop you realize that it is something
9847: else.
1.23 crook 9848:
1.78 anton 9849: This can be avoided by defining two locals at the start of the loop that
9850: are initialized with the right value for the current iteration.
9851: @example
9852: : strcmp @{ addr1 u1 addr2 u2 -- n @}
9853: addr1 addr2
9854: u1 u2 min 0
9855: ?do @{ s1 s2 @}
9856: s1 c@@ s2 c@@ -
9857: ?dup-if
9858: unloop exit
9859: then
9860: s1 char+ s2 char+
9861: loop
9862: 2drop
9863: u1 u2 - ;
9864: @end example
9865: Here it is clear from the start that @code{s1} has a different value
9866: in every loop iteration.
1.23 crook 9867:
1.78 anton 9868: @node Locals implementation, , Locals programming style, Gforth locals
9869: @subsubsection Locals implementation
9870: @cindex locals implementation
9871: @cindex implementation of locals
1.23 crook 9872:
1.78 anton 9873: @cindex locals stack
9874: Gforth uses an extra locals stack. The most compelling reason for
9875: this is that the return stack is not float-aligned; using an extra stack
9876: also eliminates the problems and restrictions of using the return stack
9877: as locals stack. Like the other stacks, the locals stack grows toward
9878: lower addresses. A few primitives allow an efficient implementation:
9879:
9880:
9881: doc-@local#
9882: doc-f@local#
9883: doc-laddr#
9884: doc-lp+!#
9885: doc-lp!
9886: doc->l
9887: doc-f>l
9888:
9889:
9890: In addition to these primitives, some specializations of these
9891: primitives for commonly occurring inline arguments are provided for
9892: efficiency reasons, e.g., @code{@@local0} as specialization of
9893: @code{@@local#} for the inline argument 0. The following compiling words
9894: compile the right specialized version, or the general version, as
9895: appropriate:
1.23 crook 9896:
1.5 anton 9897:
1.107 dvdkhlng 9898: @c doc-compile-@local
9899: @c doc-compile-f@local
1.78 anton 9900: doc-compile-lp+!
1.5 anton 9901:
9902:
1.78 anton 9903: Combinations of conditional branches and @code{lp+!#} like
9904: @code{?branch-lp+!#} (the locals pointer is only changed if the branch
9905: is taken) are provided for efficiency and correctness in loops.
1.5 anton 9906:
1.78 anton 9907: A special area in the dictionary space is reserved for keeping the
9908: local variable names. @code{@{} switches the dictionary pointer to this
9909: area and @code{@}} switches it back and generates the locals
9910: initializing code. @code{W:} etc.@ are normal defining words. This
9911: special area is cleared at the start of every colon definition.
1.5 anton 9912:
1.78 anton 9913: @cindex word list for defining locals
9914: A special feature of Gforth's dictionary is used to implement the
9915: definition of locals without type specifiers: every word list (aka
9916: vocabulary) has its own methods for searching
9917: etc. (@pxref{Word Lists}). For the present purpose we defined a word list
9918: with a special search method: When it is searched for a word, it
9919: actually creates that word using @code{W:}. @code{@{} changes the search
9920: order to first search the word list containing @code{@}}, @code{W:} etc.,
9921: and then the word list for defining locals without type specifiers.
1.5 anton 9922:
1.78 anton 9923: The lifetime rules support a stack discipline within a colon
9924: definition: The lifetime of a local is either nested with other locals
9925: lifetimes or it does not overlap them.
1.23 crook 9926:
1.78 anton 9927: At @code{BEGIN}, @code{IF}, and @code{AHEAD} no code for locals stack
9928: pointer manipulation is generated. Between control structure words
9929: locals definitions can push locals onto the locals stack. @code{AGAIN}
9930: is the simplest of the other three control flow words. It has to
9931: restore the locals stack depth of the corresponding @code{BEGIN}
9932: before branching. The code looks like this:
9933: @format
9934: @code{lp+!#} current-locals-size @minus{} dest-locals-size
9935: @code{branch} <begin>
9936: @end format
1.26 crook 9937:
1.78 anton 9938: @code{UNTIL} is a little more complicated: If it branches back, it
9939: must adjust the stack just like @code{AGAIN}. But if it falls through,
9940: the locals stack must not be changed. The compiler generates the
9941: following code:
9942: @format
9943: @code{?branch-lp+!#} <begin> current-locals-size @minus{} dest-locals-size
9944: @end format
9945: The locals stack pointer is only adjusted if the branch is taken.
1.44 crook 9946:
1.78 anton 9947: @code{THEN} can produce somewhat inefficient code:
9948: @format
9949: @code{lp+!#} current-locals-size @minus{} orig-locals-size
9950: <orig target>:
9951: @code{lp+!#} orig-locals-size @minus{} new-locals-size
9952: @end format
9953: The second @code{lp+!#} adjusts the locals stack pointer from the
9954: level at the @i{orig} point to the level after the @code{THEN}. The
9955: first @code{lp+!#} adjusts the locals stack pointer from the current
9956: level to the level at the orig point, so the complete effect is an
9957: adjustment from the current level to the right level after the
9958: @code{THEN}.
1.26 crook 9959:
1.78 anton 9960: @cindex locals information on the control-flow stack
9961: @cindex control-flow stack items, locals information
9962: In a conventional Forth implementation a dest control-flow stack entry
9963: is just the target address and an orig entry is just the address to be
9964: patched. Our locals implementation adds a word list to every orig or dest
9965: item. It is the list of locals visible (or assumed visible) at the point
9966: described by the entry. Our implementation also adds a tag to identify
9967: the kind of entry, in particular to differentiate between live and dead
9968: (reachable and unreachable) orig entries.
1.26 crook 9969:
1.78 anton 9970: A few unusual operations have to be performed on locals word lists:
1.44 crook 9971:
1.5 anton 9972:
1.78 anton 9973: doc-common-list
9974: doc-sub-list?
9975: doc-list-size
1.52 anton 9976:
9977:
1.78 anton 9978: Several features of our locals word list implementation make these
9979: operations easy to implement: The locals word lists are organised as
9980: linked lists; the tails of these lists are shared, if the lists
9981: contain some of the same locals; and the address of a name is greater
9982: than the address of the names behind it in the list.
1.5 anton 9983:
1.78 anton 9984: Another important implementation detail is the variable
9985: @code{dead-code}. It is used by @code{BEGIN} and @code{THEN} to
9986: determine if they can be reached directly or only through the branch
9987: that they resolve. @code{dead-code} is set by @code{UNREACHABLE},
9988: @code{AHEAD}, @code{EXIT} etc., and cleared at the start of a colon
9989: definition, by @code{BEGIN} and usually by @code{THEN}.
1.5 anton 9990:
1.78 anton 9991: Counted loops are similar to other loops in most respects, but
9992: @code{LEAVE} requires special attention: It performs basically the same
9993: service as @code{AHEAD}, but it does not create a control-flow stack
9994: entry. Therefore the information has to be stored elsewhere;
9995: traditionally, the information was stored in the target fields of the
9996: branches created by the @code{LEAVE}s, by organizing these fields into a
9997: linked list. Unfortunately, this clever trick does not provide enough
9998: space for storing our extended control flow information. Therefore, we
9999: introduce another stack, the leave stack. It contains the control-flow
10000: stack entries for all unresolved @code{LEAVE}s.
1.44 crook 10001:
1.78 anton 10002: Local names are kept until the end of the colon definition, even if
10003: they are no longer visible in any control-flow path. In a few cases
10004: this may lead to increased space needs for the locals name area, but
10005: usually less than reclaiming this space would cost in code size.
1.5 anton 10006:
1.44 crook 10007:
1.78 anton 10008: @node ANS Forth locals, , Gforth locals, Locals
10009: @subsection ANS Forth locals
10010: @cindex locals, ANS Forth style
1.5 anton 10011:
1.78 anton 10012: The ANS Forth locals wordset does not define a syntax for locals, but
10013: words that make it possible to define various syntaxes. One of the
10014: possible syntaxes is a subset of the syntax we used in the Gforth locals
10015: wordset, i.e.:
1.29 crook 10016:
10017: @example
1.78 anton 10018: @{ local1 local2 ... -- comment @}
10019: @end example
10020: @noindent
10021: or
10022: @example
10023: @{ local1 local2 ... @}
1.29 crook 10024: @end example
10025:
1.78 anton 10026: The order of the locals corresponds to the order in a stack comment. The
10027: restrictions are:
1.5 anton 10028:
1.78 anton 10029: @itemize @bullet
10030: @item
10031: Locals can only be cell-sized values (no type specifiers are allowed).
10032: @item
10033: Locals can be defined only outside control structures.
10034: @item
10035: Locals can interfere with explicit usage of the return stack. For the
10036: exact (and long) rules, see the standard. If you don't use return stack
10037: accessing words in a definition using locals, you will be all right. The
10038: purpose of this rule is to make locals implementation on the return
10039: stack easier.
10040: @item
10041: The whole definition must be in one line.
10042: @end itemize
1.5 anton 10043:
1.78 anton 10044: Locals defined in ANS Forth behave like @code{VALUE}s
10045: (@pxref{Values}). I.e., they are initialized from the stack. Using their
10046: name produces their value. Their value can be changed using @code{TO}.
1.77 anton 10047:
1.78 anton 10048: Since the syntax above is supported by Gforth directly, you need not do
10049: anything to use it. If you want to port a program using this syntax to
10050: another ANS Forth system, use @file{compat/anslocal.fs} to implement the
10051: syntax on the other system.
1.5 anton 10052:
1.78 anton 10053: Note that a syntax shown in the standard, section A.13 looks
10054: similar, but is quite different in having the order of locals
10055: reversed. Beware!
1.5 anton 10056:
1.78 anton 10057: The ANS Forth locals wordset itself consists of one word:
1.5 anton 10058:
1.78 anton 10059: doc-(local)
1.5 anton 10060:
1.78 anton 10061: The ANS Forth locals extension wordset defines a syntax using
10062: @code{locals|}, but it is so awful that we strongly recommend not to use
10063: it. We have implemented this syntax to make porting to Gforth easy, but
10064: do not document it here. The problem with this syntax is that the locals
10065: are defined in an order reversed with respect to the standard stack
10066: comment notation, making programs harder to read, and easier to misread
10067: and miswrite. The only merit of this syntax is that it is easy to
10068: implement using the ANS Forth locals wordset.
1.53 anton 10069:
10070:
1.78 anton 10071: @c ----------------------------------------------------------
10072: @node Structures, Object-oriented Forth, Locals, Words
10073: @section Structures
10074: @cindex structures
10075: @cindex records
1.53 anton 10076:
1.78 anton 10077: This section presents the structure package that comes with Gforth. A
10078: version of the package implemented in ANS Forth is available in
10079: @file{compat/struct.fs}. This package was inspired by a posting on
10080: comp.lang.forth in 1989 (unfortunately I don't remember, by whom;
10081: possibly John Hayes). A version of this section has been published in
10082: M. Anton Ertl,
10083: @uref{http://www.complang.tuwien.ac.at/forth/objects/structs.html, Yet
10084: Another Forth Structures Package}, Forth Dimensions 19(3), pages
10085: 13--16. Marcel Hendrix provided helpful comments.
1.53 anton 10086:
1.78 anton 10087: @menu
10088: * Why explicit structure support?::
10089: * Structure Usage::
10090: * Structure Naming Convention::
10091: * Structure Implementation::
10092: * Structure Glossary::
1.183 anton 10093: * Forth200x Structures::
1.78 anton 10094: @end menu
1.55 anton 10095:
1.78 anton 10096: @node Why explicit structure support?, Structure Usage, Structures, Structures
10097: @subsection Why explicit structure support?
1.53 anton 10098:
1.78 anton 10099: @cindex address arithmetic for structures
10100: @cindex structures using address arithmetic
10101: If we want to use a structure containing several fields, we could simply
10102: reserve memory for it, and access the fields using address arithmetic
10103: (@pxref{Address arithmetic}). As an example, consider a structure with
10104: the following fields
1.57 anton 10105:
1.78 anton 10106: @table @code
10107: @item a
10108: is a float
10109: @item b
10110: is a cell
10111: @item c
10112: is a float
10113: @end table
1.57 anton 10114:
1.78 anton 10115: Given the (float-aligned) base address of the structure we get the
10116: address of the field
1.52 anton 10117:
1.78 anton 10118: @table @code
10119: @item a
10120: without doing anything further.
10121: @item b
10122: with @code{float+}
10123: @item c
10124: with @code{float+ cell+ faligned}
10125: @end table
1.52 anton 10126:
1.78 anton 10127: It is easy to see that this can become quite tiring.
1.52 anton 10128:
1.78 anton 10129: Moreover, it is not very readable, because seeing a
10130: @code{cell+} tells us neither which kind of structure is
10131: accessed nor what field is accessed; we have to somehow infer the kind
10132: of structure, and then look up in the documentation, which field of
10133: that structure corresponds to that offset.
1.53 anton 10134:
1.78 anton 10135: Finally, this kind of address arithmetic also causes maintenance
10136: troubles: If you add or delete a field somewhere in the middle of the
10137: structure, you have to find and change all computations for the fields
10138: afterwards.
1.52 anton 10139:
1.78 anton 10140: So, instead of using @code{cell+} and friends directly, how
10141: about storing the offsets in constants:
1.52 anton 10142:
1.78 anton 10143: @example
10144: 0 constant a-offset
10145: 0 float+ constant b-offset
10146: 0 float+ cell+ faligned c-offset
10147: @end example
1.64 pazsan 10148:
1.78 anton 10149: Now we can get the address of field @code{x} with @code{x-offset
10150: +}. This is much better in all respects. Of course, you still
10151: have to change all later offset definitions if you add a field. You can
10152: fix this by declaring the offsets in the following way:
1.57 anton 10153:
1.78 anton 10154: @example
10155: 0 constant a-offset
10156: a-offset float+ constant b-offset
10157: b-offset cell+ faligned constant c-offset
10158: @end example
1.57 anton 10159:
1.78 anton 10160: Since we always use the offsets with @code{+}, we could use a defining
10161: word @code{cfield} that includes the @code{+} in the action of the
10162: defined word:
1.64 pazsan 10163:
1.78 anton 10164: @example
10165: : cfield ( n "name" -- )
10166: create ,
10167: does> ( name execution: addr1 -- addr2 )
10168: @@ + ;
1.64 pazsan 10169:
1.78 anton 10170: 0 cfield a
10171: 0 a float+ cfield b
10172: 0 b cell+ faligned cfield c
10173: @end example
1.64 pazsan 10174:
1.78 anton 10175: Instead of @code{x-offset +}, we now simply write @code{x}.
1.64 pazsan 10176:
1.78 anton 10177: The structure field words now can be used quite nicely. However,
10178: their definition is still a bit cumbersome: We have to repeat the
10179: name, the information about size and alignment is distributed before
10180: and after the field definitions etc. The structure package presented
10181: here addresses these problems.
1.64 pazsan 10182:
1.78 anton 10183: @node Structure Usage, Structure Naming Convention, Why explicit structure support?, Structures
10184: @subsection Structure Usage
10185: @cindex structure usage
1.57 anton 10186:
1.78 anton 10187: @cindex @code{field} usage
10188: @cindex @code{struct} usage
10189: @cindex @code{end-struct} usage
10190: You can define a structure for a (data-less) linked list with:
1.57 anton 10191: @example
1.78 anton 10192: struct
10193: cell% field list-next
10194: end-struct list%
1.57 anton 10195: @end example
10196:
1.78 anton 10197: With the address of the list node on the stack, you can compute the
10198: address of the field that contains the address of the next node with
10199: @code{list-next}. E.g., you can determine the length of a list
10200: with:
1.57 anton 10201:
10202: @example
1.78 anton 10203: : list-length ( list -- n )
10204: \ "list" is a pointer to the first element of a linked list
10205: \ "n" is the length of the list
10206: 0 BEGIN ( list1 n1 )
10207: over
10208: WHILE ( list1 n1 )
10209: 1+ swap list-next @@ swap
10210: REPEAT
10211: nip ;
1.57 anton 10212: @end example
10213:
1.78 anton 10214: You can reserve memory for a list node in the dictionary with
10215: @code{list% %allot}, which leaves the address of the list node on the
10216: stack. For the equivalent allocation on the heap you can use @code{list%
10217: %alloc} (or, for an @code{allocate}-like stack effect (i.e., with ior),
10218: use @code{list% %allocate}). You can get the the size of a list
10219: node with @code{list% %size} and its alignment with @code{list%
10220: %alignment}.
10221:
10222: Note that in ANS Forth the body of a @code{create}d word is
10223: @code{aligned} but not necessarily @code{faligned};
10224: therefore, if you do a:
1.57 anton 10225:
10226: @example
1.78 anton 10227: create @emph{name} foo% %allot drop
1.57 anton 10228: @end example
10229:
1.78 anton 10230: @noindent
10231: then the memory alloted for @code{foo%} is guaranteed to start at the
10232: body of @code{@emph{name}} only if @code{foo%} contains only character,
10233: cell and double fields. Therefore, if your structure contains floats,
10234: better use
1.57 anton 10235:
10236: @example
1.78 anton 10237: foo% %allot constant @emph{name}
1.57 anton 10238: @end example
10239:
1.78 anton 10240: @cindex structures containing structures
10241: You can include a structure @code{foo%} as a field of
10242: another structure, like this:
1.65 anton 10243: @example
1.78 anton 10244: struct
10245: ...
10246: foo% field ...
10247: ...
10248: end-struct ...
1.65 anton 10249: @end example
1.52 anton 10250:
1.78 anton 10251: @cindex structure extension
10252: @cindex extended records
10253: Instead of starting with an empty structure, you can extend an
10254: existing structure. E.g., a plain linked list without data, as defined
10255: above, is hardly useful; You can extend it to a linked list of integers,
10256: like this:@footnote{This feature is also known as @emph{extended
10257: records}. It is the main innovation in the Oberon language; in other
10258: words, adding this feature to Modula-2 led Wirth to create a new
10259: language, write a new compiler etc. Adding this feature to Forth just
10260: required a few lines of code.}
1.52 anton 10261:
1.78 anton 10262: @example
10263: list%
10264: cell% field intlist-int
10265: end-struct intlist%
10266: @end example
1.55 anton 10267:
1.78 anton 10268: @code{intlist%} is a structure with two fields:
10269: @code{list-next} and @code{intlist-int}.
1.55 anton 10270:
1.78 anton 10271: @cindex structures containing arrays
10272: You can specify an array type containing @emph{n} elements of
10273: type @code{foo%} like this:
1.55 anton 10274:
10275: @example
1.78 anton 10276: foo% @emph{n} *
1.56 anton 10277: @end example
1.55 anton 10278:
1.78 anton 10279: You can use this array type in any place where you can use a normal
10280: type, e.g., when defining a @code{field}, or with
10281: @code{%allot}.
10282:
10283: @cindex first field optimization
10284: The first field is at the base address of a structure and the word for
10285: this field (e.g., @code{list-next}) actually does not change the address
10286: on the stack. You may be tempted to leave it away in the interest of
10287: run-time and space efficiency. This is not necessary, because the
10288: structure package optimizes this case: If you compile a first-field
10289: words, no code is generated. So, in the interest of readability and
10290: maintainability you should include the word for the field when accessing
10291: the field.
1.52 anton 10292:
10293:
1.78 anton 10294: @node Structure Naming Convention, Structure Implementation, Structure Usage, Structures
10295: @subsection Structure Naming Convention
10296: @cindex structure naming convention
1.52 anton 10297:
1.78 anton 10298: The field names that come to (my) mind are often quite generic, and,
10299: if used, would cause frequent name clashes. E.g., many structures
10300: probably contain a @code{counter} field. The structure names
10301: that come to (my) mind are often also the logical choice for the names
10302: of words that create such a structure.
1.52 anton 10303:
1.78 anton 10304: Therefore, I have adopted the following naming conventions:
1.52 anton 10305:
1.78 anton 10306: @itemize @bullet
10307: @cindex field naming convention
10308: @item
10309: The names of fields are of the form
10310: @code{@emph{struct}-@emph{field}}, where
10311: @code{@emph{struct}} is the basic name of the structure, and
10312: @code{@emph{field}} is the basic name of the field. You can
10313: think of field words as converting the (address of the)
10314: structure into the (address of the) field.
1.52 anton 10315:
1.78 anton 10316: @cindex structure naming convention
10317: @item
10318: The names of structures are of the form
10319: @code{@emph{struct}%}, where
10320: @code{@emph{struct}} is the basic name of the structure.
10321: @end itemize
1.52 anton 10322:
1.78 anton 10323: This naming convention does not work that well for fields of extended
10324: structures; e.g., the integer list structure has a field
10325: @code{intlist-int}, but has @code{list-next}, not
10326: @code{intlist-next}.
1.53 anton 10327:
1.78 anton 10328: @node Structure Implementation, Structure Glossary, Structure Naming Convention, Structures
10329: @subsection Structure Implementation
10330: @cindex structure implementation
10331: @cindex implementation of structures
1.52 anton 10332:
1.78 anton 10333: The central idea in the implementation is to pass the data about the
10334: structure being built on the stack, not in some global
10335: variable. Everything else falls into place naturally once this design
10336: decision is made.
1.53 anton 10337:
1.78 anton 10338: The type description on the stack is of the form @emph{align
10339: size}. Keeping the size on the top-of-stack makes dealing with arrays
10340: very simple.
1.53 anton 10341:
1.78 anton 10342: @code{field} is a defining word that uses @code{Create}
10343: and @code{DOES>}. The body of the field contains the offset
10344: of the field, and the normal @code{DOES>} action is simply:
1.53 anton 10345:
10346: @example
1.78 anton 10347: @@ +
1.53 anton 10348: @end example
10349:
1.78 anton 10350: @noindent
10351: i.e., add the offset to the address, giving the stack effect
10352: @i{addr1 -- addr2} for a field.
10353:
10354: @cindex first field optimization, implementation
10355: This simple structure is slightly complicated by the optimization
10356: for fields with offset 0, which requires a different
10357: @code{DOES>}-part (because we cannot rely on there being
10358: something on the stack if such a field is invoked during
10359: compilation). Therefore, we put the different @code{DOES>}-parts
10360: in separate words, and decide which one to invoke based on the
10361: offset. For a zero offset, the field is basically a noop; it is
10362: immediate, and therefore no code is generated when it is compiled.
1.53 anton 10363:
1.183 anton 10364: @node Structure Glossary, Forth200x Structures, Structure Implementation, Structures
1.78 anton 10365: @subsection Structure Glossary
10366: @cindex structure glossary
1.53 anton 10367:
1.5 anton 10368:
1.78 anton 10369: doc-%align
10370: doc-%alignment
10371: doc-%alloc
10372: doc-%allocate
10373: doc-%allot
10374: doc-cell%
10375: doc-char%
10376: doc-dfloat%
10377: doc-double%
10378: doc-end-struct
10379: doc-field
10380: doc-float%
10381: doc-naligned
10382: doc-sfloat%
10383: doc-%size
10384: doc-struct
1.54 anton 10385:
10386:
1.183 anton 10387: @node Forth200x Structures, , Structure Glossary, Structures
10388: @subsection Forth200x Structures
10389: @cindex Structures in Forth200x
10390:
10391: The Forth 200x standard defines a slightly less convenient form of
10392: structures. In general (when using @code{field+}, you have to perform
10393: the alignment yourself, but there are a number of convenience words
10394: (e.g., @code{field:} that perform the alignment for you.
10395:
10396: A typical usage example is:
10397:
10398: @example
10399: 0
10400: field: s-a
10401: faligned 2 floats +field s-b
10402: constant s-struct
10403: @end example
10404:
10405: An alternative way of writing this structure is:
10406:
10407: @example
10408: begin-structure s-struct
10409: field: s-a
10410: faligned 2 floats +field s-b
10411: end-structure
10412: @end example
10413:
10414: doc-begin-structure
10415: doc-end-structure
10416: doc-+field
10417: doc-cfield:
10418: doc-field:
10419: doc-2field:
10420: doc-ffield:
10421: doc-sffield:
10422: doc-dffield:
10423:
1.26 crook 10424: @c -------------------------------------------------------------
1.78 anton 10425: @node Object-oriented Forth, Programming Tools, Structures, Words
10426: @section Object-oriented Forth
10427:
10428: Gforth comes with three packages for object-oriented programming:
10429: @file{objects.fs}, @file{oof.fs}, and @file{mini-oof.fs}; none of them
10430: is preloaded, so you have to @code{include} them before use. The most
10431: important differences between these packages (and others) are discussed
10432: in @ref{Comparison with other object models}. All packages are written
10433: in ANS Forth and can be used with any other ANS Forth.
1.5 anton 10434:
1.78 anton 10435: @menu
10436: * Why object-oriented programming?::
10437: * Object-Oriented Terminology::
10438: * Objects::
10439: * OOF::
10440: * Mini-OOF::
10441: * Comparison with other object models::
10442: @end menu
1.5 anton 10443:
1.78 anton 10444: @c ----------------------------------------------------------------
10445: @node Why object-oriented programming?, Object-Oriented Terminology, Object-oriented Forth, Object-oriented Forth
10446: @subsection Why object-oriented programming?
10447: @cindex object-oriented programming motivation
10448: @cindex motivation for object-oriented programming
1.44 crook 10449:
1.78 anton 10450: Often we have to deal with several data structures (@emph{objects}),
10451: that have to be treated similarly in some respects, but differently in
10452: others. Graphical objects are the textbook example: circles, triangles,
10453: dinosaurs, icons, and others, and we may want to add more during program
10454: development. We want to apply some operations to any graphical object,
10455: e.g., @code{draw} for displaying it on the screen. However, @code{draw}
10456: has to do something different for every kind of object.
10457: @comment TODO add some other operations eg perimeter, area
10458: @comment and tie in to concrete examples later..
1.5 anton 10459:
1.78 anton 10460: We could implement @code{draw} as a big @code{CASE}
10461: control structure that executes the appropriate code depending on the
10462: kind of object to be drawn. This would be not be very elegant, and,
10463: moreover, we would have to change @code{draw} every time we add
10464: a new kind of graphical object (say, a spaceship).
1.44 crook 10465:
1.78 anton 10466: What we would rather do is: When defining spaceships, we would tell
10467: the system: ``Here's how you @code{draw} a spaceship; you figure
10468: out the rest''.
1.5 anton 10469:
1.78 anton 10470: This is the problem that all systems solve that (rightfully) call
10471: themselves object-oriented; the object-oriented packages presented here
10472: solve this problem (and not much else).
10473: @comment TODO ?list properties of oo systems.. oo vs o-based?
1.44 crook 10474:
1.78 anton 10475: @c ------------------------------------------------------------------------
10476: @node Object-Oriented Terminology, Objects, Why object-oriented programming?, Object-oriented Forth
10477: @subsection Object-Oriented Terminology
10478: @cindex object-oriented terminology
10479: @cindex terminology for object-oriented programming
1.5 anton 10480:
1.78 anton 10481: This section is mainly for reference, so you don't have to understand
10482: all of it right away. The terminology is mainly Smalltalk-inspired. In
10483: short:
1.44 crook 10484:
1.78 anton 10485: @table @emph
10486: @cindex class
10487: @item class
10488: a data structure definition with some extras.
1.5 anton 10489:
1.78 anton 10490: @cindex object
10491: @item object
10492: an instance of the data structure described by the class definition.
1.5 anton 10493:
1.78 anton 10494: @cindex instance variables
10495: @item instance variables
10496: fields of the data structure.
1.5 anton 10497:
1.78 anton 10498: @cindex selector
10499: @cindex method selector
10500: @cindex virtual function
10501: @item selector
10502: (or @emph{method selector}) a word (e.g.,
10503: @code{draw}) that performs an operation on a variety of data
10504: structures (classes). A selector describes @emph{what} operation to
10505: perform. In C++ terminology: a (pure) virtual function.
1.5 anton 10506:
1.78 anton 10507: @cindex method
10508: @item method
10509: the concrete definition that performs the operation
10510: described by the selector for a specific class. A method specifies
10511: @emph{how} the operation is performed for a specific class.
1.5 anton 10512:
1.78 anton 10513: @cindex selector invocation
10514: @cindex message send
10515: @cindex invoking a selector
10516: @item selector invocation
10517: a call of a selector. One argument of the call (the TOS (top-of-stack))
10518: is used for determining which method is used. In Smalltalk terminology:
10519: a message (consisting of the selector and the other arguments) is sent
10520: to the object.
1.5 anton 10521:
1.78 anton 10522: @cindex receiving object
10523: @item receiving object
10524: the object used for determining the method executed by a selector
10525: invocation. In the @file{objects.fs} model, it is the object that is on
10526: the TOS when the selector is invoked. (@emph{Receiving} comes from
10527: the Smalltalk @emph{message} terminology.)
1.5 anton 10528:
1.78 anton 10529: @cindex child class
10530: @cindex parent class
10531: @cindex inheritance
10532: @item child class
10533: a class that has (@emph{inherits}) all properties (instance variables,
10534: selectors, methods) from a @emph{parent class}. In Smalltalk
10535: terminology: The subclass inherits from the superclass. In C++
10536: terminology: The derived class inherits from the base class.
1.5 anton 10537:
1.78 anton 10538: @end table
1.5 anton 10539:
1.78 anton 10540: @c If you wonder about the message sending terminology, it comes from
10541: @c a time when each object had it's own task and objects communicated via
10542: @c message passing; eventually the Smalltalk developers realized that
10543: @c they can do most things through simple (indirect) calls. They kept the
10544: @c terminology.
1.5 anton 10545:
1.78 anton 10546: @c --------------------------------------------------------------
10547: @node Objects, OOF, Object-Oriented Terminology, Object-oriented Forth
10548: @subsection The @file{objects.fs} model
10549: @cindex objects
10550: @cindex object-oriented programming
1.26 crook 10551:
1.78 anton 10552: @cindex @file{objects.fs}
10553: @cindex @file{oof.fs}
1.26 crook 10554:
1.78 anton 10555: This section describes the @file{objects.fs} package. This material also
10556: has been published in M. Anton Ertl,
10557: @cite{@uref{http://www.complang.tuwien.ac.at/forth/objects/objects.html,
10558: Yet Another Forth Objects Package}}, Forth Dimensions 19(2), pages
10559: 37--43.
10560: @c McKewan's and Zsoter's packages
1.26 crook 10561:
1.78 anton 10562: This section assumes that you have read @ref{Structures}.
1.5 anton 10563:
1.78 anton 10564: The techniques on which this model is based have been used to implement
10565: the parser generator, Gray, and have also been used in Gforth for
10566: implementing the various flavours of word lists (hashed or not,
10567: case-sensitive or not, special-purpose word lists for locals etc.).
1.5 anton 10568:
10569:
1.26 crook 10570: @menu
1.78 anton 10571: * Properties of the Objects model::
10572: * Basic Objects Usage::
10573: * The Objects base class::
10574: * Creating objects::
10575: * Object-Oriented Programming Style::
10576: * Class Binding::
10577: * Method conveniences::
10578: * Classes and Scoping::
10579: * Dividing classes::
10580: * Object Interfaces::
10581: * Objects Implementation::
10582: * Objects Glossary::
1.26 crook 10583: @end menu
1.5 anton 10584:
1.78 anton 10585: Marcel Hendrix provided helpful comments on this section.
1.5 anton 10586:
1.78 anton 10587: @node Properties of the Objects model, Basic Objects Usage, Objects, Objects
10588: @subsubsection Properties of the @file{objects.fs} model
10589: @cindex @file{objects.fs} properties
1.5 anton 10590:
1.78 anton 10591: @itemize @bullet
10592: @item
10593: It is straightforward to pass objects on the stack. Passing
10594: selectors on the stack is a little less convenient, but possible.
1.44 crook 10595:
1.78 anton 10596: @item
10597: Objects are just data structures in memory, and are referenced by their
10598: address. You can create words for objects with normal defining words
10599: like @code{constant}. Likewise, there is no difference between instance
10600: variables that contain objects and those that contain other data.
1.5 anton 10601:
1.78 anton 10602: @item
10603: Late binding is efficient and easy to use.
1.44 crook 10604:
1.78 anton 10605: @item
10606: It avoids parsing, and thus avoids problems with state-smartness
10607: and reduced extensibility; for convenience there are a few parsing
10608: words, but they have non-parsing counterparts. There are also a few
10609: defining words that parse. This is hard to avoid, because all standard
10610: defining words parse (except @code{:noname}); however, such
10611: words are not as bad as many other parsing words, because they are not
10612: state-smart.
1.5 anton 10613:
1.78 anton 10614: @item
10615: It does not try to incorporate everything. It does a few things and does
10616: them well (IMO). In particular, this model was not designed to support
10617: information hiding (although it has features that may help); you can use
10618: a separate package for achieving this.
1.5 anton 10619:
1.78 anton 10620: @item
10621: It is layered; you don't have to learn and use all features to use this
10622: model. Only a few features are necessary (@pxref{Basic Objects Usage},
10623: @pxref{The Objects base class}, @pxref{Creating objects}.), the others
10624: are optional and independent of each other.
1.5 anton 10625:
1.78 anton 10626: @item
10627: An implementation in ANS Forth is available.
1.5 anton 10628:
1.78 anton 10629: @end itemize
1.5 anton 10630:
1.44 crook 10631:
1.78 anton 10632: @node Basic Objects Usage, The Objects base class, Properties of the Objects model, Objects
10633: @subsubsection Basic @file{objects.fs} Usage
10634: @cindex basic objects usage
10635: @cindex objects, basic usage
1.5 anton 10636:
1.78 anton 10637: You can define a class for graphical objects like this:
1.44 crook 10638:
1.78 anton 10639: @cindex @code{class} usage
10640: @cindex @code{end-class} usage
10641: @cindex @code{selector} usage
1.5 anton 10642: @example
1.78 anton 10643: object class \ "object" is the parent class
10644: selector draw ( x y graphical -- )
10645: end-class graphical
10646: @end example
10647:
10648: This code defines a class @code{graphical} with an
10649: operation @code{draw}. We can perform the operation
10650: @code{draw} on any @code{graphical} object, e.g.:
10651:
10652: @example
10653: 100 100 t-rex draw
1.26 crook 10654: @end example
1.5 anton 10655:
1.78 anton 10656: @noindent
10657: where @code{t-rex} is a word (say, a constant) that produces a
10658: graphical object.
10659:
10660: @comment TODO add a 2nd operation eg perimeter.. and use for
10661: @comment a concrete example
1.5 anton 10662:
1.78 anton 10663: @cindex abstract class
10664: How do we create a graphical object? With the present definitions,
10665: we cannot create a useful graphical object. The class
10666: @code{graphical} describes graphical objects in general, but not
10667: any concrete graphical object type (C++ users would call it an
10668: @emph{abstract class}); e.g., there is no method for the selector
10669: @code{draw} in the class @code{graphical}.
1.5 anton 10670:
1.78 anton 10671: For concrete graphical objects, we define child classes of the
10672: class @code{graphical}, e.g.:
1.5 anton 10673:
1.78 anton 10674: @cindex @code{overrides} usage
10675: @cindex @code{field} usage in class definition
1.26 crook 10676: @example
1.78 anton 10677: graphical class \ "graphical" is the parent class
10678: cell% field circle-radius
1.5 anton 10679:
1.78 anton 10680: :noname ( x y circle -- )
10681: circle-radius @@ draw-circle ;
10682: overrides draw
1.5 anton 10683:
1.78 anton 10684: :noname ( n-radius circle -- )
10685: circle-radius ! ;
10686: overrides construct
1.5 anton 10687:
1.78 anton 10688: end-class circle
10689: @end example
1.44 crook 10690:
1.78 anton 10691: Here we define a class @code{circle} as a child of @code{graphical},
10692: with field @code{circle-radius} (which behaves just like a field
10693: (@pxref{Structures}); it defines (using @code{overrides}) new methods
10694: for the selectors @code{draw} and @code{construct} (@code{construct} is
10695: defined in @code{object}, the parent class of @code{graphical}).
1.5 anton 10696:
1.78 anton 10697: Now we can create a circle on the heap (i.e.,
10698: @code{allocate}d memory) with:
1.44 crook 10699:
1.78 anton 10700: @cindex @code{heap-new} usage
1.5 anton 10701: @example
1.78 anton 10702: 50 circle heap-new constant my-circle
1.5 anton 10703: @end example
10704:
1.78 anton 10705: @noindent
10706: @code{heap-new} invokes @code{construct}, thus
10707: initializing the field @code{circle-radius} with 50. We can draw
10708: this new circle at (100,100) with:
1.5 anton 10709:
10710: @example
1.78 anton 10711: 100 100 my-circle draw
1.5 anton 10712: @end example
10713:
1.78 anton 10714: @cindex selector invocation, restrictions
10715: @cindex class definition, restrictions
10716: Note: You can only invoke a selector if the object on the TOS
10717: (the receiving object) belongs to the class where the selector was
10718: defined or one of its descendents; e.g., you can invoke
10719: @code{draw} only for objects belonging to @code{graphical}
10720: or its descendents (e.g., @code{circle}). Immediately before
10721: @code{end-class}, the search order has to be the same as
10722: immediately after @code{class}.
10723:
10724: @node The Objects base class, Creating objects, Basic Objects Usage, Objects
10725: @subsubsection The @file{object.fs} base class
10726: @cindex @code{object} class
10727:
10728: When you define a class, you have to specify a parent class. So how do
10729: you start defining classes? There is one class available from the start:
10730: @code{object}. It is ancestor for all classes and so is the
10731: only class that has no parent. It has two selectors: @code{construct}
10732: and @code{print}.
10733:
10734: @node Creating objects, Object-Oriented Programming Style, The Objects base class, Objects
10735: @subsubsection Creating objects
10736: @cindex creating objects
10737: @cindex object creation
10738: @cindex object allocation options
10739:
10740: @cindex @code{heap-new} discussion
10741: @cindex @code{dict-new} discussion
10742: @cindex @code{construct} discussion
10743: You can create and initialize an object of a class on the heap with
10744: @code{heap-new} ( ... class -- object ) and in the dictionary
10745: (allocation with @code{allot}) with @code{dict-new} (
10746: ... class -- object ). Both words invoke @code{construct}, which
10747: consumes the stack items indicated by "..." above.
10748:
10749: @cindex @code{init-object} discussion
10750: @cindex @code{class-inst-size} discussion
10751: If you want to allocate memory for an object yourself, you can get its
10752: alignment and size with @code{class-inst-size 2@@} ( class --
10753: align size ). Once you have memory for an object, you can initialize
10754: it with @code{init-object} ( ... class object -- );
10755: @code{construct} does only a part of the necessary work.
10756:
10757: @node Object-Oriented Programming Style, Class Binding, Creating objects, Objects
10758: @subsubsection Object-Oriented Programming Style
10759: @cindex object-oriented programming style
10760: @cindex programming style, object-oriented
1.5 anton 10761:
1.78 anton 10762: This section is not exhaustive.
1.5 anton 10763:
1.78 anton 10764: @cindex stack effects of selectors
10765: @cindex selectors and stack effects
10766: In general, it is a good idea to ensure that all methods for the
10767: same selector have the same stack effect: when you invoke a selector,
10768: you often have no idea which method will be invoked, so, unless all
10769: methods have the same stack effect, you will not know the stack effect
10770: of the selector invocation.
1.5 anton 10771:
1.78 anton 10772: One exception to this rule is methods for the selector
10773: @code{construct}. We know which method is invoked, because we
10774: specify the class to be constructed at the same place. Actually, I
10775: defined @code{construct} as a selector only to give the users a
10776: convenient way to specify initialization. The way it is used, a
10777: mechanism different from selector invocation would be more natural
10778: (but probably would take more code and more space to explain).
1.5 anton 10779:
1.78 anton 10780: @node Class Binding, Method conveniences, Object-Oriented Programming Style, Objects
10781: @subsubsection Class Binding
10782: @cindex class binding
10783: @cindex early binding
1.5 anton 10784:
1.78 anton 10785: @cindex late binding
10786: Normal selector invocations determine the method at run-time depending
10787: on the class of the receiving object. This run-time selection is called
10788: @i{late binding}.
1.5 anton 10789:
1.78 anton 10790: Sometimes it's preferable to invoke a different method. For example,
10791: you might want to use the simple method for @code{print}ing
10792: @code{object}s instead of the possibly long-winded @code{print} method
10793: of the receiver class. You can achieve this by replacing the invocation
10794: of @code{print} with:
1.5 anton 10795:
1.78 anton 10796: @cindex @code{[bind]} usage
1.5 anton 10797: @example
1.78 anton 10798: [bind] object print
1.5 anton 10799: @end example
10800:
1.78 anton 10801: @noindent
10802: in compiled code or:
10803:
10804: @cindex @code{bind} usage
1.5 anton 10805: @example
1.78 anton 10806: bind object print
1.5 anton 10807: @end example
10808:
1.78 anton 10809: @cindex class binding, alternative to
10810: @noindent
10811: in interpreted code. Alternatively, you can define the method with a
10812: name (e.g., @code{print-object}), and then invoke it through the
10813: name. Class binding is just a (often more convenient) way to achieve
10814: the same effect; it avoids name clutter and allows you to invoke
10815: methods directly without naming them first.
1.5 anton 10816:
1.78 anton 10817: @cindex superclass binding
10818: @cindex parent class binding
10819: A frequent use of class binding is this: When we define a method
10820: for a selector, we often want the method to do what the selector does
10821: in the parent class, and a little more. There is a special word for
10822: this purpose: @code{[parent]}; @code{[parent]
10823: @emph{selector}} is equivalent to @code{[bind] @emph{parent
10824: selector}}, where @code{@emph{parent}} is the parent
10825: class of the current class. E.g., a method definition might look like:
1.44 crook 10826:
1.78 anton 10827: @cindex @code{[parent]} usage
10828: @example
10829: :noname
10830: dup [parent] foo \ do parent's foo on the receiving object
10831: ... \ do some more
10832: ; overrides foo
10833: @end example
1.6 pazsan 10834:
1.78 anton 10835: @cindex class binding as optimization
10836: In @cite{Object-oriented programming in ANS Forth} (Forth Dimensions,
10837: March 1997), Andrew McKewan presents class binding as an optimization
10838: technique. I recommend not using it for this purpose unless you are in
10839: an emergency. Late binding is pretty fast with this model anyway, so the
10840: benefit of using class binding is small; the cost of using class binding
10841: where it is not appropriate is reduced maintainability.
1.44 crook 10842:
1.78 anton 10843: While we are at programming style questions: You should bind
10844: selectors only to ancestor classes of the receiving object. E.g., say,
10845: you know that the receiving object is of class @code{foo} or its
10846: descendents; then you should bind only to @code{foo} and its
10847: ancestors.
1.12 anton 10848:
1.78 anton 10849: @node Method conveniences, Classes and Scoping, Class Binding, Objects
10850: @subsubsection Method conveniences
10851: @cindex method conveniences
1.44 crook 10852:
1.78 anton 10853: In a method you usually access the receiving object pretty often. If
10854: you define the method as a plain colon definition (e.g., with
10855: @code{:noname}), you may have to do a lot of stack
10856: gymnastics. To avoid this, you can define the method with @code{m:
10857: ... ;m}. E.g., you could define the method for
10858: @code{draw}ing a @code{circle} with
1.6 pazsan 10859:
1.78 anton 10860: @cindex @code{this} usage
10861: @cindex @code{m:} usage
10862: @cindex @code{;m} usage
10863: @example
10864: m: ( x y circle -- )
10865: ( x y ) this circle-radius @@ draw-circle ;m
10866: @end example
1.6 pazsan 10867:
1.78 anton 10868: @cindex @code{exit} in @code{m: ... ;m}
10869: @cindex @code{exitm} discussion
10870: @cindex @code{catch} in @code{m: ... ;m}
10871: When this method is executed, the receiver object is removed from the
10872: stack; you can access it with @code{this} (admittedly, in this
10873: example the use of @code{m: ... ;m} offers no advantage). Note
10874: that I specify the stack effect for the whole method (i.e. including
10875: the receiver object), not just for the code between @code{m:}
10876: and @code{;m}. You cannot use @code{exit} in
10877: @code{m:...;m}; instead, use
10878: @code{exitm}.@footnote{Moreover, for any word that calls
10879: @code{catch} and was defined before loading
10880: @code{objects.fs}, you have to redefine it like I redefined
10881: @code{catch}: @code{: catch this >r catch r> to-this ;}}
1.12 anton 10882:
1.78 anton 10883: @cindex @code{inst-var} usage
10884: You will frequently use sequences of the form @code{this
10885: @emph{field}} (in the example above: @code{this
10886: circle-radius}). If you use the field only in this way, you can
10887: define it with @code{inst-var} and eliminate the
10888: @code{this} before the field name. E.g., the @code{circle}
10889: class above could also be defined with:
1.6 pazsan 10890:
1.78 anton 10891: @example
10892: graphical class
10893: cell% inst-var radius
1.6 pazsan 10894:
1.78 anton 10895: m: ( x y circle -- )
10896: radius @@ draw-circle ;m
10897: overrides draw
1.6 pazsan 10898:
1.78 anton 10899: m: ( n-radius circle -- )
10900: radius ! ;m
10901: overrides construct
1.6 pazsan 10902:
1.78 anton 10903: end-class circle
10904: @end example
1.6 pazsan 10905:
1.78 anton 10906: @code{radius} can only be used in @code{circle} and its
10907: descendent classes and inside @code{m:...;m}.
1.6 pazsan 10908:
1.78 anton 10909: @cindex @code{inst-value} usage
10910: You can also define fields with @code{inst-value}, which is
10911: to @code{inst-var} what @code{value} is to
10912: @code{variable}. You can change the value of such a field with
10913: @code{[to-inst]}. E.g., we could also define the class
10914: @code{circle} like this:
1.44 crook 10915:
1.78 anton 10916: @example
10917: graphical class
10918: inst-value radius
1.6 pazsan 10919:
1.78 anton 10920: m: ( x y circle -- )
10921: radius draw-circle ;m
10922: overrides draw
1.44 crook 10923:
1.78 anton 10924: m: ( n-radius circle -- )
10925: [to-inst] radius ;m
10926: overrides construct
1.6 pazsan 10927:
1.78 anton 10928: end-class circle
10929: @end example
1.6 pazsan 10930:
1.78 anton 10931: @c !! :m is easy to confuse with m:. Another name would be better.
1.6 pazsan 10932:
1.78 anton 10933: @c Finally, you can define named methods with @code{:m}. One use of this
10934: @c feature is the definition of words that occur only in one class and are
10935: @c not intended to be overridden, but which still need method context
10936: @c (e.g., for accessing @code{inst-var}s). Another use is for methods that
10937: @c would be bound frequently, if defined anonymously.
1.6 pazsan 10938:
10939:
1.78 anton 10940: @node Classes and Scoping, Dividing classes, Method conveniences, Objects
10941: @subsubsection Classes and Scoping
10942: @cindex classes and scoping
10943: @cindex scoping and classes
1.6 pazsan 10944:
1.78 anton 10945: Inheritance is frequent, unlike structure extension. This exacerbates
10946: the problem with the field name convention (@pxref{Structure Naming
10947: Convention}): One always has to remember in which class the field was
10948: originally defined; changing a part of the class structure would require
10949: changes for renaming in otherwise unaffected code.
1.6 pazsan 10950:
1.78 anton 10951: @cindex @code{inst-var} visibility
10952: @cindex @code{inst-value} visibility
10953: To solve this problem, I added a scoping mechanism (which was not in my
10954: original charter): A field defined with @code{inst-var} (or
10955: @code{inst-value}) is visible only in the class where it is defined and in
10956: the descendent classes of this class. Using such fields only makes
10957: sense in @code{m:}-defined methods in these classes anyway.
1.6 pazsan 10958:
1.78 anton 10959: This scoping mechanism allows us to use the unadorned field name,
10960: because name clashes with unrelated words become much less likely.
1.6 pazsan 10961:
1.78 anton 10962: @cindex @code{protected} discussion
10963: @cindex @code{private} discussion
10964: Once we have this mechanism, we can also use it for controlling the
10965: visibility of other words: All words defined after
10966: @code{protected} are visible only in the current class and its
10967: descendents. @code{public} restores the compilation
10968: (i.e. @code{current}) word list that was in effect before. If you
10969: have several @code{protected}s without an intervening
10970: @code{public} or @code{set-current}, @code{public}
10971: will restore the compilation word list in effect before the first of
10972: these @code{protected}s.
1.6 pazsan 10973:
1.78 anton 10974: @node Dividing classes, Object Interfaces, Classes and Scoping, Objects
10975: @subsubsection Dividing classes
10976: @cindex Dividing classes
10977: @cindex @code{methods}...@code{end-methods}
1.6 pazsan 10978:
1.78 anton 10979: You may want to do the definition of methods separate from the
10980: definition of the class, its selectors, fields, and instance variables,
10981: i.e., separate the implementation from the definition. You can do this
10982: in the following way:
1.6 pazsan 10983:
1.78 anton 10984: @example
10985: graphical class
10986: inst-value radius
10987: end-class circle
1.6 pazsan 10988:
1.78 anton 10989: ... \ do some other stuff
1.6 pazsan 10990:
1.78 anton 10991: circle methods \ now we are ready
1.44 crook 10992:
1.78 anton 10993: m: ( x y circle -- )
10994: radius draw-circle ;m
10995: overrides draw
1.6 pazsan 10996:
1.78 anton 10997: m: ( n-radius circle -- )
10998: [to-inst] radius ;m
10999: overrides construct
1.44 crook 11000:
1.78 anton 11001: end-methods
11002: @end example
1.7 pazsan 11003:
1.78 anton 11004: You can use several @code{methods}...@code{end-methods} sections. The
11005: only things you can do to the class in these sections are: defining
11006: methods, and overriding the class's selectors. You must not define new
11007: selectors or fields.
1.7 pazsan 11008:
1.78 anton 11009: Note that you often have to override a selector before using it. In
11010: particular, you usually have to override @code{construct} with a new
11011: method before you can invoke @code{heap-new} and friends. E.g., you
11012: must not create a circle before the @code{overrides construct} sequence
11013: in the example above.
1.7 pazsan 11014:
1.78 anton 11015: @node Object Interfaces, Objects Implementation, Dividing classes, Objects
11016: @subsubsection Object Interfaces
11017: @cindex object interfaces
11018: @cindex interfaces for objects
1.7 pazsan 11019:
1.78 anton 11020: In this model you can only call selectors defined in the class of the
11021: receiving objects or in one of its ancestors. If you call a selector
11022: with a receiving object that is not in one of these classes, the
11023: result is undefined; if you are lucky, the program crashes
11024: immediately.
1.7 pazsan 11025:
1.78 anton 11026: @cindex selectors common to hardly-related classes
11027: Now consider the case when you want to have a selector (or several)
11028: available in two classes: You would have to add the selector to a
11029: common ancestor class, in the worst case to @code{object}. You
11030: may not want to do this, e.g., because someone else is responsible for
11031: this ancestor class.
1.7 pazsan 11032:
1.78 anton 11033: The solution for this problem is interfaces. An interface is a
11034: collection of selectors. If a class implements an interface, the
11035: selectors become available to the class and its descendents. A class
11036: can implement an unlimited number of interfaces. For the problem
11037: discussed above, we would define an interface for the selector(s), and
11038: both classes would implement the interface.
1.7 pazsan 11039:
1.78 anton 11040: As an example, consider an interface @code{storage} for
11041: writing objects to disk and getting them back, and a class
11042: @code{foo} that implements it. The code would look like this:
1.7 pazsan 11043:
1.78 anton 11044: @cindex @code{interface} usage
11045: @cindex @code{end-interface} usage
11046: @cindex @code{implementation} usage
11047: @example
11048: interface
11049: selector write ( file object -- )
11050: selector read1 ( file object -- )
11051: end-interface storage
1.13 pazsan 11052:
1.78 anton 11053: bar class
11054: storage implementation
1.13 pazsan 11055:
1.78 anton 11056: ... overrides write
11057: ... overrides read1
11058: ...
11059: end-class foo
11060: @end example
1.13 pazsan 11061:
1.78 anton 11062: @noindent
11063: (I would add a word @code{read} @i{( file -- object )} that uses
11064: @code{read1} internally, but that's beyond the point illustrated
11065: here.)
1.13 pazsan 11066:
1.78 anton 11067: Note that you cannot use @code{protected} in an interface; and
11068: of course you cannot define fields.
1.13 pazsan 11069:
1.78 anton 11070: In the Neon model, all selectors are available for all classes;
11071: therefore it does not need interfaces. The price you pay in this model
11072: is slower late binding, and therefore, added complexity to avoid late
11073: binding.
1.13 pazsan 11074:
1.78 anton 11075: @node Objects Implementation, Objects Glossary, Object Interfaces, Objects
11076: @subsubsection @file{objects.fs} Implementation
11077: @cindex @file{objects.fs} implementation
1.13 pazsan 11078:
1.78 anton 11079: @cindex @code{object-map} discussion
11080: An object is a piece of memory, like one of the data structures
11081: described with @code{struct...end-struct}. It has a field
11082: @code{object-map} that points to the method map for the object's
11083: class.
1.13 pazsan 11084:
1.78 anton 11085: @cindex method map
11086: @cindex virtual function table
11087: The @emph{method map}@footnote{This is Self terminology; in C++
11088: terminology: virtual function table.} is an array that contains the
11089: execution tokens (@i{xt}s) of the methods for the object's class. Each
11090: selector contains an offset into a method map.
1.13 pazsan 11091:
1.78 anton 11092: @cindex @code{selector} implementation, class
11093: @code{selector} is a defining word that uses
11094: @code{CREATE} and @code{DOES>}. The body of the
11095: selector contains the offset; the @code{DOES>} action for a
11096: class selector is, basically:
1.8 pazsan 11097:
11098: @example
1.78 anton 11099: ( object addr ) @@ over object-map @@ + @@ execute
1.13 pazsan 11100: @end example
11101:
1.78 anton 11102: Since @code{object-map} is the first field of the object, it
11103: does not generate any code. As you can see, calling a selector has a
11104: small, constant cost.
1.26 crook 11105:
1.78 anton 11106: @cindex @code{current-interface} discussion
11107: @cindex class implementation and representation
11108: A class is basically a @code{struct} combined with a method
11109: map. During the class definition the alignment and size of the class
11110: are passed on the stack, just as with @code{struct}s, so
11111: @code{field} can also be used for defining class
11112: fields. However, passing more items on the stack would be
11113: inconvenient, so @code{class} builds a data structure in memory,
11114: which is accessed through the variable
11115: @code{current-interface}. After its definition is complete, the
11116: class is represented on the stack by a pointer (e.g., as parameter for
11117: a child class definition).
1.26 crook 11118:
1.78 anton 11119: A new class starts off with the alignment and size of its parent,
11120: and a copy of the parent's method map. Defining new fields extends the
11121: size and alignment; likewise, defining new selectors extends the
11122: method map. @code{overrides} just stores a new @i{xt} in the method
11123: map at the offset given by the selector.
1.13 pazsan 11124:
1.78 anton 11125: @cindex class binding, implementation
11126: Class binding just gets the @i{xt} at the offset given by the selector
11127: from the class's method map and @code{compile,}s (in the case of
11128: @code{[bind]}) it.
1.13 pazsan 11129:
1.78 anton 11130: @cindex @code{this} implementation
11131: @cindex @code{catch} and @code{this}
11132: @cindex @code{this} and @code{catch}
11133: I implemented @code{this} as a @code{value}. At the
11134: start of an @code{m:...;m} method the old @code{this} is
11135: stored to the return stack and restored at the end; and the object on
11136: the TOS is stored @code{TO this}. This technique has one
11137: disadvantage: If the user does not leave the method via
11138: @code{;m}, but via @code{throw} or @code{exit},
11139: @code{this} is not restored (and @code{exit} may
11140: crash). To deal with the @code{throw} problem, I have redefined
11141: @code{catch} to save and restore @code{this}; the same
11142: should be done with any word that can catch an exception. As for
11143: @code{exit}, I simply forbid it (as a replacement, there is
11144: @code{exitm}).
1.13 pazsan 11145:
1.78 anton 11146: @cindex @code{inst-var} implementation
11147: @code{inst-var} is just the same as @code{field}, with
11148: a different @code{DOES>} action:
1.13 pazsan 11149: @example
1.78 anton 11150: @@ this +
1.8 pazsan 11151: @end example
1.78 anton 11152: Similar for @code{inst-value}.
1.8 pazsan 11153:
1.78 anton 11154: @cindex class scoping implementation
11155: Each class also has a word list that contains the words defined with
11156: @code{inst-var} and @code{inst-value}, and its protected
11157: words. It also has a pointer to its parent. @code{class} pushes
11158: the word lists of the class and all its ancestors onto the search order stack,
11159: and @code{end-class} drops them.
1.20 pazsan 11160:
1.78 anton 11161: @cindex interface implementation
11162: An interface is like a class without fields, parent and protected
11163: words; i.e., it just has a method map. If a class implements an
11164: interface, its method map contains a pointer to the method map of the
11165: interface. The positive offsets in the map are reserved for class
11166: methods, therefore interface map pointers have negative
11167: offsets. Interfaces have offsets that are unique throughout the
11168: system, unlike class selectors, whose offsets are only unique for the
11169: classes where the selector is available (invokable).
1.20 pazsan 11170:
1.78 anton 11171: This structure means that interface selectors have to perform one
11172: indirection more than class selectors to find their method. Their body
11173: contains the interface map pointer offset in the class method map, and
11174: the method offset in the interface method map. The
11175: @code{does>} action for an interface selector is, basically:
1.20 pazsan 11176:
11177: @example
1.78 anton 11178: ( object selector-body )
11179: 2dup selector-interface @@ ( object selector-body object interface-offset )
11180: swap object-map @@ + @@ ( object selector-body map )
11181: swap selector-offset @@ + @@ execute
1.20 pazsan 11182: @end example
11183:
1.78 anton 11184: where @code{object-map} and @code{selector-offset} are
11185: first fields and generate no code.
1.20 pazsan 11186:
1.78 anton 11187: As a concrete example, consider the following code:
1.20 pazsan 11188:
11189: @example
1.78 anton 11190: interface
11191: selector if1sel1
11192: selector if1sel2
11193: end-interface if1
1.20 pazsan 11194:
1.78 anton 11195: object class
11196: if1 implementation
11197: selector cl1sel1
11198: cell% inst-var cl1iv1
1.20 pazsan 11199:
1.78 anton 11200: ' m1 overrides construct
11201: ' m2 overrides if1sel1
11202: ' m3 overrides if1sel2
11203: ' m4 overrides cl1sel2
11204: end-class cl1
1.20 pazsan 11205:
1.78 anton 11206: create obj1 object dict-new drop
11207: create obj2 cl1 dict-new drop
11208: @end example
1.20 pazsan 11209:
1.78 anton 11210: The data structure created by this code (including the data structure
11211: for @code{object}) is shown in the
11212: @uref{objects-implementation.eps,figure}, assuming a cell size of 4.
11213: @comment TODO add this diagram..
1.20 pazsan 11214:
1.78 anton 11215: @node Objects Glossary, , Objects Implementation, Objects
11216: @subsubsection @file{objects.fs} Glossary
11217: @cindex @file{objects.fs} Glossary
1.20 pazsan 11218:
11219:
1.78 anton 11220: doc---objects-bind
11221: doc---objects-<bind>
11222: doc---objects-bind'
11223: doc---objects-[bind]
11224: doc---objects-class
11225: doc---objects-class->map
11226: doc---objects-class-inst-size
11227: doc---objects-class-override!
1.79 anton 11228: doc---objects-class-previous
11229: doc---objects-class>order
1.78 anton 11230: doc---objects-construct
11231: doc---objects-current'
11232: doc---objects-[current]
11233: doc---objects-current-interface
11234: doc---objects-dict-new
11235: doc---objects-end-class
11236: doc---objects-end-class-noname
11237: doc---objects-end-interface
11238: doc---objects-end-interface-noname
11239: doc---objects-end-methods
11240: doc---objects-exitm
11241: doc---objects-heap-new
11242: doc---objects-implementation
11243: doc---objects-init-object
11244: doc---objects-inst-value
11245: doc---objects-inst-var
11246: doc---objects-interface
11247: doc---objects-m:
11248: doc---objects-:m
11249: doc---objects-;m
11250: doc---objects-method
11251: doc---objects-methods
11252: doc---objects-object
11253: doc---objects-overrides
11254: doc---objects-[parent]
11255: doc---objects-print
11256: doc---objects-protected
11257: doc---objects-public
11258: doc---objects-selector
11259: doc---objects-this
11260: doc---objects-<to-inst>
11261: doc---objects-[to-inst]
11262: doc---objects-to-this
11263: doc---objects-xt-new
1.20 pazsan 11264:
11265:
1.78 anton 11266: @c -------------------------------------------------------------
11267: @node OOF, Mini-OOF, Objects, Object-oriented Forth
11268: @subsection The @file{oof.fs} model
11269: @cindex oof
11270: @cindex object-oriented programming
1.20 pazsan 11271:
1.78 anton 11272: @cindex @file{objects.fs}
11273: @cindex @file{oof.fs}
1.20 pazsan 11274:
1.78 anton 11275: This section describes the @file{oof.fs} package.
1.20 pazsan 11276:
1.78 anton 11277: The package described in this section has been used in bigFORTH since 1991, and
11278: used for two large applications: a chromatographic system used to
11279: create new medicaments, and a graphic user interface library (MINOS).
1.20 pazsan 11280:
1.78 anton 11281: You can find a description (in German) of @file{oof.fs} in @cite{Object
11282: oriented bigFORTH} by Bernd Paysan, published in @cite{Vierte Dimension}
11283: 10(2), 1994.
1.20 pazsan 11284:
1.78 anton 11285: @menu
11286: * Properties of the OOF model::
11287: * Basic OOF Usage::
11288: * The OOF base class::
11289: * Class Declaration::
11290: * Class Implementation::
11291: @end menu
1.20 pazsan 11292:
1.78 anton 11293: @node Properties of the OOF model, Basic OOF Usage, OOF, OOF
11294: @subsubsection Properties of the @file{oof.fs} model
11295: @cindex @file{oof.fs} properties
1.20 pazsan 11296:
1.78 anton 11297: @itemize @bullet
11298: @item
11299: This model combines object oriented programming with information
11300: hiding. It helps you writing large application, where scoping is
11301: necessary, because it provides class-oriented scoping.
1.20 pazsan 11302:
1.78 anton 11303: @item
11304: Named objects, object pointers, and object arrays can be created,
11305: selector invocation uses the ``object selector'' syntax. Selector invocation
11306: to objects and/or selectors on the stack is a bit less convenient, but
11307: possible.
1.44 crook 11308:
1.78 anton 11309: @item
11310: Selector invocation and instance variable usage of the active object is
11311: straightforward, since both make use of the active object.
1.44 crook 11312:
1.78 anton 11313: @item
11314: Late binding is efficient and easy to use.
1.20 pazsan 11315:
1.78 anton 11316: @item
11317: State-smart objects parse selectors. However, extensibility is provided
11318: using a (parsing) selector @code{postpone} and a selector @code{'}.
1.20 pazsan 11319:
1.78 anton 11320: @item
11321: An implementation in ANS Forth is available.
1.20 pazsan 11322:
1.78 anton 11323: @end itemize
1.23 crook 11324:
11325:
1.78 anton 11326: @node Basic OOF Usage, The OOF base class, Properties of the OOF model, OOF
11327: @subsubsection Basic @file{oof.fs} Usage
11328: @cindex @file{oof.fs} usage
1.23 crook 11329:
1.78 anton 11330: This section uses the same example as for @code{objects} (@pxref{Basic Objects Usage}).
1.23 crook 11331:
1.78 anton 11332: You can define a class for graphical objects like this:
1.23 crook 11333:
1.78 anton 11334: @cindex @code{class} usage
11335: @cindex @code{class;} usage
11336: @cindex @code{method} usage
11337: @example
11338: object class graphical \ "object" is the parent class
1.139 pazsan 11339: method draw ( x y -- )
1.78 anton 11340: class;
11341: @end example
1.23 crook 11342:
1.78 anton 11343: This code defines a class @code{graphical} with an
11344: operation @code{draw}. We can perform the operation
11345: @code{draw} on any @code{graphical} object, e.g.:
1.23 crook 11346:
1.78 anton 11347: @example
11348: 100 100 t-rex draw
11349: @end example
1.23 crook 11350:
1.78 anton 11351: @noindent
11352: where @code{t-rex} is an object or object pointer, created with e.g.
11353: @code{graphical : t-rex}.
1.23 crook 11354:
1.78 anton 11355: @cindex abstract class
11356: How do we create a graphical object? With the present definitions,
11357: we cannot create a useful graphical object. The class
11358: @code{graphical} describes graphical objects in general, but not
11359: any concrete graphical object type (C++ users would call it an
11360: @emph{abstract class}); e.g., there is no method for the selector
11361: @code{draw} in the class @code{graphical}.
1.23 crook 11362:
1.78 anton 11363: For concrete graphical objects, we define child classes of the
11364: class @code{graphical}, e.g.:
1.23 crook 11365:
1.78 anton 11366: @example
11367: graphical class circle \ "graphical" is the parent class
11368: cell var circle-radius
11369: how:
11370: : draw ( x y -- )
11371: circle-radius @@ draw-circle ;
1.23 crook 11372:
1.139 pazsan 11373: : init ( n-radius -- )
1.78 anton 11374: circle-radius ! ;
11375: class;
11376: @end example
1.1 anton 11377:
1.78 anton 11378: Here we define a class @code{circle} as a child of @code{graphical},
11379: with a field @code{circle-radius}; it defines new methods for the
11380: selectors @code{draw} and @code{init} (@code{init} is defined in
11381: @code{object}, the parent class of @code{graphical}).
1.1 anton 11382:
1.78 anton 11383: Now we can create a circle in the dictionary with:
1.1 anton 11384:
1.78 anton 11385: @example
11386: 50 circle : my-circle
11387: @end example
1.21 crook 11388:
1.78 anton 11389: @noindent
11390: @code{:} invokes @code{init}, thus initializing the field
11391: @code{circle-radius} with 50. We can draw this new circle at (100,100)
11392: with:
1.1 anton 11393:
1.78 anton 11394: @example
11395: 100 100 my-circle draw
11396: @end example
1.1 anton 11397:
1.78 anton 11398: @cindex selector invocation, restrictions
11399: @cindex class definition, restrictions
11400: Note: You can only invoke a selector if the receiving object belongs to
11401: the class where the selector was defined or one of its descendents;
11402: e.g., you can invoke @code{draw} only for objects belonging to
11403: @code{graphical} or its descendents (e.g., @code{circle}). The scoping
11404: mechanism will check if you try to invoke a selector that is not
11405: defined in this class hierarchy, so you'll get an error at compilation
11406: time.
1.1 anton 11407:
11408:
1.78 anton 11409: @node The OOF base class, Class Declaration, Basic OOF Usage, OOF
11410: @subsubsection The @file{oof.fs} base class
11411: @cindex @file{oof.fs} base class
1.1 anton 11412:
1.78 anton 11413: When you define a class, you have to specify a parent class. So how do
11414: you start defining classes? There is one class available from the start:
11415: @code{object}. You have to use it as ancestor for all classes. It is the
11416: only class that has no parent. Classes are also objects, except that
11417: they don't have instance variables; class manipulation such as
11418: inheritance or changing definitions of a class is handled through
11419: selectors of the class @code{object}.
1.1 anton 11420:
1.78 anton 11421: @code{object} provides a number of selectors:
1.1 anton 11422:
1.78 anton 11423: @itemize @bullet
11424: @item
11425: @code{class} for subclassing, @code{definitions} to add definitions
11426: later on, and @code{class?} to get type informations (is the class a
11427: subclass of the class passed on the stack?).
1.1 anton 11428:
1.78 anton 11429: doc---object-class
11430: doc---object-definitions
11431: doc---object-class?
1.1 anton 11432:
11433:
1.26 crook 11434: @item
1.78 anton 11435: @code{init} and @code{dispose} as constructor and destructor of the
11436: object. @code{init} is invocated after the object's memory is allocated,
11437: while @code{dispose} also handles deallocation. Thus if you redefine
11438: @code{dispose}, you have to call the parent's dispose with @code{super
11439: dispose}, too.
11440:
11441: doc---object-init
11442: doc---object-dispose
11443:
1.1 anton 11444:
1.26 crook 11445: @item
1.78 anton 11446: @code{new}, @code{new[]}, @code{:}, @code{ptr}, @code{asptr}, and
11447: @code{[]} to create named and unnamed objects and object arrays or
11448: object pointers.
11449:
11450: doc---object-new
11451: doc---object-new[]
11452: doc---object-:
11453: doc---object-ptr
11454: doc---object-asptr
11455: doc---object-[]
11456:
1.1 anton 11457:
1.26 crook 11458: @item
1.78 anton 11459: @code{::} and @code{super} for explicit scoping. You should use explicit
11460: scoping only for super classes or classes with the same set of instance
11461: variables. Explicitly-scoped selectors use early binding.
1.21 crook 11462:
1.78 anton 11463: doc---object-::
11464: doc---object-super
1.21 crook 11465:
11466:
1.26 crook 11467: @item
1.78 anton 11468: @code{self} to get the address of the object
1.21 crook 11469:
1.78 anton 11470: doc---object-self
1.21 crook 11471:
11472:
1.78 anton 11473: @item
11474: @code{bind}, @code{bound}, @code{link}, and @code{is} to assign object
11475: pointers and instance defers.
1.21 crook 11476:
1.78 anton 11477: doc---object-bind
11478: doc---object-bound
11479: doc---object-link
11480: doc---object-is
1.21 crook 11481:
11482:
1.78 anton 11483: @item
11484: @code{'} to obtain selector tokens, @code{send} to invocate selectors
11485: form the stack, and @code{postpone} to generate selector invocation code.
1.21 crook 11486:
1.78 anton 11487: doc---object-'
11488: doc---object-postpone
1.21 crook 11489:
11490:
1.78 anton 11491: @item
11492: @code{with} and @code{endwith} to select the active object from the
11493: stack, and enable its scope. Using @code{with} and @code{endwith}
11494: also allows you to create code using selector @code{postpone} without being
11495: trapped by the state-smart objects.
1.21 crook 11496:
1.78 anton 11497: doc---object-with
11498: doc---object-endwith
1.21 crook 11499:
11500:
1.78 anton 11501: @end itemize
1.21 crook 11502:
1.78 anton 11503: @node Class Declaration, Class Implementation, The OOF base class, OOF
11504: @subsubsection Class Declaration
11505: @cindex class declaration
1.21 crook 11506:
1.78 anton 11507: @itemize @bullet
11508: @item
11509: Instance variables
1.21 crook 11510:
1.78 anton 11511: doc---oof-var
1.21 crook 11512:
11513:
1.78 anton 11514: @item
11515: Object pointers
1.21 crook 11516:
1.78 anton 11517: doc---oof-ptr
11518: doc---oof-asptr
1.21 crook 11519:
11520:
1.78 anton 11521: @item
11522: Instance defers
1.21 crook 11523:
1.78 anton 11524: doc---oof-defer
1.21 crook 11525:
11526:
1.78 anton 11527: @item
11528: Method selectors
1.21 crook 11529:
1.78 anton 11530: doc---oof-early
11531: doc---oof-method
1.21 crook 11532:
11533:
1.78 anton 11534: @item
11535: Class-wide variables
1.21 crook 11536:
1.78 anton 11537: doc---oof-static
1.21 crook 11538:
11539:
1.78 anton 11540: @item
11541: End declaration
1.1 anton 11542:
1.78 anton 11543: doc---oof-how:
11544: doc---oof-class;
1.21 crook 11545:
11546:
1.78 anton 11547: @end itemize
1.21 crook 11548:
1.78 anton 11549: @c -------------------------------------------------------------
11550: @node Class Implementation, , Class Declaration, OOF
11551: @subsubsection Class Implementation
11552: @cindex class implementation
1.21 crook 11553:
1.78 anton 11554: @c -------------------------------------------------------------
11555: @node Mini-OOF, Comparison with other object models, OOF, Object-oriented Forth
11556: @subsection The @file{mini-oof.fs} model
11557: @cindex mini-oof
1.21 crook 11558:
1.78 anton 11559: Gforth's third object oriented Forth package is a 12-liner. It uses a
1.79 anton 11560: mixture of the @file{objects.fs} and the @file{oof.fs} syntax,
1.78 anton 11561: and reduces to the bare minimum of features. This is based on a posting
11562: of Bernd Paysan in comp.lang.forth.
1.21 crook 11563:
1.78 anton 11564: @menu
11565: * Basic Mini-OOF Usage::
11566: * Mini-OOF Example::
11567: * Mini-OOF Implementation::
11568: @end menu
1.21 crook 11569:
1.78 anton 11570: @c -------------------------------------------------------------
11571: @node Basic Mini-OOF Usage, Mini-OOF Example, Mini-OOF, Mini-OOF
11572: @subsubsection Basic @file{mini-oof.fs} Usage
11573: @cindex mini-oof usage
1.21 crook 11574:
1.78 anton 11575: There is a base class (@code{class}, which allocates one cell for the
11576: object pointer) plus seven other words: to define a method, a variable,
11577: a class; to end a class, to resolve binding, to allocate an object and
11578: to compile a class method.
11579: @comment TODO better description of the last one
1.26 crook 11580:
1.21 crook 11581:
1.78 anton 11582: doc-object
11583: doc-method
11584: doc-var
11585: doc-class
11586: doc-end-class
11587: doc-defines
11588: doc-new
11589: doc-::
1.21 crook 11590:
11591:
11592:
1.78 anton 11593: @c -------------------------------------------------------------
11594: @node Mini-OOF Example, Mini-OOF Implementation, Basic Mini-OOF Usage, Mini-OOF
11595: @subsubsection Mini-OOF Example
11596: @cindex mini-oof example
1.1 anton 11597:
1.78 anton 11598: A short example shows how to use this package. This example, in slightly
11599: extended form, is supplied as @file{moof-exm.fs}
11600: @comment TODO could flesh this out with some comments from the Forthwrite article
1.20 pazsan 11601:
1.26 crook 11602: @example
1.78 anton 11603: object class
11604: method init
11605: method draw
11606: end-class graphical
1.26 crook 11607: @end example
1.20 pazsan 11608:
1.78 anton 11609: This code defines a class @code{graphical} with an
11610: operation @code{draw}. We can perform the operation
11611: @code{draw} on any @code{graphical} object, e.g.:
1.20 pazsan 11612:
1.26 crook 11613: @example
1.78 anton 11614: 100 100 t-rex draw
1.26 crook 11615: @end example
1.12 anton 11616:
1.78 anton 11617: where @code{t-rex} is an object or object pointer, created with e.g.
11618: @code{graphical new Constant t-rex}.
1.12 anton 11619:
1.78 anton 11620: For concrete graphical objects, we define child classes of the
11621: class @code{graphical}, e.g.:
1.12 anton 11622:
1.26 crook 11623: @example
11624: graphical class
1.78 anton 11625: cell var circle-radius
11626: end-class circle \ "graphical" is the parent class
1.12 anton 11627:
1.78 anton 11628: :noname ( x y -- )
11629: circle-radius @@ draw-circle ; circle defines draw
11630: :noname ( r -- )
11631: circle-radius ! ; circle defines init
11632: @end example
1.12 anton 11633:
1.78 anton 11634: There is no implicit init method, so we have to define one. The creation
11635: code of the object now has to call init explicitely.
1.21 crook 11636:
1.78 anton 11637: @example
11638: circle new Constant my-circle
11639: 50 my-circle init
1.12 anton 11640: @end example
11641:
1.78 anton 11642: It is also possible to add a function to create named objects with
11643: automatic call of @code{init}, given that all objects have @code{init}
11644: on the same place:
1.38 anton 11645:
1.78 anton 11646: @example
11647: : new: ( .. o "name" -- )
11648: new dup Constant init ;
11649: 80 circle new: large-circle
11650: @end example
1.12 anton 11651:
1.78 anton 11652: We can draw this new circle at (100,100) with:
1.12 anton 11653:
1.78 anton 11654: @example
11655: 100 100 my-circle draw
11656: @end example
1.12 anton 11657:
1.78 anton 11658: @node Mini-OOF Implementation, , Mini-OOF Example, Mini-OOF
11659: @subsubsection @file{mini-oof.fs} Implementation
1.12 anton 11660:
1.78 anton 11661: Object-oriented systems with late binding typically use a
11662: ``vtable''-approach: the first variable in each object is a pointer to a
11663: table, which contains the methods as function pointers. The vtable
11664: may also contain other information.
1.12 anton 11665:
1.79 anton 11666: So first, let's declare selectors:
1.37 anton 11667:
11668: @example
1.79 anton 11669: : method ( m v "name" -- m' v ) Create over , swap cell+ swap
1.78 anton 11670: DOES> ( ... o -- ... ) @@ over @@ + @@ execute ;
11671: @end example
1.37 anton 11672:
1.79 anton 11673: During selector declaration, the number of selectors and instance
11674: variables is on the stack (in address units). @code{method} creates one
11675: selector and increments the selector number. To execute a selector, it
1.78 anton 11676: takes the object, fetches the vtable pointer, adds the offset, and
1.79 anton 11677: executes the method @i{xt} stored there. Each selector takes the object
11678: it is invoked with as top of stack parameter; it passes the parameters
11679: (including the object) unchanged to the appropriate method which should
1.78 anton 11680: consume that object.
1.37 anton 11681:
1.78 anton 11682: Now, we also have to declare instance variables
1.37 anton 11683:
1.78 anton 11684: @example
1.79 anton 11685: : var ( m v size "name" -- m v' ) Create over , +
1.78 anton 11686: DOES> ( o -- addr ) @@ + ;
1.37 anton 11687: @end example
11688:
1.78 anton 11689: As before, a word is created with the current offset. Instance
11690: variables can have different sizes (cells, floats, doubles, chars), so
11691: all we do is take the size and add it to the offset. If your machine
11692: has alignment restrictions, put the proper @code{aligned} or
11693: @code{faligned} before the variable, to adjust the variable
11694: offset. That's why it is on the top of stack.
1.37 anton 11695:
1.78 anton 11696: We need a starting point (the base object) and some syntactic sugar:
1.37 anton 11697:
1.78 anton 11698: @example
11699: Create object 1 cells , 2 cells ,
1.79 anton 11700: : class ( class -- class selectors vars ) dup 2@@ ;
1.78 anton 11701: @end example
1.12 anton 11702:
1.78 anton 11703: For inheritance, the vtable of the parent object has to be
11704: copied when a new, derived class is declared. This gives all the
11705: methods of the parent class, which can be overridden, though.
1.12 anton 11706:
1.78 anton 11707: @example
1.79 anton 11708: : end-class ( class selectors vars "name" -- )
1.78 anton 11709: Create here >r , dup , 2 cells ?DO ['] noop , 1 cells +LOOP
11710: cell+ dup cell+ r> rot @@ 2 cells /string move ;
11711: @end example
1.12 anton 11712:
1.78 anton 11713: The first line creates the vtable, initialized with
11714: @code{noop}s. The second line is the inheritance mechanism, it
11715: copies the xts from the parent vtable.
1.12 anton 11716:
1.78 anton 11717: We still have no way to define new methods, let's do that now:
1.12 anton 11718:
1.26 crook 11719: @example
1.79 anton 11720: : defines ( xt class "name" -- ) ' >body @@ + ! ;
1.78 anton 11721: @end example
1.12 anton 11722:
1.78 anton 11723: To allocate a new object, we need a word, too:
1.12 anton 11724:
1.78 anton 11725: @example
11726: : new ( class -- o ) here over @@ allot swap over ! ;
1.12 anton 11727: @end example
11728:
1.78 anton 11729: Sometimes derived classes want to access the method of the
11730: parent object. There are two ways to achieve this with Mini-OOF:
11731: first, you could use named words, and second, you could look up the
11732: vtable of the parent object.
1.12 anton 11733:
1.78 anton 11734: @example
11735: : :: ( class "name" -- ) ' >body @@ + @@ compile, ;
11736: @end example
1.12 anton 11737:
11738:
1.78 anton 11739: Nothing can be more confusing than a good example, so here is
11740: one. First let's declare a text object (called
11741: @code{button}), that stores text and position:
1.12 anton 11742:
1.78 anton 11743: @example
11744: object class
11745: cell var text
11746: cell var len
11747: cell var x
11748: cell var y
11749: method init
11750: method draw
11751: end-class button
11752: @end example
1.12 anton 11753:
1.78 anton 11754: @noindent
11755: Now, implement the two methods, @code{draw} and @code{init}:
1.21 crook 11756:
1.26 crook 11757: @example
1.78 anton 11758: :noname ( o -- )
11759: >r r@@ x @@ r@@ y @@ at-xy r@@ text @@ r> len @@ type ;
11760: button defines draw
11761: :noname ( addr u o -- )
11762: >r 0 r@@ x ! 0 r@@ y ! r@@ len ! r> text ! ;
11763: button defines init
1.26 crook 11764: @end example
1.12 anton 11765:
1.78 anton 11766: @noindent
11767: To demonstrate inheritance, we define a class @code{bold-button}, with no
1.79 anton 11768: new data and no new selectors:
1.78 anton 11769:
11770: @example
11771: button class
11772: end-class bold-button
1.12 anton 11773:
1.78 anton 11774: : bold 27 emit ." [1m" ;
11775: : normal 27 emit ." [0m" ;
11776: @end example
1.1 anton 11777:
1.78 anton 11778: @noindent
11779: The class @code{bold-button} has a different draw method to
11780: @code{button}, but the new method is defined in terms of the draw method
11781: for @code{button}:
1.20 pazsan 11782:
1.78 anton 11783: @example
11784: :noname bold [ button :: draw ] normal ; bold-button defines draw
11785: @end example
1.21 crook 11786:
1.78 anton 11787: @noindent
1.79 anton 11788: Finally, create two objects and apply selectors:
1.21 crook 11789:
1.26 crook 11790: @example
1.78 anton 11791: button new Constant foo
11792: s" thin foo" foo init
11793: page
11794: foo draw
11795: bold-button new Constant bar
11796: s" fat bar" bar init
11797: 1 bar y !
11798: bar draw
1.26 crook 11799: @end example
1.21 crook 11800:
11801:
1.78 anton 11802: @node Comparison with other object models, , Mini-OOF, Object-oriented Forth
11803: @subsection Comparison with other object models
11804: @cindex comparison of object models
11805: @cindex object models, comparison
11806:
11807: Many object-oriented Forth extensions have been proposed (@cite{A survey
11808: of object-oriented Forths} (SIGPLAN Notices, April 1996) by Bradford
11809: J. Rodriguez and W. F. S. Poehlman lists 17). This section discusses the
11810: relation of the object models described here to two well-known and two
11811: closely-related (by the use of method maps) models. Andras Zsoter
11812: helped us with this section.
11813:
11814: @cindex Neon model
11815: The most popular model currently seems to be the Neon model (see
11816: @cite{Object-oriented programming in ANS Forth} (Forth Dimensions, March
11817: 1997) by Andrew McKewan) but this model has a number of limitations
11818: @footnote{A longer version of this critique can be
11819: found in @cite{On Standardizing Object-Oriented Forth Extensions} (Forth
11820: Dimensions, May 1997) by Anton Ertl.}:
11821:
11822: @itemize @bullet
11823: @item
11824: It uses a @code{@emph{selector object}} syntax, which makes it unnatural
11825: to pass objects on the stack.
1.21 crook 11826:
1.78 anton 11827: @item
11828: It requires that the selector parses the input stream (at
1.79 anton 11829: compile time); this leads to reduced extensibility and to bugs that are
1.78 anton 11830: hard to find.
1.21 crook 11831:
1.78 anton 11832: @item
1.79 anton 11833: It allows using every selector on every object; this eliminates the
11834: need for interfaces, but makes it harder to create efficient
11835: implementations.
1.78 anton 11836: @end itemize
1.21 crook 11837:
1.78 anton 11838: @cindex Pountain's object-oriented model
11839: Another well-known publication is @cite{Object-Oriented Forth} (Academic
11840: Press, London, 1987) by Dick Pountain. However, it is not really about
11841: object-oriented programming, because it hardly deals with late
11842: binding. Instead, it focuses on features like information hiding and
11843: overloading that are characteristic of modular languages like Ada (83).
1.26 crook 11844:
1.78 anton 11845: @cindex Zsoter's object-oriented model
1.79 anton 11846: In @uref{http://www.forth.org/oopf.html, Does late binding have to be
11847: slow?} (Forth Dimensions 18(1) 1996, pages 31-35) Andras Zsoter
11848: describes a model that makes heavy use of an active object (like
11849: @code{this} in @file{objects.fs}): The active object is not only used
11850: for accessing all fields, but also specifies the receiving object of
11851: every selector invocation; you have to change the active object
11852: explicitly with @code{@{ ... @}}, whereas in @file{objects.fs} it
11853: changes more or less implicitly at @code{m: ... ;m}. Such a change at
11854: the method entry point is unnecessary with Zsoter's model, because the
11855: receiving object is the active object already. On the other hand, the
11856: explicit change is absolutely necessary in that model, because otherwise
11857: no one could ever change the active object. An ANS Forth implementation
11858: of this model is available through
11859: @uref{http://www.forth.org/oopf.html}.
1.21 crook 11860:
1.78 anton 11861: @cindex @file{oof.fs}, differences to other models
11862: The @file{oof.fs} model combines information hiding and overloading
11863: resolution (by keeping names in various word lists) with object-oriented
11864: programming. It sets the active object implicitly on method entry, but
11865: also allows explicit changing (with @code{>o...o>} or with
11866: @code{with...endwith}). It uses parsing and state-smart objects and
11867: classes for resolving overloading and for early binding: the object or
11868: class parses the selector and determines the method from this. If the
11869: selector is not parsed by an object or class, it performs a call to the
11870: selector for the active object (late binding), like Zsoter's model.
11871: Fields are always accessed through the active object. The big
11872: disadvantage of this model is the parsing and the state-smartness, which
11873: reduces extensibility and increases the opportunities for subtle bugs;
11874: essentially, you are only safe if you never tick or @code{postpone} an
11875: object or class (Bernd disagrees, but I (Anton) am not convinced).
1.21 crook 11876:
1.78 anton 11877: @cindex @file{mini-oof.fs}, differences to other models
11878: The @file{mini-oof.fs} model is quite similar to a very stripped-down
11879: version of the @file{objects.fs} model, but syntactically it is a
11880: mixture of the @file{objects.fs} and @file{oof.fs} models.
1.21 crook 11881:
11882:
1.78 anton 11883: @c -------------------------------------------------------------
1.150 anton 11884: @node Programming Tools, C Interface, Object-oriented Forth, Words
1.78 anton 11885: @section Programming Tools
11886: @cindex programming tools
1.21 crook 11887:
1.78 anton 11888: @c !! move this and assembler down below OO stuff.
1.21 crook 11889:
1.78 anton 11890: @menu
1.150 anton 11891: * Examining:: Data and Code.
11892: * Forgetting words:: Usually before reloading.
1.78 anton 11893: * Debugging:: Simple and quick.
11894: * Assertions:: Making your programs self-checking.
11895: * Singlestep Debugger:: Executing your program word by word.
11896: @end menu
1.21 crook 11897:
1.78 anton 11898: @node Examining, Forgetting words, Programming Tools, Programming Tools
11899: @subsection Examining data and code
11900: @cindex examining data and code
11901: @cindex data examination
11902: @cindex code examination
1.44 crook 11903:
1.78 anton 11904: The following words inspect the stack non-destructively:
1.21 crook 11905:
1.78 anton 11906: doc-.s
11907: doc-f.s
1.158 anton 11908: doc-maxdepth-.s
1.44 crook 11909:
1.78 anton 11910: There is a word @code{.r} but it does @i{not} display the return stack!
11911: It is used for formatted numeric output (@pxref{Simple numeric output}).
1.21 crook 11912:
1.78 anton 11913: doc-depth
11914: doc-fdepth
11915: doc-clearstack
1.124 anton 11916: doc-clearstacks
1.21 crook 11917:
1.78 anton 11918: The following words inspect memory.
1.21 crook 11919:
1.78 anton 11920: doc-?
11921: doc-dump
1.21 crook 11922:
1.78 anton 11923: And finally, @code{see} allows to inspect code:
1.21 crook 11924:
1.78 anton 11925: doc-see
11926: doc-xt-see
1.111 anton 11927: doc-simple-see
11928: doc-simple-see-range
1.182 anton 11929: doc-see-code
11930: doc-see-code-range
1.21 crook 11931:
1.78 anton 11932: @node Forgetting words, Debugging, Examining, Programming Tools
11933: @subsection Forgetting words
11934: @cindex words, forgetting
11935: @cindex forgeting words
1.21 crook 11936:
1.78 anton 11937: @c anton: other, maybe better places for this subsection: Defining Words;
11938: @c Dictionary allocation. At least a reference should be there.
1.21 crook 11939:
1.78 anton 11940: Forth allows you to forget words (and everything that was alloted in the
11941: dictonary after them) in a LIFO manner.
1.21 crook 11942:
1.78 anton 11943: doc-marker
1.21 crook 11944:
1.78 anton 11945: The most common use of this feature is during progam development: when
11946: you change a source file, forget all the words it defined and load it
11947: again (since you also forget everything defined after the source file
11948: was loaded, you have to reload that, too). Note that effects like
11949: storing to variables and destroyed system words are not undone when you
11950: forget words. With a system like Gforth, that is fast enough at
11951: starting up and compiling, I find it more convenient to exit and restart
11952: Gforth, as this gives me a clean slate.
1.21 crook 11953:
1.78 anton 11954: Here's an example of using @code{marker} at the start of a source file
11955: that you are debugging; it ensures that you only ever have one copy of
11956: the file's definitions compiled at any time:
1.21 crook 11957:
1.78 anton 11958: @example
11959: [IFDEF] my-code
11960: my-code
11961: [ENDIF]
1.26 crook 11962:
1.78 anton 11963: marker my-code
11964: init-included-files
1.21 crook 11965:
1.78 anton 11966: \ .. definitions start here
11967: \ .
11968: \ .
11969: \ end
11970: @end example
1.21 crook 11971:
1.26 crook 11972:
1.78 anton 11973: @node Debugging, Assertions, Forgetting words, Programming Tools
11974: @subsection Debugging
11975: @cindex debugging
1.21 crook 11976:
1.78 anton 11977: Languages with a slow edit/compile/link/test development loop tend to
11978: require sophisticated tracing/stepping debuggers to facilate debugging.
1.21 crook 11979:
1.78 anton 11980: A much better (faster) way in fast-compiling languages is to add
11981: printing code at well-selected places, let the program run, look at
11982: the output, see where things went wrong, add more printing code, etc.,
11983: until the bug is found.
1.21 crook 11984:
1.78 anton 11985: The simple debugging aids provided in @file{debugs.fs}
11986: are meant to support this style of debugging.
1.21 crook 11987:
1.78 anton 11988: The word @code{~~} prints debugging information (by default the source
11989: location and the stack contents). It is easy to insert. If you use Emacs
11990: it is also easy to remove (@kbd{C-x ~} in the Emacs Forth mode to
11991: query-replace them with nothing). The deferred words
1.101 anton 11992: @code{printdebugdata} and @code{.debugline} control the output of
1.78 anton 11993: @code{~~}. The default source location output format works well with
11994: Emacs' compilation mode, so you can step through the program at the
11995: source level using @kbd{C-x `} (the advantage over a stepping debugger
11996: is that you can step in any direction and you know where the crash has
11997: happened or where the strange data has occurred).
1.21 crook 11998:
1.78 anton 11999: doc-~~
12000: doc-printdebugdata
1.101 anton 12001: doc-.debugline
1.203 anton 12002: doc-debug-fid
1.21 crook 12003:
1.106 anton 12004: @cindex filenames in @code{~~} output
12005: @code{~~} (and assertions) will usually print the wrong file name if a
12006: marker is executed in the same file after their occurance. They will
12007: print @samp{*somewhere*} as file name if a marker is executed in the
12008: same file before their occurance.
12009:
12010:
1.78 anton 12011: @node Assertions, Singlestep Debugger, Debugging, Programming Tools
12012: @subsection Assertions
12013: @cindex assertions
1.21 crook 12014:
1.78 anton 12015: It is a good idea to make your programs self-checking, especially if you
12016: make an assumption that may become invalid during maintenance (for
12017: example, that a certain field of a data structure is never zero). Gforth
12018: supports @dfn{assertions} for this purpose. They are used like this:
1.21 crook 12019:
12020: @example
1.78 anton 12021: assert( @i{flag} )
1.26 crook 12022: @end example
12023:
1.78 anton 12024: The code between @code{assert(} and @code{)} should compute a flag, that
12025: should be true if everything is alright and false otherwise. It should
12026: not change anything else on the stack. The overall stack effect of the
12027: assertion is @code{( -- )}. E.g.
1.21 crook 12028:
1.26 crook 12029: @example
1.78 anton 12030: assert( 1 1 + 2 = ) \ what we learn in school
12031: assert( dup 0<> ) \ assert that the top of stack is not zero
12032: assert( false ) \ this code should not be reached
1.21 crook 12033: @end example
12034:
1.78 anton 12035: The need for assertions is different at different times. During
12036: debugging, we want more checking, in production we sometimes care more
12037: for speed. Therefore, assertions can be turned off, i.e., the assertion
12038: becomes a comment. Depending on the importance of an assertion and the
12039: time it takes to check it, you may want to turn off some assertions and
12040: keep others turned on. Gforth provides several levels of assertions for
12041: this purpose:
12042:
12043:
12044: doc-assert0(
12045: doc-assert1(
12046: doc-assert2(
12047: doc-assert3(
12048: doc-assert(
12049: doc-)
1.21 crook 12050:
12051:
1.78 anton 12052: The variable @code{assert-level} specifies the highest assertions that
12053: are turned on. I.e., at the default @code{assert-level} of one,
12054: @code{assert0(} and @code{assert1(} assertions perform checking, while
12055: @code{assert2(} and @code{assert3(} assertions are treated as comments.
1.26 crook 12056:
1.78 anton 12057: The value of @code{assert-level} is evaluated at compile-time, not at
12058: run-time. Therefore you cannot turn assertions on or off at run-time;
12059: you have to set the @code{assert-level} appropriately before compiling a
12060: piece of code. You can compile different pieces of code at different
12061: @code{assert-level}s (e.g., a trusted library at level 1 and
12062: newly-written code at level 3).
1.26 crook 12063:
12064:
1.78 anton 12065: doc-assert-level
1.26 crook 12066:
12067:
1.78 anton 12068: If an assertion fails, a message compatible with Emacs' compilation mode
12069: is produced and the execution is aborted (currently with @code{ABORT"}.
12070: If there is interest, we will introduce a special throw code. But if you
12071: intend to @code{catch} a specific condition, using @code{throw} is
12072: probably more appropriate than an assertion).
1.106 anton 12073:
12074: @cindex filenames in assertion output
12075: Assertions (and @code{~~}) will usually print the wrong file name if a
12076: marker is executed in the same file after their occurance. They will
12077: print @samp{*somewhere*} as file name if a marker is executed in the
12078: same file before their occurance.
1.44 crook 12079:
1.78 anton 12080: Definitions in ANS Forth for these assertion words are provided
12081: in @file{compat/assert.fs}.
1.26 crook 12082:
1.44 crook 12083:
1.78 anton 12084: @node Singlestep Debugger, , Assertions, Programming Tools
12085: @subsection Singlestep Debugger
12086: @cindex singlestep Debugger
12087: @cindex debugging Singlestep
1.44 crook 12088:
1.189 anton 12089: The singlestep debugger works only with the engine @code{gforth-itc}.
1.112 anton 12090:
1.78 anton 12091: When you create a new word there's often the need to check whether it
12092: behaves correctly or not. You can do this by typing @code{dbg
12093: badword}. A debug session might look like this:
1.26 crook 12094:
1.78 anton 12095: @example
12096: : badword 0 DO i . LOOP ; ok
12097: 2 dbg badword
12098: : badword
12099: Scanning code...
1.44 crook 12100:
1.78 anton 12101: Nesting debugger ready!
1.44 crook 12102:
1.78 anton 12103: 400D4738 8049BC4 0 -> [ 2 ] 00002 00000
12104: 400D4740 8049F68 DO -> [ 0 ]
12105: 400D4744 804A0C8 i -> [ 1 ] 00000
12106: 400D4748 400C5E60 . -> 0 [ 0 ]
12107: 400D474C 8049D0C LOOP -> [ 0 ]
12108: 400D4744 804A0C8 i -> [ 1 ] 00001
12109: 400D4748 400C5E60 . -> 1 [ 0 ]
12110: 400D474C 8049D0C LOOP -> [ 0 ]
12111: 400D4758 804B384 ; -> ok
12112: @end example
1.21 crook 12113:
1.78 anton 12114: Each line displayed is one step. You always have to hit return to
12115: execute the next word that is displayed. If you don't want to execute
12116: the next word in a whole, you have to type @kbd{n} for @code{nest}. Here is
12117: an overview what keys are available:
1.44 crook 12118:
1.78 anton 12119: @table @i
1.44 crook 12120:
1.78 anton 12121: @item @key{RET}
12122: Next; Execute the next word.
1.21 crook 12123:
1.78 anton 12124: @item n
12125: Nest; Single step through next word.
1.44 crook 12126:
1.78 anton 12127: @item u
12128: Unnest; Stop debugging and execute rest of word. If we got to this word
12129: with nest, continue debugging with the calling word.
1.44 crook 12130:
1.78 anton 12131: @item d
12132: Done; Stop debugging and execute rest.
1.21 crook 12133:
1.78 anton 12134: @item s
12135: Stop; Abort immediately.
1.44 crook 12136:
1.78 anton 12137: @end table
1.44 crook 12138:
1.78 anton 12139: Debugging large application with this mechanism is very difficult, because
12140: you have to nest very deeply into the program before the interesting part
12141: begins. This takes a lot of time.
1.26 crook 12142:
1.78 anton 12143: To do it more directly put a @code{BREAK:} command into your source code.
12144: When program execution reaches @code{BREAK:} the single step debugger is
12145: invoked and you have all the features described above.
1.44 crook 12146:
1.78 anton 12147: If you have more than one part to debug it is useful to know where the
12148: program has stopped at the moment. You can do this by the
12149: @code{BREAK" string"} command. This behaves like @code{BREAK:} except that
12150: string is typed out when the ``breakpoint'' is reached.
1.44 crook 12151:
1.26 crook 12152:
1.78 anton 12153: doc-dbg
12154: doc-break:
12155: doc-break"
1.44 crook 12156:
1.150 anton 12157: @c ------------------------------------------------------------
12158: @node C Interface, Assembler and Code Words, Programming Tools, Words
12159: @section C Interface
12160: @cindex C interface
12161: @cindex foreign language interface
12162: @cindex interface to C functions
12163:
1.178 anton 12164: Note that the C interface is not yet complete; callbacks are missing,
12165: as well as a way of declaring structs, unions, and their fields.
1.150 anton 12166:
12167: @menu
12168: * Calling C Functions::
12169: * Declaring C Functions::
1.180 anton 12170: * Calling C function pointers::
1.196 anton 12171: * Defining library interfaces::
12172: * Declaring OS-level libraries::
1.150 anton 12173: * Callbacks::
1.178 anton 12174: * C interface internals::
1.155 anton 12175: * Low-Level C Interface Words::
1.150 anton 12176: @end menu
12177:
1.151 pazsan 12178: @node Calling C Functions, Declaring C Functions, C Interface, C Interface
1.150 anton 12179: @subsection Calling C functions
1.155 anton 12180: @cindex C functions, calls to
12181: @cindex calling C functions
1.150 anton 12182:
1.151 pazsan 12183: Once a C function is declared (see @pxref{Declaring C Functions}), you
1.150 anton 12184: can call it as follows: You push the arguments on the stack(s), and
12185: then call the word for the C function. The arguments have to be
12186: pushed in the same order as the arguments appear in the C
12187: documentation (i.e., the first argument is deepest on the stack).
12188: Integer and pointer arguments have to be pushed on the data stack,
12189: floating-point arguments on the FP stack; these arguments are consumed
1.155 anton 12190: by the called C function.
1.150 anton 12191:
1.155 anton 12192: On returning from the C function, the return value, if any, resides on
12193: the appropriate stack: an integer return value is pushed on the data
12194: stack, an FP return value on the FP stack, and a void return value
12195: results in not pushing anything. Note that most C functions have a
12196: return value, even if that is often not used in C; in Forth, you have
12197: to @code{drop} this return value explicitly if you do not use it.
1.150 anton 12198:
1.177 anton 12199: The C interface automatically converts between the C type and the
12200: Forth type as necessary, on a best-effort basis (in some cases, there
12201: may be some loss).
1.150 anton 12202:
12203: As an example, consider the POSIX function @code{lseek()}:
12204:
12205: @example
12206: off_t lseek(int fd, off_t offset, int whence);
12207: @end example
12208:
12209: This function takes three integer arguments, and returns an integer
12210: argument, so a Forth call for setting the current file offset to the
12211: start of the file could look like this:
12212:
12213: @example
12214: fd @@ 0 SEEK_SET lseek -1 = if
12215: ... \ error handling
12216: then
12217: @end example
12218:
12219: You might be worried that an @code{off_t} does not fit into a cell, so
12220: you could not pass larger offsets to lseek, and might get only a part
1.155 anton 12221: of the return values. In that case, in your declaration of the
12222: function (@pxref{Declaring C Functions}) you should declare it to use
12223: double-cells for the off_t argument and return value, and maybe give
12224: the resulting Forth word a different name, like @code{dlseek}; the
12225: result could be called like this:
1.150 anton 12226:
12227: @example
12228: fd @@ 0. SEEK_SET dlseek -1. d= if
12229: ... \ error handling
12230: then
12231: @end example
12232:
12233: Passing and returning structs or unions is currently not supported by
12234: our interface@footnote{If you know the calling convention of your C
12235: compiler, you usually can call such functions in some way, but that
12236: way is usually not portable between platforms, and sometimes not even
12237: between C compilers.}.
12238:
1.177 anton 12239: Calling functions with a variable number of arguments (@emph{variadic}
12240: functions, e.g., @code{printf()}) is only supported by having you
12241: declare one function-calling word for each argument pattern, and
12242: calling the appropriate word for the desired pattern.
12243:
1.150 anton 12244:
1.155 anton 12245:
1.180 anton 12246: @node Declaring C Functions, Calling C function pointers, Calling C Functions, C Interface
1.150 anton 12247: @subsection Declaring C Functions
1.155 anton 12248: @cindex C functions, declarations
12249: @cindex declaring C functions
1.150 anton 12250:
12251: Before you can call @code{lseek} or @code{dlseek}, you have to declare
1.177 anton 12252: it. The declaration consists of two parts:
12253:
12254: @table @b
12255:
12256: @item The C part
1.179 anton 12257: is the C declaration of the function, or more typically and portably,
12258: a C-style @code{#include} of a file that contains the declaration of
12259: the C function.
1.177 anton 12260:
12261: @item The Forth part
12262: declares the Forth types of the parameters and the Forth word name
12263: corresponding to the C function.
12264:
12265: @end table
12266:
12267: For the words @code{lseek} and @code{dlseek} mentioned earlier, the
12268: declarations are:
12269:
12270: @example
12271: \c #define _FILE_OFFSET_BITS 64
12272: \c #include <sys/types.h>
12273: \c #include <unistd.h>
12274: c-function lseek lseek n n n -- n
12275: c-function dlseek lseek n d n -- d
12276: @end example
12277:
1.178 anton 12278: The C part of the declarations is prefixed by @code{\c}, and the rest
1.177 anton 12279: of the line is ordinary C code. You can use as many lines of C
12280: declarations as you like, and they are visible for all further
12281: function declarations.
12282:
12283: The Forth part declares each interface word with @code{c-function},
12284: followed by the Forth name of the word, the C name of the called
12285: function, and the stack effect of the word. The stack effect contains
1.178 anton 12286: an arbitrary number of types of parameters, then @code{--}, and then
1.177 anton 12287: exactly one type for the return value. The possible types are:
12288:
12289: @table @code
12290:
12291: @item n
12292: single-cell integer
12293:
12294: @item a
12295: address (single-cell)
12296:
12297: @item d
12298: double-cell integer
12299:
12300: @item r
12301: floating-point value
12302:
12303: @item func
12304: C function pointer
12305:
12306: @item void
12307: no value (used as return type for void functions)
12308:
12309: @end table
12310:
12311: @cindex variadic C functions
12312:
12313: To deal with variadic C functions, you can declare one Forth word for
12314: every pattern you want to use, e.g.:
12315:
12316: @example
12317: \c #include <stdio.h>
12318: c-function printf-nr printf a n r -- n
12319: c-function printf-rn printf a r n -- n
12320: @end example
12321:
12322: Note that with C functions declared as variadic (or if you don't
12323: provide a prototype), the C interface has no C type to convert to, so
12324: no automatic conversion happens, which may lead to portability
12325: problems in some cases. In such cases you can perform the conversion
12326: explicitly on the C level, e.g., as follows:
12327:
12328: @example
1.178 anton 12329: \c #define printfll(s,ll) printf(s,(long long)ll)
12330: c-function printfll printfll a n -- n
1.177 anton 12331: @end example
12332:
12333: Here, instead of calling @code{printf()} directly, we define a macro
1.178 anton 12334: that casts (converts) the Forth single-cell integer into a
12335: C @code{long long} before calling @code{printf()}.
1.177 anton 12336:
12337: doc-\c
12338: doc-c-function
1.207 pazsan 12339: doc-c-value
12340: doc-c-variable
1.177 anton 12341:
12342: In order to work, this C interface invokes GCC at run-time and uses
1.178 anton 12343: dynamic linking. If these features are not available, there are
12344: other, less convenient and less portable C interfaces in @file{lib.fs}
12345: and @file{oldlib.fs}. These interfaces are mostly undocumented and
12346: mostly incompatible with each other and with the documented C
12347: interface; you can find some examples for the @file{lib.fs} interface
12348: in @file{lib.fs}.
1.177 anton 12349:
12350:
1.196 anton 12351: @node Calling C function pointers, Defining library interfaces, Declaring C Functions, C Interface
1.180 anton 12352: @subsection Calling C function pointers from Forth
12353: @cindex C function pointers, calling from Forth
1.177 anton 12354:
1.180 anton 12355: If you come across a C function pointer (e.g., in some C-constructed
12356: structure) and want to call it from your Forth program, you can also
12357: use the features explained until now to achieve that, as follows:
1.150 anton 12358:
1.180 anton 12359: Let us assume that there is a C function pointer type @code{func1}
12360: defined in some header file @file{func1.h}, and you know that these
12361: functions take one integer argument and return an integer result; and
12362: you want to call functions through such pointers. Just define
1.155 anton 12363:
1.180 anton 12364: @example
12365: \c #include <func1.h>
12366: \c #define call_func1(par1,fptr) ((func1)fptr)(par1)
12367: c-function call-func1 call_func1 n func -- n
12368: @end example
12369:
12370: and then you can call a function pointed to by, say @code{func1a} as
12371: follows:
12372:
12373: @example
12374: -5 func1a call-func1 .
12375: @end example
12376:
12377: In the C part, @code{call_func} is defined as a macro to avoid having
12378: to declare the exact parameter and return types, so the C compiler
12379: knows them from the declaration of @code{func1}.
12380:
12381: The Forth word @code{call-func1} is similar to @code{execute}, except
12382: that it takes a C @code{func1} pointer instead of a Forth execution
12383: token, and it is specific to @code{func1} pointers. For each type of
12384: function pointer you want to call from Forth, you have to define
12385: a separate calling word.
12386:
12387:
1.196 anton 12388: @node Defining library interfaces, Declaring OS-level libraries, Calling C function pointers, C Interface
12389: @subsection Defining library interfaces
12390: @cindex giving a name to a library interface
12391: @cindex library interface names
12392:
12393: You can give a name to a bunch of C function declarations (a library
12394: interface), as follows:
12395:
12396: @example
12397: c-library lseek-lib
12398: \c #define _FILE_OFFSET_BITS 64
12399: ...
12400: end-c-library
12401: @end example
12402:
1.202 anton 12403: The effect of giving such a name to the interface is that the names of
12404: the generated files will contain that name, and when you use the
12405: interface a second time, it will use the existing files instead of
12406: generating and compiling them again, saving you time. Note that even
12407: if you change the declarations, the old (stale) files will be used,
12408: probably leading to errors. So, during development of the
12409: declarations we recommend not using @code{c-library}. Normally these
12410: files are cached in @file{$HOME/.gforth/libcc-named}, so by deleting
12411: that directory you can get rid of stale files.
12412:
12413: Note that you should use @code{c-library} before everything else
12414: having anything to do with that library, as it resets some setup
12415: stuff. The idea is that the typical use is to put each
12416: @code{c-library}...@code{end-library} unit in its own file, and to be
12417: able to include these files in any order.
1.196 anton 12418:
12419: Note that the library name is not allocated in the dictionary and
12420: therefore does not shadow dictionary names. It is used in the file
12421: system, so you have to use naming conventions appropriate for file
12422: systems. Also, you must not call a function you declare after
12423: @code{c-library} before you perform @code{end-c-library}.
12424:
12425: A major benefit of these named library interfaces is that, once they
12426: are generated, the tools used to generated them (in particular, the C
12427: compiler and libtool) are no longer needed, so the interface can be
12428: used even on machines that do not have the tools installed.
12429:
12430: doc-c-library-name
12431: doc-c-library
12432: doc-end-c-library
12433:
12434:
12435: @node Declaring OS-level libraries, Callbacks, Defining library interfaces, C Interface
12436: @subsection Declaring OS-level libraries
1.195 anton 12437: @cindex Shared libraries in C interface
12438: @cindex Dynamically linked libraries in C interface
12439: @cindex Libraries in C interface
12440:
1.196 anton 12441: For calling some C functions, you need to link with a specific
12442: OS-level library that contains that function. E.g., the @code{sin}
12443: function requires linking a special library by using the command line
12444: switch @code{-lm}. In our C iterface you do the equivalent thing by
12445: calling @code{add-lib} as follows:
1.195 anton 12446:
12447: @example
12448: clear-libs
12449: s" m" add-lib
12450: \c #include <math.h>
12451: c-function sin sin r -- r
12452: @end example
12453:
12454: First, you clear any libraries that may have been declared earlier
12455: (you don't need them for @code{sin}); then you add the @code{m}
12456: library (actually @code{libm.so} or somesuch) to the currently
12457: declared libraries; you can add as many as you need. Finally you
12458: declare the function as shown above. Typically you will use the same
12459: set of library declarations for many function declarations; you need
12460: to write only one set for that, right at the beginning.
12461:
1.196 anton 12462: Note that you must not call @code{clear-libs} inside
12463: @code{c-library...end-c-library}; however, @code{c-library} performs
12464: the function of @code{clear-libs}, so @code{clear-libs} is not
12465: necessary, and you usually want to put @code{add-lib} calls inside
12466: @code{c-library...end-c-library}.
12467:
1.195 anton 12468: doc-clear-libs
12469: doc-add-lib
12470:
12471:
1.196 anton 12472: @node Callbacks, C interface internals, Declaring OS-level libraries, C Interface
1.150 anton 12473: @subsection Callbacks
1.155 anton 12474: @cindex Callback functions written in Forth
12475: @cindex C function pointers to Forth words
12476:
1.177 anton 12477: Callbacks are not yet supported by the documented C interface. You
12478: can use the undocumented @file{lib.fs} interface for callbacks.
12479:
1.155 anton 12480: In some cases you have to pass a function pointer to a C function,
12481: i.e., the library wants to call back to your application (and the
12482: pointed-to function is called a callback function). You can pass the
12483: address of an existing C function (that you get with @code{lib-sym},
12484: @pxref{Low-Level C Interface Words}), but if there is no appropriate C
12485: function, you probably want to define the function as a Forth word.
12486:
12487: @c I don't understand the existing callback interface from the example - anton
12488:
1.165 anton 12489:
12490: @c > > Und dann gibt's noch die fptr-Deklaration, die einem
12491: @c > > C-Funktionspointer entspricht (Deklaration gleich wie bei
12492: @c > > Library-Funktionen, nur ohne den C-Namen, Aufruf mit der
12493: @c > > C-Funktionsadresse auf dem TOS).
12494: @c >
12495: @c > Ja, da bin ich dann ausgestiegen, weil ich aus dem Beispiel nicht
12496: @c > gesehen habe, wozu das gut ist.
12497: @c
12498: @c Irgendwie muss ich den Callback ja testen. Und es soll ja auch
12499: @c vorkommen, dass man von irgendwelchen kranken Interfaces einen
12500: @c Funktionspointer übergeben bekommt, den man dann bei Gelegenheit
12501: @c aufrufen muss. Also kann man den deklarieren, und das damit deklarierte
12502: @c Wort verhält sich dann wie ein EXECUTE für alle C-Funktionen mit
12503: @c demselben Prototyp.
12504:
12505:
1.178 anton 12506: @node C interface internals, Low-Level C Interface Words, Callbacks, C Interface
1.177 anton 12507: @subsection How the C interface works
12508:
12509: The documented C interface works by generating a C code out of the
12510: declarations.
12511:
12512: In particular, for every Forth word declared with @code{c-function},
12513: it generates a wrapper function in C that takes the Forth data from
12514: the Forth stacks, and calls the target C function with these data as
12515: arguments. The C compiler then performs an implicit conversion
12516: between the Forth type from the stack, and the C type for the
12517: parameter, which is given by the C function prototype. After the C
12518: function returns, the return value is likewise implicitly converted to
12519: a Forth type and written back on the stack.
12520:
12521: The @code{\c} lines are literally included in the C code (but without
12522: the @code{\c}), and provide the necessary declarations so that the C
12523: compiler knows the C types and has enough information to perform the
12524: conversion.
12525:
12526: These wrapper functions are eventually compiled and dynamically linked
12527: into Gforth, and then they can be called.
12528:
1.195 anton 12529: The libraries added with @code{add-lib} are used in the compile
12530: command line to specify dependent libraries with @code{-l@var{lib}},
12531: causing these libraries to be dynamically linked when the wrapper
12532: function is linked.
12533:
1.177 anton 12534:
1.178 anton 12535: @node Low-Level C Interface Words, , C interface internals, C Interface
1.155 anton 12536: @subsection Low-Level C Interface Words
1.44 crook 12537:
1.155 anton 12538: doc-open-lib
12539: doc-lib-sym
1.196 anton 12540: doc-lib-error
1.177 anton 12541: doc-call-c
1.26 crook 12542:
1.78 anton 12543: @c -------------------------------------------------------------
1.150 anton 12544: @node Assembler and Code Words, Threading Words, C Interface, Words
1.78 anton 12545: @section Assembler and Code Words
12546: @cindex assembler
12547: @cindex code words
1.44 crook 12548:
1.78 anton 12549: @menu
12550: * Code and ;code::
12551: * Common Assembler:: Assembler Syntax
12552: * Common Disassembler::
12553: * 386 Assembler:: Deviations and special cases
12554: * Alpha Assembler:: Deviations and special cases
12555: * MIPS assembler:: Deviations and special cases
1.161 anton 12556: * PowerPC assembler:: Deviations and special cases
1.193 dvdkhlng 12557: * ARM Assembler:: Deviations and special cases
1.78 anton 12558: * Other assemblers:: How to write them
12559: @end menu
1.21 crook 12560:
1.78 anton 12561: @node Code and ;code, Common Assembler, Assembler and Code Words, Assembler and Code Words
12562: @subsection @code{Code} and @code{;code}
1.26 crook 12563:
1.78 anton 12564: Gforth provides some words for defining primitives (words written in
12565: machine code), and for defining the machine-code equivalent of
12566: @code{DOES>}-based defining words. However, the machine-independent
12567: nature of Gforth poses a few problems: First of all, Gforth runs on
12568: several architectures, so it can provide no standard assembler. What's
12569: worse is that the register allocation not only depends on the processor,
12570: but also on the @code{gcc} version and options used.
1.44 crook 12571:
1.78 anton 12572: The words that Gforth offers encapsulate some system dependences (e.g.,
12573: the header structure), so a system-independent assembler may be used in
12574: Gforth. If you do not have an assembler, you can compile machine code
12575: directly with @code{,} and @code{c,}@footnote{This isn't portable,
12576: because these words emit stuff in @i{data} space; it works because
12577: Gforth has unified code/data spaces. Assembler isn't likely to be
12578: portable anyway.}.
1.21 crook 12579:
1.44 crook 12580:
1.78 anton 12581: doc-assembler
12582: doc-init-asm
12583: doc-code
12584: doc-end-code
12585: doc-;code
12586: doc-flush-icache
1.44 crook 12587:
1.21 crook 12588:
1.78 anton 12589: If @code{flush-icache} does not work correctly, @code{code} words
12590: etc. will not work (reliably), either.
1.44 crook 12591:
1.78 anton 12592: The typical usage of these @code{code} words can be shown most easily by
12593: analogy to the equivalent high-level defining words:
1.44 crook 12594:
1.78 anton 12595: @example
12596: : foo code foo
12597: <high-level Forth words> <assembler>
12598: ; end-code
12599:
12600: : bar : bar
12601: <high-level Forth words> <high-level Forth words>
12602: CREATE CREATE
12603: <high-level Forth words> <high-level Forth words>
12604: DOES> ;code
12605: <high-level Forth words> <assembler>
12606: ; end-code
12607: @end example
1.21 crook 12608:
1.78 anton 12609: @c anton: the following stuff is also in "Common Assembler", in less detail.
1.44 crook 12610:
1.78 anton 12611: @cindex registers of the inner interpreter
12612: In the assembly code you will want to refer to the inner interpreter's
12613: registers (e.g., the data stack pointer) and you may want to use other
12614: registers for temporary storage. Unfortunately, the register allocation
12615: is installation-dependent.
1.44 crook 12616:
1.78 anton 12617: In particular, @code{ip} (Forth instruction pointer) and @code{rp}
1.100 anton 12618: (return stack pointer) may be in different places in @code{gforth} and
12619: @code{gforth-fast}, or different installations. This means that you
12620: cannot write a @code{NEXT} routine that works reliably on both versions
12621: or different installations; so for doing @code{NEXT}, I recommend
12622: jumping to @code{' noop >code-address}, which contains nothing but a
12623: @code{NEXT}.
1.21 crook 12624:
1.78 anton 12625: For general accesses to the inner interpreter's registers, the easiest
12626: solution is to use explicit register declarations (@pxref{Explicit Reg
12627: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) for
12628: all of the inner interpreter's registers: You have to compile Gforth
12629: with @code{-DFORCE_REG} (configure option @code{--enable-force-reg}) and
12630: the appropriate declarations must be present in the @code{machine.h}
12631: file (see @code{mips.h} for an example; you can find a full list of all
12632: declarable register symbols with @code{grep register engine.c}). If you
12633: give explicit registers to all variables that are declared at the
12634: beginning of @code{engine()}, you should be able to use the other
12635: caller-saved registers for temporary storage. Alternatively, you can use
12636: the @code{gcc} option @code{-ffixed-REG} (@pxref{Code Gen Options, ,
12637: Options for Code Generation Conventions, gcc.info, GNU C Manual}) to
12638: reserve a register (however, this restriction on register allocation may
12639: slow Gforth significantly).
1.44 crook 12640:
1.78 anton 12641: If this solution is not viable (e.g., because @code{gcc} does not allow
12642: you to explicitly declare all the registers you need), you have to find
12643: out by looking at the code where the inner interpreter's registers
12644: reside and which registers can be used for temporary storage. You can
12645: get an assembly listing of the engine's code with @code{make engine.s}.
1.44 crook 12646:
1.78 anton 12647: In any case, it is good practice to abstract your assembly code from the
12648: actual register allocation. E.g., if the data stack pointer resides in
12649: register @code{$17}, create an alias for this register called @code{sp},
12650: and use that in your assembly code.
1.21 crook 12651:
1.78 anton 12652: @cindex code words, portable
12653: Another option for implementing normal and defining words efficiently
12654: is to add the desired functionality to the source of Gforth. For normal
12655: words you just have to edit @file{primitives} (@pxref{Automatic
12656: Generation}). Defining words (equivalent to @code{;CODE} words, for fast
12657: defined words) may require changes in @file{engine.c}, @file{kernel.fs},
12658: @file{prims2x.fs}, and possibly @file{cross.fs}.
1.44 crook 12659:
1.78 anton 12660: @node Common Assembler, Common Disassembler, Code and ;code, Assembler and Code Words
12661: @subsection Common Assembler
1.44 crook 12662:
1.78 anton 12663: The assemblers in Gforth generally use a postfix syntax, i.e., the
12664: instruction name follows the operands.
1.21 crook 12665:
1.78 anton 12666: The operands are passed in the usual order (the same that is used in the
12667: manual of the architecture). Since they all are Forth words, they have
12668: to be separated by spaces; you can also use Forth words to compute the
12669: operands.
1.44 crook 12670:
1.78 anton 12671: The instruction names usually end with a @code{,}. This makes it easier
12672: to visually separate instructions if you put several of them on one
12673: line; it also avoids shadowing other Forth words (e.g., @code{and}).
1.21 crook 12674:
1.78 anton 12675: Registers are usually specified by number; e.g., (decimal) @code{11}
12676: specifies registers R11 and F11 on the Alpha architecture (which one,
12677: depends on the instruction). The usual names are also available, e.g.,
12678: @code{s2} for R11 on Alpha.
1.21 crook 12679:
1.78 anton 12680: Control flow is specified similar to normal Forth code (@pxref{Arbitrary
12681: control structures}), with @code{if,}, @code{ahead,}, @code{then,},
12682: @code{begin,}, @code{until,}, @code{again,}, @code{cs-roll},
12683: @code{cs-pick}, @code{else,}, @code{while,}, and @code{repeat,}. The
12684: conditions are specified in a way specific to each assembler.
1.1 anton 12685:
1.78 anton 12686: Note that the register assignments of the Gforth engine can change
12687: between Gforth versions, or even between different compilations of the
12688: same Gforth version (e.g., if you use a different GCC version). So if
12689: you want to refer to Gforth's registers (e.g., the stack pointer or
12690: TOS), I recommend defining your own words for refering to these
12691: registers, and using them later on; then you can easily adapt to a
12692: changed register assignment. The stability of the register assignment
12693: is usually better if you build Gforth with @code{--enable-force-reg}.
1.1 anton 12694:
1.100 anton 12695: The most common use of these registers is to dispatch to the next word
12696: (the @code{next} routine). A portable way to do this is to jump to
12697: @code{' noop >code-address} (of course, this is less efficient than
12698: integrating the @code{next} code and scheduling it well).
1.1 anton 12699:
1.96 anton 12700: Another difference between Gforth version is that the top of stack is
12701: kept in memory in @code{gforth} and, on most platforms, in a register in
12702: @code{gforth-fast}.
12703:
1.78 anton 12704: @node Common Disassembler, 386 Assembler, Common Assembler, Assembler and Code Words
12705: @subsection Common Disassembler
1.127 anton 12706: @cindex disassembler, general
12707: @cindex gdb disassembler
1.1 anton 12708:
1.78 anton 12709: You can disassemble a @code{code} word with @code{see}
12710: (@pxref{Debugging}). You can disassemble a section of memory with
1.1 anton 12711:
1.127 anton 12712: doc-discode
1.44 crook 12713:
1.127 anton 12714: There are two kinds of disassembler for Gforth: The Forth disassembler
12715: (available on some CPUs) and the gdb disassembler (available on
12716: platforms with @command{gdb} and @command{mktemp}). If both are
12717: available, the Forth disassembler is used by default. If you prefer
12718: the gdb disassembler, say
12719:
12720: @example
12721: ' disasm-gdb is discode
12722: @end example
12723:
12724: If neither is available, @code{discode} performs @code{dump}.
12725:
12726: The Forth disassembler generally produces output that can be fed into the
1.78 anton 12727: assembler (i.e., same syntax, etc.). It also includes additional
12728: information in comments. In particular, the address of the instruction
12729: is given in a comment before the instruction.
1.1 anton 12730:
1.127 anton 12731: The gdb disassembler produces output in the same format as the gdb
12732: @code{disassemble} command (@pxref{Machine Code,,Source and machine
12733: code,gdb,Debugging with GDB}), in the default flavour (AT&T syntax for
12734: the 386 and AMD64 architectures).
12735:
1.78 anton 12736: @code{See} may display more or less than the actual code of the word,
12737: because the recognition of the end of the code is unreliable. You can
1.127 anton 12738: use @code{discode} if it did not display enough. It may display more, if
1.78 anton 12739: the code word is not immediately followed by a named word. If you have
1.116 anton 12740: something else there, you can follow the word with @code{align latest ,}
1.78 anton 12741: to ensure that the end is recognized.
1.21 crook 12742:
1.78 anton 12743: @node 386 Assembler, Alpha Assembler, Common Disassembler, Assembler and Code Words
12744: @subsection 386 Assembler
1.44 crook 12745:
1.78 anton 12746: The 386 assembler included in Gforth was written by Bernd Paysan, it's
12747: available under GPL, and originally part of bigFORTH.
1.21 crook 12748:
1.78 anton 12749: The 386 disassembler included in Gforth was written by Andrew McKewan
12750: and is in the public domain.
1.21 crook 12751:
1.91 anton 12752: The disassembler displays code in an Intel-like prefix syntax.
1.21 crook 12753:
1.78 anton 12754: The assembler uses a postfix syntax with reversed parameters.
1.1 anton 12755:
1.78 anton 12756: The assembler includes all instruction of the Athlon, i.e. 486 core
12757: instructions, Pentium and PPro extensions, floating point, MMX, 3Dnow!,
12758: but not ISSE. It's an integrated 16- and 32-bit assembler. Default is 32
12759: bit, you can switch to 16 bit with .86 and back to 32 bit with .386.
1.1 anton 12760:
1.78 anton 12761: There are several prefixes to switch between different operation sizes,
12762: @code{.b} for byte accesses, @code{.w} for word accesses, @code{.d} for
12763: double-word accesses. Addressing modes can be switched with @code{.wa}
12764: for 16 bit addresses, and @code{.da} for 32 bit addresses. You don't
12765: need a prefix for byte register names (@code{AL} et al).
1.1 anton 12766:
1.78 anton 12767: For floating point operations, the prefixes are @code{.fs} (IEEE
12768: single), @code{.fl} (IEEE double), @code{.fx} (extended), @code{.fw}
12769: (word), @code{.fd} (double-word), and @code{.fq} (quad-word).
1.21 crook 12770:
1.78 anton 12771: The MMX opcodes don't have size prefixes, they are spelled out like in
12772: the Intel assembler. Instead of move from and to memory, there are
12773: PLDQ/PLDD and PSTQ/PSTD.
1.21 crook 12774:
1.78 anton 12775: The registers lack the 'e' prefix; even in 32 bit mode, eax is called
12776: ax. Immediate values are indicated by postfixing them with @code{#},
1.91 anton 12777: e.g., @code{3 #}. Here are some examples of addressing modes in various
12778: syntaxes:
1.21 crook 12779:
1.26 crook 12780: @example
1.91 anton 12781: Gforth Intel (NASM) AT&T (gas) Name
12782: .w ax ax %ax register (16 bit)
12783: ax eax %eax register (32 bit)
12784: 3 # offset 3 $3 immediate
12785: 1000 #) byte ptr 1000 1000 displacement
12786: bx ) [ebx] (%ebx) base
12787: 100 di d) 100[edi] 100(%edi) base+displacement
12788: 20 ax *4 i#) 20[eax*4] 20(,%eax,4) (index*scale)+displacement
12789: di ax *4 i) [edi][eax*4] (%edi,%eax,4) base+(index*scale)
12790: 4 bx cx di) 4[ebx][ecx] 4(%ebx,%ecx) base+index+displacement
12791: 12 sp ax *2 di) 12[esp][eax*2] 12(%esp,%eax,2) base+(index*scale)+displacement
12792: @end example
12793:
12794: You can use @code{L)} and @code{LI)} instead of @code{D)} and
12795: @code{DI)} to enforce 32-bit displacement fields (useful for
12796: later patching).
1.21 crook 12797:
1.78 anton 12798: Some example of instructions are:
1.1 anton 12799:
12800: @example
1.78 anton 12801: ax bx mov \ move ebx,eax
12802: 3 # ax mov \ mov eax,3
1.137 pazsan 12803: 100 di d) ax mov \ mov eax,100[edi]
1.78 anton 12804: 4 bx cx di) ax mov \ mov eax,4[ebx][ecx]
12805: .w ax bx mov \ mov bx,ax
1.1 anton 12806: @end example
12807:
1.78 anton 12808: The following forms are supported for binary instructions:
1.1 anton 12809:
12810: @example
1.78 anton 12811: <reg> <reg> <inst>
12812: <n> # <reg> <inst>
12813: <mem> <reg> <inst>
12814: <reg> <mem> <inst>
1.136 pazsan 12815: <n> # <mem> <inst>
1.1 anton 12816: @end example
12817:
1.136 pazsan 12818: The shift/rotate syntax is:
1.1 anton 12819:
1.26 crook 12820: @example
1.78 anton 12821: <reg/mem> 1 # shl \ shortens to shift without immediate
12822: <reg/mem> 4 # shl
12823: <reg/mem> cl shl
1.26 crook 12824: @end example
1.1 anton 12825:
1.78 anton 12826: Precede string instructions (@code{movs} etc.) with @code{.b} to get
12827: the byte version.
1.1 anton 12828:
1.78 anton 12829: The control structure words @code{IF} @code{UNTIL} etc. must be preceded
12830: by one of these conditions: @code{vs vc u< u>= 0= 0<> u<= u> 0< 0>= ps
12831: pc < >= <= >}. (Note that most of these words shadow some Forth words
12832: when @code{assembler} is in front of @code{forth} in the search path,
12833: e.g., in @code{code} words). Currently the control structure words use
12834: one stack item, so you have to use @code{roll} instead of @code{cs-roll}
12835: to shuffle them (you can also use @code{swap} etc.).
1.21 crook 12836:
1.78 anton 12837: Here is an example of a @code{code} word (assumes that the stack pointer
12838: is in esi and the TOS is in ebx):
1.21 crook 12839:
1.26 crook 12840: @example
1.78 anton 12841: code my+ ( n1 n2 -- n )
12842: 4 si D) bx add
12843: 4 # si add
12844: Next
12845: end-code
1.26 crook 12846: @end example
1.21 crook 12847:
1.161 anton 12848:
1.78 anton 12849: @node Alpha Assembler, MIPS assembler, 386 Assembler, Assembler and Code Words
12850: @subsection Alpha Assembler
1.21 crook 12851:
1.78 anton 12852: The Alpha assembler and disassembler were originally written by Bernd
12853: Thallner.
1.26 crook 12854:
1.78 anton 12855: The register names @code{a0}--@code{a5} are not available to avoid
12856: shadowing hex numbers.
1.2 jwilke 12857:
1.78 anton 12858: Immediate forms of arithmetic instructions are distinguished by a
12859: @code{#} just before the @code{,}, e.g., @code{and#,} (note: @code{lda,}
12860: does not count as arithmetic instruction).
1.2 jwilke 12861:
1.78 anton 12862: You have to specify all operands to an instruction, even those that
12863: other assemblers consider optional, e.g., the destination register for
12864: @code{br,}, or the destination register and hint for @code{jmp,}.
1.2 jwilke 12865:
1.78 anton 12866: You can specify conditions for @code{if,} by removing the first @code{b}
12867: and the trailing @code{,} from a branch with a corresponding name; e.g.,
1.2 jwilke 12868:
1.26 crook 12869: @example
1.78 anton 12870: 11 fgt if, \ if F11>0e
12871: ...
12872: endif,
1.26 crook 12873: @end example
1.2 jwilke 12874:
1.78 anton 12875: @code{fbgt,} gives @code{fgt}.
12876:
1.161 anton 12877: @node MIPS assembler, PowerPC assembler, Alpha Assembler, Assembler and Code Words
1.78 anton 12878: @subsection MIPS assembler
1.2 jwilke 12879:
1.78 anton 12880: The MIPS assembler was originally written by Christian Pirker.
1.2 jwilke 12881:
1.78 anton 12882: Currently the assembler and disassembler only cover the MIPS-I
12883: architecture (R3000), and don't support FP instructions.
1.2 jwilke 12884:
1.78 anton 12885: The register names @code{$a0}--@code{$a3} are not available to avoid
12886: shadowing hex numbers.
1.2 jwilke 12887:
1.78 anton 12888: Because there is no way to distinguish registers from immediate values,
12889: you have to explicitly use the immediate forms of instructions, i.e.,
12890: @code{addiu,}, not just @code{addu,} (@command{as} does this
12891: implicitly).
1.2 jwilke 12892:
1.78 anton 12893: If the architecture manual specifies several formats for the instruction
12894: (e.g., for @code{jalr,}), you usually have to use the one with more
12895: arguments (i.e., two for @code{jalr,}). When in doubt, see
12896: @code{arch/mips/testasm.fs} for an example of correct use.
1.2 jwilke 12897:
1.78 anton 12898: Branches and jumps in the MIPS architecture have a delay slot. You have
12899: to fill it yourself (the simplest way is to use @code{nop,}), the
12900: assembler does not do it for you (unlike @command{as}). Even
12901: @code{if,}, @code{ahead,}, @code{until,}, @code{again,}, @code{while,},
12902: @code{else,} and @code{repeat,} need a delay slot. Since @code{begin,}
12903: and @code{then,} just specify branch targets, they are not affected.
1.2 jwilke 12904:
1.78 anton 12905: Note that you must not put branches, jumps, or @code{li,} into the delay
12906: slot: @code{li,} may expand to several instructions, and control flow
12907: instructions may not be put into the branch delay slot in any case.
1.2 jwilke 12908:
1.78 anton 12909: For branches the argument specifying the target is a relative address;
12910: You have to add the address of the delay slot to get the absolute
12911: address.
1.1 anton 12912:
1.78 anton 12913: The MIPS architecture also has load delay slots and restrictions on
12914: using @code{mfhi,} and @code{mflo,}; you have to order the instructions
12915: yourself to satisfy these restrictions, the assembler does not do it for
12916: you.
1.1 anton 12917:
1.78 anton 12918: You can specify the conditions for @code{if,} etc. by taking a
12919: conditional branch and leaving away the @code{b} at the start and the
12920: @code{,} at the end. E.g.,
1.1 anton 12921:
1.26 crook 12922: @example
1.78 anton 12923: 4 5 eq if,
12924: ... \ do something if $4 equals $5
12925: then,
1.26 crook 12926: @end example
1.1 anton 12927:
1.161 anton 12928:
1.193 dvdkhlng 12929: @node PowerPC assembler, ARM Assembler, MIPS assembler, Assembler and Code Words
1.161 anton 12930: @subsection PowerPC assembler
12931:
1.162 anton 12932: The PowerPC assembler and disassembler were contributed by Michal
1.161 anton 12933: Revucky.
12934:
1.162 anton 12935: This assembler does not follow the convention of ending mnemonic names
12936: with a ``,'', so some mnemonic names shadow regular Forth words (in
12937: particular: @code{and or xor fabs}); so if you want to use the Forth
12938: words, you have to make them visible first, e.g., with @code{also
12939: forth}.
12940:
1.161 anton 12941: Registers are referred to by their number, e.g., @code{9} means the
12942: integer register 9 or the FP register 9 (depending on the
12943: instruction).
12944:
12945: Because there is no way to distinguish registers from immediate values,
12946: you have to explicitly use the immediate forms of instructions, i.e.,
1.162 anton 12947: @code{addi,}, not just @code{add,}.
1.161 anton 12948:
1.162 anton 12949: The assembler and disassembler usually support the most general form
1.161 anton 12950: of an instruction, but usually not the shorter forms (especially for
12951: branches).
12952:
12953:
1.193 dvdkhlng 12954: @node ARM Assembler, Other assemblers, PowerPC assembler, Assembler and Code Words
12955: @subsection ARM Assembler
1.161 anton 12956:
1.193 dvdkhlng 12957: The ARM assembler included in Gforth was written from scratch by David
12958: Kuehling.
12959:
12960: The assembler includes all instruction of ARM architecture version 4,
12961: but does not (yet) have support for Thumb instructions. It also lacks
12962: support for any co-processors.
12963:
12964: The assembler uses a postfix syntax with the target operand specified
12965: last. For load/store instructions the last operand will be the
12966: register(s) to be loaded from/stored to.
12967:
12968: Registers are specified by their names @code{r0} through @code{r15},
12969: with the aliases @code{pc}, @code{lr}, @code{sp}, @code{ip} and
12970: @code{fp} provided for convenience. Note that @code{ip} means intra
12971: procedure call scratch register (@code{r12}) and does not refer to the
12972: instruction pointer.
12973:
12974: Condition codes can be specified anywhere in the instruction, but will
12975: be most readable if specified just in front of the mnemonic. The 'S'
12976: flag is not a separate word, but encoded into instruction mnemonics,
12977: ie. just use @code{adds,} instead of @code{add,} if you want the
12978: status register to be updated.
12979:
12980: The following table lists the syntax of operands for general
12981: instructions:
12982:
12983: @example
12984: Gforth normal assembler description
12985: 123 # #123 immediate
12986: r12 r12 register
12987: r12 4 #LSL r12, LSL #4 shift left by immediate
12988: r12 r1 #LSL r12, LSL r1 shift left by register
12989: r12 4 #LSR r12, LSR #4 shift right by immediate
12990: r12 r1 #LSR r12, LSR r1 shift right by register
12991: r12 4 #ASR r12, ASR #4 arithmetic shift right
12992: r12 r1 #ASR r12, ASR r1 ... by register
12993: r12 4 #ROR r12, ROR #4 rotate right by immediate
12994: r12 r1 #ROR r12, ROR r1 ... by register
12995: r12 RRX r12, RRX rotate right with extend by 1
12996: @end example
12997:
12998: Memory operand syntax is listed in this table:
12999:
13000: @example
13001: Gforth normal assembler description
13002: r4 ] [r4] register
13003: r4 4 #] [r4, #+4] register with immediate offset
13004: r4 -4 #] [r4, #-4] with negative offset
13005: r4 r1 +] [r4, +r1] register with register offset
13006: r4 r1 -] [r4, -r1] with negated register offset
13007: r4 r1 2 #LSL -] [r4, -r1, LSL #2] with negated and shifted offset
13008: r4 4 #]! [r4, #+4]! immediate preincrement
13009: r4 r1 +]! [r4, +r1]! register preincrement
13010: r4 r1 -]! [r4, +r1]! register predecrement
13011: r4 r1 2 #LSL +]! [r4, +r1, LSL #2]! shifted preincrement
13012: r4 -4 ]# [r4], #-4 immediate postdecrement
13013: r4 r1 ]+ [r4], r1 register postincrement
13014: r4 r1 ]- [r4], -r1 register postdecrement
13015: r4 r1 2 #LSL ]- [r4], -r1, LSL #2 shifted postdecrement
13016: ' xyz >body [#] xyz PC-relative addressing
13017: @end example
13018:
13019: Register lists for load/store multiple instructions are started and
13020: terminated by using the words @code{@{} and @code{@}}
13021: respectivly. Between braces, register names can be listed one by one,
13022: or register ranges can be formed by using the postfix operator
13023: @code{r-r}. The @code{^} flag is not encoded in the register list
13024: operand, but instead directly encoded into the instruction mnemonic,
13025: ie. use @code{^ldm,} and @code{^stm,}.
13026:
13027: Addressing modes for load/store multiple are not encoded as
13028: instruction suffixes, but instead specified after the register that
13029: supplies the address. Use one of @code{DA}, @code{IA}, @code{DB},
13030: @code{IB}, @code{DA!}, @code{IA!}, @code{DB!} or @code{IB!}.
13031:
13032: The following table gives some examples:
13033:
13034: @example
13035: Gforth normal assembler
13036: @{ r0 r7 r8 @} r4 ia stm, stmia @{r0,r7,r8@}, r4
13037: @{ r0 r7 r8 @} r4 db! ldm, ldmdb @{r0,r7,r8@}, r4!
13038: @{ r0 r15 r-r @} sp ia! ^ldm, ldmfd @{r0-r15@}^, sp!
13039: @end example
13040:
13041: Conditions for control structure words are specified in front of a
13042: word:
13043:
13044: @example
13045: r1 r2 cmp, \ compare r1 and r2
13046: eq if, \ equal?
13047: ... \ code executed if r1 == r2
13048: then,
13049: @end example
13050:
13051: Here is an example of a @code{code} word (assumes that the stack
13052: pointer is in @code{r9}, and that @code{r2} and @code{r3} can be
13053: clobbered):
13054:
13055: @example
13056: code my+ ( n1 n2 -- n3 )
13057: r9 IA! @{ r2 r3 @} ldm, \ pop r2 = n2, r3 = n1
13058: r2 r3 r3 add, \ r3 = n2+n1
13059: r9 -4 #]! r3 str, \ push r3
13060: next,
13061: end-code
13062: @end example
13063:
13064: Look at @file{arch/arm/asm-example.fs} for more examples.
13065:
13066: @node Other assemblers, , ARM Assembler, Assembler and Code Words
1.78 anton 13067: @subsection Other assemblers
13068:
13069: If you want to contribute another assembler/disassembler, please contact
1.103 anton 13070: us (@email{anton@@mips.complang.tuwien.ac.at}) to check if we have such
13071: an assembler already. If you are writing them from scratch, please use
13072: a similar syntax style as the one we use (i.e., postfix, commas at the
13073: end of the instruction names, @pxref{Common Assembler}); make the output
13074: of the disassembler be valid input for the assembler, and keep the style
1.78 anton 13075: similar to the style we used.
13076:
13077: Hints on implementation: The most important part is to have a good test
13078: suite that contains all instructions. Once you have that, the rest is
13079: easy. For actual coding you can take a look at
13080: @file{arch/mips/disasm.fs} to get some ideas on how to use data for both
13081: the assembler and disassembler, avoiding redundancy and some potential
13082: bugs. You can also look at that file (and @pxref{Advanced does> usage
13083: example}) to get ideas how to factor a disassembler.
13084:
13085: Start with the disassembler, because it's easier to reuse data from the
13086: disassembler for the assembler than the other way round.
1.1 anton 13087:
1.78 anton 13088: For the assembler, take a look at @file{arch/alpha/asm.fs}, which shows
13089: how simple it can be.
1.1 anton 13090:
1.161 anton 13091:
13092:
13093:
1.78 anton 13094: @c -------------------------------------------------------------
13095: @node Threading Words, Passing Commands to the OS, Assembler and Code Words, Words
13096: @section Threading Words
13097: @cindex threading words
1.1 anton 13098:
1.78 anton 13099: @cindex code address
13100: These words provide access to code addresses and other threading stuff
13101: in Gforth (and, possibly, other interpretive Forths). It more or less
13102: abstracts away the differences between direct and indirect threading
13103: (and, for direct threading, the machine dependences). However, at
13104: present this wordset is still incomplete. It is also pretty low-level;
13105: some day it will hopefully be made unnecessary by an internals wordset
13106: that abstracts implementation details away completely.
1.1 anton 13107:
1.78 anton 13108: The terminology used here stems from indirect threaded Forth systems; in
13109: such a system, the XT of a word is represented by the CFA (code field
13110: address) of a word; the CFA points to a cell that contains the code
13111: address. The code address is the address of some machine code that
13112: performs the run-time action of invoking the word (e.g., the
13113: @code{dovar:} routine pushes the address of the body of the word (a
13114: variable) on the stack
13115: ).
1.1 anton 13116:
1.78 anton 13117: @cindex code address
13118: @cindex code field address
13119: In an indirect threaded Forth, you can get the code address of @i{name}
13120: with @code{' @i{name} @@}; in Gforth you can get it with @code{' @i{name}
13121: >code-address}, independent of the threading method.
1.1 anton 13122:
1.78 anton 13123: doc-threading-method
13124: doc->code-address
13125: doc-code-address!
1.1 anton 13126:
1.78 anton 13127: @cindex @code{does>}-handler
13128: @cindex @code{does>}-code
13129: For a word defined with @code{DOES>}, the code address usually points to
13130: a jump instruction (the @dfn{does-handler}) that jumps to the dodoes
13131: routine (in Gforth on some platforms, it can also point to the dodoes
13132: routine itself). What you are typically interested in, though, is
13133: whether a word is a @code{DOES>}-defined word, and what Forth code it
13134: executes; @code{>does-code} tells you that.
1.1 anton 13135:
1.78 anton 13136: doc->does-code
1.1 anton 13137:
1.78 anton 13138: To create a @code{DOES>}-defined word with the following basic words,
13139: you have to set up a @code{DOES>}-handler with @code{does-handler!};
13140: @code{/does-handler} aus behind you have to place your executable Forth
13141: code. Finally you have to create a word and modify its behaviour with
13142: @code{does-handler!}.
1.1 anton 13143:
1.78 anton 13144: doc-does-code!
13145: doc-does-handler!
13146: doc-/does-handler
1.1 anton 13147:
1.78 anton 13148: The code addresses produced by various defining words are produced by
13149: the following words:
1.1 anton 13150:
1.78 anton 13151: doc-docol:
13152: doc-docon:
13153: doc-dovar:
13154: doc-douser:
13155: doc-dodefer:
13156: doc-dofield:
1.1 anton 13157:
1.99 anton 13158: @cindex definer
13159: The following two words generalize @code{>code-address},
13160: @code{>does-code}, @code{code-address!}, and @code{does-code!}:
13161:
13162: doc->definer
13163: doc-definer!
13164:
1.26 crook 13165: @c -------------------------------------------------------------
1.78 anton 13166: @node Passing Commands to the OS, Keeping track of Time, Threading Words, Words
1.21 crook 13167: @section Passing Commands to the Operating System
13168: @cindex operating system - passing commands
13169: @cindex shell commands
13170:
13171: Gforth allows you to pass an arbitrary string to the host operating
13172: system shell (if such a thing exists) for execution.
13173:
13174: doc-sh
13175: doc-system
13176: doc-$?
1.23 crook 13177: doc-getenv
1.44 crook 13178:
1.26 crook 13179: @c -------------------------------------------------------------
1.47 crook 13180: @node Keeping track of Time, Miscellaneous Words, Passing Commands to the OS, Words
13181: @section Keeping track of Time
13182: @cindex time-related words
13183:
13184: doc-ms
13185: doc-time&date
1.79 anton 13186: doc-utime
13187: doc-cputime
1.47 crook 13188:
13189:
13190: @c -------------------------------------------------------------
13191: @node Miscellaneous Words, , Keeping track of Time, Words
1.21 crook 13192: @section Miscellaneous Words
13193: @cindex miscellaneous words
13194:
1.29 crook 13195: @comment TODO find homes for these
13196:
1.26 crook 13197: These section lists the ANS Forth words that are not documented
1.21 crook 13198: elsewhere in this manual. Ultimately, they all need proper homes.
13199:
1.68 anton 13200: doc-quit
1.44 crook 13201:
1.26 crook 13202: The following ANS Forth words are not currently supported by Gforth
1.27 crook 13203: (@pxref{ANS conformance}):
1.21 crook 13204:
13205: @code{EDITOR}
13206: @code{EMIT?}
13207: @code{FORGET}
13208:
1.24 anton 13209: @c ******************************************************************
13210: @node Error messages, Tools, Words, Top
13211: @chapter Error messages
13212: @cindex error messages
13213: @cindex backtrace
13214:
13215: A typical Gforth error message looks like this:
13216:
13217: @example
1.86 anton 13218: in file included from \evaluated string/:-1
1.24 anton 13219: in file included from ./yyy.fs:1
13220: ./xxx.fs:4: Invalid memory address
1.134 anton 13221: >>>bar<<<
1.79 anton 13222: Backtrace:
1.25 anton 13223: $400E664C @@
13224: $400E6664 foo
1.24 anton 13225: @end example
13226:
13227: The message identifying the error is @code{Invalid memory address}. The
13228: error happened when text-interpreting line 4 of the file
13229: @file{./xxx.fs}. This line is given (it contains @code{bar}), and the
13230: word on the line where the error happened, is pointed out (with
1.134 anton 13231: @code{>>>} and @code{<<<}).
1.24 anton 13232:
13233: The file containing the error was included in line 1 of @file{./yyy.fs},
13234: and @file{yyy.fs} was included from a non-file (in this case, by giving
13235: @file{yyy.fs} as command-line parameter to Gforth).
13236:
13237: At the end of the error message you find a return stack dump that can be
13238: interpreted as a backtrace (possibly empty). On top you find the top of
13239: the return stack when the @code{throw} happened, and at the bottom you
13240: find the return stack entry just above the return stack of the topmost
13241: text interpreter.
13242:
13243: To the right of most return stack entries you see a guess for the word
13244: that pushed that return stack entry as its return address. This gives a
13245: backtrace. In our case we see that @code{bar} called @code{foo}, and
13246: @code{foo} called @code{@@} (and @code{@@} had an @emph{Invalid memory
13247: address} exception).
13248:
13249: Note that the backtrace is not perfect: We don't know which return stack
13250: entries are return addresses (so we may get false positives); and in
13251: some cases (e.g., for @code{abort"}) we cannot determine from the return
13252: address the word that pushed the return address, so for some return
13253: addresses you see no names in the return stack dump.
1.25 anton 13254:
13255: @cindex @code{catch} and backtraces
13256: The return stack dump represents the return stack at the time when a
13257: specific @code{throw} was executed. In programs that make use of
13258: @code{catch}, it is not necessarily clear which @code{throw} should be
13259: used for the return stack dump (e.g., consider one @code{throw} that
13260: indicates an error, which is caught, and during recovery another error
1.160 anton 13261: happens; which @code{throw} should be used for the stack dump?).
13262: Gforth presents the return stack dump for the first @code{throw} after
13263: the last executed (not returned-to) @code{catch} or @code{nothrow};
13264: this works well in the usual case. To get the right backtrace, you
13265: usually want to insert @code{nothrow} or @code{['] false catch drop}
13266: after a @code{catch} if the error is not rethrown.
1.25 anton 13267:
13268: @cindex @code{gforth-fast} and backtraces
13269: @cindex @code{gforth-fast}, difference from @code{gforth}
13270: @cindex backtraces with @code{gforth-fast}
13271: @cindex return stack dump with @code{gforth-fast}
1.79 anton 13272: @code{Gforth} is able to do a return stack dump for throws generated
1.25 anton 13273: from primitives (e.g., invalid memory address, stack empty etc.);
13274: @code{gforth-fast} is only able to do a return stack dump from a
1.96 anton 13275: directly called @code{throw} (including @code{abort} etc.). Given an
1.30 anton 13276: exception caused by a primitive in @code{gforth-fast}, you will
13277: typically see no return stack dump at all; however, if the exception is
13278: caught by @code{catch} (e.g., for restoring some state), and then
13279: @code{throw}n again, the return stack dump will be for the first such
13280: @code{throw}.
1.2 jwilke 13281:
1.5 anton 13282: @c ******************************************************************
1.24 anton 13283: @node Tools, ANS conformance, Error messages, Top
1.1 anton 13284: @chapter Tools
13285:
13286: @menu
13287: * ANS Report:: Report the words used, sorted by wordset.
1.127 anton 13288: * Stack depth changes:: Where does this stack item come from?
1.1 anton 13289: @end menu
13290:
13291: See also @ref{Emacs and Gforth}.
13292:
1.126 pazsan 13293: @node ANS Report, Stack depth changes, Tools, Tools
1.1 anton 13294: @section @file{ans-report.fs}: Report the words used, sorted by wordset
13295: @cindex @file{ans-report.fs}
13296: @cindex report the words used in your program
13297: @cindex words used in your program
13298:
13299: If you want to label a Forth program as ANS Forth Program, you must
13300: document which wordsets the program uses; for extension wordsets, it is
13301: helpful to list the words the program requires from these wordsets
13302: (because Forth systems are allowed to provide only some words of them).
13303:
13304: The @file{ans-report.fs} tool makes it easy for you to determine which
13305: words from which wordset and which non-ANS words your application
13306: uses. You simply have to include @file{ans-report.fs} before loading the
13307: program you want to check. After loading your program, you can get the
13308: report with @code{print-ans-report}. A typical use is to run this as
13309: batch job like this:
13310: @example
13311: gforth ans-report.fs myprog.fs -e "print-ans-report bye"
13312: @end example
13313:
13314: The output looks like this (for @file{compat/control.fs}):
13315: @example
13316: The program uses the following words
13317: from CORE :
13318: : POSTPONE THEN ; immediate ?dup IF 0=
13319: from BLOCK-EXT :
13320: \
13321: from FILE :
13322: (
13323: @end example
13324:
13325: @subsection Caveats
13326:
13327: Note that @file{ans-report.fs} just checks which words are used, not whether
13328: they are used in an ANS Forth conforming way!
13329:
13330: Some words are defined in several wordsets in the
13331: standard. @file{ans-report.fs} reports them for only one of the
13332: wordsets, and not necessarily the one you expect. It depends on usage
13333: which wordset is the right one to specify. E.g., if you only use the
13334: compilation semantics of @code{S"}, it is a Core word; if you also use
13335: its interpretation semantics, it is a File word.
1.124 anton 13336:
13337:
1.127 anton 13338: @node Stack depth changes, , ANS Report, Tools
1.124 anton 13339: @section Stack depth changes during interpretation
13340: @cindex @file{depth-changes.fs}
13341: @cindex depth changes during interpretation
13342: @cindex stack depth changes during interpretation
13343: @cindex items on the stack after interpretation
13344:
13345: Sometimes you notice that, after loading a file, there are items left
13346: on the stack. The tool @file{depth-changes.fs} helps you find out
13347: quickly where in the file these stack items are coming from.
13348:
13349: The simplest way of using @file{depth-changes.fs} is to include it
13350: before the file(s) you want to check, e.g.:
13351:
13352: @example
13353: gforth depth-changes.fs my-file.fs
13354: @end example
13355:
13356: This will compare the stack depths of the data and FP stack at every
13357: empty line (in interpretation state) against these depths at the last
13358: empty line (in interpretation state). If the depths are not equal,
13359: the position in the file and the stack contents are printed with
13360: @code{~~} (@pxref{Debugging}). This indicates that a stack depth
13361: change has occured in the paragraph of non-empty lines before the
13362: indicated line. It is a good idea to leave an empty line at the end
13363: of the file, so the last paragraph is checked, too.
13364:
13365: Checking only at empty lines usually works well, but sometimes you
13366: have big blocks of non-empty lines (e.g., when building a big table),
13367: and you want to know where in this block the stack depth changed. You
13368: can check all interpreted lines with
13369:
13370: @example
13371: gforth depth-changes.fs -e "' all-lines is depth-changes-filter" my-file.fs
13372: @end example
13373:
13374: This checks the stack depth at every end-of-line. So the depth change
13375: occured in the line reported by the @code{~~} (not in the line
13376: before).
13377:
13378: Note that, while this offers better accuracy in indicating where the
13379: stack depth changes, it will often report many intentional stack depth
13380: changes (e.g., when an interpreted computation stretches across
13381: several lines). You can suppress the checking of some lines by
13382: putting backslashes at the end of these lines (not followed by white
13383: space), and using
13384:
13385: @example
13386: gforth depth-changes.fs -e "' most-lines is depth-changes-filter" my-file.fs
13387: @end example
1.1 anton 13388:
13389: @c ******************************************************************
1.65 anton 13390: @node ANS conformance, Standard vs Extensions, Tools, Top
1.1 anton 13391: @chapter ANS conformance
13392: @cindex ANS conformance of Gforth
13393:
13394: To the best of our knowledge, Gforth is an
13395:
13396: ANS Forth System
13397: @itemize @bullet
13398: @item providing the Core Extensions word set
13399: @item providing the Block word set
13400: @item providing the Block Extensions word set
13401: @item providing the Double-Number word set
13402: @item providing the Double-Number Extensions word set
13403: @item providing the Exception word set
13404: @item providing the Exception Extensions word set
13405: @item providing the Facility word set
1.40 anton 13406: @item providing @code{EKEY}, @code{EKEY>CHAR}, @code{EKEY?}, @code{MS} and @code{TIME&DATE} from the Facility Extensions word set
1.1 anton 13407: @item providing the File Access word set
13408: @item providing the File Access Extensions word set
13409: @item providing the Floating-Point word set
13410: @item providing the Floating-Point Extensions word set
13411: @item providing the Locals word set
13412: @item providing the Locals Extensions word set
13413: @item providing the Memory-Allocation word set
13414: @item providing the Memory-Allocation Extensions word set (that one's easy)
13415: @item providing the Programming-Tools word set
13416: @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
13417: @item providing the Search-Order word set
13418: @item providing the Search-Order Extensions word set
13419: @item providing the String word set
13420: @item providing the String Extensions word set (another easy one)
13421: @end itemize
13422:
1.118 anton 13423: Gforth has the following environmental restrictions:
13424:
13425: @cindex environmental restrictions
13426: @itemize @bullet
13427: @item
13428: While processing the OS command line, if an exception is not caught,
13429: Gforth exits with a non-zero exit code instyead of performing QUIT.
13430:
13431: @item
13432: When an @code{throw} is performed after a @code{query}, Gforth does not
13433: allways restore the input source specification in effect at the
13434: corresponding catch.
13435:
13436: @end itemize
13437:
13438:
1.1 anton 13439: @cindex system documentation
13440: In addition, ANS Forth systems are required to document certain
13441: implementation choices. This chapter tries to meet these
13442: requirements. In many cases it gives a way to ask the system for the
13443: information instead of providing the information directly, in
13444: particular, if the information depends on the processor, the operating
13445: system or the installation options chosen, or if they are likely to
13446: change during the maintenance of Gforth.
13447:
13448: @comment The framework for the rest has been taken from pfe.
13449:
13450: @menu
13451: * The Core Words::
13452: * The optional Block word set::
13453: * The optional Double Number word set::
13454: * The optional Exception word set::
13455: * The optional Facility word set::
13456: * The optional File-Access word set::
13457: * The optional Floating-Point word set::
13458: * The optional Locals word set::
13459: * The optional Memory-Allocation word set::
13460: * The optional Programming-Tools word set::
13461: * The optional Search-Order word set::
13462: @end menu
13463:
13464:
13465: @c =====================================================================
13466: @node The Core Words, The optional Block word set, ANS conformance, ANS conformance
13467: @comment node-name, next, previous, up
13468: @section The Core Words
13469: @c =====================================================================
13470: @cindex core words, system documentation
13471: @cindex system documentation, core words
13472:
13473: @menu
13474: * core-idef:: Implementation Defined Options
13475: * core-ambcond:: Ambiguous Conditions
13476: * core-other:: Other System Documentation
13477: @end menu
13478:
13479: @c ---------------------------------------------------------------------
13480: @node core-idef, core-ambcond, The Core Words, The Core Words
13481: @subsection Implementation Defined Options
13482: @c ---------------------------------------------------------------------
13483: @cindex core words, implementation-defined options
13484: @cindex implementation-defined options, core words
13485:
13486:
13487: @table @i
13488: @item (Cell) aligned addresses:
13489: @cindex cell-aligned addresses
13490: @cindex aligned addresses
13491: processor-dependent. Gforth's alignment words perform natural alignment
13492: (e.g., an address aligned for a datum of size 8 is divisible by
13493: 8). Unaligned accesses usually result in a @code{-23 THROW}.
13494:
13495: @item @code{EMIT} and non-graphic characters:
13496: @cindex @code{EMIT} and non-graphic characters
13497: @cindex non-graphic characters and @code{EMIT}
13498: The character is output using the C library function (actually, macro)
13499: @code{putc}.
13500:
13501: @item character editing of @code{ACCEPT} and @code{EXPECT}:
13502: @cindex character editing of @code{ACCEPT} and @code{EXPECT}
13503: @cindex editing in @code{ACCEPT} and @code{EXPECT}
13504: @cindex @code{ACCEPT}, editing
13505: @cindex @code{EXPECT}, editing
13506: This is modeled on the GNU readline library (@pxref{Readline
13507: Interaction, , Command Line Editing, readline, The GNU Readline
13508: Library}) with Emacs-like key bindings. @kbd{Tab} deviates a little by
13509: producing a full word completion every time you type it (instead of
1.28 crook 13510: producing the common prefix of all completions). @xref{Command-line editing}.
1.1 anton 13511:
13512: @item character set:
13513: @cindex character set
13514: The character set of your computer and display device. Gforth is
13515: 8-bit-clean (but some other component in your system may make trouble).
13516:
13517: @item Character-aligned address requirements:
13518: @cindex character-aligned address requirements
13519: installation-dependent. Currently a character is represented by a C
13520: @code{unsigned char}; in the future we might switch to @code{wchar_t}
13521: (Comments on that requested).
13522:
13523: @item character-set extensions and matching of names:
13524: @cindex character-set extensions and matching of names
1.26 crook 13525: @cindex case-sensitivity for name lookup
13526: @cindex name lookup, case-sensitivity
13527: @cindex locale and case-sensitivity
1.21 crook 13528: Any character except the ASCII NUL character can be used in a
1.1 anton 13529: name. Matching is case-insensitive (except in @code{TABLE}s). The
1.47 crook 13530: matching is performed using the C library function @code{strncasecmp}, whose
1.1 anton 13531: function is probably influenced by the locale. E.g., the @code{C} locale
13532: does not know about accents and umlauts, so they are matched
13533: case-sensitively in that locale. For portability reasons it is best to
13534: write programs such that they work in the @code{C} locale. Then one can
13535: use libraries written by a Polish programmer (who might use words
13536: containing ISO Latin-2 encoded characters) and by a French programmer
13537: (ISO Latin-1) in the same program (of course, @code{WORDS} will produce
13538: funny results for some of the words (which ones, depends on the font you
13539: are using)). Also, the locale you prefer may not be available in other
13540: operating systems. Hopefully, Unicode will solve these problems one day.
13541:
13542: @item conditions under which control characters match a space delimiter:
13543: @cindex space delimiters
13544: @cindex control characters as delimiters
1.117 anton 13545: If @code{word} is called with the space character as a delimiter, all
1.1 anton 13546: white-space characters (as identified by the C macro @code{isspace()})
1.117 anton 13547: are delimiters. @code{Parse}, on the other hand, treats space like other
1.138 anton 13548: delimiters. @code{Parse-name}, which is used by the outer
1.1 anton 13549: interpreter (aka text interpreter) by default, treats all white-space
13550: characters as delimiters.
13551:
1.26 crook 13552: @item format of the control-flow stack:
13553: @cindex control-flow stack, format
13554: The data stack is used as control-flow stack. The size of a control-flow
1.1 anton 13555: stack item in cells is given by the constant @code{cs-item-size}. At the
13556: time of this writing, an item consists of a (pointer to a) locals list
13557: (third), an address in the code (second), and a tag for identifying the
13558: item (TOS). The following tags are used: @code{defstart},
13559: @code{live-orig}, @code{dead-orig}, @code{dest}, @code{do-dest},
13560: @code{scopestart}.
13561:
13562: @item conversion of digits > 35
13563: @cindex digits > 35
13564: The characters @code{[\]^_'} are the digits with the decimal value
13565: 36@minus{}41. There is no way to input many of the larger digits.
13566:
13567: @item display after input terminates in @code{ACCEPT} and @code{EXPECT}:
13568: @cindex @code{EXPECT}, display after end of input
13569: @cindex @code{ACCEPT}, display after end of input
13570: The cursor is moved to the end of the entered string. If the input is
13571: terminated using the @kbd{Return} key, a space is typed.
13572:
13573: @item exception abort sequence of @code{ABORT"}:
13574: @cindex exception abort sequence of @code{ABORT"}
13575: @cindex @code{ABORT"}, exception abort sequence
13576: The error string is stored into the variable @code{"error} and a
13577: @code{-2 throw} is performed.
13578:
13579: @item input line terminator:
13580: @cindex input line terminator
13581: @cindex line terminator on input
1.26 crook 13582: @cindex newline character on input
1.1 anton 13583: For interactive input, @kbd{C-m} (CR) and @kbd{C-j} (LF) terminate
13584: lines. One of these characters is typically produced when you type the
13585: @kbd{Enter} or @kbd{Return} key.
13586:
13587: @item maximum size of a counted string:
13588: @cindex maximum size of a counted string
13589: @cindex counted string, maximum size
13590: @code{s" /counted-string" environment? drop .}. Currently 255 characters
1.79 anton 13591: on all platforms, but this may change.
1.1 anton 13592:
13593: @item maximum size of a parsed string:
13594: @cindex maximum size of a parsed string
13595: @cindex parsed string, maximum size
13596: Given by the constant @code{/line}. Currently 255 characters.
13597:
13598: @item maximum size of a definition name, in characters:
13599: @cindex maximum size of a definition name, in characters
13600: @cindex name, maximum length
1.113 anton 13601: MAXU/8
1.1 anton 13602:
13603: @item maximum string length for @code{ENVIRONMENT?}, in characters:
13604: @cindex maximum string length for @code{ENVIRONMENT?}, in characters
13605: @cindex @code{ENVIRONMENT?} string length, maximum
1.113 anton 13606: MAXU/8
1.1 anton 13607:
13608: @item method of selecting the user input device:
13609: @cindex user input device, method of selecting
13610: The user input device is the standard input. There is currently no way to
13611: change it from within Gforth. However, the input can typically be
13612: redirected in the command line that starts Gforth.
13613:
13614: @item method of selecting the user output device:
13615: @cindex user output device, method of selecting
13616: @code{EMIT} and @code{TYPE} output to the file-id stored in the value
1.10 anton 13617: @code{outfile-id} (@code{stdout} by default). Gforth uses unbuffered
13618: output when the user output device is a terminal, otherwise the output
13619: is buffered.
1.1 anton 13620:
13621: @item methods of dictionary compilation:
13622: What are we expected to document here?
13623:
13624: @item number of bits in one address unit:
13625: @cindex number of bits in one address unit
13626: @cindex address unit, size in bits
13627: @code{s" address-units-bits" environment? drop .}. 8 in all current
1.79 anton 13628: platforms.
1.1 anton 13629:
13630: @item number representation and arithmetic:
13631: @cindex number representation and arithmetic
1.79 anton 13632: Processor-dependent. Binary two's complement on all current platforms.
1.1 anton 13633:
13634: @item ranges for integer types:
13635: @cindex ranges for integer types
13636: @cindex integer types, ranges
13637: Installation-dependent. Make environmental queries for @code{MAX-N},
13638: @code{MAX-U}, @code{MAX-D} and @code{MAX-UD}. The lower bounds for
13639: unsigned (and positive) types is 0. The lower bound for signed types on
13640: two's complement and one's complement machines machines can be computed
13641: by adding 1 to the upper bound.
13642:
13643: @item read-only data space regions:
13644: @cindex read-only data space regions
13645: @cindex data-space, read-only regions
13646: The whole Forth data space is writable.
13647:
13648: @item size of buffer at @code{WORD}:
13649: @cindex size of buffer at @code{WORD}
13650: @cindex @code{WORD} buffer size
13651: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13652: shared with the pictured numeric output string. If overwriting
13653: @code{PAD} is acceptable, it is as large as the remaining dictionary
13654: space, although only as much can be sensibly used as fits in a counted
13655: string.
13656:
13657: @item size of one cell in address units:
13658: @cindex cell size
13659: @code{1 cells .}.
13660:
13661: @item size of one character in address units:
13662: @cindex char size
1.79 anton 13663: @code{1 chars .}. 1 on all current platforms.
1.1 anton 13664:
13665: @item size of the keyboard terminal buffer:
13666: @cindex size of the keyboard terminal buffer
13667: @cindex terminal buffer, size
13668: Varies. You can determine the size at a specific time using @code{lp@@
13669: tib - .}. It is shared with the locals stack and TIBs of files that
13670: include the current file. You can change the amount of space for TIBs
13671: and locals stack at Gforth startup with the command line option
13672: @code{-l}.
13673:
13674: @item size of the pictured numeric output buffer:
13675: @cindex size of the pictured numeric output buffer
13676: @cindex pictured numeric output buffer, size
13677: @code{PAD HERE - .}. 104 characters on 32-bit machines. The buffer is
13678: shared with @code{WORD}.
13679:
13680: @item size of the scratch area returned by @code{PAD}:
13681: @cindex size of the scratch area returned by @code{PAD}
13682: @cindex @code{PAD} size
13683: The remainder of dictionary space. @code{unused pad here - - .}.
13684:
13685: @item system case-sensitivity characteristics:
13686: @cindex case-sensitivity characteristics
1.26 crook 13687: Dictionary searches are case-insensitive (except in
1.1 anton 13688: @code{TABLE}s). However, as explained above under @i{character-set
13689: extensions}, the matching for non-ASCII characters is determined by the
13690: locale you are using. In the default @code{C} locale all non-ASCII
13691: characters are matched case-sensitively.
13692:
13693: @item system prompt:
13694: @cindex system prompt
13695: @cindex prompt
13696: @code{ ok} in interpret state, @code{ compiled} in compile state.
13697:
13698: @item division rounding:
13699: @cindex division rounding
1.166 anton 13700: The ordinary division words @code{/ mod /mod */ */mod} perform floored
13701: division (with the default installation of Gforth). You can check
13702: this with @code{s" floored" environment? drop .}. If you write
13703: programs that need a specific division rounding, best use
13704: @code{fm/mod} or @code{sm/rem} for portability.
1.1 anton 13705:
13706: @item values of @code{STATE} when true:
13707: @cindex @code{STATE} values
13708: -1.
13709:
13710: @item values returned after arithmetic overflow:
13711: On two's complement machines, arithmetic is performed modulo
13712: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.164 anton 13713: arithmetic (with appropriate mapping for signed types). Division by
13714: zero typically results in a @code{-55 throw} (Floating-point
13715: unidentified fault) or @code{-10 throw} (divide by zero). Integer
1.166 anton 13716: division overflow can result in these throws, or in @code{-11 throw};
13717: in @code{gforth-fast} division overflow and divide by zero may also
13718: result in returning bogus results without producing an exception.
1.1 anton 13719:
13720: @item whether the current definition can be found after @t{DOES>}:
13721: @cindex @t{DOES>}, visibility of current definition
13722: No.
13723:
13724: @end table
13725:
13726: @c ---------------------------------------------------------------------
13727: @node core-ambcond, core-other, core-idef, The Core Words
13728: @subsection Ambiguous conditions
13729: @c ---------------------------------------------------------------------
13730: @cindex core words, ambiguous conditions
13731: @cindex ambiguous conditions, core words
13732:
13733: @table @i
13734:
13735: @item a name is neither a word nor a number:
13736: @cindex name not found
1.26 crook 13737: @cindex undefined word
1.80 anton 13738: @code{-13 throw} (Undefined word).
1.1 anton 13739:
13740: @item a definition name exceeds the maximum length allowed:
1.26 crook 13741: @cindex word name too long
1.1 anton 13742: @code{-19 throw} (Word name too long)
13743:
13744: @item addressing a region not inside the various data spaces of the forth system:
13745: @cindex Invalid memory address
1.32 anton 13746: The stacks, code space and header space are accessible. Machine code space is
1.1 anton 13747: typically readable. Accessing other addresses gives results dependent on
13748: the operating system. On decent systems: @code{-9 throw} (Invalid memory
13749: address).
13750:
13751: @item argument type incompatible with parameter:
1.26 crook 13752: @cindex argument type mismatch
1.1 anton 13753: This is usually not caught. Some words perform checks, e.g., the control
13754: flow words, and issue a @code{ABORT"} or @code{-12 THROW} (Argument type
13755: mismatch).
13756:
13757: @item attempting to obtain the execution token of a word with undefined execution semantics:
13758: @cindex Interpreting a compile-only word, for @code{'} etc.
13759: @cindex execution token of words with undefined execution semantics
13760: @code{-14 throw} (Interpreting a compile-only word). In some cases, you
13761: get an execution token for @code{compile-only-error} (which performs a
13762: @code{-14 throw} when executed).
13763:
13764: @item dividing by zero:
13765: @cindex dividing by zero
13766: @cindex floating point unidentified fault, integer division
1.80 anton 13767: On some platforms, this produces a @code{-10 throw} (Division by
1.24 anton 13768: zero); on other systems, this typically results in a @code{-55 throw}
13769: (Floating-point unidentified fault).
1.1 anton 13770:
13771: @item insufficient data stack or return stack space:
13772: @cindex insufficient data stack or return stack space
13773: @cindex stack overflow
1.26 crook 13774: @cindex address alignment exception, stack overflow
1.1 anton 13775: @cindex Invalid memory address, stack overflow
13776: Depending on the operating system, the installation, and the invocation
13777: of Gforth, this is either checked by the memory management hardware, or
1.24 anton 13778: it is not checked. If it is checked, you typically get a @code{-3 throw}
13779: (Stack overflow), @code{-5 throw} (Return stack overflow), or @code{-9
13780: throw} (Invalid memory address) (depending on the platform and how you
13781: achieved the overflow) as soon as the overflow happens. If it is not
13782: checked, overflows typically result in mysterious illegal memory
13783: accesses, producing @code{-9 throw} (Invalid memory address) or
13784: @code{-23 throw} (Address alignment exception); they might also destroy
13785: the internal data structure of @code{ALLOCATE} and friends, resulting in
13786: various errors in these words.
1.1 anton 13787:
13788: @item insufficient space for loop control parameters:
13789: @cindex insufficient space for loop control parameters
1.80 anton 13790: Like other return stack overflows.
1.1 anton 13791:
13792: @item insufficient space in the dictionary:
13793: @cindex insufficient space in the dictionary
13794: @cindex dictionary overflow
1.12 anton 13795: If you try to allot (either directly with @code{allot}, or indirectly
13796: with @code{,}, @code{create} etc.) more memory than available in the
13797: dictionary, you get a @code{-8 throw} (Dictionary overflow). If you try
13798: to access memory beyond the end of the dictionary, the results are
13799: similar to stack overflows.
1.1 anton 13800:
13801: @item interpreting a word with undefined interpretation semantics:
13802: @cindex interpreting a word with undefined interpretation semantics
13803: @cindex Interpreting a compile-only word
13804: For some words, we have defined interpretation semantics. For the
13805: others: @code{-14 throw} (Interpreting a compile-only word).
13806:
13807: @item modifying the contents of the input buffer or a string literal:
13808: @cindex modifying the contents of the input buffer or a string literal
13809: These are located in writable memory and can be modified.
13810:
13811: @item overflow of the pictured numeric output string:
13812: @cindex overflow of the pictured numeric output string
13813: @cindex pictured numeric output string, overflow
1.24 anton 13814: @code{-17 throw} (Pictured numeric ouput string overflow).
1.1 anton 13815:
13816: @item parsed string overflow:
13817: @cindex parsed string overflow
13818: @code{PARSE} cannot overflow. @code{WORD} does not check for overflow.
13819:
13820: @item producing a result out of range:
13821: @cindex result out of range
13822: On two's complement machines, arithmetic is performed modulo
13823: 2**bits-per-cell for single arithmetic and 4**bits-per-cell for double
1.166 anton 13824: arithmetic (with appropriate mapping for signed types). Division by
13825: zero typically results in a @code{-10 throw} (divide by zero) or
13826: @code{-55 throw} (floating point unidentified fault). Overflow on
13827: division may result in these errors or in @code{-11 throw} (result out
13828: of range). @code{Gforth-fast} may silently produce bogus results on
13829: division overflow or division by zero. @code{Convert} and
1.24 anton 13830: @code{>number} currently overflow silently.
1.1 anton 13831:
13832: @item reading from an empty data or return stack:
13833: @cindex stack empty
13834: @cindex stack underflow
1.24 anton 13835: @cindex return stack underflow
1.1 anton 13836: The data stack is checked by the outer (aka text) interpreter after
13837: every word executed. If it has underflowed, a @code{-4 throw} (Stack
13838: underflow) is performed. Apart from that, stacks may be checked or not,
1.24 anton 13839: depending on operating system, installation, and invocation. If they are
13840: caught by a check, they typically result in @code{-4 throw} (Stack
13841: underflow), @code{-6 throw} (Return stack underflow) or @code{-9 throw}
13842: (Invalid memory address), depending on the platform and which stack
13843: underflows and by how much. Note that even if the system uses checking
13844: (through the MMU), your program may have to underflow by a significant
13845: number of stack items to trigger the reaction (the reason for this is
13846: that the MMU, and therefore the checking, works with a page-size
13847: granularity). If there is no checking, the symptoms resulting from an
13848: underflow are similar to those from an overflow. Unbalanced return
1.80 anton 13849: stack errors can result in a variety of symptoms, including @code{-9 throw}
1.24 anton 13850: (Invalid memory address) and Illegal Instruction (typically @code{-260
13851: throw}).
1.1 anton 13852:
13853: @item unexpected end of the input buffer, resulting in an attempt to use a zero-length string as a name:
13854: @cindex unexpected end of the input buffer
13855: @cindex zero-length string as a name
13856: @cindex Attempt to use zero-length string as a name
13857: @code{Create} and its descendants perform a @code{-16 throw} (Attempt to
13858: use zero-length string as a name). Words like @code{'} probably will not
13859: find what they search. Note that it is possible to create zero-length
13860: names with @code{nextname} (should it not?).
13861:
13862: @item @code{>IN} greater than input buffer:
13863: @cindex @code{>IN} greater than input buffer
13864: The next invocation of a parsing word returns a string with length 0.
13865:
13866: @item @code{RECURSE} appears after @code{DOES>}:
13867: @cindex @code{RECURSE} appears after @code{DOES>}
13868: Compiles a recursive call to the defining word, not to the defined word.
13869:
13870: @item argument input source different than current input source for @code{RESTORE-INPUT}:
13871: @cindex argument input source different than current input source for @code{RESTORE-INPUT}
1.26 crook 13872: @cindex argument type mismatch, @code{RESTORE-INPUT}
1.1 anton 13873: @cindex @code{RESTORE-INPUT}, Argument type mismatch
13874: @code{-12 THROW}. Note that, once an input file is closed (e.g., because
13875: the end of the file was reached), its source-id may be
13876: reused. Therefore, restoring an input source specification referencing a
13877: closed file may lead to unpredictable results instead of a @code{-12
13878: THROW}.
13879:
13880: In the future, Gforth may be able to restore input source specifications
13881: from other than the current input source.
13882:
13883: @item data space containing definitions gets de-allocated:
13884: @cindex data space containing definitions gets de-allocated
13885: Deallocation with @code{allot} is not checked. This typically results in
13886: memory access faults or execution of illegal instructions.
13887:
13888: @item data space read/write with incorrect alignment:
13889: @cindex data space read/write with incorrect alignment
13890: @cindex alignment faults
1.26 crook 13891: @cindex address alignment exception
1.1 anton 13892: Processor-dependent. Typically results in a @code{-23 throw} (Address
1.12 anton 13893: alignment exception). Under Linux-Intel on a 486 or later processor with
1.1 anton 13894: alignment turned on, incorrect alignment results in a @code{-9 throw}
13895: (Invalid memory address). There are reportedly some processors with
1.12 anton 13896: alignment restrictions that do not report violations.
1.1 anton 13897:
13898: @item data space pointer not properly aligned, @code{,}, @code{C,}:
13899: @cindex data space pointer not properly aligned, @code{,}, @code{C,}
13900: Like other alignment errors.
13901:
13902: @item less than u+2 stack items (@code{PICK} and @code{ROLL}):
13903: Like other stack underflows.
13904:
13905: @item loop control parameters not available:
13906: @cindex loop control parameters not available
13907: Not checked. The counted loop words simply assume that the top of return
13908: stack items are loop control parameters and behave accordingly.
13909:
13910: @item most recent definition does not have a name (@code{IMMEDIATE}):
13911: @cindex most recent definition does not have a name (@code{IMMEDIATE})
13912: @cindex last word was headerless
13913: @code{abort" last word was headerless"}.
13914:
13915: @item name not defined by @code{VALUE} used by @code{TO}:
13916: @cindex name not defined by @code{VALUE} used by @code{TO}
13917: @cindex @code{TO} on non-@code{VALUE}s
13918: @cindex Invalid name argument, @code{TO}
13919: @code{-32 throw} (Invalid name argument) (unless name is a local or was
13920: defined by @code{CONSTANT}; in the latter case it just changes the constant).
13921:
13922: @item name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}):
13923: @cindex name not found (@code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]})
1.26 crook 13924: @cindex undefined word, @code{'}, @code{POSTPONE}, @code{[']}, @code{[COMPILE]}
1.1 anton 13925: @code{-13 throw} (Undefined word)
13926:
13927: @item parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN}):
13928: @cindex parameters are not of the same type (@code{DO}, @code{?DO}, @code{WITHIN})
13929: Gforth behaves as if they were of the same type. I.e., you can predict
13930: the behaviour by interpreting all parameters as, e.g., signed.
13931:
13932: @item @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}:
13933: @cindex @code{POSTPONE} or @code{[COMPILE]} applied to @code{TO}
13934: Assume @code{: X POSTPONE TO ; IMMEDIATE}. @code{X} performs the
13935: compilation semantics of @code{TO}.
13936:
13937: @item String longer than a counted string returned by @code{WORD}:
1.26 crook 13938: @cindex string longer than a counted string returned by @code{WORD}
1.1 anton 13939: @cindex @code{WORD}, string overflow
13940: Not checked. The string will be ok, but the count will, of course,
13941: contain only the least significant bits of the length.
13942:
13943: @item u greater than or equal to the number of bits in a cell (@code{LSHIFT}, @code{RSHIFT}):
13944: @cindex @code{LSHIFT}, large shift counts
13945: @cindex @code{RSHIFT}, large shift counts
13946: Processor-dependent. Typical behaviours are returning 0 and using only
13947: the low bits of the shift count.
13948:
13949: @item word not defined via @code{CREATE}:
13950: @cindex @code{>BODY} of non-@code{CREATE}d words
13951: @code{>BODY} produces the PFA of the word no matter how it was defined.
13952:
13953: @cindex @code{DOES>} of non-@code{CREATE}d words
13954: @code{DOES>} changes the execution semantics of the last defined word no
13955: matter how it was defined. E.g., @code{CONSTANT DOES>} is equivalent to
13956: @code{CREATE , DOES>}.
13957:
13958: @item words improperly used outside @code{<#} and @code{#>}:
13959: Not checked. As usual, you can expect memory faults.
13960:
13961: @end table
13962:
13963:
13964: @c ---------------------------------------------------------------------
13965: @node core-other, , core-ambcond, The Core Words
13966: @subsection Other system documentation
13967: @c ---------------------------------------------------------------------
13968: @cindex other system documentation, core words
13969: @cindex core words, other system documentation
13970:
13971: @table @i
13972: @item nonstandard words using @code{PAD}:
13973: @cindex @code{PAD} use by nonstandard words
13974: None.
13975:
13976: @item operator's terminal facilities available:
13977: @cindex operator's terminal facilities available
1.80 anton 13978: After processing the OS's command line, Gforth goes into interactive mode,
1.1 anton 13979: and you can give commands to Gforth interactively. The actual facilities
13980: available depend on how you invoke Gforth.
13981:
13982: @item program data space available:
13983: @cindex program data space available
13984: @cindex data space available
13985: @code{UNUSED .} gives the remaining dictionary space. The total
13986: dictionary space can be specified with the @code{-m} switch
13987: (@pxref{Invoking Gforth}) when Gforth starts up.
13988:
13989: @item return stack space available:
13990: @cindex return stack space available
13991: You can compute the total return stack space in cells with
13992: @code{s" RETURN-STACK-CELLS" environment? drop .}. You can specify it at
13993: startup time with the @code{-r} switch (@pxref{Invoking Gforth}).
13994:
13995: @item stack space available:
13996: @cindex stack space available
13997: You can compute the total data stack space in cells with
13998: @code{s" STACK-CELLS" environment? drop .}. You can specify it at
13999: startup time with the @code{-d} switch (@pxref{Invoking Gforth}).
14000:
14001: @item system dictionary space required, in address units:
14002: @cindex system dictionary space required, in address units
14003: Type @code{here forthstart - .} after startup. At the time of this
14004: writing, this gives 80080 (bytes) on a 32-bit system.
14005: @end table
14006:
14007:
14008: @c =====================================================================
14009: @node The optional Block word set, The optional Double Number word set, The Core Words, ANS conformance
14010: @section The optional Block word set
14011: @c =====================================================================
14012: @cindex system documentation, block words
14013: @cindex block words, system documentation
14014:
14015: @menu
14016: * block-idef:: Implementation Defined Options
14017: * block-ambcond:: Ambiguous Conditions
14018: * block-other:: Other System Documentation
14019: @end menu
14020:
14021:
14022: @c ---------------------------------------------------------------------
14023: @node block-idef, block-ambcond, The optional Block word set, The optional Block word set
14024: @subsection Implementation Defined Options
14025: @c ---------------------------------------------------------------------
14026: @cindex implementation-defined options, block words
14027: @cindex block words, implementation-defined options
14028:
14029: @table @i
14030: @item the format for display by @code{LIST}:
14031: @cindex @code{LIST} display format
14032: First the screen number is displayed, then 16 lines of 64 characters,
14033: each line preceded by the line number.
14034:
14035: @item the length of a line affected by @code{\}:
14036: @cindex length of a line affected by @code{\}
14037: @cindex @code{\}, line length in blocks
14038: 64 characters.
14039: @end table
14040:
14041:
14042: @c ---------------------------------------------------------------------
14043: @node block-ambcond, block-other, block-idef, The optional Block word set
14044: @subsection Ambiguous conditions
14045: @c ---------------------------------------------------------------------
14046: @cindex block words, ambiguous conditions
14047: @cindex ambiguous conditions, block words
14048:
14049: @table @i
14050: @item correct block read was not possible:
14051: @cindex block read not possible
14052: Typically results in a @code{throw} of some OS-derived value (between
14053: -512 and -2048). If the blocks file was just not long enough, blanks are
14054: supplied for the missing portion.
14055:
14056: @item I/O exception in block transfer:
14057: @cindex I/O exception in block transfer
14058: @cindex block transfer, I/O exception
14059: Typically results in a @code{throw} of some OS-derived value (between
14060: -512 and -2048).
14061:
14062: @item invalid block number:
14063: @cindex invalid block number
14064: @cindex block number invalid
14065: @code{-35 throw} (Invalid block number)
14066:
14067: @item a program directly alters the contents of @code{BLK}:
14068: @cindex @code{BLK}, altering @code{BLK}
14069: The input stream is switched to that other block, at the same
14070: position. If the storing to @code{BLK} happens when interpreting
14071: non-block input, the system will get quite confused when the block ends.
14072:
14073: @item no current block buffer for @code{UPDATE}:
14074: @cindex @code{UPDATE}, no current block buffer
14075: @code{UPDATE} has no effect.
14076:
14077: @end table
14078:
14079: @c ---------------------------------------------------------------------
14080: @node block-other, , block-ambcond, The optional Block word set
14081: @subsection Other system documentation
14082: @c ---------------------------------------------------------------------
14083: @cindex other system documentation, block words
14084: @cindex block words, other system documentation
14085:
14086: @table @i
14087: @item any restrictions a multiprogramming system places on the use of buffer addresses:
14088: No restrictions (yet).
14089:
14090: @item the number of blocks available for source and data:
14091: depends on your disk space.
14092:
14093: @end table
14094:
14095:
14096: @c =====================================================================
14097: @node The optional Double Number word set, The optional Exception word set, The optional Block word set, ANS conformance
14098: @section The optional Double Number word set
14099: @c =====================================================================
14100: @cindex system documentation, double words
14101: @cindex double words, system documentation
14102:
14103: @menu
14104: * double-ambcond:: Ambiguous Conditions
14105: @end menu
14106:
14107:
14108: @c ---------------------------------------------------------------------
14109: @node double-ambcond, , The optional Double Number word set, The optional Double Number word set
14110: @subsection Ambiguous conditions
14111: @c ---------------------------------------------------------------------
14112: @cindex double words, ambiguous conditions
14113: @cindex ambiguous conditions, double words
14114:
14115: @table @i
1.29 crook 14116: @item @i{d} outside of range of @i{n} in @code{D>S}:
14117: @cindex @code{D>S}, @i{d} out of range of @i{n}
14118: The least significant cell of @i{d} is produced.
1.1 anton 14119:
14120: @end table
14121:
14122:
14123: @c =====================================================================
14124: @node The optional Exception word set, The optional Facility word set, The optional Double Number word set, ANS conformance
14125: @section The optional Exception word set
14126: @c =====================================================================
14127: @cindex system documentation, exception words
14128: @cindex exception words, system documentation
14129:
14130: @menu
14131: * exception-idef:: Implementation Defined Options
14132: @end menu
14133:
14134:
14135: @c ---------------------------------------------------------------------
14136: @node exception-idef, , The optional Exception word set, The optional Exception word set
14137: @subsection Implementation Defined Options
14138: @c ---------------------------------------------------------------------
14139: @cindex implementation-defined options, exception words
14140: @cindex exception words, implementation-defined options
14141:
14142: @table @i
14143: @item @code{THROW}-codes used in the system:
14144: @cindex @code{THROW}-codes used in the system
14145: The codes -256@minus{}-511 are used for reporting signals. The mapping
1.29 crook 14146: from OS signal numbers to throw codes is -256@minus{}@i{signal}. The
1.1 anton 14147: codes -512@minus{}-2047 are used for OS errors (for file and memory
14148: allocation operations). The mapping from OS error numbers to throw codes
14149: is -512@minus{}@code{errno}. One side effect of this mapping is that
14150: undefined OS errors produce a message with a strange number; e.g.,
14151: @code{-1000 THROW} results in @code{Unknown error 488} on my system.
14152: @end table
14153:
14154: @c =====================================================================
14155: @node The optional Facility word set, The optional File-Access word set, The optional Exception word set, ANS conformance
14156: @section The optional Facility word set
14157: @c =====================================================================
14158: @cindex system documentation, facility words
14159: @cindex facility words, system documentation
14160:
14161: @menu
14162: * facility-idef:: Implementation Defined Options
14163: * facility-ambcond:: Ambiguous Conditions
14164: @end menu
14165:
14166:
14167: @c ---------------------------------------------------------------------
14168: @node facility-idef, facility-ambcond, The optional Facility word set, The optional Facility word set
14169: @subsection Implementation Defined Options
14170: @c ---------------------------------------------------------------------
14171: @cindex implementation-defined options, facility words
14172: @cindex facility words, implementation-defined options
14173:
14174: @table @i
14175: @item encoding of keyboard events (@code{EKEY}):
14176: @cindex keyboard events, encoding in @code{EKEY}
14177: @cindex @code{EKEY}, encoding of keyboard events
1.40 anton 14178: Keys corresponding to ASCII characters are encoded as ASCII characters.
1.41 anton 14179: Other keys are encoded with the constants @code{k-left}, @code{k-right},
14180: @code{k-up}, @code{k-down}, @code{k-home}, @code{k-end}, @code{k1},
14181: @code{k2}, @code{k3}, @code{k4}, @code{k5}, @code{k6}, @code{k7},
14182: @code{k8}, @code{k9}, @code{k10}, @code{k11}, @code{k12}.
1.40 anton 14183:
1.1 anton 14184:
14185: @item duration of a system clock tick:
14186: @cindex duration of a system clock tick
14187: @cindex clock tick duration
14188: System dependent. With respect to @code{MS}, the time is specified in
14189: microseconds. How well the OS and the hardware implement this, is
14190: another question.
14191:
14192: @item repeatability to be expected from the execution of @code{MS}:
14193: @cindex repeatability to be expected from the execution of @code{MS}
14194: @cindex @code{MS}, repeatability to be expected
14195: System dependent. On Unix, a lot depends on load. If the system is
14196: lightly loaded, and the delay is short enough that Gforth does not get
14197: swapped out, the performance should be acceptable. Under MS-DOS and
14198: other single-tasking systems, it should be good.
14199:
14200: @end table
14201:
14202:
14203: @c ---------------------------------------------------------------------
14204: @node facility-ambcond, , facility-idef, The optional Facility word set
14205: @subsection Ambiguous conditions
14206: @c ---------------------------------------------------------------------
14207: @cindex facility words, ambiguous conditions
14208: @cindex ambiguous conditions, facility words
14209:
14210: @table @i
14211: @item @code{AT-XY} can't be performed on user output device:
14212: @cindex @code{AT-XY} can't be performed on user output device
14213: Largely terminal dependent. No range checks are done on the arguments.
14214: No errors are reported. You may see some garbage appearing, you may see
14215: simply nothing happen.
14216:
14217: @end table
14218:
14219:
14220: @c =====================================================================
14221: @node The optional File-Access word set, The optional Floating-Point word set, The optional Facility word set, ANS conformance
14222: @section The optional File-Access word set
14223: @c =====================================================================
14224: @cindex system documentation, file words
14225: @cindex file words, system documentation
14226:
14227: @menu
14228: * file-idef:: Implementation Defined Options
14229: * file-ambcond:: Ambiguous Conditions
14230: @end menu
14231:
14232: @c ---------------------------------------------------------------------
14233: @node file-idef, file-ambcond, The optional File-Access word set, The optional File-Access word set
14234: @subsection Implementation Defined Options
14235: @c ---------------------------------------------------------------------
14236: @cindex implementation-defined options, file words
14237: @cindex file words, implementation-defined options
14238:
14239: @table @i
14240: @item file access methods used:
14241: @cindex file access methods used
14242: @code{R/O}, @code{R/W} and @code{BIN} work as you would
14243: expect. @code{W/O} translates into the C file opening mode @code{w} (or
14244: @code{wb}): The file is cleared, if it exists, and created, if it does
14245: not (with both @code{open-file} and @code{create-file}). Under Unix
14246: @code{create-file} creates a file with 666 permissions modified by your
14247: umask.
14248:
14249: @item file exceptions:
14250: @cindex file exceptions
14251: The file words do not raise exceptions (except, perhaps, memory access
14252: faults when you pass illegal addresses or file-ids).
14253:
14254: @item file line terminator:
14255: @cindex file line terminator
14256: System-dependent. Gforth uses C's newline character as line
14257: terminator. What the actual character code(s) of this are is
14258: system-dependent.
14259:
14260: @item file name format:
14261: @cindex file name format
14262: System dependent. Gforth just uses the file name format of your OS.
14263:
14264: @item information returned by @code{FILE-STATUS}:
14265: @cindex @code{FILE-STATUS}, returned information
14266: @code{FILE-STATUS} returns the most powerful file access mode allowed
14267: for the file: Either @code{R/O}, @code{W/O} or @code{R/W}. If the file
14268: cannot be accessed, @code{R/O BIN} is returned. @code{BIN} is applicable
14269: along with the returned mode.
14270:
14271: @item input file state after an exception when including source:
14272: @cindex exception when including source
14273: All files that are left via the exception are closed.
14274:
1.29 crook 14275: @item @i{ior} values and meaning:
14276: @cindex @i{ior} values and meaning
1.68 anton 14277: @cindex @i{wior} values and meaning
1.29 crook 14278: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14279: intended as throw codes. They typically are in the range
14280: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14281: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14282:
14283: @item maximum depth of file input nesting:
14284: @cindex maximum depth of file input nesting
14285: @cindex file input nesting, maximum depth
14286: limited by the amount of return stack, locals/TIB stack, and the number
14287: of open files available. This should not give you troubles.
14288:
14289: @item maximum size of input line:
14290: @cindex maximum size of input line
14291: @cindex input line size, maximum
14292: @code{/line}. Currently 255.
14293:
14294: @item methods of mapping block ranges to files:
14295: @cindex mapping block ranges to files
14296: @cindex files containing blocks
14297: @cindex blocks in files
14298: By default, blocks are accessed in the file @file{blocks.fb} in the
14299: current working directory. The file can be switched with @code{USE}.
14300:
14301: @item number of string buffers provided by @code{S"}:
14302: @cindex @code{S"}, number of string buffers
14303: 1
14304:
14305: @item size of string buffer used by @code{S"}:
14306: @cindex @code{S"}, size of string buffer
14307: @code{/line}. currently 255.
14308:
14309: @end table
14310:
14311: @c ---------------------------------------------------------------------
14312: @node file-ambcond, , file-idef, The optional File-Access word set
14313: @subsection Ambiguous conditions
14314: @c ---------------------------------------------------------------------
14315: @cindex file words, ambiguous conditions
14316: @cindex ambiguous conditions, file words
14317:
14318: @table @i
14319: @item attempting to position a file outside its boundaries:
14320: @cindex @code{REPOSITION-FILE}, outside the file's boundaries
14321: @code{REPOSITION-FILE} is performed as usual: Afterwards,
14322: @code{FILE-POSITION} returns the value given to @code{REPOSITION-FILE}.
14323:
14324: @item attempting to read from file positions not yet written:
14325: @cindex reading from file positions not yet written
14326: End-of-file, i.e., zero characters are read and no error is reported.
14327:
1.29 crook 14328: @item @i{file-id} is invalid (@code{INCLUDE-FILE}):
14329: @cindex @code{INCLUDE-FILE}, @i{file-id} is invalid
1.1 anton 14330: An appropriate exception may be thrown, but a memory fault or other
14331: problem is more probable.
14332:
1.29 crook 14333: @item I/O exception reading or closing @i{file-id} (@code{INCLUDE-FILE}, @code{INCLUDED}):
14334: @cindex @code{INCLUDE-FILE}, I/O exception reading or closing @i{file-id}
14335: @cindex @code{INCLUDED}, I/O exception reading or closing @i{file-id}
14336: The @i{ior} produced by the operation, that discovered the problem, is
1.1 anton 14337: thrown.
14338:
14339: @item named file cannot be opened (@code{INCLUDED}):
14340: @cindex @code{INCLUDED}, named file cannot be opened
1.29 crook 14341: The @i{ior} produced by @code{open-file} is thrown.
1.1 anton 14342:
14343: @item requesting an unmapped block number:
14344: @cindex unmapped block numbers
14345: There are no unmapped legal block numbers. On some operating systems,
14346: writing a block with a large number may overflow the file system and
14347: have an error message as consequence.
14348:
14349: @item using @code{source-id} when @code{blk} is non-zero:
14350: @cindex @code{SOURCE-ID}, behaviour when @code{BLK} is non-zero
14351: @code{source-id} performs its function. Typically it will give the id of
14352: the source which loaded the block. (Better ideas?)
14353:
14354: @end table
14355:
14356:
14357: @c =====================================================================
14358: @node The optional Floating-Point word set, The optional Locals word set, The optional File-Access word set, ANS conformance
14359: @section The optional Floating-Point word set
14360: @c =====================================================================
14361: @cindex system documentation, floating-point words
14362: @cindex floating-point words, system documentation
14363:
14364: @menu
14365: * floating-idef:: Implementation Defined Options
14366: * floating-ambcond:: Ambiguous Conditions
14367: @end menu
14368:
14369:
14370: @c ---------------------------------------------------------------------
14371: @node floating-idef, floating-ambcond, The optional Floating-Point word set, The optional Floating-Point word set
14372: @subsection Implementation Defined Options
14373: @c ---------------------------------------------------------------------
14374: @cindex implementation-defined options, floating-point words
14375: @cindex floating-point words, implementation-defined options
14376:
14377: @table @i
14378: @item format and range of floating point numbers:
14379: @cindex format and range of floating point numbers
14380: @cindex floating point numbers, format and range
14381: System-dependent; the @code{double} type of C.
14382:
1.29 crook 14383: @item results of @code{REPRESENT} when @i{float} is out of range:
14384: @cindex @code{REPRESENT}, results when @i{float} is out of range
1.1 anton 14385: System dependent; @code{REPRESENT} is implemented using the C library
14386: function @code{ecvt()} and inherits its behaviour in this respect.
14387:
14388: @item rounding or truncation of floating-point numbers:
14389: @cindex rounding of floating-point numbers
14390: @cindex truncation of floating-point numbers
14391: @cindex floating-point numbers, rounding or truncation
14392: System dependent; the rounding behaviour is inherited from the hosting C
14393: compiler. IEEE-FP-based (i.e., most) systems by default round to
14394: nearest, and break ties by rounding to even (i.e., such that the last
14395: bit of the mantissa is 0).
14396:
14397: @item size of floating-point stack:
14398: @cindex floating-point stack size
14399: @code{s" FLOATING-STACK" environment? drop .} gives the total size of
14400: the floating-point stack (in floats). You can specify this on startup
14401: with the command-line option @code{-f} (@pxref{Invoking Gforth}).
14402:
14403: @item width of floating-point stack:
14404: @cindex floating-point stack width
14405: @code{1 floats}.
14406:
14407: @end table
14408:
14409:
14410: @c ---------------------------------------------------------------------
14411: @node floating-ambcond, , floating-idef, The optional Floating-Point word set
14412: @subsection Ambiguous conditions
14413: @c ---------------------------------------------------------------------
14414: @cindex floating-point words, ambiguous conditions
14415: @cindex ambiguous conditions, floating-point words
14416:
14417: @table @i
14418: @item @code{df@@} or @code{df!} used with an address that is not double-float aligned:
14419: @cindex @code{df@@} or @code{df!} used with an address that is not double-float aligned
14420: System-dependent. Typically results in a @code{-23 THROW} like other
14421: alignment violations.
14422:
14423: @item @code{f@@} or @code{f!} used with an address that is not float aligned:
14424: @cindex @code{f@@} used with an address that is not float aligned
14425: @cindex @code{f!} used with an address that is not float aligned
14426: System-dependent. Typically results in a @code{-23 THROW} like other
14427: alignment violations.
14428:
14429: @item floating-point result out of range:
14430: @cindex floating-point result out of range
1.80 anton 14431: System-dependent. Can result in a @code{-43 throw} (floating point
14432: overflow), @code{-54 throw} (floating point underflow), @code{-41 throw}
14433: (floating point inexact result), @code{-55 THROW} (Floating-point
1.1 anton 14434: unidentified fault), or can produce a special value representing, e.g.,
14435: Infinity.
14436:
14437: @item @code{sf@@} or @code{sf!} used with an address that is not single-float aligned:
14438: @cindex @code{sf@@} or @code{sf!} used with an address that is not single-float aligned
14439: System-dependent. Typically results in an alignment fault like other
14440: alignment violations.
14441:
1.35 anton 14442: @item @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.}):
14443: @cindex @code{base} is not decimal (@code{REPRESENT}, @code{F.}, @code{FE.}, @code{FS.})
1.1 anton 14444: The floating-point number is converted into decimal nonetheless.
14445:
14446: @item Both arguments are equal to zero (@code{FATAN2}):
14447: @cindex @code{FATAN2}, both arguments are equal to zero
14448: System-dependent. @code{FATAN2} is implemented using the C library
14449: function @code{atan2()}.
14450:
1.29 crook 14451: @item Using @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero:
14452: @cindex @code{FTAN} on an argument @i{r1} where cos(@i{r1}) is zero
14453: System-dependent. Anyway, typically the cos of @i{r1} will not be zero
1.1 anton 14454: because of small errors and the tan will be a very large (or very small)
14455: but finite number.
14456:
1.29 crook 14457: @item @i{d} cannot be presented precisely as a float in @code{D>F}:
14458: @cindex @code{D>F}, @i{d} cannot be presented precisely as a float
1.1 anton 14459: The result is rounded to the nearest float.
14460:
14461: @item dividing by zero:
14462: @cindex dividing by zero, floating-point
14463: @cindex floating-point dividing by zero
14464: @cindex floating-point unidentified fault, FP divide-by-zero
1.80 anton 14465: Platform-dependent; can produce an Infinity, NaN, @code{-42 throw}
14466: (floating point divide by zero) or @code{-55 throw} (Floating-point
14467: unidentified fault).
1.1 anton 14468:
14469: @item exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@}):
14470: @cindex exponent too big for conversion (@code{DF!}, @code{DF@@}, @code{SF!}, @code{SF@@})
14471: System dependent. On IEEE-FP based systems the number is converted into
14472: an infinity.
14473:
1.29 crook 14474: @item @i{float}<1 (@code{FACOSH}):
14475: @cindex @code{FACOSH}, @i{float}<1
1.1 anton 14476: @cindex floating-point unidentified fault, @code{FACOSH}
1.80 anton 14477: Platform-dependent; on IEEE-FP systems typically produces a NaN.
1.1 anton 14478:
1.29 crook 14479: @item @i{float}=<-1 (@code{FLNP1}):
14480: @cindex @code{FLNP1}, @i{float}=<-1
1.1 anton 14481: @cindex floating-point unidentified fault, @code{FLNP1}
1.80 anton 14482: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14483: negative infinity for @i{float}=-1).
1.1 anton 14484:
1.29 crook 14485: @item @i{float}=<0 (@code{FLN}, @code{FLOG}):
14486: @cindex @code{FLN}, @i{float}=<0
14487: @cindex @code{FLOG}, @i{float}=<0
1.1 anton 14488: @cindex floating-point unidentified fault, @code{FLN} or @code{FLOG}
1.80 anton 14489: Platform-dependent; on IEEE-FP systems typically produces a NaN (or a
14490: negative infinity for @i{float}=0).
1.1 anton 14491:
1.29 crook 14492: @item @i{float}<0 (@code{FASINH}, @code{FSQRT}):
14493: @cindex @code{FASINH}, @i{float}<0
14494: @cindex @code{FSQRT}, @i{float}<0
1.1 anton 14495: @cindex floating-point unidentified fault, @code{FASINH} or @code{FSQRT}
1.80 anton 14496: Platform-dependent; for @code{fsqrt} this typically gives a NaN, for
14497: @code{fasinh} some platforms produce a NaN, others a number (bug in the
14498: C library?).
1.1 anton 14499:
1.29 crook 14500: @item |@i{float}|>1 (@code{FACOS}, @code{FASIN}, @code{FATANH}):
14501: @cindex @code{FACOS}, |@i{float}|>1
14502: @cindex @code{FASIN}, |@i{float}|>1
14503: @cindex @code{FATANH}, |@i{float}|>1
1.1 anton 14504: @cindex floating-point unidentified fault, @code{FACOS}, @code{FASIN} or @code{FATANH}
1.80 anton 14505: Platform-dependent; IEEE-FP systems typically produce a NaN.
1.1 anton 14506:
1.29 crook 14507: @item integer part of float cannot be represented by @i{d} in @code{F>D}:
14508: @cindex @code{F>D}, integer part of float cannot be represented by @i{d}
1.1 anton 14509: @cindex floating-point unidentified fault, @code{F>D}
1.80 anton 14510: Platform-dependent; typically, some double number is produced and no
14511: error is reported.
1.1 anton 14512:
14513: @item string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.}):
14514: @cindex string larger than pictured numeric output area (@code{f.}, @code{fe.}, @code{fs.})
1.80 anton 14515: @code{Precision} characters of the numeric output area are used. If
14516: @code{precision} is too high, these words will smash the data or code
14517: close to @code{here}.
1.1 anton 14518: @end table
14519:
14520: @c =====================================================================
14521: @node The optional Locals word set, The optional Memory-Allocation word set, The optional Floating-Point word set, ANS conformance
14522: @section The optional Locals word set
14523: @c =====================================================================
14524: @cindex system documentation, locals words
14525: @cindex locals words, system documentation
14526:
14527: @menu
14528: * locals-idef:: Implementation Defined Options
14529: * locals-ambcond:: Ambiguous Conditions
14530: @end menu
14531:
14532:
14533: @c ---------------------------------------------------------------------
14534: @node locals-idef, locals-ambcond, The optional Locals word set, The optional Locals word set
14535: @subsection Implementation Defined Options
14536: @c ---------------------------------------------------------------------
14537: @cindex implementation-defined options, locals words
14538: @cindex locals words, implementation-defined options
14539:
14540: @table @i
14541: @item maximum number of locals in a definition:
14542: @cindex maximum number of locals in a definition
14543: @cindex locals, maximum number in a definition
14544: @code{s" #locals" environment? drop .}. Currently 15. This is a lower
14545: bound, e.g., on a 32-bit machine there can be 41 locals of up to 8
14546: characters. The number of locals in a definition is bounded by the size
14547: of locals-buffer, which contains the names of the locals.
14548:
14549: @end table
14550:
14551:
14552: @c ---------------------------------------------------------------------
14553: @node locals-ambcond, , locals-idef, The optional Locals word set
14554: @subsection Ambiguous conditions
14555: @c ---------------------------------------------------------------------
14556: @cindex locals words, ambiguous conditions
14557: @cindex ambiguous conditions, locals words
14558:
14559: @table @i
14560: @item executing a named local in interpretation state:
14561: @cindex local in interpretation state
14562: @cindex Interpreting a compile-only word, for a local
14563: Locals have no interpretation semantics. If you try to perform the
14564: interpretation semantics, you will get a @code{-14 throw} somewhere
14565: (Interpreting a compile-only word). If you perform the compilation
14566: semantics, the locals access will be compiled (irrespective of state).
14567:
1.29 crook 14568: @item @i{name} not defined by @code{VALUE} or @code{(LOCAL)} (@code{TO}):
1.1 anton 14569: @cindex name not defined by @code{VALUE} or @code{(LOCAL)} used by @code{TO}
14570: @cindex @code{TO} on non-@code{VALUE}s and non-locals
14571: @cindex Invalid name argument, @code{TO}
14572: @code{-32 throw} (Invalid name argument)
14573:
14574: @end table
14575:
14576:
14577: @c =====================================================================
14578: @node The optional Memory-Allocation word set, The optional Programming-Tools word set, The optional Locals word set, ANS conformance
14579: @section The optional Memory-Allocation word set
14580: @c =====================================================================
14581: @cindex system documentation, memory-allocation words
14582: @cindex memory-allocation words, system documentation
14583:
14584: @menu
14585: * memory-idef:: Implementation Defined Options
14586: @end menu
14587:
14588:
14589: @c ---------------------------------------------------------------------
14590: @node memory-idef, , The optional Memory-Allocation word set, The optional Memory-Allocation word set
14591: @subsection Implementation Defined Options
14592: @c ---------------------------------------------------------------------
14593: @cindex implementation-defined options, memory-allocation words
14594: @cindex memory-allocation words, implementation-defined options
14595:
14596: @table @i
1.29 crook 14597: @item values and meaning of @i{ior}:
14598: @cindex @i{ior} values and meaning
14599: The @i{ior}s returned by the file and memory allocation words are
1.1 anton 14600: intended as throw codes. They typically are in the range
14601: -512@minus{}-2047 of OS errors. The mapping from OS error numbers to
1.29 crook 14602: @i{ior}s is -512@minus{}@i{errno}.
1.1 anton 14603:
14604: @end table
14605:
14606: @c =====================================================================
14607: @node The optional Programming-Tools word set, The optional Search-Order word set, The optional Memory-Allocation word set, ANS conformance
14608: @section The optional Programming-Tools word set
14609: @c =====================================================================
14610: @cindex system documentation, programming-tools words
14611: @cindex programming-tools words, system documentation
14612:
14613: @menu
14614: * programming-idef:: Implementation Defined Options
14615: * programming-ambcond:: Ambiguous Conditions
14616: @end menu
14617:
14618:
14619: @c ---------------------------------------------------------------------
14620: @node programming-idef, programming-ambcond, The optional Programming-Tools word set, The optional Programming-Tools word set
14621: @subsection Implementation Defined Options
14622: @c ---------------------------------------------------------------------
14623: @cindex implementation-defined options, programming-tools words
14624: @cindex programming-tools words, implementation-defined options
14625:
14626: @table @i
14627: @item ending sequence for input following @code{;CODE} and @code{CODE}:
14628: @cindex @code{;CODE} ending sequence
14629: @cindex @code{CODE} ending sequence
14630: @code{END-CODE}
14631:
14632: @item manner of processing input following @code{;CODE} and @code{CODE}:
14633: @cindex @code{;CODE}, processing input
14634: @cindex @code{CODE}, processing input
14635: The @code{ASSEMBLER} vocabulary is pushed on the search order stack, and
14636: the input is processed by the text interpreter, (starting) in interpret
14637: state.
14638:
14639: @item search order capability for @code{EDITOR} and @code{ASSEMBLER}:
14640: @cindex @code{ASSEMBLER}, search order capability
14641: The ANS Forth search order word set.
14642:
14643: @item source and format of display by @code{SEE}:
14644: @cindex @code{SEE}, source and format of output
1.80 anton 14645: The source for @code{see} is the executable code used by the inner
1.1 anton 14646: interpreter. The current @code{see} tries to output Forth source code
1.80 anton 14647: (and on some platforms, assembly code for primitives) as well as
14648: possible.
1.1 anton 14649:
14650: @end table
14651:
14652: @c ---------------------------------------------------------------------
14653: @node programming-ambcond, , programming-idef, The optional Programming-Tools word set
14654: @subsection Ambiguous conditions
14655: @c ---------------------------------------------------------------------
14656: @cindex programming-tools words, ambiguous conditions
14657: @cindex ambiguous conditions, programming-tools words
14658:
14659: @table @i
14660:
1.21 crook 14661: @item deleting the compilation word list (@code{FORGET}):
14662: @cindex @code{FORGET}, deleting the compilation word list
1.1 anton 14663: Not implemented (yet).
14664:
1.29 crook 14665: @item fewer than @i{u}+1 items on the control-flow stack (@code{CS-PICK}, @code{CS-ROLL}):
14666: @cindex @code{CS-PICK}, fewer than @i{u}+1 items on the control flow-stack
14667: @cindex @code{CS-ROLL}, fewer than @i{u}+1 items on the control flow-stack
1.1 anton 14668: @cindex control-flow stack underflow
14669: This typically results in an @code{abort"} with a descriptive error
14670: message (may change into a @code{-22 throw} (Control structure mismatch)
14671: in the future). You may also get a memory access error. If you are
14672: unlucky, this ambiguous condition is not caught.
14673:
1.29 crook 14674: @item @i{name} can't be found (@code{FORGET}):
14675: @cindex @code{FORGET}, @i{name} can't be found
1.1 anton 14676: Not implemented (yet).
14677:
1.29 crook 14678: @item @i{name} not defined via @code{CREATE}:
14679: @cindex @code{;CODE}, @i{name} not defined via @code{CREATE}
1.1 anton 14680: @code{;CODE} behaves like @code{DOES>} in this respect, i.e., it changes
14681: the execution semantics of the last defined word no matter how it was
14682: defined.
14683:
14684: @item @code{POSTPONE} applied to @code{[IF]}:
14685: @cindex @code{POSTPONE} applied to @code{[IF]}
14686: @cindex @code{[IF]} and @code{POSTPONE}
14687: After defining @code{: X POSTPONE [IF] ; IMMEDIATE}. @code{X} is
14688: equivalent to @code{[IF]}.
14689:
14690: @item reaching the end of the input source before matching @code{[ELSE]} or @code{[THEN]}:
14691: @cindex @code{[IF]}, end of the input source before matching @code{[ELSE]} or @code{[THEN]}
14692: Continue in the same state of conditional compilation in the next outer
14693: input source. Currently there is no warning to the user about this.
14694:
14695: @item removing a needed definition (@code{FORGET}):
14696: @cindex @code{FORGET}, removing a needed definition
14697: Not implemented (yet).
14698:
14699: @end table
14700:
14701:
14702: @c =====================================================================
14703: @node The optional Search-Order word set, , The optional Programming-Tools word set, ANS conformance
14704: @section The optional Search-Order word set
14705: @c =====================================================================
14706: @cindex system documentation, search-order words
14707: @cindex search-order words, system documentation
14708:
14709: @menu
14710: * search-idef:: Implementation Defined Options
14711: * search-ambcond:: Ambiguous Conditions
14712: @end menu
14713:
14714:
14715: @c ---------------------------------------------------------------------
14716: @node search-idef, search-ambcond, The optional Search-Order word set, The optional Search-Order word set
14717: @subsection Implementation Defined Options
14718: @c ---------------------------------------------------------------------
14719: @cindex implementation-defined options, search-order words
14720: @cindex search-order words, implementation-defined options
14721:
14722: @table @i
14723: @item maximum number of word lists in search order:
14724: @cindex maximum number of word lists in search order
14725: @cindex search order, maximum depth
14726: @code{s" wordlists" environment? drop .}. Currently 16.
14727:
14728: @item minimum search order:
14729: @cindex minimum search order
14730: @cindex search order, minimum
14731: @code{root root}.
14732:
14733: @end table
14734:
14735: @c ---------------------------------------------------------------------
14736: @node search-ambcond, , search-idef, The optional Search-Order word set
14737: @subsection Ambiguous conditions
14738: @c ---------------------------------------------------------------------
14739: @cindex search-order words, ambiguous conditions
14740: @cindex ambiguous conditions, search-order words
14741:
14742: @table @i
1.21 crook 14743: @item changing the compilation word list (during compilation):
14744: @cindex changing the compilation word list (during compilation)
14745: @cindex compilation word list, change before definition ends
14746: The word is entered into the word list that was the compilation word list
1.1 anton 14747: at the start of the definition. Any changes to the name field (e.g.,
14748: @code{immediate}) or the code field (e.g., when executing @code{DOES>})
1.116 anton 14749: are applied to the latest defined word (as reported by @code{latest} or
14750: @code{latestxt}), if possible, irrespective of the compilation word list.
1.1 anton 14751:
14752: @item search order empty (@code{previous}):
14753: @cindex @code{previous}, search order empty
1.26 crook 14754: @cindex vocstack empty, @code{previous}
1.1 anton 14755: @code{abort" Vocstack empty"}.
14756:
14757: @item too many word lists in search order (@code{also}):
14758: @cindex @code{also}, too many word lists in search order
1.26 crook 14759: @cindex vocstack full, @code{also}
1.1 anton 14760: @code{abort" Vocstack full"}.
14761:
14762: @end table
14763:
14764: @c ***************************************************************
1.65 anton 14765: @node Standard vs Extensions, Model, ANS conformance, Top
14766: @chapter Should I use Gforth extensions?
14767: @cindex Gforth extensions
14768:
14769: As you read through the rest of this manual, you will see documentation
14770: for @i{Standard} words, and documentation for some appealing Gforth
14771: @i{extensions}. You might ask yourself the question: @i{``Should I
14772: restrict myself to the standard, or should I use the extensions?''}
14773:
14774: The answer depends on the goals you have for the program you are working
14775: on:
14776:
14777: @itemize @bullet
14778:
14779: @item Is it just for yourself or do you want to share it with others?
14780:
14781: @item
14782: If you want to share it, do the others all use Gforth?
14783:
14784: @item
14785: If it is just for yourself, do you want to restrict yourself to Gforth?
14786:
14787: @end itemize
14788:
14789: If restricting the program to Gforth is ok, then there is no reason not
14790: to use extensions. It is still a good idea to keep to the standard
14791: where it is easy, in case you want to reuse these parts in another
14792: program that you want to be portable.
14793:
14794: If you want to be able to port the program to other Forth systems, there
14795: are the following points to consider:
14796:
14797: @itemize @bullet
14798:
14799: @item
14800: Most Forth systems that are being maintained support the ANS Forth
14801: standard. So if your program complies with the standard, it will be
14802: portable among many systems.
14803:
14804: @item
14805: A number of the Gforth extensions can be implemented in ANS Forth using
14806: public-domain files provided in the @file{compat/} directory. These are
14807: mentioned in the text in passing. There is no reason not to use these
14808: extensions, your program will still be ANS Forth compliant; just include
14809: the appropriate compat files with your program.
14810:
14811: @item
14812: The tool @file{ans-report.fs} (@pxref{ANS Report}) makes it easy to
14813: analyse your program and determine what non-Standard words it relies
14814: upon. However, it does not check whether you use standard words in a
14815: non-standard way.
14816:
14817: @item
14818: Some techniques are not standardized by ANS Forth, and are hard or
14819: impossible to implement in a standard way, but can be implemented in
14820: most Forth systems easily, and usually in similar ways (e.g., accessing
14821: word headers). Forth has a rich historical precedent for programmers
14822: taking advantage of implementation-dependent features of their tools
14823: (for example, relying on a knowledge of the dictionary
14824: structure). Sometimes these techniques are necessary to extract every
14825: last bit of performance from the hardware, sometimes they are just a
14826: programming shorthand.
14827:
14828: @item
14829: Does using a Gforth extension save more work than the porting this part
14830: to other Forth systems (if any) will cost?
14831:
14832: @item
14833: Is the additional functionality worth the reduction in portability and
14834: the additional porting problems?
14835:
14836: @end itemize
14837:
14838: In order to perform these consideratios, you need to know what's
14839: standard and what's not. This manual generally states if something is
1.81 anton 14840: non-standard, but the authoritative source is the
14841: @uref{http://www.taygeta.com/forth/dpans.html,standard document}.
1.65 anton 14842: Appendix A of the Standard (@var{Rationale}) provides a valuable insight
14843: into the thought processes of the technical committee.
14844:
14845: Note also that portability between Forth systems is not the only
14846: portability issue; there is also the issue of portability between
14847: different platforms (processor/OS combinations).
14848:
14849: @c ***************************************************************
14850: @node Model, Integrating Gforth, Standard vs Extensions, Top
1.1 anton 14851: @chapter Model
14852:
14853: This chapter has yet to be written. It will contain information, on
14854: which internal structures you can rely.
14855:
14856: @c ***************************************************************
14857: @node Integrating Gforth, Emacs and Gforth, Model, Top
14858: @chapter Integrating Gforth into C programs
14859:
14860: This is not yet implemented.
14861:
14862: Several people like to use Forth as scripting language for applications
14863: that are otherwise written in C, C++, or some other language.
14864:
14865: The Forth system ATLAST provides facilities for embedding it into
14866: applications; unfortunately it has several disadvantages: most
14867: importantly, it is not based on ANS Forth, and it is apparently dead
14868: (i.e., not developed further and not supported). The facilities
1.21 crook 14869: provided by Gforth in this area are inspired by ATLAST's facilities, so
1.1 anton 14870: making the switch should not be hard.
14871:
14872: We also tried to design the interface such that it can easily be
14873: implemented by other Forth systems, so that we may one day arrive at a
14874: standardized interface. Such a standard interface would allow you to
14875: replace the Forth system without having to rewrite C code.
14876:
14877: You embed the Gforth interpreter by linking with the library
14878: @code{libgforth.a} (give the compiler the option @code{-lgforth}). All
14879: global symbols in this library that belong to the interface, have the
14880: prefix @code{forth_}. (Global symbols that are used internally have the
14881: prefix @code{gforth_}).
14882:
14883: You can include the declarations of Forth types and the functions and
14884: variables of the interface with @code{#include <forth.h>}.
14885:
14886: Types.
14887:
14888: Variables.
14889:
14890: Data and FP Stack pointer. Area sizes.
14891:
14892: functions.
14893:
14894: forth_init(imagefile)
14895: forth_evaluate(string) exceptions?
14896: forth_goto(address) (or forth_execute(xt)?)
14897: forth_continue() (a corountining mechanism)
14898:
14899: Adding primitives.
14900:
14901: No checking.
14902:
14903: Signals?
14904:
14905: Accessing the Stacks
14906:
1.26 crook 14907: @c ******************************************************************
1.1 anton 14908: @node Emacs and Gforth, Image Files, Integrating Gforth, Top
14909: @chapter Emacs and Gforth
14910: @cindex Emacs and Gforth
14911:
14912: @cindex @file{gforth.el}
14913: @cindex @file{forth.el}
14914: @cindex Rydqvist, Goran
1.107 dvdkhlng 14915: @cindex Kuehling, David
1.1 anton 14916: @cindex comment editing commands
14917: @cindex @code{\}, editing with Emacs
14918: @cindex debug tracer editing commands
14919: @cindex @code{~~}, removal with Emacs
14920: @cindex Forth mode in Emacs
1.107 dvdkhlng 14921:
1.1 anton 14922: Gforth comes with @file{gforth.el}, an improved version of
14923: @file{forth.el} by Goran Rydqvist (included in the TILE package). The
1.26 crook 14924: improvements are:
14925:
14926: @itemize @bullet
14927: @item
1.107 dvdkhlng 14928: A better handling of indentation.
14929: @item
14930: A custom hilighting engine for Forth-code.
1.26 crook 14931: @item
14932: Comment paragraph filling (@kbd{M-q})
14933: @item
14934: Commenting (@kbd{C-x \}) and uncommenting (@kbd{C-u C-x \}) of regions
14935: @item
14936: Removal of debugging tracers (@kbd{C-x ~}, @pxref{Debugging}).
1.41 anton 14937: @item
14938: Support of the @code{info-lookup} feature for looking up the
14939: documentation of a word.
1.107 dvdkhlng 14940: @item
14941: Support for reading and writing blocks files.
1.26 crook 14942: @end itemize
14943:
1.107 dvdkhlng 14944: To get a basic description of these features, enter Forth mode and
14945: type @kbd{C-h m}.
1.1 anton 14946:
14947: @cindex source location of error or debugging output in Emacs
14948: @cindex error output, finding the source location in Emacs
14949: @cindex debugging output, finding the source location in Emacs
14950: In addition, Gforth supports Emacs quite well: The source code locations
14951: given in error messages, debugging output (from @code{~~}) and failed
14952: assertion messages are in the right format for Emacs' compilation mode
14953: (@pxref{Compilation, , Running Compilations under Emacs, emacs, Emacs
14954: Manual}) so the source location corresponding to an error or other
14955: message is only a few keystrokes away (@kbd{C-x `} for the next error,
14956: @kbd{C-c C-c} for the error under the cursor).
14957:
1.107 dvdkhlng 14958: @cindex viewing the documentation of a word in Emacs
14959: @cindex context-sensitive help
14960: Moreover, for words documented in this manual, you can look up the
14961: glossary entry quickly by using @kbd{C-h TAB}
14962: (@code{info-lookup-symbol}, @pxref{Documentation, ,Documentation
14963: Commands, emacs, Emacs Manual}). This feature requires Emacs 20.3 or
14964: later and does not work for words containing @code{:}.
14965:
14966: @menu
14967: * Installing gforth.el:: Making Emacs aware of Forth.
14968: * Emacs Tags:: Viewing the source of a word in Emacs.
14969: * Hilighting:: Making Forth code look prettier.
14970: * Auto-Indentation:: Customizing auto-indentation.
14971: * Blocks Files:: Reading and writing blocks files.
14972: @end menu
14973:
14974: @c ----------------------------------
1.109 anton 14975: @node Installing gforth.el, Emacs Tags, Emacs and Gforth, Emacs and Gforth
1.107 dvdkhlng 14976: @section Installing gforth.el
14977: @cindex @file{.emacs}
14978: @cindex @file{gforth.el}, installation
14979: To make the features from @file{gforth.el} available in Emacs, add
14980: the following lines to your @file{.emacs} file:
14981:
14982: @example
14983: (autoload 'forth-mode "gforth.el")
14984: (setq auto-mode-alist (cons '("\\.fs\\'" . forth-mode)
14985: auto-mode-alist))
14986: (autoload 'forth-block-mode "gforth.el")
14987: (setq auto-mode-alist (cons '("\\.fb\\'" . forth-block-mode)
14988: auto-mode-alist))
14989: (add-hook 'forth-mode-hook (function (lambda ()
14990: ;; customize variables here:
14991: (setq forth-indent-level 4)
14992: (setq forth-minor-indent-level 2)
14993: (setq forth-hilight-level 3)
14994: ;;; ...
14995: )))
14996: @end example
14997:
14998: @c ----------------------------------
14999: @node Emacs Tags, Hilighting, Installing gforth.el, Emacs and Gforth
15000: @section Emacs Tags
1.1 anton 15001: @cindex @file{TAGS} file
15002: @cindex @file{etags.fs}
15003: @cindex viewing the source of a word in Emacs
1.43 anton 15004: @cindex @code{require}, placement in files
15005: @cindex @code{include}, placement in files
1.107 dvdkhlng 15006: If you @code{require} @file{etags.fs}, a new @file{TAGS} file will be
15007: produced (@pxref{Tags, , Tags Tables, emacs, Emacs Manual}) that
1.1 anton 15008: contains the definitions of all words defined afterwards. You can then
1.107 dvdkhlng 15009: find the source for a word using @kbd{M-.}. Note that Emacs can use
1.1 anton 15010: several tags files at the same time (e.g., one for the Gforth sources
15011: and one for your program, @pxref{Select Tags Table,,Selecting a Tags
15012: Table,emacs, Emacs Manual}). The TAGS file for the preloaded words is
15013: @file{$(datadir)/gforth/$(VERSION)/TAGS} (e.g.,
1.43 anton 15014: @file{/usr/local/share/gforth/0.2.0/TAGS}). To get the best behaviour
15015: with @file{etags.fs}, you should avoid putting definitions both before
15016: and after @code{require} etc., otherwise you will see the same file
15017: visited several times by commands like @code{tags-search}.
1.1 anton 15018:
1.107 dvdkhlng 15019: @c ----------------------------------
15020: @node Hilighting, Auto-Indentation, Emacs Tags, Emacs and Gforth
15021: @section Hilighting
15022: @cindex hilighting Forth code in Emacs
15023: @cindex highlighting Forth code in Emacs
15024: @file{gforth.el} comes with a custom source hilighting engine. When
15025: you open a file in @code{forth-mode}, it will be completely parsed,
15026: assigning faces to keywords, comments, strings etc. While you edit
15027: the file, modified regions get parsed and updated on-the-fly.
15028:
15029: Use the variable `forth-hilight-level' to change the level of
15030: decoration from 0 (no hilighting at all) to 3 (the default). Even if
15031: you set the hilighting level to 0, the parser will still work in the
15032: background, collecting information about whether regions of text are
15033: ``compiled'' or ``interpreted''. Those information are required for
15034: auto-indentation to work properly. Set `forth-disable-parser' to
15035: non-nil if your computer is too slow to handle parsing. This will
15036: have an impact on the smartness of the auto-indentation engine,
15037: though.
15038:
15039: Sometimes Forth sources define new features that should be hilighted,
15040: new control structures, defining-words etc. You can use the variable
15041: `forth-custom-words' to make @code{forth-mode} hilight additional
15042: words and constructs. See the docstring of `forth-words' for details
15043: (in Emacs, type @kbd{C-h v forth-words}).
15044:
15045: `forth-custom-words' is meant to be customized in your
15046: @file{.emacs} file. To customize hilighing in a file-specific manner,
15047: set `forth-local-words' in a local-variables section at the end of
15048: your source file (@pxref{Local Variables in Files,, Variables, emacs, Emacs Manual}).
15049:
15050: Example:
15051: @example
15052: 0 [IF]
15053: Local Variables:
15054: forth-local-words:
15055: ((("t:") definition-starter (font-lock-keyword-face . 1)
15056: "[ \t\n]" t name (font-lock-function-name-face . 3))
15057: ((";t") definition-ender (font-lock-keyword-face . 1)))
15058: End:
15059: [THEN]
15060: @end example
15061:
15062: @c ----------------------------------
15063: @node Auto-Indentation, Blocks Files, Hilighting, Emacs and Gforth
15064: @section Auto-Indentation
15065: @cindex auto-indentation of Forth code in Emacs
15066: @cindex indentation of Forth code in Emacs
15067: @code{forth-mode} automatically tries to indent lines in a smart way,
15068: whenever you type @key{TAB} or break a line with @kbd{C-m}.
15069:
15070: Simple customization can be achieved by setting
15071: `forth-indent-level' and `forth-minor-indent-level' in your
15072: @file{.emacs} file. For historical reasons @file{gforth.el} indents
15073: per default by multiples of 4 columns. To use the more traditional
15074: 3-column indentation, add the following lines to your @file{.emacs}:
15075:
15076: @example
15077: (add-hook 'forth-mode-hook (function (lambda ()
15078: ;; customize variables here:
15079: (setq forth-indent-level 3)
15080: (setq forth-minor-indent-level 1)
15081: )))
15082: @end example
15083:
15084: If you want indentation to recognize non-default words, customize it
15085: by setting `forth-custom-indent-words' in your @file{.emacs}. See the
15086: docstring of `forth-indent-words' for details (in Emacs, type @kbd{C-h
15087: v forth-indent-words}).
15088:
15089: To customize indentation in a file-specific manner, set
15090: `forth-local-indent-words' in a local-variables section at the end of
15091: your source file (@pxref{Local Variables in Files, Variables,,emacs,
15092: Emacs Manual}).
15093:
15094: Example:
15095: @example
15096: 0 [IF]
15097: Local Variables:
15098: forth-local-indent-words:
15099: ((("t:") (0 . 2) (0 . 2))
15100: ((";t") (-2 . 0) (0 . -2)))
15101: End:
15102: [THEN]
15103: @end example
15104:
15105: @c ----------------------------------
1.109 anton 15106: @node Blocks Files, , Auto-Indentation, Emacs and Gforth
1.107 dvdkhlng 15107: @section Blocks Files
15108: @cindex blocks files, use with Emacs
15109: @code{forth-mode} Autodetects blocks files by checking whether the
15110: length of the first line exceeds 1023 characters. It then tries to
15111: convert the file into normal text format. When you save the file, it
15112: will be written to disk as normal stream-source file.
15113:
15114: If you want to write blocks files, use @code{forth-blocks-mode}. It
15115: inherits all the features from @code{forth-mode}, plus some additions:
1.41 anton 15116:
1.107 dvdkhlng 15117: @itemize @bullet
15118: @item
15119: Files are written to disk in blocks file format.
15120: @item
15121: Screen numbers are displayed in the mode line (enumerated beginning
15122: with the value of `forth-block-base')
15123: @item
15124: Warnings are displayed when lines exceed 64 characters.
15125: @item
15126: The beginning of the currently edited block is marked with an
15127: overlay-arrow.
15128: @end itemize
1.41 anton 15129:
1.107 dvdkhlng 15130: There are some restrictions you should be aware of. When you open a
15131: blocks file that contains tabulator or newline characters, these
15132: characters will be translated into spaces when the file is written
15133: back to disk. If tabs or newlines are encountered during blocks file
15134: reading, an error is output to the echo area. So have a look at the
15135: `*Messages*' buffer, when Emacs' bell rings during reading.
1.1 anton 15136:
1.107 dvdkhlng 15137: Please consult the docstring of @code{forth-blocks-mode} for more
15138: information by typing @kbd{C-h v forth-blocks-mode}).
1.1 anton 15139:
1.26 crook 15140: @c ******************************************************************
1.1 anton 15141: @node Image Files, Engine, Emacs and Gforth, Top
15142: @chapter Image Files
1.26 crook 15143: @cindex image file
15144: @cindex @file{.fi} files
1.1 anton 15145: @cindex precompiled Forth code
15146: @cindex dictionary in persistent form
15147: @cindex persistent form of dictionary
15148:
15149: An image file is a file containing an image of the Forth dictionary,
15150: i.e., compiled Forth code and data residing in the dictionary. By
15151: convention, we use the extension @code{.fi} for image files.
15152:
15153: @menu
1.18 anton 15154: * Image Licensing Issues:: Distribution terms for images.
15155: * Image File Background:: Why have image files?
1.67 anton 15156: * Non-Relocatable Image Files:: don't always work.
1.18 anton 15157: * Data-Relocatable Image Files:: are better.
1.67 anton 15158: * Fully Relocatable Image Files:: better yet.
1.18 anton 15159: * Stack and Dictionary Sizes:: Setting the default sizes for an image.
1.29 crook 15160: * Running Image Files:: @code{gforth -i @i{file}} or @i{file}.
1.18 anton 15161: * Modifying the Startup Sequence:: and turnkey applications.
1.1 anton 15162: @end menu
15163:
1.18 anton 15164: @node Image Licensing Issues, Image File Background, Image Files, Image Files
15165: @section Image Licensing Issues
15166: @cindex license for images
15167: @cindex image license
15168:
15169: An image created with @code{gforthmi} (@pxref{gforthmi}) or
15170: @code{savesystem} (@pxref{Non-Relocatable Image Files}) includes the
15171: original image; i.e., according to copyright law it is a derived work of
15172: the original image.
15173:
15174: Since Gforth is distributed under the GNU GPL, the newly created image
15175: falls under the GNU GPL, too. In particular, this means that if you
15176: distribute the image, you have to make all of the sources for the image
1.113 anton 15177: available, including those you wrote. For details see @ref{Copying, ,
1.18 anton 15178: GNU General Public License (Section 3)}.
15179:
15180: If you create an image with @code{cross} (@pxref{cross.fs}), the image
15181: contains only code compiled from the sources you gave it; if none of
15182: these sources is under the GPL, the terms discussed above do not apply
15183: to the image. However, if your image needs an engine (a gforth binary)
15184: that is under the GPL, you should make sure that you distribute both in
15185: a way that is at most a @emph{mere aggregation}, if you don't want the
15186: terms of the GPL to apply to the image.
15187:
15188: @node Image File Background, Non-Relocatable Image Files, Image Licensing Issues, Image Files
1.1 anton 15189: @section Image File Background
15190: @cindex image file background
15191:
1.80 anton 15192: Gforth consists not only of primitives (in the engine), but also of
1.1 anton 15193: definitions written in Forth. Since the Forth compiler itself belongs to
15194: those definitions, it is not possible to start the system with the
1.80 anton 15195: engine and the Forth source alone. Therefore we provide the Forth
1.26 crook 15196: code as an image file in nearly executable form. When Gforth starts up,
15197: a C routine loads the image file into memory, optionally relocates the
15198: addresses, then sets up the memory (stacks etc.) according to
15199: information in the image file, and (finally) starts executing Forth
15200: code.
1.1 anton 15201:
1.204 anton 15202: The default image file is @file{gforth.fi} (in the @code{GFORTHPATH}).
15203: You can use a different image by using the @code{-i},
15204: @code{--image-file} or @code{--appl-image} options (@pxref{Invoking
15205: Gforth}), e.g.:
15206:
15207: @example
15208: gforth-fast -i myimage.fi
15209: @end example
15210:
15211: There are different variants of image files, and they represent
15212: different compromises between the goals of making it easy to generate
15213: image files and making them portable.
1.1 anton 15214:
15215: @cindex relocation at run-time
1.26 crook 15216: Win32Forth 3.4 and Mitch Bradley's @code{cforth} use relocation at
1.1 anton 15217: run-time. This avoids many of the complications discussed below (image
15218: files are data relocatable without further ado), but costs performance
1.204 anton 15219: (one addition per memory access) and makes it difficult to pass
15220: addresses between Forth and library calls or other programs.
1.1 anton 15221:
15222: @cindex relocation at load-time
1.26 crook 15223: By contrast, the Gforth loader performs relocation at image load time. The
15224: loader also has to replace tokens that represent primitive calls with the
1.1 anton 15225: appropriate code-field addresses (or code addresses in the case of
15226: direct threading).
15227:
15228: There are three kinds of image files, with different degrees of
15229: relocatability: non-relocatable, data-relocatable, and fully relocatable
15230: image files.
15231:
15232: @cindex image file loader
15233: @cindex relocating loader
15234: @cindex loader for image files
15235: These image file variants have several restrictions in common; they are
15236: caused by the design of the image file loader:
15237:
15238: @itemize @bullet
15239: @item
15240: There is only one segment; in particular, this means, that an image file
15241: cannot represent @code{ALLOCATE}d memory chunks (and pointers to
1.26 crook 15242: them). The contents of the stacks are not represented, either.
1.1 anton 15243:
15244: @item
15245: The only kinds of relocation supported are: adding the same offset to
15246: all cells that represent data addresses; and replacing special tokens
15247: with code addresses or with pieces of machine code.
15248:
15249: If any complex computations involving addresses are performed, the
15250: results cannot be represented in the image file. Several applications that
15251: use such computations come to mind:
1.204 anton 15252:
1.1 anton 15253: @itemize @minus
15254: @item
15255: Hashing addresses (or data structures which contain addresses) for table
15256: lookup. If you use Gforth's @code{table}s or @code{wordlist}s for this
15257: purpose, you will have no problem, because the hash tables are
15258: recomputed automatically when the system is started. If you use your own
15259: hash tables, you will have to do something similar.
15260:
15261: @item
15262: There's a cute implementation of doubly-linked lists that uses
15263: @code{XOR}ed addresses. You could represent such lists as singly-linked
15264: in the image file, and restore the doubly-linked representation on
15265: startup.@footnote{In my opinion, though, you should think thrice before
15266: using a doubly-linked list (whatever implementation).}
15267:
15268: @item
15269: The code addresses of run-time routines like @code{docol:} cannot be
15270: represented in the image file (because their tokens would be replaced by
15271: machine code in direct threaded implementations). As a workaround,
15272: compute these addresses at run-time with @code{>code-address} from the
15273: executions tokens of appropriate words (see the definitions of
1.80 anton 15274: @code{docol:} and friends in @file{kernel/getdoers.fs}).
1.1 anton 15275:
15276: @item
15277: On many architectures addresses are represented in machine code in some
15278: shifted or mangled form. You cannot put @code{CODE} words that contain
15279: absolute addresses in this form in a relocatable image file. Workarounds
15280: are representing the address in some relative form (e.g., relative to
15281: the CFA, which is present in some register), or loading the address from
15282: a place where it is stored in a non-mangled form.
15283: @end itemize
15284: @end itemize
15285:
15286: @node Non-Relocatable Image Files, Data-Relocatable Image Files, Image File Background, Image Files
15287: @section Non-Relocatable Image Files
15288: @cindex non-relocatable image files
1.26 crook 15289: @cindex image file, non-relocatable
1.1 anton 15290:
1.204 anton 15291: These files are simple memory dumps of the dictionary. They are
15292: specific to the executable (i.e., @file{gforth} file) they were
15293: created with. What's worse, they are specific to the place on which
15294: the dictionary resided when the image was created. Now, there is no
1.1 anton 15295: guarantee that the dictionary will reside at the same place the next
15296: time you start Gforth, so there's no guarantee that a non-relocatable
1.204 anton 15297: image will work the next time (Gforth will complain instead of
15298: crashing, though). Indeed, on OSs with (enabled) address-space
15299: randomization non-relocatable images are unlikely to work.
1.1 anton 15300:
1.204 anton 15301: You can create a non-relocatable image file with @code{savesystem}, e.g.:
1.1 anton 15302:
1.204 anton 15303: @example
15304: gforth app.fs -e "savesystem app.fi bye"
15305: @end example
1.44 crook 15306:
1.1 anton 15307: doc-savesystem
15308:
1.44 crook 15309:
1.1 anton 15310: @node Data-Relocatable Image Files, Fully Relocatable Image Files, Non-Relocatable Image Files, Image Files
15311: @section Data-Relocatable Image Files
15312: @cindex data-relocatable image files
1.26 crook 15313: @cindex image file, data-relocatable
1.1 anton 15314:
1.204 anton 15315: These files contain relocatable data addresses, but fixed code
15316: addresses (instead of tokens). They are specific to the executable
15317: (i.e., @file{gforth} file) they were created with. Also, they disable
15318: dynamic native code generation (typically a factor of 2 in speed).
15319: You get a data-relocatable image, if you pass the engine you want to
15320: use through the @code{GFORTHD} environment variable to @file{gforthmi}
15321: (@pxref{gforthmi}), e.g.
15322:
15323: @example
15324: GFORTHD="/usr/bin/gforth-fast --no-dynamic" gforthmi myimage.fi source.fs
15325: @end example
15326:
15327: Note that the @code{--no-dynamic} is required here for the image to
15328: work (otherwise it will contain references to dynamically generated
15329: code that is not saved in the image).
15330:
1.1 anton 15331:
15332: @node Fully Relocatable Image Files, Stack and Dictionary Sizes, Data-Relocatable Image Files, Image Files
15333: @section Fully Relocatable Image Files
15334: @cindex fully relocatable image files
1.26 crook 15335: @cindex image file, fully relocatable
1.1 anton 15336:
15337: @cindex @file{kern*.fi}, relocatability
15338: @cindex @file{gforth.fi}, relocatability
15339: These image files have relocatable data addresses, and tokens for code
15340: addresses. They can be used with different binaries (e.g., with and
15341: without debugging) on the same machine, and even across machines with
1.204 anton 15342: the same data formats (byte order, cell size, floating point format),
15343: and they work with dynamic native code generation. However, they are
15344: usually specific to the version of Gforth they were created with. The
15345: files @file{gforth.fi} and @file{kernl*.fi} are fully relocatable.
1.1 anton 15346:
15347: There are two ways to create a fully relocatable image file:
15348:
15349: @menu
1.29 crook 15350: * gforthmi:: The normal way
1.1 anton 15351: * cross.fs:: The hard way
15352: @end menu
15353:
15354: @node gforthmi, cross.fs, Fully Relocatable Image Files, Fully Relocatable Image Files
15355: @subsection @file{gforthmi}
15356: @cindex @file{comp-i.fs}
15357: @cindex @file{gforthmi}
15358:
15359: You will usually use @file{gforthmi}. If you want to create an
1.29 crook 15360: image @i{file} that contains everything you would load by invoking
15361: Gforth with @code{gforth @i{options}}, you simply say:
1.1 anton 15362: @example
1.29 crook 15363: gforthmi @i{file} @i{options}
1.1 anton 15364: @end example
15365:
15366: E.g., if you want to create an image @file{asm.fi} that has the file
15367: @file{asm.fs} loaded in addition to the usual stuff, you could do it
15368: like this:
15369:
15370: @example
15371: gforthmi asm.fi asm.fs
15372: @end example
15373:
1.27 crook 15374: @file{gforthmi} is implemented as a sh script and works like this: It
15375: produces two non-relocatable images for different addresses and then
15376: compares them. Its output reflects this: first you see the output (if
1.62 crook 15377: any) of the two Gforth invocations that produce the non-relocatable image
1.27 crook 15378: files, then you see the output of the comparing program: It displays the
15379: offset used for data addresses and the offset used for code addresses;
1.1 anton 15380: moreover, for each cell that cannot be represented correctly in the
1.44 crook 15381: image files, it displays a line like this:
1.1 anton 15382:
15383: @example
15384: 78DC BFFFFA50 BFFFFA40
15385: @end example
15386:
15387: This means that at offset $78dc from @code{forthstart}, one input image
15388: contains $bffffa50, and the other contains $bffffa40. Since these cells
15389: cannot be represented correctly in the output image, you should examine
15390: these places in the dictionary and verify that these cells are dead
15391: (i.e., not read before they are written).
1.39 anton 15392:
15393: @cindex --application, @code{gforthmi} option
15394: If you insert the option @code{--application} in front of the image file
15395: name, you will get an image that uses the @code{--appl-image} option
15396: instead of the @code{--image-file} option (@pxref{Invoking
15397: Gforth}). When you execute such an image on Unix (by typing the image
15398: name as command), the Gforth engine will pass all options to the image
15399: instead of trying to interpret them as engine options.
1.1 anton 15400:
1.27 crook 15401: If you type @file{gforthmi} with no arguments, it prints some usage
15402: instructions.
15403:
1.1 anton 15404: @cindex @code{savesystem} during @file{gforthmi}
15405: @cindex @code{bye} during @file{gforthmi}
15406: @cindex doubly indirect threaded code
1.44 crook 15407: @cindex environment variables
15408: @cindex @code{GFORTHD} -- environment variable
15409: @cindex @code{GFORTH} -- environment variable
1.1 anton 15410: @cindex @code{gforth-ditc}
1.29 crook 15411: There are a few wrinkles: After processing the passed @i{options}, the
1.204 anton 15412: words @code{savesystem} and @code{bye} must be visible. A special
15413: doubly indirect threaded version of the @file{gforth} executable is
15414: used for creating the non-relocatable images; you can pass the exact
15415: filename of this executable through the environment variable
15416: @code{GFORTHD} (default: @file{gforth-ditc}); if you pass a version
15417: that is not doubly indirect threaded, you will not get a fully
15418: relocatable image, but a data-relocatable image
15419: (@pxref{Data-Relocatable Image Files}), because there is no code
15420: address offset). The normal @file{gforth} executable is used for
15421: creating the relocatable image; you can pass the exact filename of
15422: this executable through the environment variable @code{GFORTH}.
1.1 anton 15423:
15424: @node cross.fs, , gforthmi, Fully Relocatable Image Files
15425: @subsection @file{cross.fs}
15426: @cindex @file{cross.fs}
15427: @cindex cross-compiler
15428: @cindex metacompiler
1.47 crook 15429: @cindex target compiler
1.1 anton 15430:
15431: You can also use @code{cross}, a batch compiler that accepts a Forth-like
1.47 crook 15432: programming language (@pxref{Cross Compiler}).
1.1 anton 15433:
1.47 crook 15434: @code{cross} allows you to create image files for machines with
1.1 anton 15435: different data sizes and data formats than the one used for generating
15436: the image file. You can also use it to create an application image that
15437: does not contain a Forth compiler. These features are bought with
15438: restrictions and inconveniences in programming. E.g., addresses have to
15439: be stored in memory with special words (@code{A!}, @code{A,}, etc.) in
15440: order to make the code relocatable.
15441:
15442:
15443: @node Stack and Dictionary Sizes, Running Image Files, Fully Relocatable Image Files, Image Files
15444: @section Stack and Dictionary Sizes
15445: @cindex image file, stack and dictionary sizes
15446: @cindex dictionary size default
15447: @cindex stack size default
15448:
15449: If you invoke Gforth with a command line flag for the size
15450: (@pxref{Invoking Gforth}), the size you specify is stored in the
15451: dictionary. If you save the dictionary with @code{savesystem} or create
15452: an image with @file{gforthmi}, this size will become the default
15453: for the resulting image file. E.g., the following will create a
1.21 crook 15454: fully relocatable version of @file{gforth.fi} with a 1MB dictionary:
1.1 anton 15455:
15456: @example
15457: gforthmi gforth.fi -m 1M
15458: @end example
15459:
15460: In other words, if you want to set the default size for the dictionary
15461: and the stacks of an image, just invoke @file{gforthmi} with the
15462: appropriate options when creating the image.
15463:
15464: @cindex stack size, cache-friendly
15465: Note: For cache-friendly behaviour (i.e., good performance), you should
15466: make the sizes of the stacks modulo, say, 2K, somewhat different. E.g.,
15467: the default stack sizes are: data: 16k (mod 2k=0); fp: 15.5k (mod
15468: 2k=1.5k); return: 15k(mod 2k=1k); locals: 14.5k (mod 2k=0.5k).
15469:
15470: @node Running Image Files, Modifying the Startup Sequence, Stack and Dictionary Sizes, Image Files
15471: @section Running Image Files
15472: @cindex running image files
15473: @cindex invoking image files
15474: @cindex image file invocation
15475:
15476: @cindex -i, invoke image file
15477: @cindex --image file, invoke image file
1.29 crook 15478: You can invoke Gforth with an image file @i{image} instead of the
1.1 anton 15479: default @file{gforth.fi} with the @code{-i} flag (@pxref{Invoking Gforth}):
15480: @example
1.29 crook 15481: gforth -i @i{image}
1.1 anton 15482: @end example
15483:
15484: @cindex executable image file
1.26 crook 15485: @cindex image file, executable
1.1 anton 15486: If your operating system supports starting scripts with a line of the
15487: form @code{#! ...}, you just have to type the image file name to start
15488: Gforth with this image file (note that the file extension @code{.fi} is
1.29 crook 15489: just a convention). I.e., to run Gforth with the image file @i{image},
15490: you can just type @i{image} instead of @code{gforth -i @i{image}}.
1.27 crook 15491: This works because every @code{.fi} file starts with a line of this
15492: format:
15493:
15494: @example
15495: #! /usr/local/bin/gforth-0.4.0 -i
15496: @end example
15497:
15498: The file and pathname for the Gforth engine specified on this line is
15499: the specific Gforth executable that it was built against; i.e. the value
15500: of the environment variable @code{GFORTH} at the time that
15501: @file{gforthmi} was executed.
1.1 anton 15502:
1.27 crook 15503: You can make use of the same shell capability to make a Forth source
15504: file into an executable. For example, if you place this text in a file:
1.26 crook 15505:
15506: @example
15507: #! /usr/local/bin/gforth
15508:
15509: ." Hello, world" CR
15510: bye
15511: @end example
15512:
15513: @noindent
1.27 crook 15514: and then make the file executable (chmod +x in Unix), you can run it
1.26 crook 15515: directly from the command line. The sequence @code{#!} is used in two
15516: ways; firstly, it is recognised as a ``magic sequence'' by the operating
1.29 crook 15517: system@footnote{The Unix kernel actually recognises two types of files:
15518: executable files and files of data, where the data is processed by an
15519: interpreter that is specified on the ``interpreter line'' -- the first
15520: line of the file, starting with the sequence #!. There may be a small
15521: limit (e.g., 32) on the number of characters that may be specified on
15522: the interpreter line.} secondly it is treated as a comment character by
15523: Gforth. Because of the second usage, a space is required between
1.80 anton 15524: @code{#!} and the path to the executable (moreover, some Unixes
15525: require the sequence @code{#! /}).
1.27 crook 15526:
15527: The disadvantage of this latter technique, compared with using
1.80 anton 15528: @file{gforthmi}, is that it is slightly slower; the Forth source code is
15529: compiled on-the-fly, each time the program is invoked.
1.26 crook 15530:
1.1 anton 15531: doc-#!
15532:
1.44 crook 15533:
1.1 anton 15534: @node Modifying the Startup Sequence, , Running Image Files, Image Files
15535: @section Modifying the Startup Sequence
15536: @cindex startup sequence for image file
15537: @cindex image file initialization sequence
15538: @cindex initialization sequence of image file
15539:
1.120 anton 15540: You can add your own initialization to the startup sequence of an image
15541: through the deferred word @code{'cold}. @code{'cold} is invoked just
15542: before the image-specific command line processing (i.e., loading files
15543: and evaluating (@code{-e}) strings) starts.
1.1 anton 15544:
15545: A sequence for adding your initialization usually looks like this:
15546:
15547: @example
15548: :noname
15549: Defers 'cold \ do other initialization stuff (e.g., rehashing wordlists)
15550: ... \ your stuff
15551: ; IS 'cold
15552: @end example
15553:
1.157 anton 15554: After @code{'cold}, Gforth processes the image options
15555: (@pxref{Invoking Gforth}), and then it performs @code{bootmessage},
15556: another deferred word. This normally prints Gforth's startup message
15557: and does nothing else.
15558:
1.1 anton 15559: @cindex turnkey image files
1.26 crook 15560: @cindex image file, turnkey applications
1.157 anton 15561: So, if you want to make a turnkey image (i.e., an image for an
15562: application instead of an extended Forth system), you can do this in
15563: two ways:
15564:
15565: @itemize @bullet
15566:
15567: @item
15568: If you want to do your interpretation of the OS command-line
15569: arguments, hook into @code{'cold}. In that case you probably also
15570: want to build the image with @code{gforthmi --application}
15571: (@pxref{gforthmi}) to keep the engine from processing OS command line
15572: options. You can then do your own command-line processing with
15573: @code{next-arg}
15574:
15575: @item
15576: If you want to have the normal Gforth processing of OS command-line
15577: arguments, hook into @code{bootmessage}.
15578:
15579: @end itemize
15580:
15581: In either case, you probably do not want the word that you execute in
15582: these hooks to exit normally, but use @code{bye} or @code{throw}.
15583: Otherwise the Gforth startup process would continue and eventually
15584: present the Forth command line to the user.
1.26 crook 15585:
15586: doc-'cold
1.157 anton 15587: doc-bootmessage
1.44 crook 15588:
1.1 anton 15589: @c ******************************************************************
1.113 anton 15590: @node Engine, Cross Compiler, Image Files, Top
1.1 anton 15591: @chapter Engine
15592: @cindex engine
15593: @cindex virtual machine
15594:
1.26 crook 15595: Reading this chapter is not necessary for programming with Gforth. It
1.1 anton 15596: may be helpful for finding your way in the Gforth sources.
15597:
1.109 anton 15598: The ideas in this section have also been published in the following
15599: papers: Bernd Paysan, @cite{ANS fig/GNU/??? Forth} (in German),
15600: Forth-Tagung '93; M. Anton Ertl,
15601: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl93.ps.Z, A
15602: Portable Forth Engine}}, EuroForth '93; M. Anton Ertl,
15603: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl02.ps.gz,
15604: Threaded code variations and optimizations (extended version)}},
15605: Forth-Tagung '02.
1.1 anton 15606:
15607: @menu
15608: * Portability::
15609: * Threading::
15610: * Primitives::
15611: * Performance::
15612: @end menu
15613:
15614: @node Portability, Threading, Engine, Engine
15615: @section Portability
15616: @cindex engine portability
15617:
1.26 crook 15618: An important goal of the Gforth Project is availability across a wide
15619: range of personal machines. fig-Forth, and, to a lesser extent, F83,
15620: achieved this goal by manually coding the engine in assembly language
15621: for several then-popular processors. This approach is very
15622: labor-intensive and the results are short-lived due to progress in
15623: computer architecture.
1.1 anton 15624:
15625: @cindex C, using C for the engine
15626: Others have avoided this problem by coding in C, e.g., Mitch Bradley
15627: (cforth), Mikael Patel (TILE) and Dirk Zoller (pfe). This approach is
15628: particularly popular for UNIX-based Forths due to the large variety of
15629: architectures of UNIX machines. Unfortunately an implementation in C
15630: does not mix well with the goals of efficiency and with using
15631: traditional techniques: Indirect or direct threading cannot be expressed
15632: in C, and switch threading, the fastest technique available in C, is
15633: significantly slower. Another problem with C is that it is very
15634: cumbersome to express double integer arithmetic.
15635:
15636: @cindex GNU C for the engine
15637: @cindex long long
15638: Fortunately, there is a portable language that does not have these
15639: limitations: GNU C, the version of C processed by the GNU C compiler
15640: (@pxref{C Extensions, , Extensions to the C Language Family, gcc.info,
15641: GNU C Manual}). Its labels as values feature (@pxref{Labels as Values, ,
15642: Labels as Values, gcc.info, GNU C Manual}) makes direct and indirect
15643: threading possible, its @code{long long} type (@pxref{Long Long, ,
15644: Double-Word Integers, gcc.info, GNU C Manual}) corresponds to Forth's
1.109 anton 15645: double numbers on many systems. GNU C is freely available on all
1.1 anton 15646: important (and many unimportant) UNIX machines, VMS, 80386s running
15647: MS-DOS, the Amiga, and the Atari ST, so a Forth written in GNU C can run
15648: on all these machines.
15649:
15650: Writing in a portable language has the reputation of producing code that
15651: is slower than assembly. For our Forth engine we repeatedly looked at
15652: the code produced by the compiler and eliminated most compiler-induced
15653: inefficiencies by appropriate changes in the source code.
15654:
15655: @cindex explicit register declarations
15656: @cindex --enable-force-reg, configuration flag
15657: @cindex -DFORCE_REG
15658: However, register allocation cannot be portably influenced by the
15659: programmer, leading to some inefficiencies on register-starved
15660: machines. We use explicit register declarations (@pxref{Explicit Reg
15661: Vars, , Variables in Specified Registers, gcc.info, GNU C Manual}) to
15662: improve the speed on some machines. They are turned on by using the
15663: configuration flag @code{--enable-force-reg} (@code{gcc} switch
15664: @code{-DFORCE_REG}). Unfortunately, this feature not only depends on the
15665: machine, but also on the compiler version: On some machines some
15666: compiler versions produce incorrect code when certain explicit register
15667: declarations are used. So by default @code{-DFORCE_REG} is not used.
15668:
15669: @node Threading, Primitives, Portability, Engine
15670: @section Threading
15671: @cindex inner interpreter implementation
15672: @cindex threaded code implementation
15673:
15674: @cindex labels as values
15675: GNU C's labels as values extension (available since @code{gcc-2.0},
15676: @pxref{Labels as Values, , Labels as Values, gcc.info, GNU C Manual})
1.29 crook 15677: makes it possible to take the address of @i{label} by writing
15678: @code{&&@i{label}}. This address can then be used in a statement like
15679: @code{goto *@i{address}}. I.e., @code{goto *&&x} is the same as
1.1 anton 15680: @code{goto x}.
15681:
1.26 crook 15682: @cindex @code{NEXT}, indirect threaded
1.1 anton 15683: @cindex indirect threaded inner interpreter
15684: @cindex inner interpreter, indirect threaded
1.26 crook 15685: With this feature an indirect threaded @code{NEXT} looks like:
1.1 anton 15686: @example
15687: cfa = *ip++;
15688: ca = *cfa;
15689: goto *ca;
15690: @end example
15691: @cindex instruction pointer
15692: For those unfamiliar with the names: @code{ip} is the Forth instruction
15693: pointer; the @code{cfa} (code-field address) corresponds to ANS Forths
15694: execution token and points to the code field of the next word to be
15695: executed; The @code{ca} (code address) fetched from there points to some
15696: executable code, e.g., a primitive or the colon definition handler
15697: @code{docol}.
15698:
1.26 crook 15699: @cindex @code{NEXT}, direct threaded
1.1 anton 15700: @cindex direct threaded inner interpreter
15701: @cindex inner interpreter, direct threaded
15702: Direct threading is even simpler:
15703: @example
15704: ca = *ip++;
15705: goto *ca;
15706: @end example
15707:
15708: Of course we have packaged the whole thing neatly in macros called
1.26 crook 15709: @code{NEXT} and @code{NEXT1} (the part of @code{NEXT} after fetching the cfa).
1.1 anton 15710:
15711: @menu
15712: * Scheduling::
15713: * Direct or Indirect Threaded?::
1.109 anton 15714: * Dynamic Superinstructions::
1.1 anton 15715: * DOES>::
15716: @end menu
15717:
15718: @node Scheduling, Direct or Indirect Threaded?, Threading, Threading
15719: @subsection Scheduling
15720: @cindex inner interpreter optimization
15721:
15722: There is a little complication: Pipelined and superscalar processors,
15723: i.e., RISC and some modern CISC machines can process independent
15724: instructions while waiting for the results of an instruction. The
15725: compiler usually reorders (schedules) the instructions in a way that
15726: achieves good usage of these delay slots. However, on our first tries
15727: the compiler did not do well on scheduling primitives. E.g., for
15728: @code{+} implemented as
15729: @example
15730: n=sp[0]+sp[1];
15731: sp++;
15732: sp[0]=n;
15733: NEXT;
15734: @end example
1.81 anton 15735: the @code{NEXT} comes strictly after the other code, i.e., there is
15736: nearly no scheduling. After a little thought the problem becomes clear:
15737: The compiler cannot know that @code{sp} and @code{ip} point to different
1.21 crook 15738: addresses (and the version of @code{gcc} we used would not know it even
15739: if it was possible), so it could not move the load of the cfa above the
15740: store to the TOS. Indeed the pointers could be the same, if code on or
15741: very near the top of stack were executed. In the interest of speed we
15742: chose to forbid this probably unused ``feature'' and helped the compiler
1.81 anton 15743: in scheduling: @code{NEXT} is divided into several parts:
15744: @code{NEXT_P0}, @code{NEXT_P1} and @code{NEXT_P2}). @code{+} now looks
15745: like:
1.1 anton 15746: @example
1.81 anton 15747: NEXT_P0;
1.1 anton 15748: n=sp[0]+sp[1];
15749: sp++;
15750: NEXT_P1;
15751: sp[0]=n;
15752: NEXT_P2;
15753: @end example
15754:
1.81 anton 15755: There are various schemes that distribute the different operations of
15756: NEXT between these parts in several ways; in general, different schemes
15757: perform best on different processors. We use a scheme for most
15758: architectures that performs well for most processors of this
1.109 anton 15759: architecture; in the future we may switch to benchmarking and chosing
1.81 anton 15760: the scheme on installation time.
15761:
1.1 anton 15762:
1.109 anton 15763: @node Direct or Indirect Threaded?, Dynamic Superinstructions, Scheduling, Threading
1.1 anton 15764: @subsection Direct or Indirect Threaded?
15765: @cindex threading, direct or indirect?
15766:
1.109 anton 15767: Threaded forth code consists of references to primitives (simple machine
15768: code routines like @code{+}) and to non-primitives (e.g., colon
15769: definitions, variables, constants); for a specific class of
15770: non-primitives (e.g., variables) there is one code routine (e.g.,
15771: @code{dovar}), but each variable needs a separate reference to its data.
15772:
15773: Traditionally Forth has been implemented as indirect threaded code,
15774: because this allows to use only one cell to reference a non-primitive
15775: (basically you point to the data, and find the code address there).
15776:
15777: @cindex primitive-centric threaded code
15778: However, threaded code in Gforth (since 0.6.0) uses two cells for
15779: non-primitives, one for the code address, and one for the data address;
15780: the data pointer is an immediate argument for the virtual machine
15781: instruction represented by the code address. We call this
15782: @emph{primitive-centric} threaded code, because all code addresses point
15783: to simple primitives. E.g., for a variable, the code address is for
15784: @code{lit} (also used for integer literals like @code{99}).
15785:
15786: Primitive-centric threaded code allows us to use (faster) direct
15787: threading as dispatch method, completely portably (direct threaded code
15788: in Gforth before 0.6.0 required architecture-specific code). It also
15789: eliminates the performance problems related to I-cache consistency that
15790: 386 implementations have with direct threaded code, and allows
15791: additional optimizations.
15792:
15793: @cindex hybrid direct/indirect threaded code
15794: There is a catch, however: the @var{xt} parameter of @code{execute} can
15795: occupy only one cell, so how do we pass non-primitives with their code
15796: @emph{and} data addresses to them? Our answer is to use indirect
15797: threaded dispatch for @code{execute} and other words that use a
15798: single-cell xt. So, normal threaded code in colon definitions uses
15799: direct threading, and @code{execute} and similar words, which dispatch
15800: to xts on the data stack, use indirect threaded code. We call this
15801: @emph{hybrid direct/indirect} threaded code.
15802:
15803: @cindex engines, gforth vs. gforth-fast vs. gforth-itc
15804: @cindex gforth engine
15805: @cindex gforth-fast engine
15806: The engines @command{gforth} and @command{gforth-fast} use hybrid
15807: direct/indirect threaded code. This means that with these engines you
15808: cannot use @code{,} to compile an xt. Instead, you have to use
15809: @code{compile,}.
15810:
15811: @cindex gforth-itc engine
1.115 anton 15812: If you want to compile xts with @code{,}, use @command{gforth-itc}.
15813: This engine uses plain old indirect threaded code. It still compiles in
15814: a primitive-centric style, so you cannot use @code{compile,} instead of
1.109 anton 15815: @code{,} (e.g., for producing tables of xts with @code{] word1 word2
1.115 anton 15816: ... [}). If you want to do that, you have to use @command{gforth-itc}
1.109 anton 15817: and execute @code{' , is compile,}. Your program can check if it is
15818: running on a hybrid direct/indirect threaded engine or a pure indirect
15819: threaded engine with @code{threading-method} (@pxref{Threading Words}).
15820:
15821:
15822: @node Dynamic Superinstructions, DOES>, Direct or Indirect Threaded?, Threading
15823: @subsection Dynamic Superinstructions
15824: @cindex Dynamic superinstructions with replication
15825: @cindex Superinstructions
15826: @cindex Replication
15827:
15828: The engines @command{gforth} and @command{gforth-fast} use another
15829: optimization: Dynamic superinstructions with replication. As an
15830: example, consider the following colon definition:
15831:
15832: @example
15833: : squared ( n1 -- n2 )
15834: dup * ;
15835: @end example
15836:
15837: Gforth compiles this into the threaded code sequence
15838:
15839: @example
15840: dup
15841: *
15842: ;s
15843: @end example
15844:
15845: In normal direct threaded code there is a code address occupying one
15846: cell for each of these primitives. Each code address points to a
15847: machine code routine, and the interpreter jumps to this machine code in
15848: order to execute the primitive. The routines for these three
15849: primitives are (in @command{gforth-fast} on the 386):
15850:
15851: @example
15852: Code dup
15853: ( $804B950 ) add esi , # -4 \ $83 $C6 $FC
15854: ( $804B953 ) add ebx , # 4 \ $83 $C3 $4
15855: ( $804B956 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15856: ( $804B959 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15857: end-code
15858: Code *
15859: ( $804ACC4 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15860: ( $804ACC7 ) add esi , # 4 \ $83 $C6 $4
15861: ( $804ACCA ) add ebx , # 4 \ $83 $C3 $4
15862: ( $804ACCD ) imul ecx , eax \ $F $AF $C8
15863: ( $804ACD0 ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15864: end-code
15865: Code ;s
15866: ( $804A693 ) mov eax , dword ptr [edi] \ $8B $7
15867: ( $804A695 ) add edi , # 4 \ $83 $C7 $4
15868: ( $804A698 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15869: ( $804A69B ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15870: end-code
15871: @end example
15872:
15873: With dynamic superinstructions and replication the compiler does not
15874: just lay down the threaded code, but also copies the machine code
15875: fragments, usually without the jump at the end.
15876:
15877: @example
15878: ( $4057D27D ) add esi , # -4 \ $83 $C6 $FC
15879: ( $4057D280 ) add ebx , # 4 \ $83 $C3 $4
15880: ( $4057D283 ) mov dword ptr 4 [esi] , ecx \ $89 $4E $4
15881: ( $4057D286 ) mov eax , dword ptr 4 [esi] \ $8B $46 $4
15882: ( $4057D289 ) add esi , # 4 \ $83 $C6 $4
15883: ( $4057D28C ) add ebx , # 4 \ $83 $C3 $4
15884: ( $4057D28F ) imul ecx , eax \ $F $AF $C8
15885: ( $4057D292 ) mov eax , dword ptr [edi] \ $8B $7
15886: ( $4057D294 ) add edi , # 4 \ $83 $C7 $4
15887: ( $4057D297 ) lea ebx , dword ptr 4 [eax] \ $8D $58 $4
15888: ( $4057D29A ) jmp dword ptr FC [ebx] \ $FF $63 $FC
15889: @end example
15890:
15891: Only when a threaded-code control-flow change happens (e.g., in
15892: @code{;s}), the jump is appended. This optimization eliminates many of
15893: these jumps and makes the rest much more predictable. The speedup
15894: depends on the processor and the application; on the Athlon and Pentium
15895: III this optimization typically produces a speedup by a factor of 2.
15896:
15897: The code addresses in the direct-threaded code are set to point to the
15898: appropriate points in the copied machine code, in this example like
15899: this:
1.1 anton 15900:
1.109 anton 15901: @example
15902: primitive code address
15903: dup $4057D27D
15904: * $4057D286
15905: ;s $4057D292
15906: @end example
15907:
15908: Thus there can be threaded-code jumps to any place in this piece of
15909: code. This also simplifies decompilation quite a bit.
15910:
15911: @cindex --no-dynamic command-line option
15912: @cindex --no-super command-line option
15913: You can disable this optimization with @option{--no-dynamic}. You can
15914: use the copying without eliminating the jumps (i.e., dynamic
15915: replication, but without superinstructions) with @option{--no-super};
15916: this gives the branch prediction benefit alone; the effect on
1.110 anton 15917: performance depends on the CPU; on the Athlon and Pentium III the
15918: speedup is a little less than for dynamic superinstructions with
15919: replication.
15920:
15921: @cindex patching threaded code
15922: One use of these options is if you want to patch the threaded code.
15923: With superinstructions, many of the dispatch jumps are eliminated, so
15924: patching often has no effect. These options preserve all the dispatch
15925: jumps.
1.109 anton 15926:
15927: @cindex --dynamic command-line option
1.110 anton 15928: On some machines dynamic superinstructions are disabled by default,
15929: because it is unsafe on these machines. However, if you feel
15930: adventurous, you can enable it with @option{--dynamic}.
1.109 anton 15931:
15932: @node DOES>, , Dynamic Superinstructions, Threading
1.1 anton 15933: @subsection DOES>
15934: @cindex @code{DOES>} implementation
15935:
1.26 crook 15936: @cindex @code{dodoes} routine
15937: @cindex @code{DOES>}-code
1.1 anton 15938: One of the most complex parts of a Forth engine is @code{dodoes}, i.e.,
15939: the chunk of code executed by every word defined by a
1.109 anton 15940: @code{CREATE}...@code{DOES>} pair; actually with primitive-centric code,
15941: this is only needed if the xt of the word is @code{execute}d. The main
15942: problem here is: How to find the Forth code to be executed, i.e. the
15943: code after the @code{DOES>} (the @code{DOES>}-code)? There are two
15944: solutions:
1.1 anton 15945:
1.21 crook 15946: In fig-Forth the code field points directly to the @code{dodoes} and the
1.109 anton 15947: @code{DOES>}-code address is stored in the cell after the code address
15948: (i.e. at @code{@i{CFA} cell+}). It may seem that this solution is
15949: illegal in the Forth-79 and all later standards, because in fig-Forth
15950: this address lies in the body (which is illegal in these
15951: standards). However, by making the code field larger for all words this
15952: solution becomes legal again. We use this approach. Leaving a cell
15953: unused in most words is a bit wasteful, but on the machines we are
15954: targeting this is hardly a problem.
15955:
1.1 anton 15956:
15957: @node Primitives, Performance, Threading, Engine
15958: @section Primitives
15959: @cindex primitives, implementation
15960: @cindex virtual machine instructions, implementation
15961:
15962: @menu
15963: * Automatic Generation::
15964: * TOS Optimization::
15965: * Produced code::
15966: @end menu
15967:
15968: @node Automatic Generation, TOS Optimization, Primitives, Primitives
15969: @subsection Automatic Generation
15970: @cindex primitives, automatic generation
15971:
15972: @cindex @file{prims2x.fs}
1.109 anton 15973:
1.1 anton 15974: Since the primitives are implemented in a portable language, there is no
15975: longer any need to minimize the number of primitives. On the contrary,
15976: having many primitives has an advantage: speed. In order to reduce the
15977: number of errors in primitives and to make programming them easier, we
1.109 anton 15978: provide a tool, the primitive generator (@file{prims2x.fs} aka Vmgen,
15979: @pxref{Top, Vmgen, Introduction, vmgen, Vmgen}), that automatically
15980: generates most (and sometimes all) of the C code for a primitive from
15981: the stack effect notation. The source for a primitive has the following
15982: form:
1.1 anton 15983:
15984: @cindex primitive source format
15985: @format
1.58 anton 15986: @i{Forth-name} ( @i{stack-effect} ) @i{category} [@i{pronounc.}]
1.29 crook 15987: [@code{""}@i{glossary entry}@code{""}]
15988: @i{C code}
1.1 anton 15989: [@code{:}
1.29 crook 15990: @i{Forth code}]
1.1 anton 15991: @end format
15992:
15993: The items in brackets are optional. The category and glossary fields
15994: are there for generating the documentation, the Forth code is there
15995: for manual implementations on machines without GNU C. E.g., the source
15996: for the primitive @code{+} is:
15997: @example
1.58 anton 15998: + ( n1 n2 -- n ) core plus
1.1 anton 15999: n = n1+n2;
16000: @end example
16001:
16002: This looks like a specification, but in fact @code{n = n1+n2} is C
16003: code. Our primitive generation tool extracts a lot of information from
16004: the stack effect notations@footnote{We use a one-stack notation, even
16005: though we have separate data and floating-point stacks; The separate
16006: notation can be generated easily from the unified notation.}: The number
16007: of items popped from and pushed on the stack, their type, and by what
16008: name they are referred to in the C code. It then generates a C code
16009: prelude and postlude for each primitive. The final C code for @code{+}
16010: looks like this:
16011:
16012: @example
1.46 pazsan 16013: I_plus: /* + ( n1 n2 -- n ) */ /* label, stack effect */
1.1 anton 16014: /* */ /* documentation */
1.81 anton 16015: NAME("+") /* debugging output (with -DDEBUG) */
1.1 anton 16016: @{
16017: DEF_CA /* definition of variable ca (indirect threading) */
16018: Cell n1; /* definitions of variables */
16019: Cell n2;
16020: Cell n;
1.81 anton 16021: NEXT_P0; /* NEXT part 0 */
1.1 anton 16022: n1 = (Cell) sp[1]; /* input */
16023: n2 = (Cell) TOS;
16024: sp += 1; /* stack adjustment */
16025: @{
16026: n = n1+n2; /* C code taken from the source */
16027: @}
16028: NEXT_P1; /* NEXT part 1 */
16029: TOS = (Cell)n; /* output */
16030: NEXT_P2; /* NEXT part 2 */
16031: @}
16032: @end example
16033:
16034: This looks long and inefficient, but the GNU C compiler optimizes quite
16035: well and produces optimal code for @code{+} on, e.g., the R3000 and the
16036: HP RISC machines: Defining the @code{n}s does not produce any code, and
16037: using them as intermediate storage also adds no cost.
16038:
1.26 crook 16039: There are also other optimizations that are not illustrated by this
16040: example: assignments between simple variables are usually for free (copy
1.1 anton 16041: propagation). If one of the stack items is not used by the primitive
16042: (e.g. in @code{drop}), the compiler eliminates the load from the stack
16043: (dead code elimination). On the other hand, there are some things that
16044: the compiler does not do, therefore they are performed by
16045: @file{prims2x.fs}: The compiler does not optimize code away that stores
16046: a stack item to the place where it just came from (e.g., @code{over}).
16047:
16048: While programming a primitive is usually easy, there are a few cases
16049: where the programmer has to take the actions of the generator into
16050: account, most notably @code{?dup}, but also words that do not (always)
1.26 crook 16051: fall through to @code{NEXT}.
1.109 anton 16052:
16053: For more information
1.1 anton 16054:
16055: @node TOS Optimization, Produced code, Automatic Generation, Primitives
16056: @subsection TOS Optimization
16057: @cindex TOS optimization for primitives
16058: @cindex primitives, keeping the TOS in a register
16059:
16060: An important optimization for stack machine emulators, e.g., Forth
16061: engines, is keeping one or more of the top stack items in
1.29 crook 16062: registers. If a word has the stack effect @i{in1}...@i{inx} @code{--}
16063: @i{out1}...@i{outy}, keeping the top @i{n} items in registers
1.1 anton 16064: @itemize @bullet
16065: @item
1.29 crook 16066: is better than keeping @i{n-1} items, if @i{x>=n} and @i{y>=n},
1.1 anton 16067: due to fewer loads from and stores to the stack.
1.29 crook 16068: @item is slower than keeping @i{n-1} items, if @i{x<>y} and @i{x<n} and
16069: @i{y<n}, due to additional moves between registers.
1.1 anton 16070: @end itemize
16071:
16072: @cindex -DUSE_TOS
16073: @cindex -DUSE_NO_TOS
16074: In particular, keeping one item in a register is never a disadvantage,
16075: if there are enough registers. Keeping two items in registers is a
16076: disadvantage for frequent words like @code{?branch}, constants,
16077: variables, literals and @code{i}. Therefore our generator only produces
16078: code that keeps zero or one items in registers. The generated C code
16079: covers both cases; the selection between these alternatives is made at
16080: C-compile time using the switch @code{-DUSE_TOS}. @code{TOS} in the C
16081: code for @code{+} is just a simple variable name in the one-item case,
16082: otherwise it is a macro that expands into @code{sp[0]}. Note that the
16083: GNU C compiler tries to keep simple variables like @code{TOS} in
16084: registers, and it usually succeeds, if there are enough registers.
16085:
16086: @cindex -DUSE_FTOS
16087: @cindex -DUSE_NO_FTOS
16088: The primitive generator performs the TOS optimization for the
16089: floating-point stack, too (@code{-DUSE_FTOS}). For floating-point
16090: operations the benefit of this optimization is even larger:
16091: floating-point operations take quite long on most processors, but can be
16092: performed in parallel with other operations as long as their results are
16093: not used. If the FP-TOS is kept in a register, this works. If
16094: it is kept on the stack, i.e., in memory, the store into memory has to
16095: wait for the result of the floating-point operation, lengthening the
16096: execution time of the primitive considerably.
16097:
16098: The TOS optimization makes the automatic generation of primitives a
16099: bit more complicated. Just replacing all occurrences of @code{sp[0]} by
16100: @code{TOS} is not sufficient. There are some special cases to
16101: consider:
16102: @itemize @bullet
16103: @item In the case of @code{dup ( w -- w w )} the generator must not
16104: eliminate the store to the original location of the item on the stack,
16105: if the TOS optimization is turned on.
16106: @item Primitives with stack effects of the form @code{--}
1.29 crook 16107: @i{out1}...@i{outy} must store the TOS to the stack at the start.
16108: Likewise, primitives with the stack effect @i{in1}...@i{inx} @code{--}
1.1 anton 16109: must load the TOS from the stack at the end. But for the null stack
16110: effect @code{--} no stores or loads should be generated.
16111: @end itemize
16112:
16113: @node Produced code, , TOS Optimization, Primitives
16114: @subsection Produced code
16115: @cindex primitives, assembly code listing
16116:
16117: @cindex @file{engine.s}
16118: To see what assembly code is produced for the primitives on your machine
16119: with your compiler and your flag settings, type @code{make engine.s} and
1.81 anton 16120: look at the resulting file @file{engine.s}. Alternatively, you can also
16121: disassemble the code of primitives with @code{see} on some architectures.
1.1 anton 16122:
16123: @node Performance, , Primitives, Engine
16124: @section Performance
16125: @cindex performance of some Forth interpreters
16126: @cindex engine performance
16127: @cindex benchmarking Forth systems
16128: @cindex Gforth performance
16129:
16130: On RISCs the Gforth engine is very close to optimal; i.e., it is usually
1.112 anton 16131: impossible to write a significantly faster threaded-code engine.
1.1 anton 16132:
16133: On register-starved machines like the 386 architecture processors
16134: improvements are possible, because @code{gcc} does not utilize the
16135: registers as well as a human, even with explicit register declarations;
16136: e.g., Bernd Beuster wrote a Forth system fragment in assembly language
16137: and hand-tuned it for the 486; this system is 1.19 times faster on the
16138: Sieve benchmark on a 486DX2/66 than Gforth compiled with
1.40 anton 16139: @code{gcc-2.6.3} with @code{-DFORCE_REG}. The situation has improved
16140: with gcc-2.95 and gforth-0.4.9; now the most important virtual machine
16141: registers fit in real registers (and we can even afford to use the TOS
16142: optimization), resulting in a speedup of 1.14 on the sieve over the
1.112 anton 16143: earlier results. And dynamic superinstructions provide another speedup
16144: (but only around a factor 1.2 on the 486).
1.1 anton 16145:
16146: @cindex Win32Forth performance
16147: @cindex NT Forth performance
16148: @cindex eforth performance
16149: @cindex ThisForth performance
16150: @cindex PFE performance
16151: @cindex TILE performance
1.81 anton 16152: The potential advantage of assembly language implementations is not
1.112 anton 16153: necessarily realized in complete Forth systems: We compared Gforth-0.5.9
1.81 anton 16154: (direct threaded, compiled with @code{gcc-2.95.1} and
16155: @code{-DFORCE_REG}) with Win32Forth 1.2093 (newer versions are
16156: reportedly much faster), LMI's NT Forth (Beta, May 1994) and Eforth
16157: (with and without peephole (aka pinhole) optimization of the threaded
16158: code); all these systems were written in assembly language. We also
16159: compared Gforth with three systems written in C: PFE-0.9.14 (compiled
16160: with @code{gcc-2.6.3} with the default configuration for Linux:
16161: @code{-O2 -fomit-frame-pointer -DUSE_REGS -DUNROLL_NEXT}), ThisForth
16162: Beta (compiled with @code{gcc-2.6.3 -O3 -fomit-frame-pointer}; ThisForth
16163: employs peephole optimization of the threaded code) and TILE (compiled
16164: with @code{make opt}). We benchmarked Gforth, PFE, ThisForth and TILE on
16165: a 486DX2/66 under Linux. Kenneth O'Heskin kindly provided the results
16166: for Win32Forth and NT Forth on a 486DX2/66 with similar memory
16167: performance under Windows NT. Marcel Hendrix ported Eforth to Linux,
16168: then extended it to run the benchmarks, added the peephole optimizer,
16169: ran the benchmarks and reported the results.
1.40 anton 16170:
1.1 anton 16171: We used four small benchmarks: the ubiquitous Sieve; bubble-sorting and
16172: matrix multiplication come from the Stanford integer benchmarks and have
16173: been translated into Forth by Martin Fraeman; we used the versions
16174: included in the TILE Forth package, but with bigger data set sizes; and
16175: a recursive Fibonacci number computation for benchmarking calling
16176: performance. The following table shows the time taken for the benchmarks
16177: scaled by the time taken by Gforth (in other words, it shows the speedup
16178: factor that Gforth achieved over the other systems).
16179:
16180: @example
1.112 anton 16181: relative Win32- NT eforth This-
16182: time Gforth Forth Forth eforth +opt PFE Forth TILE
16183: sieve 1.00 2.16 1.78 2.16 1.32 2.46 4.96 13.37
16184: bubble 1.00 1.93 2.07 2.18 1.29 2.21 5.70
16185: matmul 1.00 1.92 1.76 1.90 0.96 2.06 5.32
16186: fib 1.00 2.32 2.03 1.86 1.31 2.64 4.55 6.54
1.1 anton 16187: @end example
16188:
1.26 crook 16189: You may be quite surprised by the good performance of Gforth when
16190: compared with systems written in assembly language. One important reason
16191: for the disappointing performance of these other systems is probably
16192: that they are not written optimally for the 486 (e.g., they use the
16193: @code{lods} instruction). In addition, Win32Forth uses a comfortable,
16194: but costly method for relocating the Forth image: like @code{cforth}, it
16195: computes the actual addresses at run time, resulting in two address
16196: computations per @code{NEXT} (@pxref{Image File Background}).
16197:
1.1 anton 16198: The speedup of Gforth over PFE, ThisForth and TILE can be easily
16199: explained with the self-imposed restriction of the latter systems to
16200: standard C, which makes efficient threading impossible (however, the
1.4 anton 16201: measured implementation of PFE uses a GNU C extension: @pxref{Global Reg
1.1 anton 16202: Vars, , Defining Global Register Variables, gcc.info, GNU C Manual}).
16203: Moreover, current C compilers have a hard time optimizing other aspects
16204: of the ThisForth and the TILE source.
16205:
1.26 crook 16206: The performance of Gforth on 386 architecture processors varies widely
16207: with the version of @code{gcc} used. E.g., @code{gcc-2.5.8} failed to
16208: allocate any of the virtual machine registers into real machine
16209: registers by itself and would not work correctly with explicit register
1.112 anton 16210: declarations, giving a significantly slower engine (on a 486DX2/66
16211: running the Sieve) than the one measured above.
1.1 anton 16212:
1.26 crook 16213: Note that there have been several releases of Win32Forth since the
16214: release presented here, so the results presented above may have little
1.40 anton 16215: predictive value for the performance of Win32Forth today (results for
16216: the current release on an i486DX2/66 are welcome).
1.1 anton 16217:
16218: @cindex @file{Benchres}
1.66 anton 16219: In
16220: @cite{@uref{http://www.complang.tuwien.ac.at/papers/ertl&maierhofer95.ps.gz,
16221: Translating Forth to Efficient C}} by M. Anton Ertl and Martin
1.1 anton 16222: Maierhofer (presented at EuroForth '95), an indirect threaded version of
1.66 anton 16223: Gforth is compared with Win32Forth, NT Forth, PFE, ThisForth, and
16224: several native code systems; that version of Gforth is slower on a 486
1.112 anton 16225: than the version used here. You can find a newer version of these
16226: measurements at
1.47 crook 16227: @uref{http://www.complang.tuwien.ac.at/forth/performance.html}. You can
1.1 anton 16228: find numbers for Gforth on various machines in @file{Benchres}.
16229:
1.26 crook 16230: @c ******************************************************************
1.113 anton 16231: @c @node Binding to System Library, Cross Compiler, Engine, Top
16232: @c @chapter Binding to System Library
1.13 pazsan 16233:
1.113 anton 16234: @c ****************************************************************
16235: @node Cross Compiler, Bugs, Engine, Top
1.14 pazsan 16236: @chapter Cross Compiler
1.47 crook 16237: @cindex @file{cross.fs}
16238: @cindex cross-compiler
16239: @cindex metacompiler
16240: @cindex target compiler
1.13 pazsan 16241:
1.46 pazsan 16242: The cross compiler is used to bootstrap a Forth kernel. Since Gforth is
16243: mostly written in Forth, including crucial parts like the outer
16244: interpreter and compiler, it needs compiled Forth code to get
16245: started. The cross compiler allows to create new images for other
16246: architectures, even running under another Forth system.
1.13 pazsan 16247:
16248: @menu
1.67 anton 16249: * Using the Cross Compiler::
16250: * How the Cross Compiler Works::
1.13 pazsan 16251: @end menu
16252:
1.21 crook 16253: @node Using the Cross Compiler, How the Cross Compiler Works, Cross Compiler, Cross Compiler
1.14 pazsan 16254: @section Using the Cross Compiler
1.46 pazsan 16255:
16256: The cross compiler uses a language that resembles Forth, but isn't. The
16257: main difference is that you can execute Forth code after definition,
16258: while you usually can't execute the code compiled by cross, because the
16259: code you are compiling is typically for a different computer than the
16260: one you are compiling on.
16261:
1.81 anton 16262: @c anton: This chapter is somewhat different from waht I would expect: I
16263: @c would expect an explanation of the cross language and how to create an
16264: @c application image with it. The section explains some aspects of
16265: @c creating a Gforth kernel.
16266:
1.46 pazsan 16267: The Makefile is already set up to allow you to create kernels for new
16268: architectures with a simple make command. The generic kernels using the
16269: GCC compiled virtual machine are created in the normal build process
16270: with @code{make}. To create a embedded Gforth executable for e.g. the
16271: 8086 processor (running on a DOS machine), type
16272:
16273: @example
16274: make kernl-8086.fi
16275: @end example
16276:
16277: This will use the machine description from the @file{arch/8086}
16278: directory to create a new kernel. A machine file may look like that:
16279:
16280: @example
16281: \ Parameter for target systems 06oct92py
16282:
16283: 4 Constant cell \ cell size in bytes
16284: 2 Constant cell<< \ cell shift to bytes
16285: 5 Constant cell>bit \ cell shift to bits
16286: 8 Constant bits/char \ bits per character
16287: 8 Constant bits/byte \ bits per byte [default: 8]
16288: 8 Constant float \ bytes per float
16289: 8 Constant /maxalign \ maximum alignment in bytes
16290: false Constant bigendian \ byte order
16291: ( true=big, false=little )
16292:
16293: include machpc.fs \ feature list
16294: @end example
16295:
16296: This part is obligatory for the cross compiler itself, the feature list
16297: is used by the kernel to conditionally compile some features in and out,
16298: depending on whether the target supports these features.
16299:
16300: There are some optional features, if you define your own primitives,
16301: have an assembler, or need special, nonstandard preparation to make the
1.81 anton 16302: boot process work. @code{asm-include} includes an assembler,
1.46 pazsan 16303: @code{prims-include} includes primitives, and @code{>boot} prepares for
16304: booting.
16305:
16306: @example
16307: : asm-include ." Include assembler" cr
16308: s" arch/8086/asm.fs" included ;
16309:
16310: : prims-include ." Include primitives" cr
16311: s" arch/8086/prim.fs" included ;
16312:
16313: : >boot ." Prepare booting" cr
16314: s" ' boot >body into-forth 1+ !" evaluate ;
16315: @end example
16316:
16317: These words are used as sort of macro during the cross compilation in
1.81 anton 16318: the file @file{kernel/main.fs}. Instead of using these macros, it would
1.46 pazsan 16319: be possible --- but more complicated --- to write a new kernel project
16320: file, too.
16321:
16322: @file{kernel/main.fs} expects the machine description file name on the
16323: stack; the cross compiler itself (@file{cross.fs}) assumes that either
16324: @code{mach-file} leaves a counted string on the stack, or
16325: @code{machine-file} leaves an address, count pair of the filename on the
16326: stack.
16327:
16328: The feature list is typically controlled using @code{SetValue}, generic
16329: files that are used by several projects can use @code{DefaultValue}
16330: instead. Both functions work like @code{Value}, when the value isn't
16331: defined, but @code{SetValue} works like @code{to} if the value is
16332: defined, and @code{DefaultValue} doesn't set anything, if the value is
16333: defined.
16334:
16335: @example
16336: \ generic mach file for pc gforth 03sep97jaw
16337:
16338: true DefaultValue NIL \ relocating
16339:
16340: >ENVIRON
16341:
16342: true DefaultValue file \ controls the presence of the
16343: \ file access wordset
16344: true DefaultValue OS \ flag to indicate a operating system
16345:
16346: true DefaultValue prims \ true: primitives are c-code
16347:
16348: true DefaultValue floating \ floating point wordset is present
16349:
16350: true DefaultValue glocals \ gforth locals are present
16351: \ will be loaded
16352: true DefaultValue dcomps \ double number comparisons
16353:
16354: true DefaultValue hash \ hashing primitives are loaded/present
16355:
16356: true DefaultValue xconds \ used together with glocals,
16357: \ special conditionals supporting gforths'
16358: \ local variables
16359: true DefaultValue header \ save a header information
16360:
16361: true DefaultValue backtrace \ enables backtrace code
16362:
16363: false DefaultValue ec
16364: false DefaultValue crlf
16365:
16366: cell 2 = [IF] &32 [ELSE] &256 [THEN] KB DefaultValue kernel-size
16367:
16368: &16 KB DefaultValue stack-size
16369: &15 KB &512 + DefaultValue fstack-size
16370: &15 KB DefaultValue rstack-size
16371: &14 KB &512 + DefaultValue lstack-size
16372: @end example
1.13 pazsan 16373:
1.48 anton 16374: @node How the Cross Compiler Works, , Using the Cross Compiler, Cross Compiler
1.14 pazsan 16375: @section How the Cross Compiler Works
1.13 pazsan 16376:
16377: @node Bugs, Origin, Cross Compiler, Top
1.21 crook 16378: @appendix Bugs
1.1 anton 16379: @cindex bug reporting
16380:
1.21 crook 16381: Known bugs are described in the file @file{BUGS} in the Gforth distribution.
1.1 anton 16382:
1.103 anton 16383: If you find a bug, please submit a bug report through
16384: @uref{https://savannah.gnu.org/bugs/?func=addbug&group=gforth}.
1.21 crook 16385:
16386: @itemize @bullet
16387: @item
1.81 anton 16388: A program (or a sequence of keyboard commands) that reproduces the bug.
16389: @item
16390: A description of what you think constitutes the buggy behaviour.
16391: @item
1.21 crook 16392: The Gforth version used (it is announced at the start of an
16393: interactive Gforth session).
16394: @item
16395: The machine and operating system (on Unix
16396: systems @code{uname -a} will report this information).
16397: @item
1.81 anton 16398: The installation options (you can find the configure options at the
16399: start of @file{config.status}) and configuration (@code{configure}
16400: output or @file{config.cache}).
1.21 crook 16401: @item
16402: A complete list of changes (if any) you (or your installer) have made to the
16403: Gforth sources.
16404: @end itemize
1.1 anton 16405:
16406: For a thorough guide on reporting bugs read @ref{Bug Reporting, , How
16407: to Report Bugs, gcc.info, GNU C Manual}.
16408:
16409:
1.21 crook 16410: @node Origin, Forth-related information, Bugs, Top
16411: @appendix Authors and Ancestors of Gforth
1.1 anton 16412:
16413: @section Authors and Contributors
16414: @cindex authors of Gforth
16415: @cindex contributors to Gforth
16416:
16417: The Gforth project was started in mid-1992 by Bernd Paysan and Anton
1.81 anton 16418: Ertl. The third major author was Jens Wilke. Neal Crook contributed a
16419: lot to the manual. Assemblers and disassemblers were contributed by
1.161 anton 16420: Andrew McKewan, Christian Pirker, Bernd Thallner, and Michal Revucky.
16421: Lennart Benschop (who was one of Gforth's first users, in mid-1993)
16422: and Stuart Ramsden inspired us with their continuous feedback. Lennart
16423: Benshop contributed @file{glosgen.fs}, while Stuart Ramsden has been
16424: working on automatic support for calling C libraries. Helpful comments
16425: also came from Paul Kleinrubatscher, Christian Pirker, Dirk Zoller,
16426: Marcel Hendrix, John Wavrik, Barrie Stott, Marc de Groot, Jorge
16427: Acerada, Bruce Hoyt, Robert Epprecht, Dennis Ruffer and David
16428: N. Williams. Since the release of Gforth-0.2.1 there were also helpful
16429: comments from many others; thank you all, sorry for not listing you
16430: here (but digging through my mailbox to extract your names is on my
16431: to-do list).
1.1 anton 16432:
16433: Gforth also owes a lot to the authors of the tools we used (GCC, CVS,
16434: and autoconf, among others), and to the creators of the Internet: Gforth
1.21 crook 16435: was developed across the Internet, and its authors did not meet
1.20 pazsan 16436: physically for the first 4 years of development.
1.1 anton 16437:
16438: @section Pedigree
1.26 crook 16439: @cindex pedigree of Gforth
1.1 anton 16440:
1.81 anton 16441: Gforth descends from bigFORTH (1993) and fig-Forth. Of course, a
16442: significant part of the design of Gforth was prescribed by ANS Forth.
1.1 anton 16443:
1.20 pazsan 16444: Bernd Paysan wrote bigFORTH, a descendent from TurboForth, an unreleased
1.1 anton 16445: 32 bit native code version of VolksForth for the Atari ST, written
16446: mostly by Dietrich Weineck.
16447:
1.81 anton 16448: VolksForth was written by Klaus Schleisiek, Bernd Pennemann, Georg
16449: Rehfeld and Dietrich Weineck for the C64 (called UltraForth there) in
1.147 anton 16450: the mid-80s and ported to the Atari ST in 1986. It descends from fig-Forth.
1.1 anton 16451:
1.147 anton 16452: @c Henry Laxen and Mike Perry wrote F83 as a model implementation of the
16453: @c Forth-83 standard. !! Pedigree? When?
1.1 anton 16454:
16455: A team led by Bill Ragsdale implemented fig-Forth on many processors in
16456: 1979. Robert Selzer and Bill Ragsdale developed the original
16457: implementation of fig-Forth for the 6502 based on microForth.
16458:
16459: The principal architect of microForth was Dean Sanderson. microForth was
16460: FORTH, Inc.'s first off-the-shelf product. It was developed in 1976 for
16461: the 1802, and subsequently implemented on the 8080, the 6800 and the
16462: Z80.
16463:
16464: All earlier Forth systems were custom-made, usually by Charles Moore,
16465: who discovered (as he puts it) Forth during the late 60s. The first full
16466: Forth existed in 1971.
16467:
1.81 anton 16468: A part of the information in this section comes from
16469: @cite{@uref{http://www.forth.com/Content/History/History1.htm,The
16470: Evolution of Forth}} by Elizabeth D. Rather, Donald R. Colburn and
1.147 anton 16471: Charles H. Moore, presented at the HOPL-II conference and preprinted
16472: in SIGPLAN Notices 28(3), 1993. You can find more historical and
16473: genealogical information about Forth there. For a more general (and
16474: graphical) Forth family tree look see
16475: @cite{@uref{http://www.complang.tuwien.ac.at/forth/family-tree/},
16476: Forth Family Tree and Timeline}.
1.1 anton 16477:
1.81 anton 16478: @c ------------------------------------------------------------------
1.113 anton 16479: @node Forth-related information, Licenses, Origin, Top
1.21 crook 16480: @appendix Other Forth-related information
16481: @cindex Forth-related information
16482:
1.81 anton 16483: @c anton: I threw most of this stuff out, because it can be found through
16484: @c the FAQ and the FAQ is more likely to be up-to-date.
1.21 crook 16485:
16486: @cindex comp.lang.forth
16487: @cindex frequently asked questions
1.81 anton 16488: There is an active news group (comp.lang.forth) discussing Forth
16489: (including Gforth) and Forth-related issues. Its
16490: @uref{http://www.complang.tuwien.ac.at/forth/faq/faq-general-2.html,FAQs}
16491: (frequently asked questions and their answers) contains a lot of
16492: information on Forth. You should read it before posting to
16493: comp.lang.forth.
1.21 crook 16494:
1.81 anton 16495: The ANS Forth standard is most usable in its
16496: @uref{http://www.taygeta.com/forth/dpans.html, HTML form}.
1.21 crook 16497:
1.113 anton 16498: @c ---------------------------------------------------
16499: @node Licenses, Word Index, Forth-related information, Top
16500: @appendix Licenses
16501:
16502: @menu
16503: * GNU Free Documentation License:: License for copying this manual.
1.192 anton 16504: * Copying:: GPL (for copying this software).
1.113 anton 16505: @end menu
16506:
1.192 anton 16507: @node GNU Free Documentation License, Copying, Licenses, Licenses
16508: @appendixsec GNU Free Documentation License
1.113 anton 16509: @include fdl.texi
16510:
1.192 anton 16511: @node Copying, , GNU Free Documentation License, Licenses
16512: @appendixsec GNU GENERAL PUBLIC LICENSE
1.113 anton 16513: @include gpl.texi
16514:
16515:
16516:
1.81 anton 16517: @c ------------------------------------------------------------------
1.113 anton 16518: @node Word Index, Concept Index, Licenses, Top
1.1 anton 16519: @unnumbered Word Index
16520:
1.26 crook 16521: This index is a list of Forth words that have ``glossary'' entries
16522: within this manual. Each word is listed with its stack effect and
16523: wordset.
1.1 anton 16524:
16525: @printindex fn
16526:
1.81 anton 16527: @c anton: the name index seems superfluous given the word and concept indices.
16528:
16529: @c @node Name Index, Concept Index, Word Index, Top
16530: @c @unnumbered Name Index
1.41 anton 16531:
1.81 anton 16532: @c This index is a list of Forth words that have ``glossary'' entries
16533: @c within this manual.
1.41 anton 16534:
1.81 anton 16535: @c @printindex ky
1.41 anton 16536:
1.113 anton 16537: @c -------------------------------------------------------
1.81 anton 16538: @node Concept Index, , Word Index, Top
1.1 anton 16539: @unnumbered Concept and Word Index
16540:
1.26 crook 16541: Not all entries listed in this index are present verbatim in the
16542: text. This index also duplicates, in abbreviated form, all of the words
16543: listed in the Word Index (only the names are listed for the words here).
1.1 anton 16544:
16545: @printindex cp
16546:
16547: @bye
1.81 anton 16548:
16549:
1.1 anton 16550:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>